-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathshell.ts
More file actions
962 lines (899 loc) · 30.4 KB
/
Copy pathshell.ts
File metadata and controls
962 lines (899 loc) · 30.4 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
import { html, nothing, render, type TemplateResult } from "lit";
import {
Box,
Brain,
ChevronDown,
Clock,
Files,
Folder,
KeyRound,
LogOut,
MessageSquare,
PanelLeft,
Plus,
RefreshCw,
Rocket,
Search,
ShieldCheck,
Webhook,
type IconNode,
} from "lucide";
import "@mariozechner/mini-lit/dist/ThemeToggle.js";
import {
api,
fetchRuntimeConfig,
fetchTranscript,
setSigninRequiredHandler,
type SigninRequired,
TAIL_TURNS,
withBase,
} from "./core-bridge";
import { applyRuntimeOptions } from "./model-options";
import { errMessage, swallow } from "../../chassis/src/errors";
import { brandMark, brandName, icon, initials } from "./ui";
import { markConnectorConnected } from "./chat";
import { clearSkillsCache, resyncModelSelection, seedRuntimeConfig } from "./composer";
import { ensureDeliveryStream, mainConversation, onExitCanvas } from "./conversations";
import { clearAllDrafts, saveDraft, storedDraft } from "./drafts";
import { deepLinkPath, isPlainLeftClick, parseDeepLink, UI_BASE } from "./deep-link";
import {
adoptRemoteSplit,
canvasToast,
drawCanvas,
exitSplitIfActive,
focusedPaneSession,
loadPersistedSplit,
mountRestoredCanvas,
openBlankInFocusedPane,
openThreadInFocusedPane,
restoredCanvasNeedsSessionList,
splitState,
} from "./split";
import { activityOf } from "./session-list";
import { replaceChildrenPreservingFocus } from "./pane-focus";
import {
openSession,
closeOpenSessionMenu,
refreshSessions,
renderList,
resetSessionsState,
sessionTitle,
sessionsState,
toggleWebOnly,
sessionSelectionBar,
} from "./sessions";
import { openCronById, renderCronsPage, resetActiveCron, routeCronsHistory } from "./crons";
import { openWebhookById, renderWebhooksPage, resetActiveWebhook, routeWebhooksHistory } from "./webhooks";
import { renderFiles } from "./files";
import { setScopedSession } from "./session-scope";
import { openChatSearch, SEARCH_HOTKEY_LABEL } from "./search";
import { hideTooltip, showTooltip } from "./tooltip";
import { clearConnectorNotice, noteConnectorResult, renderConnectors, resetKeychainState } from "./connectors";
import { renderDeploys } from "./deploys";
import { renderMemory, resetMemoryState } from "./memory";
import { renderSkills } from "./skills";
import { contextsState, ensureContexts, renderContexts, resetContextsState, resolveProjectScope } from "./contexts";
import { appState, can, isView, type AuthMode, type Me, type View } from "./shell-state";
import { trapDialogFocus } from "./dialog-focus";
import { activeSessionForDocumentTitle, updateDocumentTitle } from "./document-title";
export { appState, can, type Me, type View } from "./shell-state";
let authMode: AuthMode = "portal";
let shellMounted = false;
setSigninRequiredHandler((detail) => {
authMode = detail.mode ?? authMode;
renderAuthGate(gateFor(authMode, detail.reason));
});
onExitCanvas(() => exitSplitIfActive());
if (typeof window !== "undefined" && !localStorage.getItem("theme")) {
localStorage.setItem("theme", window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
}
export const ADMIN_BASE = (() => {
const base = ((import.meta as unknown as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? "/").replace(/\/$/, "");
return base ? base.replace(/\/[^/]+$/, "/admin") : "/admin";
})();
export const ADMIN_HOME_URL = `${ADMIN_BASE}/`;
export function syncUrlFromState(sessionOverride?: string | null): void {
const chatState = mainConversation().state;
const fromState =
sessionOverride !== undefined ? sessionOverride : (chatState.sessionId ?? chatState.rememberedSessionId);
const sessionId = splitState.active ? null : fromState;
const next = deepLinkPath(UI_BASE, appState.currentView, sessionId, contextsState.selected);
if (`${location.pathname}${location.search}` !== next) history.replaceState(null, "", next);
}
const appEl = document.getElementById("app");
if (!appEl) throw new Error("missing #app");
const narrowViewport = window.matchMedia("(max-width: 860px)");
let sidebarOpen = !narrowViewport.matches;
const SIDEBAR_MIN_W = 200;
const SIDEBAR_MAX_W = 520;
const SIDEBAR_W_KEY = "webui:sidebar-w";
function applySavedSidebarWidth(): void {
const saved = Number(localStorage.getItem(SIDEBAR_W_KEY));
if (Number.isFinite(saved) && saved >= SIDEBAR_MIN_W && saved <= SIDEBAR_MAX_W) {
document.documentElement.style.setProperty("--sidebar-w", `${saved}px`);
}
}
function startSidebarResize(e: PointerEvent): void {
e.preventDefault();
const handle = e.currentTarget as HTMLElement;
const startX = e.clientX;
const sidebar = (appEl as HTMLElement).querySelector<HTMLElement>(".sidebar");
if (!sidebar) return;
const startW = sidebar.getBoundingClientRect().width;
handle.setPointerCapture(e.pointerId);
document.body.classList.add("resizing-sidebar");
let w = startW;
const onMove = (ev: PointerEvent) => {
w = Math.min(SIDEBAR_MAX_W, Math.max(SIDEBAR_MIN_W, startW + (ev.clientX - startX)));
document.documentElement.style.setProperty("--sidebar-w", `${w}px`);
};
const onUp = () => {
handle.removeEventListener("pointermove", onMove);
handle.removeEventListener("pointerup", onUp);
handle.removeEventListener("lostpointercapture", onUp);
document.body.classList.remove("resizing-sidebar");
localStorage.setItem(SIDEBAR_W_KEY, String(Math.round(w)));
};
handle.addEventListener("pointermove", onMove);
handle.addEventListener("pointerup", onUp);
handle.addEventListener("lostpointercapture", onUp);
}
function resetSidebarWidth(): void {
document.documentElement.style.removeProperty("--sidebar-w");
localStorage.removeItem(SIDEBAR_W_KEY);
}
const NAV_WORKSPACE_KEY = "web-ui:nav-workspace";
function loadNavOpen(key: string): boolean {
try {
return localStorage.getItem(key) === "1";
} catch {
return false;
}
}
function saveNavOpen(key: string, open: boolean): void {
try {
localStorage.setItem(key, open ? "1" : "0");
} catch {
void 0;
}
}
let navWorkspaceOpen = loadNavOpen(NAV_WORKSPACE_KEY);
function toggleNavWorkspace(): void {
navWorkspaceOpen = !navWorkspaceOpen;
saveNavOpen(NAV_WORKSPACE_KEY, navWorkspaceOpen);
renderSidebarTop();
}
const ICON = {
newChat: Plus,
chats: MessageSquare,
contexts: Folder,
files: Files,
keychain: KeyRound,
deploys: Rocket,
webhooks: Webhook,
crons: Clock,
memory: Brain,
skills: Box,
};
export async function signOut(): Promise<void> {
const portal = authMode === "portal";
if (!portal) {
try {
await api("/signout", { method: "POST" });
} catch {
void 0;
}
}
appState.me = null;
clearAllDrafts();
exitSplitIfActive();
mainConversation().resetChatState();
resetSessionsState();
appState.currentView = "chats";
clearSkillsCache();
resetMemoryState();
resetContextsState();
resetKeychainState();
mainConversation().composer.resetComposer();
updateDocumentTitle();
if (!portal) {
renderAuthGate({ kind: "dev" });
return;
}
let endedSession: boolean;
try {
const r = await fetch("/auth/logout", { method: "POST", headers: { accept: "application/json" } });
endedSession = r.ok;
} catch {
endedSession = false;
}
if (!endedSession) {
renderAuthGate({ kind: "portal" });
return;
}
clearPortalAttempt();
location.href = "/";
}
export async function exitImpersonation(): Promise<void> {
try {
await fetch("/auth/impersonate/stop", { method: "POST", headers: { accept: "application/json" } });
} catch {
void 0;
}
window.location.href = ADMIN_HOME_URL;
}
function impersonationBanner(by: string) {
return html`
<div class="top-banner" role="status">
<span>Viewing the assistant as <b>${appState.me?.user ?? ""}</b> — you are <b>${by}</b></span>
<button class="top-banner-action" type="button" @click=${exitImpersonation}>Exit impersonation</button>
</div>
`;
}
function devBanner(user: string) {
return html`
<div class="top-banner dev" role="status">
<span><b>Dev mode</b> — no identity provider, signed in as ${user}</span>
<button class="top-banner-action" type="button" @click=${signOut}>Sign out</button>
</div>
`;
}
function gateShell(body: unknown) {
return html`
<div class="signin">
<div class="signin-panel">
<div class="signin-brand">
${brandMark()}<span>${brandName()}</span>
${authMode === "dev" ? html`<span class="dev-chip">DEV</span>` : nothing}
</div>
${body}
</div>
</div>
`;
}
const PORTAL_ATTEMPT_KEY = "qm.portal.signin.attempt";
const PORTAL_ATTEMPT_WINDOW_MS = 20_000;
function portalAttemptedRecently(): boolean {
try {
const at = Number(sessionStorage.getItem(PORTAL_ATTEMPT_KEY) ?? "");
return Number.isFinite(at) && Date.now() - at < PORTAL_ATTEMPT_WINDOW_MS;
} catch {
return false;
}
}
function signInWithPortal(): void {
try {
sessionStorage.setItem(PORTAL_ATTEMPT_KEY, String(Date.now()));
} catch {
void 0;
}
const returnTo = `${location.pathname}${location.search}`;
location.href = `/auth/login?returnTo=${encodeURIComponent(returnTo)}`;
}
function clearPortalAttempt(): void {
try {
sessionStorage.removeItem(PORTAL_ATTEMPT_KEY);
} catch {
void 0;
}
}
function portalGate() {
if (portalAttemptedRecently())
return gateShell(html`
<h1>Sign in through the portal</h1>
<p class="signin-body">
This surface is reached through the portal, and signing in there didn't produce a session for it. Open the
portal address directly rather than this one.
</p>
<div class="hint">
If you opened this surface's own address, that's the cause — it can't authenticate anyone on its own.
</div>
`);
return gateShell(html`
<h1>Your session ended</h1>
<p class="signin-body">You've been signed out. Sign in again and you'll come back to this page.</p>
<button class="btn primary" type="button" @click=${signInWithPortal}>Sign in</button>
`);
}
function deniedGate() {
return gateShell(html`
<h1>You don't have access</h1>
<p class="signin-body">
Your account is signed in and verified — it just isn't allowed on this instance. Ask an administrator to add you.
</p>
<button class="btn" type="button" @click=${signOut}>Sign out</button>
${
authMode === "dev"
? html`<div class="hint">This instance lists its principals in <b>WEB_UI_PRINCIPALS</b>.</div>`
: nothing
}
`);
}
function retryBoot(): void {
void bootSafely();
}
function unreachableGate() {
return gateShell(html`
<h1>We couldn't reach the assistant</h1>
<p class="signin-body">The service didn't respond. This is usually temporary.</p>
<button class="btn primary" type="button" @click=${retryBoot}>Try again</button>
<div class="hint">If this keeps happening, the core service may be down.</div>
`);
}
async function submitDevSignin(user: string): Promise<void> {
renderAuthGate({ kind: "dev", value: user, pending: true });
try {
await api("/signin", { method: "POST", body: JSON.stringify({ user }) });
} catch (err) {
renderAuthGate({ kind: "dev", value: user, error: errMessage(err, "Sign-in failed.") });
return;
}
await bootSafely();
}
function devGate(gate: { value?: string; error?: string; pending?: boolean }) {
return gateShell(html`
<form
@submit=${(e: Event) => {
e.preventDefault();
if (gate.pending) return;
const input = (e.target as HTMLFormElement).querySelector("input") as HTMLInputElement | null;
const user = input?.value.trim();
if (user) void submitDevSignin(user);
}}
>
<h1>Dev sign-in</h1>
<p class="signin-body">
No identity provider is configured, so this instance trusts a local cookie. Set
<b>CORE_SIGNING_SECRET</b> and run the portal to use real sign-in.
</p>
<label for="dev-principal">Principal</label>
<input
id="dev-principal"
name="principal"
type="text"
inputmode="email"
autocomplete="username"
spellcheck="false"
required
autofocus
placeholder="you@org.com"
.value=${gate.value ?? ""}
?disabled=${gate.pending === true}
/>
<button class="btn primary" type="submit" ?disabled=${gate.pending === true}>
${gate.pending ? "Signing in…" : "Continue"}
</button>
${gate.error ? html`<div class="hint error" role="alert">${gate.error}</div>` : nothing}
</form>
`);
}
export type AuthGate =
| { kind: "portal" }
| { kind: "denied" }
| { kind: "unreachable" }
| { kind: "dev"; value?: string; error?: string; pending?: boolean };
export function renderAuthGate(gate: AuthGate): void {
shellMounted = false;
const body = (() => {
switch (gate.kind) {
case "portal":
return portalGate();
case "denied":
return deniedGate();
case "unreachable":
return unreachableGate();
default:
return devGate(gate);
}
})();
render(body, appEl as HTMLElement);
}
function gateFor(mode: AuthMode, reason: "unauthenticated" | "not_allowed" | undefined): AuthGate {
if (reason === "not_allowed") return { kind: "denied" };
return mode === "dev" ? { kind: "dev" } : { kind: "portal" };
}
export function mountShell(): void {
applySavedSidebarWidth();
const impersonatedBy = appState.me?.impersonatedBy ?? null;
let banner: TemplateResult | null = null;
if (impersonatedBy) banner = impersonationBanner(impersonatedBy);
else if (authMode === "dev") banner = devBanner(appState.me?.user ?? "");
render(
html`
${banner ?? nothing}
<div class="layout ${sidebarOpen ? "" : "sidebar-closed"} ${banner ? "bannered" : ""}">
<aside class="sidebar" aria-label="Navigation" @keydown=${onSidebarKeydown}>
<div class="brand">
<div class="brand-lockup">${brandMark()}<span class="brand-name">${brandName()}</span></div>
<button
class="icon-btn subtle sidebar-toggle sidebar-collapse-toggle"
type="button"
title="Hide sidebar"
aria-label="Hide sidebar"
@click=${toggleSidebar}
>
${icon(PanelLeft, 17)}
</button>
</div>
<div id="sidebar-top"></div>
<div class="list" id="sidebar-body"></div>
<div class="sidebar-footer">
<div class="user-pill" title=${appState.me?.user ?? ""}>
<span class="avatar">${initials(appState.me?.user ?? "?")}</span>
<span class="user-name">${appState.me?.user ?? ""}</span>
</div>
<theme-toggle .includeSystem=${false} title="Color scheme: light / dark"></theme-toggle>
<button class="icon-btn subtle" title="Sign out" aria-label="Sign out" @click=${signOut}>
${icon(LogOut, 17)}
</button>
</div>
</aside>
<button class="sidebar-scrim" type="button" aria-label="Close sidebar" @click=${toggleSidebar}></button>
<div
class="sidebar-resize-handle"
role="separator"
aria-orientation="vertical"
aria-label="Resize sidebar"
title="Drag to resize · double-click to reset"
@pointerdown=${startSidebarResize}
@dblclick=${resetSidebarWidth}
></div>
<section class="main" id="main" tabindex="-1">
<div class="empty">Pick a conversation, or start a new chat.</div>
</section>
</div>
`,
appEl as HTMLElement,
);
appState.topEl = (appEl as HTMLElement).querySelector("#sidebar-top");
appState.listEl = (appEl as HTMLElement).querySelector("#sidebar-body");
appState.mainEl = (appEl as HTMLElement).querySelector("#main");
renderSidebarTop();
updateSidebarToggleLabels();
syncSidebarAccessibility(false);
shellMounted = true;
}
export function renderSidebarTop(): void {
syncDocumentTitle();
if (!appState.topEl) return;
const navRow = (v: View, glyph: IconNode, label: string) =>
html`<a
class="navrow ${appState.currentView === v ? "active" : ""}"
href=${deepLinkPath(UI_BASE, v, null)}
data-view=${v}
title=${label}
>
${icon(glyph, 17)}<span>${label}</span>
</a>`;
const navGroup = (id: string, title: string, open: boolean, toggle: () => void, rows: TemplateResult) => html`
<button
class="nav-section-toggle"
type="button"
aria-expanded=${open ? "true" : "false"}
aria-controls=${id}
title=${open ? `Hide ${title}` : `Show ${title}`}
@click=${toggle}
>
<span>${title}</span>
<span class="nav-section-chevron">${icon(ChevronDown, 14)}</span>
</button>
<div id=${id} class="nav-group ${open ? "" : "collapsed"}">
<div class="nav-group-inner">${rows}</div>
</div>
`;
render(
html`
<button
class="new-chat"
title="New chat"
@click=${() => {
closeSidebarOnNarrowView();
openBlankInFocusedPane();
}}
>
${icon(ICON.newChat, 17)}<span>New chat</span>
</button>
<nav class="nav" @click=${onNavClick}>
${navGroup(
"nav-workspace",
"Browse",
navWorkspaceOpen,
toggleNavWorkspace,
html`
${navRow("contexts", ICON.contexts, "Projects")} ${navRow("chats", ICON.chats, "Chats")}
${navRow("files", ICON.files, "Files")} ${navRow("crons", ICON.crons, "Crons")}
${navRow("webhooks", ICON.webhooks, "Webhooks")} ${navRow("keychain", ICON.keychain, "Keychain")}
${navRow("deploys", ICON.deploys, "Apps")} ${navRow("memory", ICON.memory, "Memory")}
${navRow("skills", ICON.skills, "Skills")}
${
can("admin")
? html`<a class="navrow" href=${ADMIN_HOME_URL} title="Admin">
${icon(ShieldCheck, 17)}<span>Admin</span>
</a>`
: nothing
}
`,
)}
</nav>
${
sessionSelectionBar() ??
html`
<div class="section-label recents-label">
<span>Sessions</span>
<button
class="chat-search-open"
type="button"
aria-label="Search your chats"
@click=${() => {
hideTooltip();
openChatSearch();
}}
@mouseenter=${(e: Event) => showTooltip(e.currentTarget as Element, `Search your chats · ${SEARCH_HOTKEY_LABEL}`)}
@mouseleave=${(e: Event) => hideTooltip(e.currentTarget as Element)}
@focus=${(e: Event) => showTooltip(e.currentTarget as Element, `Search your chats · ${SEARCH_HOTKEY_LABEL}`)}
@blur=${(e: Event) => hideTooltip(e.currentTarget as Element)}
>
${icon(Search, 13)}
</button>
<button
class="web-only-toggle ${sessionsState.webOnly ? "on" : ""}"
type="button"
role="switch"
aria-checked=${sessionsState.webOnly ? "true" : "false"}
title=${sessionsState.webOnly ? "Showing web chats only" : "Hide non-web conversations"}
@click=${toggleWebOnly}
>
<span>Web only</span><span class="mini-switch"><span class="mini-knob"></span></span>
</button>
</div>
`
}
`,
appState.topEl,
);
}
export function syncDocumentTitle(): void {
if (!appState.me) {
updateDocumentTitle();
return;
}
const state = mainConversation().state;
const active = splitState.active
? focusedPaneSession()
: activeSessionForDocumentTitle(sessionsState.list, {
openingKey: sessionsState.openingKey,
sessionId: state.sessionId,
threadRef: state.threadRef,
});
updateDocumentTitle(
appState.currentView,
active ? sessionTitle(active) : null,
Boolean(active || (!splitState.active && state.threadRef)),
);
}
function onNavClick(e: Event): void {
const target = e.target as Element | null;
const row = target?.closest<HTMLAnchorElement>(".navrow[data-view]");
const view = row?.dataset.view;
if (!isView(view)) return;
if (e instanceof MouseEvent && !isPlainLeftClick(e)) return;
e.preventDefault();
setScopedSession(null);
switchView(view);
closeSidebarOnNarrowView();
}
export function switchView(v: View): void {
closeSidebarOnNarrowView();
if (appState.currentView === v) {
refreshActiveView(v);
return;
}
appState.currentView = v;
appState.viewRenderSeq++;
sessionsState.openMenuId = null;
sessionsState.renamingId = null;
if (v !== "chats") {
mainConversation().teardown();
mainConversation().composer.resetComposer();
}
renderSidebarTop();
syncUrlFromState();
switch (v) {
case "chats":
mountRestoredCanvas();
drawCanvas();
renderList();
break;
case "webhooks":
resetActiveWebhook();
void renderWebhooksPage();
break;
case "crons":
resetActiveCron();
void renderCronsPage();
break;
case "contexts":
void renderContexts();
break;
case "files":
void renderFiles();
break;
case "keychain":
void renderConnectors();
break;
case "deploys":
void renderDeploys();
break;
case "memory":
void renderMemory();
break;
case "skills":
void renderSkills();
break;
}
}
function refreshActiveView(v: View): void {
switch (v) {
case "chats":
void refreshSessions({ silent: true, refreshContexts: true });
break;
case "contexts":
void renderContexts();
break;
case "webhooks":
void renderWebhooksPage();
break;
case "crons":
void renderCronsPage();
break;
case "files":
void renderFiles();
break;
case "keychain":
clearConnectorNotice();
void renderConnectors();
break;
case "deploys":
void renderDeploys();
break;
case "memory":
void renderMemory();
break;
case "skills":
void renderSkills();
break;
}
}
export function showMainEmpty(text: string): void {
exitSplitIfActive();
mainConversation().state.host = null;
if (appState.mainEl)
appState.mainEl.replaceChildren(
Object.assign(document.createElement("div"), { className: "empty", textContent: text }),
);
}
function toggleSidebar(): void {
setSidebarOpen(!sidebarOpen);
}
export function closeSidebarOnNarrowView(): void {
if (!narrowViewport.matches || !sidebarOpen) return;
setSidebarOpen(false, false);
requestAnimationFrame(() => appState.mainEl?.focus({ preventScroll: true }));
}
narrowViewport.addEventListener("change", (event) => {
if (event.matches && sidebarOpen) setSidebarOpen(false, false);
else syncSidebarAccessibility(false);
});
function setSidebarOpen(open: boolean, moveFocus = true): void {
sidebarOpen = open;
(appEl as HTMLElement).querySelector(".layout")?.classList.toggle("sidebar-closed", !sidebarOpen);
updateSidebarToggleLabels();
syncSidebarAccessibility(moveFocus);
}
function syncSidebarAccessibility(moveFocus: boolean): void {
const root = appEl as HTMLElement;
const sidebar = root.querySelector<HTMLElement>(".sidebar");
const main = root.querySelector<HTMLElement>(".main");
const scrim = root.querySelector<HTMLButtonElement>(".sidebar-scrim");
const modal = narrowViewport.matches && sidebarOpen;
if (!sidebar || !main || !scrim) return;
main.inert = modal;
sidebar.setAttribute("role", modal ? "dialog" : "navigation");
if (modal) sidebar.setAttribute("aria-modal", "true");
else sidebar.removeAttribute("aria-modal");
scrim.hidden = !modal;
if (!moveFocus || !narrowViewport.matches) return;
requestAnimationFrame(() => sidebar.querySelector<HTMLElement>(".sidebar-collapse-toggle")?.focus());
}
function onSidebarKeydown(event: KeyboardEvent): void {
if (!narrowViewport.matches || !sidebarOpen) return;
if (event.key === "Escape" && event.defaultPrevented) return;
if (event.key === "Escape" && closeOpenSessionMenu()) {
event.preventDefault();
event.stopPropagation();
return;
}
trapDialogFocus(event, () => setSidebarOpen(false));
}
function updateSidebarToggleLabels(): void {
const collapseLabel = sidebarOpen ? "Hide sidebar" : "Show sidebar";
(appEl as HTMLElement).querySelectorAll<HTMLButtonElement>(".sidebar-toggle").forEach((btn) => {
btn.setAttribute("aria-expanded", sidebarOpen ? "true" : "false");
btn.setAttribute("title", collapseLabel);
btn.setAttribute("aria-label", collapseLabel);
});
}
export function renderPane(
title: string,
status: string,
onRefresh: () => void,
cards: unknown,
controls: unknown = "",
): void {
if (!appState.mainEl) return;
const refreshLabel = `Refresh ${title.toLowerCase()}`;
const host = document.createElement("div");
host.className = "pane";
render(
html`
<div class="pane-head">
<h1 class="pane-title">${title}</h1>
<div class="list-page-actions">
${controls}
<button
class="pane-refresh"
type="button"
aria-label=${refreshLabel}
title=${refreshLabel}
@click=${onRefresh}
>
${icon(RefreshCw, 17)}
</button>
</div>
</div>
${status ? html`<div class="status">${status}</div>` : ""}
<div class="grid">${cards}</div>
`,
host,
);
replacePanePreservingFocus(host);
}
export function replacePanePreservingFocus(host: HTMLElement): void {
if (!appState.mainEl) return;
replaceChildrenPreservingFocus(appState.mainEl, host);
}
window.addEventListener("popstate", () => {
if (appState.currentView !== "crons" && appState.currentView !== "webhooks") return;
const { view, item } = parseDeepLink(UI_BASE, location.pathname, location.search);
if (view !== appState.currentView) return;
if (view === "crons") routeCronsHistory(item);
else routeWebhooksHistory(item);
});
window.addEventListener("focus", () => {
if (!appState.me) return;
if (appState.currentView === "contexts") void renderContexts();
else if (appState.currentView === "chats") void refreshSessions({ silent: true, refreshContexts: true });
});
function warmDeferredChunks(): void {
const warm = (): void => void import("@earendil-works/pi-web-ui").catch(() => {});
const ric = (window as unknown as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback;
if (ric) ric(warm);
else setTimeout(warm, 1500);
}
function openAppEditChat(slug: string): void {
const user = appState.me?.user ?? "anon";
const threadRef = `web:${user}:app-edit:${slug}`;
const existing = sessionsState.list.find((s) => s.threadRef === threadRef);
if (existing) {
void openSession(existing);
return;
}
if (!storedDraft(threadRef)) saveDraft(threadRef, `Update my deployed app "${slug}": `);
openThreadInFocusedPane(threadRef);
renderList();
}
export async function bootSafely(): Promise<void> {
try {
await boot();
} catch (e) {
if (shellMounted) swallow("web-ui: boot", e);
else renderAuthGate({ kind: "unreachable" });
}
}
export async function boot(): Promise<void> {
let r: Response;
try {
r = await fetch(withBase("/me"));
} catch {
renderAuthGate({ kind: "unreachable" });
return;
}
if (r.status === 401) {
const body = (await r.json().catch(() => ({}))) as SigninRequired;
authMode = body.mode ?? "portal";
renderAuthGate(gateFor(authMode, body.reason));
return;
}
if (!r.ok) {
renderAuthGate({ kind: "unreachable" });
return;
}
resetKeychainState();
appState.me = (await r.json()) as Me;
authMode = appState.me.mode ?? "portal";
clearPortalAttempt();
const personalScope = `personal:${appState.me.user}`;
const runtimeConfig = await fetchRuntimeConfig(personalScope);
if (runtimeConfig) {
applyRuntimeOptions(
personalScope,
runtimeConfig.approvedHarnesses,
runtimeConfig.modelsByHarness,
runtimeConfig.effective,
runtimeConfig.modelCatalog,
);
seedRuntimeConfig(personalScope, runtimeConfig);
}
resyncModelSelection();
mountShell();
ensureDeliveryStream();
warmDeferredChunks();
loadPersistedSplit();
await adoptRemoteSplit();
const params = new URLSearchParams(location.search);
const {
view: wanted,
session: wantedSession,
item: wantedItem,
} = parseDeepLink(UI_BASE, location.pathname, location.search);
const connectedProvider = params.get("status") === "connected" ? params.get("connector") : null;
if (connectedProvider) markConnectorConnected(connectedProvider);
const viewIntent = isView(wanted) && wanted !== "chats";
const entriesPrefetch =
wantedSession && !viewIntent ? fetchTranscript(wantedSession, { tailTurns: TAIL_TURNS }).catch(() => null) : null;
const bareEntry = !viewIntent && !wantedSession && wanted !== "app-edit" && !connectedProvider;
if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas();
await refreshSessions({ showLoading: true });
if (wanted === "app-edit") {
const slug = (params.get("slug") ?? "").toLowerCase();
if (/^[a-z0-9-]{1,63}$/.test(slug)) {
openAppEditChat(slug);
return;
}
showMainEmpty("This edit link is missing a valid app name.");
return;
}
if (wanted === "keychain") {
const provider = params.get("connector");
const status = params.get("status");
if (provider && status) noteConnectorResult(provider, status);
switchView("keychain");
} else if (viewIntent) {
if (wanted === "contexts" || wanted === "files" || wanted === "deploys") {
const scope =
params.get("scope") ?? (wantedItem ? resolveProjectScope(await ensureContexts(), wantedItem) : null);
if (scope) contextsState.selected = scope;
}
if (wanted === "crons" && wantedItem) openCronById(wantedItem);
if (wanted === "webhooks" && wantedItem) openWebhookById(wantedItem);
switchView(wanted as View);
} else if (wantedSession) {
const match = sessionsState.list.find((s) => s.id === wantedSession);
if (match) {
mountRestoredCanvas();
await openSession(match, entriesPrefetch ?? undefined);
} else if (mountRestoredCanvas()) {
canvasToast("That conversation wasn't found, or you don't have access to it.");
syncUrlFromState();
} else {
showMainEmpty("That conversation wasn't found, or you don't have access to it.");
renderList();
}
} else if (connectedProvider && sessionsState.list.length) {
const recent = [...sessionsState.list].sort((a, b) => activityOf(b) - activityOf(a))[0]!;
mountRestoredCanvas();
await openSession(recent);
} else {
mountRestoredCanvas();
}
}