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, 02:00 UTC
fix(clients): unloaded thread links show their title and project icon (#32830)
Yash Singh committed
Nov 8, 2026 at 13:41 UTC
23e3465ec6a509db01aaf364c7ca6675525aac25
21 files changed
+470
-40
apps/mobile/src/state/entities.test.ts
new
+72
@@ -0,0 +1,72 @@
1
+import { EnvironmentId, ProjectId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2
+import * as Cause from "effect/Cause";
3
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
4
+import { expect, it, vi } from "vite-plus/test";
5
+
6
+const state = vi.hoisted(() => ({ reply: null as unknown }));
7
+vi.mock(import("./threads"), async () => {
8
+ const { Atom } = await import("effect/reactivity");
9
+ return {
10
+ environmentThreadDetails: {} as never,
11
+ environmentThreadShells: {
12
+ threadShellAtom: () => Atom.make(null),
13
+ threadRefsAtom: Atom.make([{ environmentId: "remote", threadId: "older-thread" }]),
14
+ } as never,
15
+ };
16
+});
17
+vi.mock(import("./orchestration"), () => ({
18
+ orchestrationEnvironment: { threadLinkMetadata: () => state.reply } as never,
19
+}));
20
+vi.mock(import("./atom-registry"), () => ({ appAtomRegistry: {} as never }));
21
+vi.mock(import("./projects"), () => ({ environmentProjects: {} as never }));
22
+vi.mock(import("./server"), () => ({
23
+ environmentServerConfigsAtom: {} as never,
24
+ serverEnvironment: {} as never,
25
+}));
26
+vi.mock(import("./assets"), () => ({ projectFaviconUrlAtom: (() => null) as never }));
27
+vi.mock(import("../native/ProjectChipIconImages"), () => ({
28
+ projectGlyphImageAtom: (() => null) as never,
29
+ projectGlyphKey: (() => "") as never,
30
+}));
31
+
32
+import { resolveThreadLink } from "./entities";
33
+
34
+function setup() {
35
+ const reply = Atom.make<
36
+ AsyncResult.AsyncResult<Record<string, { title: string; projectId: ProjectId | null }>, string>
37
+ >(AsyncResult.initial());
38
+ state.reply = reply;
39
+ return { registry: AtomRegistry.make(), reply };
40
+}
41
+
42
+it("uses confirmed matches instead of provisional titles when resolving legacy links", () => {
43
+ const { registry, reply } = setup();
44
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
45
+ const local: ScopedThreadRef = {
46
+ environmentId: EnvironmentId.make("local"),
47
+ threadId: ThreadId.make("older-thread"),
48
+ };
49
+ const remote: ScopedThreadRef = { ...local, environmentId: EnvironmentId.make("remote") };
50
+ const link = { environmentId: null, threadId: local.threadId };
51
+ const resolve = () => resolveThreadLink(registry.get.bind(registry), link, local.environmentId);
52
+ const release = registry.mount(reply);
53
+ try {
54
+ expect(resolve()).toEqual(remote);
55
+ registry.set(reply, AsyncResult.failure(Cause.fail("offline")));
56
+ expect(resolve()).toEqual(remote);
57
+ expect(resolveThreadLink(registry.get.bind(registry), local, remote.environmentId)).toEqual(
58
+ local,
59
+ );
60
+ registry.set(
61
+ reply,
62
+ AsyncResult.success({
63
+ [local.threadId]: { title: "Thread", projectId: ProjectId.make("project") },
64
+ }),
65
+ );
66
+ expect(resolve()).toEqual(local);
67
+ registry.set(reply, AsyncResult.success({}));
68
+ expect(resolve()).toEqual(remote);
69
+ } finally {
70
+ release();
71
+ }
72
+});
apps/mobile/src/state/entities.ts
+39
-10
@@ -32,6 +32,7 @@ import { threadChipTargets } from "../lib/enrichedLinkPresentation";
32
import { resolveProjectChipIcon } from "../lib/projectIcon";
33
import { projectGlyphImageAtom, projectGlyphKey } from "../native/ProjectChipIconImages";
34
import { projectFaviconUrlAtom } from "./assets";
35
+import { orchestrationEnvironment } from "./orchestration";
36
import { environmentProjects } from "./projects";
37
import { environmentServerConfigsAtom, serverEnvironment } from "./server";
38
import { environmentThreadDetails, environmentThreadShells } from "./threads";
@@ -55,12 +56,22 @@ const EMPTY_THREAD_LINK_TITLES_ATOM = Atom.make<ReadonlyMap<string, string>>(new
56
const decodeThreadKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, ThreadId]));
57
const threadKey = (ref: ScopedThreadRef) => JSON.stringify([ref.environmentId, ref.threadId]);
58
58
-// Null when this client doesn't know the thread. Keyed, so a link never walks an environment's threads.
59
+// Omitted and archived targets need only a metadata lookup, not their conversation history.
60
const threadTitleAtom = Atom.family((key: string) => {
61
const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
61
- return Atom.make((get) => get(environmentThreadShells.threadShellAtom(ref))?.title ?? null).pipe(
62
- Atom.withLabel(`mobile-thread-title:${key}`),
63
- );
62
+ return Atom.make((get) => {
63
+ const shell = get(environmentThreadShells.threadShellAtom(ref));
64
+ if (shell !== null) return shell.title;
65
+ const titles = get(
66
+ orchestrationEnvironment.threadLinkMetadata({
67
+ environmentId: ref.environmentId,
68
+ input: { threadIds: [ref.threadId] },
69
+ }),
70
+ );
71
+ return AsyncResult.isSuccess(titles)
72
+ ? (titles.value[ref.threadId]?.title ?? (titles.waiting ? "Thread" : null))
73
+ : "Thread";
74
+ }).pipe(Atom.withLabel(`mobile-thread-title:${key}`));
75
});
76
77
const decodeThreadKeys = Schema.decodeUnknownSync(Schema.Array(Schema.String));
@@ -92,11 +103,22 @@ const threadProjectChipIconAtom = Atom.family((key: string) => {
103
const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
104
return Atom.make((get): string | null => {
105
const shell = get(environmentThreadShells.threadShellAtom(ref));
95
- const project = shell
106
+ const metadata =
107
+ shell ??
108
+ AsyncResult.getOrElse(
109
+ get(
110
+ orchestrationEnvironment.threadLinkMetadata({
111
+ environmentId: ref.environmentId,
112
+ input: { threadIds: [ref.threadId] },
113
+ }),
114
+ ),
115
+ () => null,
116
+ )?.[ref.threadId];
117
+ const project = metadata?.projectId
118
? get(
119
environmentProjects.projectAtom({
120
environmentId: ref.environmentId,
99
- projectId: shell.projectId,
121
+ projectId: metadata.projectId,
122
}),
123
)
124
: null;
@@ -222,13 +244,20 @@ export function resolveThreadLink(
244
link: ThreadLink,
245
messageEnvironmentId: EnvironmentId,
246
): ScopedThreadRef | null {
225
- const known = threadLinkCandidates(link, messageEnvironmentId).find(
226
- (ref) => read(threadTitleAtom(threadKey(ref))) !== null,
227
- );
247
+ const known = threadLinkCandidates(link, messageEnvironmentId).find((ref) => {
248
+ if (read(environmentThreadShells.threadShellAtom(ref)) !== null) return true;
249
+ const metadata = read(
250
+ orchestrationEnvironment.threadLinkMetadata({
251
+ environmentId: ref.environmentId,
252
+ input: { threadIds: [ref.threadId] },
253
+ }),
254
+ );
255
+ return AsyncResult.getOrElse(metadata, () => null)?.[ref.threadId] !== undefined;
256
+ });
257
if (known) return known;
258
return link.environmentId === null
259
? guessThreadLinkRef(link, read(environmentThreadShells.threadRefsAtom))
231
- : null;
260
+ : scopeThreadRef(link.environmentId, link.threadId);
261
}
262
263
export function useThreadChipIcons(
apps/mobile/src/state/orchestration.ts
+2
@@ -1,8 +1,10 @@
1
import { createOrchestrationEnvironmentAtoms } from "@t3tools/client-runtime/state/orchestration";
2
3
import { connectionAtomRuntime } from "../connection/runtime";
4
+import { environmentShell } from "./shell";
5
import { recordReviewTurnDiffAnswer } from "./reviewTurnDiffs";
6
7
export const orchestrationEnvironment = createOrchestrationEnvironmentAtoms(connectionAtomRuntime, {
8
+ shellState: environmentShell.stateValueAtom,
9
onCheckpointDiffAnswer: recordReviewTurnDiffAnswer,
10
});
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -52,6 +52,7 @@ export const RPC_REQUIRED_SCOPES = {
52
[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,
53
[ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: AuthOrchestrationReadScope,
54
[ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: AuthOrchestrationReadScope,
55
+ [ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata]: AuthOrchestrationReadScope,
56
[ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: AuthOrchestrationReadScope,
57
[ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads]: AuthOrchestrationReadScope,
58
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -25,6 +25,7 @@ const RPC_AGGREGATES = {
25
[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: "orchestration",
26
[ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: "orchestration",
27
[ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: "orchestration",
28
+ [ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata]: "orchestration",
29
[ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: "orchestration",
30
[ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads]: "orchestration",
31
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: "orchestrationV2",
apps/server/src/orchestration-v2/Orchestrator.ts
+9
@@ -1,4 +1,5 @@
1
import type {
2
+ OrchestrationV2ThreadLinkMetadata,
3
GuestShareId,
4
OrchestrationV2SearchThreadInput,
5
OrchestrationV2SearchThreadResult,
@@ -479,6 +480,9 @@ export interface OrchestratorV2Shape {
480
shareId: GuestShareId,
481
) => Effect.Effect<ThreadId | null, OrchestratorV2Error>;
482
/** Titles of the given threads that exist, archived ones included. */
483
+ readonly getThreadLinkMetadata: (
484
+ threadIds: ReadonlyArray<ThreadId>,
485
+ ) => Effect.Effect<Record<ThreadId, OrchestrationV2ThreadLinkMetadata>, OrchestratorV2Error>;
486
readonly getThreadTitles: (
487
threadIds: ReadonlyArray<ThreadId>,
488
) => Effect.Effect<Record<ThreadId, string>, OrchestratorV2Error>;
@@ -14540,6 +14544,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14544
.findGuestShareThreadId(shareId)
14545
.pipe(Effect.mapError(shellProjectionError));
14546
}),
14547
+ getThreadLinkMetadata: Effect.fn("OrchestratorV2.getThreadLinkMetadata")(function (threadIds) {
14548
+ return projectionStore
14549
+ .getThreadLinkMetadata(threadIds)
14550
+ .pipe(Effect.mapError(shellProjectionError));
14551
+ }),
14552
getThreadTitles: Effect.fn("OrchestratorV2.getThreadTitles")(function (threadIds) {
14553
return projectionStore.getThreadTitles(threadIds).pipe(Effect.mapError(shellProjectionError));
14554
}),
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+18
@@ -1327,6 +1327,24 @@ const threadWorktreePathsIncludeArchivedOnRequest = Effect.gen(function* () {
1327
{ threadId: ThreadId.make("thread:active"), worktreePath: "/worktrees/active" },
1328
{ threadId: ThreadId.make("thread:archived"), worktreePath: "/worktrees/archived" },
1329
]);
1330
+ assert.deepEqual(
1331
+ yield* store.getThreadLinkMetadata([
1332
+ deleted.id,
1333
+ ThreadId.make("thread:active"),
1334
+ ThreadId.make("thread:archived"),
1335
+ ThreadId.make("unknown"),
1336
+ ]),
1337
+ {
1338
+ [ThreadId.make("thread:active")]: {
1339
+ title: "Title for thread:active",
1340
+ projectId: ProjectId.make("project:worktree-paths"),
1341
+ },
1342
+ [ThreadId.make("thread:archived")]: {
1343
+ title: "Title for thread:archived",
1344
+ projectId: ProjectId.make("project:worktree-paths"),
1345
+ },
1346
+ },
1347
+ );
1348
assert.deepEqual(
1349
yield* store.getThreadTitles([
1350
deleted.id,
apps/server/src/orchestration-v2/ProjectionStore.ts
+23
@@ -6,6 +6,7 @@ import * as Stream from "effect/Stream";
6
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
7
import { makeThreadFind } from "./ThreadFind.ts";
8
import type {
9
+ OrchestrationV2ThreadLinkMetadata,
10
OrchestrationV2SearchThreadInput,
11
OrchestrationV2SearchThreadResult,
12
OrchestrationV2ThreadHistoryPage,
@@ -562,6 +563,9 @@ export interface ProjectionStoreV2Shape {
563
threadId?: ThreadId,
564
) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequests>, ProjectionStoreV2Error>;
565
/** Titles of the given threads that exist, archived ones included. */
566
+ readonly getThreadLinkMetadata: (
567
+ threadIds: ReadonlyArray<ThreadId>,
568
+ ) => Effect.Effect<Record<ThreadId, OrchestrationV2ThreadLinkMetadata>, ProjectionStoreV2Error>;
569
readonly getThreadTitles: (
570
threadIds: ReadonlyArray<ThreadId>,
571
) => Effect.Effect<Record<ThreadId, string>, ProjectionStoreV2Error>;
@@ -7306,6 +7310,24 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7310
}));
7311
}, Effect.mapError(shellSnapshotReadError));
7312
7313
+ const getThreadLinkMetadata = Effect.fn("ProjectionStore.getThreadLinkMetadata")(function* (
7314
+ threadIds: ReadonlyArray<ThreadId>,
7315
+ ) {
7316
+ if (threadIds.length === 0) return {};
7317
+ const rows = yield* sql<{
7318
+ readonly thread_id: ThreadId;
7319
+ readonly title: string;
7320
+ readonly project_id: ProjectId;
7321
+ }>`
7322
+ SELECT thread_id, title, project_id
7323
+ FROM orchestration_v2_projection_threads
7324
+ WHERE deleted_at IS NULL AND thread_id IN ${sql.in(threadIds)}
7325
+ `;
7326
+ return Object.fromEntries(
7327
+ rows.map((row) => [row.thread_id, { title: row.title, projectId: row.project_id }]),
7328
+ );
7329
+ }, Effect.mapError(shellSnapshotReadError));
7330
+
7331
const getThreadTitles = Effect.fn("ProjectionStore.getThreadTitles")(function* (
7332
threadIds: ReadonlyArray<ThreadId>,
7333
) {
@@ -7485,6 +7507,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7507
getSettlementCandidates: readOnReader(getSettlementCandidates),
7508
getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests),
7509
getThreadTitles: readOnReader(getThreadTitles),
7510
+ getThreadLinkMetadata: readOnReader(getThreadLinkMetadata),
7511
getThreadWorktreePaths: readOnReader(getThreadWorktreePaths),
7512
getOpenRemoteDelegatedTasks: getOpenRemoteDelegatedTasks.pipe(NodeSqliteClient.readOnly),
7513
getThreadProjection: readOnReader(getThreadProjection),
apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+1
@@ -221,6 +221,7 @@ it.effect(
221
readShellSnapshot: () => Effect.die("unused readShellSnapshot"),
222
getThreadShell: () => Effect.die("unused getThreadShell"),
223
getThreadTitles: () => Effect.die("unused getThreadTitles"),
224
+ getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"),
225
findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),
226
getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),
227
getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
apps/server/src/orchestration-v2/ThreadManagementService.ts
+2
@@ -423,6 +423,7 @@ export interface ThreadManagementServiceShape {
423
>;
424
readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"];
425
readonly listAppOwnedChildThreadIds: Orchestrator.OrchestratorV2["Service"]["listAppOwnedChildThreadIds"];
426
+ readonly getThreadLinkMetadata: Orchestrator.OrchestratorV2["Service"]["getThreadLinkMetadata"];
427
readonly getThreadTitles: Orchestrator.OrchestratorV2["Service"]["getThreadTitles"];
428
/** Omit `projectId` to list every project's threads. Side chats are never listed. */
429
readonly listProjectThreads: (input: {
@@ -1609,6 +1610,7 @@ const make = Effect.gen(function* () {
1610
},
1611
),
1612
getThreadTitles: orchestrator.getThreadTitles,
1613
+ getThreadLinkMetadata: orchestrator.getThreadLinkMetadata,
1614
listProjectThreads,
1615
sendToThread,
1616
assertProviderInstanceEnabled,
apps/server/src/relay/AgentAwarenessRelay.test.ts
+1
@@ -204,6 +204,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
204
listOlderSettledThreads: unused,
205
readShellSnapshot: unused,
206
getThreadTitles: unused,
207
+ getThreadLinkMetadata: unused,
208
ensureLegacyTranscript: unused,
209
dispatch: unused,
210
searchThread: () => Effect.die("unused"),
apps/server/src/ws.ts
+11
@@ -1965,6 +1965,7 @@ export const layerWsRpc = (
1965
: { managedPolicy: serverSettings.managedPolicy }),
1966
shellResumeCompletionMarker: true,
1967
shellThreadFamilies: true,
1968
+ threadLinkMetadata: true,
1969
shellOlderSettled: true,
1970
threadResumeCompletionMarker: true,
1971
threadSnapshotPagination: true,
@@ -2158,6 +2159,16 @@ export const layerWsRpc = (
2159
getOrchestrationV2ArchivedShellSnapshot,
2160
[ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input) =>
2161
readOmittableShellRows({ familyOf: input.threadId }, "Failed to load the thread family"),
2162
+ [ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata]: (input) =>
2163
+ threadManagement.getThreadLinkMetadata(input.threadIds).pipe(
2164
+ Effect.mapError(
2165
+ (cause) =>
2166
+ new OrchestrationV2GetShellSnapshotError({
2167
+ message: "Failed to load thread link metadata",
2168
+ cause,
2169
+ }),
2170
+ ),
2171
+ ),
2172
[ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: (input) =>
2173
threadManagement.getThreadTitles(input.threadIds).pipe(
2174
Effect.mapError(
apps/web/src/components/ThreadContextChip.tsx
+17
-6
@@ -1,22 +1,35 @@
1
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2
-import type { ThreadContextRecord } from "@t3tools/contracts";
2
+import type { ThreadContextRecord, ProjectId } from "@t3tools/contracts";
3
import { Link } from "@tanstack/react-router";
4
import { MessagesSquareIcon } from "lucide-react";
5
6
import { useProject, useThreadShell } from "~/state/entities";
7
+import { orchestrationEnvironment } from "~/state/orchestration";
8
+import { useEnvironmentQuery } from "~/state/query";
9
import { ContextChip, ContextChipLabel } from "./ContextChip";
10
import { ProjectFavicon } from "./ProjectFavicon";
11
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
12
13
export function ThreadContextChip(props: {
14
record: Pick<ThreadContextRecord, "environmentId" | "threadId" | "title">;
15
+ projectId?: ProjectId | null;
16
copyMarkdown?: string;
17
unreadable?: boolean;
18
}) {
19
const { environmentId, threadId } = props.record;
20
const shell = useThreadShell({ environmentId, threadId });
18
- const project = useProject(shell ? scopeProjectRef(environmentId, shell.projectId) : null);
19
- const title = shell?.title?.trim() || props.record.title;
21
+ const lookup = useEnvironmentQuery(
22
+ shell === null && props.projectId === undefined
23
+ ? orchestrationEnvironment.threadLinkMetadata({
24
+ environmentId,
25
+ input: { threadIds: [threadId] },
26
+ })
27
+ : null,
28
+ );
29
+ const metadata = lookup.data?.[threadId];
30
+ const projectId = shell?.projectId ?? props.projectId ?? metadata?.projectId;
31
+ const project = useProject(projectId ? scopeProjectRef(environmentId, projectId) : null);
32
+ const title = shell?.title?.trim() || metadata?.title.trim() || props.record.title;
33
return (
34
<Tooltip>
35
<TooltipTrigger
@@ -41,9 +54,7 @@ export function ThreadContextChip(props: {
54
<TooltipPopup side="top">
55
{props.unreadable
56
? "On another machine, so this machine's agent can't read it. Remove it or switch back to send."
44
- : shell
45
- ? "Open thread"
46
- : "Thread no longer available"}
57
+ : "Open thread"}
58
</TooltipPopup>
59
</Tooltip>
60
);
apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx
new
+134
@@ -0,0 +1,134 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
3
+import * as Cause from "effect/Cause";
4
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
5
+import { expect, it, vi } from "vite-plus/test";
6
+
7
+import { act, render } from "../../../test/render";
8
+import { MarkdownThreadLink } from "./MarkdownThreadLink";
9
+
10
+const state = vi.hoisted(() => ({
11
+ reply: null as unknown,
12
+ remote: null as unknown,
13
+}));
14
+vi.mock(import("../../state/entities"), () => ({
15
+ useThreadShell: ((ref: { environmentId: string } | null) =>
16
+ ref?.environmentId === "remote" ? state.remote : null) as never,
17
+ useThreadRefs: (enabled = true) =>
18
+ enabled
19
+ ? [{ environmentId: EnvironmentId.make("remote"), threadId: ThreadId.make("older-thread") }]
20
+ : [],
21
+ useProject: (ref: { projectId: string } | null) =>
22
+ ref?.projectId === "essay-project" ? ({ title: "Essays" } as never) : null,
23
+}));
24
+vi.mock(import("../ProjectFavicon"), () => ({
25
+ ProjectFavicon: () => (
26
+ <span role="img" aria-label="Essays project icon">
27
+ P
28
+ </span>
29
+ ),
30
+}));
31
+vi.mock(import("../contextChipParts"), () => ({
32
+ UnresolvedChip: ({ label }: { label: string }) => <span>{label}</span>,
33
+}));
34
+vi.mock(import("../../state/orchestration"), () => ({
35
+ orchestrationEnvironment: { threadLinkMetadata: () => state.reply } as never,
36
+}));
37
+
38
+function setup() {
39
+ const reply = Atom.make<
40
+ AsyncResult.AsyncResult<Record<string, { title: string; projectId: ProjectId | null }>, string>
41
+ >(AsyncResult.initial());
42
+ state.reply = reply;
43
+ state.remote = {
44
+ environmentId: EnvironmentId.make("remote"),
45
+ id: ThreadId.make("older-thread"),
46
+ title: "Remote thread",
47
+ projectId: ProjectId.make("essay-project"),
48
+ };
49
+ return { reply, registry: AtomRegistry.make() };
50
+}
51
+
52
+it.each([
53
+ { legacy: false, encoded: false },
54
+ { legacy: true, encoded: false },
55
+ { legacy: false, encoded: true },
56
+])(
57
+ "resolves an unloaded thread with its icon and the correct destination, %j",
58
+ async ({ legacy, encoded }) => {
59
+ const { reply, registry } = setup();
60
+ using _registry = { [Symbol.dispose]: () => registry.dispose() };
61
+ const environmentId = EnvironmentId.make("environment");
62
+ const threadId = ThreadId.make(encoded ? "older%2Dthread" : "older-thread");
63
+ await using screen = await render(
64
+ <RegistryContext value={registry}>
65
+ <MarkdownThreadLink
66
+ environmentId={environmentId}
67
+ link={{ environmentId: legacy ? null : environmentId, threadId }}
68
+ label={null}
69
+ />
70
+ </RegistryContext>,
71
+ );
72
+ await expect
73
+ .element(screen.getByRole("link", { name: "Thread, Thread", exact: true }))
74
+ .toBeVisible();
75
+ await act(() => registry.set(reply, AsyncResult.failure(Cause.fail("offline"))));
76
+ await expect
77
+ .element(screen.getByRole("link", { name: "Thread, Thread", exact: true }))
78
+ .toBeVisible();
79
+ await act(() =>
80
+ registry.set(
81
+ reply,
82
+ AsyncResult.success({
83
+ [threadId]: { title: "Older essay", projectId: ProjectId.make("essay-project") },
84
+ ...(encoded
85
+ ? {
86
+ "older-thread": {
87
+ title: "Decoded essay",
88
+ projectId: ProjectId.make("essay-project"),
89
+ },
90
+ }
91
+ : {}),
92
+ }),
93
+ ),
94
+ );
95
+ const link = screen.getByRole("link", { name: "Thread, Older essay" });
96
+ await expect.element(link).toBeVisible();
97
+ await expect.element(screen.getByRole("img", { name: "Essays project icon" })).toBeVisible();
98
+ await link.click();
99
+ await vi.waitFor(() =>
100
+ expect(screen.router?.state.location.pathname).toBe(
101
+ `/environment/${encodeURIComponent(threadId)}`,
102
+ ),
103
+ );
104
+ if (encoded) {
105
+ await act(() =>
106
+ registry.set(
107
+ reply,
108
+ AsyncResult.success({
109
+ "older-thread": { title: "Decoded essay", projectId: ProjectId.make("essay-project") },
110
+ }),
111
+ ),
112
+ );
113
+ const decoded = screen.getByRole("link", { name: "Thread, Decoded essay" });
114
+ await expect.element(decoded).toBeVisible();
115
+ await decoded.click();
116
+ await vi.waitFor(() =>
117
+ expect(screen.router?.state.location.pathname).toBe("/environment/older-thread"),
118
+ );
119
+ }
120
+ await act(() => registry.set(reply, AsyncResult.success({})));
121
+ if (legacy) {
122
+ const remote = screen.getByRole("link", { name: "Thread, Remote thread" });
123
+ await expect.element(remote).toBeVisible();
124
+ await remote.click();
125
+ await vi.waitFor(() =>
126
+ expect(screen.router?.state.location.pathname).toBe("/remote/older-thread"),
127
+ );
128
+ } else {
129
+ await expect
130
+ .element(screen.getByText("Thread no longer available", { exact: true }))
131
+ .toBeVisible();
132
+ }
133
+ },
134
+);
apps/web/src/components/chat/MarkdownThreadLink.tsx
+35
-14
@@ -1,15 +1,16 @@
1
-import { scopeThreadRef } from "@t3tools/client-runtime/environment";
1
import type { EnvironmentId } from "@t3tools/contracts";
2
import {
3
formatHostedThreadLink,
4
guessThreadLinkRef,
6
- percentDecodedThreadLinkId,
5
+ threadLinkCandidates,
6
type ThreadLink,
7
unknownThreadLinkLabel,
8
} from "@t3tools/shared/threadLinks";
9
10
import { configuredHostedAppUrl } from "../../hostedPairing";
11
import { useThreadRefs, useThreadShell } from "../../state/entities";
12
+import { orchestrationEnvironment } from "../../state/orchestration";
13
+import { useEnvironmentQuery } from "../../state/query";
14
import { UnresolvedChip } from "../contextChipParts";
15
import { ThreadContextChip } from "../ThreadContextChip";
16
@@ -19,26 +20,46 @@ export function MarkdownThreadLink(props: {
20
readonly link: ThreadLink;
21
readonly label: string | null;
22
}) {
22
- const environmentId = props.link.environmentId ?? props.environmentId;
23
- const decodedId = percentDecodedThreadLinkId(props.link.threadId);
24
- const written = useThreadShell(scopeThreadRef(environmentId, props.link.threadId));
25
- const decoded = useThreadShell(
26
- written === null && decodedId !== null ? scopeThreadRef(environmentId, decodedId) : null,
23
+ const candidates = threadLinkCandidates(props.link, props.environmentId);
24
+ const writtenRef = candidates[0]!;
25
+ const written = useThreadShell(writtenRef);
26
+ const lookup = useEnvironmentQuery(
27
+ written === null
28
+ ? orchestrationEnvironment.threadLinkMetadata({
29
+ environmentId: writtenRef.environmentId,
30
+ input: { threadIds: candidates.map((ref) => ref.threadId) },
31
+ })
32
+ : null,
33
);
28
- const local = written ?? decoded;
29
- const guess = local === null && props.link.environmentId === null;
34
+ const settled = lookup.isSuccess && !lookup.isPending;
35
+ const target =
36
+ written !== null
37
+ ? { ref: writtenRef, metadata: written }
38
+ : (candidates.flatMap((ref) => {
39
+ const metadata = lookup.data?.[ref.threadId];
40
+ return metadata ? [{ ref, metadata }] : [];
41
+ })[0] ?? null);
42
+ const missing = target === null && settled;
43
+ const guess = missing && props.link.environmentId === null;
44
const refs = useThreadRefs(guess);
31
- const remote = useThreadShell(guess ? guessThreadLinkRef(props.link, refs) : null);
32
- const thread = local ?? remote;
33
- if (thread === null) {
45
+ const remoteRef = guess
46
+ ? guessThreadLinkRef(
47
+ props.link,
48
+ refs.filter((ref) => ref.environmentId !== writtenRef.environmentId),
49
+ )
50
+ : null;
51
+ const remote = useThreadShell(remoteRef);
52
+ const resolved = target ?? (remoteRef && remote ? { ref: remoteRef, metadata: remote } : null);
53
+ if (missing && resolved === null) {
54
const unknown = unknownThreadLinkLabel(props.link, props.environmentId);
55
return <UnresolvedChip label={props.label ?? unknown} tooltip={unknown} />;
56
}
37
- const ref = { environmentId: thread.environmentId, threadId: thread.id };
38
- const title = thread.title.trim() || props.label || "Untitled thread";
57
+ const ref = resolved?.ref ?? writtenRef;
58
+ const title = resolved?.metadata.title.trim() || props.label || "Thread";
59
return (
60
<ThreadContextChip
61
record={{ ...ref, title }}
62
+ projectId={resolved?.metadata.projectId ?? null}
63
copyMarkdown={formatHostedThreadLink(ref, title, configuredHostedAppUrl())}
64
/>
65
);
packages/client-runtime/src/state/orchestration.ts
+47
-9
@@ -2,6 +2,7 @@ import {
2
ORCHESTRATION_V2_WS_METHODS,
3
type EnvironmentId,
4
type ThreadId,
5
+ type OrchestrationV2ThreadLinkMetadata,
6
type OrchestrationGetTurnDiffResult,
7
} from "@t3tools/contracts";
8
import * as Effect from "effect/Effect";
@@ -14,6 +15,7 @@ import { Atom } from "effect/reactivity";
15
import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT } from "./commandOutput.ts";
16
17
import {
18
+ createEnvironmentQueryAtomFamily,
19
createEnvironmentRpcCommand,
20
createEnvironmentRpcQueryAtomFamily,
21
createEnvironmentRpcSubscriptionAtomFamily,
@@ -24,7 +26,7 @@ import type { EnvironmentRegistry } from "../connection/registry.ts";
26
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
27
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
28
import * as ManagedRelayDpopSigner from "../relay/managedRelay.ts";
27
-import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
29
+import { EnvironmentRpcUnavailableError, request } from "../rpc/client.ts";
30
import type { EnvironmentShellState } from "./shell.ts";
31
import { fetchEnvironmentThreadTranscript } from "./threadTranscriptHttp.ts";
32
@@ -47,6 +49,20 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
49
? {}
50
: { onAnswer: options.onCheckpointDiffAnswer };
51
const shellState = options.shellState;
52
+ const refreshThreadLookup = ({
53
+ environmentId,
54
+ input,
55
+ }: {
56
+ readonly environmentId: EnvironmentId;
57
+ readonly input: { readonly threadIds: ReadonlyArray<ThreadId> };
58
+ }) => {
59
+ if (shellState === undefined) return undefined;
60
+ const state = shellState(environmentId);
61
+ return Atom.make((get) => {
62
+ const { removedAt } = get(state);
63
+ return Math.max(-1, ...input.threadIds.map((threadId) => removedAt.get(threadId) ?? -1));
64
+ });
65
+ };
66
return {
67
threadTitles: createEnvironmentRpcQueryAtomFamily(runtime, {
68
label: "environment-data:orchestration:thread-titles",
@@ -55,14 +71,36 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
71
idleTtlMs: 0,
72
// Deleting a thread the shell already left out keeps these ids, so the query would not rerun.
73
// A removal can also be an archive, so it only prompts a re-check.
58
- refreshTrigger: ({ environmentId, input }) => {
59
- if (shellState === undefined) return undefined;
60
- const state = shellState(environmentId);
61
- return Atom.make((get) => {
62
- const { removedAt } = get(state);
63
- return Math.max(-1, ...input.threadIds.map((threadId) => removedAt.get(threadId) ?? -1));
64
- });
65
- },
74
+ refreshTrigger: refreshThreadLookup,
75
+ }),
76
+ threadLinkMetadata: createEnvironmentQueryAtomFamily(runtime, {
77
+ label: "environment-data:orchestration:thread-link-metadata",
78
+ staleTimeMs: 0,
79
+ idleTtlMs: 0,
80
+ refreshTrigger: refreshThreadLookup,
81
+ execute: Effect.fn("orchestration.threadLinkMetadata")(function* (input: {
82
+ readonly threadIds: ReadonlyArray<ThreadId>;
83
+ }) {
84
+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
85
+ const session = yield* SubscriptionRef.get(supervisor.session);
86
+ if (Option.isNone(session)) {
87
+ return yield* new EnvironmentRpcUnavailableError({
88
+ environmentId: supervisor.target.environmentId,
89
+ message: "The environment has no session.",
90
+ });
91
+ }
92
+ const config = yield* session.value.initialConfig;
93
+ if (config.threadLinkMetadata === true) {
94
+ return yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata, input);
95
+ }
96
+ const titles = yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadTitles, input);
97
+ return Object.fromEntries(
98
+ Object.entries(titles).map(([id, title]) => [
99
+ id,
100
+ { title, projectId: null } satisfies OrchestrationV2ThreadLinkMetadata,
101
+ ]),
102
+ );
103
+ }),
104
}),
105
threadTranscript: createEnvironmentCommand(runtime, {
106
label: "environment-data:orchestration:thread-transcript",
packages/client-runtime/src/state/runtime.test.ts
+34
@@ -3,6 +3,7 @@ import {
3
EnvironmentId,
4
ORCHESTRATION_V2_WS_METHODS,
5
ThreadId,
6
+ ProjectId,
7
type ReviewDiffPreviewInput,
8
type PreviewEvent,
9
type TerminalAttachInput,
@@ -1023,6 +1024,39 @@ describe("environment query lifecycle", () => {
1024
),
1025
);
1026
1027
+ it.effect.each([true, false])("loads thread link metadata with server support %s", (supported) =>
1028
+ Effect.scoped(
1029
+ Effect.gen(function* () {
1030
+ const projectId = ProjectId.make("project");
1031
+ const tag = supported
1032
+ ? ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata
1033
+ : ORCHESTRATION_V2_WS_METHODS.getThreadTitles;
1034
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1035
+ rpcSession: {
1036
+ initialConfig: Effect.succeed({ threadLinkMetadata: supported }),
1037
+ client: {
1038
+ [tag]: () =>
1039
+ Effect.succeed(
1040
+ supported ? { fork: { title: "Fork", projectId } } : { fork: "Fork" },
1041
+ ),
1042
+ },
1043
+ } as unknown as RpcSession.RpcSession,
1044
+ });
1045
+ const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1046
+ EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1047
+ >;
1048
+ const atom = createOrchestrationEnvironmentAtoms(runtime).threadLinkMetadata({
1049
+ environmentId: QUERY_ENVIRONMENT.environmentId,
1050
+ input: { threadIds: [ThreadId.make("fork")] },
1051
+ });
1052
+ const registry = yield* mountEnvironmentQuery(atom);
1053
+ expect(yield* readEnvironmentQuery(registry, atom)).toEqual({
1054
+ fork: { title: "Fork", projectId: supported ? projectId : null },
1055
+ });
1056
+ }),
1057
+ ),
1058
+ );
1059
+
1060
it.effect("re-checks thread titles when one of their threads leaves the shell", () =>
1061
Effect.scoped(
1062
Effect.gen(function* () {
packages/contracts/src/orchestrationV2.ts
+11
@@ -3597,6 +3597,7 @@ export const ORCHESTRATION_V2_WS_METHODS = {
3597
getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
3598
getThreadFamily: "orchestration.getThreadFamily",
3599
getThreadTitles: "orchestration.getThreadTitles",
3600
+ getThreadLinkMetadata: "orchestration.getThreadLinkMetadata",
3601
getWorktreeThreadIds: "orchestration.getWorktreeThreadIds",
3602
getOlderSettledThreads: "orchestration.getOlderSettledThreads",
3603
getThreadProjection: "orchestration.getThreadProjection",
@@ -3728,6 +3729,12 @@ export const OrchestrationV2GetThreadTitlesInput = Schema.Struct({
3729
/** Titles of the requested threads that exist, archived ones included. Deleted and unknown ids are absent. */
3730
export const OrchestrationV2ThreadTitles = Schema.Record(ThreadId, Schema.String);
3731
3732
+export const OrchestrationV2ThreadLinkMetadata = Schema.Struct({
3733
+ title: Schema.String,
3734
+ projectId: Schema.NullOr(ProjectId),
3735
+});
3736
+export type OrchestrationV2ThreadLinkMetadata = typeof OrchestrationV2ThreadLinkMetadata.Type;
3737
+
3738
export const OrchestrationV2GetWorktreeThreadIdsInput = Schema.Struct({
3739
worktreePath: TrimmedNonEmptyString,
3740
});
@@ -4254,6 +4261,10 @@ export const OrchestrationV2RpcSchemas = {
4261
input: OrchestrationV2GetThreadTitlesInput,
4262
output: OrchestrationV2ThreadTitles,
4263
},
4264
+ getThreadLinkMetadata: {
4265
+ input: OrchestrationV2GetThreadTitlesInput,
4266
+ output: Schema.Record(ThreadId, OrchestrationV2ThreadLinkMetadata),
4267
+ },
4268
getWorktreeThreadIds: {
4269
input: OrchestrationV2GetWorktreeThreadIdsInput,
4270
output: OrchestrationV2WorktreeThreadIds,
packages/contracts/src/rpc.ts
+10
@@ -1811,6 +1811,15 @@ const WsOrchestrationV2GetThreadTitlesRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS
1811
error: Schema.Union([OrchestrationV2GetShellSnapshotError, EnvironmentAuthorizationError]),
1812
});
1813
1814
+const WsOrchestrationV2GetThreadLinkMetadataRpc = Rpc.make(
1815
+ ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata,
1816
+ {
1817
+ payload: OrchestrationV2RpcSchemas.getThreadLinkMetadata.input,
1818
+ success: OrchestrationV2RpcSchemas.getThreadLinkMetadata.output,
1819
+ error: Schema.Union([OrchestrationV2GetShellSnapshotError, EnvironmentAuthorizationError]),
1820
+ },
1821
+);
1822
+
1823
const WsOrchestrationV2GetWorktreeThreadIdsRpc = Rpc.make(
1824
ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds,
1825
{
@@ -2231,6 +2240,7 @@ export const WsRpcGroup = RpcGroup.make(
2240
WsOrchestrationV2GetArchivedShellSnapshotRpc,
2241
WsOrchestrationV2GetThreadFamilyRpc,
2242
WsOrchestrationV2GetThreadTitlesRpc,
2243
+ WsOrchestrationV2GetThreadLinkMetadataRpc,
2244
WsOrchestrationV2GetWorktreeThreadIdsRpc,
2245
WsOrchestrationV2GetOlderSettledThreadsRpc,
2246
WsOrchestrationV2GetThreadProjectionRpc,
packages/contracts/src/server.ts
+1
@@ -629,6 +629,7 @@ export const ServerConfig = Schema.Struct({
629
* `getThreadFamily` and `getWorktreeThreadIds` serve the rows it leaves out.
630
*/
631
shellThreadFamilies: Schema.optionalKey(Schema.Boolean),
632
+ threadLinkMetadata: Schema.optionalKey(Schema.Boolean),
633
/**
634
* The shell can leave older settled threads out of snapshots (`omitOlderSettled`), and
635
* `getOlderSettledThreads` serves them. Only servers that also advertise `shellThreadFamilies`.
packages/shared/src/threadLinks.ts
+1
-1
@@ -71,7 +71,7 @@ export function parseThreadLinkHref(href: string): ThreadLink | null {
71
return environmentId === null || threadId === null ? null : { environmentId, threadId };
72
}
73
74
-export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
74
+function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
75
try {
76
const decoded = decodeURIComponent(threadId);
77
return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));