{/* The desktop window only moves where CSS opts in, so keep a titlebar strip. */} {isElectron ? : null} diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsx index dab0f16969a56..a387349b4c038 100644 --- a/apps/web/src/components/PersistentThreadTerminals.tsx +++ b/apps/web/src/components/PersistentThreadTerminals.tsx @@ -162,6 +162,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal); const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reconciles the terminal UI store's ids with the server's terminal list when they diverge useEffect(() => { if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) { return; @@ -293,7 +294,7 @@ export interface PersistentThreadTerminalPanelProps { onSplitTerminalVertical: () => void; onNewTerminal: () => void; onActiveTerminalChange: (terminalId: string) => void; - onCloseTerminal: (terminalId: string) => void; + onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; splitShortcutLabel?: string | undefined; splitVerticalShortcutLabel?: string | undefined; newShortcutLabel?: string | undefined; diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 79c927d6e2d02..8832a444f377c 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -88,6 +88,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI void handleNewThread(scopeProjectRef(environmentId, projectId)); }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens, updates and closes imperative toastManager toasts to match the current project clones useEffect(() => { const seen = new Set(); for (const clone of clones) { @@ -215,6 +216,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI retryClone, ]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes every tracked clone toast in toastManager when the coordinator unmounts useEffect( () => () => { for (const tracked of toasts.current.values()) toastManager.close(tracked.toastId); diff --git a/apps/web/src/components/ProjectFavicon.browser.test.tsx b/apps/web/src/components/ProjectFavicon.browser.test.tsx new file mode 100644 index 0000000000000..746302ef5b242 --- /dev/null +++ b/apps/web/src/components/ProjectFavicon.browser.test.tsx @@ -0,0 +1,57 @@ +import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId } from "@t3tools/contracts"; +import { Atom, AtomRegistry } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { ProjectFavicon, type ProjectFaviconProject } from "./ProjectFavicon"; + +const state = vi.hoisted(() => ({ favicon: undefined as Atom.Atom | undefined })); +vi.mock(import("../state/assets"), () => ({ + projectFaviconUrlAtom: () => { + if (!state.favicon) throw new Error("Favicon resource not configured"); + return state.favicon; + }, +})); + +function setup() { + const activeResources = new Set(); + state.favicon = Atom.make((get) => { + activeResources.add("favicon"); + get.addFinalizer(() => activeResources.delete("favicon")); + return null; + }); + return { activeResources }; +} + +it("only activates the favicon resource after removing a custom icon", async () => { + const { activeResources } = setup(); + const registry = AtomRegistry.make(); + const project: ProjectFaviconProject = { + environmentId: EnvironmentId.make("test"), + workspaceRoot: "/project", + title: "Project", + faviconPath: "icon.png", + projectIcon: { kind: "monogram", text: "PR", color: "blue" }, + }; + const view = (projectIcon: ProjectFaviconProject["projectIcon"]) => ( + + + + ); + try { + await using screen = await render(view(project.projectIcon)); + expect(activeResources.size).toBe(0); + await screen.rerender(view({ kind: "emoji", emoji: "🌱" })); + expect(activeResources.size).toBe(0); + await screen.rerender(view({ kind: "lucide", name: "leaf", color: "green" })); + expect(activeResources.size).toBe(0); + await screen.rerender(view(null)); + expect(activeResources.size).toBe(1); + await screen.rerender(view(project.projectIcon)); + await screen.rerender(view(null)); + expect(activeResources.size).toBe(1); + } finally { + registry.dispose(); + } +}); diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index 14a00ae86583b..3545a0aa5db87 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -38,13 +38,6 @@ export function ProjectFavicon(input: { fallbackIcon?: ComponentType<{ className?: string }>; }) { const { project } = input; - const src = useAtomValue( - projectFaviconUrlAtom({ - environmentId: project.environmentId, - cwd: project.workspaceRoot, - faviconPath: project.faviconPath, - }), - ); if (project.projectIcon?.kind === "monogram") { return ( ); } + return ; +} + +function AutomaticProjectFavicon(input: Parameters[0]) { + const { project } = input; + const src = useAtomValue( + projectFaviconUrlAtom({ + environmentId: project.environmentId, + cwd: project.workspaceRoot, + faviconPath: project.faviconPath, + }), + ); const FallbackIcon = input.fallbackIcon ?? FolderCodeIcon; if (!src || isProjectFaviconFallbackUrl(src)) { diff --git a/apps/web/src/components/ProjectPinButton.tsx b/apps/web/src/components/ProjectPinButton.tsx new file mode 100644 index 0000000000000..a8bd7d5ee8e99 --- /dev/null +++ b/apps/web/src/components/ProjectPinButton.tsx @@ -0,0 +1,67 @@ +import type { ResolvedKeybindingsConfig } from "@t3tools/contracts"; +import { PinIcon, PinOffIcon } from "lucide-react"; +import type { KeyboardEvent } from "react"; + +import { resolveShortcutCommand } from "../keybindings"; + +import { cn } from "~/lib/utils"; +import { Button } from "./ui/button"; + +/** The thread pin shortcut, which pins the highlighted row in a project list. */ +export function isProjectPinShortcut( + event: KeyboardEvent, + keybindings: ResolvedKeybindingsConfig, +): boolean { + return ( + resolveShortcutCommand(event.nativeEvent, keybindings, { + platform: navigator.platform, + context: { modelPickerOpen: false, editableFocus: true }, + }) === "thread.pin" + ); +} + +/** + * Pin toggle for a project row in a menu or list. A pinned project always shows its pin; + * an unpinned one shows it only on the highlighted row. Keyboard users get a shortcut + * from the list that hosts it, so the button stays out of the tab order. + */ +export function ProjectPinButton(props: { + readonly name: string; + readonly pinned: boolean; + readonly onToggle: () => void; + readonly shortcutLabel?: string | null; +}) { + const action = `${props.pinned ? "Unpin" : "Pin"} ${props.name}`; + return ( + + + + ); +} diff --git a/apps/web/src/components/ProviderUpdatesAction.browser.test.tsx b/apps/web/src/components/ProviderUpdatesAction.browser.test.tsx new file mode 100644 index 0000000000000..d6ca540686f0e --- /dev/null +++ b/apps/web/src/components/ProviderUpdatesAction.browser.test.tsx @@ -0,0 +1,153 @@ +import { RegistryContext } from "@effect/atom-react"; +import { + AuthProvidersManageScope, + type AuthSessionState, + EnvironmentId, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useEffect } from "react"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../test/render"; + +const state = vi.hoisted(() => ({ + environments: [] as { + environmentId: EnvironmentId; + label: string; + connection: { phase: "connected" | "disconnected" }; + }[], + providers: new Map>(), + requests: [] as EnvironmentId[], + sessions: new Map>>(), +})); + +vi.mock(import("~/state/environments"), () => ({ + useEnvironments: (() => ({ environments: state.environments })) as never, + useEnvironmentProviders: () => state.providers, +})); +vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => { + const actual = await original(); + return { + ...actual, + createEnvironmentSessionAtoms: (( + ...args: Parameters + ) => ({ + ...actual.createEnvironmentSessionAtoms(...args), + sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!, + })) as typeof actual.createEnvironmentSessionAtoms, + }; +}); +vi.mock(import("~/state/server"), () => ({ + serverEnvironment: { updateProvider: {} } as never, +})); +vi.mock(import("~/state/use-atom-command"), () => ({ + useAtomCommand: (() => + async ({ environmentId }: { environmentId: EnvironmentId }) => { + state.requests.push(environmentId); + return AsyncResult.success(undefined); + }) as never, +})); + +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { useProviderUpdates } from "./ProviderUpdatesAction"; + +const provider: ServerProvider = { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-10-21T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + versionAdvisory: { + status: "behind_latest", + currentVersion: "1.0.0", + latestVersion: "1.1.0", + updateCommand: "npm install -g @openai/codex", + canUpdate: true, + checkedAt: "2026-10-21T00:00:00.000Z", + message: "Update available.", + }, +}; + +function session( + scopes: NonNullable, +): AsyncResult.AsyncResult { + return AsyncResult.success({ + authenticated: true, + scopes, + auth: { + policy: "remote-reachable", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["bearer-access-token"], + sessionCookieName: "t3_session", + }, + }); +} + +function setup() { + state.environments = [ + { environmentId: EnvironmentId.make("read-only"), label: "Read only" }, + { environmentId: EnvironmentId.make("writable"), label: "Writable" }, + { environmentId: EnvironmentId.make("unresolved"), label: "Unresolved" }, + ].map((environment) => ({ ...environment, connection: { phase: "connected" } })); + state.providers = new Map( + state.environments.map(({ environmentId }) => [environmentId, [provider]]), + ); + state.requests = []; + const sessions = new Map>>( + [ + [state.environments[0]!.environmentId, Atom.make(session(["orchestration:read"]))], + [state.environments[1]!.environmentId, Atom.make(session([AuthProvidersManageScope]))], + [ + state.environments[2]!.environmentId, + Atom.make>( + AsyncResult.initial(), + ), + ], + ], + ); + state.sessions = sessions; + return { sessions }; +} + +it("bulk provider updates exclude connections without a confirmed management grant", async () => { + const fixture = setup(); + let updates!: ReturnType; + function Probe() { + const nextUpdates = useProviderUpdates(); + useEffect(() => { + updates = nextUpdates; + }, [nextUpdates]); + return null; + } + await using _screen = await render( + + + , + ); + + const writableId = state.environments[1]!.environmentId; + expect(updates.machines.map(({ environmentId }) => environmentId)).toEqual([writableId]); + await act(async () => { + await updates.updateAll({ quiet: true }); + }); + expect(state.requests).toEqual([writableId]); + + await act(() => { + appAtomRegistry.set(fixture.sessions.get(writableId)!, session(["orchestration:read"])); + }); + expect(updates.machines).toEqual([]); + state.requests = []; + await act(async () => { + await updates.updateAll({ quiet: true }); + }); + expect(state.requests).toEqual([]); +}); diff --git a/apps/web/src/components/ProviderUpdatesAction.tsx b/apps/web/src/components/ProviderUpdatesAction.tsx index 8d45d66b71213..57573806e45db 100644 --- a/apps/web/src/components/ProviderUpdatesAction.tsx +++ b/apps/web/src/components/ProviderUpdatesAction.tsx @@ -1,9 +1,10 @@ -import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; +import { AuthProvidersManageScope, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; import { settlePromise } from "@t3tools/client-runtime/state/runtime"; import { useRef, useState } from "react"; import { useEnvironmentProviders, useEnvironments } from "~/state/environments"; import { serverEnvironment } from "~/state/server"; +import { useEnvironmentsWithScope } from "~/state/session"; import { useAtomCommand } from "~/state/use-atom-command"; import { canOneClickUpdateProviderCandidate, @@ -17,13 +18,17 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; export function useProviderUpdates() { const { environments } = useEnvironments(); + const manageableIds = useEnvironmentsWithScope(environments, AuthProvidersManageScope); const providersByEnvironment = useEnvironmentProviders(); const updateProvider = useAtomCommand(serverEnvironment.updateProvider, { reportFailure: false, }); const machines = environments.flatMap((environment) => { const providers = providersByEnvironment.get(environment.environmentId) ?? []; - if (environment.connection.phase !== "connected") { + if ( + environment.connection.phase !== "connected" || + !manageableIds.has(environment.environmentId) + ) { return []; } const candidates = collectProviderUpdateCandidates(providers).filter((candidate) => diff --git a/apps/web/src/components/PullRequestThreadDialog.test.ts b/apps/web/src/components/PullRequestThreadDialog.test.ts index 1d601205dd72f..e800d588d6ba8 100644 --- a/apps/web/src/components/PullRequestThreadDialog.test.ts +++ b/apps/web/src/components/PullRequestThreadDialog.test.ts @@ -50,13 +50,13 @@ vi.mock("~/state/session", () => ({ ? state.canOperate : scope === AuthSourceControlWriteScope && state.canWriteSourceControl, })); -vi.mock("~/lib/sourceControlActions", async () => { +vi.mock("~/state/sourceControlActions", async () => { const { usePreparePullRequestThreadAction } = await vi.importActual< typeof import("~/state/sourceControlActions") >("~/state/sourceControlActions"); return { readCachedPullRequestResolution: () => null, - usePullRequestResolution: () => ({ + usePullRequestResolutionState: () => ({ data: { pullRequest: { number: 123, title: "Pull request", state: "open" } }, }), usePreparePullRequestThreadAction, diff --git a/apps/web/src/components/PullRequestThreadDialog.tsx b/apps/web/src/components/PullRequestThreadDialog.tsx index 0ceda05792934..4ecce60109961 100644 --- a/apps/web/src/components/PullRequestThreadDialog.tsx +++ b/apps/web/src/components/PullRequestThreadDialog.tsx @@ -13,8 +13,8 @@ import { useRef, useState } from "react"; import { readCachedPullRequestResolution, usePreparePullRequestThreadAction, - usePullRequestResolution, -} from "~/lib/sourceControlActions"; + usePullRequestResolutionState, +} from "~/state/sourceControlActions"; import { cn } from "~/lib/utils"; import { parsePullRequestReference } from "@t3tools/client-runtime/pull-request-link-input"; import { getSourceControlPresentation } from "~/sourceControlPresentation"; @@ -92,7 +92,7 @@ export function PullRequestThreadDialog({ const parsedReference = parsePullRequestReference(reference); const parsedDebouncedReference = parsePullRequestReference(debouncedReference); - const pullRequestResolution = usePullRequestResolution({ + const pullRequestResolution = usePullRequestResolutionState({ environmentId, cwd, reference: open ? parsedDebouncedReference : null, diff --git a/apps/web/src/components/QuitHoldOverlay.tsx b/apps/web/src/components/QuitHoldOverlay.tsx index 819455b68f3f7..94ecda194fe43 100644 --- a/apps/web/src/components/QuitHoldOverlay.tsx +++ b/apps/web/src/components/QuitHoldOverlay.tsx @@ -22,7 +22,7 @@ function subscribeQuitHint(listener: () => void): () => void { listeners.add(listener); if (listeners.size === 1) { stopBridge = - window.desktopBridge?.onQuitShortcut?.((hint) => { + window.desktopBridge?.onQuitShortcut((hint) => { window.clearTimeout(hideTimer); if (hint.state === "down") { pressedMode = hint.mode; diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index c388ec33af0b5..5dc65e57f1ca3 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -265,4 +265,11 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }, ); + it("forwards address-bar focus from a focused desktop page", async () => { + setup(); + await using _shortcut = await renderShortcut(); + expect(state.setShortcuts).toHaveBeenLastCalledWith( + expect.arrayContaining([expect.objectContaining({ command: "preview.focusUrl" })]), + ); + }); }); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index eb7f9866919d1..77cc7b3d3068d 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -43,10 +43,13 @@ import { } from "../threadRoutes"; import { toastManager } from "./ui/toast"; -const PREVIEW_FORWARDED_LAYOUT_COMMANDS = [ +const PREVIEW_FORWARDED_COMMANDS = [ + "workspace.focusNext", + "workspace.focusPrevious", "sidebar.toggle", "rightPanel.toggle", "rightPanel.toggleMaximized", + "preview.focusUrl", ] as const; const isGlobalPullRequests = (ref: ScopedThreadRef) => @@ -89,6 +92,7 @@ export function ReopenClosedViewShortcut() { environmentKnown: true, catalogReady: true, ownerExists: true, + sideChatExists: true, shellLive: true, panel, }; @@ -97,6 +101,10 @@ export function ReopenClosedViewShortcut() { environmentKnown: catalog.entries.has(ref.environmentId), catalogReady: catalog.isReady, ownerExists: readThreadShell(ref) !== null || drafts.getDraftThreadByRef(ref) !== null, + sideChatExists: + entry.kind !== "panel-tab" || + entry.surface.kind !== "side-chat" || + readThreadShell(scopeThreadRef(ref.environmentId, entry.surface.threadId)) !== null, shellLive: appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live", panel, @@ -144,6 +152,7 @@ export function ReopenClosedViewShortcut() { }); }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown and the desktop menu action for the reopen closed view shortcut useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { if ( @@ -178,9 +187,10 @@ export function ReopenClosedViewShortcut() { }; }, [keybindings, previewOpen, terminalOpen]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers forwarded shortcut chords with the desktop preview bridge and clears them on cleanup useEffect(() => { const preview = window.desktopBridge?.preview; - if (!preview?.setForwardedShortcuts) return; + if (!preview) return; const options = { context: { previewFocus: true, @@ -196,7 +206,7 @@ export function ReopenClosedViewShortcut() { // Guest browser processes miss app keydown listeners; desktop forwards the chords as menu actions. const commands = [ ...(hasHistory ? (["view.reopenClosed"] as const) : []), - ...PREVIEW_FORWARDED_LAYOUT_COMMANDS, + ...PREVIEW_FORWARDED_COMMANDS, ]; void preview .setForwardedShortcuts( @@ -209,7 +219,7 @@ export function ReopenClosedViewShortcut() { ) .catch(() => undefined); return () => { - void preview.setForwardedShortcuts?.([]).catch(() => undefined); + void preview.setForwardedShortcuts([]).catch(() => undefined); }; }, [hasHistory, keybindings, terminalOpen]); diff --git a/apps/web/src/components/RightPanelTabs.test.tsx b/apps/web/src/components/RightPanelTabs.test.tsx index fa9cbf0141c3e..88793cce44850 100644 --- a/apps/web/src/components/RightPanelTabs.test.tsx +++ b/apps/web/src/components/RightPanelTabs.test.tsx @@ -26,8 +26,62 @@ describe("surface shortcuts", () => { const actions = [ { shortcut: "B", available: true, label: "Browser" }, { shortcut: "D", available: false, label: "Diff" }, + { shortcut: "T", available: true, label: "Terminal" }, + { shortcut: "M", available: true, label: "Device" }, ] as const; + it("falls back to the physical key when the layout types a non-Latin letter or mark", () => { + // Ukrainian layout: the B key types "и". + expect(surfaceShortcutActionForKey(actions, shortcutEvent("\u0438", { code: "KeyB" }))).toBe( + actions[0], + ); + // Greek layout: the B key types "β". + expect(surfaceShortcutActionForKey(actions, shortcutEvent("\u03b2", { code: "KeyB" }))).toBe( + actions[0], + ); + // Thai layout: the B key types the vowel sign "\u0e34", a combining mark. + expect(surfaceShortcutActionForKey(actions, shortcutEvent("\u0e34", { code: "KeyB" }))).toBe( + actions[0], + ); + // Arabic (101) layout: the B key types lam alef "\u0644\u0627", two code points. + expect( + surfaceShortcutActionForKey(actions, shortcutEvent("\u0644\u0627", { code: "KeyB" })), + ).toBe(actions[0]); + // Ukrainian layout: the D key types "\u0432", but the Diff surface is unavailable. + expect( + surfaceShortcutActionForKey(actions, shortcutEvent("\u0432", { code: "KeyD" })), + ).toBeNull(); + }); + + it("follows the typed letter on Latin layouts that move it", () => { + // Dvorak: the key at QWERTY B types "x", and "b" sits on QWERTY N. + expect(surfaceShortcutActionForKey(actions, shortcutEvent("x", { code: "KeyB" }))).toBeNull(); + // The same key with Shift or Caps Lock types "X". + expect(surfaceShortcutActionForKey(actions, shortcutEvent("X", { code: "KeyB" }))).toBeNull(); + expect(surfaceShortcutActionForKey(actions, shortcutEvent("b", { code: "KeyN" }))).toBe( + actions[0], + ); + }); + + it("keeps accented Latin letters typed on a letter key", () => { + // Bépo: the T key types "è". + expect( + surfaceShortcutActionForKey(actions, shortcutEvent("\u00e8", { code: "KeyT" })), + ).toBeNull(); + }); + + it("keeps punctuation typed on a letter key", () => { + // French AZERTY: the M key types ",". + expect(surfaceShortcutActionForKey(actions, shortcutEvent(",", { code: "KeyM" }))).toBeNull(); + }); + + it("keeps a dead key on a letter key", () => { + // A dead key starts an accented letter on a Latin layout. + expect( + surfaceShortcutActionForKey(actions, shortcutEvent("Dead", { code: "KeyT" })), + ).toBeNull(); + }); + it("leaves modified, composing, and already-handled key events alone", () => { expect(surfaceShortcutActionForKey(actions, shortcutEvent("b", { metaKey: true }))).toBeNull(); expect( @@ -37,6 +91,21 @@ describe("surface shortcuts", () => { surfaceShortcutActionForKey(actions, shortcutEvent("b", { defaultPrevented: true })), ).toBeNull(); }); + + it("leaves AltGr text alone unless it is a plain letter", () => { + const getModifierState = (key: string) => key === "AltGraph"; + // German layout: AltGr+M types "\u00b5" and sets only AltGraph on Linux and Windows. + expect( + surfaceShortcutActionForKey( + actions, + shortcutEvent("\u00b5", { code: "KeyM", getModifierState }), + ), + ).toBeNull(); + // Finnish layout: AltGr+B types "b", which still matches, as it does in keybindings.ts. + expect( + surfaceShortcutActionForKey(actions, shortcutEvent("b", { code: "KeyB", getModifierState })), + ).toBe(actions[0]); + }); }); describe("surface shortcut typing contexts", () => { diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 4cab22ef83871..596bdee96ad1f 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1,6 +1,15 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import { + useProjects, + useQuietThreadShell, + useServerConfigs, + useThreadShells, +} from "~/state/entities"; import { threadPullRequestKeysEqual, visibleThreadPullRequests, @@ -12,6 +21,7 @@ import type { ProjectId, PullRequestState, ResolvedKeybindingsConfig, + ThreadId, } from "@t3tools/contracts"; import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; import { @@ -33,6 +43,7 @@ import { FileDiff, Files, Globe2, + MessagesSquare, Plus, TerminalSquare, } from "lucide-react"; @@ -73,7 +84,7 @@ import { import { useBrowserDefaults } from "~/browser/browserDefaults"; import { ScrollArea } from "~/components/ui/scroll-area"; import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button"; -import { faviconUrlForOrigin } from "~/lib/favicon"; +import { faviconUrlForOrigin } from "@t3tools/shared/favicon"; import { useTheme } from "~/hooks/useTheme"; import { useDeviceState } from "~/state/device"; import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize"; @@ -92,6 +103,7 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon"; import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; +import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey"; export interface RightPanelTabsProps { mode: PreviewPanelMode; @@ -129,6 +141,8 @@ export interface RightPanelTabsProps { onAddPullRequest: () => void; onAddPullRequests: () => void; onAddDevice: () => void; + /** Absent where side chats are not offered. */ + onAddSideChat?: (() => void) | undefined; browserAvailable: boolean; terminalAvailable: boolean; diffAvailable: boolean; @@ -136,6 +150,9 @@ export interface RightPanelTabsProps { pullRequestAvailable: boolean; pullRequestsAvailable: boolean; deviceAvailable: boolean; + sideChatAvailable?: boolean; + /** Overrides the default reason while side chats are available but cannot start. */ + sideChatDisabledReason?: string | null; pullRequestStatusSeeds?: Readonly>; children: ReactNode; } @@ -162,6 +179,7 @@ const SURFACE_DISABLED_REASONS = { pullRequest: "This thread's branch has no pull request yet.", pullRequests: "No linked pull requests are available for this thread.", device: "Devices are only available from a thread.", + sideChat: "Side chats start after the first message.", } as const; // Closed keepMounted popups must stop blocking shortcuts once their exit transition ends. @@ -186,6 +204,7 @@ const SURFACE_UNAVAILABLE_HINTS = { pullRequest: "No pull request on this branch yet.", pullRequests: "No linked pull requests available.", device: "Available from a thread.", + sideChat: "Available after the first message.", } as const; type TabContextMenuAction = @@ -238,17 +257,17 @@ function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState { type SurfaceShortcutEvent = Pick< KeyboardEvent, "altKey" | "ctrlKey" | "defaultPrevented" | "isComposing" | "key" | "metaKey" ->; +> & + Partial>; export function surfaceShortcutActionForKey< const Action extends { available: boolean; shortcut: string }, >(actions: readonly Action[], event: SurfaceShortcutEvent): Action | null { if (event.defaultPrevented || event.isComposing) return null; if (event.metaKey || event.ctrlKey || event.altKey) return null; + const key = surfaceShortcutKey(event); return ( - actions.find( - (action) => action.available && action.shortcut.toLowerCase() === event.key.toLowerCase(), - ) ?? null + actions.find((action) => action.available && action.shortcut.toLowerCase() === key) ?? null ); } @@ -303,6 +322,8 @@ function RightPanelEmptyState(props: { onAddPullRequest: () => void; onAddPullRequests: () => void; onAddDevice: () => void; + /** Absent where side chats are not offered. */ + onAddSideChat?: (() => void) | undefined; browserAvailable: boolean; terminalAvailable: boolean; diffAvailable: boolean; @@ -310,6 +331,8 @@ function RightPanelEmptyState(props: { pullRequestAvailable: boolean; pullRequestsAvailable: boolean; deviceAvailable: boolean; + sideChatAvailable: boolean; + sideChatDisabledReason: string | null; }) { const [highlight, setHighlight] = useState(-1); @@ -371,6 +394,19 @@ function RightPanelEmptyState(props: { disabledReason: SURFACE_UNAVAILABLE_HINTS.device, onClick: props.onAddDevice, }, + ...(props.onAddSideChat + ? [ + { + label: "Side chat", + description: "Ask a side question while this thread keeps working.", + icon: MessagesSquare, + shortcut: "S", + available: props.sideChatAvailable && !props.sideChatDisabledReason, + disabledReason: props.sideChatDisabledReason ?? SURFACE_UNAVAILABLE_HINTS.sideChat, + onClick: props.onAddSideChat, + }, + ] + : []), ] as const; type SurfaceAction = (typeof actions)[number]; @@ -389,6 +425,7 @@ function RightPanelEmptyState(props: { event.stopPropagation(); action.onClick(); }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a capture-phase window keydown listener for surface shortcuts while the menu is mounted useEffect(() => { const handler = (event: KeyboardEvent) => handleShortcut(event); window.addEventListener("keydown", handler, true); @@ -435,7 +472,7 @@ function RightPanelEmptyState(props: { return (
; + case "side-chat": + return ; case "device": return surface.target?.platform === "ios" ? ( @@ -654,6 +695,41 @@ function SurfaceIcon({ } } +/** What a side chat tab's dot shows and its title's accessible name says. */ +function sideChatTabState(shell: EnvironmentThreadShell | null) { + if (shell === null) return null; + if (shell.hasPendingApprovals || shell.pendingSubagentRequest === "approval") { + return "needs approval"; + } + if (shell.hasPendingUserInput || shell.pendingSubagentRequest === "user_input") { + return "needs input"; + } + return threadRuntimeIsActive(shell.runtime) ? "running" : null; +} + +// Static dots: a side chat tab can stay open for a whole run. +function SideChatTabIcon(props: { environmentId: EnvironmentId | null; threadId: ThreadId }) { + const state = sideChatTabState( + useQuietThreadShell( + props.environmentId === null ? null : scopeThreadRef(props.environmentId, props.threadId), + ), + ); + return ( + <> + + {state === null ? null : ( + + )} + + ); +} + export function resolvePullRequestTabLink( threads: readonly Pick[], environmentId: EnvironmentId | null, @@ -711,17 +787,17 @@ function PullRequestSurfaceIcon({ ? undefined : configs.get(resolvedEnvironmentId)?.environment.capabilities; const linkedSnapshot = - capabilities?.threadPullRequests === true + capabilities !== undefined ? (resolvePullRequestTabLink(threads, resolvedEnvironmentId, host, surface)?.snapshot ?? null) : null; const detail = useEnvironmentQuery( - resolvedEnvironmentId === null || capabilities?.pullRequests !== true || linkedSnapshot !== null + resolvedEnvironmentId === null || capabilities === undefined || linkedSnapshot !== null ? null : pullRequestEnvironment.detail({ environmentId: resolvedEnvironmentId, input: { projectId: surface.projectId as ProjectId, - ...(capabilities?.threadPullRequests === true && surface.host !== undefined + ...(capabilities !== undefined && surface.host !== undefined ? { host: surface.host } : {}), repository: surface.repository, @@ -747,10 +823,6 @@ function PullRequestSurfaceIcon({ return ; } -function focusOnMount(node: HTMLDivElement | null) { - node?.focus(); -} - function SortableTabList(props: { surfaces: readonly RightPanelSurface[]; onMove: ((surfaceId: string, toIndex: number) => void) | undefined; @@ -815,7 +887,6 @@ function RightPanelTab( ) { const { surface, - title, audio, audioRuntimeTabId, onActivate, @@ -829,6 +900,13 @@ function RightPanelTab( id: surface.id, disabled: props.dragDisabled, }); + const sideChatShell = useQuietThreadShell( + surface.kind === "side-chat" && props.environmentId !== null + ? scopeThreadRef(props.environmentId, surface.threadId) + : null, + ); + const title = sideChatShell?.title ?? props.title; + const sideChatState = sideChatTabState(sideChatShell); const content = ( <> onClose(surface)}> @@ -898,6 +976,7 @@ function RightPanelTab( if (surface.kind === "device" && props.canRename) onStartRename(surface.id); }} className="cursor-pointer flex min-w-0 items-center" + aria-label={sideChatState === null ? undefined : `${title}, ${sideChatState}`} onClick={() => onActivate(surface)} > {title} @@ -944,6 +1023,7 @@ function RightPanelTab( } export function RightPanelTabs(props: RightPanelTabsProps) { + const focusedSurface = props.surfaces.find((surface) => surface.id === props.activeSurfaceId); const ownsDesktopTitleBar = isElectron && props.mode === "inline"; const browserProfiles = useBrowserDefaults().profiles; const { resolvedTheme } = useTheme(); @@ -975,6 +1055,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { setAddSurfaceMenuOpen(true); } }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a document keydown listener for the new surface shortcut while the panel is open useEffect(() => { if (props.open === false) return; document.addEventListener("keydown", onNewSurfaceKeyDown, true); @@ -1066,6 +1147,18 @@ export function RightPanelTabs(props: RightPanelTabsProps) { disabledReason: SURFACE_DISABLED_REASONS.device, onClick: props.onAddDevice, }, + ...(props.onAddSideChat + ? [ + { + label: "Side chat", + icon: MessagesSquare, + shortcut: "S", + available: props.sideChatAvailable === true && !props.sideChatDisabledReason, + disabledReason: props.sideChatDisabledReason ?? SURFACE_DISABLED_REASONS.sideChat, + onClick: props.onAddSideChat, + }, + ] + : []), ] as const; const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { @@ -1181,6 +1274,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { }); // A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the active tab DOM node into view after it changes or the tab strip starts overflowing useEffect(() => { if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return; const activeTab = tabListRef.current?.querySelector("[data-active-tab='true']"); @@ -1223,6 +1317,13 @@ export function RightPanelTabs(props: RightPanelTabsProps) { return ( ) : ( props.children diff --git a/apps/web/src/components/ServerUpdateAction.browser.test.tsx b/apps/web/src/components/ServerUpdateAction.browser.test.tsx index 0062a69c09177..ed3a723652a56 100644 --- a/apps/web/src/components/ServerUpdateAction.browser.test.tsx +++ b/apps/web/src/components/ServerUpdateAction.browser.test.tsx @@ -13,8 +13,8 @@ const testState = vi.hoisted(() => ({ updateServer: vi.fn(), toast: vi.fn(), clipboard: vi.fn(), - continueThreadsAfterServerUpdate: false, sessionAtom: null as unknown, + serverVersions: new Map(), })); vi.mock(import("~/hooks/useCopyToClipboard"), async (original) => ({ @@ -27,16 +27,6 @@ vi.mock(import("~/hooks/useCopyToClipboard"), async (original) => ({ isCopied: false, })) as never, })); -vi.mock(import("~/hooks/useSettings"), async (original) => ({ - ...(await original()), - useEnvironmentSettings: (( - _environmentId: EnvironmentId, - selector: (settings: { continueThreadsAfterServerUpdate: boolean }) => unknown, - ) => - selector({ - continueThreadsAfterServerUpdate: testState.continueThreadsAfterServerUpdate, - })) as never, -})); vi.mock(import("~/state/session"), async (original) => { const actual = await original(); return { @@ -47,6 +37,16 @@ vi.mock(import("~/state/session"), async (original) => { }, }; }); +vi.mock(import("~/state/entities"), async (original) => ({ + ...(await original()), + useServerConfigs: (() => + new Map( + [...testState.serverVersions].map(([id, serverVersion]) => [ + id, + { environment: { serverVersion } }, + ]), + )) as never, +})); vi.mock(import("~/state/use-atom-command"), async (original) => ({ ...(await original()), useAtomCommand: (() => testState.updateServer) as never, @@ -95,7 +95,7 @@ function setup(): Disposable { testState.updateServer.mockReset(); testState.toast.mockReset(); testState.clipboard.mockReset(); - testState.continueThreadsAfterServerUpdate = false; + testState.serverVersions.clear(); sessionAtom = Atom.make(AsyncResult.success(currentSession)); testState.sessionAtom = sessionAtom; resetConfirmDialogForTests(); @@ -188,16 +188,12 @@ describe("ServerUpdatesAction", () => { serverLabel: "Laptop", selfUpdate: "boot-service", targetVersion: "0.0.31", - threadContinuation: true, - continueThreadsAfterServerUpdate: true, }, { environmentId: "batch-b" as EnvironmentId, serverLabel: "Office", selfUpdate: "respawn", targetVersion: "0.0.31", - threadContinuation: true, - continueThreadsAfterServerUpdate: false, }, { environmentId: "batch-c" as EnvironmentId, @@ -228,4 +224,17 @@ describe("ServerUpdatesAction", () => { ); expect(button(screen, "Update all")!.disabled).toBe(false); }); + + it("skips a machine whose update would cross Stable and Nightly", async () => { + using _state = setup(); + testState.serverVersions.set("batch-a", "0.0.30-nightly.20261001.1"); + testState.updateServer.mockResolvedValue(success()); + await using screen = await mount(); + await click(screen, "Update all"); + + expect(testState.updateServer).toHaveBeenCalledTimes(1); + expect(testState.toast).toHaveBeenCalledWith( + expect.objectContaining({ type: "success", title: "Office updated" }), + ); + }); }); diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx index c659d410b8581..32a2811aca189 100644 --- a/apps/web/src/components/ServerUpdateAction.tsx +++ b/apps/web/src/components/ServerUpdateAction.tsx @@ -2,11 +2,13 @@ import { useAtomValue } from "@effect/atom-react"; import { AuthEnvironmentMaintainScope, type AuthSessionState, + managedUpdatesDenial, sessionGrantsScope, } from "@t3tools/contracts"; import type { AsyncResult } from "effect/reactivity"; import { environmentSession } from "~/state/session"; import type { + DesktopUpdateChannel, EnvironmentId, ServerInstallation, ServerSelfUpdateCapability, @@ -22,11 +24,15 @@ import { type ComponentProps, useRef, useState } from "react"; import { requestConfirmDialog } from "~/confirmDialog"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; -import { useEnvironmentSettings } from "~/hooks/useSettings"; import { serverEnvironment, updateOutdatedServer } from "~/state/server"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { useAtomCommand } from "~/state/use-atom-command"; +import { useServerConfigs } from "~/state/entities"; +import { useManagedPolicy } from "~/state/managedPolicy"; +import { environmentPresentations } from "~/state/presentation"; +import { ManagedControl } from "./ManagedPolicy"; import { manualServerUpdateCommand } from "~/versionSkew"; +import { crossesReleaseTrack } from "@t3tools/shared/cliRelease"; import { Button } from "./ui/button"; import { toastManager } from "./ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; @@ -42,6 +48,37 @@ export function serverUpdateStageLabel(stage: ServerUpdateStage): string { return UPDATE_STAGE_LABELS[stage]; } +/** Why the environment's policy refuses server updates, read outside render. */ +function readUpdatesDenial(environmentId: EnvironmentId): string | undefined { + return managedUpdatesDenial( + appAtomRegistry.get(environmentPresentations.serverConfigsAtom).get(environmentId) + ?.managedPolicy, + ); +} + +const CROSS_TRACK_NOTE = "Switch tracks in About → Update track"; + +/** Hosts refuse a Stable/Nightly crossing outside a track switch, which checks the database first. */ +function refusedCrossing( + target: { + readonly selfUpdate: ServerSelfUpdateCapability | null; + readonly targetVersion: string; + readonly channel?: DesktopUpdateChannel | undefined; + }, + serverVersion: string | undefined, +): boolean { + return ( + target.channel === undefined && + target.selfUpdate !== null && + serverVersion !== undefined && + crossesReleaseTrack(serverVersion, target.targetVersion) + ); +} + +function CrossTrackNote() { + return {CROSS_TRACK_NOTE}; +} + function updateFailureMessage(error: unknown): string { return error instanceof Error ? error.message : "Server update failed."; } @@ -52,9 +89,13 @@ export interface ServerUpdateTarget { readonly selfUpdate: ServerSelfUpdateCapability | null; readonly installation?: ServerInstallation | undefined; readonly desktopAppUpdate?: boolean; - readonly threadContinuation?: boolean; readonly targetVersion: string; - readonly continueThreadsAfterServerUpdate?: boolean; + /** Set only by a track switch; the host's desktop app moves to this track. */ + readonly channel?: DesktopUpdateChannel; + /** A track switch's checked release migration; the host re-checks its own database. */ + readonly targetDatabaseMigration?: number; + /** The host already runs its track's newest build and only saves the track. */ + readonly trackOnly?: boolean; } type UpdateButtonProps = Pick, "variant" | "size" | "className"> & { @@ -74,6 +115,17 @@ export function useServerUpdate() { { quiet = false }: { readonly quiet?: boolean } = {}, ): Promise => { const { environmentId, serverLabel, selfUpdate, targetVersion } = target; + const denial = readUpdatesDenial(environmentId); + if (denial !== undefined) { + if (!quiet) { + toastManager.add({ + type: "error", + title: `${serverLabel} not updated`, + description: denial, + }); + } + return { status: "failed", message: denial }; + } if ( !canUpdateServer(appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId))) || pendingUpdateEnvironmentIds.has(environmentId) @@ -84,9 +136,10 @@ export function useServerUpdate() { environmentId, input: { targetVersion, - ...(target.threadContinuation && target.continueThreadsAfterServerUpdate - ? { continueRunningThreads: true } - : {}), + ...(target.channel === undefined ? {} : { channel: target.channel }), + ...(target.targetDatabaseMigration === undefined + ? {} + : { targetDatabaseMigration: target.targetDatabaseMigration }), }, }); pendingUpdateEnvironmentIds.delete(environmentId); @@ -126,12 +179,15 @@ export function ServerUpdatesAction({ readonly targets: ReadonlyArray; }) { const update = useServerUpdate(); + const serverConfigs = useServerConfigs(); const pending = useRef(false); const [isPending, setIsPending] = useState(false); const eligible = targets.filter( (target) => target.selfUpdate !== null && - (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate), + (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) && + managedUpdatesDenial(serverConfigs.get(target.environmentId)?.managedPolicy) === undefined && + !refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion), ); const handleUpdate = async () => { if (pending.current) return; @@ -205,21 +261,19 @@ export function ServerUpdateAction({ selfUpdate, installation, desktopAppUpdate = false, - threadContinuation = false, targetVersion, + channel, label = "Update", variant = "outline", size = "xs", className, appearance = "button", -}: Omit & UpdateButtonProps) { +}: ServerUpdateTarget & UpdateButtonProps) { const isDesktopAppUpdate = selfUpdate === "desktop-managed"; + const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion; const sessionStateAtom = environmentSession.sessionStateAtom(environmentId); - const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom)); - const continueThreadsAfterServerUpdate = useEnvironmentSettings( - environmentId, - (settings) => settings.continueThreadsAfterServerUpdate, - ); + const canUpdate = useAtomValue(sessionStateAtom, canUpdateServer); + const updatesDenial = managedUpdatesDenial(useManagedPolicy(environmentId)); const update = useServerUpdate(); const { copyToClipboard } = useCopyToClipboard<{ command: string }>({ target: installation?.kind === "npm-global" ? "update command" : "relaunch command", @@ -265,12 +319,22 @@ export function ServerUpdateAction({ serverLabel, selfUpdate, desktopAppUpdate, - threadContinuation, targetVersion, - continueThreadsAfterServerUpdate, }); }; + if (updatesDenial !== undefined) { + return appearance === "icon" ? ( + + + + ) : ( + {updatesDenial} + ); + } + if (selfUpdate === "desktop-managed" && !desktopAppUpdate) { return ( @@ -279,6 +343,10 @@ export function ServerUpdateAction({ ); } + if (refusedCrossing({ selfUpdate, targetVersion, channel }, serverVersion)) { + return ; + } + const manualCommand = selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null; const actionLabel = @@ -366,6 +434,9 @@ export function OutdatedServerUpdateAction({ description: `Reconnected on t3@${result.value.targetVersion}.`, }); }; + if (fromVersion !== undefined && crossesReleaseTrack(fromVersion, targetVersion)) { + return ; + } return ( - ) : scopedProjectGroup ? ( - `No threads in ${scopedProjectGroup.displayName} yet` + ) : scopedProjectGroups.length > 1 ? ( + "No threads in these projects yet" + ) : scopedProjectGroups[0] ? ( + `No threads in ${scopedProjectGroups[0].displayName} yet` ) : ( "No threads yet" )} @@ -3248,9 +3640,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : null} - + ); } diff --git a/apps/web/src/components/SidebarStageBackdrop.tsx b/apps/web/src/components/SidebarStageBackdrop.tsx index b272c5724feb7..b5c9d34ac6670 100644 --- a/apps/web/src/components/SidebarStageBackdrop.tsx +++ b/apps/web/src/components/SidebarStageBackdrop.tsx @@ -1,4 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentIdentificationMode } from "@t3tools/contracts"; import { useId } from "react"; import { APP_STAGE_LABEL } from "../branding"; @@ -12,9 +13,11 @@ const STAGE_BACKDROP_VIEW_BOX = "0 0 8192 96"; export function resolveSidebarStageBackdropVariant( stageLabel: string, - enabled = true, + mode: EnvironmentIdentificationMode = "artwork", ): SidebarStageBackdropVariant | null { - if (!enabled) return null; + if (mode === "nightly-artwork") return "nightly"; + if (mode === "dev-artwork") return "dev"; + if (mode !== "artwork") return null; const normalized = stageLabel.trim().toLowerCase(); if (normalized === "nightly") return "nightly"; if (normalized === "dev") return "dev"; @@ -40,8 +43,10 @@ export function useEnvironmentStageLabel(): string { }); } -export function useSidebarStageBackdropVariant(enabled = true): SidebarStageBackdropVariant | null { - return resolveSidebarStageBackdropVariant(useEnvironmentStageLabel(), enabled); +export function useSidebarStageBackdropVariant( + mode: EnvironmentIdentificationMode, +): SidebarStageBackdropVariant | null { + return resolveSidebarStageBackdropVariant(useEnvironmentStageLabel(), mode); } export function SidebarStageBackdrop({ variant }: { variant: SidebarStageBackdropVariant }) { @@ -55,7 +60,7 @@ export function SidebarStageBackdrop({ variant }: { variant: SidebarStageBackdro ); } -export function StageBackdropArt({ variant }: { variant: SidebarStageBackdropVariant }) { +function StageBackdropArt({ variant }: { variant: SidebarStageBackdropVariant }) { return variant === "nightly" ? : ; } diff --git a/apps/web/src/components/SourceControlAppAccessNotice.tsx b/apps/web/src/components/SourceControlAppAccessNotice.tsx new file mode 100644 index 0000000000000..4267b53150207 --- /dev/null +++ b/apps/web/src/components/SourceControlAppAccessNotice.tsx @@ -0,0 +1,68 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { + readHostCredentialSettings, + sourceControlClients, +} from "@t3tools/client-runtime/source-control-clients"; +import { ExternalLinkIcon } from "lucide-react"; + +import { useEnvironmentSettings } from "../hooks/useSettings"; +import { cn } from "../lib/utils"; +import { useEnvironmentQuery } from "../state/query"; +import { sourceControlEnvironment } from "../state/sourceControl"; +import { T3AppIcon } from "./T3AppIcon"; +import { InlineButton } from "./ui/button"; + +/** + * Says when the server's forge app sign-in cannot reach `repository`, so requests there fall back + * to the user's own login. Renders nothing for servers that do not use the app. + */ +export function SourceControlAppAccessNotice(props: { + readonly environmentId: EnvironmentId; + readonly provider: string | undefined; + readonly host: string | undefined; + /** `owner/name`. */ + readonly repository: string; + readonly className?: string; +}) { + const definition = props.provider ? sourceControlClients.find(props.provider) : undefined; + const appSignIn = definition?.credentials?.appSignIn; + const host = (props.host ?? definition?.publicHost ?? "").toLowerCase(); + const signedIn = useEnvironmentSettings(props.environmentId, (settings) => + definition === undefined + ? false + : (readHostCredentialSettings(settings, definition.kind).signIns[host] ?? "").length > 0, + ); + const access = useEnvironmentQuery( + definition !== undefined && appSignIn?.hosts.includes(host) && signedIn + ? sourceControlEnvironment.appAccess({ + environmentId: props.environmentId, + input: { provider: definition.kind, host, repository: props.repository }, + }) + : null, + ); + if (appSignIn === undefined || access.data?.status !== "not-covered") return null; + const owner = props.repository.split("/")[0] ?? props.repository; + + return ( +
+ +

+ {appSignIn.appName} isn't installed on {owner}, so + requests here use your own GitHub login and its lower rate limit. +

+ } + > + Install on {owner} + + +
+ ); +} diff --git a/apps/web/src/components/T3AppIcon.tsx b/apps/web/src/components/T3AppIcon.tsx new file mode 100644 index 0000000000000..7e3ebef5692b1 --- /dev/null +++ b/apps/web/src/components/T3AppIcon.tsx @@ -0,0 +1,6 @@ +// The production icon, as GitHub shows the T3 Code app, whatever this build's channel. +import appIconUrl from "../../../../assets/prod/t3-black-web-apple-touch-180.png"; + +export function T3AppIcon(props: { readonly className?: string }) { + return ; +} diff --git a/apps/web/src/components/ThreadContextChip.tsx b/apps/web/src/components/ThreadContextChip.tsx index 5f1a4202f1d36..715a210f4e917 100644 --- a/apps/web/src/components/ThreadContextChip.tsx +++ b/apps/web/src/components/ThreadContextChip.tsx @@ -30,7 +30,7 @@ export function ThreadContextChip(props: { className="no-underline" > {project ? ( - + ) : ( )} diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index f253dd6be22c7..ae2ed3d10de3c 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -1,4 +1,3 @@ -import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox"; import type { AnyRouter } from "@tanstack/react-router"; import { EnvironmentId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -6,7 +5,7 @@ import * as Option from "effect/Option"; import { Atom, AtomRegistry } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; -import { fakeTimers, stubGlobal } from "../../test/render"; +import { stubGlobal } from "../../test/render"; const state = vi.hoisted(() => ({ mode: "notifications", @@ -45,6 +44,19 @@ vi.mock(import("../state/presentation"), async (original) => { }, }; }); +vi.mock(import("../state/threads"), async (original) => { + const actual = await original(); + return { + ...actual, + environmentThreadShells: { + ...actual.environmentThreadShells, + pendingSubagentRequestsAtom: (() => noRequestsAtom) as never, + get delegatedUnderParentAtom() { + return noDelegatedAtom as never; + }, + }, + }; +}); vi.mock(import("../hooks/useSettings"), async (original) => ({ ...(await original()), subscribeClientSettings: ((listener: () => void) => { @@ -68,6 +80,8 @@ import { startThreadNotifications } from "./ThreadNotificationCoordinator"; let registry: AtomRegistry.AtomRegistry; const shellAtom = Atom.family((_id: string) => Atom.make(null)); const environmentIdsAtom = Atom.make>([]); +const noRequestsAtom = Atom.make(new Map()); +const noDelegatedAtom = Atom.make>(new Set()); state.shells = { set: (id, value) => registry.set(shellAtom(id), value) }; class TestNotification extends EventTarget { @@ -226,22 +240,79 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)( }, ); -it("holds a completion through a continuation gap and notifies once it settles", async () => { +it("presents completion notifications and sound as soon as the shell completes", async () => { await using app = setup(); + state.mode = "notifications-and-sound"; app.start(); - using _timers = fakeTimers(); - const finished = (turnId: string, completedAt: string) => ({ - latestTurn: { turnId, state: "completed", completedAt }, - }); - state.shells.set("one", shell(finished("turn-1", "2026-09-13T07:00:01.000Z"))); state.shells.set( "one", - shell({ latestTurn: { turnId: "turn-2", state: "running", completedAt: null } }), + shell({ + latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:00:01.000Z" }, + }), ); - state.shells.set("one", shell(finished("turn-2", "2026-09-13T07:00:02.000Z"))); - expect(TestNotification.sent).toEqual([]); - await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS - 1); - expect(TestNotification.sent).toEqual([]); - await vi.advanceTimersByTimeAsync(1); expect(TestNotification.sent.map((sent) => sent.title)).toEqual(["Thread completed"]); + expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function)); }); + +it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)( + "notifies for offline completion and %s once across reconnects", + async (flag) => { + await using app = setup(); + const asking = { id: "asking", hasPendingApprovals: true }; + const offline = { id: "offline", [flag]: true }; + const done = { + id: "done", + latestTurn: { + turnId: "done-turn", + state: "completed", + completedAt: "2026-09-13T07:00:00.000Z", + }, + }; + state.shells.set("one", shell({ id: "working" }, { id: "asking" }, { id: "offline" }, done)); + app.start(); + state.shells.set("one", shell({ id: "working" }, asking, { id: "offline" }, done)); + state.shells.set("one", { + ...shell({ id: "working" }, asking, { id: "offline" }, done), + status: "cached", + }); + + const completed = { + id: "working", + latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:05:00.000Z" }, + }; + state.shells.set("one", { + ...shell(completed, asking, offline, done), + status: "synchronizing", + }); + state.shells.set("one", shell(completed, asking, offline, done)); + + expect(TestNotification.sent.map(({ title }) => title)).toEqual([ + "Approval needed", + "Thread completed", + flag === "hasPendingApprovals" ? "Approval needed" : "Input needed", + ]); + state.shells.set("one", { ...shell(completed, asking, offline, done), status: "cached" }); + state.shells.set("one", shell(completed, asking, offline, done)); + expect(TestNotification.sent.map(({ title }) => title)).toEqual([ + "Approval needed", + "Thread completed", + flag === "hasPendingApprovals" ? "Approval needed" : "Input needed", + ]); + }, +); + +it.each([false, true])( + "does not replay a notified completion after reconnect (continued: %s)", + async (continued) => { + await using app = setup(); + app.start(); + const completed = shell({ + latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:05:00.000Z" }, + }); + state.shells.set("one", completed); + state.shells.set("one", { ...completed, status: "cached" }); + expect(TestNotification.sent.map(({ title }) => title)).toEqual(["Thread completed"]); + state.shells.set("one", continued ? shell() : completed); + expect(TestNotification.sent.map(({ title }) => title)).toEqual(["Thread completed"]); + }, +); diff --git a/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts index 2bba09f54dcb1..a89e4159cae10 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts @@ -1,5 +1,4 @@ -import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import { createThreadNotificationGate, @@ -30,164 +29,85 @@ function harness() { } describe("createThreadNotificationGate", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - afterEach(() => { - vi.useRealTimers(); - }); - - it("drops a completion when the thread resumes within the grace", () => { - const { notify, observe } = harness(); - observe(working); - observe(completed(1)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS - 1); - observe(working); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2); - expect(notify).not.toHaveBeenCalled(); - }); - - it("notifies a real completion once after the grace", () => { + it("notifies a completion immediately and only once", () => { const { notify, observe } = harness(); observe(working); observe(completed(1)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS - 1); - expect(notify).not.toHaveBeenCalled(); - vi.advanceTimersByTime(1); expect(notify.mock.calls).toEqual([["thread", "completion"]]); observe({ ...completed(1) }); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2); - expect(notify).toHaveBeenCalledTimes(1); - }); - - it("notifies attention at once and replaces a pending completion", () => { - const { notify, observe } = harness(); observe(working); observe(completed(1)); - vi.advanceTimersByTime(500); - observe({ attention: "run-1:approval", settled: false, completedAt: null }); - expect(notify.mock.calls).toEqual([["thread", "input"]]); - vi.advanceTimersByTime(60_000); - // The request resolves and the same run reads as completed again. - observe(completed(1)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2); - expect(notify.mock.calls).toEqual([["thread", "input"]]); + expect(notify).toHaveBeenCalledTimes(1); }); - it("notifies one completion across continuation gaps", () => { + it("notifies each newer completion immediately", () => { const { notify, observe } = harness(); observe(working); observe(completed(1)); - vi.advanceTimersByTime(300); observe(working); - vi.advanceTimersByTime(5_000); observe(completed(2)); - vi.advanceTimersByTime(300); - observe(working); - vi.advanceTimersByTime(5_000); - observe(completed(3)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS); - expect(notify.mock.calls).toEqual([["thread", "completion"]]); + expect(notify.mock.calls).toEqual([ + ["thread", "completion"], + ["thread", "completion"], + ]); + observe(completed(1)); + expect(notify).toHaveBeenCalledTimes(2); }); - it("keeps a completion interrupted by attention after a working gap from firing", () => { + it("notifies attention once and still notifies the subsequent completion", () => { const { notify, observe } = harness(); observe(working); - observe(completed(1)); - vi.advanceTimersByTime(500); + const attention = { attention: "run-1:approval", settled: false, completedAt: null }; + observe(attention); + expect(notify.mock.calls).toEqual([["thread", "input"]]); + observe({ ...attention }); + expect(notify).toHaveBeenCalledTimes(1); observe(working); - observe({ attention: "run-1:approval", settled: false, completedAt: null }); - vi.advanceTimersByTime(60_000); observe(completed(1)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2); - expect(notify.mock.calls).toEqual([["thread", "input"]]); + expect(notify.mock.calls).toEqual([ + ["thread", "input"], + ["thread", "completion"], + ]); }); - it("adds nothing when attention follows a completion that already fired", () => { + it("does not replay a completion after attention resolves", () => { const { notify, observe } = harness(); observe(working); observe(completed(1)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS); observe({ attention: "run-1:limited", settled: false, completedAt: null }); observe(completed(1)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2); expect(notify.mock.calls).toEqual([ ["thread", "completion"], ["thread", "input"], ]); }); - it("still notifies a newer completion after attention", () => { + it("never notifies existing, archived or stopped completions, including when unarchived", () => { const { notify, observe } = harness(); - observe(working); observe(completed(1)); - vi.advanceTimersByTime(500); - observe({ attention: "run-2:approval", settled: false, completedAt: null }); observe(working); + observe(completed(2), { ...visible, quiet: true }); observe(completed(2)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS); - expect(notify.mock.calls).toEqual([ - ["thread", "input"], - ["thread", "completion"], - ]); - }); - - it("ignores unrelated updates while a completion waits", () => { - const { notify, observe } = harness(); observe(working); - observe(completed(1)); - vi.advanceTimersByTime(1_500); - observe({ ...completed(1) }); - vi.advanceTimersByTime(500); - expect(notify).toHaveBeenCalledTimes(1); - }); - - it("notifies a run that settles again after a brief runtime blip", () => { - const { notify, observe } = harness(); - observe(working); - observe(completed(1)); - vi.advanceTimersByTime(500); + observe(completed(3), { ...visible, archived: true }); + observe(completed(3)); + expect(notify).not.toHaveBeenCalled(); observe(working); - observe(completed(1)); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS); + observe(completed(4)); expect(notify.mock.calls).toEqual([["thread", "completion"]]); }); - it("restarts the grace when a newer completion replaces a pending one", () => { - const { notify, observe } = harness(); - observe(working); - observe(completed(1)); - vi.advanceTimersByTime(1_500); - observe(completed(2)); - vi.advanceTimersByTime(1_500); - expect(notify).not.toHaveBeenCalled(); - vi.advanceTimersByTime(500); - expect(notify).toHaveBeenCalledTimes(1); - }); - - it("drops a pending completion on archive, stop request, removal or clear", () => { - for (const end of [ - (h: ReturnType) => h.observe(completed(1), { ...visible, archived: true }), - (h: ReturnType) => - h.observe({ ...completed(1) }, { ...visible, quiet: true }), - (h: ReturnType) => h.gate.retain(new Set()), - (h: ReturnType) => h.gate.clear(), + it("forgets handled completions when a thread is removed or the gate is cleared", () => { + for (const reset of [ + (gate: ReturnType>) => gate.retain(new Set()), + (gate: ReturnType>) => gate.clear(), ]) { - const h = harness(); - h.observe(working); - h.observe(completed(1)); - end(h); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2); - expect(h.notify).not.toHaveBeenCalled(); + const { gate, notify, observe } = harness(); + observe(completed(1)); + reset(gate); + gate.observe("thread", undefined, working, visible); + gate.observe("thread", working, completed(1), visible); + expect(notify.mock.calls).toEqual([["thread", "completion"]]); } }); - - it("never notifies a stopped run or the first observation", () => { - const { notify, observe } = harness(); - observe(completed(1)); - observe(working); - observe(completed(2), { ...visible, quiet: true }); - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2); - expect(notify).not.toHaveBeenCalled(); - }); }); diff --git a/apps/web/src/components/ThreadNotificationCoordinator.logic.ts b/apps/web/src/components/ThreadNotificationCoordinator.logic.ts index 77edccfbe7741..1fe126ad37da3 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.logic.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.logic.ts @@ -1,5 +1,3 @@ -import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox"; - export type ThreadNotificationKind = "input" | "completion"; export interface ThreadNotificationObservation { @@ -11,23 +9,11 @@ export interface ThreadNotificationObservation { readonly completedAt: number | null; } -/** - * Attention notifies at once. Completion waits out the Working shelf's exit grace, - * because an orchestrator run can end moments before its continuation starts. Any - * observation that is not settled during the wait cancels it. - */ export function createThreadNotificationGate( notify: (key: Key, kind: ThreadNotificationKind) => void, ) { - const pending = new Map }>(); // The newest completion already notified, or deliberately skipped. const handled = new Map(); - // The newest completion seen settled, kept while the thread works or waits. - const lastSettled = new Map(); - const cancel = (key: Key) => { - clearTimeout(pending.get(key)?.timer); - pending.delete(key); - }; const skip = (key: Key, at: number | null) => { if (at !== null && at > (handled.get(key) ?? -Infinity)) handled.set(key, at); }; @@ -38,41 +24,24 @@ export function createThreadNotificationGate( next: ThreadNotificationObservation, options: { readonly archived: boolean; readonly quiet: boolean }, ): void { - if (next.settled && next.completedAt !== null) lastSettled.set(key, next.completedAt); - if (!next.settled || options.archived || options.quiet) cancel(key); // The first sighting, archived threads, and stopped or silent runs never notify completion. if (!prior || options.archived || options.quiet) skip(key, next.completedAt); if (!prior || options.archived) return; if (next.attention && next.attention !== prior.attention) { - // Attention replaces the completion before it, so that run must not notify later. - skip(key, lastSettled.get(key) ?? null); - cancel(key); notify(key, "input"); return; } const at = next.completedAt; if (!next.settled || at === null || at <= (handled.get(key) ?? -Infinity)) return; - if (pending.get(key)?.at === at) return; - cancel(key); - pending.set(key, { - at, - timer: setTimeout(() => { - pending.delete(key); - handled.set(key, at); - notify(key, "completion"); - }, WORKING_EXIT_GRACE_MS), - }); + handled.set(key, at); + notify(key, "completion"); }, /** Forgets threads that left the snapshot. */ retain(keys: ReadonlySet): void { - for (const key of pending.keys()) if (!keys.has(key)) cancel(key); for (const key of handled.keys()) if (!keys.has(key)) handled.delete(key); - for (const key of lastSettled.keys()) if (!keys.has(key)) lastSettled.delete(key); }, clear(): void { - for (const key of pending.keys()) cancel(key); handled.clear(); - lastSettled.clear(); }, }; } diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index a782e24da6522..a7134b481d131 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -3,8 +3,9 @@ import { type PendingSubagentRequest, presentThreadShell, } from "@t3tools/client-runtime/state/models"; -import { pendingSubagentRequestsByThread } from "@t3tools/client-runtime/state/threads"; +import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; import type { AnyRouter } from "@tanstack/react-router"; +import { threadKey } from "@t3tools/client-runtime/state/entities"; import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; import type { ClientSettings } from "@t3tools/contracts/settings"; import * as Option from "effect/Option"; @@ -20,6 +21,7 @@ import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings import { isWindowsPlatform } from "../lib/utils"; import { environmentSummaries } from "../state/presentation"; import { environmentShell } from "../state/shell"; +import { environmentThreadShells } from "../state/threads"; import { hasDesktopNotifications, hasNotificationSound, @@ -43,9 +45,12 @@ interface NotificationState extends ThreadNotificationObservation { readonly status: SidebarThreadStatus; } +type ToastId = ReturnType; + interface WatchedEnvironment { unsubscribe: () => void; previous: Map; + reconnecting: boolean; readonly gate: ReturnType>; } @@ -57,27 +62,67 @@ export function startThreadNotifications( registry: AtomRegistry.AtomRegistry, router: AnyRouter, ): () => void { - const pending = new Map(); + const pending = new Map< + string, + { environmentId: EnvironmentId; threadId: ThreadId; notification: Notification } + >(); const watched = new Map(); - const trackNotification = (environmentId: EnvironmentId, notification: Notification) => { + const trackNotification = ( + environmentId: EnvironmentId, + threadId: ThreadId, + notification: Notification, + ) => { pending.get(notification.tag)?.notification.close(); - pending.set(notification.tag, { environmentId, notification }); + pending.set(notification.tag, { environmentId, threadId, notification }); setNotificationBadge(pending.size); }; + // Toast ids by thread key, so hiding a thread can close its open toasts. + const openToasts = new Map>(); + const forgetToast = (key: string, toastId: ToastId) => { + const remaining = (openToasts.get(key) ?? []).filter((id) => id !== toastId); + if (remaining.length === 0) openToasts.delete(key); + else openToasts.set(key, remaining); + }; + // A notification shown before the tag filter turned on must not stay on screen. While hiding, + // one whose thread left the live list (archived) cannot be judged, so it closes too. + const closeHiddenPending = () => { + const hidden = registry.get(environmentThreadShells.hiddenThreadKeysAtom); + const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom) + ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey)) + : null; + const shouldClose = (key: string) => hidden.has(key) || (live !== null && !live.has(key)); + for (const [key, toastIds] of openToasts) { + if (!shouldClose(key)) continue; + for (const toastId of toastIds) toastManager.close(toastId); + openToasts.delete(key); + } + const count = pending.size; + for (const [tag, entry] of pending) { + if (!shouldClose(threadKey(entry))) continue; + entry.notification.close(); + pending.delete(tag); + } + if (count !== pending.size) setNotificationBadge(pending.size); + }; const clearPending = () => { for (const { notification } of pending.values()) notification.close(); pending.clear(); setNotificationBadge(0); }; - // Completions fire from a timer, so read settings, focus and route when presenting. const present = ( environmentId: EnvironmentId, state: NotificationState, kind: ThreadNotificationKind, ) => { const { thread, status } = state; + if ( + registry + .get(environmentThreadShells.hiddenThreadKeysAtom) + .has(threadKey({ environmentId, threadId: thread.id })) + ) + return; const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings(); const active = (router.state.matches.at(-1)?.params ?? {}) as { environmentId?: string; @@ -106,7 +151,9 @@ export function startThreadNotifications( document.hasFocus() && (active.environmentId !== environmentId || active.threadId !== thread.id) ) { - const toastId = toastManager.add({ + const toastKey = threadKey({ environmentId, threadId: thread.id }); + const toastId: ToastId = toastManager.add({ + onRemove: (): void => forgetToast(toastKey, toastId), type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning", title, description: thread.title, @@ -117,6 +164,8 @@ export function startThreadNotifications( ) : status === "approval" ? ( + ) : status === "limited" ? ( + ) : status === "failed" ? ( ) : ( @@ -134,6 +183,7 @@ export function startThreadNotifications( }, }, }); + openToasts.set(toastKey, [...(openToasts.get(toastKey) ?? []), toastId]); return; } if ( @@ -151,11 +201,11 @@ export function startThreadNotifications( // Windows drops clicks after a toast moves into Notification Center. requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform), }); - trackNotification(environmentId, notification); + trackNotification(environmentId, thread.id, notification); notification.addEventListener("click", () => { notification.close(); window.focus(); - void window.desktopBridge?.revealWindow?.().catch(() => undefined); + void window.desktopBridge?.revealWindow().catch(() => undefined); void router.navigate({ to: "/$environmentId/$threadId", params: { environmentId, threadId: thread.id }, @@ -173,13 +223,29 @@ export function startThreadNotifications( ) => { const previous = entry.previous; const next = new Map(); - const subagentRequests = pendingSubagentRequestsByThread(threads); + // A parent here also hears of what its tasks on linked environments ask. + const subagentRequests = registry.get( + environmentThreadShells.pendingSubagentRequestsAtom(environmentId), + ); + const delegatedUnderParent = registry.get(environmentThreadShells.delegatedUnderParentAtom); const changed: Array<[NotificationState | undefined, NotificationState]> = []; for (const rawThread of threads) { - if (rawThread.lineage.relationshipToParent === "subagent") continue; + if ( + isShownUnderParent( + { environmentId, threadId: rawThread.id }, + rawThread.lineage, + delegatedUnderParent, + ) + ) { + continue; + } const prior = previous.get(rawThread.id); const subagentRequest = subagentRequests.get(rawThread.id) ?? null; - if (prior?.raw === rawThread && prior.subagentRequest === subagentRequest) { + if ( + !entry.reconnecting && + prior?.raw === rawThread && + prior.subagentRequest === subagentRequest + ) { next.set(rawThread.id, prior); continue; } @@ -208,6 +274,7 @@ export function startThreadNotifications( next.set(thread.id, state); changed.push([prior, state]); } + entry.reconnecting = false; entry.previous = next; entry.gate.retain(new Set(next.keys())); for (const [prior, state] of changed) { @@ -221,16 +288,18 @@ export function startThreadNotifications( const watchEnvironment = (environmentId: EnvironmentId): WatchedEnvironment => { const entry: WatchedEnvironment = { previous: new Map(), + reconnecting: false, unsubscribe: () => {}, gate: createThreadNotificationGate((threadId, kind) => { const state = entry.previous.get(threadId); if (state) present(environmentId, state, kind); }), }; + let threads: ReadonlyArray | null = null; const unsubscribeShell = registry.subscribe( environmentShell.stateValueAtom(environmentId), (shell) => { - const threads = + threads = shell.status === "live" && Option.isSome(shell.snapshot) ? shell.snapshot.value.threads : null; @@ -238,13 +307,25 @@ export function startThreadNotifications( observeThreads(environmentId, entry, threads); return; } - entry.gate.clear(); - entry.previous = new Map(); + entry.reconnecting = true; }, { immediate: true }, ); + const reobserve = () => { + if (threads !== null) observeThreads(environmentId, entry, threads); + }; + const unsubscribeRequests = registry.subscribe( + environmentThreadShells.pendingSubagentRequestsAtom(environmentId), + reobserve, + ); + const unsubscribeDelegated = registry.subscribe( + environmentThreadShells.delegatedUnderParentAtom, + reobserve, + ); entry.unsubscribe = () => { unsubscribeShell(); + unsubscribeRequests(); + unsubscribeDelegated(); entry.gate.clear(); }; return entry; @@ -287,7 +368,7 @@ export function startThreadNotifications( clearPending(); const stops: Array<() => void> = []; if (hasDesktopNotifications(nextMode)) { - const unsubscribeBadgeClear = window.desktopBridge?.onNotificationBadgeClear?.(clearPending); + const unsubscribeBadgeClear = window.desktopBridge?.onNotificationBadgeClear(clearPending); window.addEventListener("focus", clearPending); stops.push(() => { unsubscribeBadgeClear?.(); @@ -320,11 +401,17 @@ export function startThreadNotifications( syncEnvironments(); }, ); + const unsubscribeHidden = [ + registry.subscribe(environmentThreadShells.hiddenThreadKeysAtom, closeHiddenPending), + registry.subscribe(environmentThreadShells.anyEnvironmentHidingAtom, closeHiddenPending), + registry.subscribe(environmentThreadShells.threadRefsAtom, closeHiddenPending), + ]; onSettings(); return () => { unsubscribeSettings(); unsubscribeEnvironmentIds(); + for (const unsubscribe of unsubscribeHidden) unsubscribe(); for (const entry of watched.values()) entry.unsubscribe(); watched.clear(); stopModeListeners(); diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index 30ee70d0dd637..30ab2465a9dec 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -1,4 +1,8 @@ +import { useAtomValue } from "@effect/atom-react"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities"; +import { visibilityParentKey } from "@t3tools/client-runtime/state/threads"; +import * as Option from "effect/Option"; import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; @@ -7,9 +11,13 @@ import { BackgroundThreadContext } from "./chat/backgroundThread"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; -import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities"; +import { + useEnvironmentThreadRefs, + useAnyEnvironmentHiding, + useQuietThreadShell, +} from "../state/entities"; import { useEnvironmentShellStatus } from "../state/shell"; -import { useEnvironmentThread } from "../state/threads"; +import { environmentThreadShells, useEnvironmentThread } from "../state/threads"; import { buildThreadRouteParams, isThreadRouteSnapshotAuthoritative, @@ -80,6 +88,28 @@ export function ThreadRouteView({ unlistedThreadRef?.environmentId ?? null, unlistedThreadRef?.threadId ?? null, ); + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + const unlistedThread = Option.getOrNull(Option.map(unlistedThreadDetail.data, (p) => p.thread)); + const unlistedParentKey = + unlistedThreadRef === null || unlistedThread === null + ? null + : visibilityParentKey(unlistedThreadRef.environmentId, unlistedThread); + const unlistedParentShell = useQuietThreadShell( + unlistedParentKey === null ? null : parseThreadKey(unlistedParentKey), + ); + const hidingAnywhere = useAnyEnvironmentHiding(); + const draftRedirectShell = useQuietThreadShell(draftRedirect ?? null); + const hiddenByTagFilter = serverThreadRef !== null && hiddenKeys.has(threadKey(serverThreadRef)); + // Cached detail can predate a tag or an archive, so while hiding an off-shell thread opens only + // as the child of a loaded, visible parent (lineage never changes); anything else stays closed. + const offShellBlocked = + hidingAnywhere && + unlistedThreadRef !== null && + !( + unlistedParentKey !== null && + unlistedParentShell !== null && + !hiddenKeys.has(unlistedParentKey) + ); const renderState = resolveThreadRouteRenderState({ bootstrapComplete, serverThreadExists: serverThreadShell !== null, @@ -89,6 +119,7 @@ export function ThreadRouteView({ }); const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears pending file drops and navigates the router home once a server thread is confirmed missing useEffect(() => { if (target.kind !== "server" || !bootstrapComplete) { return; @@ -105,7 +136,15 @@ export function ThreadRouteView({ let view: React.ReactNode = null; let redirect: React.ReactNode = null; if (target.kind === "draft") { - if (draftSession) { + if ( + draftSession && + hiddenKeys.has( + threadKey({ environmentId: draftSession.environmentId, threadId: draftSession.threadId }), + ) + ) { + // A draft whose thread is already live and hidden (mid-promotion): never mount it. + redirect = ; + } else if (draftSession) { view = ( ); + } else if (draftRedirect && hiddenKeys.has(threadKey(draftRedirect))) { + // Back to a promoted draft whose thread is now hidden: never mount it. + redirect = ; + } else if (draftRedirect && hidingAnywhere && draftRedirectShell === null) { + // While hiding, a thread outside the live list is judged by the server route, unmounted here. + redirect = ( + + ); } else if (draftRedirect) { // Same slot and key as the server route renders, so the swap keeps this instance. view = ( @@ -136,6 +187,11 @@ export function ThreadRouteView({ } else { redirect = ; } + } else if (hiddenByTagFilter) { + redirect = ; + } else if (offShellBlocked) { + // Before the shell bootstraps, a listed visible thread can still look off-shell. + if (bootstrapComplete && unlistedThread !== null) redirect = ; } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) { view = ( ({ + ...(await original()), + useProject: () => null, + useServerConfigs: (() => + new Map([ + [environmentId, { environment: { capabilities: { threadPullRequests: true } } }], + ])) as never, +})); + +it("updates palette PR status from linked snapshots without a legacy link or branch PR", async () => { + const link: ThreadPullRequestLink = { + host: "github.com", + repository: "example/repo", + number: 7, + url: "https://github.com/example/repo/pull/7", + source: "manual", + linkedAt: "2026-01-01T00:00:00Z", + stack: null, + snapshot: { + state: "merged", + title: "Linked change", + headBranch: "deleted-branch", + baseBranch: "main", + isDraft: false, + updatedAt: null, + syncedAt: "2026-01-03T00:00:00Z", + }, + }; + const row = (pullRequest: ThreadPullRequestLink) => ( + + + + ); + await using screen = await render(row(link)); + await expect.element(screen.getByLabelText("PR #7 - Merged: Linked change")).toBeVisible(); + await expect.element(screen.getByLabelText("PR #7, status pending")).not.toBeInTheDocument(); + + await screen.rerender(row({ ...link, snapshot: null })); + await expect.element(screen.getByLabelText("PR #7, status pending")).toBeVisible(); + await expect + .element(screen.getByLabelText("PR #7 - Merged: Linked change")) + .not.toBeInTheDocument(); + + await screen.rerender( + row({ ...link, snapshot: { ...link.snapshot!, state: "open", isDraft: true } }), + ); + await expect.element(screen.getByLabelText("PR #7 - Draft: Linked change")).toBeVisible(); + await expect.element(screen.getByLabelText("PR #7, status pending")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/ThreadStatusIndicators.test.ts b/apps/web/src/components/ThreadStatusIndicators.test.ts index 8ef5d75269b13..caba939c26e01 100644 --- a/apps/web/src/components/ThreadStatusIndicators.test.ts +++ b/apps/web/src/components/ThreadStatusIndicators.test.ts @@ -1,17 +1,10 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; import { ProjectId, type PullRequestSummary, type VcsStatusResult } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import { AtomRegistry } from "effect/reactivity"; import { - nextThreadChangeRequestSnapshot, resolveDisplayedThreadPr, resolveDisplayedThreadPrProvider, - resolveThreadPr, - threadChangeRequestSnapshotsEqual, - threadChangeRequestSnapshotsAtom, - type ThreadChangeRequestSnapshot, } from "./ThreadStatusIndicators"; import { newestPullRequestSummary } from "../state/pullRequests"; @@ -49,14 +42,6 @@ function mergedFeaturePr(): NonNullable { }; } -function snapshotFor( - branch: string, - pr: NonNullable, - sourceControlProvider?: VcsStatusResult["sourceControlProvider"], -): ThreadChangeRequestSnapshot { - return { branch, pr, sourceControlProvider }; -} - function pullRequestSummary( state: PullRequestSummary["state"], updatedAt: string, @@ -91,18 +76,7 @@ describe("shared pull request state", () => { }); }); -describe("resolveThreadPr", () => { - it("hides PR indicators when a dedicated worktree has switched away from the thread branch", () => { - expect( - resolveThreadPr({ - threadBranch: "stack/base", - gitStatus: status(), - }), - ).toBeNull(); - }); -}); - -describe("resolveDisplayedThreadPr + nextThreadChangeRequestSnapshot", () => { +describe("resolveDisplayedThreadPr", () => { const featureBranch = "feature/current"; const mergedPr = mergedFeaturePr(); const linkedPullRequest = { @@ -118,162 +92,15 @@ describe("resolveDisplayedThreadPr + nextThreadChangeRequestSnapshot", () => { }; it("shows a linked pull request when the checkout has a different branch", () => { - const linkedPullRequestStatus = { - pr: mergedPr, - sourceControlProvider: provider, - }; - - expect( - resolveDisplayedThreadPr({ - threadBranch: "feature/other", - gitStatus: status({ refName: "feature/other", pr: null }), - snapshot: undefined, - retainTerminalOnBranchMismatch: false, - linkedPullRequest, - linkedPullRequestStatus, - }), - ).toEqual(mergedPr); - expect( - resolveDisplayedThreadPrProvider({ - threadBranch: "feature/other", - gitStatus: status({ refName: "feature/other", pr: null }), - snapshot: undefined, - retainTerminalOnBranchMismatch: false, - linkedPullRequest, - linkedPullRequestStatus, - }), - ).toEqual(provider); - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: "feature/other", - gitStatus: status({ refName: "feature/other", pr: null }), - snapshot: undefined, - retainTerminalOnBranchMismatch: false, - linkedPullRequest, - linkedPullRequestStatus, - }), - ).toEqual({ - branch: "feature/other", - pr: mergedPr, - sourceControlProvider: provider, - linkedPullRequest, - }); - }); - - it("keeps a matching linked pull request snapshot while its status reloads", () => { - const snapshot = { - ...snapshotFor(featureBranch, mergedPr, provider), - linkedPullRequest, - }; - - expect( - resolveDisplayedThreadPr({ - threadBranch: null, - gitStatus: null, - snapshot, - retainTerminalOnBranchMismatch: false, - linkedPullRequest, - linkedPullRequestStatus: null, - }), - ).toEqual(mergedPr); - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: null, - gitStatus: null, - snapshot, - retainTerminalOnBranchMismatch: false, - linkedPullRequest, - linkedPullRequestStatus: null, - }), - ).toBeUndefined(); - }); - - it("clears an old snapshot when a different pull request is linked", () => { - const snapshot = { - ...snapshotFor(featureBranch, mergedPr, provider), - linkedPullRequest: { ...linkedPullRequest, number: 41 }, - }; - - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: featureBranch, - gitStatus: null, - snapshot, - retainTerminalOnBranchMismatch: true, - linkedPullRequest, - linkedPullRequestStatus: null, - }), - ).toBeNull(); - }); - - it("removes a linked pull request snapshot after the link is cleared", () => { - const snapshot = { - ...snapshotFor(featureBranch, mergedPr, provider), + const input = { + threadBranch: "feature/other", + gitStatus: status({ refName: "feature/other", pr: null }), linkedPullRequest, + linkedPullRequestStatus: { pr: mergedPr, sourceControlProvider: provider }, }; - expect( - resolveDisplayedThreadPr({ - threadBranch: featureBranch, - gitStatus: status({ refName: "main", pr: null }), - snapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeNull(); - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: featureBranch, - gitStatus: null, - snapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeNull(); - }); - - it("after caching a merged PR, resolves main status back to the cached feature PR", () => { - const matchingStatus = status({ - refName: featureBranch, - pr: mergedPr, - sourceControlProvider: provider, - }); - const cached = nextThreadChangeRequestSnapshot({ - threadBranch: featureBranch, - gitStatus: matchingStatus, - snapshot: undefined, - retainTerminalOnBranchMismatch: true, - }); - expect(cached).toEqual(snapshotFor(featureBranch, mergedPr, provider)); - - const mainStatus = status({ - refName: "main", - isDefaultRef: true, - pr: { - number: 99, - title: "Unrelated main PR", - url: "https://github.com/pingdotgg/t3code/pull/99", - baseRef: "main", - headRef: "main", - state: "open", - }, - sourceControlProvider: provider, - }); - - expect( - resolveDisplayedThreadPr({ - threadBranch: featureBranch, - gitStatus: mainStatus, - snapshot: cached as ThreadChangeRequestSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toEqual(mergedPr); - expect( - resolveDisplayedThreadPrProvider({ - threadBranch: featureBranch, - gitStatus: mainStatus, - snapshot: cached as ThreadChangeRequestSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toEqual(provider); + expect(resolveDisplayedThreadPr(input)).toEqual(mergedPr); + expect(resolveDisplayedThreadPrProvider(input)).toEqual(provider); }); it("never attaches a PR reported by main to the feature thread", () => { @@ -289,215 +116,7 @@ describe("resolveDisplayedThreadPr + nextThreadChangeRequestSnapshot", () => { resolveDisplayedThreadPr({ threadBranch: featureBranch, gitStatus: status({ refName: "main", pr: mainPr }), - snapshot: undefined, - retainTerminalOnBranchMismatch: true, - }), - ).toBeNull(); - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: featureBranch, - gitStatus: status({ refName: "main", pr: mainPr }), - snapshot: undefined, - retainTerminalOnBranchMismatch: true, }), ).toBeNull(); }); - - it("does not show a cached open PR across a branch mismatch", () => { - const openSnapshot = snapshotFor(featureBranch, { - ...mergedPr, - state: "open", - title: "Still open", - }); - - expect( - resolveDisplayedThreadPr({ - threadBranch: featureBranch, - gitStatus: status({ refName: "main", pr: null }), - snapshot: openSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeNull(); - }); - - it("retains a cached closed PR across a branch mismatch", () => { - const closedPr = { ...mergedPr, state: "closed" as const, title: "Closed feature" }; - const closedSnapshot = snapshotFor(featureBranch, closedPr, provider); - - expect( - resolveDisplayedThreadPr({ - threadBranch: featureBranch, - gitStatus: status({ refName: "main", pr: null }), - snapshot: closedSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toEqual(closedPr); - }); - - it("does not retain or display a terminal PR when a worktree switches branches", () => { - const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider); - const mismatchedStatus = status({ refName: "feature/other", pr: null }); - - expect( - resolveDisplayedThreadPr({ - threadBranch: featureBranch, - gitStatus: mismatchedStatus, - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: false, - }), - ).toBeNull(); - expect( - resolveDisplayedThreadPrProvider({ - threadBranch: featureBranch, - gitStatus: mismatchedStatus, - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: false, - }), - ).toBeUndefined(); - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: featureBranch, - gitStatus: mismatchedStatus, - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: false, - }), - ).toBeNull(); - }); - - it("retains a terminal snapshot when a local thread and status move to a branch with no PR", () => { - const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider); - - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: "main", - gitStatus: status({ refName: "main", pr: null }), - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeUndefined(); - expect( - resolveDisplayedThreadPr({ - threadBranch: "main", - gitStatus: status({ refName: "main", pr: null }), - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toEqual(mergedPr); - }); - - it("clears an open snapshot when a local thread moves to a branch with no PR", () => { - const openSnapshot = snapshotFor(featureBranch, { ...mergedPr, state: "open" }); - - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: "main", - gitStatus: status({ refName: "main", pr: null }), - snapshot: openSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeNull(); - }); - - it("clears a retained snapshot when the thread branch is cleared", () => { - const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider); - - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: null, - gitStatus: status({ refName: "main", pr: null }), - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeNull(); - expect( - resolveDisplayedThreadPr({ - threadBranch: null, - gitStatus: status({ refName: "main", pr: null }), - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeNull(); - expect( - resolveDisplayedThreadPrProvider({ - threadBranch: null, - gitStatus: status({ refName: "main", pr: null }), - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeUndefined(); - }); - - it("does not erase a terminal snapshot when VCS data is missing", () => { - const terminalSnapshot = snapshotFor(featureBranch, mergedPr, provider); - - expect( - nextThreadChangeRequestSnapshot({ - threadBranch: featureBranch, - gitStatus: null, - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toBeUndefined(); - expect( - resolveDisplayedThreadPr({ - threadBranch: featureBranch, - gitStatus: null, - snapshot: terminalSnapshot, - retainTerminalOnBranchMismatch: true, - }), - ).toEqual(mergedPr); - }); - - it("shows the last matching PR snapshot while its live status lease is released", () => { - const openPr = { ...mergedPr, state: "open" as const }; - const input = { - threadBranch: featureBranch, - gitStatus: null, - snapshot: snapshotFor(featureBranch, openPr, provider), - retainTerminalOnBranchMismatch: false, - }; - expect(resolveDisplayedThreadPr(input)).toEqual(openPr); - expect(resolveDisplayedThreadPrProvider(input)).toEqual(provider); - expect(resolveDisplayedThreadPr({ ...input, threadBranch: "feature/other" })).toBeNull(); - expect( - resolveDisplayedThreadPr({ - ...input, - snapshot: { ...input.snapshot, linkedPullRequest }, - }), - ).toBeNull(); - }); - - it("refreshes a cached snapshot when a pull request becomes ready", () => { - const readyPr = { ...mergedPr, state: "open" as const }; - const draftPr = { ...readyPr, isDraft: true }; - - expect( - threadChangeRequestSnapshotsEqual( - snapshotFor(featureBranch, draftPr), - snapshotFor(featureBranch, readyPr), - ), - ).toBe(false); - }); -}); - -describe("threadChangeRequestSnapshotsAtom", () => { - it.effect("retains snapshots while sidebar and chat consumers are unmounted", () => - Effect.gen(function* () { - const registry = AtomRegistry.make(); - const threadKey = "environment-1:thread-1"; - const snapshot = snapshotFor("feature/current", mergedFeaturePr()); - - const unmount = registry.mount(threadChangeRequestSnapshotsAtom); - registry.set(threadChangeRequestSnapshotsAtom, new Map([[threadKey, snapshot]])); - unmount(); - - yield* Effect.yieldNow; - - const remount = registry.mount(threadChangeRequestSnapshotsAtom); - expect(registry.get(threadChangeRequestSnapshotsAtom).get(threadKey)).toEqual(snapshot); - - remount(); - registry.dispose(); - }), - ); }); diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 78b2a247ba5e5..ea49b01665b64 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -1,3 +1,4 @@ +import { pipe } from "effect/Function"; import { scopeProjectRef, scopedThreadKey, @@ -15,7 +16,6 @@ import { type ThreadPullRequestLink, type VcsStatusResult, } from "@t3tools/contracts"; -import { Atom } from "effect/reactivity"; import { FolderGit2Icon, TerminalIcon } from "lucide-react"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; @@ -326,8 +326,10 @@ export function ThreadPullRequestsMiniList({ pullRequests: ReadonlyArray; onOpenPullRequest?: (event: MouseEvent, url: string) => void; }) { - const lines = pullRequestListLines( - resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests)), + const lines = pipe( + visibleThreadPullRequests(pullRequests), + resolveThreadPullRequestChains, + pullRequestListLines, ); if (lines.length === 0) return null; return ( @@ -441,7 +443,7 @@ export function ChangeRequestStatusIcon({ return ; } -export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) { +function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) { return ( {status.tooltipLead} @@ -451,165 +453,15 @@ export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator } ); } -export function resolveThreadPr(input: { - threadBranch: string | null; - gitStatus: VcsStatusResult | null; -}): ThreadPr | null { - const { threadBranch, gitStatus } = input; - if (gitStatus === null) { - return null; - } - - if (threadBranch === null || gitStatus.refName !== threadBranch) { - return null; - } - - return gitStatus.pr ?? null; -} - -/** Hold terminal PR metadata above rows because settlement moves remount them. */ -export interface ThreadChangeRequestSnapshot { - readonly branch: string; - readonly pr: NonNullable; - readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined; - readonly linkedPullRequest?: ThreadLinkedPullRequest; -} - -export const threadChangeRequestSnapshotsAtom = Atom.make< - ReadonlyMap ->(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots")); - -function isTerminalChangeRequestState( - state: NonNullable["state"], -): state is "merged" | "closed" { - return state === "merged" || state === "closed"; -} - -function sourceControlProvidersEqual( - left: VcsStatusResult["sourceControlProvider"] | undefined, - right: VcsStatusResult["sourceControlProvider"] | undefined, -): boolean { - if (left === right) return true; - if (left == null || right == null) return left == null && right == null; - return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl; -} - -function linkedPullRequestsEqual( - left: ThreadLinkedPullRequest | null | undefined, - right: ThreadLinkedPullRequest | null | undefined, -): boolean { - if (left == null || right == null) return left == null && right == null; - return ( - left.projectId === right.projectId && - left.repository === right.repository && - left.number === right.number && - left.url === right.url - ); -} - -export function threadChangeRequestSnapshotsEqual( - left: ThreadChangeRequestSnapshot, - right: ThreadChangeRequestSnapshot, -): boolean { - return ( - left.branch === right.branch && - left.pr.number === right.pr.number && - left.pr.title === right.pr.title && - left.pr.url === right.pr.url && - left.pr.baseRef === right.pr.baseRef && - left.pr.headRef === right.pr.headRef && - left.pr.state === right.pr.state && - left.pr.isDraft === right.pr.isDraft && - (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) && - sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) && - linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest) - ); -} - -export function nextThreadChangeRequestSnapshot(input: { - threadBranch: string | null; - gitStatus: VcsStatusResult | null; - snapshot: ThreadChangeRequestSnapshot | null | undefined; - retainTerminalOnBranchMismatch: boolean; - linkedPullRequest?: ThreadLinkedPullRequest | null | undefined; - linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined; -}): ThreadChangeRequestSnapshot | null | undefined { - const { - threadBranch, - gitStatus, - snapshot, - retainTerminalOnBranchMismatch, - linkedPullRequest, - linkedPullRequestStatus, - } = input; - if (linkedPullRequest != null) { - if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) { - return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest) - ? undefined - : null; - } - return { - branch: threadBranch ?? linkedPullRequestStatus.pr.headRef, - pr: linkedPullRequestStatus.pr, - sourceControlProvider: linkedPullRequestStatus.sourceControlProvider, - linkedPullRequest, - }; - } - if (gitStatus === null) { - return snapshot?.linkedPullRequest === undefined ? undefined : null; - } - if (threadBranch === null) { - return null; - } - if (gitStatus.refName !== threadBranch) { - return retainTerminalOnBranchMismatch && - snapshot != null && - snapshot.linkedPullRequest === undefined && - isTerminalChangeRequestState(snapshot.pr.state) - ? undefined - : null; - } - if (gitStatus.pr == null) { - if ( - retainTerminalOnBranchMismatch && - snapshot != null && - snapshot.linkedPullRequest === undefined && - isTerminalChangeRequestState(snapshot.pr.state) - ) { - return undefined; - } - return null; - } - return { - branch: threadBranch, - pr: gitStatus.pr, - sourceControlProvider: gitStatus.sourceControlProvider, - }; -} - export function resolveDisplayedThreadPr(input: { threadBranch: string | null; gitStatus: VcsStatusResult | null; - snapshot: ThreadChangeRequestSnapshot | null | undefined; - retainTerminalOnBranchMismatch: boolean; linkedPullRequest?: ThreadLinkedPullRequest | null | undefined; linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined; }): ThreadPr | null { - const { - threadBranch, - gitStatus, - snapshot, - retainTerminalOnBranchMismatch, - linkedPullRequest, - linkedPullRequestStatus, - } = input; + const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input; if (linkedPullRequest != null) { - return ( - linkedPullRequestStatus?.pr ?? - (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest) - ? (snapshot?.pr ?? null) - : null) - ); + return linkedPullRequestStatus?.pr ?? null; } if ( threadBranch !== null && @@ -620,51 +472,18 @@ export function resolveDisplayedThreadPr(input: { return gitStatus.pr; } - if ( - gitStatus === null && - threadBranch !== null && - snapshot?.branch === threadBranch && - snapshot.linkedPullRequest === undefined - ) { - return snapshot.pr; - } - - if ( - threadBranch !== null && - retainTerminalOnBranchMismatch && - snapshot != null && - snapshot.linkedPullRequest === undefined && - isTerminalChangeRequestState(snapshot.pr.state) - ) { - return snapshot.pr; - } - return null; } export function resolveDisplayedThreadPrProvider(input: { threadBranch: string | null; gitStatus: VcsStatusResult | null; - snapshot: ThreadChangeRequestSnapshot | null | undefined; - retainTerminalOnBranchMismatch: boolean; linkedPullRequest?: ThreadLinkedPullRequest | null | undefined; linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined; }): VcsStatusResult["sourceControlProvider"] | undefined { - const { - threadBranch, - gitStatus, - snapshot, - retainTerminalOnBranchMismatch, - linkedPullRequest, - linkedPullRequestStatus, - } = input; + const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input; if (linkedPullRequest != null) { - return ( - linkedPullRequestStatus?.sourceControlProvider ?? - (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest) - ? snapshot?.sourceControlProvider - : undefined) - ); + return linkedPullRequestStatus?.sourceControlProvider; } if ( threadBranch !== null && @@ -675,25 +494,6 @@ export function resolveDisplayedThreadPrProvider(input: { return gitStatus.sourceControlProvider; } - if ( - gitStatus === null && - threadBranch !== null && - snapshot?.branch === threadBranch && - snapshot.linkedPullRequest === undefined - ) { - return snapshot.sourceControlProvider; - } - - if ( - threadBranch !== null && - retainTerminalOnBranchMismatch && - snapshot != null && - snapshot.linkedPullRequest === undefined && - isTerminalChangeRequestState(snapshot.pr.state) - ) { - return snapshot.sourceControlProvider; - } - return undefined; } @@ -803,7 +603,7 @@ export function ThreadWorktreeIndicator({ ); } -export function ThreadStatusLabel({ +function ThreadStatusLabel({ status, compact = false, }: { @@ -856,13 +656,7 @@ export function ThreadStatusLabel({ ); } -export function ThreadRowLeadingStatus({ - thread, - snapshot, -}: { - thread: SidebarThreadSummary; - snapshot?: ThreadChangeRequestSnapshot | undefined; -}) { +export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) { const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false); // A new ref callback would detach and reattach the row, and each reattach sets lease state. const statusRef = useStableCallback((node: HTMLSpanElement | null) => @@ -880,6 +674,8 @@ export function ThreadRowLeadingStatus({ thread.environmentId, thread.linkedPullRequest, leaseLiveStatus, + thread.pullRequests, + thread.branchPullRequest, ); const gitStatus = useEnvironmentQuery( leaseLiveStatus && @@ -899,13 +695,14 @@ export function ThreadRowLeadingStatus({ const displayedPrInput = { threadBranch: thread.branch, gitStatus: visibleGitStatus, - snapshot, - retainTerminalOnBranchMismatch: thread.worktreePath === null, linkedPullRequest: thread.linkedPullRequest, linkedPullRequestStatus: linkedPullRequest, }; - const pr = resolveDisplayedThreadPr(displayedPrInput); - const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput)); + const pr = linkedPullRequest?.pr ?? resolveDisplayedThreadPr(displayedPrInput); + const prStatus = prStatusIndicator( + pr, + linkedPullRequest?.sourceControlProvider ?? resolveDisplayedThreadPrProvider(displayedPrInput), + ); const threadStatus = resolveThreadStatusPill({ thread: { ...thread, diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx new file mode 100644 index 0000000000000..a99434f6659c6 --- /dev/null +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -0,0 +1,129 @@ +import { EMPTY_TERMINAL_SESSION_STATE } from "@t3tools/client-runtime/state/terminal"; +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { act, fakeTimers, render } from "../../test/render"; +import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; + +const fixture = vi.hoisted(() => ({ + statusByThreadId: new Map(), + pendingSurfaces: [] as Array<() => void>, +})); + +// Every surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it. +const fakeSurface: object = new Proxy( + { input: document.createElement("textarea") }, + { + get: (target, key) => + key === "then" ? undefined : key in target ? Reflect.get(target, key) : () => undefined, + }, +); +vi.mock("~/terminal/ghostty/surface", () => ({ + GhosttyTerminalSurface: { + create: () => + new Promise((resolve) => { + fixture.pendingSurfaces.push(() => resolve(fakeSurface)); + }), + }, +})); +vi.mock("../state/terminalSessions", async () => { + const Atom = await import("effect/reactivity/Atom"); + const sessions = Atom.family((_environmentId: EnvironmentId) => + Atom.family((threadId: ThreadId) => + Atom.make({ + ...EMPTY_TERMINAL_SESSION_STATE, + status: fixture.statusByThreadId.get(threadId) ?? "closed", + version: 1, + }), + ), + ); + return { + attachedTerminalSessionAtom: (environmentId: EnvironmentId, terminal: { threadId: ThreadId }) => + sessions(environmentId)(terminal.threadId), + }; +}); +vi.mock("../state/session", () => ({ + useEnvironmentScope: () => true, + readEnvironmentScope: () => true, +})); +vi.mock("../state/use-atom-command", () => ({ + useAtomCommand: () => async () => ({ _tag: "Success" }), +})); +// The commands are replaced above; importing their runtime would connect a client. +vi.mock("../state/server", async () => { + const Atom = await import("effect/reactivity/Atom"); + const config = Atom.make(null); + return { serverEnvironment: { configValueAtom: () => config } }; +}); +vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } })); +vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } })); +vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} })); +vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} })); +vi.mock("~/localApi", () => ({ readLocalApi: () => null })); +vi.mock("../hooks/useSettings", async () => { + const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings"); + return { + useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) => + select(DEFAULT_CLIENT_SETTINGS), + }; +}); + +function Drawer(props: { + threadRef: ScopedThreadRef; + onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; +}) { + return ( + {}} + onSplitTerminalVertical={() => {}} + onNewTerminal={() => {}} + onActiveTerminalChange={() => {}} + onCloseTerminal={props.onCloseTerminal} + onHeightChange={() => {}} + onAddTerminalContext={() => {}} + keybindings={[]} + /> + ); +} + +function setup() { + const original: ScopedThreadRef = { + environmentId: EnvironmentId.make("environment-a"), + threadId: ThreadId.make("thread-a"), + }; + const other: ScopedThreadRef = { + environmentId: EnvironmentId.make("environment-b"), + threadId: ThreadId.make("thread-b"), + }; + fixture.statusByThreadId = new Map([ + [original.threadId, "exited"], + [other.threadId, "running"], + ]); + fixture.pendingSurfaces = []; + return { original, other }; +} + +it("closes an exited terminal on its own thread after navigating to one reusing its ID", async () => { + const { original, other } = setup(); + const onCloseTerminal = vi.fn(); + await using screen = await render( + , + ); + using _timers = fakeTimers(); + // The exit is seen once the surface loads, and its close waits for the next task. + await act(async () => { + fixture.pendingSurfaces.shift()?.(); + }); + await screen.rerender(); + await act(async () => { + vi.runOnlyPendingTimers(); + }); + expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]); +}); diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts index 9979d3563ff88..83358c39d8260 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.test.ts +++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts @@ -40,7 +40,13 @@ describe("terminal selection actions", () => { }); it("retains visible output and selection until a replacement subscription receives its snapshot", () => { - const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() }; + const terminal = { + resetAndWrite: vi.fn(), + write: vi.fn(), + getSelection: vi.fn(() => "selected"), + getSelectionCellCount: vi.fn(() => 8), + clearSelection: vi.fn(), + }; const snapshot = { threadId: "thread", terminalId: "term-1", @@ -90,7 +96,13 @@ it("retains visible output and selection until a replacement subscription receiv }); it("reports an attach failure that leaves the output unchanged", () => { - const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() }; + const terminal = { + resetAndWrite: vi.fn(), + write: vi.fn(), + getSelection: vi.fn(() => "selected"), + getSelectionCellCount: vi.fn(() => 8), + clearSelection: vi.fn(), + }; const previous = { ...EMPTY_TERMINAL_BUFFER_STATE, error: null }; const failed = { ...previous, error: "Terminal attach failed" }; @@ -99,5 +111,7 @@ it("reports an attach failure that leaves the output unchanged", () => { ).toBe(INITIAL_TERMINAL_OUTPUT_CURSOR); expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n"); expect(terminal.resetAndWrite).not.toHaveBeenCalled(); + expect(terminal.getSelection).not.toHaveBeenCalled(); + expect(terminal.getSelectionCellCount).not.toHaveBeenCalled(); expect(terminal.clearSelection).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 301255c7d516a..88a945becc985 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -1,3 +1,4 @@ +import { workspaceAreaProps } from "../lib/workspaceFocus"; import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { isAtomCommandInterrupted, @@ -164,21 +165,33 @@ export function writeTerminalOutputUpdate( } } +// Avoid formatting unbounded scrollback selections on every output update. +const MAX_COMPARED_SELECTION_CELLS = 3_000; + export function synchronizeTerminalOutput( - terminal: Pick, + terminal: Pick< + GhosttyTerminalSurface, + "resetAndWrite" | "write" | "getSelection" | "getSelectionCellCount" | "clearSelection" + >, session: Pick, cursor: TerminalOutputCursor, ): TerminalOutputCursor { if (session.version === 0) return cursor; const update = readTerminalOutputUpdate(session.output, cursor); + if (update.type === "none") return update.cursor; + const cells = terminal.getSelectionCellCount(); + const compared = cells <= MAX_COMPARED_SELECTION_CELLS; + const selection = cells > 0 && compared ? terminal.getSelection() : ""; writeTerminalOutputUpdate(terminal, update); - terminal.clearSelection(); + if (!compared || (cells > 0 && terminal.getSelection() !== selection)) { + terminal.clearSelection(); + } return update.cursor; } /** Writes what changed between two session notifications: new output, then a new error. */ export function synchronizeTerminalSession( - terminal: Pick, + terminal: Parameters[0], previous: Pick, session: Pick, cursor: TerminalOutputCursor, @@ -616,6 +629,7 @@ function TerminalSessionViewport({ openTerminalLinkInPreview({ url, threadRef, openPreview, fallbackToBrowser, forceBrowser }), ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets the terminal input's readOnly from the operate grant and consumes a pending focus request useLayoutEffect(() => { if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal; if (canOperateTerminal && visibleRef.current) @@ -624,12 +638,14 @@ function TerminalSessionViewport({ // Links re-read the grant on activation; only the hovered link's styling needs a nudge. const linkActivationScopeRef = useRef(canOpenHostEditor); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes link activation styling on the imperative terminal surface when the editor grant changes useEffect(() => { if (linkActivationScopeRef.current === canOpenHostEditor) return; linkActivationScopeRef.current = canOpenHostEditor; terminalRef.current?.refreshLinkActivation(); }, [canOpenHostEditor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes visibility into the terminal surface before paint and consumes focus requests made while hidden useLayoutEffect(() => { visibleRef.current = visible; terminalRef.current?.setVisible(visible); @@ -637,6 +653,7 @@ function TerminalSessionViewport({ if (visible) consumePendingTerminalFocus(threadRef, terminalId); }, [terminalId, threadRef, visible]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies font family and size changes to the live Ghostty terminal surface useEffect(() => { const current = terminalFontRef.current; if (current.family === terminalFontFamily && current.size === terminalFontSize) return; @@ -644,6 +661,7 @@ function TerminalSessionViewport({ void terminalRef.current?.setFont(terminalFontOptions(terminalFontFamily, terminalFontSize)); }, [terminalFontFamily, terminalFontSize]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates the Ghostty terminal in the mount node and subscribes it to the terminal session useEffect(() => { const mount = containerRef.current; if (!mount) return; @@ -681,6 +699,7 @@ function TerminalSessionViewport({ terminal.setTheme(terminalThemeFromApp(mount)); setupTerminal = terminal; terminalRef.current = terminal; + terminal.input.setAttribute("data-workspace-focus-default", ""); terminal.input.readOnly = !hasTerminalWriteAccess(); // Reapply font settings hydrated during loading, when terminalRef was null. const currentFont = terminalFontRef.current; @@ -688,6 +707,7 @@ function TerminalSessionViewport({ void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size)); } const latestSession = readTerminalSession(); + terminal.setSharedGrid(latestSession.grid); const initialOutput = readTerminalOutputUpdate( latestSession.output, INITIAL_TERMINAL_OUTPUT_CURSOR, @@ -713,6 +733,7 @@ function TerminalSessionViewport({ } const previous = previousSession; previousSession = session; + terminal.setSharedGrid(session.grid); synchronizeTerminalStatus(terminal, session.status, session.version); outputCursorRef.current = synchronizeTerminalSession( terminal, @@ -781,8 +802,12 @@ function TerminalSessionViewport({ }; }; - const addSelectionToChat = (selection: TerminalContextSelection) => { - handleAddTerminalContext(selection); + const addSelectionToChat = (clipboardText: string) => { + // Output keeps moving the selected rows while a menu is open, so take + // the line numbers now, and only if the same text is still selected. + const current = readSelectionAction(); + if (current?.clipboardText !== clipboardText) return; + handleAddTerminalContext(current.selection); terminalRef.current?.clearSelection(); terminalRef.current?.focus(); }; @@ -855,7 +880,7 @@ function TerminalSessionViewport({ switch (clicked) { case "add-to-chat": if (selectionAction && canAddSelectionToChat()) { - addSelectionToChat(selectionAction.selection); + addSelectionToChat(selectionAction.clipboardText); } return; case "copy": @@ -905,7 +930,7 @@ function TerminalSessionViewport({ } switch (clicked) { case "add-to-chat": - if (canAddSelectionToChat()) addSelectionToChat(nextAction.selection); + if (canAddSelectionToChat()) addSelectionToChat(nextAction.clipboardText); return; case "copy": await copySelection(nextAction.clipboardText, requestId); @@ -1169,7 +1194,7 @@ interface ThreadTerminalDrawerProps { newShortcutLabel?: string | undefined; closeShortcutLabel?: string | undefined; onActiveTerminalChange: (terminalId: string) => void; - onCloseTerminal: (terminalId: string) => void; + onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; onHeightChange: (height: number) => void; onAddTerminalContext: (selection: TerminalContextSelection) => void; keybindings: ResolvedKeybindingsConfig; @@ -1242,7 +1267,7 @@ function TerminalSplitPanes({ terminalLabelById: ReadonlyMap; resolveLaunchLocation: (terminalId: string) => TerminalLaunchLocation; onActiveTerminalChange: (terminalId: string) => void; - onCloseTerminal: (terminalId: string) => void; + onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; advancedTypography: boolean; threadRef: ScopedThreadRef; threadId: ThreadId; @@ -1293,7 +1318,7 @@ function TerminalSplitPanes({ {...(terminalLaunchLocation.runtimeEnv ? { runtimeEnv: terminalLaunchLocation.runtimeEnv } : {})} - onSessionExited={() => onCloseTerminal(terminalId)} + onSessionExited={() => onCloseTerminal(terminalId, threadRef)} onAddTerminalContext={onAddTerminalContext} visible={visible} keybindings={keybindings} @@ -1433,6 +1458,7 @@ export default function ThreadTerminalDrawer({ terminalLaunchLocationsById, }: ThreadTerminalDrawerProps) { const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); + const terminalArea = workspaceAreaProps("terminal", 5, "Terminal"); const isPanel = mode === "panel"; const [advancedTypography] = useLocalStorage( TYPOGRAPHY_ADVANCED_STORAGE_KEY, @@ -1616,7 +1642,7 @@ export default function ThreadTerminalDrawer({ const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId); void confirmTerminalClose([label]).then((confirmed) => { if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) { - onCloseTerminal(terminalId); + onCloseTerminal(terminalId, threadRef); } }); }; @@ -1690,6 +1716,7 @@ export default function ThreadTerminalDrawer({ if (heightBudgetChanged) setDrawerLayout(layout); }, ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the drawer before visible paint and observes window and chat column resizes while visible useLayoutEffect(() => { if (!visible) { return; @@ -1716,6 +1743,7 @@ export default function ThreadTerminalDrawer({ return (