Merge pull request #916 from sisantaChhatoi/split/chat-dashboard

refactor(web): useReducer for chat, dashboard, shared browser and auth pages
This commit is contained in:
BaaRai 2026-12-03 13:55:28 +01:00 • committed by GitHub
commit 443cf894da
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 1047 additions and 290 deletions

View file

@ -0,0 +1,65 @@
import { mergePatch, setSlice } from "@/lib/reducers/slice";
export type LoginForm = {
password: string;
agreed: boolean;
};
export type LoginTerms = {
open: boolean;
readToEnd: boolean;
};
export type LoginStatus = {
checking: boolean;
submitting: boolean;
error: string;
};
export type LoginPageState = {
form: LoginForm;
terms: LoginTerms;
status: LoginStatus;
};
export type LoginPageAction =
| { type: "formChanged"; patch: Partial<LoginForm> }
| { type: "termsChanged"; patch: Partial<LoginTerms> }
| { type: "termsAgreed" }
| { type: "statusCheckFailed"; error: string }
| { type: "statusChecked" }
| { type: "validationFailed"; error: string }
| { type: "submitStarted" }
| { type: "submitFailed"; error: string }
| { type: "submitFinished" };
export const initialLoginPageState: LoginPageState = {
form: { password: "", agreed: false },
terms: { open: false, readToEnd: false },
status: { checking: true, submitting: false, error: "" },
};
function withStatus(state: LoginPageState, patch: Partial<LoginStatus>): LoginPageState {
return setSlice(state, "status", mergePatch(state.status, patch));
}
export function loginPageReducer(state: LoginPageState, action: LoginPageAction): LoginPageState {
switch (action.type) {
case "formChanged":
return setSlice(state, "form", mergePatch(state.form, action.patch));
case "termsChanged":
return setSlice(state, "terms", mergePatch(state.terms, action.patch));
case "termsAgreed":
return { ...state, form: { ...state.form, agreed: true }, status: { ...state.status, error: "" } };
case "statusCheckFailed":
case "validationFailed":
case "submitFailed":
return withStatus(state, { error: action.error });
case "statusChecked":
return withStatus(state, { checking: false });
case "submitStarted":
return withStatus(state, { submitting: true, error: "" });
case "submitFinished":
return withStatus(state, { submitting: false });
}
}

View file

@ -1,6 +1,6 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useEffect, useReducer, useRef } from "react";
import { useRouter } from "next/navigation";
@ -15,30 +15,30 @@ import { t } from "@/i18n";
import { api } from "@/lib/api";
import { auth } from "@/lib/auth";
import { initialLoginPageState, loginPageReducer } from "./_state/login-page.reducer";
export default function LoginPage() {
const router = useRouter();
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [checking, setChecking] = useState(true);
const [agreed, setAgreed] = useState(false);
const [termsOpen, setTermsOpen] = useState(false);
const [readToEnd, setReadToEnd] = useState(false);
const [state, dispatch] = useReducer(loginPageReducer, initialLoginPageState);
const { password, agreed } = state.form;
const { open: termsOpen, readToEnd } = state.terms;
const { checking, submitting: loading, error } = state.status;
const termsBodyRef = useRef<HTMLDivElement>(null);
// Scroll to the bottom of the terms (including when everything fits without scrolling) to unlock "Agree".
function handleTermsScroll() {
const el = termsBodyRef.current;
if (!el) return;
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 8) setReadToEnd(true);
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 8)
dispatch({ type: "termsChanged", patch: { readToEnd: true } });
}
useEffect(() => {
if (!termsOpen) return;
// Reset on open, and cover the case where the content is shorter than one screen and never fires a scroll.
setReadToEnd(false);
dispatch({ type: "termsChanged", patch: { readToEnd: false } });
const el = termsBodyRef.current;
if (el && el.scrollHeight <= el.clientHeight + 8) setReadToEnd(true);
if (el && el.scrollHeight <= el.clientHeight + 8) dispatch({ type: "termsChanged", patch: { readToEnd: true } });
}, [termsOpen]);
useEffect(() => {
@ -56,26 +56,25 @@ export default function LoginPage() {
.then(({ initialized }) => {
if (!initialized) router.replace("/setup");
})
.catch(() => setError(t("Unable to connect to the backend service")))
.finally(() => setChecking(false));
.catch(() => dispatch({ type: "statusCheckFailed", error: t("Unable to connect to the backend service") }))
.finally(() => dispatch({ type: "statusChecked" }));
}, [router]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!agreed) {
setError(t("Please read and agree to the Terms of Use first"));
dispatch({ type: "validationFailed", error: t("Please read and agree to the Terms of Use first") });
return;
}
setLoading(true);
setError("");
dispatch({ type: "submitStarted" });
try {
const { token } = await api.login("ARTEX", password);
auth.setToken(token);
window.location.replace("/function/tasks");
} catch {
setError(t("Incorrect username or password"));
dispatch({ type: "submitFailed", error: t("Incorrect username or password") });
} finally {
setLoading(false);
dispatch({ type: "submitFinished" });
}
}
@ -131,7 +130,7 @@ export default function LoginPage() {
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onChange={(e) => dispatch({ type: "formChanged", patch: { password: e.target.value } })}
placeholder={t("Enter your password")}
autoFocus
autoComplete="current-password"
@ -141,14 +140,14 @@ export default function LoginPage() {
<Checkbox
id="agree-terms"
checked={agreed}
onCheckedChange={(v) => setAgreed(v === true)}
onCheckedChange={(v) => dispatch({ type: "formChanged", patch: { agreed: v === true } })}
className="mt-0.5"
/>
<Label htmlFor="agree-terms" className="text-sm font-normal leading-relaxed text-muted-foreground">
{agreeBefore}
<button
type="button"
onClick={() => setTermsOpen(true)}
onClick={() => dispatch({ type: "termsChanged", patch: { open: true } })}
className="mx-0.5 font-medium text-primary underline-offset-4 hover:underline"
>
{t("Terms of Use")}
@ -164,7 +163,7 @@ export default function LoginPage() {
</div>
</div>
<Dialog open={termsOpen} onOpenChange={setTermsOpen}>
<Dialog open={termsOpen} onOpenChange={(open) => dispatch({ type: "termsChanged", patch: { open } })}>
<DialogContent className="gap-0 p-0 sm:max-w-2xl">
<DialogHeader className="flex-row items-center gap-3 border-b px-6 py-4">
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
@ -339,14 +338,7 @@ export default function LoginPage() {
{readToEnd ? t("You have read all the terms") : t("Scroll the terms to the bottom to confirm")}
</p>
<DialogClose asChild>
<Button
type="button"
disabled={!readToEnd}
onClick={() => {
setAgreed(true);
setError("");
}}
>
<Button type="button" disabled={!readToEnd} onClick={() => dispatch({ type: "termsAgreed" })}>
{t("I have read and agree to all the terms")}
</Button>
</DialogClose>

View file

@ -0,0 +1,59 @@
import { mergePatch, setSlice } from "@/lib/reducers/slice";
export type SetupForm = {
password: string;
confirm: string;
setupToken: string;
};
export type SetupStatus = {
checking: boolean;
/**
* The initialization state could not be fetched. Do not default to "not initialized": that would show the setup
* form to an instance that already has a password, and following it would overwrite the original.
*/
unavailable: boolean;
submitting: boolean;
error: string;
};
export type SetupPageState = {
form: SetupForm;
status: SetupStatus;
};
export type SetupPageAction =
| { type: "formFieldChanged"; patch: Partial<SetupForm> }
| { type: "statusCheckFailed"; error: string }
| { type: "statusChecked" }
| { type: "validationFailed"; error: string }
| { type: "submitStarted" }
| { type: "submitFailed"; error: string }
| { type: "submitFinished" };
export const initialSetupPageState: SetupPageState = {
form: { password: "", confirm: "", setupToken: "" },
status: { checking: true, unavailable: false, submitting: false, error: "" },
};
function withStatus(state: SetupPageState, patch: Partial<SetupStatus>): SetupPageState {
return setSlice(state, "status", mergePatch(state.status, patch));
}
export function setupPageReducer(state: SetupPageState, action: SetupPageAction): SetupPageState {
switch (action.type) {
case "formFieldChanged":
return setSlice(state, "form", mergePatch(state.form, action.patch));
case "statusCheckFailed":
return withStatus(state, { error: action.error, unavailable: true });
case "statusChecked":
return withStatus(state, { checking: false });
case "validationFailed":
case "submitFailed":
return withStatus(state, { error: action.error });
case "submitStarted":
return withStatus(state, { submitting: true, error: "" });
case "submitFinished":
return withStatus(state, { submitting: false });
}
}

View file

@ -1,6 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import { useEffect, useReducer } from "react";
import { useRouter } from "next/navigation";
@ -11,17 +11,15 @@ import { t } from "@/i18n";
import { api } from "@/lib/api";
import { auth } from "@/lib/auth";
import { initialSetupPageState, setupPageReducer } from "./_state/setup-page.reducer";
export default function SetupPage() {
const router = useRouter();
const [password, setPassword] = useState("");
const [confirm, setConfirm] = useState("");
const [setupToken, setSetupToken] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [checking, setChecking] = useState(true);
const [state, dispatch] = useReducer(setupPageReducer, initialSetupPageState);
const { password, confirm, setupToken } = state.form;
// when the initialization state cannot be fetched, do not default to "not initialized" — that would show the setup form to an
// instance that already has a password, and following it would overwrite the original. Close the entrance instead.
const [unavailable, setUnavailable] = useState(false);
const { checking, unavailable, submitting: loading, error } = state.status;
useEffect(() => {
api
@ -30,32 +28,33 @@ export default function SetupPage() {
if (initialized) router.replace("/login");
})
.catch((err) => {
setError(err instanceof Error ? err.message : t("Unable to connect to the backend service"));
setUnavailable(true);
dispatch({
type: "statusCheckFailed",
error: err instanceof Error ? err.message : t("Unable to connect to the backend service"),
});
})
.finally(() => setChecking(false));
.finally(() => dispatch({ type: "statusChecked" }));
}, [router]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (password !== confirm) {
setError(t("The two passwords do not match"));
dispatch({ type: "validationFailed", error: t("The two passwords do not match") });
return;
}
if (password.length < 12) {
setError(t("Password must be at least 12 characters"));
dispatch({ type: "validationFailed", error: t("Password must be at least 12 characters") });
return;
}
setLoading(true);
setError("");
dispatch({ type: "submitStarted" });
try {
const { token } = await api.initPassword(password, setupToken.trim());
auth.setToken(token);
router.replace("/function/tasks");
} catch (err) {
setError(err instanceof Error ? err.message : t("Initialization failed"));
dispatch({ type: "submitFailed", error: err instanceof Error ? err.message : t("Initialization failed") });
} finally {
setLoading(false);
dispatch({ type: "submitFinished" });
}
}
@ -108,7 +107,7 @@ export default function SetupPage() {
<Input
id="setup-token"
value={setupToken}
onChange={(e) => setSetupToken(e.target.value)}
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { setupToken: e.target.value } })}
placeholder={t("Printed in the server log at startup")}
autoFocus
autoComplete="off"
@ -120,7 +119,7 @@ export default function SetupPage() {
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { password: e.target.value } })}
placeholder={t("At least 12 characters")}
autoComplete="new-password"
/>
@ -131,7 +130,7 @@ export default function SetupPage() {
id="confirm"
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { confirm: e.target.value } })}
placeholder={t("Enter the password again")}
autoComplete="new-password"
/>

