-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathDashboardAgent.tsx
More file actions
362 lines (336 loc) · 13.3 KB
/
Copy pathDashboardAgent.tsx
File metadata and controls
362 lines (336 loc) · 13.3 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
352
353
354
355
356
357
358
359
360
361
362
import type { SuggestedPrompt, WatchSpec } from "@internal/dashboard-agent-contracts";
import { useLocation } from "@remix-run/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
} from "~/components/primitives/Resizable";
import { useEnvironment } from "~/hooks/useEnvironment";
import { useOrganization } from "~/hooks/useOrganizations";
import { useProject } from "~/hooks/useProject";
import { useShortcutKeys } from "~/hooks/useShortcutKeys";
import { useAskAiAvailability } from "~/hooks/useAskAiAvailability";
import { agentDeepLinkParams, ASK_AI_SHORTCUT, askAiChannelTarget } from "./ask-ai-channels";
import { DashboardAgentPanel } from "./DashboardAgentPanel";
import { DashboardAgentProvider, TOGGLE_PANEL_SHORTCUT } from "./dashboardAgentLauncher";
import { useDashboardAgentOpenRequests } from "./dashboardAgentOpenRequest";
import {
agentHiddenContentClassName,
agentTakeoverClassName,
readAgentFullscreen,
writeAgentFullscreen,
} from "./panel-layout";
import { nextPendingTurnChatId } from "./pending-turn";
import { nextVisibleChat, unreadWorkForDot } from "./unread-counts";
import { startWakePolling, wakesToToast } from "./wake-poll";
import { shouldPollWakeFeed, subscribeWatchActivity } from "./watch-activity";
import {
showWatchWakesSummaryToast,
showWatchWakeToast,
WAKE_TOAST_MAX_INDIVIDUAL,
type WatchWake,
} from "./WatchWakeToast";
const TOASTED_WAKES_STORAGE_KEY = "tdev:dashboard-agent:toasted-wakes";
// Shorter than the poll interval, so a stuck request is dropped before the next tick.
const UNREAD_REQUEST_TIMEOUT_MS = 30_000;
/** `hasAccess` is a UI gate only; the resource routes enforce the same check server-side. */
export function DashboardAgent({
children,
hasAccess = false,
promotedPrompt,
/** From the page load: unread wakes waiting for this user, whatever this browser remembers. */
initialUnreadWakes = 0,
initialUnreadWork = 0,
/** Also from the page load: a watch is running, so a wake can still arrive in this tab. */
hasActiveWatches = false,
}: {
children: React.ReactNode;
hasAccess?: boolean;
promotedPrompt?: SuggestedPrompt;
initialUnreadWakes?: number;
/** Chats whose transcript moved on since their owner last looked. */
initialUnreadWork?: number;
hasActiveWatches?: boolean;
}) {
const organization = useOrganization();
const project = useProject();
const environment = useEnvironment();
const actionPath = `/resources/orgs/${organization.slug}/projects/${project.slug}/env/${environment.slug}/dashboard-agent`;
const [open, setOpen] = useState(false);
// Seeded from the page load, so the launcher dot is right before the first poll answers.
const [unreadWakes, setUnreadWakes] = useState(initialUnreadWakes);
// Work that finished behind a closed panel. Counted server-side on page load and refreshed
// with the chat list; the wake poll doesn't carry it.
const [unreadWork, setUnreadWork] = useState(initialUnreadWork);
// A turn this tab started may finish after the panel closes; that is exactly the case the
// dot exists for, so the poll has to be running when it lands.
const [pendingTurnChatId, setPendingTurnChatId] = useState<string | null>(null);
const handleTurnActivityChange = useCallback((chatId: string, active: boolean) => {
setPendingTurnChatId((current) => nextPendingTurnChatId(current, { chatId, active }));
}, []);
const toastedWakes = useRef(new Set<string>());
// The toast source is recent deliveries, not unread, so the dedupe must survive a reload.
useEffect(() => {
try {
const raw = window.localStorage.getItem(TOASTED_WAKES_STORAGE_KEY);
if (raw) for (const id of JSON.parse(raw) as string[]) toastedWakes.current.add(id);
} catch {
// Storage unavailable; the in-memory dedupe still applies.
}
}, []);
const rememberToasted = useCallback((watchId: string) => {
toastedWakes.current.add(watchId);
try {
// Newest ids only, so the key can't grow unbounded.
window.localStorage.setItem(
TOASTED_WAKES_STORAGE_KEY,
JSON.stringify([...toastedWakes.current].slice(-50))
);
} catch {
// Same as the read.
}
}, []);
// A wake in the on-screen chat toasts but must not light the dot.
const visibleChat = useRef<string | null>(null);
// Read by the poll callback, which outlives the render that started it: `open` in its closure
// is whatever it was when polling began, and opening the panel does not restart the poll.
const panelOpen = useRef(open);
useEffect(() => {
panelOpen.current = open;
}, [open]);
// Switching environment re-runs the layout loader but does not remount it, so the seeds
// above would keep the old environment's counts.
const seededEnvironment = useRef(environment.id);
useEffect(() => {
if (seededEnvironment.current === environment.id) return;
seededEnvironment.current = environment.id;
setUnreadWakes(initialUnreadWakes);
setUnreadWork(initialUnreadWork);
}, [environment.id, initialUnreadWakes, initialUnreadWork]);
// Read lazily so SSR always renders the side panel.
const [fullscreen, setFullscreen] = useState(readAgentFullscreen);
const toggleFullscreen = useCallback(() => {
setFullscreen((current) => {
writeAgentFullscreen(!current);
return !current;
});
}, []);
// Pathname only: filter and search-param changes must keep fullscreen.
const { pathname } = useLocation();
const previousPathname = useRef(pathname);
useEffect(() => {
if (previousPathname.current === pathname) return;
previousPathname.current = pathname;
setFullscreen((current) => {
if (current) writeAgentFullscreen(false);
return false;
});
}, [pathname]);
const [newChatSeq, setNewChatSeq] = useState(0);
const [requestedMessage, setRequestedMessage] = useState<
{ text: string; seq: number } | undefined
>(undefined);
// `seq` so the same chat can be asked for twice.
const [openChatRequest, setOpenChatRequest] = useState<
{ chatId: string; seq: number } | undefined
>(undefined);
const [watchRequest, setWatchRequest] = useState<{ spec: WatchSpec; seq: number } | undefined>(
undefined
);
const setPanelOpen = useCallback((next: boolean) => {
setOpen(next);
// Pending requests must be dropped or a stale one re-applies on the next open.
if (!next) {
visibleChat.current = null;
setFullscreen(false);
writeAgentFullscreen(false);
setRequestedMessage(undefined);
setOpenChatRequest(undefined);
setWatchRequest(undefined);
}
}, []);
const openChat = useCallback((chatId: string) => {
setOpen(true);
setOpenChatRequest((current) => ({ chatId, seq: (current?.seq ?? 0) + 1 }));
}, []);
const openWith = useCallback((text: string) => {
const trimmed = text.trim();
if (!trimmed) return;
setOpen(true);
setRequestedMessage((current) => ({ text: trimmed, seq: (current?.seq ?? 0) + 1 }));
}, []);
const openWithWatch = useCallback((spec: WatchSpec) => {
setOpen(true);
setWatchRequest((current) => ({ spec, seq: (current?.seq ?? 0) + 1 }));
}, []);
// Nothing to be woken about means nothing to poll for. The page load's unread count and
// active-watch flag are the ungated signals; the browser's own memory of a watch starts the
// poll without a reload. Once any says yes this tab keeps polling, so a wake reaches a tab
// that was open before the watch existed.
const [watching, setWatching] = useState(false);
useEffect(() => {
const sync = () => {
if (
shouldPollWakeFeed({
serverUnreadWakes: initialUnreadWakes,
serverHasActiveWatches: hasActiveWatches,
serverUnreadWork: initialUnreadWork,
turnInFlight: pendingTurnChatId !== null,
organizationId: organization.id,
})
)
setWatching(true);
};
sync();
return subscribeWatchActivity(sync);
}, [organization.id, initialUnreadWakes, hasActiveWatches, initialUnreadWork, pendingTurnChatId]);
useEffect(() => {
if (!hasAccess || !watching) return;
let cancelled = false;
const load = async () => {
try {
// Bounded, so one stuck request can't hold the poll's in-flight guard.
const res = await fetch(`${actionPath}?unread=1`, {
signal: AbortSignal.timeout(UNREAD_REQUEST_TIMEOUT_MS),
});
if (!res.ok) return;
const data = (await res.json()) as {
unreadWakes?: number;
unreadWork?: number;
wakes?: WatchWake[];
};
if (cancelled) return;
// The wakes list carries read ones too, so only unread ones are subtracted.
const unreadInView = (data.wakes ?? []).filter(
(wake) => wake.unread && wake.chatId === visibleChat.current
).length;
setUnreadWakes(Math.max(0, (data.unreadWakes ?? 0) - unreadInView));
setUnreadWork(
unreadWorkForDot({
reported: data.unreadWork,
panelOpen: panelOpen.current,
visibleChatId: visibleChat.current,
})
);
const fresh = wakesToToast(data.wakes, toastedWakes.current);
for (const wake of fresh) rememberToasted(wake.watchId);
if (fresh.length > WAKE_TOAST_MAX_INDIVIDUAL) {
showWatchWakesSummaryToast(fresh.length, () => setPanelOpen(true));
} else {
for (const wake of [...fresh].reverse()) {
showWatchWakeToast(wake, openChat);
}
}
} catch {
// Try again next tick.
}
};
const stop = startWakePolling({
load,
isHidden: () => document.hidden,
onVisibilityChange: (listener) => {
document.addEventListener("visibilitychange", listener);
return () => document.removeEventListener("visibilitychange", listener);
},
});
return () => {
cancelled = true;
stop();
};
}, [hasAccess, watching, actionPath, setPanelOpen, openChat]);
// Zeroes the wake dot right away; the poll restores the truth if another chat has one. The
// work count is not touched here: the panel derives it from the chat list.
const markChatRead = useCallback(
async (chatId: string, options: { leaving: boolean }) => {
visibleChat.current = nextVisibleChat(chatId, options);
setUnreadWakes(0);
const body = new FormData();
body.set("intent", "read");
body.set("chatId", chatId);
try {
await fetch(actionPath, { method: "POST", body });
} catch {
// Catches up on the next open.
}
},
[actionPath]
);
// ⌘J is contextual: closed opens the panel, open starts a new chat. It never closes.
useShortcutKeys({
shortcut: TOGGLE_PANEL_SHORTCUT,
action: () => {
if (!open) {
setPanelOpen(true);
} else {
setNewChatSeq((seq) => seq + 1);
}
},
disabled: !hasAccess,
enabledOnInputElements: true,
});
// ⌘I and the CLI's `?aiHelp=` link are Ask AI's; the agent only answers them where Ask AI
// cannot open.
const askAi = useAskAiAvailability();
const ownsAskAiChannels = askAiChannelTarget(askAi) === "dashboard-agent";
useShortcutKeys({
shortcut: ASK_AI_SHORTCUT,
action: () => setPanelOpen(true),
disabled: !hasAccess || !ownsAskAiChannels,
enabledOnInputElements: true,
});
useDashboardAgentOpenRequests({
enabled: hasAccess,
openWith,
setOpen: setPanelOpen,
deepLinkParams: agentDeepLinkParams(askAi),
});
const context = useMemo(
() => ({ open, setOpen: setPanelOpen, openWith, openWithWatch, unreadWakes, unreadWork }),
[open, setPanelOpen, openWith, openWithWatch, unreadWakes, unreadWork]
);
if (!hasAccess) {
return <div className="h-full min-h-0">{children}</div>;
}
return (
<DashboardAgentProvider value={context}>
{open ? (
// `relative` is the takeover's containing block.
<div className="relative h-full min-h-0">
<ResizablePanelGroup
orientation="horizontal"
autosaveId="dashboard-agent-split"
className="h-full min-h-0"
>
<ResizablePanel id="dashboard-content" min="320px">
<div className={agentHiddenContentClassName(fullscreen)}>{children}</div>
</ResizablePanel>
<ResizableHandle
id="dashboard-agent-handle"
className={fullscreen ? "invisible" : undefined}
/>
<ResizablePanel id="dashboard-agent-panel" default="380px" min="320px" max="720px">
<div className={agentTakeoverClassName(fullscreen)}>
<DashboardAgentPanel
onClose={() => setPanelOpen(false)}
requestedMessage={requestedMessage}
openChatRequest={openChatRequest}
watchRequest={watchRequest}
newChatSeq={newChatSeq}
promotedPrompt={promotedPrompt}
onChatRead={markChatRead}
onUnreadWorkChange={setUnreadWork}
onTurnActivityChange={handleTurnActivityChange}
isFullscreen={fullscreen}
onToggleFullscreen={toggleFullscreen}
/>
</div>
</ResizablePanel>
</ResizablePanelGroup>
</div>
) : (
<div className="h-full min-h-0 overflow-hidden">{children}</div>
)}
</DashboardAgentProvider>
);
}