diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7fdcd64fe..77fc70bf7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -216,6 +216,8 @@ jobs: - run: npm run test:auth - run: npm run test:tamper-hooks - run: npm run test:i18n + - run: npm run test:navigation + - run: npm run test:chat-filter - run: npm run test:bash - run: npm run build:static diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d7f23b0a..f92d3d631 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented in this file. The format is b ### Added - **Opt-in SELinux overlay for bind mounts**: `docker-compose.selinux.yml` layers private `:Z` labels on `./data`, `./keys` and `./skills` for hosts with SELinux enforcing. The base file keeps its unlabelled mounts, so the overlay is opt-in and a shared `:z` label never lets another container read the encryption keys (#632). +- **Browser back and forward across console views** (#641): page navigation is represented in query parameters (`tab`, `view`, `c`, `path`, and the inspector record parameters), so a user action pushes a history entry and back and forward restore the view. The native history API integrates with the Next router and a stable server snapshot keeps the static export working. Inspector payloads stay in memory and are never written to the URL or to browser storage. `npm run test:navigation` covers the history logic and now runs in CI. - **Remote approvals over a chat bridge** (#642): a bridged chat can now carry an operator approval as one-time buttons instead of waiting for the console. The nonce is stored as a SHA-256 hash in the new `chat_bridge_approvals` table (migration 0019), a button is consumed atomically so a double tap cannot approve twice, and a group chat only sees the approvals of its own bridge. - **Chat bridge text excerpts are opt-in** (#642): migration 0018 adds `share_text`, default false, so a bridge no longer forwards captured text unless the operator enables it. `SafeText` also strips more secret shapes, including quoted `curl -u` credentials, and the outbound path re-checks that the asker is still a member before delivering. - **Tampering-hook tests run in CI**: the `web` job now runs `npm run test:tamper-hooks`. The suite existed as a script but no workflow called it, so a regression in the tampering-hook editor's payload and validation handling could merge without failing a check. @@ -22,6 +23,7 @@ All notable changes to this project are documented in this file. The format is b - **Go vulnerability scanning in CI**: every push and pull request runs the official `govulncheck` action against packages reachable from `./...`, using the Go version declared by `go.mod`. Run the same check locally with `./scripts/verify.sh --security`. ### Fixed +- **The chat agent filter no longer keeps a thread from another agent open**: switching the filter left the previously selected conversation in place, so a thread started with one agent could still be read while the filter showed another, and the draft could pick the wrong agent. The selection is now cleared when it does not belong to the new filter, and the draft uses the filtered agent. `npm run test:chat-filter` covers both helpers and now runs in CI. - **Session tokens are no longer accepted from a URL query string**: the SSE, log and browser endpoints accepted `?token=`, which put a console JWT into browser history, proxy logs and `Referer` headers. Those endpoints now require the same Bearer header as the rest of the API; the console uses a `fetch` based SSE reader, the client-written auth cookie is gone, and the same-origin CORS preflight allows `Authorization` and `Last-Event-ID`. Login and uploads no longer carry a token in the URL either (#660). - **CORS answers only the console's own origin**: the middleware reflected the request `Origin` without checking it, so any site could read cross-origin responses with a victim's cookie. It now reflects only an exact origin match and sends `Vary: Origin`; a mismatched `Sec-Fetch-Site` no longer causes a foreign origin to be allowed (#633). The one exception is a loopback Origin against a loopback target, so the `next dev` console on another local port keeps its live streams; the check requireAuth applies to cookie writes stays strict. - **Task text and untrusted fields are quoted in logs**: `createTask` logged the description and goal raw, so a CR/LF in either could forge log lines. They and the sibling reason/URL lines in the engine, timeout, fingerprint and traffic-rewrite logs are now quoted with `%q` (#658). diff --git a/docs/browser-navigation.md b/docs/browser-navigation.md new file mode 100644 index 000000000..5bf3017fc --- /dev/null +++ b/docs/browser-navigation.md @@ -0,0 +1,51 @@ +# Browser navigation + +Page navigation is represented in query parameters. User actions push a history +entry; restoring an initial saved preference replaces the current entry. Rendering, +polling and back/forward handling never mirror stale component state into the URL. +The native history API integrates with Next's router and preserves other query +parameters and the hash. A stable server snapshot supports the static export. + +| View | Query parameter | +| --- | --- | +| Task detail, finding detail, task archive, assets, models, rules, tools, notifications | `tab` | +| Findings grouping | `view` | +| Conversation, including an explicit empty draft | `c` | +| Workspace directory | `path` | +| Traffic / tool execution / LLM record inspector | `exchange` / `command` / `record` | +| Return from a finding opened inside a task | `from_task` | + +`context_task` retains its existing meaning for inherited finding access. The new +return parameter does not change which finding data the API supplies. + +Inspector payloads remain in memory (at most 100 visited rows). Back/forward can +restore visited rows across client navigations; after a full reload, the selected +record must be in the loaded list. They are not arbitrary-record permalink APIs. +Payloads, credentials, and form contents are not written into the URL or browser +storage. Creation/edit dialogs and filters remain ordinary form state. + +## Regression checks + +Run `npm run test:navigation` in `web/` for the history logic. The test is included +in CI and the repository verification script. + +For the browser checks, use a Python environment with Playwright and its Chromium +browser installed, then start the mock frontend: + +```sh +cd web +NEXT_PUBLIC_MOCK=1 npm run dev -- --hostname 127.0.0.1 --port 18791 +``` + +In another terminal: + +```sh +ARTEX_TEST_URL=http://127.0.0.1:18791 python3 web/scripts/navigation-browser.py +``` + +The browser script uses the existing demo fixtures, emits a JSON result and a +screenshot alongside the script, and exits unsuccessfully if a case fails. It +covers back, forward, refresh, repeated tab selection, invalid tabs, task → finding +→ contextual return, chat selection/draft, record inspectors, and workspace +directories. `ARTEX_TEST_FILTER` selects cases whose names contain the given text. +Use this script against the mock frontend, not a production dataset. diff --git a/scripts/verify.sh b/scripts/verify.sh index 47a7bd90e..bf18487eb 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -139,6 +139,7 @@ if want_web; then run_step "npm ci" npm --prefix web ci fi run_step "tsc --noEmit" bash -c 'cd web && npx tsc --noEmit' + run_step "web navigation tests" bash -c 'cd web && npm run test:navigation' run_step "web polling tests" bash -c 'cd web && npm run test:polling' run_step "web replay tests" bash -c 'cd web && npm run test:replay' run_step "web upload tests" bash -c 'cd web && npm run test:upload' diff --git a/web/package.json b/web/package.json index 624bb63d8..b44d0b06c 100644 --- a/web/package.json +++ b/web/package.json @@ -21,7 +21,9 @@ "test:i18n": "node scripts/check-i18n.mjs && node --test scripts/i18n.test.mjs", "test:bash": "node --test src/lib/bash-exit-status.test.mjs", "test:sse": "node --test scripts/sse.test.mjs", - "test:auth": "node --test scripts/auth.test.mjs" + "test:auth": "node --test scripts/auth.test.mjs", + "test:navigation": "node --test src/lib/navigation.test.mjs", + "test:chat-filter": "node --test src/lib/chat-agent-filter.test.mjs" }, "lint-staged": { "*.{js,ts,jsx,tsx}": [ diff --git a/web/scripts/navigation-browser.py b/web/scripts/navigation-browser.py new file mode 100644 index 000000000..56472c394 --- /dev/null +++ b/web/scripts/navigation-browser.py @@ -0,0 +1,119 @@ +import json, os, re +from pathlib import Path +from playwright.sync_api import sync_playwright, expect + +base=os.environ.get('ARTEX_TEST_URL','http://127.0.0.1:18791') +results=[] +with sync_playwright() as p: + browser=p.chromium.launch(headless=True) + page=browser.new_page(viewport={"width":1440,"height":1000}) + page.set_default_timeout(30000) + errors=[] + page.on('pageerror', lambda e: errors.append(str(e))) + def run(name, fn): + if os.environ.get('ARTEX_TEST_FILTER') and os.environ['ARTEX_TEST_FILTER'] not in name: return + try: + fn() + results.append({'name':name,'passed':True}) + except Exception as e: + results.append({'name':name,'passed':False,'error':str(e)[:1200]}) + print(json.dumps(results[-1]),flush=True) + def tab(name): + return page.get_by_role('tab',name=re.compile('^'+re.escape(name)+r'(\s|\d|$)')) + def selected(name): + expect(tab(name)).to_have_attribute('data-state','active') + def roundtrip(path, first, second, query): + page.goto(base+path,wait_until='domcontentloaded',timeout=90000) + selected(first) + initial=page.evaluate('history.length') + tab(second).click() + selected(second) + expect(page).to_have_url(re.compile(query)) + tab(second).click() + assert page.evaluate('history.length')==initial+1 + page.go_back() + selected(first) + page.go_forward() + selected(second) + page.reload() + selected(second) + for args in [ + ('/function/tasks','Current tasks','Archived','tab=archived'), + ('/function/tasks/detail?id=t-acme-web','Sessions','Findings','tab=findings'), + ('/function/findings/detail?id=f-1','Overview','Exploration graph','tab=lineage'), + ('/function/findings','All findings','By task','view=grouped'), + ('/function/assets','Companies','Root domains','tab=root_domain'), + ('/system/llm','Model profiles','Retry & backoff','tab=retry'), + ('/system/intercept','Interception rules','Model config','tab=judge'), + ('/system/tools','System tools','Custom tools','tab=custom'), + ('/system/notify','Channels','Delivery log','tab=deliveries'), + ]: + run(args[0],lambda args=args: roundtrip(*args)) + def task_finding(): + page.goto(base+'/function/tasks/detail?id=t-acme-web&tab=findings',wait_until='domcontentloaded') + selected('Findings') + page.get_by_role('link',name='Details',exact=True).first.click() + expect(page).to_have_url(re.compile('from_task=t-acme-web')) + selected('Overview') + page.go_back() + selected('Findings') + page.go_forward() + selected('Overview') + back=page.locator('header a[href*="tab=findings"]') + expect(back).to_have_count(1) + back.click() + selected('Findings') + run('task → finding → browser back/forward → contextual return',task_finding) + def invalid_tab(): + page.goto(base+'/function/tasks/detail?id=t-acme-web&tab=invalid',wait_until='domcontentloaded') + selected('Sessions') + run('invalid tab fallback', invalid_tab) + def chats(): + page.goto(base+'/chat?c=1',wait_until='domcontentloaded') + one=page.locator('button[title="Double-click to rename"]').filter(has_text='Discussion on the acme admin entry point') + two=page.locator('button[title="Double-click to rename"]').filter(has_text='Mapping the API authorization bypass surface') + expect(one.locator('..')).to_have_class(re.compile('bg-accent text-accent-foreground')) + two.click() + expect(page).to_have_url(re.compile('c=2')) + expect(two.locator('..')).to_have_class(re.compile('bg-accent text-accent-foreground')) + page.go_back() + expect(page).to_have_url(re.compile('c=1')) + expect(one.locator('..')).to_have_class(re.compile('bg-accent text-accent-foreground')) + page.go_forward() + expect(two.locator('..')).to_have_class(re.compile('bg-accent text-accent-foreground')) + page.reload() + expect(two.locator('..')).to_have_class(re.compile('bg-accent text-accent-foreground')) + page.get_by_role('button',name='New conversation',exact=True).click() + expect(page).to_have_url(re.compile(r'c=($|&)')) + page.go_back() + expect(two.locator('..')).to_have_class(re.compile('bg-accent text-accent-foreground')) + run('chat selection, draft, back, forward and reload', chats) + def inspector(path,key): + page.goto(base+path,wait_until='domcontentloaded') + row=page.locator('tbody tr.cursor-pointer').first + row.wait_for() + row.click() + expect(page).to_have_url(re.compile(key+'=[^&]+')) + opened=page.url + page.go_back() + assert not re.search(key+'=[^&]+',page.url) + page.go_forward() + expect(page).to_have_url(opened) + expect(row).to_have_class(re.compile('bg-accent')) + for path,key in [('/function/traffic','exchange'),('/function/commands','command'),('/function/llm-records','record')]: + run(path+' inspector back/forward',lambda path=path,key=key: inspector(path,key)) + def workspace(): + page.goto(base+'/function/workspace',wait_until='domcontentloaded') + page.locator('tbody tr').filter(has_text='t-001').first.get_by_role('button').first.click() + expect(page).to_have_url(re.compile('path=t-001')) + page.go_back() + expect(page.locator('tbody tr').filter(has_text='t-001').first).to_be_visible() + page.go_forward() + expect(page).to_have_url(re.compile('path=t-001')) + run('workspace directories back/forward',workspace) + page.screenshot(path=str(Path(__file__).with_name('mock-navigation.png'))) + browser.close() +Path(__file__).with_name('browser-results.json').write_text(json.dumps({'results':results,'page_errors':errors},indent=2)) +assert all(r['passed'] for r in results), 'browser regressions failed' + +assert not errors, "browser page errors occurred" diff --git a/web/src/app/(main)/chat/page.tsx b/web/src/app/(main)/chat/page.tsx index e9c65b902..e8d529710 100644 --- a/web/src/app/(main)/chat/page.tsx +++ b/web/src/app/(main)/chat/page.tsx @@ -1,5 +1,8 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; +import { updateQuery } from "@/lib/navigation"; + import * as React from "react"; import { @@ -27,6 +30,7 @@ import { SideQuestionButton, SideQuestionWorkspace } from "@/components/side-que import { TodoPopover } from "@/components/todo-popover"; import { ApprovalExecutionFocus, useApprovalFocus, useApprovalHistory } from "@/components/approval-execution-focus"; import { Transcript } from "@/components/transcript"; +import { nextSelectedIdForAgentFilter, resolveDraftAgentKey } from "@/lib/chat-agent-filter"; import { AlertDialog, AlertDialogAction, @@ -355,22 +359,28 @@ function LLMProfileRow({ function DraftChat({ agents, profiles, + defaultAgentKey = null, onStarted, }: { agents: Agent[]; profiles: LLMProfile[]; + defaultAgentKey?: string | null; onStarted: (c: Conversation, pending?: { input?: string; attachments?: ChatAttachment[] }) => void; }) { - const [agentKey, setAgentKey] = React.useState(""); + const [agentKey, setAgentKey] = React.useState(() => resolveDraftAgentKey("", agents, defaultAgentKey, true)); const [llmProfileId, setLlmProfileId] = React.useState(null); const [input, setInput] = React.useState(""); const [sending, setSending] = React.useState(false); const [uploading, setUploading] = React.useState(false); + const prevDefaultAgentKey = React.useRef(defaultAgentKey); - // default the agent to Auto once agents load. + // Default to the active agent filter (falling back to Auto) on load and + // whenever the sidebar agent filter changes. React.useEffect(() => { - if (!agentKey && agents.some((a) => a.key === "auto")) setAgentKey("auto"); - }, [agentKey, agents]); + const filterChanged = prevDefaultAgentKey.current !== defaultAgentKey; + prevDefaultAgentKey.current = defaultAgentKey; + setAgentKey((current) => resolveDraftAgentKey(current, agents, defaultAgentKey, filterChanged)); + }, [agents, defaultAgentKey]); const agent = agents.find((a) => a.key === agentKey); @@ -1047,18 +1057,20 @@ export default function ChatPage() { const [profiles, setProfiles] = React.useState([]); const [convs, setConvs] = React.useState([]); const [agentFilter, setAgentFilter] = React.useState(null); - const [selectedId, setSelectedId] = React.useState(null); - const [sourceRequested, setSourceRequested] = React.useState(false); + const [conversationID] = useQueryState("c", ""); + const selectedId = /^[1-9]\d*$/.test(conversationID) ? Number(conversationID) : null; + const setSelectedId = React.useCallback((next: React.SetStateAction) => { + const raw = new URLSearchParams(window.location.search).get("c"); + const current = raw && /^[1-9]\d*$/.test(raw) ? Number(raw) : null; + const id = typeof next === "function" ? next(current) : next; + if (id !== current) updateQuery({ c: id === null ? "" : String(id), approval: null }); + }, []); + const [approvalID] = useQueryState("approval", ""); + const sourceRequested = Boolean(approvalID); const [convsLoaded, setConvsLoaded] = React.useState(false); const selectConversation = React.useCallback((id: number | null) => { - if (id !== selectedId) { - const url = new URL(window.location.href); - url.searchParams.delete("approval"); - setSourceRequested(false); - window.history.replaceState(null, "", url); - } setSelectedId(id); - }, [selectedId]); + }, [setSelectedId]); const [renamingId, setRenamingId] = React.useState(null); const [renameText, setRenameText] = React.useState(""); @@ -1152,35 +1164,16 @@ export default function ChatPage() { }); }, []); - // Restore the open conversation on mount, so a refresh or a return from another - // page lands on the same thread instead of the empty draft view: the URL - // (?c=) first, else the last conversation opened here. Runs after - // hydration (not a lazy useState init) to avoid a server/client mismatch. React.useEffect(() => { const params = new URLSearchParams(window.location.search); - setSourceRequested(params.has("approval")); - const c = params.get("c") ?? getLocalStorageValue(LAST_CONVERSATION_KEY); - const id = c ? Number(c) : NaN; - if (Number.isFinite(id)) setSelectedId(id); + if (!params.has("c")) { + const saved = getLocalStorageValue(LAST_CONVERSATION_KEY); + updateQuery({ c: saved && /^[1-9]\d*$/.test(saved) ? saved : "" }, "replace"); + } }, []); - // Mirror the current selection into the URL (replaceState → no history spam). A - // selectedId with no matching conversation (e.g. a stale ?c=, or a just-created - // one before reloadConvs lands) simply renders the draft view — harmless — so we - // deliberately do NOT auto-clear it here (that raced new-conversation creation). - // The same value goes to localStorage for the restore above. On mount this - // effect runs once with the initial null before the restored id lands; the - // restore has already read the stored value by then and writes it back on the - // next render. React.useEffect(() => { - const url = new URL(window.location.href); - if (selectedId != null) { - url.searchParams.set("c", String(selectedId)); - setLocalStorageValue(LAST_CONVERSATION_KEY, String(selectedId)); - } else { - url.searchParams.delete("c"); - removeLocalStorageValue(LAST_CONVERSATION_KEY); - } - window.history.replaceState(null, "", url); + if (selectedId !== null) setLocalStorageValue(LAST_CONVERSATION_KEY, String(selectedId)); + else removeLocalStorageValue(LAST_CONVERSATION_KEY); }, [selectedId]); const selected = React.useMemo(() => convs.find((c) => c.id === selectedId) ?? null, [convs, selectedId]); @@ -1228,6 +1221,9 @@ export default function ChatPage() { function changeAgentFilter(key: string | null) { setAgentFilter(key); + if (selectedId !== null && nextSelectedIdForAgentFilter(selectedId, convs, key) === null) { + selectConversation(null); + } setVisibleConversationCount(CONVERSATION_LIST_PAGE); setSelectedConversationIds(new Set()); setBulkDeleteOpen(false); @@ -1541,6 +1537,7 @@ export default function ChatPage() { { if (agentFilter !== null && agentFilter !== c.agent_key) changeAgentFilter(null); // Insert the new conversation immediately so `selected` resolves to diff --git a/web/src/app/(main)/function/assets/page.tsx b/web/src/app/(main)/function/assets/page.tsx index 74bd07d77..bdd2fd287 100644 --- a/web/src/app/(main)/function/assets/page.tsx +++ b/web/src/app/(main)/function/assets/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; + import * as React from "react"; import { @@ -110,7 +112,7 @@ export default function AssetsPage() { const [total, setTotal] = React.useState(0); const [companies, setCompanies] = React.useState([]); const [counts, setCounts] = React.useState>({}); - const [tab, setTab] = React.useState("company"); + const [tab, setTab] = useQueryState("tab", "company", TABS.map((tab) => tab.key)); const [query, setQuery] = React.useState(""); const [loaded, setLoaded] = React.useState(false); const [loading, setLoading] = React.useState(false); diff --git a/web/src/app/(main)/function/commands/page.tsx b/web/src/app/(main)/function/commands/page.tsx index abcb2d1c3..862a69be7 100644 --- a/web/src/app/(main)/function/commands/page.tsx +++ b/web/src/app/(main)/function/commands/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useRecordHistory } from "@/hooks/use-record-history"; + import * as React from "react"; import { BarChart3Icon, ChevronLeftIcon, ChevronRightIcon, Loader2Icon, SearchIcon, TerminalIcon } from "lucide-react"; @@ -58,7 +60,7 @@ export default function CommandsPage() { const [statsLoading, setStatsLoading] = React.useState(false); // Selected execution is rendered in a right-side detail sheet. - const [selected, setSelected] = React.useState(null); + const [selected, setSelected] = useRecordHistory("command", commands); // Debounce search input. React.useEffect(() => { diff --git a/web/src/app/(main)/function/findings/detail/page.tsx b/web/src/app/(main)/function/findings/detail/page.tsx index 2950054f4..ac22d2d79 100644 --- a/web/src/app/(main)/function/findings/detail/page.tsx +++ b/web/src/app/(main)/function/findings/detail/page.tsx @@ -1,6 +1,9 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; + import * as React from "react"; +import { findingReturnHref } from "@/lib/navigation"; import Link from "next/link"; import { useSearchParams } from "next/navigation"; @@ -64,10 +67,11 @@ function FieldRow({ label, children }: { label: string; children: React.ReactNod function FindingDetailInner() { const searchParams = useSearchParams(); const id = searchParams.get("id") ?? ""; + const backHref = findingReturnHref(searchParams.get("from_task") ?? searchParams.get("context_task")); const contextTaskId = searchParams.get("context_task") ?? ""; const [finding, setFinding] = React.useState(null); const [loaded, setLoaded] = React.useState(false); - const [tab, setTab] = React.useState("overview"); + const [tab, setTab] = useQueryState("tab", "overview", ["overview", "lineage"]); const load = React.useCallback(() => { if (!id) { @@ -141,7 +145,7 @@ function FindingDetailInner() {