View file

@ -0,0 +1,79 @@
import { CONVERSATION_LIST_PAGE, chatPageReducer, initChatPageState } from "./chat-page.reducer.ts";
import assert from "node:assert/strict";
import test from "node:test";
const conv = (id, agent_key = "auto", pinned = false) => ({ id, agent_key, pinned });
const reduce = (actions, state = initChatPageState()) => actions.reduce(chatPageReducer, state);
const loaded = (items) => [{ type: "list/loaded", items }, { type: "list/loadFinished" }];
test("a started conversation is inserted above the first unpinned row", () => {
const s = reduce([
...loaded([conv(1, "auto", true), conv(2), conv(3)]),
{ type: "conversationStarted", conversation: conv(9), pending: { input: "hi" } },
]);
assert.deepEqual(
s.list.items.map((c) => c.id),
[1, 9, 2, 3],
);
assert.deepEqual(s.pendingByConv[9], { input: "hi" });
});
test("a started conversation clears a filter that would hide it", () => {
const s = reduce([
{ type: "agentFilterChanged", agentFilter: "web" },
{ type: "conversationStarted", conversation: conv(4, "auto") },
]);
assert.equal(s.sidebar.agentFilter, null);
});
test("changing the agent filter resets paging, selection, dialog and rename", () => {
const s = reduce([
...loaded([conv(1), conv(2)]),
{ type: "moreConversationsShown" },
{ type: "selection/set", ids: [1, 2] },
{ type: "bulkDeleteOpenChanged", open: true },
{ type: "renameChanged", patch: { id: 1, text: "old" } },
{ type: "agentFilterChanged", agentFilter: "auto" },
]);
assert.equal(s.sidebar.visibleCount, CONVERSATION_LIST_PAGE);
assert.equal(s.selection.size, 0);
assert.equal(s.bulkDeleteOpen, false);
assert.equal(s.rename.id, null);
assert.equal(s.rename.text, "old");
});
test("deleting a conversation unchecks it; deleting an unchecked one keeps the state", () => {
const s = reduce([
{ type: "selection/set", ids: [1, 2] },
{ type: "conversationDeleted", id: 2 },
]);
assert.deepEqual([...s.selection], [1]);
assert.equal(chatPageReducer(s, { type: "conversationDeleted", id: 7 }), s);
});
test("bulk delete keeps selection mode only when some deletes failed", () => {
const base = reduce([
{ type: "selectionModeEntered" },
{ type: "selection/set", ids: [1, 2, 3] },
{ type: "bulkDeleteOpenChanged", open: true },
]);
const partial = chatPageReducer(base, { type: "bulkDeleteSettled", deleted: [1, 2], allSucceeded: false });
assert.deepEqual([...partial.selection], [3]);
assert.equal(partial.selectionMode, true);
assert.equal(partial.bulkDeleteOpen, false);
const full = chatPageReducer(base, { type: "bulkDeleteSettled", deleted: [1, 2, 3], allSucceeded: true });
assert.equal(full.selectionMode, false);
assert.equal(full.selection.size, 0);
});
test("an unchanged list poll keeps the same state; a changed row is updated", () => {
const s = reduce(loaded([conv(1), conv(2)]));
assert.equal(reduce(loaded([conv(1), conv(2)]), s), s);
const renamed = reduce(loaded([conv(1), { ...conv(2), title: "renamed" }]), s);
assert.equal(renamed.list.items[1].title, "renamed");
assert.equal(renamed.list.items[0].id, 1);
});
test("an empty first load still marks the list loaded", () => {
assert.equal(reduce(loaded([])).list.loaded, true);
});

View file

