@devries-cameron20 / t3code Mirror · read-only / commits / 30654b3e91
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 07:00 UTC

feat: tag threads and hide tagged threads while recording (#29053)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Nov 1, 2026 at 22:36 UTC 30654b3e91a51937d1dba18fc83af19d8003f5ca
47 files changed +876 -53
apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts
+6
@@ -9,6 +9,8 @@ import { useMemo } from "react";
9
10 import { appAtomRegistry } from "../../state/atom-registry";
11 import { orchestrationEnvironment } from "../../state/orchestration";
12 +import { serverEnvironment } from "../../state/server";
13 +import { environmentThreadShells } from "../../state/threads";
14
15 function archivedSnapshotAtom(environmentId: EnvironmentId) {
16 return orchestrationEnvironment.archivedShellSnapshot({
@@ -19,6 +21,10 @@ function archivedSnapshotAtom(environmentId: EnvironmentId) {
21
22 const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
23 getSnapshotAtom: archivedSnapshotAtom,
24 + hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
25 + hiddenThreadKeysAtom: environmentThreadShells.hiddenThreadKeysAtom,
26 + liveThreadRefsAtom: environmentThreadShells.threadRefsAtom,
27 + anyEnvironmentHidingAtom: environmentThreadShells.anyEnvironmentHidingAtom,
28 labelPrefix: "mobile:archived-thread-snapshots",
29 });
30
apps/mobile/src/features/keyboard/CommandPalette.tsx
+2 -2
@@ -46,7 +46,7 @@ import {
46 useProjects,
47 useServerConfigs,
48 useThreadShell,
49 - useThreadShells,
49 + useVisibleThreadShells,
50 } from "../../state/entities";
51 import { useThreadSearch } from "../../state/queries";
52 import { requestThreadMessageJump } from "../threads/threadMessageJump";
@@ -226,7 +226,7 @@ export function CommandPalette(props: {
226 const selectDetail = useSelectWorkspaceDetail();
227 const runCommand = props.onCommand;
228 const projects = useProjects();
229 - const threads = useThreadShells();
229 + const threads = useVisibleThreadShells();
230 const activeThreadRef = parseActiveThreadPath(props.pathname);
231 const activeThread = useThreadShell(activeThreadRef);
232 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
+15 -2
@@ -1,3 +1,5 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
3 import { AsyncResult } from "effect/reactivity";
4 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5 import * as Dialog from "../../components/ui/Dialog";
@@ -27,6 +29,7 @@ import { uuidv4 } from "../../lib/uuid";
29 import { useEnvironmentServerConfig } from "../../state/entities";
30 import { composerPullRequests } from "../../state/pull-requests";
31 import { useEnvironmentQuery } from "../../state/query";
32 +import { environmentThreadShells } from "../../state/threads";
33 import { useEnvironmentScope } from "../../state/session";
34 import {
35 createNewTaskDraft,
@@ -69,8 +72,18 @@ export function usePullRequestThreads(
72 const [lastRelations, setLastRelations] = useState({ key, data: relations.data });
73 if (relations.data && (lastRelations.key !== key || relations.data !== lastRelations.data))
74 setLastRelations({ key, data: relations.data });
72 - const threads =
73 - (relations.data ?? (lastRelations.key === key ? lastRelations.data : null))?.threads ?? [];
75 + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
76 + const hidingAnywhere = useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
77 + const loadedThreadRefs = useAtomValue(
78 + environmentThreadShells.environmentThreadRefsAtom(target.environmentId),
79 + );
80 + const threads = visibleLinkedThreads(
81 + (relations.data ?? (lastRelations.key === key ? lastRelations.data : null))?.threads ?? [],
82 + target.environmentId,
83 + loadedThreadRefs,
84 + hiddenKeys,
85 + hidingAnywhere,
86 + );
87 const connected = usePullRequestConnected(params.environmentId);
88 const canOperate = useEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope);
89 const canAsk = !connected || canOperate;
apps/mobile/src/features/threads/ThreadComposer.tsx
+2 -2
@@ -65,7 +65,7 @@ import {
65 } from "../../state/use-composer-drafts";
66 import { appAtomRegistry } from "../../state/atom-registry";
67 import type { ComposerDocumentAttachment } from "../../lib/composerContext";
68 -import { useProject, useThreadShells } from "../../state/entities";
68 +import { useProject, useVisibleThreadShells } from "../../state/entities";
69 import { useMentionableEnvironments } from "../../state/environments";
70 import { useLinkedEnvironments } from "../../state/peerLinks";
71 import { scopeProjectRef } from "@t3tools/client-runtime/environment";
@@ -539,7 +539,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
539 draftMessage: draftMessage,
540 ownerKey: composerDraftKey,
541 environmentId: props.environmentId,
542 - threadShells: useThreadShells(),
542 + threadShells: useVisibleThreadShells(),
543 environments: offersLinkedEnvironments(props.serverConfig)
544 ? mentionableEnvironments
545 : NO_MACHINES,
apps/mobile/src/state/composer-attachment-uploads.test.ts
+1
@@ -99,6 +99,7 @@ vi.mock("./entities", () => ({
99 useProjects: () => [],
100 useServerConfigs: () => new Map([["environment-1", config]]),
101 useThreadShells: () => [],
102 + useVisibleThreadShells: () => [],
103 }));
104 vi.mock("./projects", () => ({ environmentProjects: {} }));
105 vi.mock("./workspace", () => ({ workspaceConnections: {} }));
apps/mobile/src/state/entities.ts
+5
@@ -173,6 +173,11 @@ export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
173 return useAtomValue(environmentThreadShells.threadShellsAtom);
174 }
175
176 +/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
177 +export function useVisibleThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
178 + return useAtomValue(environmentThreadShells.visibleThreadShellsAtom);
179 +}
180 +
181 export function useNavigationThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
182 return useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
183 }
apps/mobile/src/state/threads.ts
+2
@@ -21,6 +21,7 @@ import {
21 pendingThreadCreationOutcomesAtom,
22 selectThreadCreationDetail,
23 } from "./pending-thread-creation";
24 +import { serverEnvironment } from "./server";
25 import { environmentShell } from "./shell";
26 import { threadOutboxManager } from "./thread-outbox";
27
@@ -43,6 +44,7 @@ export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
44 export const environmentThreadShells = createEnvironmentThreadShellAtoms({
45 catalogValueAtom: environmentCatalog.catalogValueAtom,
46 snapshotAtom: threadEnvironment.snapshotAtom,
47 + hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
48 });
49 export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
50 childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
apps/mobile/src/state/use-composer-drafts.test.ts
+1
@@ -313,6 +313,7 @@ function modelReconciliationHarness(
313 const shells = createEnvironmentThreadShellAtoms({
314 catalogValueAtom,
315 snapshotAtom: () => snapshotAtom,
316 + hiddenThreadTagsAtom: () => Atom.make(null),
317 });
318 const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
319 onTestFinished(registry.mount(selectedShell));
apps/mobile/src/state/use-pending-new-tasks.ts
+8 -4
@@ -1,6 +1,8 @@
1 import { useAtomValue } from "@effect/atom-react";
2 +import { threadKey } from "@t3tools/client-runtime/state/entities";
3 import { buildPendingNewTasks, type PendingNewTask } from "./pending-new-tasks-model";
4 import { flattenQueuedThreadMessages } from "./thread-outbox-model";
5 +import { environmentThreadShells } from "./threads";
6 import { newTaskComposerDraftsAtom } from "./use-composer-drafts";
7 import { useThreadOutboxMessages } from "./use-thread-outbox";
8
@@ -13,8 +15,10 @@ export type {
15 export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
16 const queuedMessagesByThreadKey = useThreadOutboxMessages();
17 const drafts = useAtomValue(newTaskComposerDraftsAtom);
16 - return buildPendingNewTasks({
17 - queuedMessages: flattenQueuedThreadMessages(queuedMessagesByThreadKey),
18 - drafts,
19 - });
18 + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
19 + // A delivered creation can stay queued after its thread is live and hidden.
20 + const queuedMessages = flattenQueuedThreadMessages(queuedMessagesByThreadKey).filter(
21 + (message) => !hiddenKeys.has(threadKey(message)),
22 + );
23 + return buildPendingNewTasks({ queuedMessages, drafts });
24 }
apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+5 -1
@@ -841,7 +841,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
841 const messageId = MessageId.make("message:foundation-compact");
842 const threadStateEvent = (
843 suffix: string,
844 - type: "thread.visited" | "thread.metadata-updated",
844 + type: "thread.visited" | "thread.metadata-updated" | "thread.tags-updated",
845 ): OrchestrationV2DomainEvent => ({
846 id: EventId.make(`event:foundation-compact:${suffix}`),
847 type,
@@ -936,10 +936,13 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
936 ...Array.from({ length: 501 }, (_, index) =>
937 threadStateEvent(`history-${index}`, "thread.visited"),
938 ),
939 + threadStateEvent("tags-1", "thread.tags-updated"),
940 threadStateEvent("visit-2", "thread.visited"),
941 messageEvent("message-2", "final"),
942 nodeEvent("node-2", "completed"),
943 itemEvent("item-2", "final"),
944 + // Older clients skip tag events, so these must not remove the rename above.
945 + threadStateEvent("tags-2", "thread.tags-updated"),
946 ],
947 });
948 const beforeCompaction = yield* projections.getThreadProjection(threadId);
@@ -1002,6 +1005,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
1005 "event:foundation-compact:message-2",
1006 "event:foundation-compact:node-2",
1007 "event:foundation-compact:item-2",
1008 + "event:foundation-compact:tags-2",
1009 ],
1010 );
1011
apps/server/src/orchestration-v2/Orchestrator.ts
+16
@@ -548,6 +548,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
548 case "thread.unpin":
549 case "thread.pin.reorder":
550 case "thread.active.reorder":
551 + case "thread.tag.set":
552 case "thread.visit":
553 case "thread.mark-unread":
554 case "thread.metadata.update":
@@ -3030,6 +3031,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3031 | "thread.pin"
3032 | "thread.unpin"
3033 | "thread.pin.reorder"
3034 + | "thread.tag.set"
3035 | "thread.active.reorder"
3036 | "thread.mark-unread"
3037 | "thread.metadata.update"
@@ -3565,6 +3567,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3567 updatedAt: thread.updatedAt,
3568 };
3569 }
3570 + case "thread.tag.set": {
3571 + const current = thread.tags ?? [];
3572 + return {
3573 + ...thread,
3574 + tags: command.tagged
3575 + ? current.includes(command.tag)
3576 + ? current
3577 + : [...current, command.tag]
3578 + : current.filter((tag) => tag !== command.tag),
3579 + };
3580 + }
3581 case "thread.mark-unread": {
3582 // Retire the wake before rewinding the visit, preserving its settlement timer.
3583 const snoozeExpired =
@@ -3936,6 +3949,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3949 return "thread.pin-reordered" as const;
3950 case "thread.active.reorder":
3951 return "thread.active-reordered" as const;
3952 + case "thread.tag.set":
3953 + return "thread.tags-updated" as const;
3954 case "thread.mark-unread":
3955 return "thread.marked-unread" as const;
3956 case "thread.metadata.update":
@@ -13067,6 +13082,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13082 case "thread.unpin":
13083 case "thread.pin.reorder":
13084 case "thread.active.reorder":
13085 + case "thread.tag.set":
13086 case "thread.mark-unread":
13087 case "thread.metadata.update":
13088 case "thread.pull-request.link":
apps/server/src/orchestration-v2/ProjectionMaintenance.ts
+10
@@ -219,6 +219,8 @@ export const layer: Layer.Layer<
219 ];
220 // Read-state events preserve updatedAt and supersede only each other. Activity events supersede both groups.
221 const READ_STATE_THREAD_EVENT_TYPES = ["thread.visited", "thread.marked-unread"];
222 + // Older clients skip tag events, so these supersede only each other.
223 + const TAG_THREAD_EVENT_TYPE = "thread.tags-updated";
224
225 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
226 const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
@@ -243,6 +245,7 @@ export const layer: Layer.Layer<
245 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
246 const retainedThreadIds = new Set<string>();
247 const retainedReadStateThreadIds = new Set<string>();
248 + const retainedTagThreadIds = new Set<string>();
249 // Retain each key's oldest candidate, deleting it only when an older event appears.
250 const oldestCandidateByEntityKey = new Map<string, number | null>();
251 let deletedEventCount = 0;
@@ -316,6 +319,13 @@ export const layer: Layer.Layer<
319 ) {
320 obsolete.push(row.sequence);
321 } else retainedReadStateThreadIds.add(row.stream_id);
322 + } else if (
323 + row.aggregate_kind === "thread" &&
324 + row.event_type === TAG_THREAD_EVENT_TYPE
325 + ) {
326 + if (retainedThreadIds.has(row.stream_id) || retainedTagThreadIds.has(row.stream_id)) {
327 + obsolete.push(row.sequence);
328 + } else retainedTagThreadIds.add(row.stream_id);
329 } else if (
330 row.event_type === "thread.pull-request-link-updated" &&
331 retainedThreadIds.has(row.stream_id)
apps/server/src/orchestration-v2/ProjectionStore.ts
+5
@@ -808,6 +808,7 @@ export function applyToProjection(
808 };
809 // Reordering and PR refreshes preserve the orchestrator's activity timestamp.
810 case "thread.active-reordered":
811 + case "thread.tags-updated":
812 case "thread.pull-request-synced":
813 return {
814 ...base,
@@ -1590,6 +1591,7 @@ export function threadShellFromProjection(
1591
1592 autoSettleDisabledAt: projection.thread.autoSettleDisabledAt ?? null,
1593 pinOrderKey: projection.thread.pinOrderKey ?? null,
1594 + ...(projection.thread.tags?.length ? { tags: projection.thread.tags } : {}),
1595 lastVisitedAt: projection.thread.lastVisitedAt,
1596 opens: projection.thread.opens ?? null,
1597 titleRegeneration: projection.thread.titleRegeneration ?? null,
@@ -1855,6 +1857,7 @@ function shellFromState(input: {
1857
1858 autoSettleDisabledAt: input.state.thread.autoSettleDisabledAt ?? null,
1859 pinOrderKey: input.state.thread.pinOrderKey ?? null,
1860 + ...(input.state.thread.tags?.length ? { tags: input.state.thread.tags } : {}),
1861 lastVisitedAt: input.state.thread.lastVisitedAt,
1862 opens: input.state.thread.opens ?? null,
1863 titleRegeneration: input.state.thread.titleRegeneration ?? null,
@@ -1913,6 +1916,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
1916 case "thread.unpinned":
1917 case "thread.pin-reordered":
1918 case "thread.active-reordered":
1919 + case "thread.tags-updated":
1920 case "thread.visited":
1921 case "thread.marked-unread":
1922 case "thread.metadata-updated":
@@ -2725,6 +2729,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2729 event.type !== "thread.unpinned" &&
2730 event.type !== "thread.pin-reordered" &&
2731 event.type !== "thread.active-reordered" &&
2732 + event.type !== "thread.tags-updated" &&
2733 event.type !== "thread.visited" &&
2734 event.type !== "thread.marked-unread" &&
2735 event.type !== "thread.metadata-updated" &&
apps/server/src/orchestration-v2/ThreadForkService.test.ts
+2
@@ -151,6 +151,7 @@ it.effect("resets a fork's pin, snooze, settle and delegation state but keeps it
151 },
152 historyOrigin: "v1_import",
153 linkOrigin,
154 + tags: ["private"],
155 };
156 const sourceRun = makeSourceRun("completed");
157 const result = yield* planFork(sourceRun, {
@@ -168,6 +169,7 @@ it.effect("resets a fork's pin, snooze, settle and delegation state but keeps it
169 assert.isUndefined(result.targetThread.delegatedFrom);
170 assert.equal(result.targetThread.historyOrigin, "v1_import");
171 assert.deepEqual(result.targetThread.linkOrigin, linkOrigin);
172 + assert.deepEqual(result.targetThread.tags, ["private"]);
173 assert.equal(result.targetThread.projectId, sourceThread.projectId);
174 assert.equal(result.targetThread.providerInstanceId, sourceThread.providerInstanceId);
175 assert.deepEqual(result.targetThread.modelSelection, sourceThread.modelSelection);
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+32
@@ -18,6 +18,7 @@ import {
18 TurnItemId,
19 type ModelSelection,
20 type OrchestrationV2Run,
21 + type OrchestrationV2ShellSnapshot,
22 type OrchestrationV2RuntimeRequest,
23 ProjectId,
24 type PullRequestDetail,
@@ -2546,6 +2547,37 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
2547 });
2548 assert.equal((yield* orchestrator.getThreadProjection(threadId)).thread.activeOrderKey, "a0");
2549
2550 + const shellOf = (shell: Pick<OrchestrationV2ShellSnapshot, "threads">) =>
2551 + shell.threads.find((thread) => thread.id === threadId)!;
2552 + const untaggedShell = shellOf(yield* orchestrator.getShellSnapshot());
2553 + yield* TestClock.adjust("1 minute");
2554 + for (const [step, tag, tagged, expected] of [
2555 + ["add", "demo", true, ["demo"]],
2556 + ["retry", "demo", true, ["demo"]],
2557 + ["add-other", "private", true, ["demo", "private"]],
2558 + ["remove", "demo", false, ["private"]],
2559 + ["remove-last", "private", false, []],
2560 + ] as const) {
2561 + yield* orchestrator.dispatch({
2562 + type: "thread.tag.set",
2563 + commandId: CommandId.make(`runtime-layer-lifecycle-tag-${step}`),
2564 + threadId,
2565 + tag,
2566 + tagged,
2567 + });
2568 + assert.deepEqual(
2569 + shellOf(yield* orchestrator.getShellSnapshot()).tags ?? [],
2570 + expected,
2571 + step,
2572 + );
2573 + }
2574 + const taggedShell = shellOf(yield* orchestrator.getShellSnapshot());
2575 + // Tags are not activity, so the thread keeps its place in thread lists.
2576 + assert.equal(
2577 + DateTime.toEpochMillis(taggedShell.updatedAt),
2578 + DateTime.toEpochMillis(untaggedShell.updatedAt),
2579 + );
2580 +
2581 const preAutoProjection = yield* orchestrator.getThreadProjection(threadId);
2582 const staleAutoSettle = yield* orchestrator
2583 .dispatch({
apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+1
@@ -147,6 +147,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
147 case "thread.unpin":
148 case "thread.pin.reorder":
149 case "thread.active.reorder":
150 + case "thread.tag.set":
151 case "thread.visit":
152 case "thread.mark-unread":
153 case "thread.metadata.update":
apps/server/src/relay/AgentAwarenessRelay.ts
+1
@@ -113,6 +113,7 @@ function shouldPublishAgentAwarenessEvent(
113 case "thread.unpinned":
114 case "thread.pin-reordered":
115 case "thread.active-reordered":
116 + case "thread.tags-updated":
117 case "thread.visited":
118 case "thread.marked-unread":
119 case "thread.runtime-mode-updated":
apps/web/src/components/CommandPalette.composition.browser.test.tsx
+5
@@ -21,6 +21,7 @@ vi.mock("../hooks/useEnvironmentTheme", () => ({ useEnvironmentThemeDefinitions:
21 vi.mock("../hooks/useSettings", async (original) => ({
22 ...(await original<typeof import("../hooks/useSettings")>()),
23 useClientSettings: () => DEFAULT_CLIENT_SETTINGS,
24 + useUpdateEnvironmentSettings: () => () => undefined,
25 }));
26 vi.mock("../hooks/useScratchProject", () => ({
27 useScratchProject: () => ({ scratchEnvironmentId: () => null }),
@@ -66,6 +67,10 @@ vi.mock("../state/entities", async (original) => ({
67 ...(await original<typeof import("../state/entities")>()),
68 useProjects: () => [],
69 useThreadShells: () => [],
70 + useVisibleThreadShells: () => [],
71 + useHiddenThreadKeys: () => new Set(),
72 + useAnyEnvironmentHiding: () => false,
73 + useEnvironmentThreadRefs: () => [],
74 useServerConfigs: () => new Map(),
75 waitForProject: async () => undefined,
76 }));
apps/web/src/components/CommandPalette.tsx
+23 -2
@@ -128,7 +128,16 @@ import {
128 useEnvironments,
129 usePrimaryEnvironmentId,
130 } from "../state/environments";
131 -import { useProjects, useServerConfigs, useThreadShells, waitForProject } from "../state/entities";
131 +import {
132 + useAnyEnvironmentHiding,
133 + useHiddenThreadKeys,
134 + useEnvironmentThreadRefs,
135 + useProjects,
136 + useServerConfigs,
137 + useVisibleThreadShells,
138 + waitForProject,
139 +} from "../state/entities";
140 +import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
141 import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
142 import {
143 appendBrowsePathSegment,
@@ -398,6 +407,11 @@ function OpenCommandPaletteDialog(props: {
407 },
408 );
409 const linkedThreadSearch = initialSearch.linkedThreadSearch;
410 + // Rows were captured when the palette opened; drop any hidden since then.
411 + const hiddenKeys = useHiddenThreadKeys();
412 + const linkedEnvironmentId = linkedThreadSearch?.linkedThreads?.environmentId ?? null;
413 + const hidingAnywhere = useAnyEnvironmentHiding();
414 + const linkedThreadRefs = useEnvironmentThreadRefs(linkedEnvironmentId);
415 const [searchState, dispatchSearch] = useReducer(reduceCommandPaletteSearchState, null, () => {
416 const view = props.initialContext ? null : openIntentView(props.openIntent);
417 return view
@@ -479,7 +493,7 @@ function OpenCommandPaletteDialog(props: {
493 if (activeThreadReferenceCopyTarget === null) return;
494 await copyThreadReference(activeThreadReferenceCopyTarget);
495 };
482 - const threads = useThreadShells();
496 + const threads = useVisibleThreadShells();
497 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
498 const providersByEnvironment = useEnvironmentProviders();
499 const { changeThemeItem, changeAppearanceItem, themeEditorItem } = useCommandPaletteThemeItems();
@@ -1717,6 +1731,13 @@ function OpenCommandPaletteDialog(props: {
1731 isLinkedThreadSearch && linkedThreadSearch?.linkedThreads
1732 ? buildLinkedThreadActionItems({
1733 ...linkedThreadSearch.linkedThreads,
1734 + threads: visibleLinkedThreads(
1735 + linkedThreadSearch.linkedThreads.threads,
1736 + linkedThreadSearch.linkedThreads.environmentId,
1737 + linkedThreadRefs,
1738 + hiddenKeys,
1739 + hidingAnywhere,
1740 + ),
1741 query: linkedThreadSearch.query,
1742 icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
1743 runThread: async (thread) => {
apps/web/src/components/CommandPaletteLookups.ts
+2 -2
@@ -7,7 +7,7 @@ import {
7 import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
8 import { useClientSettings } from "../hooks/useSettings";
9 import { getProjectOrderKey } from "@t3tools/client-runtime/state/project-grouping";
10 -import { useProjects, useThreadShells } from "../state/entities";
10 +import { useProjects, useVisibleThreadShells } from "../state/entities";
11 import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
12 import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
13 import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
@@ -55,7 +55,7 @@ export const selectCommandPaletteClientSettings = (settings: ClientSettings) =>
55
56 export function useSortedProjectGroups(environmentLabelById: ReadonlyMap<EnvironmentId, string>) {
57 const projects = useProjects();
58 - const threads = useThreadShells();
58 + const threads = useVisibleThreadShells();
59 const projectOrder = useUiStateStore((store) => store.projectOrder);
60 const clientSettings = useClientSettings(selectCommandPaletteClientSettings);
61 const primaryEnvironmentId = usePrimaryEnvironmentId();
apps/web/src/components/CommandPaletteThreadItems.tsx
+2 -2
@@ -23,7 +23,7 @@ import {
23 deriveProviderInstanceEntries,
24 type ProviderInstanceEntry,
25 } from "../providerInstances";
26 -import { useThreadShells } from "../state/entities";
26 +import { useVisibleThreadShells } from "../state/entities";
27 import {
28 useEnvironmentProviders,
29 useEnvironments,
@@ -99,7 +99,7 @@ export function useCommandPaletteThreadItems(input: {
99 }) {
100 const { activeThread, threadSearchQuery } = input;
101 const navigate = useNavigate();
102 - const threads = useThreadShells();
102 + const threads = useVisibleThreadShells();
103 const { projectEnvironmentLocationById } = useEnvironmentLookups();
104 const providerEntryByEnvironmentAndInstanceId = useProviderEntryByEnvironmentAndInstanceId();
105 const messageSearch = useConnectedThreadSearch(threadSearchQuery);
apps/web/src/components/ThreadNotificationCoordinator.tsx
+58 -5
@@ -5,6 +5,7 @@ import {
5 } from "@t3tools/client-runtime/state/models";
6 import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
7 import type { AnyRouter } from "@tanstack/react-router";
8 +import { threadKey } from "@t3tools/client-runtime/state/entities";
9 import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
10 import type { ClientSettings } from "@t3tools/contracts/settings";
11 import * as Option from "effect/Option";
@@ -44,6 +45,8 @@ interface NotificationState extends ThreadNotificationObservation {
45 readonly status: SidebarThreadStatus;
46 }
47
48 +type ToastId = ReturnType<typeof toastManager.add>;
49 +
50 interface WatchedEnvironment {
51 unsubscribe: () => void;
52 previous: Map<ThreadId, NotificationState>;
@@ -59,14 +62,49 @@ export function startThreadNotifications(
62 registry: AtomRegistry.AtomRegistry,
63 router: AnyRouter,
64 ): () => void {
62 - const pending = new Map<string, { environmentId: EnvironmentId; notification: Notification }>();
65 + const pending = new Map<
66 + string,
67 + { environmentId: EnvironmentId; threadId: ThreadId; notification: Notification }
68 + >();
69 const watched = new Map<EnvironmentId, WatchedEnvironment>();
70
65 - const trackNotification = (environmentId: EnvironmentId, notification: Notification) => {
71 + const trackNotification = (
72 + environmentId: EnvironmentId,
73 + threadId: ThreadId,
74 + notification: Notification,
75 + ) => {
76 pending.get(notification.tag)?.notification.close();
67 - pending.set(notification.tag, { environmentId, notification });
77 + pending.set(notification.tag, { environmentId, threadId, notification });
78 setNotificationBadge(pending.size);
79 };
80 + // Toast ids by thread key, so hiding a thread can close its open toasts.
81 + const openToasts = new Map<string, Array<ToastId>>();
82 + const forgetToast = (key: string, toastId: ToastId) => {
83 + const remaining = (openToasts.get(key) ?? []).filter((id) => id !== toastId);
84 + if (remaining.length === 0) openToasts.delete(key);
85 + else openToasts.set(key, remaining);
86 + };
87 + // A notification shown before the tag filter turned on must not stay on screen. While hiding,
88 + // one whose thread left the live list (archived) cannot be judged, so it closes too.
89 + const closeHiddenPending = () => {
90 + const hidden = registry.get(environmentThreadShells.hiddenThreadKeysAtom);
91 + const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom)
92 + ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey))
93 + : null;
94 + const shouldClose = (key: string) => hidden.has(key) || (live !== null && !live.has(key));
95 + for (const [key, toastIds] of openToasts) {
96 + if (!shouldClose(key)) continue;
97 + for (const toastId of toastIds) toastManager.close(toastId);
98 + openToasts.delete(key);
99 + }
100 + const count = pending.size;
101 + for (const [tag, entry] of pending) {
102 + if (!shouldClose(threadKey(entry))) continue;
103 + entry.notification.close();
104 + pending.delete(tag);
105 + }
106 + if (count !== pending.size) setNotificationBadge(pending.size);
107 + };
108 const clearPending = () => {
109 for (const { notification } of pending.values()) notification.close();
110 pending.clear();
@@ -80,6 +118,12 @@ export function startThreadNotifications(
118 kind: ThreadNotificationKind,
119 ) => {
120 const { thread, status } = state;
121 + if (
122 + registry
123 + .get(environmentThreadShells.hiddenThreadKeysAtom)
124 + .has(threadKey({ environmentId, threadId: thread.id }))
125 + )
126 + return;
127 const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings();
128 const active = (router.state.matches.at(-1)?.params ?? {}) as {
129 environmentId?: string;
@@ -108,7 +152,9 @@ export function startThreadNotifications(
152 document.hasFocus() &&
153 (active.environmentId !== environmentId || active.threadId !== thread.id)
154 ) {
111 - const toastId = toastManager.add({
155 + const toastKey = threadKey({ environmentId, threadId: thread.id });
156 + const toastId: ToastId = toastManager.add({
157 + onRemove: (): void => forgetToast(toastKey, toastId),
158 type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
159 title,
160 description: thread.title,
@@ -138,6 +184,7 @@ export function startThreadNotifications(
184 },
185 },
186 });
187 + openToasts.set(toastKey, [...(openToasts.get(toastKey) ?? []), toastId]);
188 return;
189 }
190 if (
@@ -155,7 +202,7 @@ export function startThreadNotifications(
202 // Windows drops clicks after a toast moves into Notification Center.
203 requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform),
204 });
158 - trackNotification(environmentId, notification);
205 + trackNotification(environmentId, thread.id, notification);
206 notification.addEventListener("click", () => {
207 notification.close();
208 window.focus();
@@ -356,11 +403,17 @@ export function startThreadNotifications(
403 syncEnvironments();
404 },
405 );
406 + const unsubscribeHidden = [
407 + registry.subscribe(environmentThreadShells.hiddenThreadKeysAtom, closeHiddenPending),
408 + registry.subscribe(environmentThreadShells.anyEnvironmentHidingAtom, closeHiddenPending),
409 + registry.subscribe(environmentThreadShells.threadRefsAtom, closeHiddenPending),
410 + ];
411 onSettings();
412
413 return () => {
414 unsubscribeSettings();
415 unsubscribeEnvironmentIds();
416 + for (const unsubscribe of unsubscribeHidden) unsubscribe();
417 for (const entry of watched.values()) entry.unsubscribe();
418 watched.clear();
419 stopModeListeners();
apps/web/src/components/ThreadRouteView.tsx
+58 -3
@@ -1,4 +1,8 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3 +import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
4 +import { visibilityParentKey } from "@t3tools/client-runtime/state/threads";
5 +import * as Option from "effect/Option";
6 import { Navigate, useNavigate } from "@tanstack/react-router";
7 import { useEffect, useState } from "react";
8
@@ -7,9 +11,13 @@ import { BackgroundThreadContext } from "./chat/backgroundThread";
11 import { SidebarInset } from "./ui/sidebar";
12 import { useComposerDraftStore } from "../composerDraftStore";
13 import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
10 -import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities";
14 +import {
15 + useEnvironmentThreadRefs,
16 + useAnyEnvironmentHiding,
17 + useQuietThreadShell,
18 +} from "../state/entities";
19 import { useEnvironmentShellStatus } from "../state/shell";
12 -import { useEnvironmentThread } from "../state/threads";
20 +import { environmentThreadShells, useEnvironmentThread } from "../state/threads";
21 import {
22 buildThreadRouteParams,
23 isThreadRouteSnapshotAuthoritative,
@@ -80,6 +88,28 @@ export function ThreadRouteView({
88 unlistedThreadRef?.environmentId ?? null,
89 unlistedThreadRef?.threadId ?? null,
90 );
91 + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
92 + const unlistedThread = Option.getOrNull(Option.map(unlistedThreadDetail.data, (p) => p.thread));
93 + const unlistedParentKey =
94 + unlistedThreadRef === null || unlistedThread === null
95 + ? null
96 + : visibilityParentKey(unlistedThreadRef.environmentId, unlistedThread);
97 + const unlistedParentShell = useQuietThreadShell(
98 + unlistedParentKey === null ? null : parseThreadKey(unlistedParentKey),
99 + );
100 + const hidingAnywhere = useAnyEnvironmentHiding();
101 + const draftRedirectShell = useQuietThreadShell(draftRedirect ?? null);
102 + const hiddenByTagFilter = serverThreadRef !== null && hiddenKeys.has(threadKey(serverThreadRef));
103 + // Cached detail can predate a tag or an archive, so while hiding an off-shell thread opens only
104 + // as the child of a loaded, visible parent (lineage never changes); anything else stays closed.
105 + const offShellBlocked =
106 + hidingAnywhere &&
107 + unlistedThreadRef !== null &&
108 + !(
109 + unlistedParentKey !== null &&
110 + unlistedParentShell !== null &&
111 + !hiddenKeys.has(unlistedParentKey)
112 + );
113 const renderState = resolveThreadRouteRenderState({
114 bootstrapComplete,
115 serverThreadExists: serverThreadShell !== null,
@@ -106,7 +136,15 @@ export function ThreadRouteView({
136 let view: React.ReactNode = null;
137 let redirect: React.ReactNode = null;
138 if (target.kind === "draft") {
109 - if (draftSession) {
139 + if (
140 + draftSession &&
141 + hiddenKeys.has(
142 + threadKey({ environmentId: draftSession.environmentId, threadId: draftSession.threadId }),
143 + )
144 + ) {
145 + // A draft whose thread is already live and hidden (mid-promotion): never mount it.
146 + redirect = <Navigate to="/" replace />;
147 + } else if (draftSession) {
148 view = (
149 <ChatView
150 key={target.draftId}
@@ -117,6 +155,18 @@ export function ThreadRouteView({
155 forceExpandedMobileComposer
156 />
157 );
158 + } else if (draftRedirect && hiddenKeys.has(threadKey(draftRedirect))) {
159 + // Back to a promoted draft whose thread is now hidden: never mount it.
160 + redirect = <Navigate to="/" replace />;
161 + } else if (draftRedirect && hidingAnywhere && draftRedirectShell === null) {
162 + // While hiding, a thread outside the live list is judged by the server route, unmounted here.
163 + redirect = (
164 + <Navigate
165 + to="/$environmentId/$threadId"
166 + params={buildThreadRouteParams(draftRedirect)}
167 + replace
168 + />
169 + );
170 } else if (draftRedirect) {
171 // Same slot and key as the server route renders, so the swap keeps this instance.
172 view = (
@@ -137,6 +187,11 @@ export function ThreadRouteView({
187 } else {
188 redirect = <Navigate to="/" replace />;
189 }
190 + } else if (hiddenByTagFilter) {
191 + redirect = <Navigate to="/" replace />;
192 + } else if (offShellBlocked) {
193 + // Before the shell bootstraps, a listed visible thread can still look off-shell.
194 + if (bootstrapComplete && unlistedThread !== null) redirect = <Navigate to="/" replace />;
195 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
196 view = (
197 <ChatView
apps/web/src/components/chat/DraftHeroHeadline.tsx
+2 -2
@@ -27,7 +27,7 @@ import {
27 buildSidebarProjectSnapshots,
28 projectGroupsSpanEnvironments,
29 } from "~/sidebarProjectGrouping";
30 -import { useProjects, useThreadShells } from "~/state/entities";
30 +import { useProjects, useVisibleThreadShells } from "~/state/entities";
31 import {
32 useEnvironments,
33 usePrimaryEnvironmentId,
@@ -75,7 +75,7 @@ export function DraftHeroHeadline({
75 activeProjectTitle,
76 }: DraftHeroHeadlineProps) {
77 const projects = useProjects();
78 - const threads = useThreadShells();
78 + const threads = useVisibleThreadShells();
79 const { environments } = useEnvironments();
80 const providersByEnvironment = useEnvironmentProviders();
81 const primaryEnvironmentId = usePrimaryEnvironmentId();
apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
+2
@@ -25,6 +25,8 @@ vi.mock(import("../../state/entities"), () => ({
25 ? []
26 : [(state.projection as { thread: unknown }).thread, ...state.relatedShells]) as never,
27 useProjects: (() => []) as never,
28 + useHiddenThreadKeys: (() => new Set()) as never,
29 + useAnyEnvironmentHiding: (() => false) as never,
30 }));
31 vi.mock(import("../../state/environments"), () => ({
32 useEnvironment: (() => null) as never,
apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+29 -11
@@ -1,4 +1,5 @@
1 import { useAtomValue } from "@effect/atom-react";
2 +import { threadKey } from "@t3tools/client-runtime/state/entities";
3 import { ThreadDetailsControl } from "./ThreadDetailsControl";
4 import { ThreadHoverCardPopup } from "../ThreadHoverCard";
5 import { ThreadDetailsSection } from "./ThreadDetailsSection";
@@ -64,6 +65,8 @@ import {
65 useQuietThreadShell,
66 useThreadProjection,
67 useThreadRelationshipShells,
68 + useHiddenThreadKeys,
69 + useAnyEnvironmentHiding,
70 } from "../../state/entities";
71 import { useEnvironment, useEnvironmentProviders } from "../../state/environments";
72 import { serverEnvironment } from "../../state/server";
@@ -386,6 +389,8 @@ export function ThreadRelationshipsPanel(props: {
389 const providersByEnvironment = useEnvironmentProviders();
390 const settings = useAtomValue(serverEnvironment.settingsValueAtom(props.environmentId));
391 const relationshipShells = useThreadRelationshipShells(ref);
392 + const hiddenKeys = useHiddenThreadKeys();
393 + const hidingAnywhere = useAnyEnvironmentHiding();
394 const allProjects = useProjects();
395 const archived = useArchivedThreadSnapshots([props.environmentId]);
396 const archivedShells = archived.snapshots.find(
@@ -464,6 +469,14 @@ export function ThreadRelationshipsPanel(props: {
469 ...(archivedShells ?? []),
470 ];
471 const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
472 + const isHiddenRelation = (threadId: ThreadId) =>
473 + hiddenKeys.has(threadKey({ environmentId: props.environmentId, threadId }));
474 + // While hiding, an unloaded parent, fork or transfer may be hidden; unloaded subagent
475 + // children (idle, left out of the shell) follow this visible thread, so they stay.
476 + const isHiddenUnloadedRelation = (row: { threadId: ThreadId; edge: ThreadRelationshipEdge }) =>
477 + hidingAnywhere &&
478 + graph.nodes.get(row.threadId)?.missing === true &&
479 + (row.edge.kind !== "subagent" || isParentThreadRelationship(row.edge, props.threadId));
480 const currentProject = projects.find((project) => project.id === currentThread?.projectId);
481 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
482 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
@@ -472,16 +485,19 @@ export function ThreadRelationshipsPanel(props: {
485 rows: immediateThreadRelationships(graph, props.threadId),
486 currentThreadId: props.threadId,
487 mergeTargetThreadId,
475 - }).map((row) => {
476 - const agent =
477 - row.edge.kind === "subagent" && !isParentThreadRelationship(row.edge, props.threadId)
478 - ? subagentsByThreadId.get(row.threadId)
479 - : undefined;
480 - const workflowGroup = agent === undefined ? undefined : workflowGroupsById.get(agent.id);
481 - return workflowGroup === undefined
482 - ? row
483 - : { ...row, edge: { ...row.edge, status: workflowGroup.workflow.status } };
484 - });
488 + })
489 + // The graph rebuilds missing parents from lineage, so filter the rows it returns.
490 + .filter((row) => !isHiddenRelation(row.threadId) && !isHiddenUnloadedRelation(row))
491 + .map((row) => {
492 + const agent =
493 + row.edge.kind === "subagent" && !isParentThreadRelationship(row.edge, props.threadId)
494 + ? subagentsByThreadId.get(row.threadId)
495 + : undefined;
496 + const workflowGroup = agent === undefined ? undefined : workflowGroupsById.get(agent.id);
497 + return workflowGroup === undefined
498 + ? row
499 + : { ...row, edge: { ...row.edge, status: workflowGroup.workflow.status } };
500 + });
501 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
502 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
503
@@ -623,7 +639,9 @@ export function ThreadRelationshipsPanel(props: {
639 const parentTitle =
640 mergeTargetThreadId === null
641 ? null
626 - : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
642 + : isHiddenRelation(mergeTargetThreadId)
643 + ? null
644 + : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
645
646 const renderRelationshipRow = ({ threadId, edge }: ThreadRelationshipWalkRow) => {
647 const node = graph.nodes.get(threadId);
apps/web/src/components/chat/useComposerMenuItems.ts
+2 -2
@@ -28,7 +28,7 @@ import {
28 getProviderSlashCommandsForSlashMenu,
29 } from "@t3tools/client-runtime/providerSkills";
30 import { searchProviderSkills } from "../../providerSkillSearch";
31 -import { useThreadShells } from "~/state/entities";
31 +import { useVisibleThreadShells } from "~/state/entities";
32 import { useEnvironmentIdentities, useEnvironmentMachines } from "~/state/environments";
33 import { offersLinkedEnvironmentsAtom } from "~/state/peerLinks";
34 import {
@@ -109,7 +109,7 @@ export function useComposerMenuItems({
109 const settledPullRequestTextQuery =
110 pullRequestTextQuery === debouncedPullRequestTextQuery ? pullRequestTextQuery : null;
111 const isPathTrigger = composerTriggerKind === "path";
112 - const environmentThreadShells = useThreadShells(isPathTrigger);
112 + const environmentThreadShells = useVisibleThreadShells(isPathTrigger);
113 // Mounts older settled threads matching the mention, which shells may leave out.
114 useThreadSearch(isPathTrigger ? [environmentId] : [], pathTriggerQuery, { titlesOnly: true });
115 // The user's machines feed `@` machine matches; the catalog summary is cheap and stable.
apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx
+22 -4
@@ -1,5 +1,7 @@
1 import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
2 +import { useAtomValue } from "@effect/atom-react";
3 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
4 +import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
5 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6 import type { EnvironmentId, PullRequestRef, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
7 import { CheckIcon, MessageSquareIcon } from "lucide-react";
@@ -9,8 +11,16 @@ import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
11
12 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
13 import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
12 -import { useProjects, useServerConfigs, useThreadShell, useThreadShells } from "~/state/entities";
14 +import {
15 + useAnyEnvironmentHiding,
16 + useEnvironmentThreadRefs,
17 + useProjects,
18 + useServerConfigs,
19 + useThreadShell,
20 + useVisibleThreadShells,
21 +} from "~/state/entities";
22 import { pullRequestEnvironment } from "~/state/pullRequests";
23 +import { environmentThreadShells } from "~/state/threads";
24 import { useEnvironmentQuery } from "~/state/query";
25 import { useThreadSearch } from "~/state/queries";
26 import { appAtomRegistry } from "~/rpc/atomRegistry";
@@ -58,6 +68,9 @@ function EnabledPullRequestThreadLinks({
68 const currentThreadRef = thread === null ? null : threadRef;
69 const linking = usePullRequestLinking(environmentId);
70 const linkedHere = linking.isLinked(thread, url);
71 + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
72 + const hidingAnywhere = useAnyEnvironmentHiding();
73 + const loadedThreadRefs = useEnvironmentThreadRefs(environmentId);
74 const relations = useEnvironmentQuery(
75 linking.mode === "multiple" && display !== "menu-item"
76 ? pullRequestEnvironment.linkedThreads({
@@ -104,8 +117,13 @@ function EnabledPullRequestThreadLinks({
117 };
118
119 if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
107 - const linkedThreads =
108 - linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [];
120 + const linkedThreads = visibleLinkedThreads(
121 + linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [],
122 + environmentId,
123 + loadedThreadRefs,
124 + hiddenKeys,
125 + hidingAnywhere,
126 + );
127 const linkedThreadsLabel =
128 linkedThreads.length > 0
129 ? `Linked from ${linkedThreads.length} ${linkedThreads.length === 1 ? "thread" : "threads"}`
@@ -188,7 +206,7 @@ function ThreadPicker({
206 pending: boolean;
207 onSelect: (threadId: ThreadId) => void;
208 }) {
191 - const threads = useThreadShells();
209 + const threads = useVisibleThreadShells();
210 const linking = usePullRequestLinking(environmentId);
211 const projects = useProjects();
212 const [query, setQuery] = useState("");
apps/web/src/composerDraftStore.test.ts
+1
@@ -1335,6 +1335,7 @@ function modelReconciliationHarness(
1335 const shells = createEnvironmentThreadShellAtoms({
1336 catalogValueAtom,
1337 snapshotAtom: () => snapshotAtom,
1338 + hiddenThreadTagsAtom: () => Atom.make(null),
1339 });
1340 const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
1341 onTestFinished(registry.mount(selectedShell));
apps/web/src/lib/archivedThreadsState.ts
+6
@@ -7,6 +7,8 @@ import {
7 import type { EnvironmentId } from "@t3tools/contracts";
8
9 import { orchestrationEnvironment } from "../state/orchestration";
10 +import { serverEnvironment } from "../state/server";
11 +import { environmentThreadShells } from "../state/threads";
12 import { appAtomRegistry } from "../rpc/atomRegistry";
13
14 function archivedSnapshotAtom(environmentId: EnvironmentId) {
@@ -18,6 +20,10 @@ function archivedSnapshotAtom(environmentId: EnvironmentId) {
20
21 const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
22 getSnapshotAtom: archivedSnapshotAtom,
23 + hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
24 + hiddenThreadKeysAtom: environmentThreadShells.hiddenThreadKeysAtom,
25 + liveThreadRefsAtom: environmentThreadShells.threadRefsAtom,
26 + anyEnvironmentHidingAtom: environmentThreadShells.anyEnvironmentHidingAtom,
27 labelPrefix: "web:archived-thread-snapshots",
28 });
29
apps/web/src/routes/_chat.index.tsx
+2 -2
@@ -17,7 +17,7 @@ import {
17 readProject,
18 useAllEnvironmentShellsBootstrapped,
19 useProjects,
20 - useThreadShells,
20 + useVisibleThreadShells,
21 } from "../state/entities";
22 import { useEnvironments } from "../state/environments";
23
@@ -35,7 +35,7 @@ function ChatIndexRouteView() {
35
36 function IndexDraftLanding() {
37 const projects = useProjects();
38 - const threads = useThreadShells();
38 + const threads = useVisibleThreadShells();
39 const bootstrapped = useAllEnvironmentShellsBootstrapped();
40 const handleNewThread = useNewThreadHandler();
41 const router = useRouter();
apps/web/src/state/entities.ts
+17
@@ -107,6 +107,23 @@ export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThread
107 );
108 }
109
110 +/** Whether any connected environment is hiding tagged threads right now. */
111 +export function useAnyEnvironmentHiding(): boolean {
112 + return useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
113 +}
114 +
115 +/** Keys of threads the tag filter hides from display, by `threadKey`. */
116 +export function useHiddenThreadKeys(): ReadonlySet<string> {
117 + return useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
118 +}
119 +
120 +/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
121 +export function useVisibleThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
122 + return useAtomValue(
123 + enabled ? environmentThreadShells.visibleThreadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
124 + );
125 +}
126 +
127 export function useAllEnvironmentShellsBootstrapped(): boolean {
128 return useAtomValue(allEnvironmentShellsBootstrappedAtom);
129 }
apps/web/src/state/threads.ts
+2
@@ -18,6 +18,7 @@ import { AsyncResult, Atom } from "effect/reactivity";
18
19 import { environmentCatalog } from "../connection/catalog";
20 import { connectionAtomRuntime } from "../connection/runtime";
21 +import { serverEnvironment } from "./server";
22 import { environmentShell } from "./shell";
23
24 export const threadFamilies = createThreadFamilyAtoms(
@@ -39,6 +40,7 @@ export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
40 export const environmentThreadShells = createEnvironmentThreadShellAtoms({
41 catalogValueAtom: environmentCatalog.catalogValueAtom,
42 snapshotAtom: threadEnvironment.snapshotAtom,
43 + hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
44 });
45 export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
46 childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
packages/client-runtime/src/state/archivedThreads.test.ts
+79 -2
@@ -1,12 +1,18 @@
1 -import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
1 +import {
2 + EnvironmentId,
3 + type OrchestrationV2ArchivedShellSnapshot,
4 + type ScopedThreadRef,
5 + ThreadId,
6 +} from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
8 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
4 -import { expect, it } from "vite-plus/test";
9 +import { describe, expect, it } from "vite-plus/test";
10
11 import {
12 createArchivedThreadSnapshotsAtomFamily,
13 makeArchivedThreadsEnvironmentKey,
14 } from "./archivedThreads.ts";
15 +import { v2Project, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
16
17 it("does not expose an archived snapshot failure message", () => {
18 const environmentId = EnvironmentId.make("env-sensitive");
@@ -17,6 +23,10 @@ it("does not expose an archived snapshot failure message", () => {
23 Cause.fail(new Error("credential=secret-value")),
24 ),
25 ),
26 + hiddenThreadTagsAtom: () => Atom.make(null),
27 + hiddenThreadKeysAtom: Atom.make((): ReadonlySet<string> => new Set()),
28 + liveThreadRefsAtom: Atom.make((): ReadonlyArray<ScopedThreadRef> => []),
29 + anyEnvironmentHidingAtom: Atom.make(false),
30 labelPrefix: "test:archived-thread-snapshots",
31 });
32 const registry = AtomRegistry.make();
@@ -29,3 +39,70 @@ it("does not expose an archived snapshot failure message", () => {
39
40 registry.dispose();
41 });
42 +
43 +describe("archived delegated tasks follow their parent on another machine", () => {
44 + const parentEnvironmentId = EnvironmentId.make("env-parent");
45 + const taskEnvironmentId = EnvironmentId.make("env-task");
46 + const parentId = ThreadId.make("thread-parent");
47 + const page = (
48 + threads: OrchestrationV2ArchivedShellSnapshot["threads"],
49 + ): OrchestrationV2ArchivedShellSnapshot => ({
50 + schemaVersion: 1,
51 + snapshotSequence: 1,
52 + projects: [v2Project],
53 + threads,
54 + });
55 + const taskPage = page([
56 + {
57 + ...v2ThreadShell,
58 + id: ThreadId.make("thread-task"),
59 + delegatedFrom: { environmentId: parentEnvironmentId, threadId: parentId, title: "p" },
60 + },
61 + ]);
62 + const archivedTaggedParent = page([{ ...v2ThreadShell, id: parentId, tags: ["private"] }]);
63 +
64 + it.each([
65 + { name: "archived tagged parent", parentPage: archivedTaggedParent, live: false, tasks: 0 },
66 + { name: "live visible parent", parentPage: page([]), live: true, tasks: 1 },
67 + { name: "parent page not loaded yet", parentPage: null, live: false, tasks: 0 },
68 + { name: "archive scoped to the task's machine", parentPage: undefined, live: false, tasks: 0 },
69 + {
70 + name: "only a third machine hides tags",
71 + parentPage: page([]),
72 + live: false,
73 + tasks: 0,
74 + parentTags: null,
75 + },
76 + ])("$name", ({ parentPage, live, tasks, parentTags = ["private"] }) => {
77 + const snapshotsAtom = createArchivedThreadSnapshotsAtomFamily<Error>({
78 + getSnapshotAtom: (environmentId) =>
79 + Atom.make(
80 + environmentId === taskEnvironmentId
81 + ? AsyncResult.success(taskPage)
82 + : parentPage === null || parentPage === undefined
83 + ? AsyncResult.initial<OrchestrationV2ArchivedShellSnapshot, Error>(true)
84 + : AsyncResult.success(parentPage),
85 + ),
86 + hiddenThreadTagsAtom: (environmentId) =>
87 + Atom.make(environmentId === parentEnvironmentId ? parentTags : null),
88 + hiddenThreadKeysAtom: Atom.make((): ReadonlySet<string> => new Set()),
89 + liveThreadRefsAtom: Atom.make((): ReadonlyArray<ScopedThreadRef> =>
90 + live ? [{ environmentId: parentEnvironmentId, threadId: parentId }] : [],
91 + ),
92 + // The parent's machine hides tags; a scoped archive learns that only from this flag.
93 + anyEnvironmentHidingAtom: Atom.make(true),
94 + labelPrefix: "test:archived-thread-snapshots",
95 + });
96 + const registry = AtomRegistry.make();
97 + const { snapshots } = registry.get(
98 + snapshotsAtom(
99 + makeArchivedThreadsEnvironmentKey(
100 + parentPage === undefined ? [taskEnvironmentId] : [parentEnvironmentId, taskEnvironmentId],
101 + ),
102 + ),
103 + );
104 + const taskSnapshot = snapshots.find((entry) => entry.environmentId === taskEnvironmentId);
105 + expect(taskSnapshot?.snapshot.threads.length).toBe(tasks);
106 + registry.dispose();
107 + });
108 +});
packages/client-runtime/src/state/archivedThreads.ts
+47 -2
@@ -1,9 +1,16 @@
1 -import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
1 +import {
2 + EnvironmentId,
3 + type OrchestrationV2ArchivedShellSnapshot,
4 + type ScopedThreadRef,
5 +} from "@t3tools/contracts";
6 import * as Arr from "effect/Array";
7 import { pipe } from "effect/Function";
8 import * as Order from "effect/Order";
9 import { AsyncResult, Atom } from "effect/reactivity";
10
11 +import { threadKey } from "./entities.ts";
12 +import { hiddenThreadKeys, type TagFilteredEnvironment } from "./threadTagFilter.ts";
13 +
14 export interface ArchivedSnapshotEntry {
15 readonly environmentId: EnvironmentId;
16 readonly snapshot: OrchestrationV2ArchivedShellSnapshot;
@@ -40,11 +47,21 @@ export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
47 readonly getSnapshotAtom: (
48 environmentId: EnvironmentId,
49 ) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2ArchivedShellSnapshot, E>>;
50 + readonly hiddenThreadTagsAtom: (
51 + environmentId: EnvironmentId,
52 + ) => Atom.Atom<ReadonlyArray<string> | null>;
53 + /** Live threads the tag filter hides, so archived children of hidden parents stay hidden. */
54 + readonly hiddenThreadKeysAtom: Atom.Atom<ReadonlySet<string>>;
55 + /** Live threads, so archived children of loaded, visible parents stay visible. */
56 + readonly liveThreadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
57 + /** Whether any connected environment hides tags, including ones outside this archive's scope. */
58 + readonly anyEnvironmentHidingAtom: Atom.Atom<boolean>;
59 readonly labelPrefix: string;
60 }) {
61 return Atom.family((environmentKey: string) =>
62 Atom.make((get): ArchivedThreadSnapshotsState => {
63 const snapshots: ArchivedSnapshotEntry[] = [];
64 + const environments: TagFilteredEnvironment[] = [];
65 let error: string | null = null;
66 let isLoading = false;
67
@@ -56,13 +73,41 @@ export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
73 if (snapshot !== null) {
74 snapshots.push({ environmentId, snapshot });
75 }
76 + // A page that has not arrived still counts, so its tags apply to children elsewhere.
77 + environments.push({
78 + environmentId,
79 + threads: snapshot?.threads ?? [],
80 + hiddenTags: get(options.hiddenThreadTagsAtom(environmentId)),
81 + });
82
83 if (error === null && result._tag === "Failure") {
84 error = "Failed to load archived threads.";
85 }
86 }
87
65 - return { snapshots, error, isLoading };
88 + // One pass over every environment's page, so archived tasks follow parents archived elsewhere.
89 + // Any connected machine may hide an unloaded parent, so the global flag decides, not the scope.
90 + const hidingAnywhere = get(options.anyEnvironmentHidingAtom);
91 + const hidden = hiddenThreadKeys(
92 + environments,
93 + get(options.hiddenThreadKeysAtom),
94 + hidingAnywhere ? new Set(get(options.liveThreadRefsAtom).map(threadKey)) : undefined,
95 + hidingAnywhere,
96 + );
97 + if (hidden.size === 0) return { snapshots, error, isLoading };
98 + return {
99 + snapshots: snapshots.map(({ environmentId, snapshot }) => ({
100 + environmentId,
101 + snapshot: {
102 + ...snapshot,
103 + threads: snapshot.threads.filter(
104 + (thread) => !hidden.has(threadKey({ environmentId, threadId: thread.id })),
105 + ),
106 + },
107 + })),
108 + error,
109 + isLoading,
110 + };
111 }).pipe(Atom.withLabel(`${options.labelPrefix}:${environmentKey}`)),
112 );
113 }
packages/client-runtime/src/state/orchestrationV2Projection.ts
+2 -1
@@ -293,8 +293,9 @@ export function applyOrchestrationV2ProjectionEvent(
293 case "thread.provider-switched":
294 case "thread.guest-share-updated":
295 return { ...base, thread: event.payload };
296 - // Visited tracking is read state, not activity: skip the updatedAt bump.
296 + // Visited tracking and tags are not activity: skip the updatedAt bump.
297 case "thread.visited":
298 + case "thread.tags-updated":
299 case "thread.marked-unread":
300 return { ...projection, thread: event.payload };
301 case "run.created":
packages/client-runtime/src/state/server.ts
+21
@@ -1078,6 +1078,26 @@ export function createServerEnvironmentAtoms<R, E>(
1078 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
1079 ),
1080 );
1081 + const hiddenThreadTagsAtom = Atom.family((environmentId: EnvironmentId) =>
1082 + Atom.make((get) => {
1083 + const settings = get(settingsValueAtom(environmentId));
1084 + if (settings?.hideTaggedThreads !== true) return null;
1085 + // Tags are trimmed on write; trim hand-edited entries so " private" still matches.
1086 + const tags = settings.hiddenThreadTags.map((tag) => tag.trim()).filter((tag) => tag !== "");
1087 + return tags.length > 0 ? tags : null;
1088 + }).pipe(
1089 + // Trimming makes a new array on every settings push; keep equal lists stable.
1090 + Atom.withEquality(
1091 + (a: ReadonlyArray<string> | null, b: ReadonlyArray<string> | null) =>
1092 + a === b ||
1093 + (a !== null &&
1094 + b !== null &&
1095 + a.length === b.length &&
1096 + a.every((tag, index) => tag === b[index])),
1097 + ),
1098 + Atom.withLabel(`environment-data:server:hidden-thread-tags:${environmentId}`),
1099 + ),
1100 + );
1101 const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>
1102 Atom.make((get) => {
1103 const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};
@@ -1201,6 +1221,7 @@ export function createServerEnvironmentAtoms<R, E>(
1221 }),
1222 updateStateAtom,
1223 settingsValueAtom,
1224 + hiddenThreadTagsAtom,
1225 usageModelFilterAtom,
1226 providersValueAtom,
1227 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
packages/client-runtime/src/state/threadShell.test.ts
+5 -1
@@ -48,7 +48,11 @@ function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [environment
48 registry: AtomRegistry.make(),
49 snapshotAtom,
50 catalogValueAtom,
51 - threads: createEnvironmentThreadShellAtoms({ catalogValueAtom, snapshotAtom }),
51 + threads: createEnvironmentThreadShellAtoms({
52 + catalogValueAtom,
53 + snapshotAtom,
54 + hiddenThreadTagsAtom: () => Atom.make(null),
55 + }),
56 };
57 }
58
packages/client-runtime/src/state/threadShell.ts
+66 -1
@@ -16,6 +16,7 @@ import { Atom } from "effect/reactivity";
16
17 import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
18 import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
19 +import { hiddenThreadKeys, NO_HIDDEN_THREADS } from "./threadTagFilter.ts";
20 import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
21 import {
22 arrayElementsEqual,
@@ -204,6 +205,10 @@ export function createEnvironmentThreadShellAtoms(input: {
205 readonly snapshotAtom: (
206 environmentId: EnvironmentId,
207 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
208 + /** Tags whose threads display lists leave out; null while the filter is off. */
209 + readonly hiddenThreadTagsAtom: (
210 + environmentId: EnvironmentId,
211 + ) => Atom.Atom<ReadonlyArray<string> | null>;
212 }) {
213 // Point reads and aggregate lists share values without keeping an atom alive
214 // for every listed thread. Replaced source objects can be collected.
@@ -589,12 +594,67 @@ export function createEnvironmentThreadShellAtoms(input: {
594 return previousThreadShells;
595 }).pipe(Atom.withLabel("environment-thread-shell-list"));
596
597 + // Point reads and threadShellsAtom stay complete, so code that asks whether a thread
598 + // exists (outboxes, drafts, removals) never mistakes a hidden thread for a missing one.
599 + let previousHiddenThreadKeys: ReadonlySet<string> = NO_HIDDEN_THREADS;
600 + const hiddenThreadKeysAtom = Atom.make((get) => {
601 + const environments = Array.from(
602 + enabledEnvironmentIds(get(input.catalogValueAtom)),
603 + (environmentId) => ({
604 + environmentId,
605 + hiddenTags: get(input.hiddenThreadTagsAtom(environmentId)),
606 + }),
607 + );
608 + // Read shells only while some environment hides tags, so streaming ticks cost nothing otherwise.
609 + if (!environments.some((environment) => environment.hiddenTags !== null)) {
610 + previousHiddenThreadKeys = NO_HIDDEN_THREADS;
611 + return NO_HIDDEN_THREADS;
612 + }
613 + const next = hiddenThreadKeys(
614 + environments.map((environment) => ({
615 + ...environment,
616 + threads: get(environmentThreadsAtom(environment.environmentId)),
617 + })),
618 + );
619 + if (
620 + next.size === previousHiddenThreadKeys.size &&
621 + [...next].every((key) => previousHiddenThreadKeys.has(key))
622 + ) {
623 + return previousHiddenThreadKeys;
624 + }
625 + previousHiddenThreadKeys = next;
626 + return next;
627 + }).pipe(Atom.withLabel("environment-hidden-thread-keys"));
628 +
629 + const anyEnvironmentHidingAtom = Atom.make((get) =>
630 + Array.from(enabledEnvironmentIds(get(input.catalogValueAtom))).some(
631 + (environmentId) => get(input.hiddenThreadTagsAtom(environmentId)) !== null,
632 + ),
633 + ).pipe(Atom.withLabel("environment-any-hiding-thread-tags"));
634 +
635 + /** threadShellsAtom without the threads the tag filter hides, for pickers and palettes. */
636 + let previousVisibleThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
637 + const visibleThreadShellsAtom = Atom.make((get) => {
638 + const threads = get(threadShellsAtom);
639 + const hidden = get(hiddenThreadKeysAtom);
640 + if (hidden.size === 0) return threads;
641 + const next = threads.filter(
642 + (thread) =>
643 + !hidden.has(threadKey({ environmentId: thread.environmentId, threadId: thread.id })),
644 + );
645 + if (arrayElementsEqual(previousVisibleThreadShells, next)) return previousVisibleThreadShells;
646 + previousVisibleThreadShells = next;
647 + return next;
648 + }).pipe(Atom.withLabel("environment-visible-thread-shell-list"));
649 +
650 // Lists that arrange threads read this, so a running thread's streaming
651 // ticks reach only what reads its live shell.
652 let previousQuietThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
653 const quietThreadShellsAtom = Atom.make((get) => {
654 const next: EnvironmentThreadShell[] = [];
655 + const hidden = get(hiddenThreadKeysAtom);
656 for (const ref of get(threadRefsAtom)) {
657 + if (hidden.has(threadKey(ref))) continue;
658 const shell = get(quietThreadShellAtomFamily(threadKey(ref)));
659 if (shell !== null) next.push(shell);
660 }
@@ -635,12 +695,14 @@ export function createEnvironmentThreadShellAtoms(input: {
695 const navigationThreadShellsAtom = Atom.make((get) => {
696 const next: EnvironmentThreadShell[] = [];
697 const underParent = get(delegatedUnderParentAtom);
698 + const hidden = get(hiddenThreadKeysAtom);
699 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
700 const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
701 for (const thread of get(environmentThreadsAtom(environmentId))) {
702 if (
703 thread.archivedAt !== null ||
643 - isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent)
704 + isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent) ||
705 + hidden.has(threadKey({ environmentId, threadId: thread.id }))
706 ) {
707 continue;
708 }
@@ -659,6 +721,9 @@ export function createEnvironmentThreadShellAtoms(input: {
721 environmentThreadRefsByProjectAtom,
722 threadRefsAtom,
723 threadShellsAtom,
724 + visibleThreadShellsAtom,
725 + hiddenThreadKeysAtom,
726 + anyEnvironmentHidingAtom,
727 quietThreadShellsAtom,
728 navigationThreadShellsAtom,
729 delegatedUnderParentAtom,
packages/client-runtime/src/state/threadTagFilter.test.ts new
+127
@@ -0,0 +1,127 @@
1 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { threadKey } from "./entities.ts";
5 +import { hiddenThreadKeys, NO_HIDDEN_THREADS, visibleLinkedThreads } from "./threadTagFilter.ts";
6 +
7 +const local = EnvironmentId.make("local");
8 +const linked = EnvironmentId.make("linked");
9 +
10 +const thread = (
11 + id: string,
12 + tags: Array<string>,
13 + parent?: { readonly id: string; readonly relationship: "fork" | "subagent" },
14 + delegatedFrom?: { readonly environmentId: EnvironmentId; readonly id: string },
15 +) => ({
16 + id: ThreadId.make(id),
17 + tags,
18 + lineage: {
19 + parentThreadId: parent === undefined ? null : ThreadId.make(parent.id),
20 + relationshipToParent: parent?.relationship ?? null,
21 + rootThreadId: ThreadId.make(parent?.id ?? id),
22 + },
23 + ...(delegatedFrom === undefined
24 + ? {}
25 + : {
26 + delegatedFrom: {
27 + environmentId: delegatedFrom.environmentId,
28 + threadId: ThreadId.make(delegatedFrom.id),
29 + title: "parent",
30 + },
31 + }),
32 +});
33 +
34 +const localThreads = [
35 + thread("private", ["private"]),
36 + thread("private-subagent", [], { id: "private", relationship: "subagent" }),
37 + thread("private-fork", [], { id: "private", relationship: "fork" }),
38 + thread("plain", []),
39 + thread("plain-private-side-chat", ["private"], { id: "plain", relationship: "subagent" }),
40 +];
41 +const linkedThreads = [
42 + thread("delegated-from-private", [], undefined, { environmentId: local, id: "private" }),
43 + thread("linked-client", ["client"]),
44 +];
45 +const hiddenIds = (localTags: Array<string> | null, linkedTags: Array<string> | null) =>
46 + [
47 + ...hiddenThreadKeys([
48 + { environmentId: local, threads: localThreads, hiddenTags: localTags },
49 + { environmentId: linked, threads: linkedThreads, hiddenTags: linkedTags },
50 + ]),
51 + ].toSorted();
52 +const key = (environmentId: EnvironmentId, id: string) =>
53 + threadKey({ environmentId, threadId: ThreadId.make(id) });
54 +
55 +describe("hiddenThreadKeys", () => {
56 + it("hides nothing while every filter is off", () => {
57 + expect(hiddenIds(null, null)).toEqual([]);
58 + expect(
59 + hiddenThreadKeys([{ environmentId: local, threads: localThreads, hiddenTags: null }]),
60 + ).toBe(NO_HIDDEN_THREADS);
61 + });
62 +
63 + it("hides a tagged thread with its subagents and linked tasks, but not its forks", () => {
64 + expect(hiddenIds(["private"], null)).toEqual(
65 + [
66 + key(local, "private"),
67 + key(local, "private-subagent"),
68 + key(linked, "delegated-from-private"),
69 + ].toSorted(),
70 + );
71 + });
72 +
73 + it("judges an archive page against live hidden parents", () => {
74 + const archived = hiddenThreadKeys(
75 + [{ environmentId: linked, threads: [linkedThreads[0]!], hiddenTags: null }],
76 + new Set([key(local, "private")]),
77 + );
78 + expect([...archived]).toEqual([key(linked, "delegated-from-private")]);
79 + });
80 +
81 + it("hides a child whose parent is not loaded while any environment hides tags", () => {
82 + const orphan = thread("orphan-task", [], undefined, { environmentId: local, id: "archived" });
83 + const keys = (localTags: Array<string> | null, linkedTags: Array<string> | null) => [
84 + ...hiddenThreadKeys([
85 + { environmentId: local, threads: [], hiddenTags: localTags },
86 + { environmentId: linked, threads: [orphan], hiddenTags: linkedTags },
87 + ]),
88 + ];
89 + expect(keys(["private"], null)).toEqual([key(linked, "orphan-task")]);
90 + expect(keys(null, ["client"])).toEqual([key(linked, "orphan-task")]);
91 + expect(keys(null, null)).toEqual([]);
92 + });
93 +
94 + it("applies each environment's own tags", () => {
95 + expect(hiddenIds(null, ["client", "private"])).toEqual([key(linked, "linked-client")]);
96 + });
97 +
98 + it("judges loaded PR rows by visibility and leaves out unloaded rows while hiding", () => {
99 + const hidden = hiddenThreadKeys([
100 + { environmentId: local, threads: localThreads, hiddenTags: ["private"] },
101 + ]);
102 + const rows = [
103 + { id: ThreadId.make("private-subagent") },
104 + { id: ThreadId.make("plain-private-side-chat") },
105 + { id: ThreadId.make("off-shell") },
106 + ];
107 + const loaded = localThreads.map((entry) => ({ environmentId: local, threadId: entry.id }));
108 + const visible = (hiding: boolean) =>
109 + visibleLinkedThreads(rows, local, loaded, hidden, hiding).map((row) => row.id);
110 + expect(visible(true)).toEqual(["plain-private-side-chat"]);
111 + // Another machine hides tags while nothing here is hidden: unloaded rows still stay out.
112 + expect(
113 + visibleLinkedThreads(rows, local, loaded, NO_HIDDEN_THREADS, true).map((row) => row.id),
114 + ).toEqual(["private-subagent", "plain-private-side-chat"]);
115 + expect(visibleLinkedThreads(rows, local, loaded, NO_HIDDEN_THREADS, false)).toBe(rows);
116 + });
117 +
118 + it("lets a live hidden parent win over the same parent being loaded elsewhere", () => {
119 + const parentKey = key(local, "private");
120 + const archived = hiddenThreadKeys(
121 + [{ environmentId: linked, threads: [linkedThreads[0]!], hiddenTags: null }],
122 + new Set([parentKey]),
123 + new Set([parentKey]),
124 + );
125 + expect([...archived]).toEqual([key(linked, "delegated-from-private")]);
126 + });
127 +});
packages/client-runtime/src/state/threadTagFilter.ts new
+125
@@ -0,0 +1,125 @@
1 +import {
2 + type EnvironmentId,
3 + isListedThreadLineage,
4 + type OrchestrationV2ThreadShell,
5 + type ScopedThreadRef,
6 + type ThreadId,
7 +} from "@t3tools/contracts";
8 +
9 +import { threadKey } from "./entities.ts";
10 +
11 +type FilterableThread = Pick<
12 + OrchestrationV2ThreadShell,
13 + "id" | "lineage" | "tags" | "delegatedFrom"
14 +>;
15 +
16 +export interface TagFilteredEnvironment {
17 + readonly environmentId: EnvironmentId;
18 + readonly threads: ReadonlyArray<FilterableThread>;
19 + /** Tags this environment hides, or null while its filter is off. */
20 + readonly hiddenTags: ReadonlyArray<string> | null;
21 +}
22 +
23 +export const NO_HIDDEN_THREADS: ReadonlySet<string> = new Set();
24 +
25 +/** The thread a subagent, side chat or delegated task takes its visibility from, if any. */
26 +export function visibilityParentKey(
27 + environmentId: EnvironmentId,
28 + thread: Pick<FilterableThread, "lineage" | "delegatedFrom">,
29 +): string | null {
30 + const parentId = thread.lineage.parentThreadId;
31 + if (!isListedThreadLineage(thread.lineage) && parentId !== null) {
32 + return threadKey({ environmentId, threadId: parentId });
33 + }
34 + return thread.delegatedFrom === undefined ? null : threadKey(thread.delegatedFrom);
35 +}
36 +
37 +/**
38 + * Pull request linked-thread rows the tag filter leaves visible. Loaded threads use the
39 + * parent-aware hidden set. Rows the shell leaves out carry no lineage, so while any
40 + * environment hides tags they stay out.
41 + */
42 +export function visibleLinkedThreads<Row extends { readonly id: ThreadId }>(
43 + rows: ReadonlyArray<Row>,
44 + environmentId: EnvironmentId,
45 + loadedThreadRefs: ReadonlyArray<ScopedThreadRef>,
46 + hiddenKeys: ReadonlySet<string>,
47 + hidingAnywhere: boolean,
48 +): ReadonlyArray<Row> {
49 + if (!hidingAnywhere && hiddenKeys.size === 0) return rows;
50 + const loaded = new Set(loadedThreadRefs.map((ref) => ref.threadId));
51 + return rows.filter((row) =>
52 + loaded.has(row.id)
53 + ? !hiddenKeys.has(threadKey({ environmentId, threadId: row.id }))
54 + : !hidingAnywhere,
55 + );
56 +}
57 +
58 +function hasHiddenTag(
59 + tags: ReadonlyArray<string> | undefined,
60 + hiddenTags: ReadonlyArray<string> | null,
61 +): boolean {
62 + return hiddenTags?.some((tag) => tags?.includes(tag) === true) === true;
63 +}
64 +
65 +/**
66 + * Keys of threads the tag filter hides. Children (subagents, side chats, delegated tasks) follow
67 + * their parent; while any environment hides tags, a child whose parent is not loaded stays hidden.
68 + * For a partial list such as an archive page, `alreadyHidden` and `loadedElsewhere` give the
69 + * hidden and loaded keys of live threads, and `hidingAnywhere` the global flag.
70 + */
71 +export function hiddenThreadKeys(
72 + environments: ReadonlyArray<TagFilteredEnvironment>,
73 + alreadyHidden: ReadonlySet<string> = NO_HIDDEN_THREADS,
74 + loadedElsewhere: ReadonlySet<string> = NO_HIDDEN_THREADS,
75 + hidingAnywhere: boolean = environments.some((environment) => environment.hiddenTags !== null),
76 +): ReadonlySet<string> {
77 + if (alreadyHidden.size === 0 && !hidingAnywhere) return NO_HIDDEN_THREADS;
78 + const byKey = new Map<
79 + string,
80 + { thread: FilterableThread; environment: TagFilteredEnvironment }
81 + >();
82 + for (const environment of environments) {
83 + for (const thread of environment.threads) {
84 + byKey.set(threadKey({ environmentId: environment.environmentId, threadId: thread.id }), {
85 + thread,
86 + environment,
87 + });
88 + }
89 + }
90 + const hiddenByKey = new Map<string, boolean>();
91 + const isHidden = (key: string): boolean => {
92 + if (alreadyHidden.has(key)) return true;
93 + const known = hiddenByKey.get(key);
94 + if (known !== undefined) return known;
95 + const entry = byKey.get(key);
96 + if (entry === undefined) return false;
97 + const { thread, environment } = entry;
98 + const parentKey = visibilityParentKey(environment.environmentId, thread);
99 + const followsParent =
100 + parentKey !== null && (byKey.has(parentKey) || alreadyHidden.has(parentKey));
101 + if (parentKey !== null && !followsParent && loadedElsewhere.has(parentKey)) {
102 + hiddenByKey.set(key, false);
103 + return false;
104 + }
105 + if (parentKey !== null && !followsParent && hidingAnywhere) {
106 + hiddenByKey.set(key, true);
107 + return true;
108 + }
109 + if (!followsParent) {
110 + const hidden = hasHiddenTag(thread.tags, environment.hiddenTags);
111 + hiddenByKey.set(key, hidden);
112 + return hidden;
113 + }
114 + // Seed before following the parent so a malformed cycle ends visible.
115 + hiddenByKey.set(key, false);
116 + const hidden = isHidden(parentKey);
117 + hiddenByKey.set(key, hidden);
118 + return hidden;
119 + };
120 + const hidden = new Set<string>();
121 + for (const key of byKey.keys()) {
122 + if (isHidden(key)) hidden.add(key);
123 + }
124 + return hidden.size === 0 ? NO_HIDDEN_THREADS : hidden;
125 +}
packages/client-runtime/src/state/threads.ts
+1
@@ -1113,3 +1113,4 @@ export * from "./threadFamilies.ts";
1113 export * from "./olderSettledThreads.ts";
1114 export * from "./threadShell.ts";
1115 export * from "./threadState.ts";
1116 +export * from "./threadTagFilter.ts";
packages/contracts/src/index.ts
+1
@@ -46,6 +46,7 @@ export * from "./peerLink.ts";
46 export * from "./threadMetadataMcp.ts";
47 export * from "./threadPullRequest.ts";
48 export * from "./threadSearch.ts";
49 +export * from "./threadTags.ts";
50 export * from "./threadTitle.ts";
51 export * from "./t3ProjectFile.ts";
52 export * from "./editor.ts";
packages/contracts/src/orchestrationV2.ts
+14
@@ -44,6 +44,7 @@ import {
44 import { AuthMcpClientAccess } from "./auth.ts";
45 import { ChatAttachment } from "./chatAttachment.ts";
46 import { ThreadGuestShare } from "./guestShare.ts";
47 +import { StoredThreadTags, ThreadTag } from "./threadTags.ts";
48 import {
49 OrchestrationSearchThreadsInput,
50 OrchestrationSearchThreadsResult,
@@ -487,6 +488,8 @@ export const OrchestrationV2AppThread = Schema.Struct({
488 autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
489 pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
490 activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
491 + /** Absent on threads written before tags existed; read as empty. */
492 + tags: Schema.optional(StoredThreadTags),
493 lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
494 Schema.withDecodingDefault(Effect.succeed(null)),
495 ),
@@ -1877,6 +1880,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([
1880 "thread.unpinned",
1881 "thread.pin-reordered",
1882 "thread.active-reordered",
1883 + "thread.tags-updated",
1884 "thread.visited",
1885 "thread.marked-unread",
1886 "thread.metadata-updated",
@@ -2129,6 +2133,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
2133 autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2134 pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2135 activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2136 + /** Absent on threads written before tags existed; read as empty. */
2137 + tags: Schema.optional(StoredThreadTags),
2138 lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2139 opens: Schema.optional(LenientThreadOpens),
2140 titleRegeneration: Schema.optional(
@@ -2758,6 +2764,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([
2764 "thread.unpinned",
2765 "thread.pin-reordered",
2766 "thread.active-reordered",
2767 + "thread.tags-updated",
2768 "thread.visited",
2769 "thread.marked-unread",
2770 "thread.pull-request-synced",
@@ -2999,6 +3006,13 @@ export const OrchestrationV2Command = Schema.Union([
3006 commandId: CommandId,
3007 threadId: ThreadId,
3008 }),
3009 + Schema.Struct({
3010 + type: Schema.Literal("thread.tag.set"),
3011 + commandId: CommandId,
3012 + threadId: ThreadId,
3013 + tag: ThreadTag,
3014 + tagged: Schema.Boolean,
3015 + }),
3016 Schema.Struct({
3017 type: Schema.Literal("thread.pin.reorder"),
3018 commandId: CommandId,
packages/contracts/src/settings.test.ts
+9
@@ -139,6 +139,15 @@ describe("ServerSettings usage price overrides", () => {
139 });
140 });
141
142 +it("drops a hand-edited non-string hidden tag and keeps the rest of the settings", () => {
143 + const settings = decodeServerSettings({
144 + hiddenThreadTags: ["private", 123],
145 + hideTaggedThreads: true,
146 + });
147 + expect(settings.hiddenThreadTags).toEqual(["private"]);
148 + expect(settings.hideTaggedThreads).toBe(true);
149 +});
150 +
151 describe("ServerSettings secret providers", () => {
152 const onePassword = (account: string) => ({
153 kind: "one_password",
packages/contracts/src/settings.ts
+14
@@ -1255,6 +1255,18 @@ export const ServerSettings = Schema.Struct({
1255 snoozePresets: SnoozePresetSettings.pipe(
1256 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNOOZE_PRESETS)),
1257 ),
1258 + /** Clients hide threads with these tags while `hideTaggedThreads` is on. Bad entries drop alone, so a hand edit cannot reset settings. */
1259 + hiddenThreadTags: Schema.Array(Schema.Unknown).pipe(
1260 + Schema.decodeTo(
1261 + Schema.Array(Schema.String),
1262 + SchemaTransformation.transform<ReadonlyArray<string>, ReadonlyArray<unknown>>({
1263 + decode: (values) => values.filter((value) => typeof value === "string"),
1264 + encode: (values) => values,
1265 + }),
1266 + ),
1267 + Schema.withDecodingDefault(Effect.succeed([])),
1268 + ),
1269 + hideTaggedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1270 /** Beta: guest links for this machine's threads. Off refuses new links and pauses existing ones. */
1271 guestSharingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1272 /**
@@ -1639,6 +1651,8 @@ export const ServerSettingsPatch = Schema.Struct({
1651 autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),
1652 snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean),
1653 snoozePresets: Schema.optionalKey(SnoozePresetSettings),
1654 + hiddenThreadTags: Schema.optionalKey(Schema.Array(Schema.String)),
1655 + hideTaggedThreads: Schema.optionalKey(Schema.Boolean),
1656 guestSharingEnabled: Schema.optionalKey(Schema.Boolean),
1657 linkedEnvironmentsEnabled: Schema.optionalKey(Schema.Boolean),
1658 backgroundActivity: Schema.optionalKey(
packages/contracts/src/threadTags.ts new
+18
@@ -0,0 +1,18 @@
1 +import * as Effect from "effect/Effect";
2 +import * as Schema from "effect/Schema";
3 +
4 +import { TrimmedNonEmptyString } from "./baseSchemas.ts";
5 +
6 +/** Tags match by exact spelling and case after trimming. */
7 +export const ThreadTag = TrimmedNonEmptyString.check(
8 + Schema.isMaxLength(64),
9 + Schema.makeFilter((value) =>
10 + /[\p{Cc}]/u.test(value) ? "A thread tag must be a single line of text." : true,
11 + ),
12 +);
13 +export type ThreadTag = typeof ThreadTag.Type;
14 +
15 +/** Tags read back from storage or a peer. Lenient so a later tag rule never fails a whole thread. */
16 +export const StoredThreadTags = Schema.Array(Schema.String).pipe(
17 + Schema.catchDecoding(() => Effect.succeedSome([])),
18 +);