Repository navigation
Expand file tree
/
Copy pathThreadAttachPicker.tsx
More file actions
351 lines (339 loc) · 14.2 KB
/
Copy pathThreadAttachPicker.tsx
File metadata and controls
351 lines (339 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import { useAtomValue } from "@effect/atom-react";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
import { listThreadTabMemberships } from "@t3tools/client-runtime/thread-tabs";
import type { PreparedConnection } from "@t3tools/client-runtime/connection";
import type {
ProviderInstanceId,
ScopedThreadRef,
ThreadId,
ThreadTabMembership,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import { Atom } from "effect/reactivity";
import { MessageSquareIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useComposerDraftStore } from "~/composerDraftStore";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { useProjects, useThreadShells } from "~/state/entities";
import { useEnvironmentProviders } from "~/state/environments";
import { deriveProviderInstanceEntries, shouldShowInstanceBadge } from "~/providerInstances";
import { runtime } from "~/lib/runtime";
import { usePreparedConnection } from "~/state/session";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { useUiStateStore } from "~/uiStateStore";
import { ProjectFavicon } from "../ProjectFavicon";
import { hasUnseenCompletion, resolveSidebarThreadStatus } from "../Sidebar.logic";
import { resolveSidebarTopStatus, SidebarTopStatusIcon } from "../sidebar/SidebarTopStatus";
import { CommandPaletteContent } from "../CommandPaletteContent";
import {
CommandCollection,
CommandDialog,
CommandDialogPopup,
CommandGroup,
CommandItem,
CommandList,
} from "../ui/command";
import { toastManager } from "../ui/toast";
import {
composerThreadReferenceItems,
DEFAULT_THREAD_ATTACH_PICKER_VIEW,
groupThreadAttachPickerItems,
threadAttachPickerFacets,
} from "./composerThreadReferences";
import { CursorPreviewCard } from "./CursorPreviewCard";
import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
import { ThreadAttachPickerFilterBar } from "./ThreadAttachPickerFilters";
import { createThreadAttachSummaryLoader } from "./threadAttachPickerSummary";
import { ThreadSummaryPreview } from "./ThreadSummaryPreview";
import { useCaptureThreadTabContext } from "./ThreadTabs";
const THREAD_PICKER_LIMIT = 50;
/** Keeps the destination draft stable while the attach menu or command palette closes. */
const threadAttachPickerTargetAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("chat:thread-attach-picker-target"),
);
export function openThreadAttachPicker(threadRef: ScopedThreadRef): void {
appAtomRegistry.set(threadAttachPickerTargetAtom, threadRef);
}
function closeThreadAttachPicker(): void {
appAtomRegistry.set(threadAttachPickerTargetAtom, null);
}
/** Mounted once by the chat view; summaries use the same capture path as `@` mentions. */
export function ThreadAttachPickerHost() {
const threadRef = useAtomValue(threadAttachPickerTargetAtom);
if (threadRef === null) return null;
return (
<ThreadAttachPickerDialog
key={`${threadRef.environmentId}:${threadRef.threadId}`}
threadRef={threadRef}
/>
);
}
function ThreadAttachPickerDialog({ threadRef }: { threadRef: ScopedThreadRef }) {
const threads = useThreadShells();
const projects = useProjects();
const providersByEnvironment = useEnvironmentProviders();
const prepared = usePreparedConnection(threadRef.environmentId);
// Renames and activity updates do not change membership. A new or closed tab does.
const membershipThreadIds = threads
.filter(
(thread) => thread.environmentId === threadRef.environmentId && thread.archivedAt === null,
)
.map((thread) => thread.id)
.toSorted()
.join("|");
const [tabMemberships, setTabMemberships] = useState<{
connection: PreparedConnection;
threadIds: string;
rows: ReadonlyArray<ThreadTabMembership>;
} | null>(null);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads thread-tab membership from the prepared connection while the picker is open
useEffect(() => {
if (Option.isNone(prepared)) return;
const connection = prepared.value;
let active = true;
const store = (rows: ReadonlyArray<ThreadTabMembership>) => {
if (active) setTabMemberships({ connection, threadIds: membershipThreadIds, rows });
};
runtime.runPromise(listThreadTabMemberships(connection)).then(store, () => {
// Upstream environments without tabs still expose their ordinary threads.
store([]);
});
return () => {
active = false;
};
}, [prepared, membershipThreadIds]);
const membershipsReady =
Option.isNone(prepared) ||
(tabMemberships?.connection === prepared.value &&
tabMemberships.threadIds === membershipThreadIds);
const memberships =
Option.isSome(prepared) && tabMemberships?.connection === prepared.value
? tabMemberships.rows
: undefined;
const captureContext = useCaptureThreadTabContext(threadRef.environmentId, threadRef.threadId);
const loadSummary =
captureContext === null ? null : createThreadAttachSummaryLoader(captureContext.fetchSummary);
const [query, setQuery] = useState("");
const [view, setView] = useState(DEFAULT_THREAD_ATTACH_PICKER_VIEW);
const [attaching, setAttaching] = useState(false);
const attachInFlight = useRef(false);
const entries = composerThreadReferenceItems({
threads,
projects,
environmentId: threadRef.environmentId,
excludeThreadIds: new Set([threadRef.threadId]),
query,
limit: THREAD_PICKER_LIMIT,
view,
...(memberships ? { tabMemberships: memberships } : {}),
});
const groups = groupThreadAttachPickerItems(entries);
const threadsById = new Map(
threads
.filter((thread) => thread.environmentId === threadRef.environmentId)
.map((thread) => [thread.id, thread]),
);
const projectsById = new Map(
projects
.filter((project) => project.environmentId === threadRef.environmentId)
.map((project) => [project.id, project]),
);
const providerEntries = new Map(
deriveProviderInstanceEntries(providersByEnvironment.get(threadRef.environmentId) ?? []).map(
(provider) => [provider.instanceId, provider],
),
);
const projectOf = (threadId: ThreadId) => {
const thread = threadsById.get(threadId);
return thread ? projectsById.get(thread.projectId) : undefined;
};
const facets = threadAttachPickerFacets({
threads,
projects,
environmentId: threadRef.environmentId,
excludeThreadIds: new Set([threadRef.threadId]),
query,
view,
...(memberships ? { tabMemberships: memberships } : {}),
});
const providerName = (value: ProviderInstanceId) =>
providerEntries.get(value)?.displayName ??
threads.find((thread) => thread.modelSelection.instanceId === value)?.runtime?.providerName ??
value;
// Counts come back by id; equal counts read alphabetically by name instead.
const byCountThenLabel = (
a: { count: number; label: string },
b: { count: number; label: string },
) => b.count - a.count || a.label.localeCompare(b.label);
const filterOptions = {
projects: facets.projects.toSorted(byCountThenLabel),
providers: facets.providers
.map((choice) => ({ ...choice, label: providerName(choice.value) }))
.toSorted(byCountThenLabel),
};
async function select(entry: (typeof entries)[number]) {
if (attachInFlight.current || captureContext === null || loadSummary === null) return;
attachInFlight.current = true;
setAttaching(true);
try {
const summary = await loadSummary(entry.threadId);
const reference = await captureContext.capture(entry.threadId, entry.label, summary);
useComposerDraftStore.getState().insertContextReference(threadRef, reference);
// A dismissed picker may have been reopened for a different draft during capture.
if (appAtomRegistry.get(threadAttachPickerTargetAtom) === threadRef) {
closeThreadAttachPicker();
}
} catch (cause) {
toastManager.add({
type: "error",
title: "Could not attach that thread",
description: cause instanceof Error ? cause.message : undefined,
});
}
attachInFlight.current = false;
setAttaching(false);
}
return (
<CommandDialog
open
onOpenChange={(open) => {
if (!open) closeThreadAttachPicker();
}}
>
<CommandDialogPopup aria-label="Attach thread" className="overflow-hidden">
<CommandPaletteContent
inputProps={{ placeholder: "Search threads by title", startAddon: <MessageSquareIcon /> }}
footerActionLabel={attaching ? "Attaching…" : "Attach"}
inputAccessory={
<ThreadAttachPickerFilterBar {...filterOptions} view={view} onChange={setView} />
}
mode="none"
value={query}
onValueChange={setQuery}
>
{!membershipsReady ? (
<div className="py-10 text-center text-muted-foreground text-sm">
Loading thread tabs…
</div>
) : entries.length === 0 ? (
<div className="py-10 text-center text-muted-foreground text-sm">
{query.trim() || view.projectIds.length > 0 || view.providerInstanceIds.length > 0
? "No threads match these filters."
: "No other threads to attach."}
</div>
) : (
<CommandList>
{groups.map((group) => {
const isTabGroup = group.parentTitle !== null;
return (
<CommandGroup key={group.id} items={group.entries}>
{/* A thread's tabs hang off one side rule, each an ordinary row. */}
<div className={isTabGroup ? "my-1 ml-4 border-l pl-1" : undefined}>
<CommandCollection>
{(entry: (typeof entries)[number]) => (
<CommandItem
key={entry.id}
value={entry.id}
disabled={attaching || captureContext === null}
onMouseDown={(event) => event.preventDefault()}
onClick={() => void select(entry)}
>
<CursorPreviewCard
trigger={
<span className="flex min-w-0 flex-1 items-center gap-2">
<ThreadProjectIcon project={projectOf(entry.threadId)} />
<span className="min-w-0 flex-1 truncate text-sm">
{entry.label}
</span>
<ThreadProviderIcon
thread={threadsById.get(entry.threadId)}
providerEntries={providerEntries}
/>
<ThreadActivityMeta thread={threadsById.get(entry.threadId)} />
</span>
}
>
<ThreadSummaryPreview
environmentId={threadRef.environmentId}
threadId={entry.threadId}
title={entry.label}
parentTitle={entry.parentThreadTitle}
loadSummary={loadSummary}
/>
</CursorPreviewCard>
</CommandItem>
)}
</CommandCollection>
</div>
</CommandGroup>
);
})}
</CommandList>
)}
</CommandPaletteContent>
</CommandDialogPopup>
</CommandDialog>
);
}
function ThreadProjectIcon(props: {
project: Parameters<typeof ProjectFavicon>[0]["project"] | undefined;
}) {
return props.project ? (
<ProjectFavicon project={props.project} className="size-4 shrink-0" />
) : (
<MessageSquareIcon className="size-4 shrink-0 text-muted-foreground" />
);
}
/** The thread's provider glyph, badged like the sidebar when two instances share a driver. */
function ThreadProviderIcon(props: {
thread: EnvironmentThreadShell | undefined;
providerEntries: ReadonlyMap<string, ReturnType<typeof deriveProviderInstanceEntries>[number]>;
}) {
const { thread, providerEntries } = props;
if (!thread) return null;
const instanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
const entry = providerEntries.get(instanceId);
if (!entry) return null;
return (
<span className="inline-flex shrink-0 items-center">
<ProviderInstanceIcon
driverKind={entry.driverKind}
displayName={entry.displayName}
accentColor={entry.accentColor}
showBadge={shouldShowInstanceBadge(entry, providerEntries.values())}
iconClassName="size-3.5 opacity-60"
badgeClassName="right-[-0.1875rem] bottom-[-0.1875rem] h-3 min-w-3 px-0.5 text-5xs"
/>
</span>
);
}
/** The sidebar's status and last-activity time, so rows read the same in both places. */
function ThreadActivityMeta({ thread }: { thread: EnvironmentThreadShell | undefined }) {
const threadKey = thread
? scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
: null;
const lastVisitedAt = useUiStateStore((state) =>
threadKey === null ? undefined : state.threadLastVisitedAtById[threadKey],
);
if (!thread) return null;
const status = resolveSidebarTopStatus(
resolveSidebarThreadStatus(thread),
false,
hasUnseenCompletion({ ...thread, lastVisitedAt }),
);
const time = formatRelativeTimeLabel(thread.latestUserMessageAt ?? thread.updatedAt);
return (
<span className="flex shrink-0 items-center gap-2 text-xs">
{status ? (
<span className={`inline-flex items-center gap-1 font-medium ${status.className}`}>
<SidebarTopStatusIcon icon={status.icon} className="size-3.5 shrink-0" />
{status.label}
</span>
) : null}
{/* A fixed slot keeps the provider icons and statuses in one column. */}
<span className="min-w-16 text-right text-muted-foreground tabular-nums">{time}</span>
</span>
);
}