@ -0,0 +1,193 @@
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
import { mergePatch, setSlice } from "@/lib/reducers/slice";
import type { Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
export const CONVERSATION_LIST_PAGE = 100;
export type ChatPageRequest = "bulkDelete";
export type PendingHandoff = { input?: string; attachments?: ChatAttachment[] };
export type ChatCatalog = {
agents: Agent[];
profiles: LLMProfile[];
};
export type ChatSidebar = {
/** null = all agents. */
agentFilter: string | null;
visibleCount: number;
/**
* Agent groups the user collapsed. Persisted to localStorage by the page and hydrated
* after mount (not in the initial state) so the server and client render the same first pass.
*/
collapsedAgents: Set<string>;
};
export type ChatRename = {
id: number | null;
text: string;
};
export type ChatPageState = {
catalog: ChatCatalog;
list: ListState<Conversation>;
sidebar: ChatSidebar;
rename: ChatRename;
selectionMode: boolean;
selection: Set<number>;
bulkDeleteOpen: boolean;
requests: Requests<ChatPageRequest>;
/**
* Handoffs keyed by the new conversation id, consumed once by ChatView on mount
* (ids never repeat, so leftover entries are harmless).
*/
pendingByConv: Record<number, PendingHandoff>;
};
export type ChatPageAction =
| ListAction<Conversation>
| SelectionAction<number>
| RequestAction<ChatPageRequest>
| { type: "catalogChanged"; patch: Partial<ChatCatalog> }
// The selected conversation lives in the URL (?c=); these keep the list in step with it.
| { type: "conversationStarted"; conversation: Conversation; pending?: PendingHandoff }
| { type: "conversationDeleted"; id: number }
// sidebar
| { type: "agentFilterChanged"; agentFilter: string | null }
| { type: "moreConversationsShown" }
| { type: "agentGroupToggled"; key: string }
| { type: "collapsedAgentsRestored"; keys: string[] }
// rename
| { type: "renameChanged"; patch: Partial<ChatRename> }
// multi-select + bulk delete
| { type: "selectionModeEntered" }
| { type: "selectionModeExited" }
| { type: "conversationCheckedChanged"; id: number; checked: boolean }
| { type: "bulkDeleteOpenChanged"; open: boolean }
| { type: "bulkDeleteSettled"; deleted: number[]; allSucceeded: boolean };
export function initChatPageState(): ChatPageState {
return {
catalog: { agents: [], profiles: [] },
list: createList(),
sidebar: { agentFilter: null, visibleCount: CONVERSATION_LIST_PAGE, collapsedAgents: new Set() },
rename: { id: null, text: "" },
selectionMode: false,
selection: new Set(),
bulkDeleteOpen: false,
requests: createRequests<ChatPageRequest>(["bulkDelete"]),
pendingByConv: {},
};
}
export function conversationIsPinned(conversation: Conversation): boolean {
return conversation.pinned ?? Boolean(conversation.pinned_at);
}
function withoutIds(selection: Set<number>, ids: Iterable<number>): Set<number> {
const next = new Set(selection);
for (const id of ids) next.delete(id);
return next.size === selection.size ? selection : next;
}
// A different agent filter starts a fresh view of the rail: first page, nothing
// checked, no open bulk-delete dialog and no rename in progress.
function changeAgentFilter(state: ChatPageState, agentFilter: string | null): ChatPageState {
return {
...state,
sidebar: { ...state.sidebar, agentFilter, visibleCount: CONVERSATION_LIST_PAGE },
selection: state.selection.size === 0 ? state.selection : new Set(),
bulkDeleteOpen: false,
rename: state.rename.id === null ? state.rename : { ...state.rename, id: null },
};
}
export function chatPageReducer(state: ChatPageState, action: ChatPageAction): ChatPageState {
if (isListAction<Conversation>(action)) {
if (action.type === "list/loaded" && JSON.stringify(action.items) === JSON.stringify(state.list.items))
return state;
return setSlice(state, "list", listReducer(state.list, action));
}
if (isSelectionAction<number>(action)) return setSlice(state, "selection", selectionReducer(state.selection, action));
if (isRequestAction<ChatPageRequest>(action)) {
return setSlice(state, "requests", requestReducer(state.requests, action));
}
switch (action.type) {
case "catalogChanged":
return setSlice(state, "catalog", mergePatch(state.catalog, action.patch));
case "conversationStarted": {
const c = action.conversation;
const next =
state.sidebar.agentFilter !== null && state.sidebar.agentFilter !== c.agent_key
? changeAgentFilter(state, null)
: state;
// Insert the new conversation right away (above the first unpinned row) so the
// pane switches to it before the next list poll reconciles titles etc.
let list = next.list;
if (!list.items.some((item) => item.id === c.id)) {
const firstUnpinned = list.items.findIndex((item) => !conversationIsPinned(item));
const insertAt = firstUnpinned < 0 ? list.items.length : firstUnpinned;
const items = [...list.items.slice(0, insertAt), c, ...list.items.slice(insertAt)];
list = { ...list, items, total: list.total + 1 };
}
return {
...next,
list,
pendingByConv: action.pending ? { ...next.pendingByConv, [c.id]: action.pending } : next.pendingByConv,
};
}
case "conversationDeleted":
return setSlice(state, "selection", withoutIds(state.selection, [action.id]));
case "agentFilterChanged":
return changeAgentFilter(state, action.agentFilter);
case "moreConversationsShown":
return {
...state,
sidebar: { ...state.sidebar, visibleCount: state.sidebar.visibleCount + CONVERSATION_LIST_PAGE },
};
case "agentGroupToggled": {
const collapsedAgents = new Set(state.sidebar.collapsedAgents);
if (!collapsedAgents.delete(action.key)) collapsedAgents.add(action.key);
return { ...state, sidebar: { ...state.sidebar, collapsedAgents } };
}
case "collapsedAgentsRestored":
return { ...state, sidebar: { ...state.sidebar, collapsedAgents: new Set(action.keys) } };
case "renameChanged":
return setSlice(state, "rename", mergePatch(state.rename, action.patch));
case "selectionModeEntered":
return state.selectionMode ? state : { ...state, selectionMode: true };
case "selectionModeExited":
return { ...state, selectionMode: false, selection: state.selection.size === 0 ? state.selection : new Set() };
case "conversationCheckedChanged":
return setSlice(
state,
"selection",
selectionReducer(state.selection, { type: "selection/changed", ids: [action.id], selected: action.checked }),
);
case "bulkDeleteOpenChanged":
if (action.open === state.bulkDeleteOpen) return state;
return { ...state, bulkDeleteOpen: action.open };
case "bulkDeleteSettled":
// Fully successful → back to the clean list; keep selection mode on if some
// failed so the user can retry the remaining ones.
return {
...state,
selection: withoutIds(state.selection, action.deleted),
bulkDeleteOpen: false,
selectionMode: action.allSucceeded ? false : state.selectionMode,
};
}
}

View file

@ -0,0 +1,54 @@
import { chatViewReducer, initChatViewState } from "./chat-view.reducer.ts";
import assert from "node:assert/strict";
import test from "node:test";
const act = (seq, kind = "text") => ({ seq, kind, ts: "" });
const reduce = (actions, state = initChatViewState(undefined)) => actions.reduce(chatViewReducer, state);
const seqs = (state) => state.transcript.messages.map((a) => a.seq);
test("latest history merges with live messages that arrived first and keeps running", () => {
const s = reduce([
{ type: "messagesPolled", items: [act(5), act(6)], running: true },
{ type: "latestHistoryLoaded", items: [act(3), act(5)], hasMore: true, running: false },
]);
assert.deepEqual(seqs(s), [3, 5, 6]);
assert.equal(s.transcript.running, true);
assert.equal(s.transcript.hasMore, true);
assert.equal(s.transcript.historyLoaded, true);
});
test("an idle poll returns the same state", () => {
const s = reduce([{ type: "transcriptChanged", patch: { running: true } }]);
assert.equal(chatViewReducer(s, { type: "messagesPolled", items: [], running: true }), s);
assert.equal(chatViewReducer(s, { type: "messagesPolled", items: [], running: false }).transcript.running, false);
});
test("older pages prepend without duplicates", () => {
const s = reduce([
{ type: "latestHistoryLoaded", items: [act(10), act(11)], hasMore: true, running: false },
{ type: "olderHistoryMerged", items: [act(8), act(10)], hasMore: false },
]);
assert.deepEqual(seqs(s), [8, 10, 11]);
assert.equal(s.transcript.hasMore, false);
assert.equal(chatViewReducer(s, { type: "olderHistoryMerged", items: [], hasMore: false }), s);
});
test("send clears the composer, a failure restores it", () => {
const att = { path: "p", name: "p", size: 1 };
const typed = reduce([
{ type: "composerChanged", patch: { input: "hello" } },
{ type: "attachmentsUploaded", attachments: [att] },
]);
const sending = chatViewReducer(typed, { type: "messageSendStarted" });
assert.deepEqual(sending.composer, { input: "", attachments: [] });
assert.equal(sending.requests.send.pending, true);
const failed = reduce(
[
{ type: "messageSendFailed", input: "hello", attachments: [att] },
{ type: "request/finished", key: "send" },
],
sending,
);
assert.deepEqual(failed.composer, { input: "hello", attachments: [att] });
assert.equal(failed.requests.send.pending, false);
});

View file

@ -0,0 +1,129 @@
import { mergeActivities } from "@/lib/activity-merge";
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { mergePatch, setSlice } from "@/lib/reducers/slice";
import type { Activity, ChatAttachment } from "@/lib/types";
export type ChatViewRequest = "send" | "stop" | "upload";
export type ChatTranscript = {
messages: Activity[];
running: boolean;
historyLoaded: boolean;
hasMore: boolean;
};
export type ChatComposer = {
input: string;
/** Already uploaded (under sessions/conv-<id>/uploads/), sent with the next message. */
attachments: ChatAttachment[];
};
export type ChatViewState = {
transcript: ChatTranscript;
composer: ChatComposer;
requests: Requests<ChatViewRequest>;
};
export type ChatViewInitial = { input?: string; attachments?: ChatAttachment[] } | undefined;
export type ChatViewAction =
| RequestAction<ChatViewRequest>
// transcript
| { type: "conversationReset" }
| { type: "latestHistoryLoaded"; items: Activity[]; hasMore: boolean; running: boolean }
| { type: "latestHistoryFailed" }
| { type: "olderHistoryMerged"; items: Activity[]; hasMore: boolean }
| { type: "messagesPolled"; items: Activity[]; running: boolean }
| { type: "transcriptChanged"; patch: Partial<ChatTranscript> }
// composer
| { type: "composerChanged"; patch: Partial<ChatComposer> }
| { type: "attachmentsUploaded"; attachments: ChatAttachment[] }
| { type: "attachmentRemoved"; path: string }
| { type: "messageSendStarted" }
| { type: "messageSendFailed"; input: string; attachments: ChatAttachment[] };
export function initChatViewState(initial: ChatViewInitial): ChatViewState {
return {
transcript: { messages: [], running: false, historyLoaded: false, hasMore: false },
composer: { input: initial?.input ?? "", attachments: initial?.attachments ?? [] },
requests: createRequests<ChatViewRequest>(["send", "stop", "upload"]),
};
}
function patchTranscript(state: ChatViewState, patch: Partial<ChatTranscript>): ChatViewState {
return { ...state, transcript: { ...state.transcript, ...patch } };
}
export function chatViewReducer(state: ChatViewState, action: ChatViewAction): ChatViewState {
if (isRequestAction<ChatViewRequest>(action)) {
return setSlice(state, "requests", requestReducer(state.requests, action));
}
switch (action.type) {
case "conversationReset": {
const { messages, running, historyLoaded, hasMore } = state.transcript;
if (!messages.length && !running && !historyLoaded && !hasMore) return state;
return patchTranscript(state, { messages: [], running: false, historyLoaded: false, hasMore: false });
}
case "latestHistoryLoaded":
// Live messages polled meanwhile win over the history page; a turn seen running stays running.
return patchTranscript(state, {
messages: mergeActivities(action.items, state.transcript.messages),
hasMore: action.hasMore,
running: state.transcript.running || action.running,
historyLoaded: true,
});
case "latestHistoryFailed":
if (state.transcript.historyLoaded) return state;
return patchTranscript(state, { historyLoaded: true });
case "olderHistoryMerged":
if (!action.items.length && action.hasMore === state.transcript.hasMore) return state;
return patchTranscript(state, {
messages: action.items.length
? mergeActivities(action.items, state.transcript.messages)
: state.transcript.messages,
hasMore: action.hasMore,
});
case "messagesPolled":
// An idle poll (nothing new, same running flag) returns the same state.
if (!action.items.length && action.running === state.transcript.running) return state;
return patchTranscript(state, {
messages: action.items.length
? mergeActivities(state.transcript.messages, action.items)
: state.transcript.messages,
running: action.running,
});
case "transcriptChanged":
return setSlice(state, "transcript", mergePatch(state.transcript, action.patch));
case "composerChanged":
return setSlice(state, "composer", mergePatch(state.composer, action.patch));
case "attachmentsUploaded":
return {
...state,
composer: { ...state.composer, attachments: [...state.composer.attachments, ...action.attachments] },
};
case "attachmentRemoved":
return {
...state,
composer: {
...state.composer,
attachments: state.composer.attachments.filter((x) => x.path !== action.path),
},
};
case "messageSendStarted":
// The composer is cleared eagerly; a failed send restores it.
return {
...state,
composer: { input: "", attachments: [] },
requests: requestReducer<ChatViewRequest>(state.requests, { type: "request/started", key: "send" }),
};
case "messageSendFailed":
return { ...state, composer: { input: action.input, attachments: action.attachments } };
}
}

View file

@ -0,0 +1,76 @@
import { type AgentFilterOption, resolveDraftAgentKey } from "@/lib/chat-agent-filter";
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { setSlice } from "@/lib/reducers/slice";
export type DraftChatRequest = "send" | "upload";
export type DraftChatForm = {
agentKey: string;
/** null = the default LLM profile. */
llmProfileId: number | null;
input: string;
};
export type DraftChatState = {
form: DraftChatForm;
/**
* `send` creates the conversation and sends the first message; `upload` creates it
* and uploads the picked files. Both stay pending on success, because the parent
* switches to the new conversation; only a failure finishes them.
*/
requests: Requests<DraftChatRequest>;
};
export type DraftChatAction =
| RequestAction<DraftChatRequest>
| { type: "agentChanged"; agentKey: string }
/** The agent list or the sidebar filter changed: keep, default or fall back the picked agent. */
| {
type: "agentDefaultsChanged";
agents: readonly AgentFilterOption[];
defaultAgentKey: string | null;
filterChanged: boolean;
}
| { type: "llmProfileChanged"; llmProfileId: number | null }
| { type: "inputChanged"; input: string };
export const initialDraftChatState: DraftChatState = {
form: { agentKey: "", llmProfileId: null, input: "" },
requests: createRequests<DraftChatRequest>(["send", "upload"]),
};
function patchForm(state: DraftChatState, patch: Partial<DraftChatForm>): DraftChatState {
const form = { ...state.form, ...patch };
return (Object.keys(patch) as (keyof DraftChatForm)[]).every((k) => form[k] === state.form[k])
? state
: { ...state, form };
}
export function draftChatReducer(state: DraftChatState, action: DraftChatAction): DraftChatState {
if (isRequestAction<DraftChatRequest>(action)) {
return setSlice(state, "requests", requestReducer(state.requests, action));
}
switch (action.type) {
case "agentChanged":
return patchForm(state, { agentKey: action.agentKey });
case "agentDefaultsChanged":
return patchForm(state, {
agentKey: resolveDraftAgentKey(
state.form.agentKey,
action.agents,
action.defaultAgentKey,
action.filterChanged,
),
});
case "llmProfileChanged":
return patchForm(state, { llmProfileId: action.llmProfileId });
case "inputChanged":
return patchForm(state, { input: action.input });
}
}

View file

@ -55,7 +55,6 @@ import { Spinner } from "@/components/ui/spinner";
import { useQueryState } from "@/hooks/use-query-state";
import { useSideQuestions } from "@/hooks/use-side-questions";
import { intlLocale, t } from "@/i18n";
import { mergeActivities } from "@/lib/activity-merge";
import { api } from "@/lib/api";
import { nextSelectedIdForAgentFilter, resolveDraftAgentKey } from "@/lib/chat-agent-filter";
import { shouldSubmitOnKey, useChatSendMode } from "@/lib/chat-send-mode";
@ -66,11 +65,14 @@ import { isBtwCommand } from "@/lib/side-questions";
import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
import { cn } from "@/lib/utils";
import { chatPageReducer, conversationIsPinned, initChatPageState } from "./_state/chat-page.reducer";
import { chatViewReducer, initChatViewState } from "./_state/chat-view.reducer";
import { draftChatReducer, initialDraftChatState } from "./_state/draft-chat.reducer";
// HISTORY_PAGE is how many steps one history page loads: the latest page on open,
// then one more page each time the user scrolls to the top. Kept modest so a long
// thread stays snappy (only ~a page of rows is in the DOM until you scroll up).
const HISTORY_PAGE = 200;
const CONVERSATION_LIST_PAGE = 100;
// Which agent groups the user has collapsed in the left rail. Persisted so the
// rail looks the same after a reload; unknown keys are harmless (a deleted agent
@ -81,10 +83,6 @@ const COLLAPSED_AGENTS_KEY = "artex.chat.collapsed-agents";
// always lands on the empty draft view. A ?c= in the URL takes precedence.
const LAST_CONVERSATION_KEY = "artex.chat.last-conversation";
function conversationIsPinned(conversation: Conversation): boolean {
return conversation.pinned ?? Boolean(conversation.pinned_at);
}
// AgentGroup is one collapsible section of the left rail: all unpinned
// conversations of a single agent, newest activity first.
interface AgentGroup {
@ -366,11 +364,13 @@ function DraftChat({
defaultAgentKey?: string | null;
onStarted: (c: Conversation, pending?: { input?: string; attachments?: ChatAttachment[] }) => void;
}) {
const [agentKey, setAgentKey] = React.useState(() => resolveDraftAgentKey("", agents, defaultAgentKey, true));
const [llmProfileId, setLlmProfileId] = React.useState<number | null>(null);
const [input, setInput] = React.useState("");
const [sending, setSending] = React.useState(false);
const [uploading, setUploading] = React.useState(false);
const [state, dispatch] = React.useReducer(draftChatReducer, null, () => ({
...initialDraftChatState,
form: { ...initialDraftChatState.form, agentKey: resolveDraftAgentKey("", agents, defaultAgentKey, true) },
}));
const { agentKey, llmProfileId, input } = state.form;
const sending = state.requests.send.pending;
const uploading = state.requests.upload.pending;
const prevDefaultAgentKey = React.useRef<string | null>(defaultAgentKey);
// Default to the active agent filter (falling back to Auto) on load and
@ -378,7 +378,7 @@ function DraftChat({
React.useEffect(() => {
const filterChanged = prevDefaultAgentKey.current !== defaultAgentKey;
prevDefaultAgentKey.current = defaultAgentKey;
setAgentKey((current) => resolveDraftAgentKey(current, agents, defaultAgentKey, filterChanged));
dispatch({ type: "agentDefaultsChanged", agents, defaultAgentKey, filterChanged });
}, [agents, defaultAgentKey]);
const agent = agents.find((a) => a.key === agentKey);
@ -386,14 +386,14 @@ function DraftChat({
async function send() {
const msg = input.trim();
if (!msg || !agentKey || sending) return;
setSending(true);
dispatch({ type: "request/started", key: "send" });
try {
const c = await api.createConversation(agentKey, "", llmProfileId);
await api.sendConversationMessage(c.id, msg);
onStarted(c);
} catch (e) {
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
setSending(false);
dispatch({ type: "request/finished", key: "send" });
}
}
@ -404,19 +404,19 @@ function DraftChat({
// the ChatGPT-style lazy-create flow.
async function pickFiles(files: File[]) {
if (files.length === 0 || !agentKey || uploading || sending) return;
setUploading(true);
dispatch({ type: "request/started", key: "upload" });
try {
const c = await api.createConversation(agentKey, "", llmProfileId);
const r = await api.chatUpload("session", `conv-${c.id}`, files);
onStarted(c, { input, attachments: r.attachments });
} catch (e) {
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
setUploading(false);
dispatch({ type: "request/finished", key: "upload" });
}
}
const agentPicker = (
<Select value={agentKey} onValueChange={setAgentKey}>
<Select value={agentKey} onValueChange={(key) => dispatch({ type: "agentChanged", agentKey: key })}>
<SelectTrigger className="w-full sm:w-40">
<SelectValue placeholder={t("Select an agent…")} />
</SelectTrigger>
@ -455,7 +455,7 @@ function DraftChat({
<Composer
value={input}
onChange={setInput}
onChange={(value) => dispatch({ type: "inputChanged", input: value })}
onSend={send}
disabled={sending || uploading || !agentKey}
placeholder={t("Type a message, @ to reference records, Enter to send")}
@ -466,7 +466,7 @@ function DraftChat({
<LLMProfileRow
profiles={profiles}
selected={llmProfileId}
onChange={setLlmProfileId}
onChange={(id) => dispatch({ type: "llmProfileChanged", llmProfileId: id })}
disabled={sending || uploading}
/>
</>
@ -493,21 +493,18 @@ function ChatView({
onTitleMaybeChanged: () => void;
onConvUpdated: () => void;
}) {
const approvalFocus = useApprovalFocus({ conversationId: conv.id });
const [messages, setMessages] = React.useState<Activity[]>([]);
const [running, setRunning] = React.useState(false);
const [input, setInput] = React.useState(initial?.input ?? "");
const [sending, setSending] = React.useState(false);
const [stopping, setStopping] = React.useState(false);
const approvalFocus: ReturnType<typeof useApprovalFocus> = useApprovalFocus({ conversationId: conv.id });
// Upload method 1: already-uploaded attachments (stored under sessions/conv-<id>/uploads/) are sent with the next message.
const [attachments, setAttachments] = React.useState<ChatAttachment[]>(initial?.attachments ?? []);
const [uploading, setUploading] = React.useState(false);
const [state, dispatch] = React.useReducer(chatViewReducer, initial, initChatViewState);
const { messages, running, historyLoaded, hasMore } = state.transcript;
const { input, attachments } = state.composer;
const sending = state.requests.send.pending;
const stopping = state.requests.stop.pending;
const uploading = state.requests.upload.pending;
const cursorRef = React.useRef(0); // newest loaded id — incremental-tail anchor
const earliestRef = React.useRef(0); // earliest loaded id — reverse-pagination anchor
const hasMoreRef = React.useRef(false); // older history remains above the loaded window
const loadingMoreRef = React.useRef(false); // guard: one scroll-up load at a time
const [historyLoaded, setHistoryLoaded] = React.useState(false);
const [hasMore, setHasMore] = React.useState(false); // drives the "load earlier" hint
const agent = agents.find((a) => a.key === conv.agent_key);
const currentProfileId = conv.llm_profile_id ?? null;
const side = useSideQuestions(`/api/conversations/${conv.id}`);
@ -542,27 +539,21 @@ function ChatView({
cursorRef.current = 0;
earliestRef.current = 0;
hasMoreRef.current = false;
setHasMore(false);
setMessages([]);
setHistoryLoaded(false);
setRunning(false);
dispatch({ type: "conversationReset" });
let live = true;
api
.conversationHistory(conv.id, 0, HISTORY_PAGE)
.then((r) => {
if (!live) return;
setMessages((current) => mergeActivities(r.items, current));
dispatch({ type: "latestHistoryLoaded", items: r.items, hasMore: r.hasMore, running: r.running });
cursorRef.current = Math.max(cursorRef.current, r.cursor);
earliestRef.current = r.items.length ? r.items[0].seq : 0;
hasMoreRef.current = r.hasMore;
setHasMore(r.hasMore);
setRunning((current) => current || r.running);
setHistoryLoaded(true);
})
.catch(() => {
// A source link can retry history through its locator; ordinary chats
// retain the existing usable empty state on a transient failure.
if (live) setHistoryLoaded(true);
if (live) dispatch({ type: "latestHistoryFailed" });
});
return () => {
live = false;
@ -572,7 +563,7 @@ function ChatView({
// A trigger or another tab may start a turn while this conversation is open.
// A false list snapshot must not stop the tail before its final messages load.
React.useEffect(() => {
if (conv.running) setRunning(true);
if (conv.running) dispatch({ type: "transcriptChanged", patch: { running: true } });
}, [conv.running]);
// poll while a turn is running: pull new steps after the cursor.
@ -585,12 +576,9 @@ function ChatView({
try {
const r = await api.conversationMessages(conv.id, cursorRef.current);
if (!live) return;
if (r.items.length) {
setMessages((prev) => mergeActivities(prev, r.items));
}
dispatch({ type: "messagesPolled", items: r.items, running: r.running });
cursorRef.current = Math.max(cursorRef.current, r.cursor);
keepPolling = r.running;
setRunning(r.running);
if (!r.running) onTitleMaybeChanged(); // first-turn auto-title landed
} catch {
/* transient — keep polling */
@ -611,12 +599,11 @@ function ChatView({
[conv.id],
);
const mergeFocusPage = React.useCallback((page: { items: Activity[]; hasMore: boolean }) => {
setMessages((prev) => mergeActivities(page.items, prev));
dispatch({ type: "olderHistoryMerged", items: page.items, hasMore: page.hasMore });
earliestRef.current = page.items[0]?.seq ?? earliestRef.current;
hasMoreRef.current = page.hasMore;
setHasMore(page.hasMore);
}, []);
const focusHistory = useApprovalHistory(
const focusHistory: ReturnType<typeof useApprovalHistory> = useApprovalHistory(
approvalFocus.state?.source,
historyLoaded,
messages,
@ -642,12 +629,9 @@ function ChatView({
const prevTop = vp.scrollTop;
try {
const r = await api.conversationHistory(conv.id, earliestRef.current, HISTORY_PAGE);
if (r.items.length) {
setMessages((prev) => mergeActivities(r.items, prev));
earliestRef.current = r.items[0].seq;
}
dispatch({ type: "olderHistoryMerged", items: r.items, hasMore: r.hasMore });
if (r.items.length) earliestRef.current = r.items[0].seq;
hasMoreRef.current = r.hasMore;
setHasMore(r.hasMore);
requestAnimationFrame(() => {
const v = viewport();
if (v) v.scrollTop = prevTop + (v.scrollHeight - prevH);
@ -719,36 +703,34 @@ function ChatView({
// uploads/) and queues the returned metadata to send with the next message.
async function pickFiles(files: File[]) {
if (files.length === 0) return;
setUploading(true);
dispatch({ type: "request/started", key: "upload" });
try {
const r = await api.chatUpload("session", `conv-${conv.id}`, files);
setAttachments((prev) => [...prev, ...r.attachments]);
dispatch({ type: "attachmentsUploaded", attachments: r.attachments });
} catch (e) {
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
} finally {
setUploading(false);
dispatch({ type: "request/finished", key: "upload" });
}
}
async function send() {
const msg = input.trim();
const atts = attachments;
if (side.handleCommand(msg, () => setInput(""))) return;
if (side.handleCommand(msg, () => dispatch({ type: "composerChanged", patch: { input: "" } }))) return;
if ((!msg && atts.length === 0) || sending || running) return;
setSending(true);
setInput("");
setAttachments([]);
dispatch({ type: "messageSendStarted" });
try {
await api.sendConversationMessage(conv.id, msg, atts.length ? atts : undefined);
// The live loop pulls the persisted human turn immediately. Sharing that
// fetch avoids racing a separate post-send request against the poller.
setRunning(true);
dispatch({ type: "transcriptChanged", patch: { running: true } });
} catch (e) {
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
setInput(msg); // restore so the user doesn't lose their text
setAttachments(atts); // and their attachments
// restore so the user doesn't lose their text and attachments
dispatch({ type: "messageSendFailed", input: msg, attachments: atts });
} finally {
setSending(false);
dispatch({ type: "request/finished", key: "send" });
}
}
@ -757,13 +739,13 @@ function ChatView({
// affected — the agent's next queued fire still starts.
async function stop() {
if (stopping) return;
setStopping(true);
dispatch({ type: "request/started", key: "stop" });
try {
await api.stopConversation(conv.id);
} catch (e) {
toast.error(t("Stop failed: {error}", { error: (e as Error).message }));
} finally {
setStopping(false);
dispatch({ type: "request/finished", key: "stop" });
}
}
@ -832,7 +814,7 @@ function ChatView({
<Composer
value={input}
onChange={setInput}
onChange={(value) => dispatch({ type: "composerChanged", patch: { input: value } })}
onSend={send}
disabled={running || sending}
allowBtw
@ -846,7 +828,7 @@ function ChatView({
stopDisabled={stopping}
attachments={attachments}
onPickFiles={pickFiles}
onRemoveAttachment={(path) => setAttachments((p) => p.filter((x) => x.path !== path))}
onRemoveAttachment={(path) => dispatch({ type: "attachmentRemoved", path })}
uploading={uploading}
/>
<LLMProfileRow
@ -1075,10 +1057,9 @@ function AgentGroupHeader({
}
export default function ChatPage() {
const [agents, setAgents] = React.useState<Agent[]>([]);
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [convs, setConvs] = React.useState<Conversation[]>([]);
const [agentFilter, setAgentFilter] = React.useState<string | null>(null);
const [state, dispatch] = React.useReducer(chatPageReducer, undefined, initChatPageState);
const { agents, profiles } = state.catalog;
const { items: convs, loaded: convsLoaded } = state.list;
const [conversationID] = useQueryState("c", "");
const selectedId = /^[1-9]\d*$/.test(conversationID) ? Number(conversationID) : null;
const setSelectedId = React.useCallback((next: React.SetStateAction<number | null>) => {
@ -1089,7 +1070,13 @@ export default function ChatPage() {
}, []);
const [approvalID] = useQueryState("approval", "");
const sourceRequested = Boolean(approvalID);
const [convsLoaded, setConvsLoaded] = React.useState(false);
const { agentFilter, visibleCount: visibleConversationCount, collapsedAgents } = state.sidebar;
const { id: renamingId, text: renameText } = state.rename;
// selectionMode gates the multi-select UI: off by default (clean list, no
// checkboxes); the header "Select" button turns it on, "Done" turns it off and
// clears the selection.
const { selectionMode, selection: selectedConversationIds, bulkDeleteOpen, pendingByConv } = state;
const bulkDeleting = state.requests.bulkDelete.pending;
const selectConversation = React.useCallback(
(id: number | null) => {
setSelectedId(id);
@ -1097,34 +1084,14 @@ export default function ChatPage() {
[setSelectedId],
);
const [renamingId, setRenamingId] = React.useState<number | null>(null);
const [renameText, setRenameText] = React.useState("");
const [selectedConversationIds, setSelectedConversationIds] = React.useState<Set<number>>(() => new Set());
// selectionMode gates the multi-select UI: off by default (clean list, no
// checkboxes); the header "Select" button turns it on, "Done" turns it off and
// clears the selection.
const [selectionMode, setSelectionMode] = React.useState(false);
const [bulkDeleteOpen, setBulkDeleteOpen] = React.useState(false);
const [bulkDeleting, setBulkDeleting] = React.useState(false);
const [visibleConversationCount, setVisibleConversationCount] = React.useState(CONVERSATION_LIST_PAGE);
// Collapsed agent groups. Hydrated from localStorage after mount (not a lazy
// useState init) so the server and client render the same first pass.
const [collapsedAgents, setCollapsedAgents] = React.useState<Set<string>>(() => new Set());
// Pending text + uploaded attachments handed off from a draft that created a
// conversation via the paperclip, keyed by the new conversation id (consumed once
// by ChatView on mount; ids never repeat, so leftover entries are harmless).
const [pendingByConv, setPendingByConv] = React.useState<
Record<number, { input?: string; attachments?: ChatAttachment[] }>
>({});
const conversationListSeq = React.useRef(0);
const reloadConvs = React.useCallback(async () => {
const seq = ++conversationListSeq.current;
try {
const items = await api.conversations();
if (seq === conversationListSeq.current) {
setConvs(items);
setConvsLoaded(true);
dispatch({ type: "list/loaded", items });
dispatch({ type: "list/loadFinished" });
}
} catch {
// Preserve the selected transcript and list on a transient poll failure.
@ -1133,13 +1100,13 @@ export default function ChatPage() {
React.useEffect(() => {
api
.agents()
.then(setAgents)
.then((items) => dispatch({ type: "catalogChanged", patch: { agents: items } }))
.catch(() => {
/* Agent metadata is optional for rendering an existing conversation. */
});
api
.llmProfiles()
.then(setProfiles)
.then((items) => dispatch({ type: "catalogChanged", patch: { profiles: items } }))
.catch(() => {
/* The conversation remains usable without profile labels. */
});
@ -1163,12 +1130,7 @@ export default function ChatPage() {
}, [reloadConvs]);
React.useEffect(() => {
setSelectedConversationIds((current) => {
if (current.size === 0) return current;
const live = new Set(convs.map((conversation) => conversation.id));
const next = new Set([...current].filter((id) => live.has(id)));
return next.size === current.size ? current : next;
});
dispatch({ type: "selection/pruned", keep: convs.map((conversation) => conversation.id) });
}, [convs]);
React.useEffect(() => {
@ -1177,20 +1139,26 @@ export default function ChatPage() {
try {
const keys = JSON.parse(raw);
if (Array.isArray(keys))
setCollapsedAgents(new Set(keys.filter((key): key is string => typeof key === "string")));
dispatch({
type: "collapsedAgentsRestored",
keys: keys.filter((key): key is string => typeof key === "string"),
});
} catch {
// Corrupted entry → start with everything expanded.
}
}, []);
// Persist only after the user toggles a group, so hydration never writes back.
const collapsedAgentsTouched = React.useRef(false);
const toggleAgentCollapsed = React.useCallback((key: string) => {
setCollapsedAgents((current) => {
const next = new Set(current);
if (!next.delete(key)) next.add(key);
setLocalStorageValue(COLLAPSED_AGENTS_KEY, JSON.stringify([...next]));
return next;
});
collapsedAgentsTouched.current = true;
dispatch({ type: "agentGroupToggled", key });
}, []);
React.useEffect(() => {
if (collapsedAgentsTouched.current) {
setLocalStorageValue(COLLAPSED_AGENTS_KEY, JSON.stringify([...collapsedAgents]));
}
}, [collapsedAgents]);
React.useEffect(() => {
const params = new URLSearchParams(window.location.search);
@ -1250,14 +1218,10 @@ export default function ChatPage() {
: `${filteredConversations.length} / ${convs.length}`;
function changeAgentFilter(key: string | null) {
setAgentFilter(key);
dispatch({ type: "agentFilterChanged", agentFilter: key });
if (selectedId !== null && nextSelectedIdForAgentFilter(selectedId, convs, key) === null) {
selectConversation(null);
}
setVisibleConversationCount(CONVERSATION_LIST_PAGE);
setSelectedConversationIds(new Set());
setBulkDeleteOpen(false);
setRenamingId(null);
}
const selectedConversationCount = selectedConversationIds.size;
@ -1269,23 +1233,16 @@ export default function ChatPage() {
else if (someConversationsSelected) conversationHeaderChecked = "indeterminate";
const toggleConversationSelected = React.useCallback((id: number, checked: boolean) => {
setSelectedConversationIds((current) => {
const next = new Set(current);
if (checked) next.add(id);
else next.delete(id);
return next;
});
dispatch({ type: "conversationCheckedChanged", id, checked });
}, []);
function toggleAllConversations(checked: boolean) {
setSelectedConversationIds(
checked ? new Set(filteredConversations.map((conversation) => conversation.id)) : new Set(),
);
if (checked) dispatch({ type: "selection/set", ids: filteredConversations.map((conversation) => conversation.id) });
else dispatch({ type: "selection/cleared" });
}
function exitSelectionMode() {
setSelectionMode(false);
setSelectedConversationIds(new Set());
dispatch({ type: "selectionModeExited" });
}
const del = React.useCallback(
@ -1293,12 +1250,7 @@ export default function ChatPage() {
try {
await api.deleteConversation(id);
setSelectedId((current) => (current === id ? null : current));
setSelectedConversationIds((current) => {
if (!current.has(id)) return current;
const next = new Set(current);
next.delete(id);
return next;
});
dispatch({ type: "conversationDeleted", id });
void reloadConvs();
} catch (e) {
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
@ -1310,7 +1262,7 @@ export default function ChatPage() {
async function deleteSelectedConversations() {
const ids = [...selectedConversationIds];
if (ids.length === 0 || bulkDeleting) return;
setBulkDeleting(true);
dispatch({ type: "request/started", key: "bulkDelete" });
const deleted = new Set<number>();
const failed: { id: number; error: string }[] = [];
try {
@ -1322,11 +1274,6 @@ export default function ChatPage() {
}
}
if (deleted.has(selectedId ?? -1)) selectConversation(null);
setSelectedConversationIds((current) => {
const next = new Set(current);
for (const id of deleted) next.delete(id);
return next;
});
if (deleted.size > 0) toast.success(t("Deleted {count} conversations", { count: deleted.size }));
if (failed.length > 0) {
const details = failed
@ -1340,16 +1287,15 @@ export default function ChatPage() {
}),
);
}
setBulkDeleteOpen(false);
// Fully successful → return to the clean list; keep selection mode on if
// some failed so the user can retry the remaining ones.
if (failed.length === 0) setSelectionMode(false);
dispatch({ type: "bulkDeleteSettled", deleted: [...deleted], allSucceeded: failed.length === 0 });
void reloadConvs();
} catch (error) {
toast.error(t("Bulk delete failed: {error}", { error: (error as Error).message }));
void reloadConvs();
} finally {
setBulkDeleting(false);
dispatch({ type: "request/finished", key: "bulkDelete" });
}
}
@ -1368,13 +1314,13 @@ export default function ChatPage() {
);
const startRename = React.useCallback((c: Conversation) => {
setRenamingId(c.id);
setRenameText(c.title || "");
dispatch({ type: "renameChanged", patch: { id: c.id, text: c.title || "" } });
}, []);
const setRenameText = React.useCallback((text: string) => dispatch({ type: "renameChanged", patch: { text } }), []);
const commitRename = React.useCallback(
async (id: number, value: string) => {
const title = value.trim();
setRenamingId(null);
dispatch({ type: "renameChanged", patch: { id: null } });
if (!title) return;
try {
await api.renameConversation(id, title);
@ -1385,7 +1331,7 @@ export default function ChatPage() {
},
[reloadConvs],
);
const cancelRename = React.useCallback(() => setRenamingId(null), []);
const cancelRename = React.useCallback(() => dispatch({ type: "renameChanged", patch: { id: null } }), []);
return (
<div
@ -1438,7 +1384,7 @@ export default function ChatPage() {
size="sm"
variant="destructive"
disabled={bulkDeleting}
onClick={() => setBulkDeleteOpen(true)}
onClick={() => dispatch({ type: "bulkDeleteOpenChanged", open: true })}
>
<Trash2Icon data-icon="inline-start" />
{t("Delete")}
@ -1457,7 +1403,7 @@ export default function ChatPage() {
size="sm"
variant="ghost"
className="text-muted-foreground"
onClick={() => setSelectionMode(true)}
onClick={() => dispatch({ type: "selectionModeEntered" })}
disabled={filteredConversations.length === 0}
>
<ListChecksIcon data-icon="inline-start" />
@ -1538,7 +1484,7 @@ export default function ChatPage() {
variant="ghost"
size="sm"
className="mt-1 w-full"
onClick={() => setVisibleConversationCount((count) => count + CONVERSATION_LIST_PAGE)}
onClick={() => dispatch({ type: "moreConversationsShown" })}
>
{t("Load more")}
</Button>
@ -1569,17 +1515,10 @@ export default function ChatPage() {
profiles={profiles}
defaultAgentKey={agentFilter}
onStarted={(c, pending) => {
if (agentFilter !== null && agentFilter !== c.agent_key) changeAgentFilter(null);
// Insert the new conversation immediately so `selected` resolves to
// it on this render (switching to ChatView right away, before the
// async reloadConvs lands); reloadConvs then reconciles titles etc.
if (pending) setPendingByConv((p) => ({ ...p, [c.id]: pending }));
setConvs((prev) => {
if (prev.some((item) => item.id === c.id)) return prev;
const firstUnpinned = prev.findIndex((item) => !conversationIsPinned(item));
const insertAt = firstUnpinned < 0 ? prev.length : firstUnpinned;
return [...prev.slice(0, insertAt), c, ...prev.slice(insertAt)];
});
dispatch({ type: "conversationStarted", conversation: c, pending });
setSelectedId(c.id);
void reloadConvs();
}}
@ -1587,7 +1526,7 @@ export default function ChatPage() {
)}
</div>
</div>
<AlertDialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
<AlertDialog open={bulkDeleteOpen} onOpenChange={(open) => dispatch({ type: "bulkDeleteOpenChanged", open })}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>

View file

@ -0,0 +1,25 @@
import { dashboardPageReducer, initialDashboardPageState } from "./dashboard-page.reducer.ts";
import assert from "node:assert/strict";
import test from "node:test";
const live = { ...initialDashboardPageState.live, findings: [{ id: 1, severity: "high" }], pending: [{ id: 9 }] };
const system = { ...initialDashboardPageState.system, assetCounts: { domain: 3 } };
test("unchanged live and system polls keep the same state", () => {
const s = [
{ type: "liveLoaded", live },
{ type: "systemLoaded", system },
].reduce(dashboardPageReducer, initialDashboardPageState);
const again = [
{ type: "liveLoaded", live: structuredClone(live) },
{ type: "systemLoaded", system: structuredClone(system) },
].reduce(dashboardPageReducer, s);
assert.equal(again, s);
});
test("a poll that changes one nested field updates it", () => {
const s = dashboardPageReducer(initialDashboardPageState, { type: "liveLoaded", live });
const next = structuredClone(live);
next.findings[0].severity = "low";
assert.equal(dashboardPageReducer(s, { type: "liveLoaded", live: next }).live.findings[0].severity, "low");
});

View file

@ -0,0 +1,106 @@
import { mergePatch, setSlice } from "@/lib/reducers/slice";
import type {
Activity,
Agent,
ConvTokenSummary,
Finding,
InterceptPending,
LLMProfile,
MCPServer,
Settings,
SkillItem,
Stats,
Task,
TokenTotal,
Tool,
TrafficExchange,
UsageStats,
} from "@/lib/types";
export type TokenVersion = "old" | "new";
/** "all" = every profile; a number (or null for the default bucket) = one profile. */
export type TokenTab = number | null | "all";
export type TokenDays = 7 | 30 | 90 | 180 | 365;
/** Fast-poll sources (every 5s), fetched together and applied in one dispatch. */
export type DashboardLive = {
findings: Finding[];
stats: Stats | null;
settings: Settings | null;
pending: InterceptPending[];
activity: Activity[];
tokens: TokenTotal | null;
convTokens: ConvTokenSummary[];
};
/** Slow-poll sources (every 15s): traffic, assets and mostly static system config. */
export type DashboardSystem = {
traffic: TrafficExchange[];
assetCounts: Record<string, number>;
agents: Agent[];
mcpServers: MCPServer[];
skills: SkillItem[];
tools: Tool[];
llmProfiles: LLMProfile[];
usageStats: UsageStats | null;
};
export type TokenView = {
/** Data source: old = activity (task.tokens + conversations), new = the llm_usage metering ledger. */
version: TokenVersion;
tab: TokenTab;
days: TokenDays;
};
export type DashboardPageState = {
/** Polled on its own: the task list is the most expensive source. */
tasks: Task[];
live: DashboardLive;
system: DashboardSystem;
tokenView: TokenView;
};
export type DashboardPageAction =
| { type: "tasksLoaded"; tasks: Task[] }
| { type: "liveLoaded"; live: DashboardLive }
| { type: "systemLoaded"; system: DashboardSystem }
| { type: "tokenViewChanged"; patch: Partial<TokenView> };
export const initialDashboardPageState: DashboardPageState = {
tasks: [],
live: {
findings: [],
stats: null,
settings: null,
pending: [],
activity: [],
tokens: null,
convTokens: [],
},
system: {
traffic: [],
assetCounts: {},
agents: [],
mcpServers: [],
skills: [],
tools: [],
llmProfiles: [],
usageStats: null,
},
tokenView: { version: "old", tab: "all", days: 30 },
};
export function dashboardPageReducer(state: DashboardPageState, action: DashboardPageAction): DashboardPageState {
switch (action.type) {
case "tasksLoaded":
return action.tasks === state.tasks ? state : { ...state, tasks: action.tasks };
case "liveLoaded":
return JSON.stringify(action.live) === JSON.stringify(state.live) ? state : { ...state, live: action.live };
case "systemLoaded":
return JSON.stringify(action.system) === JSON.stringify(state.system)
? state
: { ...state, system: action.system };
case "tokenViewChanged":
return setSlice(state, "tokenView", mergePatch(state.tokenView, action.patch));
}
}

View file

@ -25,26 +25,12 @@ import { t } from "@/i18n";
import { api } from "@/lib/api";
import { formatTokens } from "@/lib/format";
import { setVisibleInterval } from "@/lib/polling";
import type {
Activity,
Agent,
ConvTokenSummary,
Finding,
InterceptPending,
LLMProfile,
MCPServer,
Settings,
SkillItem,
Stats,
Task,
TokenTotal,
Tool,
TrafficExchange,
UsageStats,
} from "@/lib/types";
import type { Activity } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useActiveCompany } from "@/stores/company/company-store";
import { dashboardPageReducer, initialDashboardPageState } from "./_state/dashboard-page.reducer";
// ── chart constants ───────────────────────────────────────────────────────────
const dailyTrendConfig = {
@ -131,23 +117,11 @@ export default function DashboardPage() {
// The sidebar's company switcher narrows the finding-derived panels to that
// company (server-side `company` filter). Undefined means all companies.
const company = useActiveCompany();
// data state
const [tasks, setTasks] = React.useState<Task[]>([]);
const [findings, setFindings] = React.useState<Finding[]>([]);
const [stats, setStats] = React.useState<Stats | null>(null);
const [settings, setSettings] = React.useState<Settings | null>(null);
const [pending, setPending] = React.useState<InterceptPending[]>([]);
const [activity, setActivity] = React.useState<Activity[]>([]);
const [tokens, setTokens] = React.useState<TokenTotal | null>(null);
const [convTokens, setConvTokens] = React.useState<ConvTokenSummary[]>([]);
const [usageStats, setUsageStats] = React.useState<UsageStats | null>(null);
const [assetCounts, setAssetCounts] = React.useState<Record<string, number>>({});
const [traffic, setTraffic] = React.useState<TrafficExchange[]>([]);
const [agents, setAgents] = React.useState<Agent[]>([]);
const [mcpServers, setMcpServers] = React.useState<MCPServer[]>([]);
const [skills, setSkills] = React.useState<SkillItem[]>([]);
const [tools, setTools] = React.useState<Tool[]>([]);
const [llmProfiles, setLLMProfiles] = React.useState<LLMProfile[]>([]);
const [state, dispatch] = React.useReducer(dashboardPageReducer, initialDashboardPageState);
const { tasks, live, system, tokenView } = state;
const { findings, stats, settings, pending, activity, convTokens } = live;
const { traffic, assetCounts, tools, llmProfiles, usageStats } = system;
const { version: tokenVersion, tab: tokenTab, days: tokenDays } = tokenView;
// The task list is the most expensive dashboard source. Poll it independently
// so a large history cannot hold back every other dashboard panel.
@ -164,7 +138,7 @@ export default function DashboardPage() {
const nextSignature = JSON.stringify(tr.tasks);
if (nextSignature !== signature) {
signature = nextSignature;
setTasks(tr.tasks);
dispatch({ type: "tasksLoaded", tasks: tr.tasks });
}
} catch {
/* transient errors — next poll retries */
@ -198,13 +172,18 @@ export default function DashboardPage() {
api.conversationTokens(),
]);
if (!alive) return;
setFindings(findings);
setStats(stats);
setSettings(settings);
setPending(pending);
setActivity(activity.items);
setTokens(tokens.total ?? null);
setConvTokens(conversationTokens);
dispatch({
type: "liveLoaded",
live: {
findings,
stats,
settings,
pending,
activity: activity.items,
tokens: tokens.total ?? null,
convTokens: conversationTokens,
},
});
} catch {
// Preserve stale data and retry on the next interval.
} finally {
@ -235,14 +214,19 @@ export default function DashboardPage() {
api.usageStats(365),
]);
if (!alive) return;
setTraffic(traf.exchanges ?? []);
setAssetCounts(counts ?? {});
setAgents(agentList);
setMcpServers(mcpList);
setSkills(skillList);
setTools(toolList);
setLLMProfiles(profileList);
setUsageStats(usage);
dispatch({
type: "systemLoaded",
system: {
traffic: traf.exchanges ?? [],
assetCounts: counts ?? {},
agents: agentList,
mcpServers: mcpList,
skills: skillList,
tools: toolList,
llmProfiles: profileList,
usageStats: usage,
},
});
} catch {
/* transient errors */
}
@ -329,13 +313,6 @@ export default function DashboardPage() {
// tasks whose llm_profile_id is null/undefined used the active default profile
const defaultProfileId = activeProfile ? Number(activeProfile.id) : null;
// Data source toggle: old = activity (task.tokens + conversations), new = the llm_usage metering ledger.
const [tokenVersion, setTokenVersion] = React.useState<"old" | "new">("old");
// selected profile tab: "all" = all; number = specific profile id
const [tokenTab, setTokenTab] = React.useState<number | null | "all">("all");
// day range for the daily bar chart
const [tokenDays, setTokenDays] = React.useState<7 | 30 | 90 | 180 | 365>(30);
// profile name → id, mapping llm_usage profile_name to the existing profile tabs.
const profileIdByName = React.useMemo(() => {
const m = new Map<string, number>();
@ -616,7 +593,7 @@ export default function DashboardPage() {
<button
type="button"
key={v}
onClick={() => setTokenVersion(v)}
onClick={() => dispatch({ type: "tokenViewChanged", patch: { version: v } })}
title={
v === "new"
? t(
@ -645,7 +622,7 @@ export default function DashboardPage() {
<div className="flex flex-wrap items-center gap-1">
<button
type="button"
onClick={() => setTokenTab("all")}
onClick={() => dispatch({ type: "tokenViewChanged", patch: { tab: "all" } })}
className={cn(
"rounded-md px-2.5 py-1 text-[10px] font-medium transition-colors",
tokenTab === "all"
@ -663,7 +640,7 @@ export default function DashboardPage() {
<button
type="button"
key={p.id}
onClick={() => setTokenTab(resolvedKey)}
onClick={() => dispatch({ type: "tokenViewChanged", patch: { tab: resolvedKey } })}
className={cn(
"flex items-center gap-1 rounded-md px-2.5 py-1 text-[10px] font-medium transition-colors",
tokenTab === resolvedKey
@ -795,7 +772,7 @@ export default function DashboardPage() {
<button
type="button"
key={days}
onClick={() => setTokenDays(days)}
onClick={() => dispatch({ type: "tokenViewChanged", patch: { days } })}
className={cn(
"rounded px-2.5 py-0.5 text-[9px] font-medium transition-colors",
tokenDays === days

View file

@ -0,0 +1,59 @@
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { mergePatch, setSlice } from "@/lib/reducers/slice";
import type { SharedBrowserStatus } from "@/lib/types";
/** The address bar: what is typed, and whether the operator is typing (so tab changes don't overwrite it). */
export type AddressBar = {
value: string;
editing: boolean;
};
export type SharedBrowserPageState = {
status: SharedBrowserStatus;
frame: string;
connected: boolean;
address: AddressBar;
/** `control` covers start/stop/navigation actions; load and input errors land on it too. */
requests: Requests<"control">;
};
export type SharedBrowserPageAction =
| RequestAction<"control">
| { type: "statusChanged"; status: SharedBrowserStatus }
| { type: "frameReceived"; frame: string }
| { type: "connectionChanged"; connected: boolean }
| { type: "addressChanged"; patch: Partial<AddressBar> };
/** The empty status comes from the page, which owns its defaults. */
export function initSharedBrowserPageState(status: SharedBrowserStatus): SharedBrowserPageState {
return {
status,
frame: "",
connected: false,
address: { value: "", editing: false },
requests: createRequests(["control"]),
};
}
export function sharedBrowserPageReducer(
state: SharedBrowserPageState,
action: SharedBrowserPageAction,
): SharedBrowserPageState {
if (isRequestAction<"control">(action)) return setSlice(state, "requests", requestReducer(state.requests, action));
switch (action.type) {
case "statusChanged":
return { ...state, status: action.status };
case "frameReceived":
return { ...state, frame: action.frame };
case "connectionChanged":
return action.connected === state.connected ? state : { ...state, connected: action.connected };
case "addressChanged":
return setSlice(state, "address", mergePatch(state.address, action.patch));
}
}

View file

@ -27,6 +27,8 @@ import { MOCK } from "@/lib/mock/enabled";
import type { SharedBrowserAction, SharedBrowserInput, SharedBrowserStatus } from "@/lib/types";
import { cn } from "@/lib/utils";
import { initSharedBrowserPageState, sharedBrowserPageReducer } from "./_state/shared-browser-page.reducer";
// The shared browser: the same Chromium the agents drive through the browser MCP.
// The page shows its viewed tab live (CDP screencast frames over SSE). Take over to
// solve a CAPTCHA, enter an OTP or sign in; the agent's browser tools wait while
@ -65,13 +67,10 @@ function tabLabel(tab: { title: string; url: string }): string {
}
export default function SharedBrowserPage() {
const [status, setStatus] = React.useState<SharedBrowserStatus>(EMPTY);
const [frame, setFrame] = React.useState<string>("");
const [address, setAddress] = React.useState("");
const [editingAddress, setEditingAddress] = React.useState(false);
const [busy, setBusy] = React.useState(false);
const [error, setError] = React.useState("");
const [connected, setConnected] = React.useState(false);
const [state, dispatch] = React.useReducer(sharedBrowserPageReducer, EMPTY, initSharedBrowserPageState);
const { status, frame, connected } = state;
const { value: address, editing: editingAddress } = state.address;
const { pending: busy, error } = state.requests.control;
const viewRef = React.useRef<HTMLDivElement>(null);
const imgRef = React.useRef<HTMLImageElement>(null);
@ -86,7 +85,7 @@ export default function SharedBrowserPage() {
// Keep the address bar on the viewed tab's URL unless the operator is typing.
React.useEffect(() => {
if (!editingAddress) setAddress(viewedTab?.url ?? "");
if (!editingAddress) dispatch({ type: "addressChanged", patch: { value: viewedTab?.url ?? "" } });
}, [viewedTab?.url, editingAddress]);
// Live view: status and frame events.
@ -96,15 +95,16 @@ export default function SharedBrowserPage() {
let closed = false;
const open = () => {
es = openSSE("/api/browser/stream");
es.onopen = () => setConnected(true);
es.onerror = () => setConnected(false); // The stream reconnects by itself.
es.onopen = () => dispatch({ type: "connectionChanged", connected: true });
es.onerror = () => dispatch({ type: "connectionChanged", connected: false }); // The stream reconnects by itself.
es.onmessage = (e) => {
try {
const ev = JSON.parse(e.data) as
| { type: "status"; status: SharedBrowserStatus }
| { type: "frame"; data: string };
if (ev.type === "status") setStatus({ ...ev.status, tabs: ev.status.tabs ?? [] });
else if (ev.type === "frame") setFrame(ev.data);
if (ev.type === "status")
dispatch({ type: "statusChanged", status: { ...ev.status, tabs: ev.status.tabs ?? [] } });
else if (ev.type === "frame") dispatch({ type: "frameReceived", frame: ev.data });
} catch {
/* ignore a malformed event */
}
@ -115,10 +115,12 @@ export default function SharedBrowserPage() {
.browserStatus()
.then((s) => {
if (closed) return;
setStatus(s);
dispatch({ type: "statusChanged", status: s });
if (s.enabled) open();
})
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
.catch((e: unknown) =>
dispatch({ type: "request/failed", key: "control", error: e instanceof Error ? e.message : String(e) }),
);
return () => {
closed = true;
es?.close();
@ -126,15 +128,14 @@ export default function SharedBrowserPage() {
}, []);
const run = React.useCallback(async (fn: () => Promise<SharedBrowserStatus | undefined>) => {
setBusy(true);
setError("");
dispatch({ type: "request/started", key: "control" });
try {
const s = await fn();
if (s) setStatus({ ...s, tabs: s.tabs ?? [] });
if (s) dispatch({ type: "statusChanged", status: { ...s, tabs: s.tabs ?? [] } });
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
dispatch({ type: "request/failed", key: "control", error: e instanceof Error ? e.message : String(e) });
} finally {
setBusy(false);
dispatch({ type: "request/finished", key: "control" });
}
}, []);
@ -149,7 +150,11 @@ export default function SharedBrowserPage() {
const events = queue.current;
queue.current = [];
if (!events.length) return;
api.browserInput(events).catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
api
.browserInput(events)
.catch((e: unknown) =>
dispatch({ type: "request/failed", key: "control", error: e instanceof Error ? e.message : String(e) }),
);
}, []);
const send = React.useCallback(
(ev: SharedBrowserInput) => {
@ -233,7 +238,7 @@ export default function SharedBrowserPage() {
const submitAddress = (e: React.FormEvent) => {
e.preventDefault();
setEditingAddress(false);
dispatch({ type: "addressChanged", patch: { editing: false } });
if (address.trim()) void control("goto", address.trim());
};
@ -356,9 +361,9 @@ export default function SharedBrowserPage() {
value={address}
placeholder={t("Address")}
disabled={!status.running}
onFocus={() => setEditingAddress(true)}
onBlur={() => setEditingAddress(false)}
onChange={(e) => setAddress(e.target.value)}
onFocus={() => dispatch({ type: "addressChanged", patch: { editing: true } })}
onBlur={() => dispatch({ type: "addressChanged", patch: { editing: false } })}
onChange={(e) => dispatch({ type: "addressChanged", patch: { value: e.target.value } })}
/>
</form>
{status.tabs.length > 0 && (