{loaded ? t("Finding {id} not found", { id }) : t("Loading…")}

{loaded && ( @@ -159,7 +163,7 @@ function FindingDetailInner() {
diff --git a/web/src/app/(main)/function/findings/page.tsx b/web/src/app/(main)/function/findings/page.tsx index 824c48f6a..70d68e77e 100644 --- a/web/src/app/(main)/function/findings/page.tsx +++ b/web/src/app/(main)/function/findings/page.tsx @@ -1,5 +1,8 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; +import { updateQuery } from "@/lib/navigation"; + import * as React from "react"; import Link from "next/link"; @@ -146,7 +149,7 @@ export default function FindingsPage() { // flat and grouped lists, the asset tree and the stat cards all send `company`. // Undefined means all companies. const company = useActiveCompany(); - const [view, setView] = React.useState("flat"); + const [view, setView] = useQueryState("view", "flat", FINDING_VIEWS); const [severity, setSeverity] = React.useState<"all" | Severity>("all"); const [status, setStatus] = React.useState<"all" | FindingStatus>("all"); const [reportState, setReportState] = React.useState<"all" | FindingReportState>("all"); @@ -236,7 +239,9 @@ export default function FindingsPage() { task?: unknown; sort?: unknown; }; - if (FINDING_VIEWS.includes(parsed.view as FindingView)) setView(parsed.view as FindingView); + if (!new URLSearchParams(window.location.search).has("view")) { + updateQuery({ view: FINDING_VIEWS.includes(parsed.view as FindingView) ? String(parsed.view) : "flat" }, "replace"); + } if (parsed.severity === "all" || SEVERITIES.includes(parsed.severity as Severity)) { setSeverity(parsed.severity as "all" | Severity); } @@ -259,6 +264,7 @@ export default function FindingsPage() { // Ignore malformed or legacy preferences and retain the defaults. } } + if (!new URLSearchParams(window.location.search).has("view")) updateQuery({ view: "flat" }, "replace"); setPreferencesHydrated(true); }, []); diff --git a/web/src/app/(main)/function/llm-records/page.tsx b/web/src/app/(main)/function/llm-records/page.tsx index 829df7ca5..5f78c129f 100644 --- a/web/src/app/(main)/function/llm-records/page.tsx +++ b/web/src/app/(main)/function/llm-records/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useRecordHistory } from "@/hooks/use-record-history"; + import * as React from "react"; import { RadioIcon, @@ -126,7 +128,7 @@ export default function LLMRecordsPage() { const [recBusy, setRecBusy] = React.useState(false); // Inline detail panel (Burp-style split, not a dialog) - const [selected, setSelected] = React.useState(null); + const [selected, setSelected] = useRecordHistory("record", records); const [detail, setDetail] = React.useState(null); const [detailLoading, setDetailLoading] = React.useState(false); // Normalized view / raw HTTP view. The raw exchange is the only authoritative source when debugging diff --git a/web/src/app/(main)/function/tasks/detail/_tabs/findings-tab.tsx b/web/src/app/(main)/function/tasks/detail/_tabs/findings-tab.tsx index 09b7c85a2..478594f2e 100644 --- a/web/src/app/(main)/function/tasks/detail/_tabs/findings-tab.tsx +++ b/web/src/app/(main)/function/tasks/detail/_tabs/findings-tab.tsx @@ -116,8 +116,8 @@ function Row({ (null); const [paused, setPaused] = React.useState(false); const [loaded, setLoaded] = React.useState(false); - const [tab, setTab] = React.useState("sessions"); + const [tab, setTab] = useQueryState("tab", "sessions", TABS.map((tab) => tab.value)); const [interceptPendingCount, setInterceptPendingCount] = React.useState(0); const [profiles, setProfiles] = React.useState([]); const [archiving, setArchiving] = React.useState(false); diff --git a/web/src/app/(main)/function/tasks/page.tsx b/web/src/app/(main)/function/tasks/page.tsx index 7b69cc0b8..2245d33a4 100644 --- a/web/src/app/(main)/function/tasks/page.tsx +++ b/web/src/app/(main)/function/tasks/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; + import * as React from "react"; import Link from "next/link"; @@ -297,7 +299,7 @@ function compareTasks(left: Task, right: Task, field: TaskSortField, direction: export default function TasksPage() { // The sidebar's company switcher: the server returns only the tasks scoped to it. const companyId = useActiveCompanyID(); - const [activeTab, setActiveTab] = React.useState("current"); + const [activeTab, setActiveTab] = useQueryState("tab", "current", ["current", "archived"]); const [tasks, setTasks] = React.useState([]); const [categories, setCategories] = React.useState([]); const [categoriesLoaded, setCategoriesLoaded] = React.useState(false); diff --git a/web/src/app/(main)/function/traffic/page.tsx b/web/src/app/(main)/function/traffic/page.tsx index 4820118f6..a8e214223 100644 --- a/web/src/app/(main)/function/traffic/page.tsx +++ b/web/src/app/(main)/function/traffic/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useRecordHistory } from "@/hooks/use-record-history"; + import * as React from "react"; import { @@ -127,7 +129,7 @@ export default function TrafficPage() { const [sort, setSort] = useStoredSortPreference(SORT_STORAGE_KEY, SORT_FIELDS, "ts", "desc"); const [traffic, setTraffic] = React.useState(null); - const [selected, setSelected] = React.useState(null); + const [selected, setSelected] = useRecordHistory("exchange", traffic?.exchanges ?? []); const [detail, setDetail] = React.useState(null); const [detailLoading, setDetailLoading] = React.useState(false); const [detailTab, setDetailTab] = React.useState("request"); diff --git a/web/src/app/(main)/function/workspace/page.tsx b/web/src/app/(main)/function/workspace/page.tsx index f261f95e7..647688b2b 100644 --- a/web/src/app/(main)/function/workspace/page.tsx +++ b/web/src/app/(main)/function/workspace/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; + import * as React from "react"; import { DownloadIcon, @@ -54,7 +56,7 @@ type EditState = { }; export default function WorkspacePage() { - const [path, setPath] = React.useState(""); + const [path, setPath] = useQueryState("path", ""); const [entries, setEntries] = React.useState([]); const [loading, setLoading] = React.useState(true); const [edit, setEdit] = React.useState(null); @@ -62,24 +64,26 @@ export default function WorkspacePage() { const [mkdirName, setMkdirName] = React.useState(""); const uploadRef = React.useRef(null); + const loadSequence = React.useRef(0); const load = React.useCallback( (p: string) => { + const sequence = ++loadSequence.current; setLoading(true); api .workspaceList(p) .then((r) => { - setEntries(r.entries); - setPath(r.path); + if (sequence === loadSequence.current) setEntries(r.entries); }) .catch((e) => toast.error(t("Failed to read directory: {error}", { error: (e as Error).message }))) - .finally(() => setLoading(false)); + .finally(() => { if (sequence === loadSequence.current) setLoading(false); }); }, [], ); React.useEffect(() => { - load(""); - }, [load]); + load(path); + return () => { loadSequence.current++; }; + }, [load, path]); const crumbs = React.useMemo(() => { const parts = path ? path.split("/") : []; @@ -169,7 +173,7 @@ export default function WorkspacePage() { {i > 0 && /}
- + {t("Interception rules")} {t("Model config")} diff --git a/web/src/app/(main)/system/llm/page.tsx b/web/src/app/(main)/system/llm/page.tsx index bf2630228..a64d92761 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; + import * as React from "react"; import { @@ -967,6 +969,7 @@ function ProfileSheet({ // ───────────────────────────────────────────────────────────────────────────── export default function LLMPage() { + const [tab, setTab] = useQueryState("tab", "profiles", ["profiles", "retry"]); const [profiles, setProfiles] = React.useState([]); const [pool, setPool] = React.useState(null); const [poolOpen, setPoolOpen] = React.useState(false); @@ -1059,7 +1062,7 @@ export default function LLMPage() { - + {t("Model profiles")} {t("Retry & backoff")} diff --git a/web/src/app/(main)/system/notify/page.tsx b/web/src/app/(main)/system/notify/page.tsx index 4ceb1e30a..270f8c318 100644 --- a/web/src/app/(main)/system/notify/page.tsx +++ b/web/src/app/(main)/system/notify/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; + import * as React from "react"; import { BellIcon, PlusIcon, SendIcon, Trash2Icon } from "lucide-react"; @@ -52,7 +54,7 @@ function limitInvalid(raw: string, max: number): boolean { export default function NotifyPage() { const [meta, setMeta] = React.useState(null); const [channels, setChannels] = React.useState([]); - const [tab, setTab] = React.useState<"channels" | "deliveries">("channels"); + const [tab, setTab] = useQueryState("tab", "channels", ["channels", "deliveries"]); const [open, setOpen] = React.useState(false); const [editing, setEditing] = React.useState(null); diff --git a/web/src/app/(main)/system/tools/page.tsx b/web/src/app/(main)/system/tools/page.tsx index 5e47d59c6..b79da6e6b 100644 --- a/web/src/app/(main)/system/tools/page.tsx +++ b/web/src/app/(main)/system/tools/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useQueryState } from "@/hooks/use-query-state"; + import * as React from "react"; import { toast } from "sonner"; import { PlayIcon, PlusIcon, RotateCcwIcon, SaveIcon, SearchIcon, Trash2Icon } from "lucide-react"; @@ -375,6 +377,7 @@ function ToolGridCard({ tool, onClick }: { tool: Tool; onClick: () => void }) { } export default function ToolsPage() { + const [tab, setTab] = useQueryState("tab", "system", ["system", "custom"]); const [tools, setTools] = React.useState([]); const [agents, setAgents] = React.useState([]); const [captureOn, setCaptureOn] = React.useState(false); @@ -427,7 +430,7 @@ export default function ToolsPage() { - + {t("System tools")} {t("Custom tools")} diff --git a/web/src/hooks/use-query-state.ts b/web/src/hooks/use-query-state.ts new file mode 100644 index 000000000..289046189 --- /dev/null +++ b/web/src/hooks/use-query-state.ts @@ -0,0 +1,36 @@ +"use client"; + +import * as React from "react"; + +import { usePathname } from "next/navigation"; + +import { NAVIGATION_EVENT, readQuery, updateQuery } from "@/lib/navigation"; + +function subscribe(notify: () => void) { + window.addEventListener("popstate", notify); + window.addEventListener(NAVIGATION_EVENT, notify); + return () => { + window.removeEventListener("popstate", notify); + window.removeEventListener(NAVIGATION_EVENT, notify); + }; +} + +const snapshot = () => window.location.search; +const serverSnapshot = () => ""; + +// A stable SSR snapshot supports static export without a Suspense wrapper. +// Read the URL on back/forward rather than mirroring component state into it. +export function useQueryState(key: string, fallback: string, allowed?: readonly string[]) { + usePathname(); // Re-read when a Next client navigation changes the page. + const search = React.useSyncExternalStore(subscribe, snapshot, serverSnapshot); + const value = readQuery(search, key, fallback, allowed); + const setValue = React.useCallback( + (next: React.SetStateAction) => { + const current = readQuery(window.location.search, key, fallback, allowed); + const resolved = typeof next === "function" ? next(current) : next; + if (resolved !== current && (!allowed || allowed.includes(resolved))) updateQuery({ [key]: resolved }); + }, + [key, fallback, allowed], + ); + return [value, setValue] as const; +} diff --git a/web/src/hooks/use-record-history.ts b/web/src/hooks/use-record-history.ts new file mode 100644 index 000000000..9326b9f1b --- /dev/null +++ b/web/src/hooks/use-record-history.ts @@ -0,0 +1,36 @@ +"use client"; + +import * as React from "react"; + +import { usePathname } from "next/navigation"; + +import { useQueryState } from "@/hooks/use-query-state"; + +// Inspectors have no detail route. Cache visited rows in memory so back/forward +// can reopen them even after changing pages or filters. Do not put payloads in +// history.state, localStorage or URLs. A reload resolves against the loaded rows. +const visited = new Map(); + +export function useRecordHistory(key: string, rows: readonly T[]) { + const pathname = usePathname(); + const [id, setID] = useQueryState(key, ""); + const prefix = `${pathname}:${key}:`; + const selected = (visited.get(prefix + id) as T | undefined) ?? rows.find((row) => String(row.id) === id) ?? null; + const select = React.useCallback( + (row: T | null) => { + if (row) { + const cacheKey = prefix + String(row.id); + visited.delete(cacheKey); + visited.set(cacheKey, row); + // Bound retention when an operator inspects a large log. + if (visited.size > 100) { + const oldest = visited.keys().next().value; + if (oldest !== undefined) visited.delete(oldest); + } + } + setID(row === null ? "" : String(row.id)); + }, + [prefix, setID], + ); + return [selected, select] as const; +} diff --git a/web/src/lib/chat-agent-filter.test.mjs b/web/src/lib/chat-agent-filter.test.mjs new file mode 100644 index 000000000..0391143c2 --- /dev/null +++ b/web/src/lib/chat-agent-filter.test.mjs @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { nextSelectedIdForAgentFilter, resolveDraftAgentKey } from "./chat-agent-filter.ts"; + +const CONVS = [ + { id: 10, agent_key: "auto" }, + { id: 20, agent_key: "recon" }, +]; + +const AGENTS = [{ key: "auto" }, { key: "recon" }, { key: "reporter" }]; + +test("nextSelectedIdForAgentFilter clears selectedId when open conversation does not match", () => { + assert.equal(nextSelectedIdForAgentFilter(10, CONVS, "recon"), null); + assert.equal(nextSelectedIdForAgentFilter(20, CONVS, "auto"), null); + assert.equal(nextSelectedIdForAgentFilter(999, CONVS, "recon"), null); +}); + +test("nextSelectedIdForAgentFilter keeps selectedId when filter matches or is cleared", () => { + assert.equal(nextSelectedIdForAgentFilter(10, CONVS, "auto"), 10); + assert.equal(nextSelectedIdForAgentFilter(20, CONVS, "recon"), 20); + assert.equal(nextSelectedIdForAgentFilter(20, CONVS, null), 20); + assert.equal(nextSelectedIdForAgentFilter(null, CONVS, "recon"), null); +}); + +test("resolveDraftAgentKey defaults to filtered agent and syncs on filter changes", () => { + // Initial mount with filter already selected. + assert.equal(resolveDraftAgentKey("", AGENTS, "recon", true), "recon"); + // Agents arrive asynchronously after mount with filter set. + assert.equal(resolveDraftAgentKey("", AGENTS, "recon", false), "recon"); + // Switching sidebar filter updates an active draft picker. + assert.equal(resolveDraftAgentKey("auto", AGENTS, "reporter", true), "reporter"); + // Clearing sidebar filter resets back to auto. + assert.equal(resolveDraftAgentKey("reporter", AGENTS, null, true), "auto"); +}); + +test("resolveDraftAgentKey preserves manual picker selection and falls back for unknown filter", () => { + // Manual override is kept when agents refresh without a filter change. + assert.equal(resolveDraftAgentKey("reporter", AGENTS, "recon", false), "reporter"); + // Disabled/historical agent not in chatAgents falls back to auto. + assert.equal(resolveDraftAgentKey("", AGENTS, "deleted-agent", true), "auto"); + assert.equal(resolveDraftAgentKey("recon", AGENTS, "deleted-agent", true), "recon"); + assert.equal(resolveDraftAgentKey("", [], "recon", true), ""); +}); diff --git a/web/src/lib/chat-agent-filter.ts b/web/src/lib/chat-agent-filter.ts new file mode 100644 index 000000000..b313c23e4 --- /dev/null +++ b/web/src/lib/chat-agent-filter.ts @@ -0,0 +1,42 @@ +export interface AgentFilterConversation { + id: number; + agent_key: string; +} + +export interface AgentFilterOption { + key: string; +} + +// Keep the open conversation only when it still matches the active agent filter. +export function nextSelectedIdForAgentFilter( + selectedId: number | null, + conversations: readonly AgentFilterConversation[], + nextFilter: string | null, +): number | null { + if (selectedId === null || nextFilter === null) return selectedId; + const open = conversations.find((c) => c.id === selectedId); + if (!open || open.agent_key !== nextFilter) return null; + return selectedId; +} + +// Resolve DraftChat's agent picker value when mounting, when agents finish +// loading, or when the sidebar agent filter changes. +export function resolveDraftAgentKey( + currentKey: string, + agents: readonly AgentFilterOption[], + defaultAgentKey: string | null, + filterChanged: boolean, +): string { + const hasKey = (key: string) => agents.some((a) => a.key === key); + if (defaultAgentKey && hasKey(defaultAgentKey)) { + if (filterChanged || !currentKey || !hasKey(currentKey)) { + return defaultAgentKey; + } + } + if (filterChanged && defaultAgentKey === null && hasKey("auto")) { + return "auto"; + } + if (currentKey && hasKey(currentKey)) return currentKey; + if (hasKey("auto")) return "auto"; + return ""; +} diff --git a/web/src/lib/mock/handler.ts b/web/src/lib/mock/handler.ts index 001e5da7d..12c6637c1 100644 --- a/web/src/lib/mock/handler.ts +++ b/web/src/lib/mock/handler.ts @@ -1615,6 +1615,14 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re }; // ── Workspace file manager (demo: static sample tree; writes/creates/deletes hit the {ok:true} write fallback below) ── + // Empty notification fixtures keep the settings tabs usable in mock navigation tests. + if (path === "/notify/meta") return { + kinds: [], enabled: false, public_base_url: "", digest_interval_min: "10", + defaults: { digest_interval_min: 10 }, + stats: { channels: 0, channels_on: 0, pending: 0, failed: 0, sent_today: 0, backlog_age_ms: 0 }, + }; + if (path === "/notify/channels") return { channels: [] }; + if (path === "/notify/deliveries") return { deliveries: [], total: 0, page: 1, page_size: 50 }; if (path === "/workspace/list") return D.workspaceList(q.get("path") ?? ""); if (path === "/workspace/read") return D.workspaceRead(q.get("path") ?? ""); diff --git a/web/src/lib/navigation.test.mjs b/web/src/lib/navigation.test.mjs new file mode 100644 index 000000000..866787f4e --- /dev/null +++ b/web/src/lib/navigation.test.mjs @@ -0,0 +1,102 @@ +import { findingReturnHref, NAVIGATION_EVENT, readQuery, updateQuery } from "./navigation.ts"; +import assert from "node:assert/strict"; +import test from "node:test"; + +function browser(href) { + const entries = [href]; + let index = 0; + let notifications = 0; + globalThis.window = { + location: { href }, + history: { + pushState(_state, _title, url) { + entries.splice(++index, entries.length, String(url)); + window.location.href = String(url); + }, + replaceState(_state, _title, url) { + entries[index] = window.location.href = String(url); + }, + }, + dispatchEvent(event) { + assert.equal(event.type, NAVIGATION_EVENT); + notifications++; + }, + }; + return { + entries, + go(delta) { + index += delta; + window.location.href = entries[index]; + }, + get notifications() { + return notifications; + }, + get search() { + return new URL(window.location.href).search; + }, + }; +} + +test("task tabs survive back and forward without erasing id, focus or hash", () => { + const b = browser("https://artex.test/function/tasks/detail?id=7&approval=9#event"); + updateQuery({ tab: "findings" }); + updateQuery({ tab: "report" }); + b.go(-1); + assert.equal(readQuery(b.search, "tab", "sessions"), "findings"); + b.go(-1); + assert.equal(readQuery(b.search, "tab", "sessions"), "sessions"); + b.go(1); + assert.equal(readQuery(b.search, "tab", "sessions"), "findings"); + assert.equal(new URL(window.location.href).searchParams.get("id"), "7"); + assert.equal(new URL(window.location.href).searchParams.get("approval"), "9"); + assert.equal(new URL(window.location.href).hash, "#event"); +}); + +test("repeated selection and reads do not create history entries", () => { + const b = browser("https://artex.test/function/tasks?tab=archived"); + updateQuery({ tab: "archived" }); + readQuery(b.search, "tab", "current"); + assert.equal(b.entries.length, 1); + assert.equal(b.notifications, 0); +}); + +test("a new selection after back drops only the forward branch", () => { + const b = browser("https://artex.test/chat?c=1"); + updateQuery({ c: "2" }); + updateQuery({ c: "3" }); + b.go(-1); + updateQuery({ c: "4" }); + assert.equal(b.entries.length, 3); + assert.equal(readQuery(b.search, "c", ""), "4"); +}); + +test("chat switches remove focus only from the new entry and preserve draft", () => { + const b = browser("https://artex.test/chat?c=1&approval=99"); + updateQuery({ c: "2", approval: null }); + updateQuery({ c: "", approval: null }); + assert.equal(new URL(window.location.href).searchParams.get("c"), ""); + b.go(-1); + assert.equal(readQuery(b.search, "c", ""), "2"); + b.go(-1); + assert.equal(new URL(window.location.href).searchParams.get("approval"), "99"); +}); + +test("restoring a preference replaces only the initial entry", () => { + const b = browser("https://artex.test/function/findings"); + updateQuery({ view: "grouped" }, "replace"); + assert.equal(b.entries.length, 1); + updateQuery({ view: "asset" }); + b.go(-1); + assert.equal(readQuery(b.search, "view", "flat"), "grouped"); +}); + +test("missing and invalid tabs fall back without a history write", () => { + assert.equal(readQuery("?tab=unknown", "tab", "sessions", ["sessions", "findings"]), "sessions"); + assert.equal(readQuery("?id=1", "tab", "sessions"), "sessions"); +}); + +test("finding return destinations are local and preserve the task context", () => { + assert.equal(findingReturnHref(null), "/function/findings"); + assert.equal(findingReturnHref("7"), "/function/tasks/detail?id=7&tab=findings"); + assert.equal(findingReturnHref("x&tab=report"), "/function/tasks/detail?id=x%26tab%3Dreport&tab=findings"); +}); diff --git a/web/src/lib/navigation.ts b/web/src/lib/navigation.ts new file mode 100644 index 000000000..2cc9912dd --- /dev/null +++ b/web/src/lib/navigation.ts @@ -0,0 +1,24 @@ +// Only explicit navigation writes history. Rendering and polling never do. +export const NAVIGATION_EVENT = "artex:navigation"; + +export function updateQuery(values: Record, mode: "push" | "replace" = "push") { + const url = new URL(window.location.href); + for (const [key, value] of Object.entries(values)) { + if (value === null) url.searchParams.delete(key); + else url.searchParams.set(key, value); + } + if (url.href === window.location.href) return; + // Next patches these native methods to retain its router state and update + // useSearchParams. Do not copy private Next history flags into a new entry. + window.history[mode === "push" ? "pushState" : "replaceState"](null, "", url); + window.dispatchEvent(new Event(NAVIGATION_EVENT)); +} + +export function readQuery(search: string, key: string, fallback: string, allowed?: readonly string[]) { + const value = new URLSearchParams(search).get(key); + return value !== null && (!allowed || allowed.includes(value)) ? value : fallback; +} + +export function findingReturnHref(task: string | null) { + return task ? `/function/tasks/detail?id=${encodeURIComponent(task)}&tab=findings` : "/function/findings"; +}