Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(web): use themed confirmation dialogs (#5624)
Wout Stiens9821bca1ceb9
diff --git a/apps/desktop/src/electron/ElectronDialog.test.ts b/apps/desktop/src/electron/ElectronDialog.test.tsindex 388b3fd2c..c41bb34bb 100644--- a/apps/desktop/src/electron/ElectronDialog.test.ts+++ b/apps/desktop/src/electron/ElectronDialog.test.ts@@ -28,70 +28,6 @@ describe("ElectronDialog", () => {showErrorBoxMock.mockReset();});- it.effect("returns false without opening a confirm dialog for empty messages", () =>- Effect.gen(function* () {- const dialog = yield* ElectronDialog.ElectronDialog;-- const result = yield* dialog.confirm({- message: " ",- owner: Option.none(),- });-- assert.isFalse(result);- assert.equal(showMessageBoxMock.mock.calls.length, 0);- }).pipe(Effect.provide(ElectronDialog.layer)),- );-- it.effect("opens a confirm dialog for the owner window", () =>- Effect.gen(function* () {- const owner = { id: 1 } as BrowserWindow;- showMessageBoxMock.mockResolvedValue({ response: 1 });- const dialog = yield* ElectronDialog.ElectronDialog;-- const result = yield* dialog.confirm({- message: "Delete worktree?",- owner: Option.some(owner),- });-- assert.isTrue(result);- assert.deepEqual(showMessageBoxMock.mock.calls[0], [- owner,- {- type: "question",- buttons: ["No", "Yes"],- defaultId: 0,- cancelId: 0,- noLink: true,- message: "Delete worktree?",- },- ]);- }).pipe(Effect.provide(ElectronDialog.layer)),- );-- it.effect("opens an app-level confirm dialog when there is no owner window", () =>- Effect.gen(function* () {- showMessageBoxMock.mockResolvedValue({ response: 0 });- const dialog = yield* ElectronDialog.ElectronDialog;-- const result = yield* dialog.confirm({- message: "Delete worktree?",- owner: Option.none(),- });-- assert.isFalse(result);- assert.deepEqual(showMessageBoxMock.mock.calls[0], [- {- type: "question",- buttons: ["No", "Yes"],- defaultId: 0,- cancelId: 0,- noLink: true,- message: "Delete worktree?",- },- ]);- }).pipe(Effect.provide(ElectronDialog.layer)),- );-it.effect("preserves folder picker request context and cause", () =>Effect.gen(function* () {const cause = new Error("folder picker failed");@@ -117,31 +53,6 @@ describe("ElectronDialog", () => {}).pipe(Effect.provide(ElectronDialog.layer)),);- it.effect("preserves confirmation request context and cause", () =>- Effect.gen(function* () {- const cause = new Error("confirmation failed");- const owner = { id: 9 } as BrowserWindow;- showMessageBoxMock.mockRejectedValue(cause);- const dialog = yield* ElectronDialog.ElectronDialog;-- const error = yield* Effect.flip(- dialog.confirm({- owner: Option.some(owner),- message: " Confirm removal? ",- }),- );-- assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);- assert.strictEqual(error.ownerWindowId, 9);- assert.strictEqual(error.promptLength, "Confirm removal?".length);- assert.notProperty(error, "promptMessage");- assert.strictEqual(error.cause, cause);- assert.include(error.message, "window 9");- assert.notInclude(error.message, "Confirm removal?");- assert.notInclude(error.message, cause.message);- }).pipe(Effect.provide(ElectronDialog.layer)),- );-it.effect("preserves message box request context and cause", () =>Effect.gen(function* () {const cause = new Error("message box failed");diff --git a/apps/desktop/src/electron/ElectronDialog.ts b/apps/desktop/src/electron/ElectronDialog.tsindex f1add4c7c..c33a24bef 100644--- a/apps/desktop/src/electron/ElectronDialog.ts+++ b/apps/desktop/src/electron/ElectronDialog.ts@@ -6,8 +6,6 @@ import * as Schema from "effect/Schema";import * as Electron from "electron";-const CONFIRM_BUTTON_INDEX = 1;-export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()("ElectronDialogPickFolderError",{@@ -38,20 +36,6 @@ export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<Electr}}-export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(- "ElectronDialogConfirmError",- {- ownerWindowId: Schema.NullOr(Schema.Number),- promptLength: Schema.Number,- cause: Schema.Defect(),- },-) {- override get message(): string {- const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;- return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;- }-}-export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()("ElectronDialogShowMessageBoxError",{@@ -85,7 +69,6 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Eleexport const ElectronDialogError = Schema.Union([ElectronDialogPickFolderError,ElectronDialogPickFilesError,- ElectronDialogConfirmError,ElectronDialogShowMessageBoxError,ElectronDialogShowErrorBoxError,]);@@ -103,11 +86,6 @@ export interface ElectronDialogPickFilesInput {readonly filters: readonly Electron.FileFilter[];}-export interface ElectronDialogConfirmInput {- readonly owner: Option.Option<Electron.BrowserWindow>;- readonly message: string;-}-export class ElectronDialog extends Context.Service<ElectronDialog,{@@ -117,9 +95,6 @@ export class ElectronDialog extends Context.Service<readonly pickFiles: (input: ElectronDialogPickFilesInput,) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;- readonly confirm: (- input: ElectronDialogConfirmInput,- ) => Effect.Effect<boolean, ElectronDialogConfirmError>;readonly showMessageBox: (options: Electron.MessageBoxOptions,) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;@@ -188,39 +163,6 @@ export const make = ElectronDialog.of({});return result.canceled ? [] : result.filePaths;}),- confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {- const normalizedMessage = input.message.trim();- if (normalizedMessage.length === 0) {- return false;- }-- const options = {- type: "question" as const,- buttons: ["No", "Yes"],- defaultId: 0,- cancelId: 0,- noLink: true,- message: normalizedMessage,- };- const ownerWindowId = Option.match(input.owner, {- onNone: () => null,- onSome: (owner) => owner.id,- });- const result = yield* Effect.tryPromise({- try: () =>- Option.match(input.owner, {- onNone: () => Electron.dialog.showMessageBox(options),- onSome: (owner) => Electron.dialog.showMessageBox(owner, options),- }),- catch: (cause) =>- new ElectronDialogConfirmError({- ownerWindowId,- promptLength: normalizedMessage.length,- cause,- }),- });- return result.response === CONFIRM_BUTTON_INDEX;- }),showMessageBox: (options) =>Effect.tryPromise({try: () => Electron.dialog.showMessageBox(options),diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.tsindex 503a586d9..cb35ad19a 100644--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts@@ -31,7 +31,6 @@ import {setUpdateChannel,} from "./methods/updates.ts";import {- confirm,getAppBranding,getLocalEnvironmentBootstraps,getLocalEnvironmentBearerToken,@@ -81,7 +80,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"yield* ipc.handle(pickFolder);yield* ipc.handle(pickThemeFiles);- yield* ipc.handle(confirm);yield* ipc.handle(setTheme);yield* ipc.handle(showContextMenu);yield* ipc.handle(openExternal);diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.tsindex 4d8e783d1..4a1213e4e 100644--- a/apps/desktop/src/ipc/channels.ts+++ b/apps/desktop/src/ipc/channels.ts@@ -1,6 +1,5 @@export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";-export const CONFIRM_CHANNEL = "desktop:confirm";export const SET_THEME_CHANNEL = "desktop:set-theme";export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.tsindex cfa854e7a..7a39eb429 100644--- a/apps/desktop/src/ipc/methods/window.ts+++ b/apps/desktop/src/ipc/methods/window.ts@@ -220,19 +220,6 @@ export const pickFolder = DesktopIpc.makeIpcMethod({}),});-export const confirm = DesktopIpc.makeIpcMethod({- channel: IpcChannels.CONFIRM_CHANNEL,- payload: Schema.String,- result: Schema.Boolean,- handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {- const dialog = yield* ElectronDialog.ElectronDialog;- const electronWindow = yield* ElectronWindow.ElectronWindow;- return yield* electronWindow.focusedMainOrFirst.pipe(- Effect.flatMap((owner) => dialog.confirm({ owner, message })),- );- }),-});-export const setTheme = DesktopIpc.makeIpcMethod({channel: IpcChannels.SET_THEME_CHANNEL,payload: DesktopThemeSchema,diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 7e8859359..2aa345ee5 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -98,7 +98,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),- confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),showContextMenu: (items, position) =>ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.tsindex 0c826e36d..09c287763 100644--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts@@ -53,7 +53,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {pickFolder: () => Effect.succeed(Option.none()),pickFiles: () => Effect.succeed([]),- confirm: () => Effect.succeed(false),showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),showErrorBox: () => Effect.void,} satisfies ElectronDialog.ElectronDialog["Service"]);diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 07f5d3b5f..880bf8a50 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -4745,6 +4745,7 @@ function ChatViewContent(props: ChatViewProps) {"This will discard newer messages and turn diffs in this thread.","This action cannot be undone.",].join("\n"),+ { variant: "destructive" },);if (!confirmed) {return;diff --git a/apps/web/src/components/ConfirmDialogHost.tsx b/apps/web/src/components/ConfirmDialogHost.tsxnew file mode 100644index 000000000..c169a1eff--- /dev/null+++ b/apps/web/src/components/ConfirmDialogHost.tsx@@ -0,0 +1,96 @@+import { useEffect, useSyncExternalStore } from "react";++import {+ completeConfirmDialogClose,+ readConfirmDialogState,+ registerConfirmDialogHost,+ respondToConfirmDialog,+ subscribeConfirmDialog,+} from "../confirmDialog";+import {+ AlertDialog,+ AlertDialogClose,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogPopup,+ AlertDialogTitle,+} from "./ui/alert-dialog";+import { Button } from "./ui/button";++type ConfirmationCopy = {+ readonly title: string;+ readonly description: string | null;+};++export function resolveConfirmDialogCopy(message: string): ConfirmationCopy {+ const normalizedMessage = message.trim();+ const lines = normalizedMessage.split("\n");+ const questionLineIndex = lines.findIndex((line) => line.trim().endsWith("?"));++ if (questionLineIndex >= 0) {+ const title = lines[questionLineIndex]!.trim();+ const description = lines+ .filter((_, index) => index !== questionLineIndex)+ .join("\n")+ .trim();+ return { title, description: description || null };+ }++ const questionMarkIndex = normalizedMessage.indexOf("?");+ if (questionMarkIndex >= 0) {+ return {+ title: normalizedMessage.slice(0, questionMarkIndex + 1).trim(),+ description: normalizedMessage.slice(questionMarkIndex + 1).trim() || null,+ };+ }++ return {+ title: "Confirm action",+ description: normalizedMessage || "This action requires your confirmation.",+ };+}++export function ConfirmDialogHost() {+ const state = useSyncExternalStore(+ subscribeConfirmDialog,+ readConfirmDialogState,+ readConfirmDialogState,+ );++ useEffect(() => registerConfirmDialogHost(), []);++ const copy = resolveConfirmDialogCopy(state.status === "idle" ? "" : state.message);+ const confirmVariant = state.status === "idle" ? "default" : state.variant;+ const onCancel = () => respondToConfirmDialog(false);+ const onConfirm = () => respondToConfirmDialog(true);++ return (+ <AlertDialog+ open={state.status === "confirming"}+ onOpenChange={(open) => {+ if (!open) onCancel();+ }}+ onOpenChangeComplete={(open) => {+ if (!open) completeConfirmDialogClose();+ }}+ >+ <AlertDialogPopup className="max-w-lg">+ <AlertDialogHeader>+ <AlertDialogTitle>{copy.title}</AlertDialogTitle>+ {copy.description ? (+ <AlertDialogDescription className="whitespace-pre-line">+ {copy.description}+ </AlertDialogDescription>+ ) : null}+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>+ <Button variant={confirmVariant} onClick={onConfirm}>+ Confirm+ </Button>+ </AlertDialogFooter>+ </AlertDialogPopup>+ </AlertDialog>+ );+}diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex 54fbc12df..f17508e25 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -104,7 +104,7 @@ import {} from "../keybindings";import { isModelPickerOpen } from "../modelPickerVisibility";import { useShortcutModifierState } from "../shortcutModifierState";-import { readLocalApi } from "../localApi";+import { ensureLocalApi, readLocalApi } from "../localApi";import { useComposerDraftStore } from "../composerDraftStore";import { useNewThreadHandler } from "../hooks/useHandleNewThread";import { useDesktopUpdateState } from "../state/desktopUpdate";@@ -1499,6 +1499,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec: []),"This removes only this project entry.",].join("\n"),+ { variant: "destructive" },);if (!confirmed) {return;@@ -1547,7 +1548,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []),"This removes only this project entry.",].join("\n");- const confirmed = await api.dialogs.confirm(message);+ const confirmed = await api.dialogs.confirm(message, { variant: "destructive" });if (!confirmed) {return;}@@ -1830,6 +1831,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec`Delete ${count} thread${count === 1 ? "" : "s"}?`,"This permanently clears conversation history for these threads.",].join("\n"),+ { variant: "destructive" },);if (!confirmed) return;}@@ -2180,6 +2182,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec`Delete thread "${thread.title}"?`,"This permanently clears conversation history for this thread.",].join("\n"),+ { variant: "destructive" },);if (!confirmed) {return;@@ -2730,6 +2733,7 @@ interface SidebarProjectsContentProps {arm64IntelBuildWarningDescription: string | null;desktopUpdateButtonAction: "download" | "install" | "none";desktopUpdateButtonDisabled: boolean;+ desktopUpdateActionPending: boolean;handleDesktopUpdateButtonClick: () => void;projectSortOrder: SidebarProjectSortOrder;threadSortOrder: SidebarThreadSortOrder;@@ -2770,6 +2774,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(arm64IntelBuildWarningDescription,desktopUpdateButtonAction,desktopUpdateButtonDisabled,+ desktopUpdateActionPending,handleDesktopUpdateButtonClick,projectSortOrder,threadSortOrder,@@ -2862,7 +2867,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(<Buttonsize="xs"variant="outline"- disabled={desktopUpdateButtonDisabled}+ disabled={desktopUpdateButtonDisabled || desktopUpdateActionPending}onClick={handleDesktopUpdateButtonClick}>{desktopUpdateButtonAction === "download"@@ -3032,6 +3037,7 @@ export default function LegacySidebar() {const suppressProjectClickAfterDragRef = useRef(false);const suppressProjectClickForContextMenuRef = useRef(false);const desktopUpdateState = useDesktopUpdateState();+ const [desktopUpdateActionPending, setDesktopUpdateActionPending] = useState(false);const clearSelection = useThreadSelectionStore((s) => s.clearSelection);const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);const platform = navigator.platform;@@ -3498,10 +3504,18 @@ export default function LegacySidebar() {"commandPalette.toggle",newThreadShortcutLabelOptions,);- const handleDesktopUpdateButtonClick = useCallback(() => {+ const handleDesktopUpdateButtonClick = useCallback(async () => {const bridge = window.desktopBridge;if (!bridge || !desktopUpdateState) return;- if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return;+ if (+ desktopUpdateButtonDisabled ||+ desktopUpdateButtonAction === "none" ||+ desktopUpdateActionPending+ ) {+ return;+ }++ setDesktopUpdateActionPending(true);if (desktopUpdateButtonAction === "download") {void bridge@@ -3529,15 +3543,32 @@ export default function LegacySidebar() {description: error instanceof Error ? error.message : "An unexpected error occurred.",}),);- });+ })+ .finally(() => setDesktopUpdateActionPending(false));return;}if (desktopUpdateButtonAction === "install") {- const confirmed = window.confirm(- getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),- );- if (!confirmed) return;+ let confirmed = false;+ try {+ confirmed = await ensureLocalApi().dialogs.confirm(+ getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform),+ );+ } catch (error) {+ setDesktopUpdateActionPending(false);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Could not confirm update",+ description: error instanceof Error ? error.message : "Update confirmation failed.",+ }),+ );+ return;+ }+ if (!confirmed) {+ setDesktopUpdateActionPending(false);+ return;+ }void bridge.installUpdate().then((result) => {@@ -3560,9 +3591,15 @@ export default function LegacySidebar() {description: error instanceof Error ? error.message : "An unexpected error occurred.",}),);- });+ })+ .finally(() => setDesktopUpdateActionPending(false));}- }, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);+ }, [+ desktopUpdateActionPending,+ desktopUpdateButtonAction,+ desktopUpdateButtonDisabled,+ desktopUpdateState,+ ]);const expandThreadListForProject = useCallback((projectKey: string) => {setExpandedThreadListsByProject((current) => {@@ -3594,6 +3631,7 @@ export default function LegacySidebar() {arm64IntelBuildWarningDescription={arm64IntelBuildWarningDescription}desktopUpdateButtonAction={desktopUpdateButtonAction}desktopUpdateButtonDisabled={desktopUpdateButtonDisabled}+ desktopUpdateActionPending={desktopUpdateActionPending}handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick}projectSortOrder={sidebarProjectSortOrder}threadSortOrder={sidebarThreadSortOrder}diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex a2dda3b76..22c28df1c 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -2812,6 +2812,7 @@ export default function Sidebar() {`Delete ${count} thread${count === 1 ? "" : "s"}?`,"This permanently clears conversation history for these threads.",].join("\n"),+ { variant: "destructive" },),);if (confirmed._tag === "Failure" || !confirmed.value) return;@@ -3014,6 +3015,7 @@ export default function Sidebar() {`Delete thread "${thread.title}"?`,"This permanently clears conversation history for this thread.",].join("\n"),+ { variant: "destructive" },),);if (confirmed._tag === "Failure" || !confirmed.value) return;diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsxindex 9ae5f8226..5bd4fdc08 100644--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx@@ -12,7 +12,7 @@ import {isAtomCommandInterrupted,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";-import { useCallback, useMemo, useState, type ReactNode } from "react";+import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";import type {ServerProcessDiagnosticsEntry,ServerProcessResourceHistorySummary,@@ -22,6 +22,7 @@ import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";import { cn } from "../../lib/utils";+import { ensureLocalApi } from "../../localApi";import { resolveAndPersistPreferredEditor } from "../../editorPreferences";import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";import { useEnvironmentQuery } from "../../state/query";@@ -857,6 +858,11 @@ export function DiagnosticsSettingsPanel() {const [isOpeningLogsDirectory, setIsOpeningLogsDirectory] = useState(false);const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);const [signalingPid, setSignalingPid] = useState<number | null>(null);+ const signalingPidRef = useRef<number | null>(null);+ const environmentIdRef = useRef(environmentId);+ const processDataRef = useRef(processData);+ environmentIdRef.current = environmentId;+ processDataRef.current = processData;const openLogsDirectory = useCallback(() => {const logsDirectoryPath = observability?.logsDirectoryPath ?? null;@@ -895,28 +901,51 @@ export function DiagnosticsSettingsPanel() {const isInitialLoading = isPending && data === null;const isProcessInitialLoading = isProcessPending && processData === null;const signalProcess = useCallback(- (pid: number, signal: ServerProcessSignal) => {- if (- signal === "SIGKILL" &&- !window.confirm(`Send SIGKILL to process ${pid}? This cannot be handled by the process.`)- ) {- return;+ async (pid: number, signal: ServerProcessSignal) => {+ if (signalingPidRef.current !== null) return;+ signalingPidRef.current = pid;+ setSignalingPid(pid);+ const clearSignaling = () => {+ signalingPidRef.current = null;+ setSignalingPid(null);+ };+ if (signal === "SIGKILL") {+ let confirmed = false;+ try {+ confirmed = await ensureLocalApi().dialogs.confirm(+ `Send SIGKILL to process ${pid}? This cannot be handled by the process.`,+ { variant: "destructive" },+ );+ } catch (error) {+ clearSignaling();+ toastManager.add({+ type: "error",+ title: "Could not confirm signal",+ description: error instanceof Error ? error.message : `Failed to send ${signal}.`,+ });+ return;+ }+ if (!confirmed) {+ clearSignaling();+ return;+ }}- if (environmentId === null) {+ const currentEnvironmentId = environmentIdRef.current;+ if (currentEnvironmentId === null) {+ clearSignaling();return;}- const process = processData?.processes.find((entry) => entry.pid === pid);+ const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);if (process === undefined) {+ clearSignaling();return;}- setSignalingPid(pid);- void (async () => {+ try {const result = await signalServerProcess({- environmentId,+ environmentId: currentEnvironmentId,input: { pid, startTimeMs: process.startTimeMs, signal },});- setSignalingPid(null);if (result._tag === "Failure") {if (!isAtomCommandInterrupted(result)) {const error = squashAtomCommandFailure(result);@@ -949,9 +978,11 @@ export function DiagnosticsSettingsPanel() {return;}refreshProcesses();- })();+ } finally {+ clearSignaling();+ }},- [environmentId, processData?.processes, refreshProcesses, signalServerProcess],+ [refreshProcesses, signalServerProcess],);const processDiagnosticsError = processData ? Option.getOrNull(processData.error) : null;diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsxindex 23a176219..50cf9c318 100644--- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx@@ -700,6 +700,7 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {: "Other entries in this grouped project are unaffected.","This action cannot be undone.",].join("\n"),+ { variant: "destructive" },),);if (confirmed._tag === "Failure" || !confirmed.value) return;diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsxindex b4f2b09c6..062326c21 100644--- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx+++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx@@ -27,7 +27,7 @@ import type {} from "@t3tools/contracts";import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";-import { useCallback, useMemo, useState, type ReactNode } from "react";+import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";import {isAtomCommandInterrupted,squashAtomCommandFailure,@@ -38,6 +38,7 @@ import {useResourceTelemetryHistory,} from "../../lib/resourceTelemetryState";import { cn } from "../../lib/utils";+import { ensureLocalApi } from "../../localApi";import { usePrimaryEnvironment } from "../../state/environments";import { serverEnvironment } from "../../state/server";import { useAtomCommand } from "../../state/use-atom-command";@@ -845,26 +846,54 @@ export function ResourceTelemetryDiagnostics() {reportFailure: false,});const [signalingKeys, setSignalingKeys] = useState<ReadonlySet<string>>(() => new Set());+ const signalingKeysRef = useRef<ReadonlySet<string>>(new Set());+ signalingKeysRef.current = signalingKeys;+ const primaryEnvironmentIdRef = useRef(primaryEnvironment?.environmentId);+ primaryEnvironmentIdRef.current = primaryEnvironment?.environmentId;const [isRetrying, setIsRetrying] = useState(false);const snapshot = telemetry.data;const allT3 = snapshot?.groups.allT3;const signalProcess = useCallback(- (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {- if (- signal === "SIGKILL" &&- !window.confirm(- `Send SIGKILL to process ${process.identity.pid}? This cannot be handled by the process.`,- )- ) {- return;- }+ async (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {const identityKey = processIdentityKey(process);- const environmentId = primaryEnvironment?.environmentId;+ if (signalingKeysRef.current.has(identityKey)) return;+ const nextSignalingKeys = new Set(signalingKeysRef.current).add(identityKey);+ signalingKeysRef.current = nextSignalingKeys;+ setSignalingKeys(nextSignalingKeys);+ const clearSignaling = () => {+ const next = new Set(signalingKeysRef.current);+ next.delete(identityKey);+ signalingKeysRef.current = next;+ setSignalingKeys(next);+ };++ if (signal === "SIGKILL") {+ let confirmed = false;+ try {+ confirmed = await ensureLocalApi().dialogs.confirm(+ `Send SIGKILL to process ${process.identity.pid}? This cannot be handled by the process.`,+ { variant: "destructive" },+ );+ } catch (error) {+ clearSignaling();+ toastManager.add({+ type: "error",+ title: "Could not confirm signal",+ description: error instanceof Error ? error.message : `Failed to send ${signal}.`,+ });+ return;+ }+ if (!confirmed) {+ clearSignaling();+ return;+ }+ }+ const environmentId = primaryEnvironmentIdRef.current;if (environmentId === undefined) {+ clearSignaling();return;}- setSignalingKeys((current) => new Set(current).add(identityKey));void signalServerProcess({environmentId,input: {@@ -896,15 +925,10 @@ export function ResourceTelemetryDiagnostics() {});}).finally(() => {- setSignalingKeys((current) => {- if (!current.has(identityKey)) return current;- const next = new Set(current);- next.delete(identityKey);- return next;- });+ clearSignaling();});},- [primaryEnvironment?.environmentId, signalServerProcess],+ [signalServerProcess],);const retryCollector = useCallback(() => {diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex c10dd5d2b..6743952ae 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -220,6 +220,7 @@ function AboutVersionTitle() {function AboutVersionSection() {const updateState = useDesktopUpdateState();const [isChangingUpdateChannel, setIsChangingUpdateChannel] = useState(false);+ const [isUpdateActionPending, setIsUpdateActionPending] = useState(false);const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);const selectedUpdateChannel = updateState?.channel ?? "latest";@@ -255,7 +256,7 @@ function AboutVersionSection() {[selectedUpdateChannel],);- const handleButtonClick = useCallback(() => {+ const handleButtonClick = useCallback(async () => {const bridge = window.desktopBridge;if (!bridge) return;@@ -275,22 +276,43 @@ function AboutVersionSection() {}if (action === "install") {- const confirmed = window.confirm(- getDesktopUpdateInstallConfirmationMessage(- updateState ?? { availableVersion: null, downloadedVersion: null },- navigator.platform,- ),- );- if (!confirmed) return;- void bridge.installUpdate().catch((error: unknown) => {+ if (isUpdateActionPending) return;+ setIsUpdateActionPending(true);+ let confirmed = false;+ try {+ confirmed = await ensureLocalApi().dialogs.confirm(+ getDesktopUpdateInstallConfirmationMessage(+ updateState ?? { availableVersion: null, downloadedVersion: null },+ navigator.platform,+ ),+ );+ } catch (error) {+ setIsUpdateActionPending(false);toastManager.add(stackedThreadToast({type: "error",- title: "Could not install update",- description: error instanceof Error ? error.message : "Install failed.",+ title: "Could not confirm update",+ description: error instanceof Error ? error.message : "Update confirmation failed.",}),);- });+ return;+ }+ if (!confirmed) {+ setIsUpdateActionPending(false);+ return;+ }+ void bridge+ .installUpdate()+ .catch((error: unknown) => {+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Could not install update",+ description: error instanceof Error ? error.message : "Install failed.",+ }),+ );+ })+ .finally(() => setIsUpdateActionPending(false));return;}@@ -318,7 +340,7 @@ function AboutVersionSection() {}),);});- }, [updateState]);+ }, [isUpdateActionPending, updateState]);const action = updateState ? resolveDesktopUpdateButtonAction(updateState) : "none";const buttonTooltip = updateState ? getDesktopUpdateButtonTooltip(updateState) : null;@@ -352,7 +374,7 @@ function AboutVersionSection() {<Buttonsize="xs"variant={action === "install" ? "default" : "outline"}- disabled={buttonDisabled}+ disabled={buttonDisabled || isUpdateActionPending}onClick={handleButtonClick}>{buttonLabel}@@ -550,6 +572,7 @@ export function useSettingsRestore(onRestored?: () => void) {["Restore default settings?", `This will reset: ${changedSettingLabels.join(", ")}.`].join("\n",),+ { variant: "destructive" },);if (!confirmed) return;diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsxindex 89dd795d8..503411eb6 100644--- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx+++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx@@ -1,6 +1,7 @@import { DownloadIcon, RotateCwIcon, TriangleAlertIcon, XIcon } from "lucide-react";import { useCallback, useState } from "react";import { isElectron } from "../../env";+import { ensureLocalApi } from "../../localApi";import { useDesktopUpdateState } from "../../state/desktopUpdate";import { stackedThreadToast, toastManager } from "../ui/toast";import {@@ -70,6 +71,7 @@ function SidebarUpdateReleaseNotesTooltip({export function SidebarUpdatePill() {const state = useDesktopUpdateState();const [dismissed, setDismissed] = useState(false);+ const [isActionPending, setIsActionPending] = useState(false);const visible = isElectron && shouldShowDesktopUpdateButton(state) && !dismissed;const tooltip = state ? getDesktopUpdateButtonTooltip(state) : "Update available";@@ -80,10 +82,12 @@ export function SidebarUpdatePill() {const arm64Description =state && showArm64Warning ? getArm64IntelBuildWarningDescription(state) : null;- const handleAction = useCallback(() => {+ const handleAction = useCallback(async () => {const bridge = window.desktopBridge;if (!bridge || !state) return;- if (disabled || action === "none") return;+ if (disabled || action === "none" || isActionPending) return;++ setIsActionPending(true);if (action === "download") {void bridge@@ -111,15 +115,32 @@ export function SidebarUpdatePill() {description: error instanceof Error ? error.message : "An unexpected error occurred.",}),);- });+ })+ .finally(() => setIsActionPending(false));return;}if (action === "install") {- const confirmed = window.confirm(- getDesktopUpdateInstallConfirmationMessage(state, navigator.platform),- );- if (!confirmed) return;+ let confirmed = false;+ try {+ confirmed = await ensureLocalApi().dialogs.confirm(+ getDesktopUpdateInstallConfirmationMessage(state, navigator.platform),+ );+ } catch (error) {+ setIsActionPending(false);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Could not confirm update",+ description: error instanceof Error ? error.message : "Update confirmation failed.",+ }),+ );+ return;+ }+ if (!confirmed) {+ setIsActionPending(false);+ return;+ }void bridge.installUpdate().then((result) => {@@ -142,9 +163,10 @@ export function SidebarUpdatePill() {description: error instanceof Error ? error.message : "An unexpected error occurred.",}),);- });+ })+ .finally(() => setIsActionPending(false));}- }, [action, disabled, state]);+ }, [action, disabled, isActionPending, state]);if (!visible && !showArm64Warning) return null;@@ -170,8 +192,8 @@ export function SidebarUpdatePill() {<buttontype="button"aria-label={tooltip}- aria-disabled={disabled || undefined}- disabled={disabled}+ aria-disabled={disabled || isActionPending || undefined}+ disabled={disabled || isActionPending}className="update-main relative flex h-full flex-1 items-center gap-2 px-2 enabled:cursor-pointer"onClick={handleAction}>diff --git a/apps/web/src/confirmDialog.test.ts b/apps/web/src/confirmDialog.test.tsnew file mode 100644index 000000000..ef60c55ce--- /dev/null+++ b/apps/web/src/confirmDialog.test.ts@@ -0,0 +1,104 @@+import { beforeEach, describe, expect, it } from "vite-plus/test";++import {+ completeConfirmDialogClose,+ readConfirmDialogState,+ registerConfirmDialogHost,+ requestConfirmDialog,+ resetConfirmDialogForTests,+ respondToConfirmDialog,+} from "./confirmDialog";++function requireConfirmation(confirmation: Promise<boolean> | undefined): Promise<boolean> {+ if (!confirmation) {+ throw new Error("Expected a registered confirmation host.");+ }+ return confirmation;+}++describe("confirm dialog coordinator", () => {+ beforeEach(() => {+ resetConfirmDialogForTests();+ });++ it("returns undefined until a themed host is mounted", () => {+ expect(requestConfirmDialog("Confirm this action?")).toBeUndefined();+ expect(readConfirmDialogState()).toEqual({ status: "idle" });+ });++ it("resolves a displayed confirmation and waits for its close transition", async () => {+ const unregister = registerConfirmDialogHost();+ const confirmation = requireConfirmation(+ requestConfirmDialog("Delete this thread?", { variant: "destructive" }),+ );++ expect(readConfirmDialogState()).toEqual({+ status: "confirming",+ message: "Delete this thread?",+ variant: "destructive",+ });++ respondToConfirmDialog(true);+ await expect(confirmation).resolves.toBe(true);+ expect(readConfirmDialogState()).toEqual({+ status: "closing",+ message: "Delete this thread?",+ variant: "destructive",+ });++ completeConfirmDialogClose();+ expect(readConfirmDialogState()).toEqual({ status: "idle" });+ unregister();+ });++ it("serializes concurrent confirmations", async () => {+ const unregister = registerConfirmDialogHost();+ const first = requireConfirmation(requestConfirmDialog("Delete the project?"));+ const second = requireConfirmation(requestConfirmDialog("Delete the worktree too?"));++ respondToConfirmDialog(false);+ await expect(first).resolves.toBe(false);+ expect(readConfirmDialogState()).toEqual({+ status: "closing",+ message: "Delete the project?",+ variant: "default",+ });++ completeConfirmDialogClose();+ expect(readConfirmDialogState()).toEqual({+ status: "confirming",+ message: "Delete the worktree too?",+ variant: "default",+ });++ respondToConfirmDialog(true);+ await expect(second).resolves.toBe(true);+ completeConfirmDialogClose();+ expect(readConfirmDialogState()).toEqual({ status: "idle" });+ unregister();+ });++ it("cancels active and queued confirmations if the last host unmounts", async () => {+ const unregister = registerConfirmDialogHost();+ const active = requireConfirmation(requestConfirmDialog("Delete the thread?"));+ const queued = requireConfirmation(requestConfirmDialog("Delete the worktree too?"));++ unregister();++ await expect(Promise.all([active, queued])).resolves.toEqual([false, false]);+ expect(readConfirmDialogState()).toEqual({ status: "idle" });+ });++ it("ignores responses after the active dialog has been closed", () => {+ const unregister = registerConfirmDialogHost();+ const confirmation = requireConfirmation(requestConfirmDialog("Continue?"));++ respondToConfirmDialog(true);+ respondToConfirmDialog(false);+ completeConfirmDialogClose();++ expect(readConfirmDialogState()).toEqual({ status: "idle" });+ unregister();+ return expect(confirmation).resolves.toBe(true);+ });+});diff --git a/apps/web/src/confirmDialog.ts b/apps/web/src/confirmDialog.tsnew file mode 100644index 000000000..1bff7c930--- /dev/null+++ b/apps/web/src/confirmDialog.ts@@ -0,0 +1,131 @@+import type { ConfirmDialogOptions, ConfirmDialogVariant } from "@t3tools/contracts";++export type ConfirmDialogState =+ | { readonly status: "idle" }+ | {+ readonly status: "confirming";+ readonly message: string;+ readonly variant: ConfirmDialogVariant;+ }+ | {+ readonly status: "closing";+ readonly message: string;+ readonly variant: ConfirmDialogVariant;+ };++type PendingConfirmation = {+ readonly message: string;+ readonly variant: ConfirmDialogVariant;+ readonly resolve: (confirmed: boolean) => void;+};++const idleState: ConfirmDialogState = { status: "idle" };+let state: ConfirmDialogState = idleState;+let activeConfirmation: PendingConfirmation | null = null;+let queuedConfirmations: PendingConfirmation[] = [];+let registeredHostCount = 0;+const listeners = new Set<() => void>();++function publish(next: ConfirmDialogState): void {+ state = next;+ for (const listener of listeners) {+ listener();+ }+}++function resolvePendingConfirmations(confirmed: boolean): void {+ activeConfirmation?.resolve(confirmed);+ for (const confirmation of queuedConfirmations) {+ confirmation.resolve(confirmed);+ }+ activeConfirmation = null;+ queuedConfirmations = [];+}++export function readConfirmDialogState(): ConfirmDialogState {+ return state;+}++export function subscribeConfirmDialog(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/**+ * Registers the renderer host that can present themed confirmations. The+ * returned cleanup function also cancels any request left without a host.+ */+export function registerConfirmDialogHost(): () => void {+ registeredHostCount += 1;+ let registered = true;++ return () => {+ if (!registered) return;+ registered = false;+ registeredHostCount = Math.max(0, registeredHostCount - 1);++ if (registeredHostCount === 0) {+ resolvePendingConfirmations(false);+ publish(idleState);+ }+ };+}++/**+ * Requests a themed confirmation when a host is mounted. An undefined result+ * means no themed host is currently available.+ */+export function requestConfirmDialog(+ message: string,+ options?: ConfirmDialogOptions,+): Promise<boolean> | undefined {+ if (registeredHostCount === 0) return undefined;++ const confirmation = new Promise<boolean>((resolve) => {+ const pending = {+ message,+ variant: options?.variant ?? "default",+ resolve,+ } satisfies PendingConfirmation;+ if (activeConfirmation || state.status === "closing") {+ queuedConfirmations.push(pending);+ return;+ }++ activeConfirmation = pending;+ publish({ status: "confirming", message, variant: pending.variant });+ });++ return confirmation;+}++export function respondToConfirmDialog(confirmed: boolean): void {+ if (state.status !== "confirming" || !activeConfirmation) return;++ const confirmation = activeConfirmation;+ activeConfirmation = null;+ confirmation.resolve(confirmed);+ publish({ status: "closing", message: state.message, variant: state.variant });+}++export function completeConfirmDialogClose(): void {+ if (state.status !== "closing") return;++ const next = queuedConfirmations.shift();+ if (!next) {+ publish(idleState);+ return;+ }++ activeConfirmation = next;+ publish({ status: "confirming", message: next.message, variant: next.variant });+}++export function resetConfirmDialogForTests(): void {+ resolvePendingConfirmations(false);+ registeredHostCount = 0;+ publish(idleState);+ listeners.clear();+}diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.tsindex 85ffde776..24efe4ea1 100644--- a/apps/web/src/hooks/useThreadActionMenu.ts+++ b/apps/web/src/hooks/useThreadActionMenu.ts@@ -250,6 +250,7 @@ export function useThreadActionMenu(input: {`Delete thread "${thread.title}"?`,"This permanently clears conversation history for this thread.",].join("\n"),+ { variant: "destructive" },),);if (confirmed._tag === "Failure" || !confirmed.value) return;diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.tsindex 22548b233..569b4be96 100644--- a/apps/web/src/hooks/useThreadActions.ts+++ b/apps/web/src/hooks/useThreadActions.ts@@ -324,6 +324,7 @@ export function useThreadActions() {"","Delete the worktree too?",].join("\n"),+ { variant: "destructive" },),);if (confirmationResult._tag === "Failure") {@@ -678,6 +679,7 @@ export function useThreadActions() {`Delete thread "${title}"?`,"This permanently clears conversation history for this thread.",].join("\n"),+ { variant: "destructive" },),);if (confirmationResult._tag === "Failure") {diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.tsindex 260256c12..064b92703 100644--- a/apps/web/src/localApi.test.ts+++ b/apps/web/src/localApi.test.ts@@ -1,5 +1,6 @@import {DEFAULT_CLIENT_SETTINGS,+ type ConfirmDialogOptions,type ContextMenuItem,type DesktopBridge,} from "@t3tools/contracts";@@ -13,10 +14,17 @@ const showContextMenuFallbackMock =) => Promise<T | null>>();+const requestConfirmDialogMock =+ vi.fn<(message: string, options?: ConfirmDialogOptions) => Promise<boolean> | undefined>();+vi.mock("./contextMenuFallback", () => ({showContextMenuFallback: showContextMenuFallbackMock,}));+vi.mock("./confirmDialog", () => ({+ requestConfirmDialog: requestConfirmDialogMock,+}));+function createLocalStorageStub(): Storage {const values = new Map<string, string>();return {@@ -77,6 +85,24 @@ describe("LocalApi", () => {expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });});+ it("uses the themed confirmation host when it is available", async () => {+ requestConfirmDialogMock.mockResolvedValue(true);+ const { createLocalApi } = await import("./localApi");+ const options = { variant: "destructive" } as const;++ await expect(createLocalApi().dialogs.confirm("Delete this thread?", options)).resolves.toBe(+ true,+ );+ expect(requestConfirmDialogMock).toHaveBeenCalledWith("Delete this thread?", options);+ });++ it("fails closed in a browser when no themed host is available", async () => {+ requestConfirmDialogMock.mockReturnValue(undefined);+ const { createLocalApi } = await import("./localApi");++ await expect(createLocalApi().dialogs.confirm("Delete this thread?")).resolves.toBe(false);+ });+it("delegates host capabilities and persistence to the desktop bridge", async () => {const showContextMenu = vi.fn().mockResolvedValue("delete");const pickFolder = vi.fn().mockResolvedValue("/tmp/project");@@ -94,6 +120,8 @@ describe("LocalApi", () => {const items = [{ id: "delete", label: "Delete" }] as const;await expect(api.contextMenu.show(items)).resolves.toBe("delete");+ requestConfirmDialogMock.mockReturnValue(undefined);+ await expect(api.dialogs.confirm("Install update?")).resolves.toBe(false);await expect(api.dialogs.pickFolder({ initialPath: "/tmp" })).resolves.toBe("/tmp/project");await expect(api.persistence.getClientSettings()).resolves.toEqual(DEFAULT_CLIENT_SETTINGS);await api.persistence.setClientSettings(DEFAULT_CLIENT_SETTINGS);diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.tsindex b42702c7a..5c8f4ec9d 100644--- a/apps/web/src/localApi.ts+++ b/apps/web/src/localApi.ts@@ -1,8 +1,9 @@-import type { ContextMenuItem, LocalApi } from "@t3tools/contracts";+import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/contracts";-import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";+import { requestConfirmDialog } from "./confirmDialog";import { showContextMenuFallback } from "./contextMenuFallback";import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage";+import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";let cachedApi: LocalApi | undefined;@@ -13,11 +14,8 @@ function createBrowserLocalApi(): LocalApi {if (!window.desktopBridge) return null;return window.desktopBridge.pickFolder(options);},- confirm: async (message) => {- if (window.desktopBridge) {- return window.desktopBridge.confirm(message);- }- return window.confirm(message);+ confirm: async (message, options?: ConfirmDialogOptions) => {+ return requestConfirmDialog(message, options) ?? false;},},shell: {diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex cff930539..c4f65564e 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -14,6 +14,7 @@ import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";import { resolveServerBackedAppDisplayName } from "../branding.logic";import { AppSidebarLayout } from "../components/AppSidebarLayout";import { CommandPalette } from "../components/CommandPalette";+import { ConfirmDialogHost } from "../components/ConfirmDialogHost";import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";@@ -135,6 +136,7 @@ function RootRouteView() {<RelayClientInstallDialog /><ConnectOnboardingDialog /><SshPasswordPromptDialog />+ <ConfirmDialogHost /><SlowRpcRequestToastCoordinator /><HostedStaticEnvironmentBootstrap />{primaryEnvironmentAuthenticated ? <EventRouter /> : null}diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex 64ef755ee..7f9fdb271 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -1042,7 +1042,6 @@ export interface DesktopBridge {* web callers fall back to a plain file input.*/pickThemeFiles?: () => Promise<readonly PickedThemeFile[] | null>;- confirm: (message: string) => Promise<boolean>;setTheme: (theme: DesktopTheme) => Promise<void>;showContextMenu: <T extends string>(items: readonly ContextMenuItem<T>[],@@ -1137,6 +1136,12 @@ export interface DesktopPreviewBridge {onPointerEvent: (listener: (event: DesktopPreviewPointerEvent) => void) => () => void;}+export type ConfirmDialogVariant = "default" | "destructive";++export interface ConfirmDialogOptions {+ readonly variant?: ConfirmDialogVariant;+}+/*** APIs bound to the local app shell, not to any particular backend environment.*@@ -1150,7 +1155,7 @@ export interface DesktopPreviewBridge {export interface LocalApi {dialogs: {pickFolder: (options?: PickFolderOptions) => Promise<string | null>;- confirm: (message: string) => Promise<boolean>;+ confirm: (message: string, options?: ConfirmDialogOptions) => Promise<boolean>;};shell: {openExternal: (url: string) => Promise<void>;