Skip to content
TypeScript

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

Theo Browne30654b3e91a5
diff --git a/apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts b/apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts
index aeec98f116e..4ca5a32f606 100644
--- a/apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts
+++ b/apps/mobile/src/features/archive/useArchivedThreadSnapshots.ts
@@ -9,6 +9,8 @@ import { useMemo } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { orchestrationEnvironment } from "../../state/orchestration";
+import { serverEnvironment } from "../../state/server";
+import { environmentThreadShells } from "../../state/threads";
function archivedSnapshotAtom(environmentId: EnvironmentId) {
return orchestrationEnvironment.archivedShellSnapshot({
@@ -19,6 +21,10 @@ function archivedSnapshotAtom(environmentId: EnvironmentId) {
const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
getSnapshotAtom: archivedSnapshotAtom,
+ hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
+ hiddenThreadKeysAtom: environmentThreadShells.hiddenThreadKeysAtom,
+ liveThreadRefsAtom: environmentThreadShells.threadRefsAtom,
+ anyEnvironmentHidingAtom: environmentThreadShells.anyEnvironmentHidingAtom,
labelPrefix: "mobile:archived-thread-snapshots",
});
diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx
index 841eaae7c6d..e9e9e50d452 100644
--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx
+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx
@@ -46,7 +46,7 @@ import {
useProjects,
useServerConfigs,
useThreadShell,
- useThreadShells,
+ useVisibleThreadShells,
} from "../../state/entities";
import { useThreadSearch } from "../../state/queries";
import { requestThreadMessageJump } from "../threads/threadMessageJump";
@@ -226,7 +226,7 @@ export function CommandPalette(props: {
const selectDetail = useSelectWorkspaceDetail();
const runCommand = props.onCommand;
const projects = useProjects();
- const threads = useThreadShells();
+ const threads = useVisibleThreadShells();
const activeThreadRef = parseActiveThreadPath(props.pathname);
const activeThread = useThreadShell(activeThreadRef);
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts b/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
index e1d9d871510..e19dc333f2e 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
@@ -1,3 +1,5 @@
+import { useAtomValue } from "@effect/atom-react";
+import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
import { AsyncResult } from "effect/reactivity";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import * as Dialog from "../../components/ui/Dialog";
@@ -27,6 +29,7 @@ import { uuidv4 } from "../../lib/uuid";
import { useEnvironmentServerConfig } from "../../state/entities";
import { composerPullRequests } from "../../state/pull-requests";
import { useEnvironmentQuery } from "../../state/query";
+import { environmentThreadShells } from "../../state/threads";
import { useEnvironmentScope } from "../../state/session";
import {
createNewTaskDraft,
@@ -69,8 +72,18 @@ export function usePullRequestThreads(
const [lastRelations, setLastRelations] = useState({ key, data: relations.data });
if (relations.data && (lastRelations.key !== key || relations.data !== lastRelations.data))
setLastRelations({ key, data: relations.data });
- const threads =
- (relations.data ?? (lastRelations.key === key ? lastRelations.data : null))?.threads ?? [];
+ const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
+ const hidingAnywhere = useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
+ const loadedThreadRefs = useAtomValue(
+ environmentThreadShells.environmentThreadRefsAtom(target.environmentId),
+ );
+ const threads = visibleLinkedThreads(
+ (relations.data ?? (lastRelations.key === key ? lastRelations.data : null))?.threads ?? [],
+ target.environmentId,
+ loadedThreadRefs,
+ hiddenKeys,
+ hidingAnywhere,
+ );
const connected = usePullRequestConnected(params.environmentId);
const canOperate = useEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope);
const canAsk = !connected || canOperate;
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index 52ef705e93b..ea2928f5313 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -65,7 +65,7 @@ import {
} from "../../state/use-composer-drafts";
import { appAtomRegistry } from "../../state/atom-registry";
import type { ComposerDocumentAttachment } from "../../lib/composerContext";
-import { useProject, useThreadShells } from "../../state/entities";
+import { useProject, useVisibleThreadShells } from "../../state/entities";
import { useMentionableEnvironments } from "../../state/environments";
import { useLinkedEnvironments } from "../../state/peerLinks";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
@@ -539,7 +539,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
draftMessage: draftMessage,
ownerKey: composerDraftKey,
environmentId: props.environmentId,
- threadShells: useThreadShells(),
+ threadShells: useVisibleThreadShells(),
environments: offersLinkedEnvironments(props.serverConfig)
? mentionableEnvironments
: NO_MACHINES,
diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts
index 59639116f1c..fefdb151f5f 100644
--- a/apps/mobile/src/state/composer-attachment-uploads.test.ts
+++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts
@@ -99,6 +99,7 @@ vi.mock("./entities", () => ({
useProjects: () => [],
useServerConfigs: () => new Map([["environment-1", config]]),
useThreadShells: () => [],
+ useVisibleThreadShells: () => [],
}));
vi.mock("./projects", () => ({ environmentProjects: {} }));
vi.mock("./workspace", () => ({ workspaceConnections: {} }));
diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts
index c5c33a5432e..1625998fdc6 100644
--- a/apps/mobile/src/state/entities.ts
+++ b/apps/mobile/src/state/entities.ts
@@ -173,6 +173,11 @@ export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
return useAtomValue(environmentThreadShells.threadShellsAtom);
}
+/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
+export function useVisibleThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
+ return useAtomValue(environmentThreadShells.visibleThreadShellsAtom);
+}
+
export function useNavigationThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
return useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
}
diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts
index bfd088ccf7f..d6e784377cc 100644
--- a/apps/mobile/src/state/threads.ts
+++ b/apps/mobile/src/state/threads.ts
@@ -21,6 +21,7 @@ import {
pendingThreadCreationOutcomesAtom,
selectThreadCreationDetail,
} from "./pending-thread-creation";
+import { serverEnvironment } from "./server";
import { environmentShell } from "./shell";
import { threadOutboxManager } from "./thread-outbox";
@@ -43,6 +44,7 @@ export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
export const environmentThreadShells = createEnvironmentThreadShellAtoms({
catalogValueAtom: environmentCatalog.catalogValueAtom,
snapshotAtom: threadEnvironment.snapshotAtom,
+ hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
});
export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts
index a10431d802b..868901f81f7 100644
--- a/apps/mobile/src/state/use-composer-drafts.test.ts
+++ b/apps/mobile/src/state/use-composer-drafts.test.ts
@@ -313,6 +313,7 @@ function modelReconciliationHarness(
const shells = createEnvironmentThreadShellAtoms({
catalogValueAtom,
snapshotAtom: () => snapshotAtom,
+ hiddenThreadTagsAtom: () => Atom.make(null),
});
const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
onTestFinished(registry.mount(selectedShell));
diff --git a/apps/mobile/src/state/use-pending-new-tasks.ts b/apps/mobile/src/state/use-pending-new-tasks.ts
index 1ad6a443b71..0d5e3f602e5 100644
--- a/apps/mobile/src/state/use-pending-new-tasks.ts
+++ b/apps/mobile/src/state/use-pending-new-tasks.ts
@@ -1,6 +1,8 @@
import { useAtomValue } from "@effect/atom-react";
+import { threadKey } from "@t3tools/client-runtime/state/entities";
import { buildPendingNewTasks, type PendingNewTask } from "./pending-new-tasks-model";
import { flattenQueuedThreadMessages } from "./thread-outbox-model";
+import { environmentThreadShells } from "./threads";
import { newTaskComposerDraftsAtom } from "./use-composer-drafts";
import { useThreadOutboxMessages } from "./use-thread-outbox";
@@ -13,8 +15,10 @@ export type {
export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const drafts = useAtomValue(newTaskComposerDraftsAtom);
- return buildPendingNewTasks({
- queuedMessages: flattenQueuedThreadMessages(queuedMessagesByThreadKey),
- drafts,
- });
+ const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
+ // A delivered creation can stay queued after its thread is live and hidden.
+ const queuedMessages = flattenQueuedThreadMessages(queuedMessagesByThreadKey).filter(
+ (message) => !hiddenKeys.has(threadKey(message)),
+ );
+ return buildPendingNewTasks({ queuedMessages, drafts });
}
diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
index 770da193984..9d261469c20 100644
--- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
@@ -841,7 +841,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
const messageId = MessageId.make("message:foundation-compact");
const threadStateEvent = (
suffix: string,
- type: "thread.visited" | "thread.metadata-updated",
+ type: "thread.visited" | "thread.metadata-updated" | "thread.tags-updated",
): OrchestrationV2DomainEvent => ({
id: EventId.make(`event:foundation-compact:${suffix}`),
type,
@@ -936,10 +936,13 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
...Array.from({ length: 501 }, (_, index) =>
threadStateEvent(`history-${index}`, "thread.visited"),
),
+ threadStateEvent("tags-1", "thread.tags-updated"),
threadStateEvent("visit-2", "thread.visited"),
messageEvent("message-2", "final"),
nodeEvent("node-2", "completed"),
itemEvent("item-2", "final"),
+ // Older clients skip tag events, so these must not remove the rename above.
+ threadStateEvent("tags-2", "thread.tags-updated"),
],
});
const beforeCompaction = yield* projections.getThreadProjection(threadId);
@@ -1002,6 +1005,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
"event:foundation-compact:message-2",
"event:foundation-compact:node-2",
"event:foundation-compact:item-2",
+ "event:foundation-compact:tags-2",
],
);
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 906cda37991..75df815127f 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -548,6 +548,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
case "thread.unpin":
case "thread.pin.reorder":
case "thread.active.reorder":
+ case "thread.tag.set":
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
@@ -3030,6 +3031,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
| "thread.pin"
| "thread.unpin"
| "thread.pin.reorder"
+ | "thread.tag.set"
| "thread.active.reorder"
| "thread.mark-unread"
| "thread.metadata.update"
@@ -3565,6 +3567,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
updatedAt: thread.updatedAt,
};
}
+ case "thread.tag.set": {
+ const current = thread.tags ?? [];
+ return {
+ ...thread,
+ tags: command.tagged
+ ? current.includes(command.tag)
+ ? current
+ : [...current, command.tag]
+ : current.filter((tag) => tag !== command.tag),
+ };
+ }
case "thread.mark-unread": {
// Retire the wake before rewinding the visit, preserving its settlement timer.
const snoozeExpired =
@@ -3936,6 +3949,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return "thread.pin-reordered" as const;
case "thread.active.reorder":
return "thread.active-reordered" as const;
+ case "thread.tag.set":
+ return "thread.tags-updated" as const;
case "thread.mark-unread":
return "thread.marked-unread" as const;
case "thread.metadata.update":
@@ -13067,6 +13082,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "thread.unpin":
case "thread.pin.reorder":
case "thread.active.reorder":
+ case "thread.tag.set":
case "thread.mark-unread":
case "thread.metadata.update":
case "thread.pull-request.link":
diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts
index aad9d355924..211fb2ad8e7 100644
--- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts
+++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts
@@ -219,6 +219,8 @@ export const layer: Layer.Layer<
];
// Read-state events preserve updatedAt and supersede only each other. Activity events supersede both groups.
const READ_STATE_THREAD_EVENT_TYPES = ["thread.visited", "thread.marked-unread"];
+ // Older clients skip tag events, so these supersede only each other.
+ const TAG_THREAD_EVENT_TYPE = "thread.tags-updated";
const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
@@ -243,6 +245,7 @@ export const layer: Layer.Layer<
let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
const retainedThreadIds = new Set<string>();
const retainedReadStateThreadIds = new Set<string>();
+ const retainedTagThreadIds = new Set<string>();
// Retain each key's oldest candidate, deleting it only when an older event appears.
const oldestCandidateByEntityKey = new Map<string, number | null>();
let deletedEventCount = 0;
@@ -316,6 +319,13 @@ export const layer: Layer.Layer<
) {
obsolete.push(row.sequence);
} else retainedReadStateThreadIds.add(row.stream_id);
+ } else if (
+ row.aggregate_kind === "thread" &&
+ row.event_type === TAG_THREAD_EVENT_TYPE
+ ) {
+ if (retainedThreadIds.has(row.stream_id) || retainedTagThreadIds.has(row.stream_id)) {
+ obsolete.push(row.sequence);
+ } else retainedTagThreadIds.add(row.stream_id);
} else if (
row.event_type === "thread.pull-request-link-updated" &&
retainedThreadIds.has(row.stream_id)
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 975ce7b0b9c..451a917770e 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -808,6 +808,7 @@ export function applyToProjection(
};
// Reordering and PR refreshes preserve the orchestrator's activity timestamp.
case "thread.active-reordered":
+ case "thread.tags-updated":
case "thread.pull-request-synced":
return {
...base,
@@ -1590,6 +1591,7 @@ export function threadShellFromProjection(
autoSettleDisabledAt: projection.thread.autoSettleDisabledAt ?? null,
pinOrderKey: projection.thread.pinOrderKey ?? null,
+ ...(projection.thread.tags?.length ? { tags: projection.thread.tags } : {}),
lastVisitedAt: projection.thread.lastVisitedAt,
opens: projection.thread.opens ?? null,
titleRegeneration: projection.thread.titleRegeneration ?? null,
@@ -1855,6 +1857,7 @@ function shellFromState(input: {
autoSettleDisabledAt: input.state.thread.autoSettleDisabledAt ?? null,
pinOrderKey: input.state.thread.pinOrderKey ?? null,
+ ...(input.state.thread.tags?.length ? { tags: input.state.thread.tags } : {}),
lastVisitedAt: input.state.thread.lastVisitedAt,
opens: input.state.thread.opens ?? null,
titleRegeneration: input.state.thread.titleRegeneration ?? null,
@@ -1913,6 +1916,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
case "thread.unpinned":
case "thread.pin-reordered":
case "thread.active-reordered":
+ case "thread.tags-updated":
case "thread.visited":
case "thread.marked-unread":
case "thread.metadata-updated":
@@ -2725,6 +2729,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
event.type !== "thread.unpinned" &&
event.type !== "thread.pin-reordered" &&
event.type !== "thread.active-reordered" &&
+ event.type !== "thread.tags-updated" &&
event.type !== "thread.visited" &&
event.type !== "thread.marked-unread" &&
event.type !== "thread.metadata-updated" &&
diff --git a/apps/server/src/orchestration-v2/ThreadForkService.test.ts b/apps/server/src/orchestration-v2/ThreadForkService.test.ts
index 05994a7e696..5b35b5d195e 100644
--- a/apps/server/src/orchestration-v2/ThreadForkService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadForkService.test.ts
@@ -151,6 +151,7 @@ it.effect("resets a fork's pin, snooze, settle and delegation state but keeps it
},
historyOrigin: "v1_import",
linkOrigin,
+ tags: ["private"],
};
const sourceRun = makeSourceRun("completed");
const result = yield* planFork(sourceRun, {
@@ -168,6 +169,7 @@ it.effect("resets a fork's pin, snooze, settle and delegation state but keeps it
assert.isUndefined(result.targetThread.delegatedFrom);
assert.equal(result.targetThread.historyOrigin, "v1_import");
assert.deepEqual(result.targetThread.linkOrigin, linkOrigin);
+ assert.deepEqual(result.targetThread.tags, ["private"]);
assert.equal(result.targetThread.projectId, sourceThread.projectId);
assert.equal(result.targetThread.providerInstanceId, sourceThread.providerInstanceId);
assert.deepEqual(result.targetThread.modelSelection, sourceThread.modelSelection);
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index dbbdd5c66ba..2bb9f5ed631 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -18,6 +18,7 @@ import {
TurnItemId,
type ModelSelection,
type OrchestrationV2Run,
+ type OrchestrationV2ShellSnapshot,
type OrchestrationV2RuntimeRequest,
ProjectId,
type PullRequestDetail,
@@ -2546,6 +2547,37 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
});
assert.equal((yield* orchestrator.getThreadProjection(threadId)).thread.activeOrderKey, "a0");
+ const shellOf = (shell: Pick<OrchestrationV2ShellSnapshot, "threads">) =>
+ shell.threads.find((thread) => thread.id === threadId)!;
+ const untaggedShell = shellOf(yield* orchestrator.getShellSnapshot());
+ yield* TestClock.adjust("1 minute");
+ for (const [step, tag, tagged, expected] of [
+ ["add", "demo", true, ["demo"]],
+ ["retry", "demo", true, ["demo"]],
+ ["add-other", "private", true, ["demo", "private"]],
+ ["remove", "demo", false, ["private"]],
+ ["remove-last", "private", false, []],
+ ] as const) {
+ yield* orchestrator.dispatch({
+ type: "thread.tag.set",
+ commandId: CommandId.make(`runtime-layer-lifecycle-tag-${step}`),
+ threadId,
+ tag,
+ tagged,
+ });
+ assert.deepEqual(
+ shellOf(yield* orchestrator.getShellSnapshot()).tags ?? [],
+ expected,
+ step,
+ );
+ }
+ const taggedShell = shellOf(yield* orchestrator.getShellSnapshot());
+ // Tags are not activity, so the thread keeps its place in thread lists.
+ assert.equal(
+ DateTime.toEpochMillis(taggedShell.updatedAt),
+ DateTime.toEpochMillis(untaggedShell.updatedAt),
+ );
+
const preAutoProjection = yield* orchestrator.getThreadProjection(threadId);
const staleAutoSettle = yield* orchestrator
.dispatch({
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
index 77e8bae8f08..a3151462bbe 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
@@ -147,6 +147,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
case "thread.unpin":
case "thread.pin.reorder":
case "thread.active.reorder":
+ case "thread.tag.set":
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts
index f3c7b893afa..66e5a3def7c 100644
--- a/apps/server/src/relay/AgentAwarenessRelay.ts
+++ b/apps/server/src/relay/AgentAwarenessRelay.ts
@@ -113,6 +113,7 @@ function shouldPublishAgentAwarenessEvent(
case "thread.unpinned":
case "thread.pin-reordered":
case "thread.active-reordered":
+ case "thread.tags-updated":
case "thread.visited":
case "thread.marked-unread":
case "thread.runtime-mode-updated":
diff --git a/apps/web/src/components/CommandPalette.composition.browser.test.tsx b/apps/web/src/components/CommandPalette.composition.browser.test.tsx
index 47878859059..2eb58411808 100644
--- a/apps/web/src/components/CommandPalette.composition.browser.test.tsx
+++ b/apps/web/src/components/CommandPalette.composition.browser.test.tsx
@@ -21,6 +21,7 @@ vi.mock("../hooks/useEnvironmentTheme", () => ({ useEnvironmentThemeDefinitions:
vi.mock("../hooks/useSettings", async (original) => ({
...(await original<typeof import("../hooks/useSettings")>()),
useClientSettings: () => DEFAULT_CLIENT_SETTINGS,
+ useUpdateEnvironmentSettings: () => () => undefined,
}));
vi.mock("../hooks/useScratchProject", () => ({
useScratchProject: () => ({ scratchEnvironmentId: () => null }),
@@ -66,6 +67,10 @@ vi.mock("../state/entities", async (original) => ({
...(await original<typeof import("../state/entities")>()),
useProjects: () => [],
useThreadShells: () => [],
+ useVisibleThreadShells: () => [],
+ useHiddenThreadKeys: () => new Set(),
+ useAnyEnvironmentHiding: () => false,
+ useEnvironmentThreadRefs: () => [],
useServerConfigs: () => new Map(),
waitForProject: async () => undefined,
}));
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index 1d498481863..068808707b4 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -128,7 +128,16 @@ import {
useEnvironments,
usePrimaryEnvironmentId,
} from "../state/environments";
-import { useProjects, useServerConfigs, useThreadShells, waitForProject } from "../state/entities";
+import {
+ useAnyEnvironmentHiding,
+ useHiddenThreadKeys,
+ useEnvironmentThreadRefs,
+ useProjects,
+ useServerConfigs,
+ useVisibleThreadShells,
+ waitForProject,
+} from "../state/entities";
+import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
import {
appendBrowsePathSegment,
@@ -398,6 +407,11 @@ function OpenCommandPaletteDialog(props: {
},
);
const linkedThreadSearch = initialSearch.linkedThreadSearch;
+ // Rows were captured when the palette opened; drop any hidden since then.
+ const hiddenKeys = useHiddenThreadKeys();
+ const linkedEnvironmentId = linkedThreadSearch?.linkedThreads?.environmentId ?? null;
+ const hidingAnywhere = useAnyEnvironmentHiding();
+ const linkedThreadRefs = useEnvironmentThreadRefs(linkedEnvironmentId);
const [searchState, dispatchSearch] = useReducer(reduceCommandPaletteSearchState, null, () => {
const view = props.initialContext ? null : openIntentView(props.openIntent);
return view
@@ -479,7 +493,7 @@ function OpenCommandPaletteDialog(props: {
if (activeThreadReferenceCopyTarget === null) return;
await copyThreadReference(activeThreadReferenceCopyTarget);
};
- const threads = useThreadShells();
+ const threads = useVisibleThreadShells();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const providersByEnvironment = useEnvironmentProviders();
const { changeThemeItem, changeAppearanceItem, themeEditorItem } = useCommandPaletteThemeItems();
@@ -1717,6 +1731,13 @@ function OpenCommandPaletteDialog(props: {
isLinkedThreadSearch && linkedThreadSearch?.linkedThreads
? buildLinkedThreadActionItems({
...linkedThreadSearch.linkedThreads,
+ threads: visibleLinkedThreads(
+ linkedThreadSearch.linkedThreads.threads,
+ linkedThreadSearch.linkedThreads.environmentId,
+ linkedThreadRefs,
+ hiddenKeys,
+ hidingAnywhere,
+ ),
query: linkedThreadSearch.query,
icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
runThread: async (thread) => {
diff --git a/apps/web/src/components/CommandPaletteLookups.ts b/apps/web/src/components/CommandPaletteLookups.ts
index 6c9fcc629f7..3eb0ff69bf1 100644
--- a/apps/web/src/components/CommandPaletteLookups.ts
+++ b/apps/web/src/components/CommandPaletteLookups.ts
@@ -7,7 +7,7 @@ import {
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
import { useClientSettings } from "../hooks/useSettings";
import { getProjectOrderKey } from "@t3tools/client-runtime/state/project-grouping";
-import { useProjects, useThreadShells } from "../state/entities";
+import { useProjects, useVisibleThreadShells } from "../state/entities";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
@@ -55,7 +55,7 @@ export const selectCommandPaletteClientSettings = (settings: ClientSettings) =>
export function useSortedProjectGroups(environmentLabelById: ReadonlyMap<EnvironmentId, string>) {
const projects = useProjects();
- const threads = useThreadShells();
+ const threads = useVisibleThreadShells();
const projectOrder = useUiStateStore((store) => store.projectOrder);
const clientSettings = useClientSettings(selectCommandPaletteClientSettings);
const primaryEnvironmentId = usePrimaryEnvironmentId();
diff --git a/apps/web/src/components/CommandPaletteThreadItems.tsx b/apps/web/src/components/CommandPaletteThreadItems.tsx
index d106b4d1069..ddccc1c3a54 100644
--- a/apps/web/src/components/CommandPaletteThreadItems.tsx
+++ b/apps/web/src/components/CommandPaletteThreadItems.tsx
@@ -23,7 +23,7 @@ import {
deriveProviderInstanceEntries,
type ProviderInstanceEntry,
} from "../providerInstances";
-import { useThreadShells } from "../state/entities";
+import { useVisibleThreadShells } from "../state/entities";
import {
useEnvironmentProviders,
useEnvironments,
@@ -99,7 +99,7 @@ export function useCommandPaletteThreadItems(input: {
}) {
const { activeThread, threadSearchQuery } = input;
const navigate = useNavigate();
- const threads = useThreadShells();
+ const threads = useVisibleThreadShells();
const { projectEnvironmentLocationById } = useEnvironmentLookups();
const providerEntryByEnvironmentAndInstanceId = useProviderEntryByEnvironmentAndInstanceId();
const messageSearch = useConnectedThreadSearch(threadSearchQuery);
diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx
index 3af74e1d341..74c9aa9561b 100644
--- a/apps/web/src/components/ThreadNotificationCoordinator.tsx
+++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx
@@ -5,6 +5,7 @@ import {
} from "@t3tools/client-runtime/state/models";
import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
import type { AnyRouter } from "@tanstack/react-router";
+import { threadKey } from "@t3tools/client-runtime/state/entities";
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import type { ClientSettings } from "@t3tools/contracts/settings";
import * as Option from "effect/Option";
@@ -44,6 +45,8 @@ interface NotificationState extends ThreadNotificationObservation {
readonly status: SidebarThreadStatus;
}
+type ToastId = ReturnType<typeof toastManager.add>;
+
interface WatchedEnvironment {
unsubscribe: () => void;
previous: Map<ThreadId, NotificationState>;
@@ -59,14 +62,49 @@ export function startThreadNotifications(
registry: AtomRegistry.AtomRegistry,
router: AnyRouter,
): () => void {
- const pending = new Map<string, { environmentId: EnvironmentId; notification: Notification }>();
+ const pending = new Map<
+ string,
+ { environmentId: EnvironmentId; threadId: ThreadId; notification: Notification }
+ >();
const watched = new Map<EnvironmentId, WatchedEnvironment>();
- const trackNotification = (environmentId: EnvironmentId, notification: Notification) => {
+ const trackNotification = (
+ environmentId: EnvironmentId,
+ threadId: ThreadId,
+ notification: Notification,
+ ) => {
pending.get(notification.tag)?.notification.close();
- pending.set(notification.tag, { environmentId, notification });
+ pending.set(notification.tag, { environmentId, threadId, notification });
setNotificationBadge(pending.size);
};
+ // Toast ids by thread key, so hiding a thread can close its open toasts.
+ const openToasts = new Map<string, Array<ToastId>>();
+ const forgetToast = (key: string, toastId: ToastId) => {
+ const remaining = (openToasts.get(key) ?? []).filter((id) => id !== toastId);
+ if (remaining.length === 0) openToasts.delete(key);
+ else openToasts.set(key, remaining);
+ };
+ // A notification shown before the tag filter turned on must not stay on screen. While hiding,
+ // one whose thread left the live list (archived) cannot be judged, so it closes too.
+ const closeHiddenPending = () => {
+ const hidden = registry.get(environmentThreadShells.hiddenThreadKeysAtom);
+ const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom)
+ ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey))
+ : null;
+ const shouldClose = (key: string) => hidden.has(key) || (live !== null && !live.has(key));
+ for (const [key, toastIds] of openToasts) {
+ if (!shouldClose(key)) continue;
+ for (const toastId of toastIds) toastManager.close(toastId);
+ openToasts.delete(key);
+ }
+ const count = pending.size;
+ for (const [tag, entry] of pending) {
+ if (!shouldClose(threadKey(entry))) continue;
+ entry.notification.close();
+ pending.delete(tag);
+ }
+ if (count !== pending.size) setNotificationBadge(pending.size);
+ };
const clearPending = () => {
for (const { notification } of pending.values()) notification.close();
pending.clear();
@@ -80,6 +118,12 @@ export function startThreadNotifications(
kind: ThreadNotificationKind,
) => {
const { thread, status } = state;
+ if (
+ registry
+ .get(environmentThreadShells.hiddenThreadKeysAtom)
+ .has(threadKey({ environmentId, threadId: thread.id }))
+ )
+ return;
const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings();
const active = (router.state.matches.at(-1)?.params ?? {}) as {
environmentId?: string;
@@ -108,7 +152,9 @@ export function startThreadNotifications(
document.hasFocus() &&
(active.environmentId !== environmentId || active.threadId !== thread.id)
) {
- const toastId = toastManager.add({
+ const toastKey = threadKey({ environmentId, threadId: thread.id });
+ const toastId: ToastId = toastManager.add({
+ onRemove: (): void => forgetToast(toastKey, toastId),
type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
title,
description: thread.title,
@@ -138,6 +184,7 @@ export function startThreadNotifications(
},
},
});
+ openToasts.set(toastKey, [...(openToasts.get(toastKey) ?? []), toastId]);
return;
}
if (
@@ -155,7 +202,7 @@ export function startThreadNotifications(
// Windows drops clicks after a toast moves into Notification Center.
requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform),
});
- trackNotification(environmentId, notification);
+ trackNotification(environmentId, thread.id, notification);
notification.addEventListener("click", () => {
notification.close();
window.focus();
@@ -356,11 +403,17 @@ export function startThreadNotifications(
syncEnvironments();
},
);
+ const unsubscribeHidden = [
+ registry.subscribe(environmentThreadShells.hiddenThreadKeysAtom, closeHiddenPending),
+ registry.subscribe(environmentThreadShells.anyEnvironmentHidingAtom, closeHiddenPending),
+ registry.subscribe(environmentThreadShells.threadRefsAtom, closeHiddenPending),
+ ];
onSettings();
return () => {
unsubscribeSettings();
unsubscribeEnvironmentIds();
+ for (const unsubscribe of unsubscribeHidden) unsubscribe();
for (const entry of watched.values()) entry.unsubscribe();
watched.clear();
stopModeListeners();
diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx
index 79f4633ea54..30ab2465a9d 100644
--- a/apps/web/src/components/ThreadRouteView.tsx
+++ b/apps/web/src/components/ThreadRouteView.tsx
@@ -1,4 +1,8 @@
+import { useAtomValue } from "@effect/atom-react";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
+import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
+import { visibilityParentKey } from "@t3tools/client-runtime/state/threads";
+import * as Option from "effect/Option";
import { Navigate, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
@@ -7,9 +11,13 @@ import { BackgroundThreadContext } from "./chat/backgroundThread";
import { SidebarInset } from "./ui/sidebar";
import { useComposerDraftStore } from "../composerDraftStore";
import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
-import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities";
+import {
+ useEnvironmentThreadRefs,
+ useAnyEnvironmentHiding,
+ useQuietThreadShell,
+} from "../state/entities";
import { useEnvironmentShellStatus } from "../state/shell";
-import { useEnvironmentThread } from "../state/threads";
+import { environmentThreadShells, useEnvironmentThread } from "../state/threads";
import {
buildThreadRouteParams,
isThreadRouteSnapshotAuthoritative,
@@ -80,6 +88,28 @@ export function ThreadRouteView({
unlistedThreadRef?.environmentId ?? null,
unlistedThreadRef?.threadId ?? null,
);
+ const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
+ const unlistedThread = Option.getOrNull(Option.map(unlistedThreadDetail.data, (p) => p.thread));
+ const unlistedParentKey =
+ unlistedThreadRef === null || unlistedThread === null
+ ? null
+ : visibilityParentKey(unlistedThreadRef.environmentId, unlistedThread);
+ const unlistedParentShell = useQuietThreadShell(
+ unlistedParentKey === null ? null : parseThreadKey(unlistedParentKey),
+ );
+ const hidingAnywhere = useAnyEnvironmentHiding();
+ const draftRedirectShell = useQuietThreadShell(draftRedirect ?? null);
+ const hiddenByTagFilter = serverThreadRef !== null && 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 &&
+ !(
+ unlistedParentKey !== null &&
+ unlistedParentShell !== null &&
+ !hiddenKeys.has(unlistedParentKey)
+ );
const renderState = resolveThreadRouteRenderState({
bootstrapComplete,
serverThreadExists: serverThreadShell !== null,
@@ -106,7 +136,15 @@ export function ThreadRouteView({
let view: React.ReactNode = null;
let redirect: React.ReactNode = null;
if (target.kind === "draft") {
- if (draftSession) {
+ if (
+ draftSession &&
+ hiddenKeys.has(
+ threadKey({ environmentId: draftSession.environmentId, threadId: draftSession.threadId }),
+ )
+ ) {
+ // A draft whose thread is already live and hidden (mid-promotion): never mount it.
+ redirect = <Navigate to="/" replace />;
+ } else if (draftSession) {
view = (
<ChatView
key={target.draftId}
@@ -117,6 +155,18 @@ export function ThreadRouteView({
forceExpandedMobileComposer
/>
);
+ } else if (draftRedirect && hiddenKeys.has(threadKey(draftRedirect))) {
+ // Back to a promoted draft whose thread is now hidden: never mount it.
+ redirect = <Navigate to="/" replace />;
+ } else if (draftRedirect && hidingAnywhere && draftRedirectShell === null) {
+ // While hiding, a thread outside the live list is judged by the server route, unmounted here.
+ redirect = (
+ <Navigate
+ to="/$environmentId/$threadId"
+ params={buildThreadRouteParams(draftRedirect)}
+ replace
+ />
+ );
} else if (draftRedirect) {
// Same slot and key as the server route renders, so the swap keeps this instance.
view = (
@@ -137,6 +187,11 @@ export function ThreadRouteView({
} else {
redirect = <Navigate to="/" replace />;
}
+ } else if (hiddenByTagFilter) {
+ redirect = <Navigate to="/" replace />;
+ } else if (offShellBlocked) {
+ // Before the shell bootstraps, a listed visible thread can still look off-shell.
+ if (bootstrapComplete && unlistedThread !== null) redirect = <Navigate to="/" replace />;
} else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
view = (
<ChatView
diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx
index 250152c4d85..dac76937a9c 100644
--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx
+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx
@@ -27,7 +27,7 @@ import {
buildSidebarProjectSnapshots,
projectGroupsSpanEnvironments,
} from "~/sidebarProjectGrouping";
-import { useProjects, useThreadShells } from "~/state/entities";
+import { useProjects, useVisibleThreadShells } from "~/state/entities";
import {
useEnvironments,
usePrimaryEnvironmentId,
@@ -75,7 +75,7 @@ export function DraftHeroHeadline({
activeProjectTitle,
}: DraftHeroHeadlineProps) {
const projects = useProjects();
- const threads = useThreadShells();
+ const threads = useVisibleThreadShells();
const { environments } = useEnvironments();
const providersByEnvironment = useEnvironmentProviders();
const primaryEnvironmentId = usePrimaryEnvironmentId();
diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
index 9fc48530c59..1330f0057a6 100644
--- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
@@ -25,6 +25,8 @@ vi.mock(import("../../state/entities"), () => ({
? []
: [(state.projection as { thread: unknown }).thread, ...state.relatedShells]) as never,
useProjects: (() => []) as never,
+ useHiddenThreadKeys: (() => new Set()) as never,
+ useAnyEnvironmentHiding: (() => false) as never,
}));
vi.mock(import("../../state/environments"), () => ({
useEnvironment: (() => null) as never,
diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
index 131d77b8aac..c91d5acebc9 100644
--- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
@@ -1,4 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
+import { threadKey } from "@t3tools/client-runtime/state/entities";
import { ThreadDetailsControl } from "./ThreadDetailsControl";
import { ThreadHoverCardPopup } from "../ThreadHoverCard";
import { ThreadDetailsSection } from "./ThreadDetailsSection";
@@ -64,6 +65,8 @@ import {
useQuietThreadShell,
useThreadProjection,
useThreadRelationshipShells,
+ useHiddenThreadKeys,
+ useAnyEnvironmentHiding,
} from "../../state/entities";
import { useEnvironment, useEnvironmentProviders } from "../../state/environments";
import { serverEnvironment } from "../../state/server";
@@ -386,6 +389,8 @@ export function ThreadRelationshipsPanel(props: {
const providersByEnvironment = useEnvironmentProviders();
const settings = useAtomValue(serverEnvironment.settingsValueAtom(props.environmentId));
const relationshipShells = useThreadRelationshipShells(ref);
+ const hiddenKeys = useHiddenThreadKeys();
+ const hidingAnywhere = useAnyEnvironmentHiding();
const allProjects = useProjects();
const archived = useArchivedThreadSnapshots([props.environmentId]);
const archivedShells = archived.snapshots.find(
@@ -464,6 +469,14 @@ export function ThreadRelationshipsPanel(props: {
...(archivedShells ?? []),
];
const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
+ const isHiddenRelation = (threadId: ThreadId) =>
+ hiddenKeys.has(threadKey({ environmentId: props.environmentId, threadId }));
+ // While hiding, an unloaded parent, fork or transfer may be hidden; unloaded subagent
+ // children (idle, left out of the shell) follow this visible thread, so they stay.
+ const isHiddenUnloadedRelation = (row: { threadId: ThreadId; edge: ThreadRelationshipEdge }) =>
+ hidingAnywhere &&
+ graph.nodes.get(row.threadId)?.missing === true &&
+ (row.edge.kind !== "subagent" || isParentThreadRelationship(row.edge, props.threadId));
const currentProject = projects.find((project) => project.id === currentThread?.projectId);
const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
@@ -472,16 +485,19 @@ export function ThreadRelationshipsPanel(props: {
rows: immediateThreadRelationships(graph, props.threadId),
currentThreadId: props.threadId,
mergeTargetThreadId,
- }).map((row) => {
- const agent =
- row.edge.kind === "subagent" && !isParentThreadRelationship(row.edge, props.threadId)
- ? subagentsByThreadId.get(row.threadId)
- : undefined;
- const workflowGroup = agent === undefined ? undefined : workflowGroupsById.get(agent.id);
- return workflowGroup === undefined
- ? row
- : { ...row, edge: { ...row.edge, status: workflowGroup.workflow.status } };
- });
+ })
+ // The graph rebuilds missing parents from lineage, so filter the rows it returns.
+ .filter((row) => !isHiddenRelation(row.threadId) && !isHiddenUnloadedRelation(row))
+ .map((row) => {
+ const agent =
+ row.edge.kind === "subagent" && !isParentThreadRelationship(row.edge, props.threadId)
+ ? subagentsByThreadId.get(row.threadId)
+ : undefined;
+ const workflowGroup = agent === undefined ? undefined : workflowGroupsById.get(agent.id);
+ return workflowGroup === undefined
+ ? row
+ : { ...row, edge: { ...row.edge, status: workflowGroup.workflow.status } };
+ });
const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
@@ -623,7 +639,9 @@ export function ThreadRelationshipsPanel(props: {
const parentTitle =
mergeTargetThreadId === null
? null
- : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
+ : isHiddenRelation(mergeTargetThreadId)
+ ? null
+ : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
const renderRelationshipRow = ({ threadId, edge }: ThreadRelationshipWalkRow) => {
const node = graph.nodes.get(threadId);
diff --git a/apps/web/src/components/chat/useComposerMenuItems.ts b/apps/web/src/components/chat/useComposerMenuItems.ts
index c9870f8318a..5f778ac6cac 100644
--- a/apps/web/src/components/chat/useComposerMenuItems.ts
+++ b/apps/web/src/components/chat/useComposerMenuItems.ts
@@ -28,7 +28,7 @@ import {
getProviderSlashCommandsForSlashMenu,
} from "@t3tools/client-runtime/providerSkills";
import { searchProviderSkills } from "../../providerSkillSearch";
-import { useThreadShells } from "~/state/entities";
+import { useVisibleThreadShells } from "~/state/entities";
import { useEnvironmentIdentities, useEnvironmentMachines } from "~/state/environments";
import { offersLinkedEnvironmentsAtom } from "~/state/peerLinks";
import {
@@ -109,7 +109,7 @@ export function useComposerMenuItems({
const settledPullRequestTextQuery =
pullRequestTextQuery === debouncedPullRequestTextQuery ? pullRequestTextQuery : null;
const isPathTrigger = composerTriggerKind === "path";
- const environmentThreadShells = useThreadShells(isPathTrigger);
+ const environmentThreadShells = useVisibleThreadShells(isPathTrigger);
// Mounts older settled threads matching the mention, which shells may leave out.
useThreadSearch(isPathTrigger ? [environmentId] : [], pathTriggerQuery, { titlesOnly: true });
// The user's machines feed `@` machine matches; the catalog summary is cheap and stable.
diff --git a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx
index 8750a35660a..a5b9ce5a3c2 100644
--- a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx
@@ -1,5 +1,7 @@
import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
+import { useAtomValue } from "@effect/atom-react";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
+import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, PullRequestRef, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { CheckIcon, MessageSquareIcon } from "lucide-react";
@@ -9,8 +11,16 @@ import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
-import { useProjects, useServerConfigs, useThreadShell, useThreadShells } from "~/state/entities";
+import {
+ useAnyEnvironmentHiding,
+ useEnvironmentThreadRefs,
+ useProjects,
+ useServerConfigs,
+ useThreadShell,
+ useVisibleThreadShells,
+} from "~/state/entities";
import { pullRequestEnvironment } from "~/state/pullRequests";
+import { environmentThreadShells } from "~/state/threads";
import { useEnvironmentQuery } from "~/state/query";
import { useThreadSearch } from "~/state/queries";
import { appAtomRegistry } from "~/rpc/atomRegistry";
@@ -58,6 +68,9 @@ function EnabledPullRequestThreadLinks({
const currentThreadRef = thread === null ? null : threadRef;
const linking = usePullRequestLinking(environmentId);
const linkedHere = linking.isLinked(thread, url);
+ const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
+ const hidingAnywhere = useAnyEnvironmentHiding();
+ const loadedThreadRefs = useEnvironmentThreadRefs(environmentId);
const relations = useEnvironmentQuery(
linking.mode === "multiple" && display !== "menu-item"
? pullRequestEnvironment.linkedThreads({
@@ -104,8 +117,13 @@ function EnabledPullRequestThreadLinks({
};
if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
- const linkedThreads =
- linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [];
+ const linkedThreads = visibleLinkedThreads(
+ linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [],
+ environmentId,
+ loadedThreadRefs,
+ hiddenKeys,
+ hidingAnywhere,
+ );
const linkedThreadsLabel =
linkedThreads.length > 0
? `Linked from ${linkedThreads.length} ${linkedThreads.length === 1 ? "thread" : "threads"}`
@@ -188,7 +206,7 @@ function ThreadPicker({
pending: boolean;
onSelect: (threadId: ThreadId) => void;
}) {
- const threads = useThreadShells();
+ const threads = useVisibleThreadShells();
const linking = usePullRequestLinking(environmentId);
const projects = useProjects();
const [query, setQuery] = useState("");
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index 9489402fc1f..d92417ba96d 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -1335,6 +1335,7 @@ function modelReconciliationHarness(
const shells = createEnvironmentThreadShellAtoms({
catalogValueAtom,
snapshotAtom: () => snapshotAtom,
+ hiddenThreadTagsAtom: () => Atom.make(null),
});
const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
onTestFinished(registry.mount(selectedShell));
diff --git a/apps/web/src/lib/archivedThreadsState.ts b/apps/web/src/lib/archivedThreadsState.ts
index a84e072255b..fbd17226cef 100644
--- a/apps/web/src/lib/archivedThreadsState.ts
+++ b/apps/web/src/lib/archivedThreadsState.ts
@@ -7,6 +7,8 @@ import {
import type { EnvironmentId } from "@t3tools/contracts";
import { orchestrationEnvironment } from "../state/orchestration";
+import { serverEnvironment } from "../state/server";
+import { environmentThreadShells } from "../state/threads";
import { appAtomRegistry } from "../rpc/atomRegistry";
function archivedSnapshotAtom(environmentId: EnvironmentId) {
@@ -18,6 +20,10 @@ function archivedSnapshotAtom(environmentId: EnvironmentId) {
const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
getSnapshotAtom: archivedSnapshotAtom,
+ hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
+ hiddenThreadKeysAtom: environmentThreadShells.hiddenThreadKeysAtom,
+ liveThreadRefsAtom: environmentThreadShells.threadRefsAtom,
+ anyEnvironmentHidingAtom: environmentThreadShells.anyEnvironmentHidingAtom,
labelPrefix: "web:archived-thread-snapshots",
});
diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsx
index 75bd468f752..b511be0fa92 100644
--- a/apps/web/src/routes/_chat.index.tsx
+++ b/apps/web/src/routes/_chat.index.tsx
@@ -17,7 +17,7 @@ import {
readProject,
useAllEnvironmentShellsBootstrapped,
useProjects,
- useThreadShells,
+ useVisibleThreadShells,
} from "../state/entities";
import { useEnvironments } from "../state/environments";
@@ -35,7 +35,7 @@ function ChatIndexRouteView() {
function IndexDraftLanding() {
const projects = useProjects();
- const threads = useThreadShells();
+ const threads = useVisibleThreadShells();
const bootstrapped = useAllEnvironmentShellsBootstrapped();
const handleNewThread = useNewThreadHandler();
const router = useRouter();
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index 0f94280768d..19c07367798 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -107,6 +107,23 @@ export function useThreadShells(enabled = true): ReadonlyArray<EnvironmentThread
);
}
+/** Whether any connected environment is hiding tagged threads right now. */
+export function useAnyEnvironmentHiding(): boolean {
+ return useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
+}
+
+/** Keys of threads the tag filter hides from display, by `threadKey`. */
+export function useHiddenThreadKeys(): ReadonlySet<string> {
+ return useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
+}
+
+/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
+export function useVisibleThreadShells(enabled = true): ReadonlyArray<EnvironmentThreadShell> {
+ return useAtomValue(
+ enabled ? environmentThreadShells.visibleThreadShellsAtom : EMPTY_THREAD_SHELLS_ATOM,
+ );
+}
+
export function useAllEnvironmentShellsBootstrapped(): boolean {
return useAtomValue(allEnvironmentShellsBootstrappedAtom);
}
diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts
index 9d7aae58033..6d2ce2a07c9 100644
--- a/apps/web/src/state/threads.ts
+++ b/apps/web/src/state/threads.ts
@@ -18,6 +18,7 @@ import { AsyncResult, Atom } from "effect/reactivity";
import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
+import { serverEnvironment } from "./server";
import { environmentShell } from "./shell";
export const threadFamilies = createThreadFamilyAtoms(
@@ -39,6 +40,7 @@ export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
export const environmentThreadShells = createEnvironmentThreadShellAtoms({
catalogValueAtom: environmentCatalog.catalogValueAtom,
snapshotAtom: threadEnvironment.snapshotAtom,
+ hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
});
export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
diff --git a/packages/client-runtime/src/state/archivedThreads.test.ts b/packages/client-runtime/src/state/archivedThreads.test.ts
index f69a814df7d..acb7b8c5728 100644
--- a/packages/client-runtime/src/state/archivedThreads.test.ts
+++ b/packages/client-runtime/src/state/archivedThreads.test.ts
@@ -1,12 +1,18 @@
-import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
+import {
+ EnvironmentId,
+ type OrchestrationV2ArchivedShellSnapshot,
+ type ScopedThreadRef,
+ ThreadId,
+} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
-import { expect, it } from "vite-plus/test";
+import { describe, expect, it } from "vite-plus/test";
import {
createArchivedThreadSnapshotsAtomFamily,
makeArchivedThreadsEnvironmentKey,
} from "./archivedThreads.ts";
+import { v2Project, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
it("does not expose an archived snapshot failure message", () => {
const environmentId = EnvironmentId.make("env-sensitive");
@@ -17,6 +23,10 @@ it("does not expose an archived snapshot failure message", () => {
Cause.fail(new Error("credential=secret-value")),
),
),
+ hiddenThreadTagsAtom: () => Atom.make(null),
+ hiddenThreadKeysAtom: Atom.make((): ReadonlySet<string> => new Set()),
+ liveThreadRefsAtom: Atom.make((): ReadonlyArray<ScopedThreadRef> => []),
+ anyEnvironmentHidingAtom: Atom.make(false),
labelPrefix: "test:archived-thread-snapshots",
});
const registry = AtomRegistry.make();
@@ -29,3 +39,70 @@ it("does not expose an archived snapshot failure message", () => {
registry.dispose();
});
+
+describe("archived delegated tasks follow their parent on another machine", () => {
+ const parentEnvironmentId = EnvironmentId.make("env-parent");
+ const taskEnvironmentId = EnvironmentId.make("env-task");
+ const parentId = ThreadId.make("thread-parent");
+ const page = (
+ threads: OrchestrationV2ArchivedShellSnapshot["threads"],
+ ): OrchestrationV2ArchivedShellSnapshot => ({
+ schemaVersion: 1,
+ snapshotSequence: 1,
+ projects: [v2Project],
+ threads,
+ });
+ const taskPage = page([
+ {
+ ...v2ThreadShell,
+ id: ThreadId.make("thread-task"),
+ delegatedFrom: { environmentId: parentEnvironmentId, threadId: parentId, title: "p" },
+ },
+ ]);
+ const archivedTaggedParent = page([{ ...v2ThreadShell, id: parentId, tags: ["private"] }]);
+
+ it.each([
+ { name: "archived tagged parent", parentPage: archivedTaggedParent, live: false, tasks: 0 },
+ { name: "live visible parent", parentPage: page([]), live: true, tasks: 1 },
+ { name: "parent page not loaded yet", parentPage: null, live: false, tasks: 0 },
+ { name: "archive scoped to the task's machine", parentPage: undefined, live: false, tasks: 0 },
+ {
+ name: "only a third machine hides tags",
+ parentPage: page([]),
+ live: false,
+ tasks: 0,
+ parentTags: null,
+ },
+ ])("$name", ({ parentPage, live, tasks, parentTags = ["private"] }) => {
+ const snapshotsAtom = createArchivedThreadSnapshotsAtomFamily<Error>({
+ getSnapshotAtom: (environmentId) =>
+ Atom.make(
+ environmentId === taskEnvironmentId
+ ? AsyncResult.success(taskPage)
+ : parentPage === null || parentPage === undefined
+ ? AsyncResult.initial<OrchestrationV2ArchivedShellSnapshot, Error>(true)
+ : AsyncResult.success(parentPage),
+ ),
+ hiddenThreadTagsAtom: (environmentId) =>
+ Atom.make(environmentId === parentEnvironmentId ? parentTags : null),
+ hiddenThreadKeysAtom: Atom.make((): ReadonlySet<string> => new Set()),
+ liveThreadRefsAtom: Atom.make((): ReadonlyArray<ScopedThreadRef> =>
+ live ? [{ environmentId: parentEnvironmentId, threadId: parentId }] : [],
+ ),
+ // The parent's machine hides tags; a scoped archive learns that only from this flag.
+ anyEnvironmentHidingAtom: Atom.make(true),
+ labelPrefix: "test:archived-thread-snapshots",
+ });
+ const registry = AtomRegistry.make();
+ const { snapshots } = registry.get(
+ snapshotsAtom(
+ makeArchivedThreadsEnvironmentKey(
+ parentPage === undefined ? [taskEnvironmentId] : [parentEnvironmentId, taskEnvironmentId],
+ ),
+ ),
+ );
+ const taskSnapshot = snapshots.find((entry) => entry.environmentId === taskEnvironmentId);
+ expect(taskSnapshot?.snapshot.threads.length).toBe(tasks);
+ registry.dispose();
+ });
+});
diff --git a/packages/client-runtime/src/state/archivedThreads.ts b/packages/client-runtime/src/state/archivedThreads.ts
index 3a67dc1c52f..067a913d018 100644
--- a/packages/client-runtime/src/state/archivedThreads.ts
+++ b/packages/client-runtime/src/state/archivedThreads.ts
@@ -1,9 +1,16 @@
-import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
+import {
+ EnvironmentId,
+ type OrchestrationV2ArchivedShellSnapshot,
+ type ScopedThreadRef,
+} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Order from "effect/Order";
import { AsyncResult, Atom } from "effect/reactivity";
+import { threadKey } from "./entities.ts";
+import { hiddenThreadKeys, type TagFilteredEnvironment } from "./threadTagFilter.ts";
+
export interface ArchivedSnapshotEntry {
readonly environmentId: EnvironmentId;
readonly snapshot: OrchestrationV2ArchivedShellSnapshot;
@@ -40,11 +47,21 @@ export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
readonly getSnapshotAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2ArchivedShellSnapshot, E>>;
+ readonly hiddenThreadTagsAtom: (
+ environmentId: EnvironmentId,
+ ) => Atom.Atom<ReadonlyArray<string> | null>;
+ /** Live threads the tag filter hides, so archived children of hidden parents stay hidden. */
+ readonly hiddenThreadKeysAtom: Atom.Atom<ReadonlySet<string>>;
+ /** Live threads, so archived children of loaded, visible parents stay visible. */
+ readonly liveThreadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
+ /** Whether any connected environment hides tags, including ones outside this archive's scope. */
+ readonly anyEnvironmentHidingAtom: Atom.Atom<boolean>;
readonly labelPrefix: string;
}) {
return Atom.family((environmentKey: string) =>
Atom.make((get): ArchivedThreadSnapshotsState => {
const snapshots: ArchivedSnapshotEntry[] = [];
+ const environments: TagFilteredEnvironment[] = [];
let error: string | null = null;
let isLoading = false;
@@ -56,13 +73,41 @@ export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
if (snapshot !== null) {
snapshots.push({ environmentId, snapshot });
}
+ // A page that has not arrived still counts, so its tags apply to children elsewhere.
+ environments.push({
+ environmentId,
+ threads: snapshot?.threads ?? [],
+ hiddenTags: get(options.hiddenThreadTagsAtom(environmentId)),
+ });
if (error === null && result._tag === "Failure") {
error = "Failed to load archived threads.";
}
}
- return { snapshots, error, isLoading };
+ // One pass over every environment's page, so archived tasks follow parents archived elsewhere.
+ // Any connected machine may hide an unloaded parent, so the global flag decides, not the scope.
+ const hidingAnywhere = get(options.anyEnvironmentHidingAtom);
+ const hidden = hiddenThreadKeys(
+ environments,
+ get(options.hiddenThreadKeysAtom),
+ hidingAnywhere ? new Set(get(options.liveThreadRefsAtom).map(threadKey)) : undefined,
+ hidingAnywhere,
+ );
+ if (hidden.size === 0) return { snapshots, error, isLoading };
+ return {
+ snapshots: snapshots.map(({ environmentId, snapshot }) => ({
+ environmentId,
+ snapshot: {
+ ...snapshot,
+ threads: snapshot.threads.filter(
+ (thread) => !hidden.has(threadKey({ environmentId, threadId: thread.id })),
+ ),
+ },
+ })),
+ error,
+ isLoading,
+ };
}).pipe(Atom.withLabel(`${options.labelPrefix}:${environmentKey}`)),
);
}
diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts
index fbba7d1bd9d..d9368ef4058 100644
--- a/packages/client-runtime/src/state/orchestrationV2Projection.ts
+++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts
@@ -293,8 +293,9 @@ export function applyOrchestrationV2ProjectionEvent(
case "thread.provider-switched":
case "thread.guest-share-updated":
return { ...base, thread: event.payload };
- // Visited tracking is read state, not activity: skip the updatedAt bump.
+ // Visited tracking and tags are not activity: skip the updatedAt bump.
case "thread.visited":
+ case "thread.tags-updated":
case "thread.marked-unread":
return { ...projection, thread: event.payload };
case "run.created":
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 06eb14e2d84..04a2d663215 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -1078,6 +1078,26 @@ export function createServerEnvironmentAtoms<R, E>(
Atom.withLabel(`environment-data:server:settings:${environmentId}`),
),
);
+ const hiddenThreadTagsAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make((get) => {
+ const settings = get(settingsValueAtom(environmentId));
+ if (settings?.hideTaggedThreads !== true) return null;
+ // Tags are trimmed on write; trim hand-edited entries so " private" still matches.
+ const tags = settings.hiddenThreadTags.map((tag) => tag.trim()).filter((tag) => tag !== "");
+ return tags.length > 0 ? tags : null;
+ }).pipe(
+ // Trimming makes a new array on every settings push; keep equal lists stable.
+ Atom.withEquality(
+ (a: ReadonlyArray<string> | null, b: ReadonlyArray<string> | null) =>
+ a === b ||
+ (a !== null &&
+ b !== null &&
+ a.length === b.length &&
+ a.every((tag, index) => tag === b[index])),
+ ),
+ Atom.withLabel(`environment-data:server:hidden-thread-tags:${environmentId}`),
+ ),
+ );
const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>
Atom.make((get) => {
const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};
@@ -1201,6 +1221,7 @@ export function createServerEnvironmentAtoms<R, E>(
}),
updateStateAtom,
settingsValueAtom,
+ hiddenThreadTagsAtom,
usageModelFilterAtom,
providersValueAtom,
providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts
index 7eb329320ac..39607575627 100644
--- a/packages/client-runtime/src/state/threadShell.test.ts
+++ b/packages/client-runtime/src/state/threadShell.test.ts
@@ -48,7 +48,11 @@ function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [environment
registry: AtomRegistry.make(),
snapshotAtom,
catalogValueAtom,
- threads: createEnvironmentThreadShellAtoms({ catalogValueAtom, snapshotAtom }),
+ threads: createEnvironmentThreadShellAtoms({
+ catalogValueAtom,
+ snapshotAtom,
+ hiddenThreadTagsAtom: () => Atom.make(null),
+ }),
};
}
diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts
index 60c454469b5..f5ced761c56 100644
--- a/packages/client-runtime/src/state/threadShell.ts
+++ b/packages/client-runtime/src/state/threadShell.ts
@@ -16,6 +16,7 @@ import { Atom } from "effect/reactivity";
import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
+import { hiddenThreadKeys, NO_HIDDEN_THREADS } from "./threadTagFilter.ts";
import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
import {
arrayElementsEqual,
@@ -204,6 +205,10 @@ export function createEnvironmentThreadShellAtoms(input: {
readonly snapshotAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
+ /** Tags whose threads display lists leave out; null while the filter is off. */
+ readonly hiddenThreadTagsAtom: (
+ environmentId: EnvironmentId,
+ ) => Atom.Atom<ReadonlyArray<string> | null>;
}) {
// Point reads and aggregate lists share values without keeping an atom alive
// for every listed thread. Replaced source objects can be collected.
@@ -589,12 +594,67 @@ export function createEnvironmentThreadShellAtoms(input: {
return previousThreadShells;
}).pipe(Atom.withLabel("environment-thread-shell-list"));
+ // Point reads and threadShellsAtom stay complete, so code that asks whether a thread
+ // exists (outboxes, drafts, removals) never mistakes a hidden thread for a missing one.
+ let previousHiddenThreadKeys: ReadonlySet<string> = NO_HIDDEN_THREADS;
+ const hiddenThreadKeysAtom = Atom.make((get) => {
+ const environments = Array.from(
+ enabledEnvironmentIds(get(input.catalogValueAtom)),
+ (environmentId) => ({
+ environmentId,
+ hiddenTags: get(input.hiddenThreadTagsAtom(environmentId)),
+ }),
+ );
+ // Read shells only while some environment hides tags, so streaming ticks cost nothing otherwise.
+ if (!environments.some((environment) => environment.hiddenTags !== null)) {
+ previousHiddenThreadKeys = NO_HIDDEN_THREADS;
+ return NO_HIDDEN_THREADS;
+ }
+ const next = hiddenThreadKeys(
+ environments.map((environment) => ({
+ ...environment,
+ threads: get(environmentThreadsAtom(environment.environmentId)),
+ })),
+ );
+ if (
+ next.size === previousHiddenThreadKeys.size &&
+ [...next].every((key) => previousHiddenThreadKeys.has(key))
+ ) {
+ return previousHiddenThreadKeys;
+ }
+ previousHiddenThreadKeys = next;
+ return next;
+ }).pipe(Atom.withLabel("environment-hidden-thread-keys"));
+
+ const anyEnvironmentHidingAtom = Atom.make((get) =>
+ Array.from(enabledEnvironmentIds(get(input.catalogValueAtom))).some(
+ (environmentId) => get(input.hiddenThreadTagsAtom(environmentId)) !== null,
+ ),
+ ).pipe(Atom.withLabel("environment-any-hiding-thread-tags"));
+
+ /** threadShellsAtom without the threads the tag filter hides, for pickers and palettes. */
+ let previousVisibleThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
+ const visibleThreadShellsAtom = Atom.make((get) => {
+ const threads = get(threadShellsAtom);
+ const hidden = get(hiddenThreadKeysAtom);
+ if (hidden.size === 0) return threads;
+ const next = threads.filter(
+ (thread) =>
+ !hidden.has(threadKey({ environmentId: thread.environmentId, threadId: thread.id })),
+ );
+ if (arrayElementsEqual(previousVisibleThreadShells, next)) return previousVisibleThreadShells;
+ previousVisibleThreadShells = next;
+ return next;
+ }).pipe(Atom.withLabel("environment-visible-thread-shell-list"));
+
// Lists that arrange threads read this, so a running thread's streaming
// ticks reach only what reads its live shell.
let previousQuietThreadShells: ReadonlyArray<EnvironmentThreadShell> = [];
const quietThreadShellsAtom = Atom.make((get) => {
const next: EnvironmentThreadShell[] = [];
+ const hidden = get(hiddenThreadKeysAtom);
for (const ref of get(threadRefsAtom)) {
+ if (hidden.has(threadKey(ref))) continue;
const shell = get(quietThreadShellAtomFamily(threadKey(ref)));
if (shell !== null) next.push(shell);
}
@@ -635,12 +695,14 @@ export function createEnvironmentThreadShellAtoms(input: {
const navigationThreadShellsAtom = Atom.make((get) => {
const next: EnvironmentThreadShell[] = [];
const underParent = get(delegatedUnderParentAtom);
+ const hidden = get(hiddenThreadKeysAtom);
for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));
for (const thread of get(environmentThreadsAtom(environmentId))) {
if (
thread.archivedAt !== null ||
- isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent)
+ isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent) ||
+ hidden.has(threadKey({ environmentId, threadId: thread.id }))
) {
continue;
}
@@ -659,6 +721,9 @@ export function createEnvironmentThreadShellAtoms(input: {
environmentThreadRefsByProjectAtom,
threadRefsAtom,
threadShellsAtom,
+ visibleThreadShellsAtom,
+ hiddenThreadKeysAtom,
+ anyEnvironmentHidingAtom,
quietThreadShellsAtom,
navigationThreadShellsAtom,
delegatedUnderParentAtom,
diff --git a/packages/client-runtime/src/state/threadTagFilter.test.ts b/packages/client-runtime/src/state/threadTagFilter.test.ts
new file mode 100644
index 00000000000..d38e5386d52
--- /dev/null
+++ b/packages/client-runtime/src/state/threadTagFilter.test.ts
@@ -0,0 +1,127 @@
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { threadKey } from "./entities.ts";
+import { hiddenThreadKeys, NO_HIDDEN_THREADS, visibleLinkedThreads } from "./threadTagFilter.ts";
+
+const local = EnvironmentId.make("local");
+const linked = EnvironmentId.make("linked");
+
+const thread = (
+ id: string,
+ tags: Array<string>,
+ parent?: { readonly id: string; readonly relationship: "fork" | "subagent" },
+ delegatedFrom?: { readonly environmentId: EnvironmentId; readonly id: string },
+) => ({
+ id: ThreadId.make(id),
+ tags,
+ lineage: {
+ parentThreadId: parent === undefined ? null : ThreadId.make(parent.id),
+ relationshipToParent: parent?.relationship ?? null,
+ rootThreadId: ThreadId.make(parent?.id ?? id),
+ },
+ ...(delegatedFrom === undefined
+ ? {}
+ : {
+ delegatedFrom: {
+ environmentId: delegatedFrom.environmentId,
+ threadId: ThreadId.make(delegatedFrom.id),
+ title: "parent",
+ },
+ }),
+});
+
+const localThreads = [
+ thread("private", ["private"]),
+ thread("private-subagent", [], { id: "private", relationship: "subagent" }),
+ thread("private-fork", [], { id: "private", relationship: "fork" }),
+ thread("plain", []),
+ thread("plain-private-side-chat", ["private"], { id: "plain", relationship: "subagent" }),
+];
+const linkedThreads = [
+ thread("delegated-from-private", [], undefined, { environmentId: local, id: "private" }),
+ thread("linked-client", ["client"]),
+];
+const hiddenIds = (localTags: Array<string> | null, linkedTags: Array<string> | null) =>
+ [
+ ...hiddenThreadKeys([
+ { environmentId: local, threads: localThreads, hiddenTags: localTags },
+ { environmentId: linked, threads: linkedThreads, hiddenTags: linkedTags },
+ ]),
+ ].toSorted();
+const key = (environmentId: EnvironmentId, id: string) =>
+ threadKey({ environmentId, threadId: ThreadId.make(id) });
+
+describe("hiddenThreadKeys", () => {
+ it("hides nothing while every filter is off", () => {
+ expect(hiddenIds(null, null)).toEqual([]);
+ expect(
+ hiddenThreadKeys([{ environmentId: local, threads: localThreads, hiddenTags: null }]),
+ ).toBe(NO_HIDDEN_THREADS);
+ });
+
+ it("hides a tagged thread with its subagents and linked tasks, but not its forks", () => {
+ expect(hiddenIds(["private"], null)).toEqual(
+ [
+ key(local, "private"),
+ key(local, "private-subagent"),
+ key(linked, "delegated-from-private"),
+ ].toSorted(),
+ );
+ });
+
+ it("judges an archive page against live hidden parents", () => {
+ const archived = hiddenThreadKeys(
+ [{ environmentId: linked, threads: [linkedThreads[0]!], hiddenTags: null }],
+ new Set([key(local, "private")]),
+ );
+ expect([...archived]).toEqual([key(linked, "delegated-from-private")]);
+ });
+
+ it("hides a child whose parent is not loaded while any environment hides tags", () => {
+ const orphan = thread("orphan-task", [], undefined, { environmentId: local, id: "archived" });
+ const keys = (localTags: Array<string> | null, linkedTags: Array<string> | null) => [
+ ...hiddenThreadKeys([
+ { environmentId: local, threads: [], hiddenTags: localTags },
+ { environmentId: linked, threads: [orphan], hiddenTags: linkedTags },
+ ]),
+ ];
+ expect(keys(["private"], null)).toEqual([key(linked, "orphan-task")]);
+ expect(keys(null, ["client"])).toEqual([key(linked, "orphan-task")]);
+ expect(keys(null, null)).toEqual([]);
+ });
+
+ it("applies each environment's own tags", () => {
+ expect(hiddenIds(null, ["client", "private"])).toEqual([key(linked, "linked-client")]);
+ });
+
+ it("judges loaded PR rows by visibility and leaves out unloaded rows while hiding", () => {
+ const hidden = hiddenThreadKeys([
+ { environmentId: local, threads: localThreads, hiddenTags: ["private"] },
+ ]);
+ const rows = [
+ { id: ThreadId.make("private-subagent") },
+ { id: ThreadId.make("plain-private-side-chat") },
+ { id: ThreadId.make("off-shell") },
+ ];
+ const loaded = localThreads.map((entry) => ({ environmentId: local, threadId: entry.id }));
+ const visible = (hiding: boolean) =>
+ visibleLinkedThreads(rows, local, loaded, hidden, hiding).map((row) => row.id);
+ expect(visible(true)).toEqual(["plain-private-side-chat"]);
+ // Another machine hides tags while nothing here is hidden: unloaded rows still stay out.
+ expect(
+ visibleLinkedThreads(rows, local, loaded, NO_HIDDEN_THREADS, true).map((row) => row.id),
+ ).toEqual(["private-subagent", "plain-private-side-chat"]);
+ expect(visibleLinkedThreads(rows, local, loaded, NO_HIDDEN_THREADS, false)).toBe(rows);
+ });
+
+ it("lets a live hidden parent win over the same parent being loaded elsewhere", () => {
+ const parentKey = key(local, "private");
+ const archived = hiddenThreadKeys(
+ [{ environmentId: linked, threads: [linkedThreads[0]!], hiddenTags: null }],
+ new Set([parentKey]),
+ new Set([parentKey]),
+ );
+ expect([...archived]).toEqual([key(linked, "delegated-from-private")]);
+ });
+});
diff --git a/packages/client-runtime/src/state/threadTagFilter.ts b/packages/client-runtime/src/state/threadTagFilter.ts
new file mode 100644
index 00000000000..78e314445bf
--- /dev/null
+++ b/packages/client-runtime/src/state/threadTagFilter.ts
@@ -0,0 +1,125 @@
+import {
+ type EnvironmentId,
+ isListedThreadLineage,
+ type OrchestrationV2ThreadShell,
+ type ScopedThreadRef,
+ type ThreadId,
+} from "@t3tools/contracts";
+
+import { threadKey } from "./entities.ts";
+
+type FilterableThread = Pick<
+ OrchestrationV2ThreadShell,
+ "id" | "lineage" | "tags" | "delegatedFrom"
+>;
+
+export interface TagFilteredEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly threads: ReadonlyArray<FilterableThread>;
+ /** Tags this environment hides, or null while its filter is off. */
+ readonly hiddenTags: ReadonlyArray<string> | null;
+}
+
+export const NO_HIDDEN_THREADS: ReadonlySet<string> = new Set();
+
+/** The thread a subagent, side chat or delegated task takes its visibility from, if any. */
+export function visibilityParentKey(
+ environmentId: EnvironmentId,
+ thread: Pick<FilterableThread, "lineage" | "delegatedFrom">,
+): string | null {
+ const parentId = thread.lineage.parentThreadId;
+ if (!isListedThreadLineage(thread.lineage) && parentId !== null) {
+ return threadKey({ environmentId, threadId: parentId });
+ }
+ return thread.delegatedFrom === undefined ? null : threadKey(thread.delegatedFrom);
+}
+
+/**
+ * Pull request linked-thread rows the tag filter leaves visible. Loaded threads use the
+ * parent-aware hidden set. Rows the shell leaves out carry no lineage, so while any
+ * environment hides tags they stay out.
+ */
+export function visibleLinkedThreads<Row extends { readonly id: ThreadId }>(
+ rows: ReadonlyArray<Row>,
+ environmentId: EnvironmentId,
+ loadedThreadRefs: ReadonlyArray<ScopedThreadRef>,
+ hiddenKeys: ReadonlySet<string>,
+ hidingAnywhere: boolean,
+): ReadonlyArray<Row> {
+ if (!hidingAnywhere && hiddenKeys.size === 0) return rows;
+ const loaded = new Set(loadedThreadRefs.map((ref) => ref.threadId));
+ return rows.filter((row) =>
+ loaded.has(row.id)
+ ? !hiddenKeys.has(threadKey({ environmentId, threadId: row.id }))
+ : !hidingAnywhere,
+ );
+}
+
+function hasHiddenTag(
+ tags: ReadonlyArray<string> | undefined,
+ hiddenTags: ReadonlyArray<string> | null,
+): boolean {
+ return hiddenTags?.some((tag) => tags?.includes(tag) === true) === true;
+}
+
+/**
+ * Keys of threads the tag filter hides. Children (subagents, side chats, delegated tasks) follow
+ * their parent; while any environment hides tags, a child whose parent is not loaded stays hidden.
+ * For a partial list such as an archive page, `alreadyHidden` and `loadedElsewhere` give the
+ * hidden and loaded keys of live threads, and `hidingAnywhere` the global flag.
+ */
+export function hiddenThreadKeys(
+ environments: ReadonlyArray<TagFilteredEnvironment>,
+ alreadyHidden: ReadonlySet<string> = NO_HIDDEN_THREADS,
+ loadedElsewhere: ReadonlySet<string> = NO_HIDDEN_THREADS,
+ hidingAnywhere: boolean = environments.some((environment) => environment.hiddenTags !== null),
+): ReadonlySet<string> {
+ if (alreadyHidden.size === 0 && !hidingAnywhere) return NO_HIDDEN_THREADS;
+ const byKey = new Map<
+ string,
+ { thread: FilterableThread; environment: TagFilteredEnvironment }
+ >();
+ for (const environment of environments) {
+ for (const thread of environment.threads) {
+ byKey.set(threadKey({ environmentId: environment.environmentId, threadId: thread.id }), {
+ thread,
+ environment,
+ });
+ }
+ }
+ const hiddenByKey = new Map<string, boolean>();
+ const isHidden = (key: string): boolean => {
+ if (alreadyHidden.has(key)) return true;
+ const known = hiddenByKey.get(key);
+ if (known !== undefined) return known;
+ const entry = byKey.get(key);
+ if (entry === undefined) return false;
+ const { thread, environment } = entry;
+ const parentKey = visibilityParentKey(environment.environmentId, thread);
+ const followsParent =
+ parentKey !== null && (byKey.has(parentKey) || alreadyHidden.has(parentKey));
+ if (parentKey !== null && !followsParent && loadedElsewhere.has(parentKey)) {
+ hiddenByKey.set(key, false);
+ return false;
+ }
+ if (parentKey !== null && !followsParent && hidingAnywhere) {
+ hiddenByKey.set(key, true);
+ return true;
+ }
+ if (!followsParent) {
+ const hidden = hasHiddenTag(thread.tags, environment.hiddenTags);
+ hiddenByKey.set(key, hidden);
+ return hidden;
+ }
+ // Seed before following the parent so a malformed cycle ends visible.
+ hiddenByKey.set(key, false);
+ const hidden = isHidden(parentKey);
+ hiddenByKey.set(key, hidden);
+ return hidden;
+ };
+ const hidden = new Set<string>();
+ for (const key of byKey.keys()) {
+ if (isHidden(key)) hidden.add(key);
+ }
+ return hidden.size === 0 ? NO_HIDDEN_THREADS : hidden;
+}
diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts
index 5c6622b5ad9..970ec6cd8d8 100644
--- a/packages/client-runtime/src/state/threads.ts
+++ b/packages/client-runtime/src/state/threads.ts
@@ -1113,3 +1113,4 @@ export * from "./threadFamilies.ts";
export * from "./olderSettledThreads.ts";
export * from "./threadShell.ts";
export * from "./threadState.ts";
+export * from "./threadTagFilter.ts";
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index f2d88e96470..896733c5197 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -46,6 +46,7 @@ export * from "./peerLink.ts";
export * from "./threadMetadataMcp.ts";
export * from "./threadPullRequest.ts";
export * from "./threadSearch.ts";
+export * from "./threadTags.ts";
export * from "./threadTitle.ts";
export * from "./t3ProjectFile.ts";
export * from "./editor.ts";
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 837721aa7f6..abf2b309858 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -44,6 +44,7 @@ import {
import { AuthMcpClientAccess } from "./auth.ts";
import { ChatAttachment } from "./chatAttachment.ts";
import { ThreadGuestShare } from "./guestShare.ts";
+import { StoredThreadTags, ThreadTag } from "./threadTags.ts";
import {
OrchestrationSearchThreadsInput,
OrchestrationSearchThreadsResult,
@@ -487,6 +488,8 @@ export const OrchestrationV2AppThread = Schema.Struct({
autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
+ /** Absent on threads written before tags existed; read as empty. */
+ tags: Schema.optional(StoredThreadTags),
lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
@@ -1877,6 +1880,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([
"thread.unpinned",
"thread.pin-reordered",
"thread.active-reordered",
+ "thread.tags-updated",
"thread.visited",
"thread.marked-unread",
"thread.metadata-updated",
@@ -2129,6 +2133,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
+ /** Absent on threads written before tags existed; read as empty. */
+ tags: Schema.optional(StoredThreadTags),
lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
opens: Schema.optional(LenientThreadOpens),
titleRegeneration: Schema.optional(
@@ -2758,6 +2764,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([
"thread.unpinned",
"thread.pin-reordered",
"thread.active-reordered",
+ "thread.tags-updated",
"thread.visited",
"thread.marked-unread",
"thread.pull-request-synced",
@@ -2999,6 +3006,13 @@ export const OrchestrationV2Command = Schema.Union([
commandId: CommandId,
threadId: ThreadId,
}),
+ Schema.Struct({
+ type: Schema.Literal("thread.tag.set"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ tag: ThreadTag,
+ tagged: Schema.Boolean,
+ }),
Schema.Struct({
type: Schema.Literal("thread.pin.reorder"),
commandId: CommandId,
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 4b593d4d335..4ff7d2c9618 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -139,6 +139,15 @@ describe("ServerSettings usage price overrides", () => {
});
});
+it("drops a hand-edited non-string hidden tag and keeps the rest of the settings", () => {
+ const settings = decodeServerSettings({
+ hiddenThreadTags: ["private", 123],
+ hideTaggedThreads: true,
+ });
+ expect(settings.hiddenThreadTags).toEqual(["private"]);
+ expect(settings.hideTaggedThreads).toBe(true);
+});
+
describe("ServerSettings secret providers", () => {
const onePassword = (account: string) => ({
kind: "one_password",
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index b1848090d9d..f291cec115f 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -1255,6 +1255,18 @@ export const ServerSettings = Schema.Struct({
snoozePresets: SnoozePresetSettings.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNOOZE_PRESETS)),
),
+ /** Clients hide threads with these tags while `hideTaggedThreads` is on. Bad entries drop alone, so a hand edit cannot reset settings. */
+ hiddenThreadTags: Schema.Array(Schema.Unknown).pipe(
+ Schema.decodeTo(
+ Schema.Array(Schema.String),
+ SchemaTransformation.transform<ReadonlyArray<string>, ReadonlyArray<unknown>>({
+ decode: (values) => values.filter((value) => typeof value === "string"),
+ encode: (values) => values,
+ }),
+ ),
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
+ hideTaggedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
/** Beta: guest links for this machine's threads. Off refuses new links and pauses existing ones. */
guestSharingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
/**
@@ -1639,6 +1651,8 @@ export const ServerSettingsPatch = Schema.Struct({
autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),
snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean),
snoozePresets: Schema.optionalKey(SnoozePresetSettings),
+ hiddenThreadTags: Schema.optionalKey(Schema.Array(Schema.String)),
+ hideTaggedThreads: Schema.optionalKey(Schema.Boolean),
guestSharingEnabled: Schema.optionalKey(Schema.Boolean),
linkedEnvironmentsEnabled: Schema.optionalKey(Schema.Boolean),
backgroundActivity: Schema.optionalKey(
diff --git a/packages/contracts/src/threadTags.ts b/packages/contracts/src/threadTags.ts
new file mode 100644
index 00000000000..ec6d8285c1a
--- /dev/null
+++ b/packages/contracts/src/threadTags.ts
@@ -0,0 +1,18 @@
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+import { TrimmedNonEmptyString } from "./baseSchemas.ts";
+
+/** Tags match by exact spelling and case after trimming. */
+export const ThreadTag = TrimmedNonEmptyString.check(
+ Schema.isMaxLength(64),
+ Schema.makeFilter((value) =>
+ /[\p{Cc}]/u.test(value) ? "A thread tag must be a single line of text." : true,
+ ),
+);
+export type ThreadTag = typeof ThreadTag.Type;
+
+/** Tags read back from storage or a peer. Lenient so a later tag rule never fails a whole thread. */
+export const StoredThreadTags = Schema.Array(Schema.String).pipe(
+ Schema.catchDecoding(() => Effect.succeedSome([])),
+);