Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(desktop): navigate question toasts to their originating chat (#1673)

new-Beginnerabb429874c92
diff --git a/apps/desktop/src/components/Toast.tsx b/apps/desktop/src/components/Toast.tsx
index c0aa20cf4..86473710f 100644
--- a/apps/desktop/src/components/Toast.tsx
+++ b/apps/desktop/src/components/Toast.tsx
@@ -9,7 +9,7 @@ import {
IconInfo,
IconTriangleAlert,
} from "./icons";
-import { TooltipButton } from "./ui";
+import { Button, TooltipButton } from "./ui";
import {
playNotificationChime,
shouldPlayToastSound,
@@ -25,8 +25,9 @@ const VARIANT_ICON: Record<ToastVariant, typeof IconInfo> = {
function ToastCard({ item }: { item: ToastItem }) {
const { t } = useTranslation();
const dismissToast = useAppStore((s) => s.dismissToast);
+ const sessionId = item.sessionId;
const [closing, setClosing] = useState(false);
- // Hover pauses the auto-dismiss timer; remaining time survives re-hovers.
+ // Hover or keyboard focus pauses the auto-dismiss timer.
const remainingRef = useRef(item.duration);
const startedAtRef = useRef(0);
const timerRef = useRef<number | null>(null);
@@ -41,7 +42,7 @@ function ToastCard({ item }: { item: ToastItem }) {
}, []);
const resumeTimer = useCallback(() => {
- if (item.duration === 0 || closing) return;
+ if (item.duration === 0 || closing || timerRef.current !== null) return;
startedAtRef.current = Date.now();
timerRef.current = window.setTimeout(beginClose, Math.max(remainingRef.current, 0));
}, [item.duration, closing, beginClose]);
@@ -56,18 +57,49 @@ function ToastCard({ item }: { item: ToastItem }) {
};
const Icon = VARIANT_ICON[item.variant];
+ const content = <>
+ <span className="toast-icon" aria-hidden>
+ <Icon size={16} />
+ </span>
+ <span className="toast-message selectable">{item.message}</span>
+ </>;
return (
<div
className={`toast ${item.variant}${closing ? " closing" : ""}`}
role={item.variant === "error" || item.variant === "warning" ? "alert" : "status"}
onMouseEnter={pauseTimer}
- onMouseLeave={resumeTimer}
+ onMouseLeave={(event) => {
+ if (!event.currentTarget.contains(document.activeElement)) resumeTimer();
+ }}
+ onFocusCapture={pauseTimer}
+ onBlurCapture={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget) && !event.currentTarget.matches(":hover")) {
+ resumeTimer();
+ }
+ }}
onAnimationEnd={onAnimationEnd}
>
- <span className="toast-icon" aria-hidden>
- <Icon size={16} />
- </span>
- <span className="toast-message selectable">{item.message}</span>
+ {sessionId ? (
+ <Button
+ type="button"
+ variant="ghost"
+ className="toast-action"
+ onClick={(event) => {
+ // Dragging to copy the question is not a navigation gesture.
+ const selection = window.getSelection();
+ if (!selection?.isCollapsed && selection?.containsNode(event.currentTarget, true)) return;
+ void useAppStore.getState().selectSession(sessionId).then(() => {
+ dismissToast(item.id);
+ }).catch((error) => {
+ useAppStore.getState().showToast(error instanceof Error ? error.message : String(error), {
+ variant: "error",
+ });
+ });
+ }}
+ >
+ {content}
+ </Button>
+ ) : content}
<TooltipButton
type="button"
className="toast-dismiss"
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index 9ab1bc174..7858a3e7b 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -64,6 +64,8 @@ export type ToastItem = {
duration: number;
/** Notification chime is enabled by default. */
sound: boolean;
+ /** Optional conversation opened when the user activates the toast. */
+ sessionId?: string;
};
export type ToastOptions = {
@@ -72,6 +74,8 @@ export type ToastOptions = {
duration?: number;
/** Suppress the default soft chime when another notification surface already played it. */
sound?: boolean;
+ /** Make the toast message an explicit conversation-navigation action. */
+ sessionId?: string;
};
export type AgentTurnResult = {
diff --git a/apps/desktop/src/stores/runtime/notification-runtime.ts b/apps/desktop/src/stores/runtime/notification-runtime.ts
index 8dcb77e4c..98ef2203b 100644
--- a/apps/desktop/src/stores/runtime/notification-runtime.ts
+++ b/apps/desktop/src/stores/runtime/notification-runtime.ts
@@ -37,6 +37,7 @@ export function createInteractivePromptNotifier(
variant: "info",
duration: 8_000,
sound: false,
+ sessionId,
});
}
void api
diff --git a/apps/desktop/src/stores/slices/interaction-slice.ts b/apps/desktop/src/stores/slices/interaction-slice.ts
index 29406b838..dcf29e0ef 100644
--- a/apps/desktop/src/stores/slices/interaction-slice.ts
+++ b/apps/desktop/src/stores/slices/interaction-slice.ts
@@ -211,7 +211,8 @@ export function createInteractionSlice({
(variant === "error" ? TOAST_ERROR_DURATION_MS : TOAST_DURATION_MS);
set((state) => {
const kept = state.toasts.filter(
- (item) => item.message !== message || item.variant !== variant,
+ (item) => item.message !== message || item.variant !== variant ||
+ item.sessionId !== options?.sessionId,
);
const next = [
...kept,
@@ -221,6 +222,7 @@ export function createInteractionSlice({
variant,
duration,
sound: options?.sound !== false,
+ sessionId: options?.sessionId,
},
];
return { toasts: next.slice(-TOAST_STACK_LIMIT) };
diff --git a/apps/desktop/src/styles/overlays.css b/apps/desktop/src/styles/overlays.css
index 74c52e5e0..da53d9cf5 100644
--- a/apps/desktop/src/styles/overlays.css
+++ b/apps/desktop/src/styles/overlays.css
@@ -557,6 +557,27 @@
overflow-wrap: anywhere;
}
+.toast-action.btn {
+ display: flex;
+ flex: 1;
+ min-width: 0;
+ align-items: flex-start;
+ justify-content: flex-start;
+ gap: 10px;
+ padding: 0;
+ text-align: left;
+ color: inherit;
+}
+
+.toast-action.btn:hover:not(:disabled) {
+ background: transparent;
+}
+
+.toast-action:focus-visible {
+ outline: 2px solid var(--ds-accent);
+ outline-offset: 3px;
+}
+
.toast-dismiss {
display: inline-flex;
flex: 0 0 auto;
diff --git a/docs/spec/03-runtime/17-asktool-questions.md b/docs/spec/03-runtime/17-asktool-questions.md
index cedc0a4a5..8a4753ad2 100644
--- a/docs/spec/03-runtime/17-asktool-questions.md
+++ b/docs/spec/03-runtime/17-asktool-questions.md
@@ -49,6 +49,17 @@ existing native notification policy. Ask titles deliberately do not interpolate
the session title, because generated titles may contain tool-call text. The ask
event plays one soft in-app chime; its toast does not play a second one.
+The toast retains its originating session. Clicking its message, or activating
+the focused message button with Enter/Space, opens the conversation through
+normal session selection, including project alignment and pending-question
+restoration, then dismisses the toast only after success. Receipt alone never navigates. Closing the
+toast or selecting its text does not open a conversation. Hover and keyboard
+focus pause auto-dismiss. Identical prompts from different sessions keep
+separate targets; repeats within one session still replace the earlier toast.
+Navigation failures show an error toast and retain the original reminder for
+retry without resolving the pending question.
+Ordinary toasts without a session target remain non-interactive.
+
## 4. Tool output
The response is the normal tool result returned to the model and persisted with
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index c4638e5ca..b4972377c 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -11064,6 +11064,15 @@ This test plan spec is accepted when:
text never replaces that title. Background sessions retain the existing
native notification policy. Exactly one soft chime plays for the ask; the
toast and native banner do not double it.
+ Clicking the question toast (including from New task or Settings) opens its
+ originating conversation and project, shows the pending card, and permits
+ submitting an answer for that request. Enter and Space activate the focused
+ message button. Dismiss and text selection do not navigate. Identical prompt
+ text from two sessions preserves two independent navigation targets; ordinary
+ info toasts stay non-interactive. A history-read failure produces a visible
+ error and leaves both the original reminder and question pending. Retrying
+ from that same reminder after the read recovers opens the correct chat and
+ dismisses the reminder only after navigation succeeds.
- **Specs linked**: `03-runtime/17-asktool-questions.md`,
`04-ux/11-asktool-question-card.md`, ADR 0077
- **Acceptance**: E (interactive tool output), C (inline card)
@@ -11071,6 +11080,9 @@ This test plan spec is accepted when:
- **Automated coverage**: `pnpm test:e2e:asktool-card` mounts the production
component in Electron and covers long-prompt scrolling, keyboard reachability,
visible header actions, and scroll reset on Next.
+ `pnpm test:e2e:question-notification` exercises real renderer event handling,
+ toast creation, session/project navigation, and answer submission in isolated
+ Electron with only the IPC boundary stubbed, plus native keyboard input.
- **Status**: Partially automated (component paths and long-prompt behavior are
covered; full application journey pending)
diff --git a/package.json b/package.json
index c019baa40..31d0c4aa0 100644
--- a/package.json
+++ b/package.json
@@ -25,6 +25,7 @@
"test:e2e:storage": "node scripts/e2e-storage-settings.mjs && node scripts/e2e-storage-migration.mjs && node scripts/e2e-storage-bootstrap.mjs",
"test:e2e:asktool-card": "node scripts/e2e-asktool-card.mjs",
"test:e2e:worktree-live": "node scripts/e2e-worktree-live.mjs",
+ "test:e2e:question-notification": "node scripts/e2e-question-notification.mjs",
"test:e2e:scheduled": "node scripts/e2e-scheduled.mjs",
"test:e2e:keep-awake": "node scripts/e2e-keep-awake.mjs",
"test:e2e:live-voice": "node scripts/e2e-live-voice.mjs",
diff --git a/scripts/e2e-question-notification.mjs b/scripts/e2e-question-notification.mjs
new file mode 100644
index 000000000..c4c4eb89f
--- /dev/null
+++ b/scripts/e2e-question-notification.mjs
@@ -0,0 +1,89 @@
+#!/usr/bin/env node
+/** Isolated React/Chromium user path for question-toast navigation. No provider calls. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(join(root, "packages/agent-runtime/package.json"));
+const { build } = require("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR || tmpdir(), "pi-question-notification-"));
+try {
+ await build({
+ entryPoints: [join(root, "scripts/e2e/question-notification.tsx")],
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife",
+ jsx: "automatic", loader: { ".css": "empty" },
+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ "@pi-desktop/shared/protocol": join(root, "packages/shared/src/protocol.ts"),
+ "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ // Use the production toast rules; no app build or existing user profile required.
+ const styles = await Promise.all(["ui-kit.css", "overlays.css"].map((name) =>
+ readFile(join(root, "apps/desktop/src/styles", name), "utf8")));
+ await writeFile(join(temp, "index.html"), `<!doctype html><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'">
+<style>:root { --motion-duration-normal: 200ms; --motion-duration-fast: 150ms;
+--motion-ease-in: ease-in; --motion-ease-out: ease-out; }${styles.join("\n")}</style>
+<script src="renderer.js"></script>`);
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({ show: true, title: "Question notification regression", width: 1000, height: 800,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ win.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ win.focus();
+ const result = await win.webContents.executeJavaScript("globalThis.questionNotificationProbe()");
+ console.log("QUESTION_POINTER_CHECKS " + JSON.stringify(result));
+ for (const keyCode of ["Return", "Space"]) {
+ console.log("QUESTION_KEYBOARD_CHECK " + keyCode);
+ await win.webContents.executeJavaScript("globalThis.prepareQuestionNotificationKeyboard()");
+ win.webContents.sendInputEvent({ type: "keyDown", keyCode });
+ win.webContents.sendInputEvent({ type: "char", keyCode: keyCode === "Return" ? "\\r" : " " });
+ win.webContents.sendInputEvent({ type: "keyUp", keyCode });
+ await win.webContents.executeJavaScript("globalThis.finishQuestionNotificationKeyboard()");
+ }
+ console.log("QUESTION_NOTIFICATION_PROBE " + JSON.stringify({ ...result, keyboard: true }));
+ app.exit(0);
+ } catch (error) {
+ console.error("QUESTION_NOTIFICATION_PROBE " + JSON.stringify({ ok: false, error: error?.stack ?? String(error) }));
+ app.exit(1);
+ }
+});
+`);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", (data) => { output += data; });
+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally { clearTimeout(timer); }
+ const line = output.split(/\r?\n/).find((item) => item.startsWith("QUESTION_NOTIFICATION_PROBE "));
+ assert(line, `No probe result (exit=${code}): ${output.slice(-6000)}`);
+ const result = JSON.parse(line.slice("QUESTION_NOTIFICATION_PROBE ".length));
+ console.log("QUESTION_NOTIFICATION_PROBE " + JSON.stringify(result));
+ assert.equal(code, 0, output.slice(-6000));
+ assert.equal(result.ok, true, result.error);
+ console.log("question notification navigation: ok");
+} finally { await rm(temp, { recursive: true, force: true }); }
diff --git a/scripts/e2e/question-notification.tsx b/scripts/e2e/question-notification.tsx
new file mode 100644
index 000000000..8499b2b9b
--- /dev/null
+++ b/scripts/e2e/question-notification.tsx
@@ -0,0 +1,260 @@
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "@pi-desktop/i18n";
+import { IPC } from "@pi-desktop/shared/protocol";
+import type { AskToolRequest, Result, SessionSummary } from "@pi-desktop/shared";
+import { AskToolCard } from "../../apps/desktop/src/components/AskToolCard";
+import { ToastHost } from "../../apps/desktop/src/components/Toast";
+import { headAsk } from "../../apps/desktop/src/lib/pending-asks";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+const createdAt = "2026-09-01T00:00:00Z";
+const sessions: SessionSummary[] = ["A", "B"].map((id) => ({
+ id, title: `Chat ${id}`, mode: "agent", permissionMode: "ask", thinkingLevel: "off",
+ providerId: "fixture", modelId: "fixture", createdAt, updatedAt: createdAt,
+ messageCount: 1, projectPath: `C:/fixture/${id}`,
+}));
+const requests = new Map<string, AskToolRequest>();
+const resolutions: unknown[] = [];
+const unexpected: string[] = [];
+let rejectReads = false;
+let readCount = 0;
+let sequence = 0;
+const frame = () => new Promise<void>((resolve) => queueMicrotask(resolve));
+function assert(value: unknown, message: string): asserts value {
+ if (!value) throw new Error(message);
+}
+function until(predicate: () => boolean, message: string): Promise<void> {
+ if (predicate()) return Promise.resolve();
+ return new Promise((resolve, reject) => {
+ const check = () => {
+ if (!predicate()) return;
+ cleanup();
+ resolve();
+ };
+ const observer = new MutationObserver(check);
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true });
+ const unsubscribe = useAppStore.subscribe(check);
+ const timer = setTimeout(() => {
+ cleanup();
+ reject(new Error(`Timed out: ${message}; active=${useAppStore.getState().activeSessionId}`));
+ }, 8_000);
+ const cleanup = () => { clearTimeout(timer); unsubscribe(); observer.disconnect(); };
+ check();
+ });
+}
+function Surface() {
+ const active = useAppStore((state) => state.activeSessionId);
+ const page = useAppStore((state) => state.page);
+ const pending = useAppStore((state) => state.pendingAsks);
+ const request = active ? headAsk(pending, active) : undefined;
+ return <>
+ <output id="active-chat">{page}:{active ?? "home"}</output>
+ {request && <AskToolCard key={request.requestId} request={request} />}
+ <ToastHost />
+ </>;
+}
+function reset(page: "chat" | "settings" = "chat", activeSessionId?: string) {
+ requests.clear();
+ flushSync(() => useAppStore.setState({
+ page, activeSessionId, selectingSessionId: undefined, messages: [],
+ toasts: [], pendingAsks: {}, workspace: undefined, activeProjectPath: undefined,
+ }));
+}
+function ask(sessionId: string, question = "Which path should we take?") {
+ const request: AskToolRequest = {
+ sessionId, requestId: `ask-${++sequence}`, toolCallId: `tool-${sequence}`,
+ questions: [{ question, options: ["Continue", "Cancel"] }],
+ };
+ requests.set(sessionId, request);
+ flushSync(() => useAppStore.getState().handleAgentEvent({
+ ts: Date.parse(createdAt),
+ sessionId, turnId: `turn-${sequence}`, event: { type: "asktool_request", request },
+ }));
+ return request;
+}
+function action(sessionId: string) {
+ const toasts = useAppStore.getState().toasts;
+ const index = toasts.findIndex((item) => item.sessionId === sessionId);
+ assert(index >= 0, `Missing toast target for session ${sessionId}`);
+ const button = document.querySelectorAll(".toast")[index]
+ ?.querySelector<HTMLButtonElement>("button:not(.toast-dismiss)");
+ assert(button, "Question toast must expose a navigable button");
+ return button;
+}
+async function selected(sessionId: string) {
+ await until(() => useAppStore.getState().activeSessionId === sessionId &&
+ useAppStore.getState().selectingSessionId === undefined &&
+ document.getElementById("active-chat")?.textContent === `chat:${sessionId}` &&
+ Boolean(document.querySelector(".asktool-card")), `destination chat ${sessionId} and pending question`);
+ assert(useAppStore.getState().activeProjectPath === `C:/fixture/${sessionId}`, "Project did not follow the chat");
+ assert(useAppStore.getState().messages[0]?.content === `Transcript ${sessionId}`, "Wrong conversation transcript");
+}
+
+declare global {
+ var questionNotificationProbe: () => Promise<unknown>;
+ var prepareQuestionNotificationKeyboard: () => void;
+ var finishQuestionNotificationKeyboard: () => Promise<void>;
+}
+
+globalThis.questionNotificationProbe = async () => {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ window.piDesktop = {
+ channels: IPC, platform: "win32", on: () => () => {},
+ invoke: async <T,>(channel: string, ...args: unknown[]): Promise<Result<T>> => {
+ const input = args[0];
+ let data: unknown;
+ if (channel === IPC.invoke.sessionGet) {
+ readCount++;
+ if (rejectReads) return { ok: false, error: { code: "FIXTURE_READ", message: "Fixture history unavailable" } };
+ assert(input && typeof input === "object" && "id" in input, "Invalid session read");
+ const session = sessions.find((item) => item.id === input.id);
+ assert(session, "Unexpected session read");
+ data = { session: { ...session, messages: [{ id: `message-${session.id}`, role: "user",
+ content: `Transcript ${session.id}`, createdAt, status: "complete" }] } };
+ } else if (channel === IPC.invoke.projectSet) {
+ assert(typeof input === "string", "Invalid project activation");
+ data = { workspace: { path: input, name: input.split("/").at(-1), branch: "main" } };
+ } else if (channel === IPC.invoke.plansPending) data = { plans: [], state: "inactive" };
+ else if (channel === IPC.invoke.pendingInteractive) {
+ assert(input && typeof input === "object" && "sessionId" in input, "Invalid pending request");
+ const request = requests.get(String(input.sessionId));
+ data = { permissions: [], asks: request ? [request] : [] };
+ } else if (channel === IPC.invoke.notificationShowNative) data = { shown: false };
+ else if (channel === IPC.invoke.askToolResolve) { resolutions.push(input); data = { ok: true }; }
+ else {
+ unexpected.push(channel);
+ return { ok: false, error: { code: "FIXTURE_UNEXPECTED", message: `Unexpected IPC ${channel}` } };
+ }
+ return { ok: true, data: data as T };
+ },
+ };
+ useAppStore.setState({
+ sessions, notifications: [], runningSessions: {}, retainedSessionIds: [], retainedTranscripts: {},
+ pendingPlans: {}, pendingPermissions: {}, providers: [], providerModels: {},
+ });
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><Surface /></I18nextProvider>));
+ await until(() => Boolean(document.querySelector(".toast-viewport")), "toast host");
+
+ // Start at the empty New task surface, as in the reported screenshot.
+ reset();
+ const request = ask("B");
+ const originalToastId = useAppStore.getState().toasts[0]?.id;
+ assert(useAppStore.getState().activeSessionId === undefined, "Receipt must not navigate automatically");
+ action("B").click();
+ assert(useAppStore.getState().toasts.some((item) => item.id === originalToastId),
+ "Question toast disappeared before navigation succeeded");
+ await selected("B");
+ await until(() => !useAppStore.getState().toasts.some((item) => item.id === originalToastId),
+ "successful navigation dismisses the original toast");
+ const option = document.querySelector<HTMLButtonElement>(".asktool-option");
+ assert(option, "Pending question is not answerable");
+ flushSync(() => option.click());
+ const submit = document.querySelector<HTMLButtonElement>(".asktool-card-header-actions .btn-primary");
+ assert(submit, "Missing submit action");
+ submit.click();
+ await until(() => resolutions.length === 1, "answer reaches the host");
+ assert(JSON.stringify(resolutions[0]) === JSON.stringify({
+ requestId: request.requestId, sessionId: "B", answers: [["Continue"]],
+ }), "Answer resolved the wrong request");
+
+ // Same text in different chats must retain both destinations.
+ reset("chat", "A");
+ ask("A"); ask("B");
+ assert(useAppStore.getState().toasts.length === 2, "Different sessions must not deduplicate each other");
+ const previous = useAppStore.getState().toasts.find((item) => item.sessionId === "A")?.id;
+ ask("A");
+ assert(useAppStore.getState().toasts.length === 2 &&
+ !useAppStore.getState().toasts.some((item) => item.id === previous), "Same-session repeat did not replace its toast");
+ action("B").click();
+ await selected("B");
+ action("A").click();
+ await selected("A");
+
+ // Dismiss and text selection are not activation gestures.
+ reset("settings");
+ ask("B");
+ const reads = readCount;
+ const target = action("B");
+ const message = target.querySelector(".toast-message");
+ assert(message, "Missing selectable message");
+ const range = document.createRange(); range.selectNodeContents(message);
+ window.getSelection()?.removeAllRanges(); window.getSelection()?.addRange(range);
+ target.click();
+ await frame();
+ assert(readCount === reads, "Selecting toast text must not navigate");
+ window.getSelection()?.removeAllRanges();
+ const dismiss = document.querySelector<HTMLButtonElement>(".toast-dismiss");
+ assert(dismiss, "Missing dismiss control");
+ dismiss.click();
+ await until(() => useAppStore.getState().toasts.length === 0, "dismiss animation");
+ assert(readCount === reads && useAppStore.getState().page === "settings", "Dismiss unexpectedly navigated");
+
+ // Controlled timers prove focus/hover transitions never duplicate the countdown.
+ reset();
+ const browser: Window = window;
+ const originalSetTimeout = browser.setTimeout;
+ const originalClearTimeout = browser.clearTimeout;
+ const timers = new Map<number, TimerHandler>();
+ let timerId = -1;
+ browser.setTimeout = (handler) => { timers.set(--timerId, handler); return timerId; };
+ browser.clearTimeout = (id) => {
+ if (id === undefined || !timers.delete(id)) originalClearTimeout(id);
+ };
+ try {
+ flushSync(() => useAppStore.getState().showToast("Focus timer", { sessionId: "B", sound: false }));
+ assert(Array.from(timers).length === 1, "Toast should own one countdown");
+ const focused = action("B");
+ flushSync(() => focused.focus());
+ assert(Array.from(timers).length === 0, "Focus did not pause the countdown");
+ focused.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: document.body }));
+ assert(Array.from(timers).length === 0, "Mouse leave restarted a keyboard-focused countdown");
+ flushSync(() => focused.blur());
+ assert(Array.from(timers).length === 1, "Blur did not resume the countdown");
+ reset();
+ assert(Array.from(timers).length === 0, "Unmount left a countdown behind");
+ } finally {
+ browser.setTimeout = originalSetTimeout;
+ browser.clearTimeout = originalClearTimeout;
+ }
+
+ reset();
+ flushSync(() => useAppStore.getState().showToast("Ordinary information", { sound: false, duration: 0 }));
+ assert(!document.querySelector(".toast button:not(.toast-dismiss)"), "Ordinary toast became interactive");
+
+ // Failures remain visible and the question stays pending.
+ reset();
+ ask("B"); rejectReads = true;
+ const failedToastId = useAppStore.getState().toasts[0]?.id;
+ action("B").click();
+ await until(() => useAppStore.getState().toasts.some((item) => item.variant === "error" &&
+ item.message.includes("Fixture history unavailable")), "navigation failure feedback");
+ rejectReads = false;
+ assert(headAsk(useAppStore.getState().pendingAsks, "B"), "Navigation failure discarded the pending question");
+ assert(useAppStore.getState().toasts.some((item) => item.id === failedToastId),
+ "Navigation failure discarded the original question reminder");
+ action("B").click();
+ await selected("B");
+ await until(() => !useAppStore.getState().toasts.some((item) => item.id === failedToastId),
+ "successful retry dismisses the retained reminder");
+ assert(unexpected.length === 0, `Unexpected IPC: ${unexpected}`);
+
+ // The runner delivers real Chromium keyboard events after focusing the action.
+ globalThis.prepareQuestionNotificationKeyboard = () => {
+ reset("settings");
+ ask("B", "Keyboard question");
+ action("B").focus();
+ assert(document.activeElement === action("B"), "Question action is not focusable");
+ };
+ globalThis.finishQuestionNotificationKeyboard = async () => {
+ await selected("B");
+ assert(unexpected.length === 0, `Unexpected IPC: ${unexpected}`);
+ };
+ return { ok: true, home: true, crossProject: true, answered: true, distinctTargets: true,
+ dismiss: true, textSelection: true, focusTimer: true, ordinaryToast: true, errorFeedback: true, retry: true };
+};