@devries-cameron20 / t3code Mirror · read-only
Fork 0

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 21, 03:37 UTC

main
ts 1,487 lines 58.2 KB
Raw
1 import {
2 parseScopedThreadKey,
3 scopedThreadKey,
4 scopeThreadRef,
5 } from "@t3tools/client-runtime/environment";
6 import { EnvironmentId, RunId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
7 import { msg } from "gt-react";
8 import { create } from "zustand";
9 import { createJSONStorage, persist } from "zustand/middleware";
10
11 import { useClosedViewStore } from "./closedViewStore";
12 import { m } from "./i18n/messages";
13 import { resolveStorage } from "./lib/storage";
14 import type { LinkedThreadTarget } from "@t3tools/client-runtime/linked-thread";
15 import {
16 decodeLinkedThreadSurface,
17 linkedThreadSurface,
18 type LinkedThreadSurface,
19 } from "./linkedThreadSurface";
20 import type { ThreadPanelPresentation } from "./rightPanelLayout";
21 import type { ChatFileAttachment } from "./types";
22
23 const RIGHT_PANEL_KINDS = [
24 "diff",
25 "files",
26 "file",
27 "preview",
28 "device",
29 "terminal",
30 "pull-request",
31 "pull-requests",
32 "issue",
33 "thread",
34 "linked-thread",
35 ] as const;
36 export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
37
38 export type PullRequestDetailTab = "summary" | "guide" | "timeline" | "code";
39
40 export interface DeviceTabTarget {
41 hostId: string;
42 deviceId: string;
43 platform: "ios" | "android";
44 name: string;
45 }
46
47 export type RightPanelSurface =
48 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
49 | { id: "browser:new"; kind: "preview"; resourceId: null }
50 | { id: "device" | `device:${string}`; kind: "device"; target?: DeviceTabTarget; title?: string }
51 | {
52 id: `terminal:${string}`;
53 kind: "terminal";
54 resourceId: string;
55 terminalIds: string[];
56 activeTerminalId: string;
57 splitDirection?: "horizontal" | "vertical";
58 }
59 | { id: "diff"; kind: "diff" }
60 | {
61 id: "files";
62 kind: "files";
63 /** Set when breadcrumbs moved a folder browser up to the workspace root. */
64 folderTrail?: string;
65 }
66 | {
67 id: `file:${string}` | `attachment:${string}`;
68 kind: "file";
69 relativePath: string;
70 revealLine: number | null;
71 revealRequestId: number;
72 attachment?: ChatFileAttachment;
73 /** Deepest workspace path retained for navigating back down after moving up. */
74 folderTrail?: string;
75 }
76 | {
77 id: `pull-request:${string}`;
78 kind: "pull-request";
79 /** Cross-environment lists can repeat project ids; thread panels inherit their ref's environment. */
80 environmentId?: string;
81 projectId: string;
82 host?: string;
83 repository: string;
84 number: number;
85 url?: string;
86 /** A clicked link waiting for the panel to show where it points; cleared once shown. */
87 revealUrl?: string;
88 detailTab?: PullRequestDetailTab;
89 }
90 | { id: "pull-requests"; kind: "pull-requests" }
91 /**
92 * An issue opened in the issues list's shared panel, or beside a thread. Like `pull-request`,
93 * the reference lives in the id so several issues can stay open as peer tabs.
94 */
95 | {
96 id: `issue:${string}`;
97 kind: "issue";
98 environmentId?: string;
99 projectId: string;
100 tracker: string;
101 host?: string;
102 scope: string;
103 key: string;
104 url?: string;
105 }
106 /**
107 * A thread of the panel's environment shown beside it: a side chat or a subagent. Which one is
108 * the thread's own lineage, so the surface only names it.
109 */
110 | ThreadSurface
111 /** A linked environment's thread, read through `viaEnvironmentId`; it has no thread here. */
112 | LinkedThreadSurface;
113
114 export type ThreadSurface = { id: `thread:${string}`; kind: "thread"; threadId: ThreadId };
115
116 const threadSurface = (threadId: ThreadId): ThreadSurface => ({
117 id: `thread:${threadId}`,
118 kind: "thread",
119 threadId,
120 });
121
122 /**
123 * A saved thread surface with its id rebuilt, or null when it names no thread. Builds before
124 * subagents opened here saved it as `side-chat`.
125 */
126 export function decodeThreadSurface(surface: object): ThreadSurface | null {
127 const { kind, threadId } = surface as Record<string, unknown>;
128 if ((kind !== "thread" && kind !== "side-chat") || typeof threadId !== "string") return null;
129 return threadId === "" ? null : threadSurface(ThreadId.make(threadId));
130 }
131
132 const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
133 const RIGHT_PANEL_STORAGE_VERSION = 16;
134
135 export const PULL_REQUESTS_PANEL_REF = scopeThreadRef(
136 EnvironmentId.make("pull-requests-panel"),
137 ThreadId.make("pull-requests-panel"),
138 );
139
140 /** The issues page's shared panel, with the same fixed sentinel ref as the pull-request list. */
141 export const ISSUES_PANEL_REF = scopeThreadRef(
142 EnvironmentId.make("issues-panel"),
143 ThreadId.make("issues-panel"),
144 );
145
146 /**
147 * The pull-request and issues lists' shared panels are session
148 * state: reopening the app should show the list, not last session's tabs and detail fetches.
149 */
150 const isPullRequestsPanelKey = (threadKey: string) =>
151 threadKey.endsWith(":pull-requests-panel") || threadKey.endsWith(":issues-panel");
152
153 export interface ThreadRightPanelState {
154 isOpen: boolean;
155 activeSurfaceId: string | null;
156 surfaces: RightPanelSurface[];
157 dismissedDeviceSurfaceIds?: string[];
158 maximized?: true;
159 proactiveDiffTurnId?: RunId;
160 }
161
162 export interface ThreadPanelVisibility {
163 inlineOpen: boolean;
164 popoverOpen: boolean;
165 }
166
167 interface RightPanelStoreState {
168 byThreadKey: Record<string, ThreadRightPanelState>;
169 pendingMaximizeThreadKey: string | null;
170 requestMaximize: (ref: ScopedThreadRef) => void;
171 consumeMaximizeRequest: (ref: ScopedThreadRef) => boolean;
172 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
173 userActionRevisionByThreadKey: Record<string, number>;
174 closeRevisionByThreadKey: Record<string, number>;
175 getUserActionRevision: (ref: ScopedThreadRef) => number;
176 markUserAction: (ref: ScopedThreadRef) => number;
177 /** Refused if the user chose a panel after expectedUserActionRevision was read. */
178 openProactive: (
179 ref: ScopedThreadRef,
180 request:
181 | Extract<RightPanelSurface, { kind: "pull-request" | "pull-requests" }>
182 | { kind: "diff"; turnId: RunId },
183 expectedUserActionRevision: number,
184 activateExisting?: boolean,
185 ) => boolean;
186 open: (
187 ref: ScopedThreadRef,
188 kind: Exclude<
189 RightPanelKind,
190 "file" | "terminal" | "pull-request" | "issue" | "thread" | "linked-thread"
191 >,
192 ) => void;
193 /** Opens a side chat or subagent of `ref`'s environment as a tab; `ref` itself has no tab. */
194 openThread: (ref: ScopedThreadRef, threadId: ThreadId) => void;
195 openLinkedThread: (ref: ScopedThreadRef, target: LinkedThreadTarget) => void;
196 /** Records the title the linked environment gave, so the tab and a reopened one show it. */
197 setLinkedThreadTitle: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
198 openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;
199 renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
200 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
201 openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
202 /** Moves in place; "" opens the root explorer. folderTrail keeps the return path; keepSource opens beside the source. */
203 navigateFolder: (
204 ref: ScopedThreadRef,
205 surfaceId: string,
206 relativePath: string,
207 folderTrail: string,
208 keepSource?: boolean,
209 ) => void;
210 openAttachment: (ref: ScopedThreadRef, attachment: ChatFileAttachment) => void;
211 openPullRequest: (
212 ref: ScopedThreadRef,
213 target: {
214 environmentId?: string;
215 projectId: string;
216 host?: string;
217 repository: string;
218 number: number;
219 url?: string;
220 /** A clicked link to reveal; reopening a surface passes only its `url`. */
221 revealUrl?: string;
222 detailTab?: PullRequestDetailTab;
223 },
224 ) => void;
225 openIssue: (ref: ScopedThreadRef, target: IssueSurfaceTarget) => void;
226 setPullRequestDetailTab: (
227 ref: ScopedThreadRef,
228 surfaceId: string,
229 detailTab: PullRequestDetailTab,
230 ) => void;
231 /** Clears the surface's pending link only while it is still `revealUrl`. */
232 settlePullRequestReveal: (ref: ScopedThreadRef, surfaceId: string, revealUrl: string) => void;
233 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
234 splitTerminal: (
235 ref: ScopedThreadRef,
236 surfaceId: string,
237 terminalId: string,
238 direction?: "horizontal" | "vertical",
239 ) => void;
240 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
241 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
242 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
243 /** Agent-driven activation. Not a user action, so it does not move keyboard focus. */
244 revealSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
245 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
246 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
247 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
248 closeAllSurfaces: (ref: ScopedThreadRef) => void;
249 moveSurface: (ref: ScopedThreadRef, surfaceId: string, toIndex: number) => void;
250 reconcileBrowserSurfaces: (
251 ref: ScopedThreadRef,
252 tabIds: readonly string[],
253 hiddenTabIds?: ReadonlySet<string>,
254 ) => void;
255 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
256 show: (ref: ScopedThreadRef) => void;
257 close: (ref: ScopedThreadRef) => void;
258 setMaximized: (ref: ScopedThreadRef, maximized: boolean) => void;
259 toggleVisibility: (ref: ScopedThreadRef) => void;
260 toggle: (
261 ref: ScopedThreadRef,
262 kind: Exclude<
263 RightPanelKind,
264 "file" | "terminal" | "pull-request" | "issue" | "thread" | "linked-thread"
265 >,
266 ) => void;
267 setThreadPanelOpen: (
268 ref: ScopedThreadRef,
269 presentation: ThreadPanelPresentation,
270 open: boolean,
271 ) => void;
272 toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
273 removeThread: (ref: ScopedThreadRef) => void;
274 }
275
276 const EMPTY_THREAD_STATE: ThreadRightPanelState = {
277 isOpen: false,
278 activeSurfaceId: null,
279 surfaces: [],
280 };
281
282 const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
283 inlineOpen: true,
284 popoverOpen: false,
285 };
286
287 const singletonSurface = (
288 kind: Exclude<
289 RightPanelKind,
290 "file" | "preview" | "terminal" | "pull-request" | "issue" | "thread" | "linked-thread"
291 >,
292 ): RightPanelSurface => {
293 switch (kind) {
294 case "diff":
295 return { id: "diff", kind };
296 case "files":
297 return { id: "files", kind };
298 case "pull-requests":
299 return { id: "pull-requests", kind };
300 case "device":
301 return { id: "device", kind };
302 }
303 };
304
305 const browserSurface = (tabId: string | null): RightPanelSurface =>
306 tabId
307 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
308 : { id: "browser:new", kind: "preview", resourceId: null };
309
310 const fileSurface = (
311 relativePath: string,
312 revealLine: number | null,
313 revealRequestId: number,
314 ): RightPanelSurface => ({
315 id: `file:${relativePath}`,
316 kind: "file",
317 relativePath,
318 revealLine,
319 revealRequestId,
320 });
321
322 const attachmentSurface = (attachment: ChatFileAttachment): RightPanelSurface => ({
323 id: `attachment:${attachment.id}`,
324 kind: "file",
325 relativePath: attachment.name,
326 revealLine: null,
327 revealRequestId: 0,
328 attachment,
329 });
330
331 const terminalSurface = (terminalId: string): RightPanelSurface => ({
332 id: `terminal:${terminalId}`,
333 kind: "terminal",
334 resourceId: terminalId,
335 terminalIds: [terminalId],
336 activeTerminalId: terminalId,
337 });
338
339 export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
340
341 export function pullRequestSurfaceId(target: {
342 environmentId?: string;
343 projectId: string;
344 host?: string;
345 repository: string;
346 number: number;
347 }): PullRequestSurface["id"] {
348 const scope =
349 target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
350 const host = target.host === undefined ? "" : `${encodeURIComponent(target.host.toLowerCase())}:`;
351 return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${host}${encodeURIComponent(target.repository)}:${target.number}`;
352 }
353
354 export type IssueSurface = Extract<RightPanelSurface, { kind: "issue" }>;
355
356 export interface IssueSurfaceTarget {
357 environmentId?: string;
358 projectId: string;
359 tracker: string;
360 host?: string;
361 scope: string;
362 key: string;
363 url?: string;
364 }
365
366 function issueSurfaceId(target: Omit<IssueSurfaceTarget, "url">): IssueSurface["id"] {
367 const environment =
368 target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
369 const host = target.host === undefined ? "" : `${encodeURIComponent(target.host.toLowerCase())}:`;
370 return `issue:${environment}${encodeURIComponent(target.projectId)}:${target.tracker}:${host}${encodeURIComponent(target.scope.toLowerCase())}:${encodeURIComponent(target.key)}`;
371 }
372
373 function issueSurface(target: IssueSurfaceTarget): IssueSurface {
374 return {
375 id: issueSurfaceId(target),
376 kind: "issue",
377 ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
378 projectId: target.projectId,
379 tracker: target.tracker,
380 ...(typeof target.host === "string" ? { host: target.host.toLowerCase() } : {}),
381 scope: target.scope,
382 key: target.key,
383 ...(typeof target.url === "string" ? { url: target.url } : {}),
384 };
385 }
386
387 export function pullRequestSurface(target: {
388 environmentId?: string;
389 projectId: string;
390 host?: string;
391 repository: string;
392 number: number;
393 url?: string;
394 detailTab?: PullRequestDetailTab;
395 }): PullRequestSurface {
396 return {
397 id: pullRequestSurfaceId(target),
398 kind: "pull-request",
399 ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
400 projectId: target.projectId,
401 ...(typeof target.host === "string" ? { host: target.host.toLowerCase() } : {}),
402 repository: target.repository,
403 number: target.number,
404 ...(typeof target.url === "string" ? { url: target.url } : {}),
405 ...(target.detailTab === undefined ? {} : { detailTab: target.detailTab }),
406 };
407 }
408
409 /** A pending link belongs to the click that made it, not to a reload or a reopen. */
410 const withoutReveal = (surface: RightPanelSurface): RightPanelSurface => {
411 if (surface.kind !== "pull-request" || surface.revealUrl === undefined) return surface;
412 const { revealUrl: _pending, ...rest } = surface;
413 return rest;
414 };
415
416 const upsertSurface = (
417 current: ThreadRightPanelState,
418 surface: RightPanelSurface,
419 activate = true,
420 ): ThreadRightPanelState => ({
421 ...current,
422 isOpen: true,
423 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
424 ? current.surfaces
425 : [...current.surfaces, surface],
426 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
427 });
428
429 const updateThreadStateMap = (
430 byThreadKey: Record<string, ThreadRightPanelState>,
431 threadKey: string,
432 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
433 ): Record<string, ThreadRightPanelState> => {
434 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
435 const next = updater(current);
436 if (
437 !next.isOpen &&
438 next.activeSurfaceId === null &&
439 next.surfaces.length === 0 &&
440 !next.dismissedDeviceSurfaceIds?.length &&
441 next.proactiveDiffTurnId === undefined
442 ) {
443 if (!(threadKey in byThreadKey)) return byThreadKey;
444 const { [threadKey]: _removed, ...rest } = byThreadKey;
445 return rest;
446 }
447 if (next === current) return byThreadKey;
448 return { ...byThreadKey, [threadKey]: next };
449 };
450
451 const updateThreadPanelVisibilityMap = (
452 byThreadKey: Record<string, ThreadPanelVisibility>,
453 threadKey: string,
454 updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
455 ): Record<string, ThreadPanelVisibility> => {
456 const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
457 const next = updater(current);
458 if (next.inlineOpen && !next.popoverOpen) {
459 if (!(threadKey in byThreadKey)) return byThreadKey;
460 const { [threadKey]: _removed, ...rest } = byThreadKey;
461 return rest;
462 }
463 if (next === current) return byThreadKey;
464 return { ...byThreadKey, [threadKey]: next };
465 };
466
467 type RightPanelStoreData = Pick<
468 RightPanelStoreState,
469 "byThreadKey" | "threadPanelVisibilityByThreadKey"
470 >;
471
472 const updateThread = (
473 state: RightPanelStoreData,
474 threadKey: string,
475 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
476 ): RightPanelStoreData => {
477 const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
478 const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
479 const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
480 let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
481
482 if (!current.isOpen && next.isOpen) {
483 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
484 threadPanelVisibilityByThreadKey,
485 threadKey,
486 (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
487 );
488 } else if (current.isOpen && !next.isOpen) {
489 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
490 threadPanelVisibilityByThreadKey,
491 threadKey,
492 (visibility) =>
493 visibility.popoverOpen && !visibility.inlineOpen
494 ? { ...visibility, inlineOpen: true }
495 : visibility,
496 );
497 }
498
499 return { byThreadKey, threadPanelVisibilityByThreadKey };
500 };
501
502 const automaticUpdate = (
503 state: RightPanelStoreState,
504 threadKey: string,
505 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
506 ): Partial<RightPanelStoreState> => ({
507 ...updateThread(state, threadKey, updater),
508 });
509
510 // A side chat pane has no panel of its own, so its panel actions open in its parent's panel.
511 const panelHosts = new Map<string, ScopedThreadRef>();
512
513 /** Routes `guest`'s panel actions to `host`'s panel until the returned cleanup runs. */
514 export function hostRightPanel(guest: ScopedThreadRef, host: ScopedThreadRef): () => void {
515 const guestKey = scopedThreadKey(guest);
516 panelHosts.set(guestKey, host);
517 return () => {
518 if (panelHosts.get(guestKey) === host) panelHosts.delete(guestKey);
519 };
520 }
521
522 /** The thread whose panel shows `ref`'s panel actions, so it also owns their browser tabs. */
523 export function rightPanelHostRef(ref: ScopedThreadRef): ScopedThreadRef {
524 return panelHosts.get(scopedThreadKey(ref)) ?? ref;
525 }
526
527 const userAction = (
528 state: RightPanelStoreState,
529 guestKey: string,
530 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
531 closesView = false,
532 ): Partial<RightPanelStoreState> => {
533 const host = panelHosts.get(guestKey);
534 const threadKey = host === undefined ? guestKey : scopedThreadKey(host);
535 return userActionOnThread(state, threadKey, updater, closesView);
536 };
537
538 const userActionOnThread = (
539 state: RightPanelStoreState,
540 threadKey: string,
541 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
542 closesView: boolean,
543 ): Partial<RightPanelStoreState> => ({
544 ...updateThread(state, threadKey, (current) => {
545 const next = updater(current);
546 if (next === current) return current;
547 const removedDevices = current.surfaces.filter(
548 (surface) =>
549 surface.kind === "device" && !next.surfaces.some((entry) => entry.id === surface.id),
550 );
551 if (removedDevices.length === 0) return next;
552 return {
553 ...next,
554 dismissedDeviceSurfaceIds: [
555 ...new Set([
556 ...(next.dismissedDeviceSurfaceIds ?? []),
557 ...removedDevices.map((surface) => surface.id),
558 ]),
559 ],
560 };
561 }),
562 userActionRevisionByThreadKey: {
563 ...state.userActionRevisionByThreadKey,
564 [threadKey]: (state.userActionRevisionByThreadKey[threadKey] ?? 0) + 1,
565 },
566 ...(closesView
567 ? {
568 closeRevisionByThreadKey: {
569 ...state.closeRevisionByThreadKey,
570 [threadKey]: (state.closeRevisionByThreadKey[threadKey] ?? 0) + 1,
571 },
572 }
573 : {}),
574 });
575
576 const activated = (current: ThreadRightPanelState, surfaceId: string): ThreadRightPanelState =>
577 current.surfaces.some((surface) => surface.id === surfaceId)
578 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
579 : current;
580
581 const closeAction = (
582 state: RightPanelStoreState,
583 threadKey: string,
584 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
585 ): Partial<RightPanelStoreState> => userAction(state, threadKey, updater, true);
586
587 function normalizeRevealLine(line: number | undefined): number | null {
588 if (line === undefined || !Number.isFinite(line)) return null;
589 return Math.max(1, Math.trunc(line));
590 }
591
592 export function migratePersistedRightPanelState(persistedState: unknown): {
593 byThreadKey: Record<string, ThreadRightPanelState>;
594 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
595 } {
596 if (!persistedState || typeof persistedState !== "object") {
597 return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
598 }
599 const byThreadKey =
600 "byThreadKey" in persistedState &&
601 persistedState.byThreadKey &&
602 typeof persistedState.byThreadKey === "object"
603 ? Object.fromEntries(
604 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>)
605 .filter(([threadKey]) => !isPullRequestsPanelKey(threadKey))
606 .map(([threadKey, threadState]) => {
607 const validThreadState =
608 threadState && typeof threadState === "object" ? threadState : null;
609 const surfaces = Array.isArray(validThreadState?.surfaces)
610 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
611 if (!surface || typeof surface !== "object") return [];
612 const kind = (surface as { kind?: string }).kind;
613 if (kind === "thread" || kind === "side-chat") {
614 const decoded = decodeThreadSurface(surface);
615 return decoded === null ? [] : [decoded];
616 }
617 // Also drops kinds this build does not know, such as one a newer build saved.
618 if (!(RIGHT_PANEL_KINDS as ReadonlyArray<unknown>).includes(kind)) return [];
619 if (surface.kind === "linked-thread") {
620 const decoded = decodeLinkedThreadSurface(surface);
621 return decoded === null ? [] : [decoded];
622 }
623 if (
624 (surface.kind === "file" || surface.kind === "files") &&
625 "folderTrail" in surface &&
626 typeof surface.folderTrail !== "string"
627 ) {
628 const { folderTrail: _invalid, ...rest } = surface;
629 surface = rest;
630 }
631 if (surface.kind === "file") {
632 const revealLine =
633 typeof surface.revealLine === "number" &&
634 Number.isFinite(surface.revealLine)
635 ? Math.max(1, Math.trunc(surface.revealLine))
636 : null;
637 const revealRequestId =
638 typeof surface.revealRequestId === "number" &&
639 Number.isSafeInteger(surface.revealRequestId) &&
640 surface.revealRequestId >= 0
641 ? surface.revealRequestId
642 : 0;
643 return [{ ...surface, revealLine, revealRequestId }];
644 }
645 if (surface.kind === "pull-request") {
646 if (
647 typeof surface.projectId !== "string" ||
648 typeof surface.repository !== "string" ||
649 typeof surface.number !== "number" ||
650 !Number.isSafeInteger(surface.number) ||
651 surface.number < 1
652 ) {
653 return [];
654 }
655 const { environmentId, ...rest } = surface;
656 return [
657 pullRequestSurface({
658 ...rest,
659 ...(typeof environmentId === "string" ? { environmentId } : {}),
660 }),
661 ];
662 }
663 if (surface.kind === "issue") {
664 if (
665 typeof surface.projectId !== "string" ||
666 typeof surface.tracker !== "string" ||
667 typeof surface.scope !== "string" ||
668 typeof surface.key !== "string"
669 ) {
670 return [];
671 }
672 const { environmentId, ...rest } = surface;
673 return [
674 issueSurface({
675 ...rest,
676 ...(typeof environmentId === "string" ? { environmentId } : {}),
677 }),
678 ];
679 }
680 if (surface.kind !== "terminal") return [surface];
681 if (
682 !("resourceId" in surface) ||
683 typeof surface.resourceId !== "string" ||
684 surface.id !== `terminal:${surface.resourceId}`
685 ) {
686 return [];
687 }
688 const terminalIds =
689 "terminalIds" in surface && Array.isArray(surface.terminalIds)
690 ? [
691 ...new Set(
692 surface.terminalIds.filter(
693 (terminalId): terminalId is string =>
694 typeof terminalId === "string",
695 ),
696 ),
697 ]
698 : [surface.resourceId];
699 const activeTerminalId =
700 "activeTerminalId" in surface &&
701 typeof surface.activeTerminalId === "string" &&
702 terminalIds.includes(surface.activeTerminalId)
703 ? surface.activeTerminalId
704 : (terminalIds[0] ?? surface.resourceId);
705 return [
706 {
707 ...surface,
708 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
709 activeTerminalId,
710 },
711 ];
712 })
713 : [];
714 const savedActiveSurfaceId = validThreadState?.activeSurfaceId;
715 const rawActiveSurfaceId =
716 typeof savedActiveSurfaceId === "string" &&
717 savedActiveSurfaceId.startsWith("side-chat:")
718 ? `thread:${savedActiveSurfaceId.slice("side-chat:".length)}`
719 : savedActiveSurfaceId;
720 const persistedActiveSurfaceId = surfaces.some(
721 (surface) => surface.id === rawActiveSurfaceId,
722 )
723 ? (rawActiveSurfaceId ?? null)
724 : rawActiveSurfaceId === "pull-request"
725 ? (surfaces.find((surface) => surface.kind === "pull-request")?.id ?? null)
726 : null;
727 const isOpen =
728 surfaces.length > 0 &&
729 (typeof validThreadState?.isOpen === "boolean"
730 ? validThreadState.isOpen
731 : persistedActiveSurfaceId !== null);
732 const activeSurfaceId =
733 persistedActiveSurfaceId ??
734 (isOpen || rawActiveSurfaceId === "agents" ? (surfaces[0]?.id ?? null) : null);
735 return [
736 threadKey,
737 {
738 isOpen,
739 surfaces,
740 activeSurfaceId,
741 ...(typeof validThreadState?.proactiveDiffTurnId === "string"
742 ? { proactiveDiffTurnId: RunId.make(validThreadState.proactiveDiffTurnId) }
743 : {}),
744 ...(Array.isArray(validThreadState?.dismissedDeviceSurfaceIds)
745 ? {
746 dismissedDeviceSurfaceIds:
747 validThreadState.dismissedDeviceSurfaceIds.filter(
748 (id): id is string => typeof id === "string",
749 ),
750 }
751 : {}),
752 ...(validThreadState?.maximized === true ? { maximized: true as const } : {}),
753 },
754 ];
755 }),
756 )
757 : {};
758 const threadPanelVisibilityByThreadKey =
759 "threadPanelVisibilityByThreadKey" in persistedState &&
760 persistedState.threadPanelVisibilityByThreadKey &&
761 typeof persistedState.threadPanelVisibilityByThreadKey === "object"
762 ? Object.fromEntries(
763 Object.entries(
764 persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
765 ).flatMap(([threadKey, value]) => {
766 if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
767 return value.inlineOpen === false
768 ? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
769 : [];
770 }),
771 )
772 : {};
773 return { byThreadKey, threadPanelVisibilityByThreadKey };
774 }
775
776 export const useRightPanelStore = create<RightPanelStoreState>()(
777 persist(
778 (set, get) => ({
779 byThreadKey: {},
780 pendingMaximizeThreadKey: null,
781 requestMaximize: (ref) => set({ pendingMaximizeThreadKey: scopedThreadKey(ref) }),
782 consumeMaximizeRequest: (ref) => {
783 if (get().pendingMaximizeThreadKey !== scopedThreadKey(ref)) return false;
784 set({ pendingMaximizeThreadKey: null });
785 return true;
786 },
787 threadPanelVisibilityByThreadKey: {},
788 userActionRevisionByThreadKey: {},
789 closeRevisionByThreadKey: {},
790 getUserActionRevision: (ref) =>
791 get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0,
792 markUserAction: (ref) => {
793 const revision = get().getUserActionRevision(ref) + 1;
794 set((state) => ({
795 userActionRevisionByThreadKey: {
796 ...state.userActionRevisionByThreadKey,
797 [scopedThreadKey(ref)]: revision,
798 },
799 }));
800 return revision;
801 },
802 openProactive: (ref, request, expectedUserActionRevision, activateExisting = false) => {
803 let opened = false;
804 set((state) => {
805 const threadKey = scopedThreadKey(ref);
806 if (request.kind === "diff") {
807 const current = selectThreadRightPanelState(state.byThreadKey, ref);
808 if (current.proactiveDiffTurnId === request.turnId) return state;
809 const activePanel = selectActiveRightPanel(state.byThreadKey, ref);
810 const pullRequestActive =
811 activePanel === "pull-request" || activePanel === "pull-requests";
812 opened =
813 (state.userActionRevisionByThreadKey[threadKey] ?? 0) ===
814 expectedUserActionRevision &&
815 activePanel !== "diff" &&
816 !pullRequestActive;
817 // Record the offer even when refused, so a revisit does not retry this turn.
818 return automaticUpdate(state, threadKey, (thread) => ({
819 ...(opened ? upsertSurface(thread, singletonSurface("diff")) : thread),
820 proactiveDiffTurnId: request.turnId,
821 }));
822 }
823 if (
824 (state.userActionRevisionByThreadKey[threadKey] ?? 0) !== expectedUserActionRevision
825 ) {
826 return state;
827 }
828 // Keep an existing PR tab where the user left it when revisiting a thread.
829 if (
830 !activateExisting &&
831 selectThreadRightPanelState(state.byThreadKey, ref).surfaces.some(
832 (entry) => entry.id === request.id,
833 )
834 ) {
835 return state;
836 }
837 opened = true;
838 return automaticUpdate(state, threadKey, (current) => upsertSurface(current, request));
839 });
840 return opened;
841 },
842 open: (ref, kind) =>
843 set((state) =>
844 userAction(state, scopedThreadKey(ref), (current) => {
845 if (kind === "preview") {
846 const existing = current.surfaces.find((surface) => surface.kind === "preview");
847 return upsertSurface(current, existing ?? browserSurface(null));
848 }
849 return upsertSurface(current, singletonSurface(kind));
850 }),
851 ),
852 openDevice: (ref, target, automatic = false) =>
853 set((state) =>
854 (automatic ? automaticUpdate : userAction)(state, scopedThreadKey(ref), (current) => {
855 const id =
856 `device:${encodeURIComponent(target.hostId)}:${encodeURIComponent(target.deviceId)}` as const;
857 if (automatic && current.dismissedDeviceSurfaceIds?.includes(id)) return current;
858 const surface: RightPanelSurface = { id, kind: "device", target };
859 const existing = current.surfaces.find((entry) => entry.id === id);
860 const surfaces = existing
861 ? current.surfaces.filter((entry) => entry.id !== "device")
862 : current.surfaces.map((entry) => (entry.id === "device" ? surface : entry));
863 return upsertSurface(
864 {
865 ...current,
866 surfaces,
867 dismissedDeviceSurfaceIds: (current.dismissedDeviceSurfaceIds ?? []).filter(
868 (entry) => entry !== id,
869 ),
870 },
871 existing ?? surface,
872 );
873 }),
874 ),
875 openThread: (ref, threadId) =>
876 set((state) =>
877 rightPanelHostRef(ref).threadId === threadId
878 ? state
879 : userAction(state, scopedThreadKey(ref), (current) =>
880 upsertSurface(current, threadSurface(threadId)),
881 ),
882 ),
883 openLinkedThread: (ref, target) =>
884 set((state) =>
885 userAction(state, scopedThreadKey(ref), (current) => {
886 const surface = linkedThreadSurface(target);
887 const next = upsertSurface(current, surface);
888 return {
889 ...next,
890 // A later click may know the title or label an earlier one did not.
891 surfaces: next.surfaces.map((entry) =>
892 entry.id === surface.id && entry.kind === "linked-thread"
893 ? { ...surface, title: surface.title ?? entry.title }
894 : entry,
895 ),
896 };
897 }),
898 ),
899 setLinkedThreadTitle: (ref, surfaceId, title) =>
900 set((state) => {
901 const threadKey = scopedThreadKey(rightPanelHostRef(ref));
902 const existing = state.byThreadKey[threadKey]?.surfaces.find(
903 (surface) => surface.id === surfaceId,
904 );
905 if (existing?.kind !== "linked-thread" || existing.title === title) return state;
906 return automaticUpdate(state, threadKey, (current) => ({
907 ...current,
908 surfaces: current.surfaces.map((surface) =>
909 surface.id === surfaceId && surface.kind === "linked-thread"
910 ? { ...surface, title }
911 : surface,
912 ),
913 }));
914 }),
915 renameDevice: (ref, surfaceId, title) =>
916 set((state) =>
917 userAction(state, scopedThreadKey(ref), (current) => ({
918 ...current,
919 surfaces: current.surfaces.map((surface) =>
920 surface.id === surfaceId && surface.kind === "device"
921 ? {
922 ...surface,
923 title:
924 title.trim() ||
925 surface.target?.name ||
926 m(msg("Device", { $context: "a simulator or emulator" })),
927 }
928 : surface,
929 ),
930 })),
931 ),
932 openBrowser: (ref, tabId) =>
933 set((state) =>
934 userAction(state, scopedThreadKey(ref), (current) => {
935 const surface = browserSurface(tabId);
936 const withoutPlaceholder = tabId
937 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
938 : current.surfaces;
939 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
940 }),
941 ),
942 openPullRequest: (ref, target) =>
943 set((state) =>
944 userAction(state, scopedThreadKey(ref), (current) => {
945 const surface = pullRequestSurface(target);
946 const next = upsertSurface(current, surface);
947 const { url, revealUrl } = target;
948 if (!url && !revealUrl) return next;
949 return {
950 ...next,
951 surfaces: next.surfaces.map((entry) => {
952 if (entry.id !== surface.id || entry.kind !== "pull-request") return entry;
953 // A later link replaces one not yet shown.
954 const { revealUrl: _previous, ...rest } = entry;
955 return { ...rest, ...surface, ...(revealUrl ? { revealUrl } : {}) };
956 }),
957 };
958 }),
959 ),
960 openIssue: (ref, target) =>
961 set((state) =>
962 userAction(state, scopedThreadKey(ref), (current) => {
963 const surface = issueSurface(target);
964 const next = upsertSurface(current, surface);
965 return target.url
966 ? {
967 ...next,
968 surfaces: next.surfaces.map((entry) =>
969 entry.id === surface.id ? surface : entry,
970 ),
971 }
972 : next;
973 }),
974 ),
975 setPullRequestDetailTab: (ref, surfaceId, detailTab) =>
976 set((state) => {
977 const threadKey = scopedThreadKey(ref);
978 const existing = state.byThreadKey[threadKey]?.surfaces.find(
979 (surface) => surface.id === surfaceId,
980 );
981 if (existing?.kind !== "pull-request" || (existing.detailTab ?? "summary") === detailTab)
982 return state;
983 return automaticUpdate(state, threadKey, (current) => ({
984 ...current,
985 surfaces: current.surfaces.map((surface) =>
986 surface.id === surfaceId && surface.kind === "pull-request"
987 ? { ...surface, detailTab }
988 : surface,
989 ),
990 }));
991 }),
992 settlePullRequestReveal: (ref, surfaceId, revealUrl) =>
993 set((state) => {
994 const threadKey = scopedThreadKey(ref);
995 const existing = state.byThreadKey[threadKey]?.surfaces.find(
996 (surface) => surface.id === surfaceId,
997 );
998 if (existing?.kind !== "pull-request" || existing.revealUrl !== revealUrl) return state;
999 return automaticUpdate(state, threadKey, (current) => ({
1000 ...current,
1001 surfaces: current.surfaces.map((surface) =>
1002 surface.id === surfaceId ? withoutReveal(surface) : surface,
1003 ),
1004 }));
1005 }),
1006 openFile: (ref, requestedPath, line) =>
1007 set((state) =>
1008 userAction(state, scopedThreadKey(ref), (current) => {
1009 if (requestedPath === ".") {
1010 return upsertSurface(current, singletonSurface("files"));
1011 }
1012 // Workspace entry paths use '/', including on Windows.
1013 const relativePath = /^[A-Za-z]:\/+$/.test(requestedPath)
1014 ? requestedPath
1015 : requestedPath.replace(/\/+$/, "") || requestedPath;
1016 const withoutStandaloneExplorer = current.surfaces.filter(
1017 (surface) => surface.kind !== "files",
1018 );
1019 const surfaceId = `file:${relativePath}` as const;
1020 const existing = withoutStandaloneExplorer.find(
1021 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
1022 surface.id === surfaceId && surface.kind === "file",
1023 );
1024 const surface = fileSurface(
1025 relativePath,
1026 normalizeRevealLine(line),
1027 (existing?.revealRequestId ?? 0) + 1,
1028 );
1029 return {
1030 ...current,
1031 isOpen: true,
1032 activeSurfaceId: surface.id,
1033 surfaces: existing
1034 ? withoutStandaloneExplorer.map((entry) =>
1035 entry.id === surface.id ? surface : entry,
1036 )
1037 : [...withoutStandaloneExplorer, surface],
1038 };
1039 }),
1040 ),
1041 navigateFolder: (ref, surfaceId, relativePath, folderTrail, keepSource = false) =>
1042 set((state) =>
1043 userAction(state, scopedThreadKey(ref), (current) => {
1044 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
1045 if (index < 0) return current;
1046 const trail = folderTrail === relativePath ? {} : { folderTrail };
1047 const target: RightPanelSurface =
1048 relativePath === ""
1049 ? { ...singletonSurface("files"), ...trail }
1050 : { ...fileSurface(relativePath, null, 1), ...trail };
1051 const source = current.surfaces[index]!;
1052 const existing = current.surfaces.some(
1053 (surface, i) => i !== index && surface.id === target.id,
1054 );
1055 const surfaces = current.surfaces.flatMap((surface, i) => {
1056 if (i === index) {
1057 const kept = keepSource ? [source] : [];
1058 return existing ? kept : [...kept, target];
1059 }
1060 return !existing && target.kind === "file" && surface.kind === "files"
1061 ? []
1062 : [surface];
1063 });
1064 return { ...current, isOpen: true, activeSurfaceId: target.id, surfaces };
1065 }),
1066 ),
1067 openAttachment: (ref, attachment) =>
1068 set((state) =>
1069 userAction(state, scopedThreadKey(ref), (current) => {
1070 const withoutStandaloneExplorer = current.surfaces.filter(
1071 (surface) => surface.kind !== "files",
1072 );
1073 return upsertSurface(
1074 { ...current, surfaces: withoutStandaloneExplorer },
1075 attachmentSurface(attachment),
1076 );
1077 }),
1078 ),
1079 openTerminal: (ref, terminalId) =>
1080 set((state) =>
1081 userAction(state, scopedThreadKey(ref), (current) =>
1082 upsertSurface(current, terminalSurface(terminalId)),
1083 ),
1084 ),
1085 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
1086 set((state) =>
1087 userAction(state, scopedThreadKey(ref), (current) => ({
1088 ...current,
1089 isOpen: true,
1090 activeSurfaceId: surfaceId,
1091 surfaces: current.surfaces.map((surface) => {
1092 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
1093 const { splitDirection: _splitDirection, ...baseSurface } = surface;
1094 return {
1095 ...baseSurface,
1096 terminalIds: surface.terminalIds.includes(terminalId)
1097 ? surface.terminalIds
1098 : [...surface.terminalIds, terminalId],
1099 activeTerminalId: terminalId,
1100 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
1101 };
1102 }),
1103 })),
1104 ),
1105 activateTerminal: (ref, surfaceId, terminalId) =>
1106 set((state) =>
1107 userAction(state, scopedThreadKey(ref), (current) => ({
1108 ...current,
1109 activeSurfaceId: surfaceId,
1110 surfaces: current.surfaces.map((surface) =>
1111 surface.id === surfaceId &&
1112 surface.kind === "terminal" &&
1113 surface.terminalIds.includes(terminalId)
1114 ? { ...surface, activeTerminalId: terminalId }
1115 : surface,
1116 ),
1117 })),
1118 ),
1119 closeTerminal: (ref, surfaceId, terminalId) =>
1120 set((state) =>
1121 closeAction(state, scopedThreadKey(ref), (current) => {
1122 const surface = current.surfaces.find(
1123 (entry) => entry.id === surfaceId && entry.kind === "terminal",
1124 );
1125 if (!surface || surface.kind !== "terminal") return current;
1126 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
1127 if (terminalIds.length === 0) {
1128 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
1129 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
1130 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
1131 return {
1132 ...current,
1133 isOpen: surfaces.length > 0 && current.isOpen,
1134 surfaces,
1135 activeSurfaceId:
1136 current.activeSurfaceId === surfaceId
1137 ? (fallback?.id ?? null)
1138 : current.activeSurfaceId,
1139 };
1140 }
1141 return {
1142 ...current,
1143 surfaces: current.surfaces.map((entry) =>
1144 entry.id === surfaceId && entry.kind === "terminal"
1145 ? {
1146 ...entry,
1147 terminalIds,
1148 activeTerminalId:
1149 entry.activeTerminalId === terminalId
1150 ? (terminalIds.at(-1) ?? terminalIds[0]!)
1151 : entry.activeTerminalId,
1152 }
1153 : entry,
1154 ),
1155 };
1156 }),
1157 ),
1158 activateSurface: (ref, surfaceId) =>
1159 set((state) =>
1160 userAction(state, scopedThreadKey(ref), (current) => activated(current, surfaceId)),
1161 ),
1162 revealSurface: (ref, surfaceId) =>
1163 set((state) =>
1164 automaticUpdate(state, scopedThreadKey(ref), (current) => activated(current, surfaceId)),
1165 ),
1166 closeSurface: (ref, surfaceId) =>
1167 set((state) =>
1168 closeAction(state, scopedThreadKey(ref), (current) => {
1169 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
1170 if (index < 0) return current;
1171 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
1172 const next = {
1173 ...current,
1174 isOpen: surfaces.length > 0 && current.isOpen,
1175 surfaces,
1176 };
1177 if (current.activeSurfaceId !== surfaceId) {
1178 return next;
1179 }
1180 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
1181 return {
1182 ...next,
1183 activeSurfaceId: fallback?.id ?? null,
1184 };
1185 }),
1186 ),
1187 closeOtherSurfaces: (ref, surfaceId) =>
1188 set((state) =>
1189 closeAction(state, scopedThreadKey(ref), (current) => {
1190 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
1191 if (!surface || current.surfaces.length === 1) return current;
1192 return {
1193 ...current,
1194 isOpen: true,
1195 surfaces: [surface],
1196 activeSurfaceId: surface.id,
1197 };
1198 }),
1199 ),
1200 closeSurfacesToRight: (ref, surfaceId) =>
1201 set((state) =>
1202 closeAction(state, scopedThreadKey(ref), (current) => {
1203 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
1204 if (index < 0 || index === current.surfaces.length - 1) return current;
1205 const surfaces = current.surfaces.slice(0, index + 1);
1206 const activeStillExists = surfaces.some(
1207 (surface) => surface.id === current.activeSurfaceId,
1208 );
1209 return {
1210 ...current,
1211 surfaces,
1212 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
1213 };
1214 }),
1215 ),
1216 closeAllSurfaces: (ref) =>
1217 set((state) =>
1218 closeAction(state, scopedThreadKey(ref), (current) =>
1219 current.surfaces.length === 0
1220 ? current
1221 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
1222 ),
1223 ),
1224 moveSurface: (ref, surfaceId, toIndex) =>
1225 set((state) =>
1226 updateThread(state, scopedThreadKey(ref), (current) => {
1227 const fromIndex = current.surfaces.findIndex((surface) => surface.id === surfaceId);
1228 if (fromIndex < 0 || fromIndex === toIndex) return current;
1229 const surfaces = [...current.surfaces];
1230 surfaces.splice(toIndex, 0, ...surfaces.splice(fromIndex, 1));
1231 return { ...current, surfaces };
1232 }),
1233 ),
1234 reconcileBrowserSurfaces: (ref, tabIds, hiddenTabIds) =>
1235 set((state) =>
1236 automaticUpdate(state, scopedThreadKey(ref), (current) => {
1237 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
1238 const kept = current.surfaces.filter(
1239 (surface) =>
1240 surface.kind !== "preview" ||
1241 (surface.id !== "browser:new" && validIds.has(surface.id)),
1242 );
1243 const knownIds = new Set(kept.map((surface) => surface.id));
1244 const added = tabIds
1245 .filter((tabId) => !knownIds.has(`browser:${tabId}`) && !hiddenTabIds?.has(tabId))
1246 .map((tabId) => browserSurface(tabId));
1247 const surfaces = [...kept, ...added];
1248 const activeStillExists = surfaces.some(
1249 (surface) => surface.id === current.activeSurfaceId,
1250 );
1251 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
1252 // A closed session tab was the last surface: hide the panel rather than leave it on
1253 // the empty picker, as a user close would. A dropped `browser:new` placeholder does not count.
1254 const closedLastSessionTab =
1255 surfaces.length === 0 &&
1256 current.surfaces.some((surface) => surface.kind === "preview" && surface.resourceId);
1257 return {
1258 ...current,
1259 isOpen: closedLastSessionTab ? false : current.isOpen,
1260 surfaces,
1261 activeSurfaceId: activeStillExists
1262 ? current.activeSurfaceId
1263 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
1264 };
1265 }),
1266 ),
1267 reconcileFileSurfaces: (ref, workspaceAvailable) =>
1268 set((state) =>
1269 automaticUpdate(state, scopedThreadKey(ref), (current) => {
1270 if (workspaceAvailable) return current;
1271 const surfaces = current.surfaces.filter(
1272 (surface) =>
1273 surface.kind !== "files" &&
1274 (surface.kind !== "file" || surface.attachment !== undefined),
1275 );
1276 if (surfaces.length === current.surfaces.length) return current;
1277 const activeStillExists = surfaces.some(
1278 (surface) => surface.id === current.activeSurfaceId,
1279 );
1280 return {
1281 ...current,
1282 isOpen: surfaces.length > 0 ? current.isOpen : false,
1283 surfaces,
1284 activeSurfaceId: activeStillExists
1285 ? current.activeSurfaceId
1286 : (surfaces.at(-1)?.id ?? null),
1287 };
1288 }),
1289 ),
1290 show: (ref) =>
1291 set((state) =>
1292 userAction(state, scopedThreadKey(ref), (current) =>
1293 current.isOpen ? current : { ...current, isOpen: true },
1294 ),
1295 ),
1296 close: (ref) =>
1297 set((state) =>
1298 userAction(state, scopedThreadKey(ref), (current) =>
1299 current.isOpen ? { ...current, isOpen: false } : current,
1300 ),
1301 ),
1302 setMaximized: (ref, maximized) =>
1303 set((state) =>
1304 automaticUpdate(state, scopedThreadKey(ref), (current) => {
1305 if ((current.maximized ?? false) === maximized) return current;
1306 const { maximized: _maximized, ...rest } = current;
1307 return maximized ? { ...rest, maximized: true } : rest;
1308 }),
1309 ),
1310 toggleVisibility: (ref) =>
1311 set((state) =>
1312 userAction(state, scopedThreadKey(ref), (current) => ({
1313 ...current,
1314 isOpen: !current.isOpen,
1315 })),
1316 ),
1317 toggle: (ref, kind) =>
1318 set((state) =>
1319 userAction(state, scopedThreadKey(ref), (current) => {
1320 const active = current.surfaces.find(
1321 (surface) => surface.id === current.activeSurfaceId,
1322 );
1323 if (current.isOpen && active?.kind === kind) {
1324 return { ...current, isOpen: false };
1325 }
1326 if (kind === "preview") {
1327 const existing = current.surfaces.find((surface) => surface.kind === "preview");
1328 return upsertSurface(current, existing ?? browserSurface(null));
1329 }
1330 return upsertSurface(current, singletonSurface(kind));
1331 }),
1332 ),
1333 setThreadPanelOpen: (ref, presentation, open) =>
1334 set((state) => ({
1335 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
1336 state.threadPanelVisibilityByThreadKey,
1337 scopedThreadKey(ref),
1338 (visibility) => {
1339 const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
1340 return visibility[key] === open ? visibility : { ...visibility, [key]: open };
1341 },
1342 ),
1343 })),
1344 toggleThreadPanel: (ref, presentation) =>
1345 set((state) => ({
1346 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
1347 state.threadPanelVisibilityByThreadKey,
1348 scopedThreadKey(ref),
1349 (visibility) =>
1350 presentation === "inline"
1351 ? { ...visibility, inlineOpen: !visibility.inlineOpen }
1352 : { ...visibility, popoverOpen: !visibility.popoverOpen },
1353 ),
1354 })),
1355 removeThread: (ref) =>
1356 set((state) => {
1357 const threadKey = scopedThreadKey(ref);
1358 if (
1359 !(threadKey in state.byThreadKey) &&
1360 !(threadKey in state.threadPanelVisibilityByThreadKey) &&
1361 !(threadKey in state.userActionRevisionByThreadKey) &&
1362 !(threadKey in state.closeRevisionByThreadKey)
1363 ) {
1364 return state;
1365 }
1366 const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey;
1367 const { [threadKey]: _visibility, ...threadPanelVisibilityByThreadKey } =
1368 state.threadPanelVisibilityByThreadKey;
1369 const { [threadKey]: _revision, ...userActionRevisionByThreadKey } =
1370 state.userActionRevisionByThreadKey;
1371 const { [threadKey]: _closeRevision, ...closeRevisionByThreadKey } =
1372 state.closeRevisionByThreadKey;
1373 return {
1374 byThreadKey,
1375 threadPanelVisibilityByThreadKey,
1376 userActionRevisionByThreadKey,
1377 closeRevisionByThreadKey,
1378 };
1379 }),
1380 }),
1381 {
1382 name: RIGHT_PANEL_STORAGE_KEY,
1383 version: RIGHT_PANEL_STORAGE_VERSION,
1384 storage: createJSONStorage(() =>
1385 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
1386 ),
1387 partialize: (state) => ({
1388 byThreadKey: Object.fromEntries(
1389 Object.entries(state.byThreadKey).flatMap(([threadKey, threadState]) =>
1390 isPullRequestsPanelKey(threadKey)
1391 ? []
1392 : [
1393 [
1394 threadKey,
1395 { ...threadState, surfaces: threadState.surfaces.map(withoutReveal) },
1396 ],
1397 ],
1398 ),
1399 ),
1400 threadPanelVisibilityByThreadKey: Object.fromEntries(
1401 Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
1402 ([threadKey, visibility]) =>
1403 visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
1404 ),
1405 ),
1406 }),
1407 migrate: migratePersistedRightPanelState,
1408 },
1409 ),
1410 );
1411
1412 useRightPanelStore.subscribe((next, previous) => {
1413 if (next.closeRevisionByThreadKey === previous.closeRevisionByThreadKey) return;
1414 for (const [threadKey, revision] of Object.entries(next.closeRevisionByThreadKey)) {
1415 if (revision === previous.closeRevisionByThreadKey[threadKey]) continue;
1416 const threadRef = parseScopedThreadKey(threadKey);
1417 if (!threadRef) continue;
1418 const before = previous.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1419 const after = next.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
1420 const removed = before.surfaces.filter(
1421 (surface) => !after.surfaces.some((entry) => entry.id === surface.id),
1422 );
1423 const closedInOrder = [
1424 ...removed.filter((surface) => surface.id !== before.activeSurfaceId),
1425 ...removed.filter((surface) => surface.id === before.activeSurfaceId),
1426 ];
1427 for (const surface of closedInOrder.map(withoutReveal)) {
1428 if (
1429 surface.kind === "terminal" ||
1430 (surface.kind === "preview" && surface.resourceId !== null)
1431 )
1432 continue;
1433 useClosedViewStore.getState().remember({ kind: "panel-tab", threadRef, surface });
1434 }
1435 }
1436 });
1437
1438 export function selectThreadRightPanelState(
1439 byThreadKey: Record<string, ThreadRightPanelState>,
1440 ref: ScopedThreadRef | null | undefined,
1441 ): ThreadRightPanelState {
1442 if (!ref) return EMPTY_THREAD_STATE;
1443 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
1444 }
1445
1446 export function selectThreadPanelVisibility(
1447 byThreadKey: Record<string, ThreadPanelVisibility>,
1448 ref: ScopedThreadRef | null | undefined,
1449 ): ThreadPanelVisibility {
1450 if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
1451 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
1452 }
1453
1454 export function selectThreadPanelOpen(
1455 byThreadKey: Record<string, ThreadPanelVisibility>,
1456 ref: ScopedThreadRef | null | undefined,
1457 presentation: ThreadPanelPresentation,
1458 ): boolean {
1459 const visibility = selectThreadPanelVisibility(byThreadKey, ref);
1460 return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
1461 }
1462
1463 export function selectActiveRightPanel(
1464 byThreadKey: Record<string, ThreadRightPanelState>,
1465 ref: ScopedThreadRef | null | undefined,
1466 ): RightPanelKind | null {
1467 const state = selectThreadRightPanelState(byThreadKey, ref);
1468 if (!state.isOpen) return null;
1469 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
1470 }
1471
1472 export function selectActiveRightPanelSurface(
1473 byThreadKey: Record<string, ThreadRightPanelState>,
1474 ref: ScopedThreadRef | null | undefined,
1475 ): RightPanelSurface | null {
1476 const state = selectThreadRightPanelState(byThreadKey, ref);
1477 if (!state.isOpen) return null;
1478 return selectSelectedRightPanelSurface(byThreadKey, ref);
1479 }
1480
1481 export function selectSelectedRightPanelSurface(
1482 byThreadKey: Record<string, ThreadRightPanelState>,
1483 ref: ScopedThreadRef | null | undefined,
1484 ): RightPanelSurface | null {
1485 const state = selectThreadRightPanelState(byThreadKey, ref);
1486 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
1487 }