From d7091a72de18c887e89cffff706e2a14c860f29f Mon Sep 17 00:00:00 2001
From: Fabricio Medrano <48396639+fabricio3g@users.noreply.github.com>
Date: Tue, 24 Nov 2026 17:14:25 -0300
Subject: [PATCH 1/2] feat(desktop): agent layout styles, session pane, and
workspace polish
- Appearance: add an "Agent layout" setting (AgentStyleId: agente, cards,
pills, spotlight, rail, accented, notebook, sheet, minimal) that changes
how reads, edits, diffs, shell cards, thoughts and tasks are drawn in the
Code transcript, with its styles in app.css and copy in en.json
- Workspace: a dockable "session" pane; the bottom dock no longer runs
under the right column, and its width divider is measured against the
space it can actually take
- Code surfaces (composer, live status, work block, step and thought rows,
tasks/session panels, disclosure) follow the new layout styles; the
project-controls store is folded into the workspace
- Smoke tests updated for the new pane and layout
---
apps/desktop/renderer/src/app.css | 585 ++++++++++++++++++
.../src/lib/components/layout/AppShell.svelte | 11 +-
.../components/layout/ChatSearchModal.svelte | 6 +-
.../lib/components/layout/PanelTabs.svelte | 320 ++++++----
.../src/lib/components/layout/Titlebar.svelte | 20 +-
.../components/layout/WorkspaceHost.svelte | 2 +-
.../layout/workspace-layout.spec.ts | 3 +-
.../lib/components/layout/workspace-layout.ts | 7 +-
.../settings/AppearanceSettings.svelte | 283 +++++++++
.../src/lib/features/code/CodeComposer.svelte | 6 +-
.../lib/features/code/CodeLiveStatus.svelte | 5 +-
.../src/lib/features/code/CodeSurface.svelte | 9 +-
.../lib/features/code/CodeThoughtRow.svelte | 11 +-
.../lib/features/code/CodeWorkBlock.svelte | 6 +-
.../features/code/ConversationPanes.svelte | 5 +-
.../code/ConversationWorkspace.svelte | 17 +-
.../src/lib/features/code/Disclosure.svelte | 69 ++-
.../src/lib/features/code/SessionPanel.svelte | 32 +-
.../src/lib/features/code/TasksPanel.svelte | 278 ++++++---
.../src/lib/features/code/ToolStepRow.svelte | 12 +-
.../code/workspace/project-controls.svelte.ts | 37 --
apps/desktop/renderer/src/lib/locales/en.json | 23 +-
.../src/lib/stores/appearance.spec.ts | 3 +
.../src/lib/stores/appearance.svelte.ts | 3 +-
apps/desktop/shared/appearance.ts | 28 +
.../electron/split-conversations.smoke.ts | 7 +-
.../electron/workspace-renderer.smoke.ts | 7 +-
27 files changed, 1455 insertions(+), 340 deletions(-)
delete mode 100644 apps/desktop/renderer/src/lib/features/code/workspace/project-controls.svelte.ts
diff --git a/apps/desktop/renderer/src/app.css b/apps/desktop/renderer/src/app.css
index 2c4304ce..8b3dab11 100644
--- a/apps/desktop/renderer/src/app.css
+++ b/apps/desktop/renderer/src/app.css
@@ -581,11 +581,14 @@
--theme-background: #1f1d1a;
--theme-foreground: #f4f0e8;
--card: #272420;
+ --card-foreground: #f4f0e8;
--popover: #2d2924;
+ --popover-foreground: #f4f0e8;
--secondary: #302c26;
--muted: #302c26;
--muted-foreground: #b5aea1;
--text-secondary: #cbc4b8;
+ --text-tertiary: #8d8679;
--sidebar: #25221e;
--sheet-rail: #25221e;
--surface-hover: #34302a;
@@ -625,11 +628,14 @@
--theme-background: #0f1012;
--theme-foreground: #f3f4f6;
--card: #16181c;
+ --card-foreground: #f3f4f6;
--popover: #1b1e24;
+ --popover-foreground: #f3f4f6;
--secondary: #1e2128;
--muted: #1e2128;
--muted-foreground: #9fa6b4;
--text-secondary: #c1c7d2;
+ --text-tertiary: #798192;
--sidebar: #14161a;
--sheet-rail: #14161a;
--surface-hover: #232730;
@@ -669,11 +675,14 @@
--theme-background: #181c23;
--theme-foreground: #eef2f7;
--card: #1f242e;
+ --card-foreground: #eef2f7;
--popover: #242b36;
+ --popover-foreground: #eef2f7;
--secondary: #262d39;
--muted: #262d39;
--muted-foreground: #a2aec0;
--text-secondary: #c2ccd9;
+ --text-tertiary: #7c8a9f;
--sidebar: #1d222b;
--sheet-rail: #1d222b;
--surface-hover: #2b3341;
@@ -714,11 +723,14 @@
--theme-background: #1d1e19;
--theme-foreground: #efeae0;
--card: #24251f;
+ --card-foreground: #efeae0;
--popover: #2a2b24;
+ --popover-foreground: #efeae0;
--secondary: #2d2e27;
--muted: #2d2e27;
--muted-foreground: #b0aa9c;
--text-secondary: #c7c1b3;
+ --text-tertiary: #898375;
--sidebar: #22231d;
--sheet-rail: #22231d;
--surface-hover: #32332b;
@@ -1379,6 +1391,559 @@ textarea {
padding: 0.25rem 0.125rem 0.375rem;
}
+/* ── Native Desktop Agent UI Layouts (reads, edits, diffs, shell cards, thinking, live status & tasks) ── */
+@keyframes agent-rail-slide {
+ 0% { transform: translateX(-100%); }
+ 100% { transform: translateX(300%); }
+}
+
+/* CodeTranscript wraps work blocks and live status in `-mx-2` inside a
+ `content-visibility: auto` message slot (paint containment). Layouts that
+ paint outer cards, borders, left bars, gutters, pills, or spine nodes cancel
+ that 8px horizontal bleed so edges and corners are never clipped. */
+:root:is([data-agent-style='cards'], [data-agent-style='pills'], [data-agent-style='spotlight'], [data-agent-style='rail'], [data-agent-style='accented'], [data-agent-style='notebook'], [data-agent-style='sheet']) .-mx-2 > :is(.work, .live) {
+ margin-inline: 0.5rem;
+}
+
+/* 1. Step Cards — full-width rounded cards, zero outer hairline */
+:root[data-agent-style='cards'] .work {
+ --block-body-ml: 0;
+ --block-body-pl: 0;
+ --block-body-bl: 0;
+ --block-body-gap: 0.4375rem;
+ --block-body-pt: 0.25rem;
+}
+:root[data-agent-style='cards'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-subagent) {
+ position: relative;
+ overflow: hidden;
+ border-radius: 0.75rem;
+ border: 1px solid var(--border);
+ background: var(--card);
+ padding: 0.125rem 0.25rem;
+ --step-body-indent: 0.5rem;
+ --step-body-padding: 0.5rem;
+ --step-body-bt: 1px solid var(--border-subtle);
+ --step-term-bg: var(--background);
+ transition: border-color var(--motion-instant) var(--motion-ease);
+}
+:root[data-agent-style='cards'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-subagent):hover {
+ border-color: var(--border-hover);
+}
+:root[data-agent-style='cards'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-running='true'] {
+ border-color: color-mix(in srgb, var(--brand-accent) 45%, var(--border));
+}
+:root[data-agent-style='cards'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-running='true']::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 35%;
+ height: 2px;
+ background: linear-gradient(90deg, transparent, var(--brand-accent), transparent);
+ animation: agent-rail-slide 1.5s ease-in-out infinite;
+}
+:root[data-agent-style='cards'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-thought {
+ border-radius: 0.625rem;
+ border: 1px solid var(--border-subtle);
+ background: color-mix(in srgb, var(--card) 55%, transparent);
+ padding: 0.125rem 0.25rem;
+ --thought-body-margin: 0;
+ --thought-body-padding: 0.375rem 0.5rem 0.5rem;
+ --thought-body-bl: 0;
+ --thought-body-bt: 1px solid var(--border-subtle);
+}
+:root[data-agent-style='cards'] .live[data-live-style='cards'] {
+ border-radius: 0.75rem;
+ border: 1px solid color-mix(in srgb, var(--brand-accent) 35%, var(--border));
+ background: var(--card);
+ padding: 0.4375rem 0.75rem;
+}
+:root[data-agent-style='cards'] .todo-dock {
+ border-radius: 0.75rem;
+ border-color: var(--border);
+ background: var(--card);
+}
+
+/* 2. Compact Pill Stream — horizontal wrapping pills for reads/searches, cards for edits/commands & expanded pills */
+:root[data-agent-style='pills'] .work {
+ --block-body-ml: 0;
+ --block-body-pl: 0;
+ --block-body-bl: 0;
+ --block-body-direction: row;
+ --block-body-wrap: wrap;
+ --block-body-align: center;
+ --block-body-gap: 0.375rem;
+ --block-body-pt: 0.3125rem;
+}
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='read'], [data-step-kind='list'], [data-step-kind='search'], [data-step-kind='web']):not(:has(> .row > .head[aria-expanded='true'])) {
+ flex: 0 1 auto;
+ width: fit-content;
+ max-width: 100%;
+ border-radius: 9999px;
+ border: 1px solid var(--border);
+ background: var(--card);
+ --step-head-padding: 0.2rem 0.625rem;
+ --step-head-gap: 0.375rem;
+ --step-head-font-size: var(--text-xs);
+ --step-head-radius: 9999px;
+ transition: border-color var(--motion-instant) var(--motion-ease), background-color var(--motion-instant) var(--motion-ease);
+}
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='read'], [data-step-kind='list'], [data-step-kind='search'], [data-step-kind='web']):not(:has(> .row > .head[aria-expanded='true'])):hover {
+ border-color: var(--border-hover);
+ background: var(--surface-hover);
+}
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='read'], [data-step-kind='list'], [data-step-kind='search'], [data-step-kind='web'])[data-step-running='true']:not(:has(> .row > .head[aria-expanded='true'])) {
+ border-color: color-mix(in srgb, var(--brand-accent) 55%, var(--border));
+ background: color-mix(in srgb, var(--brand-accent) 7%, var(--card));
+}
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='read'], [data-step-kind='list'], [data-step-kind='search'], [data-step-kind='web']):not(:has(> .row > .head[aria-expanded='true'])) .flex-1 {
+ display: none;
+}
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='read'], [data-step-kind='list'], [data-step-kind='search'], [data-step-kind='web']):not(:has(> .row > .head[aria-expanded='true'])) .chip {
+ max-width: 15rem;
+}
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='read'], [data-step-kind='list'], [data-step-kind='search'], [data-step-kind='web']):not(:has(> .row > .head[aria-expanded='true'])) .step-icon {
+ width: 0.75rem;
+ height: 0.75rem;
+}
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='read'], [data-step-kind='list'], [data-step-kind='search'], [data-step-kind='web']):has(> .row > .head[aria-expanded='true']),
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:is([data-step-kind='edit'], [data-step-kind='command'], [data-step-kind='other']),
+:root[data-agent-style='pills'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-thought, .disclosure.level-subagent) {
+ flex: 1 0 100%;
+ width: 100%;
+ min-width: 0;
+ border-radius: 0.75rem;
+ border: 1px solid var(--border);
+ background: var(--card);
+ padding: 0.125rem 0.25rem;
+ --step-body-indent: 0.5rem;
+ --step-body-padding: 0.5rem;
+ --step-body-bt: 1px solid var(--border-subtle);
+ --step-term-bg: var(--background);
+ --thought-body-margin: 0;
+ --thought-body-padding: 0.375rem 0.5rem 0.5rem;
+ --thought-body-bl: 0;
+ --thought-body-bt: 1px solid var(--border-subtle);
+}
+:root[data-agent-style='pills'] .live[data-live-style='pills'] {
+ width: fit-content;
+ border-radius: 9999px;
+ border: 1px solid color-mix(in srgb, var(--brand-accent) 40%, var(--border));
+ background: var(--card);
+ padding: 0.25rem 0.75rem;
+}
+:root[data-agent-style='pills'] .todo-dock {
+ border-radius: 1rem;
+}
+
+/* 3. Spotlight Focus — quiet compact settled steps, elevated focus card for active work */
+:root[data-agent-style='spotlight'] .work {
+ --block-body-ml: 0.25rem;
+ --block-body-pl: 0;
+ --block-body-bl: 0;
+ --block-body-gap: 0.1875rem;
+ --block-body-pt: 0.1875rem;
+}
+:root[data-agent-style='spotlight'] :is(.work > .disclosure.level-block > .body, .work-single) > .disclosure:is(.level-step, .level-thought):not([data-step-running='true']):not(:has(> .row > .head[aria-expanded='true'])):not(:has(.is-error)):not(:has(.is-approval)) > .row {
+ opacity: 0.62;
+ transition: opacity var(--motion-instant) var(--motion-ease);
+}
+:root[data-agent-style='spotlight'] :is(.work > .disclosure.level-block > .body, .work-single) > .disclosure:is(.level-step, .level-thought):not([data-step-running='true']):is(:hover, :focus-within) > .row {
+ opacity: 1;
+}
+:root[data-agent-style='spotlight'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure:is(.level-step, .level-thought)[data-step-running='true'],
+:root[data-agent-style='spotlight'] .live[data-live-style='spotlight'] {
+ position: relative;
+ overflow: hidden;
+ margin-block: 0.25rem;
+ border-radius: 0.875rem;
+ border: 1px solid color-mix(in srgb, var(--brand-accent) 50%, var(--border));
+ background: var(--card);
+ box-shadow: 0 4px 16px rgb(0 0 0 / 0.08), 0 1px 3px rgb(0 0 0 / 0.05);
+}
+:root.dark[data-agent-style='spotlight'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure:is(.level-step, .level-thought)[data-step-running='true'],
+:root.dark[data-agent-style='spotlight'] .live[data-live-style='spotlight'] {
+ box-shadow: 0 6px 22px rgb(0 0 0 / 0.32), 0 1px 3px rgb(0 0 0 / 0.2);
+}
+:root[data-agent-style='spotlight'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure:is(.level-step, .level-thought)[data-step-running='true'] {
+ padding: 0.1875rem 0.3125rem;
+ --step-body-indent: 0.5rem;
+}
+:root[data-agent-style='spotlight'] .live[data-live-style='spotlight'] {
+ padding: 0.4375rem 0.75rem;
+}
+:root[data-agent-style='spotlight'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure:is(.level-step, .level-thought)[data-step-running='true']::before,
+:root[data-agent-style='spotlight'] .live[data-live-style='spotlight']::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 35%;
+ height: 2px;
+ background: linear-gradient(90deg, transparent, var(--brand-accent), transparent);
+ animation: agent-rail-slide 1.5s ease-in-out infinite;
+}
+
+/* 4. Structured Icon Rail — vertical timeline spine with true circular icon nodes centered on the spine */
+:root[data-agent-style='rail'] .work-multi > .disclosure.level-block {
+ --block-body-ml: 1rem;
+ --block-body-pl: 1rem;
+ --block-body-bl: 1.5px solid var(--border);
+ --block-body-gap: 0.375rem;
+ --block-body-pt: 0.25rem;
+ --step-head-padding: 0.3125rem 0.5rem 0.3125rem 0;
+ --thought-head-padding: 0.3125rem 0.5rem 0.3125rem 0;
+ --step-body-indent: 0.5rem;
+ --thought-body-margin: 0.125rem 0 0.375rem 0;
+ --thought-body-padding: 0.125rem 0.5rem;
+ --thought-body-bl: 0;
+}
+:root[data-agent-style='rail'] .work > .disclosure.level-block > .body > .disclosure.level-step > .row > .head > .step-icon,
+:root[data-agent-style='rail'] :is(.work-single, .work-waiting) > .disclosure.level-step > .row > .head > .step-icon {
+ width: 1.375rem;
+ height: 1.375rem;
+ padding: 0.25rem;
+ border-radius: 9999px;
+ border: 1px solid var(--border-hover);
+ background: var(--card);
+ color: var(--muted-foreground);
+ box-shadow: 0 0 0 3px var(--background);
+ transition: border-color var(--motion-instant) var(--motion-ease), color var(--motion-instant) var(--motion-ease), background-color var(--motion-instant) var(--motion-ease);
+}
+:root[data-agent-style='rail'] .work > .disclosure.level-block > .body > .disclosure.level-step > .row > .head > .step-icon {
+ margin-left: calc(-1rem - 0.6875rem - 0.75px);
+ margin-right: 0.125rem;
+}
+:root[data-agent-style='rail'] .work > .disclosure.level-block > .body > .disclosure.level-thought > .row > .head::before {
+ content: '';
+ width: 0.5625rem;
+ height: 0.5625rem;
+ flex-shrink: 0;
+ border-radius: 9999px;
+ border: 1.5px solid var(--border-hover);
+ background: var(--background);
+ box-shadow: 0 0 0 3px var(--background);
+ margin-left: calc(-1rem - 0.28125rem - 0.75px);
+ margin-right: 0.53125rem;
+}
+:root[data-agent-style='rail'] .work > .disclosure.level-block > .body > .disclosure.level-thought[data-step-running='true'] > .row > .head::before {
+ border-color: var(--brand-accent);
+ background: var(--brand-accent);
+}
+:root[data-agent-style='rail'] .work .disclosure.level-step[data-step-kind='edit'] > .row > .head > .step-icon {
+ border-color: color-mix(in srgb, var(--brand-accent) 55%, var(--border));
+ color: var(--brand-accent);
+}
+:root[data-agent-style='rail'] .work .disclosure.level-step[data-step-kind='command'] > .row > .head > .step-icon {
+ border-color: color-mix(in srgb, var(--success) 50%, var(--border));
+ color: var(--success);
+}
+:root[data-agent-style='rail'] .work .disclosure.level-step[data-step-kind='search'] > .row > .head > .step-icon {
+ border-color: color-mix(in srgb, var(--accent-sky) 45%, var(--border));
+ color: var(--accent-sky);
+}
+:root[data-agent-style='rail'] .work .disclosure.level-step[data-step-kind='web'] > .row > .head > .step-icon {
+ border-color: color-mix(in srgb, var(--accent-violet) 45%, var(--border));
+ color: var(--accent-violet);
+}
+:root[data-agent-style='rail'] .work .disclosure.level-step[data-step-running='true'] > .row > .head > .step-icon {
+ border-color: var(--brand-accent);
+ background: color-mix(in srgb, var(--brand-accent) 12%, var(--card));
+ color: var(--brand-accent);
+}
+:root[data-agent-style='rail'] .work .disclosure.level-step > .row > .head > .step-icon.is-error {
+ border-color: var(--error);
+ color: var(--error);
+}
+:root[data-agent-style='rail'] .work .disclosure.level-step > .row > .head > .step-icon.is-approval {
+ border-color: var(--warning);
+ color: var(--warning);
+}
+:root[data-agent-style='rail'] .live[data-live-style='rail'] {
+ margin-left: 0.375rem;
+ padding-left: 0.75rem;
+ border-left: 1.5px solid var(--brand-accent);
+ border-radius: 0;
+}
+
+/* 5. Accent-Railed Cards — flush cards with kind-coded 3px left bar, zero outer hairline */
+:root[data-agent-style='accented'] .work {
+ --block-body-ml: 0;
+ --block-body-pl: 0;
+ --block-body-bl: 0;
+ --block-body-gap: 0.375rem;
+ --block-body-pt: 0.25rem;
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-thought, .disclosure.level-subagent) {
+ border-radius: 0 0.625rem 0.625rem 0;
+ border: 1px solid var(--border-subtle);
+ border-left: 3px solid color-mix(in srgb, var(--foreground) 24%, transparent);
+ background: var(--card);
+ padding: 0.125rem 0.375rem;
+ --step-body-indent: 0.5rem;
+ --step-body-padding: 0.5rem;
+ --step-body-bt: 1px solid var(--border-subtle);
+ --step-term-bg: var(--background);
+ --thought-body-margin: 0;
+ --thought-body-padding: 0.375rem 0.5rem 0.5rem;
+ --thought-body-bl: 0;
+ --thought-body-bt: 1px solid var(--border-subtle);
+ transition: border-color var(--motion-instant) var(--motion-ease);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='search'] {
+ border-left-color: var(--accent-sky);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='web'] {
+ border-left-color: var(--accent-violet);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='edit'] {
+ border-left-color: var(--brand-accent);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='command'] {
+ border-left-color: var(--success);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='command'][data-step-running='true'] {
+ border-left-color: var(--warning);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-thought {
+ border-left-color: color-mix(in srgb, var(--muted-foreground) 32%, transparent);
+ background: color-mix(in srgb, var(--card) 65%, transparent);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-subagent {
+ border-left-color: var(--companion);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:has(.step-icon.is-error) {
+ border-left-color: var(--error);
+}
+:root[data-agent-style='accented'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:has(.step-icon.is-approval) {
+ border-left-color: var(--warning);
+}
+:root[data-agent-style='accented'] .live[data-live-style='accented'] {
+ border-radius: 0 0.625rem 0.625rem 0;
+ border: 1px solid var(--border-subtle);
+ border-left: 3px solid var(--brand-accent);
+ background: var(--card);
+ padding: 0.4375rem 0.75rem;
+}
+:root[data-agent-style='accented'] .todo-dock {
+ border-radius: 0 0.75rem 0.75rem 0;
+ border-left: 3px solid var(--brand-accent);
+}
+
+/* 6. Notebook Cells — bordered cells with crisp full-height 3.5rem left gutter */
+:root[data-agent-style='notebook'] .work {
+ --block-body-ml: 0;
+ --block-body-pl: 0;
+ --block-body-bl: 0;
+ --block-body-gap: 0.375rem;
+ --block-body-pt: 0.25rem;
+}
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-thought, .disclosure.level-subagent) {
+ position: relative;
+ border-radius: 0.625rem;
+ border: 1px solid var(--border);
+ background: var(--card);
+ overflow: hidden;
+ --step-head-padding: 0 0.5rem 0 0;
+ --step-head-gap: 0.625rem;
+ --step-head-min-h: 2.125rem;
+ --step-head-radius: 0;
+ --thought-head-padding: 0 0.5rem 0 0;
+ --thought-head-gap: 0.625rem;
+ --thought-head-min-h: 2.125rem;
+ --thought-head-radius: 0;
+ --subagent-head-padding: 0 0.5rem 0 0;
+ --subagent-head-min-h: 2.125rem;
+ --subagent-head-radius: 0;
+ --step-body-padding: 0.5rem 0.625rem 0.5rem 4.125rem;
+ --step-body-bt: 1px solid var(--border-subtle);
+ --step-term-bg: var(--background);
+ --thought-body-margin: 0;
+ --thought-body-padding: 0.375rem 0.625rem 0.5rem 4.125rem;
+ --thought-body-bl: 0;
+ --thought-body-bt: 1px solid var(--border-subtle);
+ --subagent-body-ml: 0;
+ --subagent-body-padding: 0.5rem 0.625rem 0.5rem 4.125rem;
+ --subagent-body-bl: 0;
+ --subagent-body-bt: 1px solid var(--border-subtle);
+}
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-thought, .disclosure.level-subagent)::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 3.5rem;
+ background: color-mix(in srgb, var(--foreground) 3%, var(--background));
+ border-right: 1px solid var(--border-subtle);
+ pointer-events: none;
+ z-index: 0;
+}
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-thought, .disclosure.level-subagent)[data-step-running='true']::before {
+ background: color-mix(in srgb, var(--brand-accent) 9%, var(--background));
+}
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-thought, .disclosure.level-subagent) > :is(.row, .body) {
+ position: relative;
+ z-index: 1;
+}
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step > .row > .head > .step-icon {
+ display: none;
+}
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > :is(.disclosure.level-step, .disclosure.level-thought, .disclosure.level-subagent) > .row > .head::before {
+ content: 'STEP';
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 3.5rem;
+ flex-shrink: 0;
+ font-family: var(--font-mono);
+ font-size: 0.625rem;
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ color: var(--muted-foreground);
+}
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='read'] > .row > .head::before { content: 'READ'; }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='list'] > .row > .head::before { content: 'LIST'; }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='search'] > .row > .head::before { content: 'FIND'; color: var(--accent-sky); }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='edit'] > .row > .head::before { content: 'DIFF'; color: var(--brand-accent); }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='command'] > .row > .head::before { content: 'RUN'; color: var(--success); }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step[data-step-kind='web'] > .row > .head::before { content: 'WEB'; color: var(--accent-violet); }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-thought > .row > .head::before { content: 'THINK'; }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-subagent > .row > .head::before { content: 'AGENT'; color: var(--companion); }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:has(.step-icon.is-error) > .row > .head::before { color: var(--error); }
+:root[data-agent-style='notebook'] :is(.work > .disclosure.level-block > .body, .work-single, .work-waiting) > .disclosure.level-step:has(.step-icon.is-approval) > .row > .head::before { content: 'ASK'; color: var(--warning); }
+:root[data-agent-style='notebook'] .live[data-live-style='notebook'] {
+ position: relative;
+ overflow: hidden;
+ border-radius: 0.625rem;
+ border: 1px solid color-mix(in srgb, var(--brand-accent) 42%, var(--border));
+ background: var(--card);
+ padding: 0 0.625rem 0 0;
+ min-height: 2.125rem;
+ gap: 0.625rem;
+}
+:root[data-agent-style='notebook'] .live[data-live-style='notebook']::before {
+ content: 'LIVE';
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ align-self: stretch;
+ width: 3.5rem;
+ flex-shrink: 0;
+ background: color-mix(in srgb, var(--brand-accent) 9%, var(--background));
+ border-right: 1px solid var(--border-subtle);
+ font-family: var(--font-mono);
+ font-size: 0.625rem;
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ color: var(--brand-accent);
+}
+
+/* 7. Unified Work Sheet — single bordered Desktop sheet with clean hairline dividers */
+:root[data-agent-style='sheet'] .work-multi > .disclosure.level-block,
+:root[data-agent-style='sheet'] :is(.work-single, .work-waiting) > .disclosure {
+ border-radius: 0.875rem;
+ border: 1px solid var(--border);
+ background: var(--card);
+ overflow: hidden;
+ --block-body-ml: 0;
+ --block-body-pl: 0;
+ --block-body-bl: 0;
+ --block-body-gap: 0;
+ --step-head-radius: 0.375rem;
+ --thought-head-radius: 0.375rem;
+ --subagent-head-radius: 0.375rem;
+ --step-term-bg: var(--background);
+ --thought-body-margin: 0.125rem 0 0.375rem 0.5rem;
+ --thought-body-padding: 0.125rem 0.5rem 0.25rem;
+ --thought-body-bl: 0;
+}
+:root[data-agent-style='sheet'] :is(.work-single, .work-waiting) > .disclosure {
+ padding: 0.125rem 0.4375rem;
+}
+:root[data-agent-style='sheet'] .work-multi > .disclosure.level-block > .row {
+ padding: 0.25rem 0.4375rem;
+ background: color-mix(in srgb, var(--foreground) 2.5%, transparent);
+}
+:root[data-agent-style='sheet'] .work-multi > .disclosure.level-block > .body {
+ border-top: 1px solid var(--border-subtle);
+}
+:root[data-agent-style='sheet'] .work-multi > .disclosure.level-block > .body > .disclosure {
+ padding: 0.125rem 0.4375rem;
+ border-bottom: 1px solid var(--border-subtle);
+ transition: background-color var(--motion-instant) var(--motion-ease);
+}
+:root[data-agent-style='sheet'] .work-multi > .disclosure.level-block > .body > .disclosure:hover {
+ background: color-mix(in srgb, var(--foreground) 2%, transparent);
+}
+:root[data-agent-style='sheet'] .work-multi > .disclosure.level-block > .body > .disclosure:last-child {
+ border-bottom: 0;
+}
+:root[data-agent-style='sheet'] .live[data-live-style='sheet'] {
+ border-radius: 0.875rem;
+ border: 1px solid var(--border);
+ background: var(--card);
+ padding: 0.4375rem 0.75rem;
+}
+:root[data-agent-style='sheet'] .todo-dock {
+ border-radius: 0.875rem;
+ border-color: var(--border);
+ background: var(--card);
+}
+
+/* 8. Whisper Minimal — calm borderless tonal prose flow */
+:root[data-agent-style='minimal'] .work {
+ --block-body-ml: 0.5rem;
+ --block-body-pl: 0;
+ --block-body-bl: 0;
+ --block-body-gap: 2px;
+ --step-surface-border: transparent;
+ --step-surface-bg: color-mix(in srgb, var(--foreground) 3%, transparent);
+ --step-term-bg: color-mix(in srgb, var(--foreground) 3%, transparent);
+ --thought-body-bl: 0;
+ --thought-body-margin: 0.125rem 0 0.375rem 0.25rem;
+ --thought-body-padding: 0.125rem 0.5rem;
+ --subagent-body-bl: 0;
+}
+:root[data-agent-style='minimal'] .work .disclosure.level-step .step-icon:not(.is-error):not(.is-approval),
+:root[data-agent-style='minimal'] .work .disclosure.level-step .duration {
+ opacity: 0.45;
+}
+:root[data-agent-style='minimal'] .work .disclosure.level-step .chip {
+ background: transparent;
+ padding-inline: 0;
+}
+:root[data-agent-style='minimal'] .work .diff-card {
+ border-color: transparent;
+ background: color-mix(in srgb, var(--foreground) 3%, transparent);
+}
+:root[data-agent-style='minimal'] .work .diff-head {
+ border-bottom-color: var(--border-subtle);
+}
+:root[data-agent-style='minimal'] .live[data-live-style='minimal'] {
+ background: transparent;
+ border-color: transparent;
+ padding-inline: 0.5rem;
+}
+:root[data-agent-style='minimal'] .todo-dock {
+ border-color: transparent;
+ background: transparent;
+}
+:root[data-agent-style='minimal'] .todo-progress { opacity: 0.45; }
+
+@media (prefers-reduced-motion: reduce) {
+ :root[data-agent-style='cards'] .disclosure.level-step[data-step-running='true']::before,
+ :root[data-agent-style='spotlight'] .disclosure:is(.level-step, .level-thought)[data-step-running='true']::before,
+ :root[data-agent-style='spotlight'] .live[data-live-style='spotlight']::before {
+ animation: none;
+ }
+}
+html.a11y-reduce-motion :root[data-agent-style='cards'] .disclosure.level-step[data-step-running='true']::before,
+html.a11y-reduce-motion :root[data-agent-style='spotlight'] .disclosure:is(.level-step, .level-thought)[data-step-running='true']::before,
+html.a11y-reduce-motion :root[data-agent-style='spotlight'] .live[data-live-style='spotlight']::before {
+ animation: none;
+}
+
.composer-bar {
display: flex;
min-height: 1.875rem;
@@ -1706,6 +2271,26 @@ textarea {
);
}
+.ui-bottom-fade {
+ position: relative;
+}
+
+.ui-bottom-fade::after {
+ content: '';
+ position: absolute;
+ inset-inline: 0;
+ bottom: 0;
+ z-index: 4;
+ height: 1.75rem;
+ pointer-events: none;
+ background: linear-gradient(
+ to bottom,
+ transparent,
+ color-mix(in srgb, var(--ui-top-fade-from, var(--background)) 62%, transparent) 65%,
+ var(--ui-top-fade-from, var(--background))
+ );
+}
+
/* A rounded field on a muted fill: the browser address bar, the dock's run box. */
.ui-pill-field {
display: flex;
diff --git a/apps/desktop/renderer/src/lib/components/layout/AppShell.svelte b/apps/desktop/renderer/src/lib/components/layout/AppShell.svelte
index 2e545a39..7352d840 100644
--- a/apps/desktop/renderer/src/lib/components/layout/AppShell.svelte
+++ b/apps/desktop/renderer/src/lib/components/layout/AppShell.svelte
@@ -158,12 +158,12 @@
const target = event.target as HTMLElement;
const inInput = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;
- if (ctrl && event.key === 'k' && !event.shiftKey) {
+ if (ctrl && event.key.toLowerCase() === 'k' && !event.shiftKey) {
event.preventDefault();
startNewSession();
return;
}
- if (ctrl && event.key === 'k' && event.shiftKey) {
+ if (ctrl && event.key.toLowerCase() === 'k' && event.shiftKey) {
event.preventDefault(); appStore.openSearch(); return;
}
if (ctrl && event.key === ',') {
@@ -181,6 +181,13 @@
closeSettings();
return;
}
+ if (ctrl && event.altKey && !event.shiftKey && event.code === 'Digit0' && !settingsShowing) {
+ if (appStore.activeTab === 'code' && appStore.currentChat?.projectId) {
+ event.preventDefault();
+ workspaceLayout.scoped(conversationScope(appStore.currentChat.id)).toggle('session');
+ }
+ return;
+ }
if (ctrl && event.key === 'b') {
event.preventDefault();
// There is no sidebar to show while Settings owns the window.
diff --git a/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte b/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte
index e091ef9c..ca55b948 100644
--- a/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte
+++ b/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte
@@ -12,6 +12,7 @@
-{#snippet pane(id: string, label: string, pressed: boolean, onclick: () => void, icon: typeof Activity, badge: Snippet | null = null, text: string | null = null)}
+{#snippet pane(id: string, label: string, pressed: boolean, onclick: () => void, icon: typeof Activity, badge: Snippet | null = null)}
{@const Icon = icon}
-
+
- {#if text}{text} {/if}
{#if badge}{@render badge()}{/if}
@@ -107,7 +177,10 @@
{#snippet changesBadge()}
{#if changes?.files.length}
- +{groupedNumber(changeTotals.add)} −{groupedNumber(changeTotals.del)}
+
+ +{compactCount(changeTotals.add)}
+ −{compactCount(changeTotals.del)}
+
{/if}
{/snippet}
@@ -115,152 +188,139 @@
{groupedNumber(remainingTasks)}
{/snippet}
-{#snippet boardBadge()}
-
- 0} aria-hidden="true">{boardTally.review || boardTally.working}
-{/snippet}
-
event.stopPropagation()}>
-
-
- {#if inCode}
-
{@render pane('session', projectControls.open ? $t('sessionHud.fold') : $t('sessionHud.open'), projectControls.open, () => projectControls.toggle(), PanelsTopLeft)}
- {/if}
-
- {#if chat}
- {#if inCode}
- {@render pane('changes', $t('codeWs.changes'), workspaceLayout.isOpen('changes'), () => workspaceLayout.toggle('changes'), GitCompareArrows, changesBadge, $t('codeWs.changes'))}
- {@render pane('files', $t('codeWs.files'), workspaceLayout.isOpen('files'), () => workspaceLayout.toggle('files'), FolderTree, null, $t('codeWs.files'))}
+ {#if chat}
+
+ {#if inCode}
+ {@const changesLabel = changes?.files.length ? `${$t('codeWs.changes')} (+${groupedNumber(changeTotals.add)} −${groupedNumber(changeTotals.del)})` : $t('codeWs.changes')}
+ {@render pane('changes', changesLabel, workspaceLayout.isOpen('changes'), () => workspaceLayout.toggle('changes'), GitCompareArrows, changes?.files.length ? changesBadge : null)}
+ {@render pane('files', $t('codeWs.files'), workspaceLayout.isOpen('files'), () => workspaceLayout.toggle('files'), FolderTree)}
+ {@render pane('terminal', $t('codeWs.terminal'), terminalOpen, () => void toggleTerminal(), SquareTerminal)}
+ {@const sessionOpen = workspaceLayout.isOpen('session')}
+
{@render pane('session', sessionOpen ? $t('sessionHud.fold') : $t('sessionHud.open'), sessionOpen, () => workspaceLayout.toggle('session'), PanelsTopLeft)}
+
+
+ {#snippet trigger(props)}
+
+
+
+ {#if secondaryOpen} {/if}
+
+
+ {/snippet}
+
+
+
+ void toggleProcesses()} />
+ workspaceLayout.toggle('canvas')} />
{#if boardShown}
- {@render pane('board', $t('code.swarm.board'), workspaceLayout.isOpen('board'), () => workspaceLayout.toggle('board'), LayoutGrid, boardTally.review || boardTally.working ? boardBadge : null, $t('code.swarm.board'))}
+ workspaceLayout.toggle('board')}
+ >
+
+ {#if boardTally.review || boardTally.working}
+ 0}>{boardTally.review || boardTally.working}
+ {/if}
+
+ {/if}
+
+ {#if checkpoints.length}
+
+ {$t('code.historyTitle')}
+ {#each checkpoints as checkpoint (checkpoint.turnIndex)}
+ confirmRestore(checkpoint.turnIndex)}>
+
+ {timeLabel(checkpoint.createdAt)}
+ · {say.files(checkpoint.fileCount)}
+
+
+ +{compactCount(checkpoint.additions)}
+ −{compactCount(checkpoint.deletions)}
+
+
+ {/each}
{/if}
- {/if}
-
- {#if !inCode}
- {@render pane('tasks', $t('code.todosTitle'), workspaceLayout.isOpen('tasks'), () => workspaceLayout.toggle('tasks'), ListChecks, remainingTasks ? tasksBadge : null, $t('code.todosTitle'))}
- {/if}
- {#if inCode}
- {@render pane('terminal', $t('codeWs.terminal'), terminalOpen, () => void toggleTerminal(), SquareTerminal)}
- {/if}
- {@render pane('browser', $t('browser.title'), browserPanelStore.open, () => void browserPanelStore.toggle().catch((error) => toastStore.error(String(error))), Globe)}
- {#if !inCode}
- {@render pane('context', $t('context.button'), workspaceLayout.isOpen('context'), () => workspaceLayout.toggle('context'), ContextIcon)}
- {/if}
+
+ {:else}
+ {@render pane('tasks', $t('code.todosTitle'), workspaceLayout.isOpen('tasks'), () => workspaceLayout.toggle('tasks'), ListChecks, remainingTasks ? tasksBadge : null)}
+ {@render pane('browser', $t('browser.title'), browserPanelStore.open, toggleBrowser, Globe)}
+ {@render pane('context', $t('context.button'), workspaceLayout.isOpen('context'), () => workspaceLayout.toggle('context'), ContextIcon)}
{/if}
-
-
- {#if inCode && checkpoints.length}
-
- {#snippet trigger(props)}
-
-
-
-
-
- {/snippet}
- {$t('code.historyTitle')}
- {#each checkpoints as checkpoint (checkpoint.turnIndex)}
- confirmRestore(checkpoint.turnIndex)}>
-
- {timeLabel(checkpoint.createdAt)}
- · {say.files(checkpoint.fileCount)}
-
-
- +{checkpoint.additions}
- −{checkpoint.deletions}
-
-
- {/each}
-
- {/if}
-
+ {/if}
diff --git a/apps/desktop/renderer/src/lib/components/layout/Titlebar.svelte b/apps/desktop/renderer/src/lib/components/layout/Titlebar.svelte
index c892e0d5..10952b7e 100644
--- a/apps/desktop/renderer/src/lib/components/layout/Titlebar.svelte
+++ b/apps/desktop/renderer/src/lib/components/layout/Titlebar.svelte
@@ -25,6 +25,7 @@
import WindowControls from './WindowControls.svelte';
import { PanelRight as ContextIcon } from '$lib/icons';
import ComputerButton from '$lib/features/computer/ComputerButton.svelte';
+ import { computerStore } from '$lib/features/computer/computer.svelte';
import NotificationsButton from '$lib/features/shared/NotificationsButton.svelte';
let { sidebarPreview = false, settingsOpen = false, onSidebarEnter, onSidebarLeave, onSidebarToggle }: {
@@ -56,6 +57,15 @@
});
// Settings owns the window: a conversation's pane toggles have nothing to act on there.
const toolsHere = $derived(!settingsOpen && workspaceLayout.panes.length < 2);
+ // Auto-hide idle utilities in Code to keep the titlebar calm; Computer use
+ // stays reachable in Session → Connections when ready and pops up here while active.
+ const computerActive = $derived(['active', 'preparing', 'paused', 'requesting'].includes(computerStore.state.phase));
+ const showComputer = $derived(
+ !settingsOpen &&
+ !!appStore.currentChat &&
+ (appStore.activeSpace === 'home' || (appStore.activeSpace === 'code' && computerActive))
+ );
+ const showDownloads = $derived(downloadsStore.hasActive || downloadsStore.jobs.length > 0);
const platform = typeof window !== 'undefined' ? (window.electronAPI?.platform ?? 'linux') : 'linux';
const isMac = platform === 'darwin';
@@ -110,19 +120,19 @@
{/if}
{/if}
- {#if !settingsOpen && appStore.currentChat && (appStore.activeSpace === 'home' || appStore.activeSpace === 'code')}
+ {#if showComputer}
{/if}
-
+ {#if showDownloads}
+
+ {/if}
- {
const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
themeStore.toggle({ x: r.left + r.width / 2, y: r.top + r.height / 2 });
}}
-
>
{#if themeStore.current === 'dark'}
diff --git a/apps/desktop/renderer/src/lib/components/layout/WorkspaceHost.svelte b/apps/desktop/renderer/src/lib/components/layout/WorkspaceHost.svelte
index e5e5b531..c5c578be 100644
--- a/apps/desktop/renderer/src/lib/components/layout/WorkspaceHost.svelte
+++ b/apps/desktop/renderer/src/lib/components/layout/WorkspaceHost.svelte
@@ -287,7 +287,7 @@
diff --git a/apps/desktop/renderer/src/lib/features/code/CodeComposer.svelte b/apps/desktop/renderer/src/lib/features/code/CodeComposer.svelte
index 3f0cabbf..b73545bc 100644
--- a/apps/desktop/renderer/src/lib/features/code/CodeComposer.svelte
+++ b/apps/desktop/renderer/src/lib/features/code/CodeComposer.svelte
@@ -34,7 +34,8 @@
import GenerationSpeed from '$lib/features/shared/composer/GenerationSpeed.svelte';
import { latestGenerationSpeed } from '$lib/utils/generation-speed';
import ContextUsageRing from '$lib/features/chat/composer/ContextUsageRing.svelte';
- import { projectControls } from './workspace/project-controls.svelte';
+ import { conversationScope } from '$shared/workspace-scope';
+ import { workspaceLayout } from '$lib/stores/workspace-layout.svelte';
import { codeStore } from './code.svelte';
import { initProject, projectFiles, setAgenteModel } from './code-ipc';
import { restoreCodeEdits } from './code-edits';
@@ -806,7 +807,8 @@
{/snippet}
{#snippet microphone()} {/snippet}
{#snippet trailing()}
- {#if showContextRing && usage && !(projectControls.open && chat.projectId)}
+ {@const sessionOpen = !!chat.projectId && (workspaceLayout.layouts[conversationScope(chat.id)]?.open.includes('session') ?? false)}
+ {#if showContextRing && usage && !sessionOpen}
{/if}
{/snippet}
diff --git a/apps/desktop/renderer/src/lib/features/code/CodeLiveStatus.svelte b/apps/desktop/renderer/src/lib/features/code/CodeLiveStatus.svelte
index 0b588373..623dd9fc 100644
--- a/apps/desktop/renderer/src/lib/features/code/CodeLiveStatus.svelte
+++ b/apps/desktop/renderer/src/lib/features/code/CodeLiveStatus.svelte
@@ -14,12 +14,15 @@
import { codeRunElapsed, type CodeRunState } from './code-run';
import { toolKind } from '$shared/tool-kinds';
import TileMeter from '$lib/components/ui/TileMeter.svelte';
+ import { appearanceStore } from '$lib/stores/appearance.svelte';
import { liveStatus, QUIET_MS, type LiveStatus } from './work-blocks';
import { runMeterMode, type MeterRun } from './tile-meter';
type LiveRun = MeterRun & Pick & Partial>;
let { run, awaitingApproval = false }: { run: LiveRun; awaitingApproval?: boolean } = $props();
+ const agentStyle = $derived(appearanceStore.prefs.agentStyle);
+
let now = $state(Date.now());
$effect(() => {
const timer = setInterval(() => (now = Date.now()), 500);
@@ -78,7 +81,7 @@
{#if status.kind !== 'approval'}
-
+
{label}
diff --git a/apps/desktop/renderer/src/lib/features/code/CodeSurface.svelte b/apps/desktop/renderer/src/lib/features/code/CodeSurface.svelte
index 53f60613..9853c074 100644
--- a/apps/desktop/renderer/src/lib/features/code/CodeSurface.svelte
+++ b/apps/desktop/renderer/src/lib/features/code/CodeSurface.svelte
@@ -25,6 +25,7 @@
import CodeTranscript from './CodeTranscript.svelte';
import CodeComposer from './CodeComposer.svelte';
import SubagentPill from './SubagentPill.svelte';
+ import TasksPanel from './TasksPanel.svelte';
import { isCodeSession } from '$lib/features/shared/session-guards';
import type { ChatSession } from '$lib/types/chat';
import { spaceVisible } from '$lib/components/layout/space-visibility';
@@ -189,7 +190,7 @@
first message never remounts it and never drops the keyboard. -->
{#if unlinked}
-
+
{#key chat.id} {/key}
{:else if empty}
@@ -202,7 +203,7 @@
{/if}
{:else}
-
+
{#key chat.id} {/key}
{/if}
@@ -212,7 +213,7 @@
{$t('code.unlinkedHint')}
{:else}
- {#key chat.id}
{/key}
+ {#key chat.id}
{/key}
{#if empty}
@@ -261,4 +262,6 @@
.empty-project-path { overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--font-mono);font-size:var(--text-xs); }
.empty-links { margin-top:0.75rem; }
+ .chat-todos-wrap { flex-shrink: 0; margin-top: 0.375rem; margin-bottom: 0.25rem; }
+ .chat-todos-wrap:empty { display: none; }
diff --git a/apps/desktop/renderer/src/lib/features/code/CodeThoughtRow.svelte b/apps/desktop/renderer/src/lib/features/code/CodeThoughtRow.svelte
index d733966a..e4c791a5 100644
--- a/apps/desktop/renderer/src/lib/features/code/CodeThoughtRow.svelte
+++ b/apps/desktop/renderer/src/lib/features/code/CodeThoughtRow.svelte
@@ -35,7 +35,7 @@
onDestroy(() => { if (scrollFrame) cancelAnimationFrame(scrollFrame); });
-
+
{#snippet header()}
{#if live} {/if}
{live ? $t('code.thinking') : $t('code.thought')}
@@ -54,13 +54,18 @@
.thought-body {
max-height: 16rem;
overflow-y: auto;
+ padding-block: 0.75rem;
white-space: pre-wrap;
overflow-wrap: anywhere;
color: var(--muted-foreground);
+ mask-image: linear-gradient(to bottom, transparent 0%, #000 0.75rem, #000 calc(100% - 0.75rem), transparent 100%);
+ -webkit-mask-image: linear-gradient(to bottom, transparent 0%, #000 0.75rem, #000 calc(100% - 0.75rem), transparent 100%);
}
- /* Live: a short window on the newest lines, fading out at the top. */
+ /* Live: a short window on the newest lines, fading cleanly at both top and bottom. */
.thought-body.is-live {
max-height: 7.5rem;
- mask-image: linear-gradient(to bottom, transparent, #000 1.5rem);
+ padding-block: 0.875rem;
+ mask-image: linear-gradient(to bottom, transparent 0%, #000 0.875rem, #000 calc(100% - 0.875rem), transparent 100%);
+ -webkit-mask-image: linear-gradient(to bottom, transparent 0%, #000 0.875rem, #000 calc(100% - 0.875rem), transparent 100%);
}
diff --git a/apps/desktop/renderer/src/lib/features/code/CodeWorkBlock.svelte b/apps/desktop/renderer/src/lib/features/code/CodeWorkBlock.svelte
index 6dd6174d..7b569262 100644
--- a/apps/desktop/renderer/src/lib/features/code/CodeWorkBlock.svelte
+++ b/apps/desktop/renderer/src/lib/features/code/CodeWorkBlock.svelte
@@ -122,9 +122,9 @@
{/snippet}
{#if folded.length === 1}
- {@render row(folded[0])}
+ {@render row(folded[0])}
{:else if folded.length}
-
+
{#snippet header()}
{line}
@@ -138,7 +138,7 @@
{/if}
-{#each waiting as item (item.key)}
{@render row(item)}
{/each}
+{#each waiting as item (item.key)}
{@render row(item)}
{/each}
diff --git a/apps/desktop/renderer/src/lib/features/code/ToolStepRow.svelte b/apps/desktop/renderer/src/lib/features/code/ToolStepRow.svelte
index 4c824985..465ec6b9 100644
--- a/apps/desktop/renderer/src/lib/features/code/ToolStepRow.svelte
+++ b/apps/desktop/renderer/src/lib/features/code/ToolStepRow.svelte
@@ -123,6 +123,8 @@
{
- if (!(event.ctrlKey || event.metaKey) || !event.altKey || event.shiftKey || event.code !== 'Digit0') return;
- // Only where a Code conversation is on screen (Code stays mounted, hidden, behind other spaces).
- if (!document.querySelector('[data-space-layer="code"]:not([hidden]) [data-conversation-workspace]')) return;
- event.preventDefault();
- projectControls.toggle();
- });
-}
diff --git a/apps/desktop/renderer/src/lib/locales/en.json b/apps/desktop/renderer/src/lib/locales/en.json
index 631f92d3..31bee9ff 100644
--- a/apps/desktop/renderer/src/lib/locales/en.json
+++ b/apps/desktop/renderer/src/lib/locales/en.json
@@ -2421,7 +2421,28 @@
"composer_terminal": "Terminal",
"composer_terminal_desc": "Compact monospace bar with prompt prefix and focus rail",
"composer_minimal": "Minimal",
- "composer_minimal_desc": "Borderless input line that recedes into the canvas"
+ "composer_minimal_desc": "Borderless input line that recedes into the canvas",
+ "agentSection": "Agent layout",
+ "agentStyle": "Live work layout",
+ "agentStyleDesc": "Choose how file reads, edits, diffs, shell cards, thoughts and tasks are laid out in the conversation.",
+ "agent_agente": "Agente",
+ "agent_agente_desc": "Clean default rail with quiet settled rows and live matrix",
+ "agent_cards": "Step Cards",
+ "agent_cards_desc": "Rounded cards for every read, edit, diff and command with active top bar",
+ "agent_pills": "Compact Pill Stream",
+ "agent_pills_desc": "Horizontal pill chips for reads and searches, full cards for edits",
+ "agent_spotlight": "Spotlight Focus",
+ "agent_spotlight_desc": "Quiet settled steps with an elevated focus card for active work",
+ "agent_rail": "Structured Icon Rail",
+ "agent_rail_desc": "Vertical timeline spine with circular icon nodes per step",
+ "agent_accented": "Accent-Railed Cards",
+ "agent_accented_desc": "Color-coded left bars distinguishing reads, edits and commands",
+ "agent_notebook": "Notebook Cells",
+ "agent_notebook_desc": "Bordered cells with fixed left gutter badges (READ, DIFF, RUN)",
+ "agent_sheet": "Unified Work Sheet",
+ "agent_sheet_desc": "Single bordered sheet with hairline dividers and zero stacked borders",
+ "agent_minimal": "Whisper Minimal",
+ "agent_minimal_desc": "Borderless tonal surfaces so the conversation stays calm"
},
"accessibility": {
"title": "Accessibility",
diff --git a/apps/desktop/renderer/src/lib/stores/appearance.spec.ts b/apps/desktop/renderer/src/lib/stores/appearance.spec.ts
index 5b174705..d3430295 100644
--- a/apps/desktop/renderer/src/lib/stores/appearance.spec.ts
+++ b/apps/desktop/renderer/src/lib/stores/appearance.spec.ts
@@ -30,6 +30,7 @@ describe('appearance shared helpers', () => {
customAccentHex: '#abc',
uiStyle: 'sharp',
composerStyle: 'card',
+ agentStyle: 'pills',
tintedUserBubbles: true
})
);
@@ -40,6 +41,7 @@ describe('appearance shared helpers', () => {
customAccentHex: '#aabbcc',
uiStyle: 'sharp',
composerStyle: 'card',
+ agentStyle: 'pills',
tintedUserBubbles: true
});
@@ -51,6 +53,7 @@ describe('appearance shared helpers', () => {
customAccentHex: 'not-a-hex',
uiStyle: 'weird',
composerStyle: 'floating',
+ agentStyle: 'cyberpunk',
tintedUserBubbles: 'yes'
})
);
diff --git a/apps/desktop/renderer/src/lib/stores/appearance.svelte.ts b/apps/desktop/renderer/src/lib/stores/appearance.svelte.ts
index cc0ac94f..cedccc75 100644
--- a/apps/desktop/renderer/src/lib/stores/appearance.svelte.ts
+++ b/apps/desktop/renderer/src/lib/stores/appearance.svelte.ts
@@ -95,7 +95,7 @@ class AppearanceStore {
if (typeof document === 'undefined') return;
const root = document.documentElement;
const resolved = this.resolvedMode;
- const { theme, accent, customAccentHex, uiStyle, composerStyle, tintedUserBubbles } = this.prefs;
+ const { theme, accent, customAccentHex, uiStyle, composerStyle, agentStyle, tintedUserBubbles } = this.prefs;
if (isElectron()) {
root.dataset.themeSwitching = 'true';
@@ -112,6 +112,7 @@ class AppearanceStore {
root.dataset.accent = accent;
root.dataset.uiStyle = uiStyle;
root.dataset.composerStyle = composerStyle;
+ root.dataset.agentStyle = agentStyle;
root.classList.toggle('appearance-tinted-bubbles', tintedUserBubbles);
if (accent === 'custom') {
diff --git a/apps/desktop/shared/appearance.ts b/apps/desktop/shared/appearance.ts
index e76070be..01ffd00d 100644
--- a/apps/desktop/shared/appearance.ts
+++ b/apps/desktop/shared/appearance.ts
@@ -13,6 +13,16 @@ export type AccentPresetId =
| 'custom';
export type UiStyleId = 'default' | 'soft' | 'sharp' | 'minimal';
export type ComposerStyleId = 'agente' | 'pill' | 'card' | 'terminal' | 'minimal';
+export type AgentStyleId =
+ | 'agente'
+ | 'cards'
+ | 'pills'
+ | 'spotlight'
+ | 'rail'
+ | 'accented'
+ | 'notebook'
+ | 'sheet'
+ | 'minimal';
export interface AppearancePrefs {
mode: ColorMode;
@@ -21,6 +31,7 @@ export interface AppearancePrefs {
customAccentHex: string;
uiStyle: UiStyleId;
composerStyle: ComposerStyleId;
+ agentStyle: AgentStyleId;
tintedUserBubbles: boolean;
}
@@ -33,6 +44,7 @@ export const DEFAULT_APPEARANCE: AppearancePrefs = {
customAccentHex: '#e8793a',
uiStyle: 'default',
composerStyle: 'agente',
+ agentStyle: 'agente',
tintedUserBubbles: false
};
@@ -99,11 +111,23 @@ export const ACCENT_PRESETS: readonly AccentPresetMeta[] = [
export const UI_STYLE_IDS: readonly UiStyleId[] = ['default', 'soft', 'sharp', 'minimal'] as const;
export const COMPOSER_STYLE_IDS: readonly ComposerStyleId[] = ['agente', 'pill', 'card', 'terminal', 'minimal'] as const;
+export const AGENT_STYLE_IDS: readonly AgentStyleId[] = [
+ 'agente',
+ 'cards',
+ 'pills',
+ 'spotlight',
+ 'rail',
+ 'accented',
+ 'notebook',
+ 'sheet',
+ 'minimal'
+] as const;
const THEME_ID_SET = new Set(THEME_PRESETS.map((preset) => preset.id));
const ACCENT_ID_SET = new Set([...ACCENT_PRESETS.map((preset) => preset.id), 'custom']);
const UI_STYLE_SET = new Set(UI_STYLE_IDS);
const COMPOSER_STYLE_SET = new Set(COMPOSER_STYLE_IDS);
+const AGENT_STYLE_SET = new Set(AGENT_STYLE_IDS);
export function normalizeHexColor(value: unknown, fallback = DEFAULT_APPEARANCE.customAccentHex): string {
if (typeof value !== 'string') return fallback;
@@ -150,6 +174,10 @@ export function parseAppearance(raw: string | null, legacyTheme?: 'light' | 'dar
typeof saved.composerStyle === 'string' && COMPOSER_STYLE_SET.has(saved.composerStyle)
? (saved.composerStyle as ComposerStyleId)
: base.composerStyle,
+ agentStyle:
+ typeof saved.agentStyle === 'string' && AGENT_STYLE_SET.has(saved.agentStyle)
+ ? (saved.agentStyle as AgentStyleId)
+ : base.agentStyle,
tintedUserBubbles: saved.tintedUserBubbles === true
};
}
diff --git a/apps/desktop/tests/electron/split-conversations.smoke.ts b/apps/desktop/tests/electron/split-conversations.smoke.ts
index 16731ea7..72e6bd84 100644
--- a/apps/desktop/tests/electron/split-conversations.smoke.ts
+++ b/apps/desktop/tests/electron/split-conversations.smoke.ts
@@ -101,11 +101,10 @@ async function run() {
const dataTransfer=new DataTransfer();source.dispatchEvent(new DragEvent('dragstart',{bubbles:true,dataTransfer}));target.dispatchEvent(new DragEvent('drop',{bubbles:true,cancelable:true,dataTransfer}));
if(sidebarOrganization.list('projects',codeStore.projects)[0].id!=='project-a')throw new Error('project order was not saved');
})()`);
- // The session column adds scripts and permits its nested branch picker.
- // The session column is open by default; its toggle lives in the pane's header.
- await js(`if(!document.querySelector('[data-project-controls="split-a"]'))document.querySelector('[data-conversation-workspace="split-a"] [data-session-toggle] button').click()`);await pause();
+ // The session panel adds scripts and permits its nested branch picker.
+ await js(`if(!document.querySelector('[data-conversation-workspace="split-a"] [data-workspace-panel="session"]:not([hidden])'))document.querySelector('[data-conversation-workspace="split-a"] [data-session-toggle] button').click()`);await pause();
await js(`document.querySelector('[data-project-controls="split-a"] [data-keep-open]').click()`);await pause();
- assert.equal(await js(`!!document.querySelector('[data-project-controls="split-a"] .script-form')`),true,'Add script stays in the session column');
+ assert.equal(await js(`!!document.querySelector('[data-project-controls="split-a"] .script-form')`),true,'Add script stays in the session panel');
await js(`document.querySelector('[data-project-controls="split-a"] .script-form input').value='Dev';document.querySelector('[data-project-controls="split-a"] .script-form input').dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('[data-project-controls="split-a"] .script-form input+input').value='npm run dev';document.querySelector('[data-project-controls="split-a"] .script-form input+input').dispatchEvent(new Event('input',{bubbles:true}));`);
await pause();await js(`document.querySelector('[data-project-controls="split-a"] .script-form').dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}))`);await pause();
assert.equal(await js(`JSON.parse(localStorage.getItem('agente.projectScripts'))['project-a'][0].command`),'npm run dev');
diff --git a/apps/desktop/tests/electron/workspace-renderer.smoke.ts b/apps/desktop/tests/electron/workspace-renderer.smoke.ts
index 8a4eda12..5a2d894c 100644
--- a/apps/desktop/tests/electron/workspace-renderer.smoke.ts
+++ b/apps/desktop/tests/electron/workspace-renderer.smoke.ts
@@ -88,14 +88,13 @@ async function run() {
metadata: { codeTodos: [{ content: 'Read the code', status: 'completed' }, { content: 'Verify the change', status: 'pending' }] }
});
})()`);
- // In Code the session column carries the tasks; the pane strip has no Tasks chip.
- const tasksPanel = '[data-project-controls=code-a] .tasks';
- await run(`(async () => { const { projectControls } = await import('/src/lib/features/code/workspace/project-controls.svelte.ts'); projectControls.set(true); })()`);
+ // In Code the main chat column carries the tasks; the pane strip has no Tasks chip.
+ const tasksPanel = '[data-chat-todos=code-a]';
await new Promise(resolve => setTimeout(resolve, 100));
assert.equal(await run('!document.querySelector("[data-panel-tab=tasks]")'), true, 'Code has no Tasks chip');
assert.match(await run(`document.querySelector('${tasksPanel}').textContent`), /Verify the change/);
assert.equal(await run(`document.querySelector('${tasksPanel} [role=progressbar]').getAttribute('aria-valuenow')`), '1');
- assert.equal(await run(`document.body.textContent.split('Verify the change').length - 1`), 1, 'Tasks render only in the session column');
+ assert.equal(await run(`document.body.textContent.split('Verify the change').length - 1`), 1, 'Tasks render only in the main chat column');
await run(`(async () => { const { workspaceLayout } = await import('/src/lib/stores/workspace-layout.svelte.ts'); workspaceLayout.show('changes'); })()`);
await new Promise(resolve => setTimeout(resolve, 100));
assert.equal(await run('!!document.querySelector("[data-workspace-panel=changes]:not([hidden])")'), true);
From 23cdf49bf744b2f31b135edfc5b47e23839e6d32 Mon Sep 17 00:00:00 2001
From: Fabricio Medrano <48396639+fabricio3g@users.noreply.github.com>
Date: Tue, 24 Nov 2026 17:14:43 -0300
Subject: [PATCH 2/2] fix: resolve 32 open issues across core, runtime, TUI and
desktop
Core web_fetch / search
- Resolve relative links against (#47); skip content roots
under hidden ancestors (#52); fence code longer than any backtick run
inside it (#53); lay rowspan/colspan cells on a grid (#46)
- Read charset from the body only for HTML tags (#38); fit each
part inside the registry's output caps so the advertised offset matches
what was delivered (#35)
- Pair DuckDuckGo Lite snippets with their own result row (#27)
Agent loop / compaction
- Summary is a user checkpoint, compaction repairs role order, and
request-time reminders merge into one user turn (#4)
- Shrink oversized recent and single-line tool results; scale the
tokenizer gap with the compacted transcript (#5)
- Only report normalization changes that happened; continue replies cut
by the output limit (max 2) and nudge after an empty Length stop (#6)
Runtime undo/redo
- Anchor edit batches to their prompt so rewind survives compaction, and
refuse a point inside the compacted part (#8); refuse rewinding over a
hand edit made between turns (#9); only a missing file counts as absent
(#10)
TUI
- Resuming a session open in another tab focuses that tab (#11); bind the
delete confirmation to the session id it was armed on (#12)
Desktop search and research
- SearXNG keeps its base path (#51); Perplexity prefers structured
citations (#50); per-provider base URLs (#29); Save and use cancels a
pending autosave (#37); empty results keep an engine healthy (#36);
timeouts and aborts cover the response body (#34)
- Same-title pages on different hosts stay apart (#26); explicit queries
are sent as typed (#31); Unicode-aware tokenizer (#32, partial); thin
page reads never replace a fuller provider body (#42)
- Crawler: hard read cap (#39), working embedding similarity (#40), keep
trailing slashes (#43), keep paragraphs and fix the summarizer cutting
the relevant late paragraph (#44), report omitted sources (#45)
- Case-sensitive citation identity and full export URLs (#41); one source
numbering across sub-queries (#54)
Desktop Home / Code / RAG
- Retry writes the reactive version and keeps sources per version
(#48, #49); search results are tied to their query (#14); Code scrolls
to the searched message (#13); steering checks input modalities (#19);
a filename filter keeps every same-named candidate (#20)
---
apps/desktop/main/agente/rust-engine.ts | 33 +-
apps/desktop/main/content-summarizer.ts | 46 ++-
apps/desktop/main/embedding-client.ts | 19 ++
apps/desktop/main/rag-engine.ts | 17 +-
apps/desktop/main/search-engine.ts | 17 +-
.../main/search-providers/aggregator/index.ts | 9 +-
.../main/search-providers/providers.ts | 46 ++-
apps/desktop/main/search-providers/shared.ts | 70 ++++-
apps/desktop/main/web-crawler.ts | 114 +++++--
.../components/layout/ChatSearchModal.svelte | 10 +-
.../settings/UnifiedSettingsPanel.svelte | 19 +-
.../chat/thread/ResearchWidget.svelte | 3 +-
.../lib/features/code/CodeTranscript.svelte | 40 +++
.../src/lib/features/code/code-ipc.ts | 2 +-
.../src/lib/features/code/code.svelte.ts | 3 +
.../lib/services/research-artifacts.spec.ts | 23 ++
.../src/lib/services/research-artifacts.ts | 26 +-
.../renderer/src/lib/stores/app.svelte.ts | 28 +-
.../renderer/src/lib/stores/chat-turn.ts | 6 +-
.../lib/stores/deep-research-evidence.spec.ts | 36 +++
.../src/lib/stores/deep-research.svelte.ts | 75 ++++-
apps/desktop/renderer/src/lib/types/chat.ts | 6 +
.../renderer/src/lib/utils/autosave.spec.ts | 31 ++
.../renderer/src/lib/utils/autosave.ts | 31 +-
.../tests/crawler/crawler-budgets.test.js | 121 ++++++++
.../tests/unit/search-provider-fixes.test.js | 149 +++++++++
.../src/agent/channel/loop_/mod.rs | 52 +++-
.../src/agent/channel/loop_/request.rs | 4 +
.../src/agent/channel/loop_/tests.rs | 124 ++++++++
.../agente-core/src/context/compaction/mod.rs | 3 +-
.../src/context/compaction/normalize.rs | 53 +++-
.../src/context/compaction/semantic.rs | 12 +-
.../src/context/compaction/tests.rs | 63 ++++
.../src/context/compaction/trim.rs | 68 ++++-
crates/agente-core/src/tools/web/extract.rs | 207 +++++++++++--
crates/agente-core/src/tools/web/mod.rs | 153 ++++++++--
crates/agente-core/src/tools/web/search.rs | 73 +++--
.../agente-daemon/src/connection/handlers.rs | 9 +-
crates/agente-runtime/src/bridge.rs | 4 +-
crates/agente-runtime/src/edits.rs | 288 ++++++++++++++++--
crates/agente-runtime/src/sessions.rs | 2 +-
crates/agente-runtime/src/tests.rs | 4 +-
crates/agente-runtime/src/turns.rs | 3 +-
crates/agente-tui/src/app/keys/session.rs | 55 ++--
crates/agente-tui/src/app/keys/tests.rs | 31 +-
crates/agente-tui/src/app/persistence.rs | 3 +
crates/agente-tui/src/app/tabs.rs | 38 +++
crates/agente-tui/src/session_picker.rs | 6 +-
crates/agente-tui/src/state/picker.rs | 10 +-
49 files changed, 1996 insertions(+), 249 deletions(-)
create mode 100644 apps/desktop/renderer/src/lib/stores/deep-research-evidence.spec.ts
create mode 100644 apps/desktop/tests/crawler/crawler-budgets.test.js
create mode 100644 apps/desktop/tests/unit/search-provider-fixes.test.js
diff --git a/apps/desktop/main/agente/rust-engine.ts b/apps/desktop/main/agente/rust-engine.ts
index 66a58ca6..e7a8245a 100644
--- a/apps/desktop/main/agente/rust-engine.ts
+++ b/apps/desktop/main/agente/rust-engine.ts
@@ -50,6 +50,8 @@ type ChatState = {
/** Sent with the first turn of a new session only. */
systemPrompt?: string;
turnId: string | null;
+ /** The provider and model the running turn uses: steered input goes to it. */
+ turnModel?: { id: string; model: string };
stopRequested: boolean;
stopGrace?: ReturnType;
settlement?: { promise: Promise; resolve: () => void };
@@ -559,17 +561,13 @@ async function prompt(chatId: string, text: string, images?: Array<{ data: strin
const provider = await useProvider(client, chat.provider, chat.model, chat.localSelection);
const expanded = await client.request<{ text: string }>('project.expand_prompt', { project_dir: chat.projectRoot, text });
const media = [...attachments, ...(await storeImages(client, images))];
- if (media.length) {
- const info = await client.request<{ capabilities: { input_modalities?: string[]; vision: boolean } }>('models.info', { provider: provider.id, model: provider.model });
- const modalities = info.capabilities.input_modalities || [];
- const unsupported = media.filter((item) => modalities.length ? !modalities.includes(item.kind) && !(item.kind === 'pdf' && modalities.includes('file')) : item.kind !== 'image' || !info.capabilities.vision);
- if (unsupported.length) throw new Error(`The selected model cannot accept ${unsupported.map((item) => item.name).join(', ')}. Choose a model with those input modalities.`);
- }
+ await assertModelAccepts(client, provider, media);
const message: Message = { role: 'user', content: expanded.text, attachments: media };
if (chat.owner) trackGoalTurn(chat.sessionId, client, chat.owner, provider.id, provider.model, message.content);
const started = await client.request<{ turn_id: string; conversation_index?: number }>('turn.start', turnParams(chat, provider, message));
chat.systemPrompt = undefined;
chat.turnId = started.turn_id;
+ chat.turnModel = { id: provider.id, model: provider.model };
goalTurnStarted(chat.sessionId,started.turn_id);
const computerOwner = codeComputerOwner(chat); if (computerOwner) bindComputerOwner(computerOwner);
return { ok: true, conversationIndex: started.conversation_index };
@@ -580,16 +578,37 @@ async function prompt(chatId: string, text: string, images?: Array<{ data: strin
}
}
+/**
+ * One capability decision for every way input reaches a model (a new turn,
+ * a steer into a running one, a queued follow-up when it starts): refuse
+ * media the model that will receive it cannot read, rather than letting the
+ * provider swap the file for a note while the UI still shows it attached.
+ */
+async function assertModelAccepts(client: Awaited>, provider: { id: string; model: string }, media: Attachment[]): Promise {
+ if (!media.length) return;
+ const info = await client.request<{ capabilities: { input_modalities?: string[]; vision: boolean } }>('models.info', { provider: provider.id, model: provider.model });
+ const modalities = info.capabilities.input_modalities || [];
+ const unsupported = media.filter((item) => modalities.length ? !modalities.includes(item.kind) && !(item.kind === 'pdf' && modalities.includes('file')) : item.kind !== 'image' || !info.capabilities.vision);
+ if (unsupported.length) throw new Error(`The selected model cannot accept ${unsupported.map((item) => item.name).join(', ')}. Choose a model with those input modalities.`);
+}
+
function failedPrompt(error: unknown, message: string): { ok: false; error: string; errorKey?: string } {
return { ok: false, error: message, ...(error instanceof RuntimeNoModelError ? { errorKey: error.errorKey } : {}) };
}
-async function steer(chatId: string, text: string, attachments: Attachment[] = []): Promise<{ ok: boolean }> {
+async function steer(chatId: string, text: string, attachments: Attachment[] = []): Promise<{ ok: boolean; error?: string }> {
const chat = chats.get(chatId);
if (!chat || chat.stopRequested) return { ok: false };
if (!chat.turnId) return queueFollowUp(chat, text, attachments);
const turnId = chat.turnId;
const client = await connect();
+ if (attachments.length) {
+ try {
+ await assertModelAccepts(client, chat.turnModel || { id: chat.provider, model: chat.model }, attachments);
+ } catch (error: unknown) {
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
+ }
+ }
const expanded = await client.request<{ text: string }>('project.expand_prompt', { project_dir: chat.projectRoot, text });
if (chat.stopRequested || chat.turnId !== turnId) return { ok: false };
return client.request('turn.steer', { turn_id: turnId, content: expanded.text, attachments });
diff --git a/apps/desktop/main/content-summarizer.ts b/apps/desktop/main/content-summarizer.ts
index 9788dd22..5bbd9be4 100644
--- a/apps/desktop/main/content-summarizer.ts
+++ b/apps/desktop/main/content-summarizer.ts
@@ -33,12 +33,24 @@ function topParagraphsByQuery(text, queryTerms, maxChars) {
return left.index - right.index;
});
+ // Take the best paragraphs that fit whole (the best one is cut to fit if
+ // it alone is too long). Picking past the budget and cutting the joined
+ // text afterwards dropped exactly the late, relevant paragraph once the
+ // selection went back into page order.
const selected = [];
let used = 0;
for (const item of ranked) {
- if (used >= maxChars) break;
+ const room = maxChars - used;
+ if (room <= 0) break;
const candidate = item.paragraph;
if (!candidate) continue;
+ if (candidate.length > room) {
+ if (!selected.length) {
+ selected.push({ ...item, paragraph: candidate.slice(0, room) });
+ used = maxChars;
+ }
+ continue;
+ }
selected.push(item);
used += candidate.length + 2;
}
@@ -50,7 +62,7 @@ function topParagraphsByQuery(text, queryTerms, maxChars) {
export function summarizeCrawledPages({ pages, query, targetChars } = {}) {
const list = Array.isArray(pages) ? pages : [];
const budget = Math.max(500, Number(targetChars) || 4000);
- if (!list.length) return { text: '', truncated: false, usedChars: 0 };
+ if (!list.length) return { text: '', truncated: false, omitted: 0, usedChars: 0 };
const queryTerms = tokenize(query).slice(0, 12);
const rankedPages = [...list].sort((left, right) => {
@@ -60,21 +72,27 @@ export function summarizeCrawledPages({ pages, query, targetChars } = {}) {
return Number(right?.score || 0) - Number(left?.score || 0);
});
+ // Each page gets a fair share of what is left, so every source keeps a
+ // short excerpt instead of the first pages taking the whole budget.
const blocks = [];
+ const omittedUrls = [];
let used = 0;
- for (const page of rankedPages) {
- if (used >= budget) break;
- const pageBudget = Math.max(600, Math.min(2200, Math.floor((budget - used) * 0.55)));
- const condensed = topParagraphsByQuery(page?.content || '', queryTerms, pageBudget);
- if (!condensed) continue;
- const block = [
+ for (let i = 0; i < rankedPages.length; i += 1) {
+ const page = rankedPages[i];
+ const header = [
`## ${page?.title || page?.url || 'Untitled page'}`,
- page?.url ? `URL: ${page.url}` : null,
- condensed
+ page?.url ? `URL: ${page.url}` : null
].filter(Boolean).join('\n\n');
- if (!block) continue;
+ const share = Math.floor((budget - used) / (rankedPages.length - i)) - header.length - 12;
+ const pageBudget = Math.min(2200, share);
+ const condensed = pageBudget >= 120 ? topParagraphsByQuery(page?.content || '', queryTerms, pageBudget) : '';
+ if (!condensed) {
+ if (page?.url) omittedUrls.push(page.url);
+ continue;
+ }
+ const block = `${header}\n\n${condensed}`;
blocks.push(block);
- used += block.length + 6;
+ used += block.length + 7;
}
let text = blocks.join('\n\n---\n\n');
@@ -88,10 +106,14 @@ export function summarizeCrawledPages({ pages, query, targetChars } = {}) {
if (blocks.length < list.length) {
truncated = true;
}
+ if (omittedUrls.length) {
+ text = `${text}\n\n(Not included for space: ${omittedUrls.join(', ')})`;
+ }
return {
text,
truncated,
+ omitted: list.length - blocks.length,
usedChars: text.length
};
}
diff --git a/apps/desktop/main/embedding-client.ts b/apps/desktop/main/embedding-client.ts
index d0f4a4f3..a791e413 100644
--- a/apps/desktop/main/embedding-client.ts
+++ b/apps/desktop/main/embedding-client.ts
@@ -110,3 +110,22 @@ export async function getEmbeddings(texts) {
export function clearEmbeddingCache() {
embeddingCache.clear();
}
+
+/**
+ * Cosine similarity of two embeddings (0 when either is empty, zero-length
+ * or the sizes differ, as after a model change). The crawler's link scorer
+ * imports it; without it semantic scoring silently stayed off.
+ */
+export function cosineSimilarity(left: ArrayLike, right: ArrayLike): number {
+ if (!left || !right || left.length === 0 || left.length !== right.length) return 0;
+ let dot = 0;
+ let leftNorm = 0;
+ let rightNorm = 0;
+ for (let i = 0; i < left.length; i += 1) {
+ dot += left[i] * right[i];
+ leftNorm += left[i] * left[i];
+ rightNorm += right[i] * right[i];
+ }
+ if (leftNorm === 0 || rightNorm === 0) return 0;
+ return dot / Math.sqrt(leftNorm * rightNorm);
+}
diff --git a/apps/desktop/main/rag-engine.ts b/apps/desktop/main/rag-engine.ts
index 60552737..3a9c9d0c 100644
--- a/apps/desktop/main/rag-engine.ts
+++ b/apps/desktop/main/rag-engine.ts
@@ -505,11 +505,22 @@ async function queryDocumentsHybrid({ query, chat_id, top_k, scope, files, file_
wantedDocIds = new Set();
try {
const records = await chatDatabase.request>('listFileRecords');
+ // A hash names one file. A name can belong to files in several chats
+ // (or two in one): keep every candidate, and let the scope below pick
+ // the ones this chat may read — choosing one record first lost the
+ // in-scope file whenever another chat used the same name.
const byHash = new Map(records.map((file) => [String(file.hash), file]));
- const byName = new Map(records.map((file) => [String(file.name).toLowerCase(), file]));
+ const byName = new Map();
+ for (const file of records) {
+ const name = String(file.name).toLowerCase();
+ byName.set(name, [...(byName.get(name) || []), file]);
+ }
for (const entry of wanted) {
- const file = byHash.get(entry) || byName.get(entry.toLowerCase());
- if (file?.ragDocId) wantedDocIds.add(String(file.ragDocId));
+ const exact = byHash.get(entry);
+ const matches = exact ? [exact] : byName.get(entry.toLowerCase()) || [];
+ for (const file of matches) {
+ if (file.ragDocId) wantedDocIds.add(String(file.ragDocId));
+ }
}
} catch {
// Without the registry a name filter cannot be resolved; the other
diff --git a/apps/desktop/main/search-engine.ts b/apps/desktop/main/search-engine.ts
index ee9f6e67..b7f8e966 100644
--- a/apps/desktop/main/search-engine.ts
+++ b/apps/desktop/main/search-engine.ts
@@ -6,7 +6,7 @@ import {
normalizeProviderName, providerHasCredentials, providerDisplayName, providerCandidates,
getCacheKey, getCachedResult, setCachedResult, mergeAndRankResults, buildContext,
buildJinaReaderUrl, toErrorMessage, classifyNetworkError, providerSearchError,
- REMOVED_SEARCH_PROVIDERS
+ REMOVED_SEARCH_PROVIDERS, tokenize
} from './search-providers/shared.ts';
import type { SearchResult } from './search-providers/shared.ts';
import {
@@ -135,7 +135,11 @@ async function fetchPageContent(url: string, options: Record =
/** Prefer pages with more query-relevant title/snippet before scraping. */
function scoreResultForDeepFetch(result: SearchResult, query: string): number {
- const terms = normalizeWhitespace(query).toLowerCase().match(/[a-z0-9]+/g)?.filter((t) => t.length > 2).slice(0, 12) || [];
+ // Short words count outside ASCII: a Japanese or Chinese word is often one
+ // or two characters.
+ const terms = tokenize(query)
+ .filter((t) => t.length > 2 || /[^\p{ASCII}]/u.test(t))
+ .slice(0, 12);
const title = normalizeWhitespace(result.title || '').toLowerCase();
const snippet = normalizeWhitespace(result.snippet || '').toLowerCase();
let score = 0;
@@ -204,11 +208,16 @@ async function enrichWithDeepContent(results: SearchResult[], limit: number, emi
warning: page?.warning,
scrape_quality: normalizeWhitespace(content).length < 200 ? 'thin' : 'ok'
};
- if (!content || normalizeWhitespace(content).length < 200) {
+ // A blocked or thin read ("Sign in to continue") never replaces a
+ // fuller body the provider already returned; the warning stays in
+ // the metadata.
+ const providerBody = item.r.full_content || '';
+ const fetchedLength = normalizeWhitespace(content).length;
+ if (!content || fetchedLength < 200 || fetchedLength < normalizeWhitespace(providerBody).length) {
return {
...item.r,
title: page?.title || item.r.title,
- full_content: content || undefined,
+ full_content: normalizeWhitespace(providerBody).length >= fetchedLength ? providerBody : content,
published_at: page?.published_at || item.r.published_at,
metadata: meta,
scrape_quality: 'thin' as const
diff --git a/apps/desktop/main/search-providers/aggregator/index.ts b/apps/desktop/main/search-providers/aggregator/index.ts
index 28dba593..0aede7d1 100644
--- a/apps/desktop/main/search-providers/aggregator/index.ts
+++ b/apps/desktop/main/search-providers/aggregator/index.ts
@@ -82,12 +82,13 @@ async function executeEngine(
try {
const results = await runAggregatorEngine(engine, query, limit, { ...options, aggregator_signal: signal });
- const success = results.length > 0;
- if (success) recordSuccess(key);
- else recordFailure(key);
+ // A well-formed answer with no matches is a healthy engine: only
+ // transport, service or response failures (thrown below) count toward
+ // the cooldown. The empty count stays visible in the diagnostics.
+ recordSuccess(key);
return {
results,
- attempt: { engine, success, result_count: results.length, latency_ms: Date.now() - started, error: success ? undefined : 'No results' },
+ attempt: { engine, success: true, result_count: results.length, latency_ms: Date.now() - started },
};
} catch (error: unknown) {
const cooldownUntil = signal.aborted ? 0 : recordFailure(key);
diff --git a/apps/desktop/main/search-providers/providers.ts b/apps/desktop/main/search-providers/providers.ts
index acbe66be..587ab853 100644
--- a/apps/desktop/main/search-providers/providers.ts
+++ b/apps/desktop/main/search-providers/providers.ts
@@ -9,7 +9,8 @@ import type { SearchResult } from './shared.ts';
export async function searchSearxng(query: string, maxResults: number, options: Record): Promise {
const baseUrl = requireOption(options, 'searxng_base_url', 'No SearXNG base URL');
- const url = new URL('/search', baseUrl.replace(/\/+$/, '') + '/');
+ // Relative to the configured base, so a path prefix (`/searx/`) is kept.
+ const url = new URL('search', baseUrl.replace(/\/+$/, '') + '/');
url.searchParams.set('q', query);
url.searchParams.set('format', 'json');
url.searchParams.set('language', 'en');
@@ -112,18 +113,13 @@ export async function searchPerplexity(query: string, maxResults: number, option
? data.sources as unknown[]
: [];
- const parsed = parseSearchResultsFromText('perplexity', text, maxResults, 'https://www.perplexity.ai');
- if (parsed.length) return parsed;
-
- if (citations.length) {
- return citations.slice(0, maxResults).map((citation, index) => normalizeSearchItem('perplexity', {
- title: text.split(/\r?\n/).find(Boolean) || `Perplexity result ${index + 1}`,
- url: typeof citation === 'string' ? citation : (citation as Record)?.url || (citation as Record)?.link || '',
- snippet: text.slice(0, 1200),
- full_content: text.slice(0, 4000),
- metadata: citation as Record
- }, index));
- }
+ // Structured citations are the real sources: prefer them to anything read
+ // out of the answer text, whose last resort is the Perplexity homepage.
+ const inline = parseSearchResultsFromText('perplexity', text, maxResults)
+ .filter((result) => /^https?:\/\//i.test(result.url));
+ const cited = citationResults(citations, inline, text, maxResults);
+ if (cited.length) return cited;
+ if (inline.length) return inline;
if (text) {
return [normalizeSearchItem('perplexity', {
@@ -137,3 +133,27 @@ export async function searchPerplexity(query: string, maxResults: number, option
return [];
}
+
+/** One result per distinct citation URL, titled from the citation or a matching inline link. */
+function citationResults(citations: unknown[], inline: SearchResult[], text: string, maxResults: number): SearchResult[] {
+ const seen = new Set();
+ const results: SearchResult[] = [];
+ for (const citation of citations) {
+ if (results.length >= maxResults) break;
+ const record = (citation && typeof citation === 'object' ? citation : {}) as Record;
+ const url = String(typeof citation === 'string' ? citation : record.url || record.link || '').trim();
+ if (!/^https?:\/\//i.test(url) || seen.has(url)) continue;
+ seen.add(url);
+ const linked = inline.find((result) => result.url === url);
+ let host = url;
+ try { host = new URL(url).hostname.replace(/^www\./, ''); } catch { /* keep the URL */ }
+ results.push(normalizeSearchItem('perplexity', {
+ title: String(record.title || linked?.title || host),
+ url,
+ snippet: linked?.snippet || text.slice(0, 1200),
+ full_content: text.slice(0, 4000),
+ metadata: typeof citation === 'string' ? { citation_index: results.length + 1 } : record
+ }, results.length));
+ }
+ return results;
+}
diff --git a/apps/desktop/main/search-providers/shared.ts b/apps/desktop/main/search-providers/shared.ts
index a9dbb54b..b645c489 100644
--- a/apps/desktop/main/search-providers/shared.ts
+++ b/apps/desktop/main/search-providers/shared.ts
@@ -77,6 +77,12 @@ export function classifyNetworkError(err: unknown) {
return { error_type: 'unknown', retryable: false, hint: 'Unexpected error.' };
}
+const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
+
+/**
+ * `fetch` with retries, a timeout and the caller's abort signal covering the
+ * whole exchange: the response comes back with its body already read.
+ */
export async function fetchWithRetry(url: string, opts: Record = {}): Promise {
const retries = (opts.retries as number | undefined) ?? 2;
const timeoutMs = (opts.timeout_ms as number | undefined) ?? 15000;
@@ -88,7 +94,7 @@ export async function fetchWithRetry(url: string, opts: Record
const abortFromExternal = () => ctrl.abort(externalSignal?.reason);
if (externalSignal?.aborted) abortFromExternal();
else externalSignal?.addEventListener('abort', abortFromExternal, { once: true });
- const timer = setTimeout(() => ctrl.abort(), timeoutMs);
+ const timer = setTimeout(() => ctrl.abort(new DOMException('Request timeout', 'TimeoutError')), timeoutMs);
try {
const resp = await fetch(url, {
method: (opts.method as string) || 'GET',
@@ -96,9 +102,19 @@ export async function fetchWithRetry(url: string, opts: Record
headers: opts.headers as Record | undefined,
body: opts.body as string | undefined
});
+ // Read the body while the deadline and the caller's signal still hold:
+ // headers can arrive promptly and the body stall, and a read started
+ // after this returned would outlive both.
+ const body = NULL_BODY_STATUSES.has(resp.status) ? null : await resp.arrayBuffer();
clearTimeout(timer);
externalSignal?.removeEventListener('abort', abortFromExternal);
- return resp;
+ const buffered = new Response(body, {
+ status: resp.status,
+ statusText: resp.statusText,
+ headers: resp.headers
+ });
+ Object.defineProperty(buffered, 'url', { value: resp.url });
+ return buffered;
} catch (err: unknown) {
clearTimeout(timer);
externalSignal?.removeEventListener('abort', abortFromExternal);
@@ -163,18 +179,51 @@ export function coerceSearchText(value: unknown, maxChars = 4000): string {
return '';
}
+const wordSegmenter = typeof Intl.Segmenter === 'function'
+ ? new Intl.Segmenter(undefined, { granularity: 'word' })
+ : null;
+
+/**
+ * Words of any script: letters and digits, so Arabic, accented Latin and
+ * Japanese queries keep their terms. Text outside ASCII goes through the
+ * word segmenter, which splits unspaced scripts into words.
+ */
export function tokenize(text: string): string[] {
- return normalizeWhitespace(text).toLowerCase().match(/[a-z0-9]+/g) || [];
+ const normalized = normalizeWhitespace(text).toLowerCase();
+ if (!normalized) return [];
+ // eslint-disable-next-line no-control-regex
+ if (!wordSegmenter || /^[\x00-\x7f]*$/.test(normalized)) {
+ return normalized.match(/[\p{L}\p{N}]+/gu) || [];
+ }
+ const tokens: string[] = [];
+ for (const part of wordSegmenter.segment(normalized)) {
+ if (part.isWordLike) tokens.push(...(part.segment.match(/[\p{L}\p{N}]+/gu) || []));
+ }
+ return tokens;
}
export function compactSearchContext(context: unknown, max = 1800): string {
return normalizeWhitespace(context).slice(0, max);
}
+/**
+ * Whether a query only makes sense with the conversation ("what changed in
+ * that release?"). Freshness words alone ("latest Node.js releases") are not
+ * a reference, and a query that names its subject (a capitalized name, a
+ * version, a dotted name) or is quoted is explicit and sent as typed.
+ */
function looksContextDependent(query: string): boolean {
- const normalized = normalizeWhitespace(query).toLowerCase();
+ const normalized = normalizeWhitespace(query);
if (!normalized) return false;
- return /\b(this|that|these|those|it|its|he|him|his|she|her|hers|they|them|their|there|latest|recent|current|today|now|news|update|price|stock|version|release)\b/i.test(normalized);
+ if (/["“”]/.test(normalized)) return false;
+ const namesSubject = /\s[A-Z]|\d|\w\.\w/.test(normalized) || /^[A-Z][a-z]*[A-Z]/.test(normalized);
+ const refers = /\b(this|that|these|those|it|its|he|him|his|she|her|hers|they|them|their|there)\b/i.test(normalized);
+ if (refers) {
+ // "that release", "this one": a reference even next to a named subject.
+ return !namesSubject || /\b(this|that|these|those)\s+(one|ones|release|version|update|change|model|product|company|article|paper|page|thing)\b/i.test(normalized);
+ }
+ // A bare follow-up ("and the price?", "why") with no subject of its own.
+ return !namesSubject && tokenize(normalized).length <= 2;
}
function extractContextTerms(context: string): string[] {
@@ -220,7 +269,7 @@ export function buildEffectiveSearchQuery(query: string, context: string): strin
const normalizedQuery = normalizeWhitespace(query);
const normalizedContext = compactSearchContext(context);
if (!normalizedQuery || !normalizedContext) return normalizedQuery;
- if (!looksContextDependent(normalizedQuery) && normalizedQuery.length >= 16) return normalizedQuery;
+ if (!looksContextDependent(normalizedQuery)) return normalizedQuery;
const queryTokens = new Set(tokenize(normalizedQuery));
const contextTerms = extractContextTerms(normalizedContext)
@@ -463,7 +512,8 @@ function dedupeKey(result: SearchResult): string {
}
function normalizedTitleKey(title: string): string {
- return tokenize(title).filter((token) => token.length > 2).sort().join(' ');
+ // Numbers stay: "Node 18 docs" and "Node 20 docs" are different pages.
+ return tokenize(title).filter((token) => token.length > 2 || /\d/.test(token)).sort().join(' ');
}
function parsedRecencyBoost(value: string | null): number {
@@ -486,7 +536,11 @@ export function mergeAndRankResults(results: SearchResult[], query: string, limi
for (const result of results) {
let key = dedupeKey(result);
- const titleKey = normalizedTitleKey(result.title);
+ // The same page under two URLs (http/https, a tracking variant) shares a
+ // host and a title; pages on different hosts with one stock title
+ // ("Installation guide") are different sources and keep their own text.
+ const title = normalizedTitleKey(result.title);
+ const titleKey = title ? `${getDomain(result.url)}|${title}` : '';
if (titleKey && titleKeys.has(titleKey)) key = titleKeys.get(titleKey)!;
const existing = merged.get(key);
const reciprocalRank = 1 / (60 + Math.max(1, result.source_rank || 1));
diff --git a/apps/desktop/main/web-crawler.ts b/apps/desktop/main/web-crawler.ts
index dcd9140d..2004d106 100644
--- a/apps/desktop/main/web-crawler.ts
+++ b/apps/desktop/main/web-crawler.ts
@@ -20,20 +20,43 @@ const MODE_CONFIG = {
}
};
+/**
+ * The URL to request: http(s) only, without its fragment. The path is kept
+ * as written: `/guide/` and `/guide` can be different documents (one may
+ * 404), so a trailing slash is never stripped. Pages read twice under both
+ * spellings are deduplicated by their content instead.
+ */
function normalizeUrl(url) {
try {
const parsed = new URL(String(url || '').trim());
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return '';
parsed.hash = '';
- if (parsed.pathname.length > 1 && parsed.pathname.endsWith('/')) {
- parsed.pathname = parsed.pathname.slice(0, -1);
- }
return parsed.toString();
} catch {
return '';
}
}
+/**
+ * Page text with its paragraphs kept: spaces collapse within each line and
+ * blank-line runs shrink to one, so the summarizer can still pick the
+ * paragraph that answers the query.
+ */
+function tidyPageText(text) {
+ return String(text || '')
+ .replace(/\r\n?/g, '\n')
+ .split('\n')
+ .map((line) => line.replace(/[ \t\f\v ]+/g, ' ').trim())
+ .join('\n')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
+
+function contentKey(text) {
+ const flat = normalizeWhitespace(text).toLowerCase();
+ return `${flat.length}:${flat.slice(0, 2000)}`;
+}
+
function enqueue(queue, candidate) {
queue.push(candidate);
queue.sort((left, right) => {
@@ -54,28 +77,39 @@ function uniqueSeedUrls(seedUrls) {
return items;
}
+/**
+ * Every page whole, in crawl order, while they fit. Reports what it left
+ * out (`omitted` pages, `clipped` text) so the caller never mistakes a
+ * partial context for the full one.
+ */
function buildCrawlContext(pages, budgetChars) {
const budget = Math.max(500, Number(budgetChars) || 7000);
const blocks = [];
let used = 0;
+ let omitted = 0;
+ let clipped = false;
for (let i = 0; i < pages.length; i += 1) {
- if (used >= budget) break;
const page = pages[i];
- const content = normalizeWhitespace(page.content || '');
- if (!content) continue;
+ const content = page.content || '';
+ if (!normalizeWhitespace(content)) continue;
+ const limit = Math.min(4200, budget);
+ if (content.length > limit) clipped = true;
const block = [
`## [C${i + 1}] ${page.title || page.url || 'Untitled page'}`,
`URL: ${page.url}`,
`Depth: ${page.depth}`,
- content.slice(0, Math.min(4200, budget))
+ content.slice(0, limit)
].join('\n\n');
- if (blocks.length > 0 && used + block.length > budget) break;
+ if (used >= budget || (blocks.length > 0 && used + block.length > budget)) {
+ omitted += 1;
+ continue;
+ }
blocks.push(block);
used += block.length + 24;
}
- return blocks.join('\n\n---\n\n');
+ return { text: blocks.join('\n\n---\n\n'), omitted, clipped };
}
export async function crawlWeb({
@@ -106,6 +140,9 @@ export async function crawlWeb({
stats: {
pages_crawled: 0,
pages_discovered: 0,
+ pages_attempted: 0,
+ pages_failed: 0,
+ pages_omitted: 0,
truncated: false,
max_depth_reached: 0
}
@@ -115,15 +152,22 @@ export async function crawlWeb({
const queue = [];
const queued = new Set();
const visited = new Set();
+ const seenContent = new Set();
const pages = [];
let maxDepthReached = 0;
+ // Network reads have their own hard cap: a failed read (404, timeout)
+ // adds no page, and without a cap a burst of dead links kept the crawl
+ // going well past the page budget.
+ const maxAttempts = Math.ceil(modeConfig.maxPages * 1.5);
+ let attempts = 0;
+ let failed = 0;
for (const url of seeds) {
enqueue(queue, { url, depth: 0, parentUrl: '', priority: 1.0 });
queued.add(url);
}
- while (queue.length && pages.length < modeConfig.maxPages) {
+ while (queue.length && pages.length < modeConfig.maxPages && attempts < maxAttempts) {
const next = queue.shift();
if (!next) break;
queued.delete(next.url);
@@ -133,21 +177,35 @@ export async function crawlWeb({
emit?.('crawl_page', `Crawling page ${pages.length + 1}/${modeConfig.maxPages}: ${next.url}`);
- const scraped = await scrapeFn({
- url: next.url,
- maxLength: modeConfig.maxCharsPerPage,
- timeoutMs: 18000,
- maxLinks: 120
- });
+ attempts += 1;
+ let scraped;
+ try {
+ scraped = await scrapeFn({
+ url: next.url,
+ maxLength: modeConfig.maxCharsPerPage,
+ timeoutMs: 18000,
+ maxLinks: 120
+ });
+ } catch {
+ scraped = null;
+ }
if (!scraped || scraped.error || !normalizeWhitespace(scraped.content)) {
+ failed += 1;
continue;
}
+ const content = tidyPageText(scraped.content);
+ // The same document under another spelling of its URL (`/guide` and
+ // `/guide/`, a redirect): read once, kept once.
+ const key = contentKey(content);
+ if (seenContent.has(key)) continue;
+ seenContent.add(key);
+
pages.push({
url: next.url,
title: scraped.title || next.url,
- content: normalizeWhitespace(scraped.content),
+ content,
excerpt: scraped.excerpt || '',
depth: next.depth,
parentUrl: next.parentUrl || '',
@@ -181,22 +239,23 @@ export async function crawlWeb({
}
}
- const contextRaw = buildCrawlContext(pages, budgetChars);
- const summary = summarizeCrawledPages({
+ const raw = buildCrawlContext(pages, budgetChars);
+ // The whole pages fit: send them. Otherwise condense every page to its
+ // most relevant paragraphs, which keeps a short excerpt of each source
+ // (and names any that still did not fit) instead of silently dropping
+ // the ones at the end.
+ const complete = raw.omitted === 0 && !raw.clipped && raw.text.length <= budgetChars;
+ const summary = complete ? null : summarizeCrawledPages({
pages,
query,
targetChars: budgetChars
});
-
- const shouldSummarize = contextRaw.length > budgetChars || summary.truncated;
- const finalContext = shouldSummarize
- ? summary.text || contextRaw.slice(0, budgetChars)
- : contextRaw;
+ const finalContext = complete ? raw.text : (summary?.text || raw.text.slice(0, budgetChars));
const results = pages.map((page, index) => ({
title: page.title,
url: page.url,
- snippet: page.excerpt || page.content.slice(0, 280),
+ snippet: page.excerpt || normalizeWhitespace(page.content).slice(0, 280),
full_content: page.content.slice(0, modeConfig.maxCharsPerPage),
provider: 'crawler',
source_rank: index + 1,
@@ -216,7 +275,10 @@ export async function crawlWeb({
stats: {
pages_crawled: pages.length,
pages_discovered: visited.size,
- truncated: shouldSummarize,
+ pages_attempted: attempts,
+ pages_failed: failed,
+ pages_omitted: summary ? summary.omitted : raw.omitted,
+ truncated: !complete,
max_depth_reached: maxDepthReached
}
};
diff --git a/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte b/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte
index ca55b948..d59f1a05 100644
--- a/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte
+++ b/apps/desktop/renderer/src/lib/components/layout/ChatSearchModal.svelte
@@ -84,15 +84,17 @@
snippet: string | null;
}
- let dbMatches = $state>({});
+ // Database matches carry the query they answer: rows found for an earlier
+ // query must not stay selectable (or open) while the next lookup runs.
+ let dbMatches = $state<{ query: string; hits: Record }>({ query: '', hits: {} });
$effect(() => {
const q = query.trim();
const unloaded = spaceChats.filter((chat) => chat.messagesLoaded === false).map((chat) => chat.id);
- if (!q || !unloaded.length) { dbMatches = {}; return; }
+ if (!q || !unloaded.length) { dbMatches = { query: '', hits: {} }; return; }
let current = true;
const timer = setTimeout(() => {
void searchChatsInDb(q, unloaded).then((hits) => {
- if (current) dbMatches = Object.fromEntries(hits.map((hit) => [hit.chatId, { messageId: hit.messageId, content: hit.content }]));
+ if (current) dbMatches = { query: q, hits: Object.fromEntries(hits.map((hit) => [hit.chatId, { messageId: hit.messageId, content: hit.content }])) };
});
}, 150);
return () => { current = false; clearTimeout(timer); };
@@ -107,7 +109,7 @@
continue;
}
const titleHit = (chat.title || '').toLowerCase().includes(q) || displayChatTitle(chat).toLowerCase().includes(q);
- const stored = chat.messagesLoaded === false ? dbMatches[chat.id] : undefined;
+ const stored = chat.messagesLoaded === false && dbMatches.query.toLowerCase() === q ? dbMatches.hits[chat.id] : undefined;
const msg = stored ? { id: stored.messageId, content: stored.content } : (chat.messages ?? []).find((m) => (m.content || '').toLowerCase().includes(q));
if (!titleHit && !msg) continue;
let snippet: string | null = null;
diff --git a/apps/desktop/renderer/src/lib/components/settings/UnifiedSettingsPanel.svelte b/apps/desktop/renderer/src/lib/components/settings/UnifiedSettingsPanel.svelte
index 1b29631a..18cd0040 100644
--- a/apps/desktop/renderer/src/lib/components/settings/UnifiedSettingsPanel.svelte
+++ b/apps/desktop/renderer/src/lib/components/settings/UnifiedSettingsPanel.svelte
@@ -27,7 +27,17 @@
let persistedSearchProvider = $state(appStore.config.search?.provider || 'aggregator');
let searchMaxResults = $state(String(appStore.config.search?.max_results ?? 6));
let searchApiKey = $state('');
- let searchBaseUrl = $state(appStore.config.search?.providers?.searxng?.base_url || 'https://searx.org');
+ // One field edits the base URL of whichever provider takes one; each keeps
+ // its own saved value and default (the connectors' defaults).
+ const DEFAULT_BASE_URLS: Record = {
+ searxng: 'https://searx.org',
+ jina: 'https://s.jina.ai',
+ };
+ function storedBaseUrl(provider: string): string {
+ const providers = (appStore.config.search?.providers || {}) as Record;
+ return providers[provider]?.base_url || DEFAULT_BASE_URLS[provider] || '';
+ }
+ let searchBaseUrl = $state(storedBaseUrl(appStore.config.search?.provider || 'aggregator') || DEFAULT_BASE_URLS.searxng);
let searchModel = $state(appStore.config.search?.providers?.perplexity?.model || 'sonar');
let searchApiUrl = $state(appStore.config.search?.providers?.perplexity?.api_url || 'https://api.perplexity.ai');
let aggregatorEngines = $state([
@@ -150,6 +160,7 @@
$effect(() => {
const provider = String(searchProvider || 'auto').toLowerCase();
searchApiKey = getStoredSearchApiKey(provider);
+ if (provider in DEFAULT_BASE_URLS) searchBaseUrl = untrack(() => storedBaseUrl(provider));
});
$effect(() => {
@@ -195,6 +206,10 @@
}
savingSearchConfiguration = true;
try {
+ // A debounced preference write captured the previous provider (an
+ // unconfigured one cannot be activated by autosave); drop it so it
+ // cannot land after this save and switch the provider back.
+ await searchAutosave.cancel();
await appStore.updateSearchSettings({
provider: searchProvider,
max_results: normalizedMaxResults(),
@@ -209,7 +224,7 @@
? { searxng: { base_url: searchBaseUrl || appStore.config.search?.providers?.searxng?.base_url || 'https://searx.org' } }
: {}),
...(searchProvider === 'jina'
- ? { jina: { api_key: searchApiKey || appStore.config.search?.providers?.jina?.api_key, base_url: searchBaseUrl || appStore.config.search?.providers?.jina?.base_url || 'https://api.jina.ai' } }
+ ? { jina: { api_key: searchApiKey || appStore.config.search?.providers?.jina?.api_key, base_url: searchBaseUrl || storedBaseUrl('jina') } }
: {}),
...(searchProvider === 'perplexity'
? { perplexity: { api_key: searchApiKey || appStore.config.search?.providers?.perplexity?.api_key, model: searchModel || appStore.config.search?.providers?.perplexity?.model || 'sonar', api_url: searchApiUrl || appStore.config.search?.providers?.perplexity?.api_url || 'https://api.perplexity.ai' } }
diff --git a/apps/desktop/renderer/src/lib/features/chat/thread/ResearchWidget.svelte b/apps/desktop/renderer/src/lib/features/chat/thread/ResearchWidget.svelte
index 87e9d0de..9ac7d86b 100644
--- a/apps/desktop/renderer/src/lib/features/chat/thread/ResearchWidget.svelte
+++ b/apps/desktop/renderer/src/lib/features/chat/thread/ResearchWidget.svelte
@@ -22,6 +22,7 @@
import {
buildResearchExportFiles,
downloadResearchExportFile,
+ sourceIdentity,
suggestedExportKinds,
type ResearchExportKind
} from '$lib/services/research-artifacts';
@@ -41,7 +42,7 @@
const seen = new Set();
const out: SearchResult[] = [];
for (const source of ctx.message.sources || []) {
- const key = String(source.url || source.title || '').trim().toLowerCase().replace(/#.*$/, '').replace(/\/$/, '');
+ const key = sourceIdentity(source.url, source.title);
if (!key || seen.has(key)) continue;
seen.add(key);
out.push(source);
diff --git a/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte b/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte
index 384f0a22..7fd2bc4e 100644
--- a/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte
+++ b/apps/desktop/renderer/src/lib/features/code/CodeTranscript.svelte
@@ -197,6 +197,46 @@
return () => cancelAnimationFrame(frame);
});
+ /*
+ * Conversation search opens a chat and then asks for the message it
+ * matched. The session may still be loading, so the request waits until
+ * that message is in the transcript (or gives up after a few seconds)
+ * instead of leaving the view on the latest turn.
+ */
+ let pendingScrollId = $state(null);
+ let pendingScrollTimer: ReturnType | undefined;
+ $effect(() => {
+ const onRequest = (event: Event) => {
+ const messageId = (event as CustomEvent<{ messageId?: string }>).detail?.messageId;
+ if (!messageId) return;
+ pendingScrollId = messageId;
+ if (pendingScrollTimer) clearTimeout(pendingScrollTimer);
+ pendingScrollTimer = setTimeout(() => (pendingScrollId = null), 5000);
+ };
+ window.addEventListener('scroll-to-chat-message', onRequest);
+ return () => {
+ window.removeEventListener('scroll-to-chat-message', onRequest);
+ if (pendingScrollTimer) clearTimeout(pendingScrollTimer);
+ };
+ });
+ $effect(() => {
+ const messageId = pendingScrollId;
+ if (!messageId || !viewport) return;
+ const index = messages.findIndex((message) => message.id === messageId);
+ if (index < 0) return;
+ pendingScrollId = null;
+ follow.pause();
+ browseTimeline(index);
+ // Two frames: slots off screen render at an estimated height until
+ // laid out, so the second pass lands on the real position.
+ const reveal = () => viewport?.querySelectorAll('.code-message-slot')[index]?.scrollIntoView({ block: 'center' });
+ const frame = requestAnimationFrame(() => {
+ reveal();
+ requestAnimationFrame(reveal);
+ });
+ return () => cancelAnimationFrame(frame);
+ });
+
async function messageAction(message: ChatMessage, action: 'copy' | 'fork' | 'rewind') {
try {
if (action === 'copy') {
diff --git a/apps/desktop/renderer/src/lib/features/code/code-ipc.ts b/apps/desktop/renderer/src/lib/features/code/code-ipc.ts
index a0fe78d1..a1216496 100644
--- a/apps/desktop/renderer/src/lib/features/code/code-ipc.ts
+++ b/apps/desktop/renderer/src/lib/features/code/code-ipc.ts
@@ -17,7 +17,7 @@ export function promptCodeAgent(chatId: string, text: string, attachments?: Atta
return invoke('agente_prompt', { chatId, text, attachments });
}
-export function steerCodeAgent(chatId: string, text: string, attachments?: Attachment[]): Promise<{ ok: boolean }> {
+export function steerCodeAgent(chatId: string, text: string, attachments?: Attachment[]): Promise<{ ok: boolean; error?: string }> {
return invoke('agente_steer', { chatId, text, attachments });
}
diff --git a/apps/desktop/renderer/src/lib/features/code/code.svelte.ts b/apps/desktop/renderer/src/lib/features/code/code.svelte.ts
index aea76bf7..68abf3d8 100644
--- a/apps/desktop/renderer/src/lib/features/code/code.svelte.ts
+++ b/apps/desktop/renderer/src/lib/features/code/code.svelte.ts
@@ -1,6 +1,7 @@
import { appStore } from '$lib/stores/app.svelte';
import { isConfigModelReady } from '$lib/stores/chat-model';
import { approvalsStore } from '$lib/stores/approvals.svelte';
+import { toastStore } from '$lib/stores/toast.svelte';
import {
loadCodeProjectsFromDb,
saveCodeProjectToDb,
@@ -950,6 +951,8 @@ class CodeStore {
try {
const result = await steerCodeAgent(chatId, text, attachments);
if (result.ok) return;
+ // The message stays in the panel to edit or resend; say why.
+ if (result.error) toastStore.error(result.error);
} catch { /* falls through: back to the panel */ }
this.#rollbackQueued(run);
item.sending = false;
diff --git a/apps/desktop/renderer/src/lib/services/research-artifacts.spec.ts b/apps/desktop/renderer/src/lib/services/research-artifacts.spec.ts
index 2cf6f9e2..9f6169d6 100644
--- a/apps/desktop/renderer/src/lib/services/research-artifacts.spec.ts
+++ b/apps/desktop/renderer/src/lib/services/research-artifacts.spec.ts
@@ -95,3 +95,26 @@ describe('research-artifacts', () => {
expect(parseExportKinds('shortlist,bibliography')).toEqual(['shortlist', 'bibliography']);
});
});
+
+describe('citation identity', () => {
+ const source = (url: string, title = 'Doc'): SearchResult => ({
+ title, url, snippet: 'snippet', full_content: '', provider: 'test', providers: ['test'], source_rank: 1,
+ published_at: null, metadata: {},
+ } as unknown as SearchResult);
+
+ it('keeps pages whose paths differ only in case', () => {
+ const citations = buildResearchCitations([
+ source('https://Docs.Example/docs/Api'),
+ source('https://docs.example/docs/API'),
+ source('https://DOCS.example/docs/Api#section'),
+ ]);
+ expect(citations.map((c) => c.url)).toEqual(['https://Docs.Example/docs/Api', 'https://docs.example/docs/API']);
+ });
+
+ it('exports the whole destination of a long link', () => {
+ const url = `https://example.test/search?q=${'x'.repeat(520)}&page=2`;
+ const [citation] = buildResearchCitations([source(url)]);
+ expect(citation.url).toBe(url);
+ expect(buildApaReferences([citation])).toContain('&page=2');
+ });
+});
diff --git a/apps/desktop/renderer/src/lib/services/research-artifacts.ts b/apps/desktop/renderer/src/lib/services/research-artifacts.ts
index 77ee9a7a..23e86493 100644
--- a/apps/desktop/renderer/src/lib/services/research-artifacts.ts
+++ b/apps/desktop/renderer/src/lib/services/research-artifacts.ts
@@ -100,15 +100,37 @@ function takeawayFromSource(source: SearchResult): string {
return clean(sentence, 220);
}
+/**
+ * Which source a URL names: scheme and host are case-insensitive and the
+ * fragment never reaches the server, but the path and query are the
+ * site's own (`/docs/Api` and `/docs/API` can be two pages). A source
+ * without a URL is known by its title.
+ */
+export function sourceIdentity(url: unknown, title: unknown = ''): string {
+ const raw = String(url ?? '').trim();
+ if (raw) {
+ try {
+ const parsed = new URL(raw);
+ parsed.hash = '';
+ return parsed.toString();
+ } catch {
+ return raw.replace(/#.*$/, '');
+ }
+ }
+ return clean(title, 240).toLowerCase();
+}
+
/** Normalize and dedupe sources for research exports. Never invent metadata. */
export function buildResearchCitations(sources: SearchResult[]): ResearchCitation[] {
const seen = new Set();
const out: ResearchCitation[] = [];
for (const source of sources || []) {
- const url = clean(source.url, 500);
+ // The whole destination: a long query string can carry the part that
+ // matters (`&page=2`). Only the visible label is ever shortened.
+ const url = String(source.url ?? '').trim();
const title = clean(source.title || url, 240);
if (!url && !title) continue;
- const key = (url || title).toLowerCase().replace(/#.*$/, '');
+ const key = sourceIdentity(url, title);
if (seen.has(key)) continue;
seen.add(key);
out.push({
diff --git a/apps/desktop/renderer/src/lib/stores/app.svelte.ts b/apps/desktop/renderer/src/lib/stores/app.svelte.ts
index 8ded96c8..ae464942 100644
--- a/apps/desktop/renderer/src/lib/stores/app.svelte.ts
+++ b/apps/desktop/renderer/src/lib/stores/app.svelte.ts
@@ -2584,10 +2584,21 @@ class AppStore {
// A reply that never recorded its first version keeps it as version 1.
if (!message.versions?.length && message.content) {
- message.versions = [{ content: message.content, reasoning: message.reasoning || '', createdAt: message.createdAt, metadata: message.metadata }];
- }
+ message.versions = [{ content: message.content, reasoning: message.reasoning || '', createdAt: message.createdAt, metadata: message.metadata, sources: [...(message.sources || [])] }];
+ }
+ // Sources belong to the answer that cites them: the version being left
+ // keeps its own, and the new one starts empty, so a retry's `[1]` never
+ // points at the previous answer's first source.
+ const leaving = message.versions?.[message.activeVersion ?? 0];
+ if (leaving && leaving.sources === undefined) leaving.sources = [...(message.sources || [])];
+ nextVersion.sources = [];
+ message.sources = [];
message.versions = [...(message.versions || []), nextVersion];
message.activeVersion = message.versions.length - 1;
+ // The array element is the reactive copy the transcript reads; writes to
+ // the plain `nextVersion` object no longer reach it, which left a
+ // finished retry showing its progress placeholder.
+ const liveVersion = message.versions[message.activeVersion];
message.content = agentic ? optimisticAck(regenPrompt, message.mode === 'agent' ? 'work' : 'lookup') : '';
message.reasoning = '';
message.done = false;
@@ -2605,9 +2616,9 @@ class AppStore {
currentActivity: initial.activity,
activityLabel: activityLabel(initial.activity)
};
- nextVersion.content = message.content;
- nextVersion.reasoning = message.reasoning;
- nextVersion.metadata = { ...(nextVersion.metadata || {}), currentActivity: initial.activity, activityLabel: activityLabel(initial.activity), codeTimeline: undefined };
+ liveVersion.content = message.content;
+ liveVersion.reasoning = message.reasoning;
+ liveVersion.metadata = { ...(liveVersion.metadata || {}), currentActivity: initial.activity, activityLabel: activityLabel(initial.activity), codeTimeline: undefined };
message.artifact = null;
message.artifacts = [];
if (this.currentArtifactMessageId === message.id) {
@@ -2619,7 +2630,7 @@ class AppStore {
await executeChatTurn(this.chatTurnHost, {
chatId: targetChatId,
message,
- targetVersion: nextVersion,
+ targetVersion: liveVersion,
backendMode: activeBackendMode,
runMode: message.mode === 'instant' ? 'instant' : message.mode === 'agent' ? 'agent' : 'chat',
modelLabel: activeModelLabel,
@@ -2681,7 +2692,7 @@ class AppStore {
onSuccess: async () => {
if (message.mode === 'slides') {
try {
- const slides = await parseSlidesFromMarkdown(nextVersion.content);
+ const slides = await parseSlidesFromMarkdown(liveVersion.content);
message.slides = slides.length ? slides : [];
} catch {
message.slides = [];
@@ -2700,6 +2711,9 @@ class AppStore {
const next = Math.max(0, Math.min(current + direction, message.versions.length - 1));
if (next === current) return;
message.activeVersion = next;
+ // Citations resolve against the shown answer's own sources.
+ const shownSources = message.versions[next]?.sources;
+ if (shownSources) message.sources = [...shownSources];
if (chat.contextMode === 'roleplay') {
const version = message.versions[next];
const snapshot = version.metadata?.roleplay;
diff --git a/apps/desktop/renderer/src/lib/stores/chat-turn.ts b/apps/desktop/renderer/src/lib/stores/chat-turn.ts
index 95ff68de..e335bb7e 100644
--- a/apps/desktop/renderer/src/lib/stores/chat-turn.ts
+++ b/apps/desktop/renderer/src/lib/stores/chat-turn.ts
@@ -113,6 +113,7 @@ export async function executeChatTurn(host: ChatTurnHost, args: ExecuteChatTurnA
if (!targetVersion) return;
targetVersion.content = message.content;
targetVersion.reasoning = message.reasoning;
+ if (message.sources) targetVersion.sources = [...message.sources];
const { currentActivity, activityLabel: label, codeTimeline } = message.metadata || {};
if (currentActivity) {
targetVersion.metadata = { ...(targetVersion.metadata || {}), currentActivity, activityLabel: label, codeTimeline };
@@ -143,12 +144,14 @@ export async function executeChatTurn(host: ChatTurnHost, args: ExecuteChatTurnA
targetVersion.content = message.content;
targetVersion.reasoning = message.reasoning;
targetVersion.metadata = message.metadata;
+ targetVersion.sources = [...(message.sources || [])];
} else {
message.versions = [{
content: message.content,
createdAt: message.createdAt,
reasoning: message.reasoning,
- metadata: message.metadata
+ metadata: message.metadata,
+ sources: [...(message.sources || [])]
}];
}
};
@@ -202,6 +205,7 @@ export async function executeChatTurn(host: ChatTurnHost, args: ExecuteChatTurnA
targetVersion.content = message.content;
targetVersion.reasoning = message.reasoning;
targetVersion.metadata = message.metadata;
+ targetVersion.sources = [...(message.sources || [])];
}
if (execution.agentDebugLogs && (agentResult.warning || agentResult.error)) {
console.info('[agent]', agentResult.warning || agentResult.error);
diff --git a/apps/desktop/renderer/src/lib/stores/deep-research-evidence.spec.ts b/apps/desktop/renderer/src/lib/stores/deep-research-evidence.spec.ts
new file mode 100644
index 00000000..581a4988
--- /dev/null
+++ b/apps/desktop/renderer/src/lib/stores/deep-research-evidence.spec.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import type { SearchResult } from '$lib/types/bridge';
+import { renumberEvidence } from './deep-research.svelte';
+
+const result = (url: string, title: string) => ({ url, title, snippet: '' } as unknown as SearchResult);
+const block = (n: string, title: string, url: string) => `## [${n}] ${title}\n\nURL: ${url}\n\ntext about ${title}`;
+
+describe('deep research evidence numbering', () => {
+ it('gives each source the id it has in the merged source index', () => {
+ const alpha = result('https://alpha.test/', 'Alpha');
+ const beta = result('https://beta.test/', 'Beta');
+ const merged = [alpha, beta];
+ const used = new Set();
+ const first = renumberEvidence(block('1', 'Alpha', alpha.url), [alpha], merged, 24, used);
+ const second = renumberEvidence(block('1', 'Beta', beta.url), [beta], merged, 24, used);
+ expect(first).toContain('## [1] Alpha');
+ expect(second).toContain('## [2] Beta');
+ expect(second).not.toContain('## [1]');
+ });
+
+ it('keeps one block for a URL found under different ranks and maps crawler ids', () => {
+ const alpha = result('https://alpha.test/', 'Alpha');
+ const gamma = result('https://gamma.test/', 'Gamma');
+ const merged = [alpha, gamma];
+ const used = new Set();
+ renumberEvidence(block('1', 'Alpha', alpha.url), [alpha], merged, 24, used);
+ const again = renumberEvidence(
+ [block('1', 'Gamma', gamma.url), block('2', 'Alpha', alpha.url)].join('\n\n---\n\n'),
+ [gamma, alpha], merged, 24, used,
+ );
+ expect(again).toContain('## [2] Gamma');
+ expect(again).not.toContain('Alpha');
+ const crawl = renumberEvidence(block('C1', 'Gamma', gamma.url), [gamma], merged, 24, new Set());
+ expect(crawl).toContain('## [2] Gamma');
+ });
+});
diff --git a/apps/desktop/renderer/src/lib/stores/deep-research.svelte.ts b/apps/desktop/renderer/src/lib/stores/deep-research.svelte.ts
index 0fd7409b..76609540 100644
--- a/apps/desktop/renderer/src/lib/stores/deep-research.svelte.ts
+++ b/apps/desktop/renderer/src/lib/stores/deep-research.svelte.ts
@@ -6,6 +6,7 @@ import {
} from '$lib/services/agent-prompts';
import { listen, invoke, isElectron } from '$lib/services/bridge';
import { webSearch } from '$lib/services/search';
+import { sourceIdentity } from '$lib/services/research-artifacts';
import { createId } from '$lib/utils/id';
import { safeParse, normalizeWhitespace } from '$lib/utils/storage';
@@ -203,7 +204,7 @@ function raceWithAbort(promise: Promise, signal?: AbortSignal): Promise
}
async function synthesizeResearch(task: DeepResearchTask, signal?: AbortSignal): Promise {
- const sourceLines = buildSourceLines(task, task.mode === 'max' ? 40 : 24);
+ const sourceLines = buildSourceLines(task, sourceLimit(task.mode));
const answerContext = buildAnswerContext(task);
const query = task.enhancedQuery || task.query;
const medical = isMedicalResearchQuery(query);
@@ -626,13 +627,15 @@ class DeepResearchStore {
if (signal.aborted || this.getTask(taskId)?.status === 'cancelled') return;
const allResults: SearchResult[] = [];
- let combinedContext = '';
+ // Each search's own context with the results its numbers refer to;
+ // renumbered against the merged list once it is known.
+ const searchContexts: Array<{ context: string; results: SearchResult[] }> = [];
const providers = new Set();
for (const result of searchResults) {
if (result.status === 'fulfilled' && result.value) {
allResults.push(...(result.value.results || []));
- combinedContext += (result.value.context || '') + '\n\n';
+ searchContexts.push({ context: result.value.context || '', results: result.value.results || [] });
if (result.value.provider_used) providers.add(result.value.provider_used);
const providerWarnings = normalizeWhitespace(result.value.error || '');
if (providerWarnings && /401|unauthorized|authentication/i.test(providerWarnings)) {
@@ -642,6 +645,13 @@ class DeepResearchStore {
}
const dedupedResults = dedupeResults(allResults).slice(0, 36);
+ const combinedContext = (() => {
+ const used = new Set();
+ return searchContexts
+ .map(({ context, results }) => renumberEvidence(context, results, dedupedResults, sourceLimit(task?.mode || 'deep'), used))
+ .filter(Boolean)
+ .join('\n\n---\n\n');
+ })();
this.updateTask(taskId, (entry) => ({
...entry,
status: 'crawling',
@@ -677,7 +687,14 @@ class DeepResearchStore {
if (signal.aborted || this.getTask(taskId)?.status === 'cancelled') return;
const merged = dedupeResults([...(dedupedResults || []), ...((crawl?.results || []) as SearchResult[])]).slice(0, task.mode === 'max' ? 70 : 36);
- const mergedContext = [combinedContext, crawl?.context || ''].filter(Boolean).join('\n\n---\n\n');
+ // One numbering for every block: the merged list's, which the source
+ // index in the synthesis prompt is built from.
+ const evidenceUsed = new Set();
+ const limit = sourceLimit(task.mode);
+ const mergedContext = [
+ ...searchContexts.map(({ context, results }) => renumberEvidence(context, results, merged, limit, evidenceUsed)),
+ renumberEvidence(crawl?.context || '', (crawl?.results || []) as SearchResult[], merged, limit, evidenceUsed),
+ ].filter(Boolean).join('\n\n---\n\n');
this.updateTask(taskId, (entry) => ({
...entry,
@@ -811,14 +828,56 @@ function entryMode(taskId: string, tasks: DeepResearchTask[]) {
function dedupeResults(results: SearchResult[]) {
const seen = new Set();
return (Array.isArray(results) ? results : []).filter((entry) => {
- const url = normalizeWhitespace(entry?.url || '').toLowerCase();
- if (!url) return false;
- if (seen.has(url)) return false;
- seen.add(url);
+ if (!normalizeWhitespace(entry?.url || '')) return false;
+ const key = sourceIdentity(entry.url);
+ if (seen.has(key)) return false;
+ seen.add(key);
return true;
});
}
+/** How many sources the synthesis prompt lists (and may cite). */
+function sourceLimit(mode: string): number {
+ return mode === 'max' ? 40 : 24;
+}
+
+/**
+ * Give every evidence block the number its source has in `merged`, the list
+ * the source index is built from. Each search (and the crawler, `[C n]`)
+ * numbers its own results from one, so two queries both said `[1]` for
+ * different pages. A block whose source is not in the first `limit` merged
+ * results, or was already given, is dropped; blocks with no number (the
+ * crawler's condensed summary) are kept as they are.
+ */
+export function renumberEvidence(
+ context: string,
+ results: SearchResult[],
+ merged: SearchResult[],
+ limit: number,
+ used: Set,
+): string {
+ const idByIdentity = new Map();
+ merged.slice(0, limit).forEach((entry, index) => {
+ const key = sourceIdentity(entry.url);
+ if (!idByIdentity.has(key)) idByIdentity.set(key, index + 1);
+ });
+ const blocks: string[] = [];
+ for (const block of String(context || '').split(/\n\n---\n\n/)) {
+ if (!block.trim()) continue;
+ const header = block.match(/^\s*## \[C?(\d+)\] /);
+ if (!header) {
+ blocks.push(block.trim());
+ continue;
+ }
+ const source = results[Number(header[1]) - 1];
+ const id = source?.url ? idByIdentity.get(sourceIdentity(source.url)) : undefined;
+ if (!id || used.has(id)) continue;
+ used.add(id);
+ blocks.push(block.trim().replace(/^## \[C?\d+\] /, `## [${id}] `));
+ }
+ return blocks.join('\n\n---\n\n');
+}
+
function isAuthFailure(searchError: unknown) {
const text = normalizeWhitespace(searchError || '').toLowerCase();
return text.includes('401')
diff --git a/apps/desktop/renderer/src/lib/types/chat.ts b/apps/desktop/renderer/src/lib/types/chat.ts
index 8a5e2dfe..99c5c82f 100644
--- a/apps/desktop/renderer/src/lib/types/chat.ts
+++ b/apps/desktop/renderer/src/lib/types/chat.ts
@@ -32,6 +32,12 @@ export interface MessageVersion {
content: string;
reasoning?: string;
createdAt: number;
+ /**
+ * The sources this version's answer cites; its `[n]` markers index into
+ * them. Absent on versions saved before sources moved here, which fall
+ * back to the message's list.
+ */
+ sources?: SearchResult[];
metadata?: {
/** Optional reaction chosen by the Home agent for a user message. */
agentReaction?: string;
diff --git a/apps/desktop/renderer/src/lib/utils/autosave.spec.ts b/apps/desktop/renderer/src/lib/utils/autosave.spec.ts
index 5d5e4a5f..4d766f71 100644
--- a/apps/desktop/renderer/src/lib/utils/autosave.spec.ts
+++ b/apps/desktop/renderer/src/lib/utils/autosave.spec.ts
@@ -68,4 +68,35 @@ describe('createAutosaveController', () => {
controller.dispose();
vi.useRealTimers();
});
+
+ it('cancel drops a pending write and waits for one under way', async () => {
+ vi.useFakeTimers();
+ const pending = vi.fn(async () => undefined);
+ const idle = createAutosaveController(pending, () => undefined, 300);
+ idle.schedule('aggregator');
+ await idle.cancel();
+ await vi.advanceTimersByTimeAsync(300);
+ expect(pending).not.toHaveBeenCalled();
+ idle.dispose();
+
+ let release: (() => void) | undefined;
+ const order: string[] = [];
+ const running = vi.fn((value: string) => {
+ order.push(`start ${value}`);
+ return new Promise((resolve) => {
+ release = () => { order.push(`end ${value}`); resolve(); };
+ });
+ });
+ const busy = createAutosaveController(running, () => undefined, 10);
+ busy.schedule('aggregator');
+ await vi.advanceTimersByTimeAsync(10);
+ busy.schedule('later');
+ const cancelled = busy.cancel().then(() => order.push('cancelled'));
+ release?.();
+ await cancelled;
+ await vi.advanceTimersByTimeAsync(50);
+ expect(order).toEqual(['start aggregator', 'end aggregator', 'cancelled']);
+ busy.dispose();
+ vi.useRealTimers();
+ });
});
diff --git a/apps/desktop/renderer/src/lib/utils/autosave.ts b/apps/desktop/renderer/src/lib/utils/autosave.ts
index ae472c4b..62f4c7c0 100644
--- a/apps/desktop/renderer/src/lib/utils/autosave.ts
+++ b/apps/desktop/renderer/src/lib/utils/autosave.ts
@@ -11,6 +11,12 @@ export interface AutosaveController {
block(message: string, value?: T): void;
retry(): void;
flush(): Promise;
+ /**
+ * Drop the pending value and wait for a write already under way, so an
+ * explicit save made next is the last word (a debounced write of an older
+ * value can no longer land after it).
+ */
+ cancel(): Promise;
dispose(): void;
}
@@ -25,10 +31,19 @@ export function createAutosaveController(
let hasValue = false;
let running = false;
let disposed = false;
+ let inflight: Promise | null = null;
- async function persist(targetRevision: number, value: T) {
- if (disposed) return;
- if (running) return;
+ function persist(targetRevision: number, value: T): Promise {
+ if (disposed || running) return inflight ?? Promise.resolve();
+ const run = persistNow(targetRevision, value);
+ inflight = run;
+ void run.finally(() => {
+ if (inflight === run) inflight = null;
+ });
+ return run;
+ }
+
+ async function persistNow(targetRevision: number, value: T) {
running = true;
onstate({ state: 'saving', value });
try {
@@ -47,7 +62,7 @@ export function createAutosaveController(
} finally {
running = false;
if (targetRevision !== revision && hasValue && latestValue !== undefined && !disposed) {
- await persist(revision, latestValue);
+ await persistNow(revision, latestValue);
}
}
}
@@ -90,6 +105,14 @@ export function createAutosaveController(
if (hasValue && latestValue !== undefined) schedule(latestValue);
},
flush,
+ async cancel() {
+ if (timer) clearTimeout(timer);
+ timer = undefined;
+ hasValue = false;
+ latestValue = undefined;
+ revision += 1;
+ if (inflight) await inflight.catch(() => undefined);
+ },
dispose() {
if (timer) clearTimeout(timer);
timer = undefined;
diff --git a/apps/desktop/tests/crawler/crawler-budgets.test.js b/apps/desktop/tests/crawler/crawler-budgets.test.js
new file mode 100644
index 00000000..5a738201
--- /dev/null
+++ b/apps/desktop/tests/crawler/crawler-budgets.test.js
@@ -0,0 +1,121 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { crawlWeb } from '../../main/web-crawler.ts';
+import { scoreLinksForQuery } from '../../main/link-scorer.ts';
+import { setEmbeddingStatus } from '../../main/embedding-state.ts';
+import { clearEmbeddingCache, cosineSimilarity } from '../../main/embedding-client.ts';
+
+const scoreAll = async ({ links }) => links.map((link) => ({ ...link, relevance_score: 1 }));
+
+test('failed reads count toward a hard attempt cap', async () => {
+ const site = {};
+ for (let i = 0; i < 10; i += 1) {
+ site[`https://seed.test/${i}`] = {
+ title: `Seed ${i}`,
+ content: `Readable seed page ${i} with text.`,
+ links: Array.from({ length: 7 }, (_, j) => ({ text: 'dead', url: `https://dead.test/${i}-${j}` }))
+ };
+ }
+ let reads = 0;
+ const result = await crawlWeb({
+ query: 'seed', mode: 'deep', seed_urls: Object.keys(site)
+ }, {
+ scrapeFn: async ({ url }) => {
+ reads += 1;
+ return site[url] ? { ...site[url], url } : { error: 'not found', content: '' };
+ },
+ scoreFn: scoreAll
+ });
+ assert.ok(reads <= 36, `bounded network reads (${reads})`);
+ assert.equal(result.stats.pages_attempted, reads);
+ assert.equal(result.stats.pages_failed, reads - result.stats.pages_crawled);
+ assert.equal(result.stats.pages_crawled, 10, 'collected pages are kept');
+});
+
+test('a trailing slash is requested as written', async () => {
+ const requested = [];
+ const result = await crawlWeb({ query: 'guide', seed_urls: ['https://docs.test/guide/'] }, {
+ scrapeFn: async ({ url }) => {
+ requested.push(url);
+ return url === 'https://docs.test/guide/'
+ ? { title: 'Guide', content: 'The guide article.', links: [] }
+ : { error: 'not found', content: '' };
+ },
+ scoreFn: scoreAll
+ });
+ assert.deepEqual(requested, ['https://docs.test/guide/']);
+ assert.equal(result.results.length, 1);
+});
+
+test('a relevant late paragraph survives a small context budget', async () => {
+ const intro = Array.from({ length: 30 }, (_, i) => `Introductory paragraph ${i} about general topics and background material.`).join('\n\n');
+ const content = `${intro}\n\nUnique reimbursement deadline: claims are due within 30 days.`;
+ const result = await crawlWeb({
+ query: 'reimbursement deadline', seed_urls: ['https://policy.test/'], context_budget_chars: 1000
+ }, {
+ scrapeFn: async () => ({ title: 'Policy', content, links: [] }),
+ scoreFn: scoreAll
+ });
+ assert.ok(result.context.includes('Unique reimbursement deadline'), result.context);
+ assert.ok(result.results[0].full_content.includes('\n\n'), 'paragraph breaks kept');
+ assert.equal(result.stats.truncated, true);
+});
+
+test('a source that does not fit is excerpted or reported, never silently dropped', async () => {
+ const site = {
+ 'https://s.test/first': 'text '.repeat(24),
+ 'https://s.test/second': 'second '.repeat(78),
+ 'https://s.test/third': 'text '.repeat(24) + 'third',
+ };
+ const result = await crawlWeb({
+ query: 'text', seed_urls: Object.keys(site), context_budget_chars: 1000
+ }, {
+ scrapeFn: async ({ url }) => ({ title: url, content: site[url], links: [] }),
+ scoreFn: scoreAll
+ });
+ assert.equal(result.results.length, 3);
+ assert.ok(result.context.includes('https://s.test/third'), result.context);
+ if (!result.context.includes('URL: https://s.test/third')) {
+ assert.equal(result.stats.truncated, true);
+ }
+});
+
+test('semantic link scoring runs when embeddings are ready', async () => {
+ assert.ok(Math.abs(cosineSimilarity([1, 0], [1, 0]) - 1) < 1e-9);
+ assert.equal(cosineSimilarity([1, 0], [1, 0, 0]), 0);
+
+ const vectorFor = (text) => (/reimbursement|repayment/i.test(text) ? [1, 0] : [0, 1]);
+ let requests = 0;
+ const server = createServer((req, res) => {
+ let body = '';
+ req.on('data', (chunk) => { body += chunk; });
+ req.on('end', () => {
+ requests += 1;
+ const input = JSON.parse(body).input;
+ const inputs = Array.isArray(input) ? input : [input];
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ data: inputs.map((text, index) => ({ index, embedding: vectorFor(text) })) }));
+ });
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ setEmbeddingStatus({ state: 'ready', port: server.address().port });
+ clearEmbeddingCache();
+ try {
+ const scored = await scoreLinksForQuery({
+ query: 'reimbursement',
+ links: [
+ { text: 'expense repayment policy', url: 'https://hr.test/policy' },
+ { text: 'office map', url: 'https://hr.test/map' },
+ ],
+ });
+ assert.ok(requests > 0, 'the embedding endpoint was asked');
+ const policy = scored.find((link) => link.url.endsWith('/policy'));
+ assert.ok(policy.relevance.semantic > 0.9, JSON.stringify(policy.relevance));
+ assert.equal(scored[0].url, 'https://hr.test/policy');
+ } finally {
+ setEmbeddingStatus({ state: 'stopped', port: null });
+ clearEmbeddingCache();
+ server.close();
+ }
+});
diff --git a/apps/desktop/tests/unit/search-provider-fixes.test.js b/apps/desktop/tests/unit/search-provider-fixes.test.js
new file mode 100644
index 00000000..b116f687
--- /dev/null
+++ b/apps/desktop/tests/unit/search-provider-fixes.test.js
@@ -0,0 +1,149 @@
+import { afterEach, describe, it } from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import {
+ resetAggregatorCircuitBreakers,
+ searchAggregator,
+} from '../../main/search-providers/aggregator.ts';
+import {
+ buildEffectiveSearchQuery,
+ fetchWithRetry,
+ mergeAndRankResults,
+ normalizeSearchItem,
+ tokenize,
+} from '../../main/search-providers/shared.ts';
+import { searchPerplexity, searchSearxng } from '../../main/search-providers/providers.ts';
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+ resetAggregatorCircuitBreakers();
+});
+
+describe('aggregator health', () => {
+ it('keeps querying an engine that answers with no matches', async () => {
+ let calls = 0;
+ globalThis.fetch = async () => {
+ calls += 1;
+ const body = calls <= 3 ? [] : [{ Title: 'Match', URL: 'https://match.example/', Snippet: 'found' }];
+ return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
+ };
+ for (const query of ['one', 'two', 'three']) {
+ await searchAggregator(query, 3, { aggregator_engines: ['wiby'] });
+ }
+ const options = { aggregator_engines: ['wiby'] };
+ const results = await searchAggregator('four', 3, options);
+ assert.equal(calls, 4, 'the engine is not in cooldown');
+ assert.equal(results.length, 1);
+ const attempt = options.aggregator_diagnostics.engine_attempts[0];
+ assert.equal(attempt.success, true);
+ assert.equal(attempt.result_count, 1);
+ });
+});
+
+describe('SearXNG base URL', () => {
+ for (const base of ['https://search.example/searx/', 'https://search.example/searx', 'https://search.example']) {
+ it(`keeps the path of ${base}`, async () => {
+ let requested = '';
+ globalThis.fetch = async (url) => {
+ requested = String(url);
+ return new Response(JSON.stringify({ results: [] }), { status: 200 });
+ };
+ await searchSearxng('rust', 3, { searxng_base_url: base });
+ const url = new URL(requested);
+ const prefix = new URL(base).pathname.replace(/\/+$/, '');
+ assert.equal(url.pathname, `${prefix}/search`);
+ assert.equal(url.searchParams.get('q'), 'rust');
+ assert.equal(url.searchParams.get('format'), 'json');
+ });
+ }
+});
+
+describe('Perplexity citations', () => {
+ it('returns the structured citations instead of the homepage', async () => {
+ globalThis.fetch = async () => new Response(JSON.stringify({
+ choices: [{ message: { content: 'The answer comes from the original source.[1][2]' } }],
+ citations: ['https://docs.example/actual-source', 'https://other.example/page', 'https://docs.example/actual-source'],
+ }), { status: 200 });
+ const results = await searchPerplexity('q', 5, { perplexity_api_key: 'test' });
+ assert.deepEqual(results.map((r) => r.url), ['https://docs.example/actual-source', 'https://other.example/page']);
+ assert.ok(!results.some((r) => r.url.includes('perplexity.ai')));
+ });
+});
+
+describe('fetchWithRetry body deadline', () => {
+ it('times out a body that stalls after the headers', async () => {
+ const server = createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.write('{"partial":');
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ const started = Date.now();
+ await assert.rejects(fetchWithRetry(`http://127.0.0.1:${port}/`, { timeout_ms: 150, retries: 0 }));
+ assert.ok(Date.now() - started < 2000, 'the deadline covered the body');
+ server.closeAllConnections();
+ server.close();
+ });
+
+ it('a caller abort stops the body read', async () => {
+ const server = createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'text/plain' });
+ res.write('first bytes');
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 100);
+ await assert.rejects(fetchWithRetry(`http://127.0.0.1:${port}/`, { timeout_ms: 10_000, retries: 0, signal: controller.signal }));
+ server.closeAllConnections();
+ server.close();
+ });
+});
+
+describe('ranking identity', () => {
+ it('keeps same-title pages on different hosts apart', () => {
+ const ranked = mergeAndRankResults([
+ normalizeSearchItem('exa', { title: 'Official installation and setup guide', url: 'https://first.example/install', content: 'first host text' }, 0),
+ normalizeSearchItem('exa', { title: 'Official installation and setup guide', url: 'https://second.example/install', content: 'second host text that is longer' }, 1),
+ ], 'installation guide', 5);
+ assert.equal(ranked.length, 2);
+ for (const result of ranked) {
+ const host = new URL(result.url).hostname.split('.')[0];
+ assert.ok(result.full_content.startsWith(host), `${result.url} kept its own text`);
+ }
+ });
+
+ it('keeps versioned docs with different numbers apart', () => {
+ const ranked = mergeAndRankResults([
+ normalizeSearchItem('exa', { title: 'Node 18 docs', url: 'https://nodejs.example/v18' }, 0),
+ normalizeSearchItem('exa', { title: 'Node 20 docs', url: 'https://nodejs.example/v20' }, 1),
+ ], 'node docs', 5);
+ assert.equal(ranked.length, 2);
+ });
+});
+
+describe('effective query', () => {
+ const context = 'User: compare PostgreSQL and PostGIS for spatial data';
+
+ it('sends an explicit freshness query as typed', () => {
+ assert.equal(buildEffectiveSearchQuery('latest Node.js releases', context), 'latest Node.js releases');
+ assert.equal(buildEffectiveSearchQuery('"exact phrase" news', context), '"exact phrase" news');
+ });
+
+ it('resolves a reference from the conversation', () => {
+ const effective = buildEffectiveSearchQuery('what changed in that release?', context);
+ assert.notEqual(effective, 'what changed in that release?');
+ assert.ok(effective.endsWith('what changed in that release?'));
+ });
+});
+
+describe('unicode terms', () => {
+ it('tokenizes Japanese, Arabic and accented Latin', () => {
+ assert.ok(tokenize('日本語の検索 東京').length > 0);
+ assert.deepEqual(tokenize('البحث العربي'), ['البحث', 'العربي']);
+ assert.deepEqual(tokenize('Café Zürich 2024'), ['café', 'zürich', '2024']);
+ assert.deepEqual(tokenize('Rust 1.80 release'), ['rust', '1', '80', 'release']);
+ });
+});
diff --git a/crates/agente-core/src/agent/channel/loop_/mod.rs b/crates/agente-core/src/agent/channel/loop_/mod.rs
index cac06a54..a0bc2ebc 100644
--- a/crates/agente-core/src/agent/channel/loop_/mod.rs
+++ b/crates/agente-core/src/agent/channel/loop_/mod.rs
@@ -42,6 +42,16 @@ use request::{
use stream::{consume_completion_stream, StreamCollected, StreamOutcome};
use todo_review::should_review_todos;
+/// How many times one turn asks a reply the output limit cut off to go on.
+const MAX_LENGTH_CONTINUATIONS: u32 = 2;
+
+const LENGTH_CONTINUE_NOTE: &str = "[Your previous reply was cut off by the output token limit. \
+Continue exactly where it stopped, without repeating what you already wrote.]";
+
+const EMPTY_LENGTH_NOTE: &str = "[Your previous reply hit the output token limit before producing \
+anything usable — probably one very large tool call. Work in smaller steps: split large file \
+writes into several edits and keep each call's arguments short.]";
+
#[allow(clippy::too_many_arguments)]
pub fn spawn_chat_task(
session_id: uuid::Uuid,
@@ -266,6 +276,15 @@ impl TurnState {
messages: Vec,
tokens_after: usize,
) {
+ // The gap was measured against the transcript before compaction and
+ // grows with it; carried over whole it would hold back room the
+ // smaller transcript no longer needs (or, after an overflow, keep
+ // the wrong size). Scale it with the transcript until the next
+ // provider-reported usage measures it again.
+ if self.running_tokens > 0 {
+ self.tokenizer_gap = ((self.tokenizer_gap as u128 * tokens_after as u128)
+ / self.running_tokens as u128) as usize;
+ }
self.messages = messages;
self.running_tokens = tokens_after;
self.tokens_measured = false;
@@ -438,6 +457,8 @@ async fn run_agent_loop_inner(cfg: AgentRunConfig) -> Result<(), AgentLoopFailur
let mut generation_progress = StreamProgress::default();
let mut retry_attempt = 0u32;
let mut empty_response_retries = 0u32;
+ // Replies the output limit cut off that were asked to go on, this turn.
+ let mut length_continuations = 0u32;
let max_retries = 2u32;
let base_delay_ms = 500u64;
const MAX_OVERFLOW_RECOVERIES: u32 = 2;
@@ -761,6 +782,12 @@ async fn run_agent_loop_inner(cfg: AgentRunConfig) -> Result<(), AgentLoopFailur
iteration,
"Empty completion; retrying once"
);
+ if stream_stop_reason == StopReason::Length {
+ // The output limit ran out before anything usable — most
+ // often one huge tool call. The same request would end
+ // the same way, so ask for smaller steps.
+ state.push_message(Message::user(EMPTY_LENGTH_NOTE));
+ }
iteration = iteration.saturating_sub(1);
continue;
}
@@ -772,7 +799,19 @@ async fn run_agent_loop_inner(cfg: AgentRunConfig) -> Result<(), AgentLoopFailur
}
empty_response_retries = 0;
- if stream_stop_reason == StopReason::Length && !full_response.is_empty() {
+ // A reply the output limit cut off mid-text: keep it and ask the model
+ // to go on from where it stopped, a bounded number of times, instead
+ // of ending the turn on half an answer.
+ let continue_after_length = stream_stop_reason == StopReason::Length
+ && tool_calls.is_empty()
+ && !full_response.is_empty()
+ && length_continuations < MAX_LENGTH_CONTINUATIONS
+ && !cancel_signal.is_aborted()
+ && max_iterations.map(|max| iteration < max).unwrap_or(true);
+ if stream_stop_reason == StopReason::Length
+ && !full_response.is_empty()
+ && !continue_after_length
+ {
full_response.push_str("\n\n[response truncated by the model's output limit]");
}
@@ -811,6 +850,17 @@ async fn run_agent_loop_inner(cfg: AgentRunConfig) -> Result<(), AgentLoopFailur
}
}
+ if continue_after_length {
+ length_continuations += 1;
+ tracing::info!(
+ iteration,
+ length_continuations,
+ "Reply hit the output limit; asking the model to continue"
+ );
+ state.push_message(Message::user(LENGTH_CONTINUE_NOTE));
+ continue;
+ }
+
if tool_calls.is_empty()
&& !cancel_signal.is_aborted()
&& user_inbox
diff --git a/crates/agente-core/src/agent/channel/loop_/request.rs b/crates/agente-core/src/agent/channel/loop_/request.rs
index 5dd904c3..1c58ce49 100644
--- a/crates/agente-core/src/agent/channel/loop_/request.rs
+++ b/crates/agente-core/src/agent/channel/loop_/request.rs
@@ -425,6 +425,10 @@ pub(super) fn prepare_request_messages(
if let Some(index) = todo_review_at {
reminder_tokens += inject_todo_review(&mut request_messages, index);
}
+ // Goal, budget and todo notes join the user turn they follow instead of
+ // reaching the provider as two or three user turns in a row
+ // (deterministic, so the cached prefix stays byte-stable).
+ crate::context::compaction::merge_consecutive_user_turns(&mut request_messages);
let request_estimate = used + tool_tokens + reminder_tokens;
(request_messages, request_estimate)
}
diff --git a/crates/agente-core/src/agent/channel/loop_/tests.rs b/crates/agente-core/src/agent/channel/loop_/tests.rs
index b3b326c2..cb13b5c0 100644
--- a/crates/agente-core/src/agent/channel/loop_/tests.rs
+++ b/crates/agente-core/src/agent/channel/loop_/tests.rs
@@ -1072,3 +1072,127 @@ async fn explicit_cap_still_stops_the_loop() {
);
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// Answers in parts: every reply but the last stops at the output limit.
+struct LengthLimitedProvider {
+ info: crate::providers::ProviderInfo,
+ parts: Vec<&'static str>,
+ seen: std::sync::Mutex>>,
+}
+
+#[async_trait::async_trait]
+impl crate::providers::Provider for LengthLimitedProvider {
+ fn info(&self) -> &crate::providers::ProviderInfo {
+ &self.info
+ }
+
+ async fn stream_completion(
+ &self,
+ messages: &[Message],
+ _tools: Option<&[crate::types::ToolDefinition]>,
+ _model: &crate::providers::ModelInfo,
+ sender: tokio::sync::mpsc::Sender,
+ _context: crate::providers::RequestContext,
+ ) -> Result {
+ let call = {
+ let mut seen = self.seen.lock().unwrap();
+ seen.push(messages.to_vec());
+ seen.len() - 1
+ };
+ let last = call + 1 >= self.parts.len();
+ let text = self.parts[call.min(self.parts.len() - 1)];
+ sender
+ .send(crate::llm::StreamEvent::TextDelta(text.to_string()))
+ .await
+ .ok();
+ sender
+ .send(crate::llm::StreamEvent::Done {
+ usage: crate::llm::Usage::default(),
+ stop_reason: if last {
+ crate::llm::StopReason::Stop
+ } else {
+ crate::llm::StopReason::Length
+ },
+ })
+ .await
+ .ok();
+ Ok(crate::llm::Usage::default())
+ }
+
+ async fn list_models(&self) -> Result, crate::llm::LlmError> {
+ Ok(Vec::new())
+ }
+}
+
+#[tokio::test]
+async fn a_reply_cut_by_the_output_limit_is_continued() {
+ use crate::cancellation::AbortController;
+ use crate::permissions::{shared_permission_engine, ApprovalBroker};
+
+ let registry = Arc::new(ProviderRegistry::new());
+ let provider = Arc::new(LengthLimitedProvider {
+ info: crate::providers::ProviderInfo {
+ id: "test-length".into(),
+ models: vec![overflow_test_model()],
+ ..Default::default()
+ },
+ parts: vec!["first half", "second half"],
+ seen: std::sync::Mutex::new(Vec::new()),
+ });
+ registry.register("test-length", provider.clone());
+ let (tx, rx) = std::sync::mpsc::channel();
+ let config = AgentRunConfig {
+ session_id: uuid::Uuid::new_v4(),
+ task_id: 1,
+ sender: tx,
+ messages: vec![Message::user("write the essay")],
+ provider_id: "test-length".into(),
+ model: "stub-model".into(),
+ thinking_level: "off".into(),
+ project_dir: ".".into(),
+ max_iterations: Some(5),
+ registry,
+ catalog: None,
+ permission_engine: shared_permission_engine(AgentMode::Build),
+ cancel_signal: AbortController::new().signal(),
+ approval_broker: ApprovalBroker::new(),
+ mcp_manager: None,
+ subagent_host: None,
+ custom_agents: Vec::new(),
+ tool_policy: None,
+ is_subagent: false,
+ depth: 0,
+ loop_nudge_after: DEFAULT_LOOP_NUDGE_AFTER,
+ loop_stop_after: DEFAULT_LOOP_STOP_AFTER,
+ smart_compaction: false,
+ compaction_model: None,
+ user_inbox: None,
+ extra_tools: Vec::new(),
+ only_tools: None,
+ shell_env: Default::default(),
+ initial_gap: 0,
+ };
+ tokio::time::timeout(std::time::Duration::from_secs(5), run_agent_loop(config))
+ .await
+ .expect("turn finishes")
+ .expect("turn completes");
+
+ let seen = provider.seen.lock().unwrap().clone();
+ assert_eq!(seen.len(), 2, "the cut reply was continued once");
+ let second = &seen[1];
+ assert_eq!(second[second.len() - 2].content, "first half");
+ assert!(second
+ .last()
+ .is_some_and(|m| m.role == Role::User && m.content.contains("cut off")));
+ let done = rx
+ .try_iter()
+ .find_map(|e| match e.event {
+ AgentEvent::Done { conversation, .. } => Some(conversation),
+ _ => None,
+ })
+ .expect("Done");
+ assert_eq!(done.last().unwrap().content, "second half");
+ assert!(!done
+ .iter()
+ .any(|m| m.content.contains("response truncated by the model's output limit")));
+}
diff --git a/crates/agente-core/src/context/compaction/mod.rs b/crates/agente-core/src/context/compaction/mod.rs
index afa323b7..0f8bf207 100644
--- a/crates/agente-core/src/context/compaction/mod.rs
+++ b/crates/agente-core/src/context/compaction/mod.rs
@@ -12,7 +12,8 @@ mod tests;
mod trim;
pub use normalize::{
- normalize_tool_messages, normalize_tool_messages_tracked, CARRIED_SKILLS_HEADING,
+ merge_consecutive_user_turns, normalize_tool_messages, normalize_tool_messages_tracked,
+ CARRIED_SKILLS_HEADING, COMPACTED_GAP_NOTE,
};
pub use semantic::{
build_summarization_messages, serialize_conversation, SummarizeError, Summarizer,
diff --git a/crates/agente-core/src/context/compaction/normalize.rs b/crates/agente-core/src/context/compaction/normalize.rs
index 23683c86..14e32238 100644
--- a/crates/agente-core/src/context/compaction/normalize.rs
+++ b/crates/agente-core/src/context/compaction/normalize.rs
@@ -59,9 +59,10 @@ pub fn normalize_tool_messages_tracked(messages: Vec) -> (Vec,
.is_some_and(|id| expected.remove(id))
{
tool_results.push(tool_result);
+ } else {
+ // A result with a stale/duplicate id is protocol noise — drop it.
+ changed = true;
}
- // A result with a stale/duplicate id is protocol noise — drop it.
- changed = true;
}
if expected.is_empty() {
@@ -97,6 +98,54 @@ pub fn normalize_tool_messages_tracked(messages: Vec) -> (Vec,
(output, changed)
}
+/// Stands in for the user turn compaction removed between two messages.
+pub const COMPACTED_GAP_NOTE: &str = "[Earlier messages were compacted to save context.]";
+
+/// Keep the transcript in an order strict providers accept after
+/// compaction removed messages: the first turn after the system prompt is a
+/// user turn, and two assistant turns never touch. A short user note fills
+/// each gap (the removed turn) instead of guessing at what to merge.
+pub(super) fn repair_role_order(messages: Vec) -> Vec {
+ let mut out: Vec = Vec::with_capacity(messages.len() + 1);
+ for message in messages {
+ if matches!(message.role, Role::Assistant)
+ && out
+ .last()
+ .is_none_or(|prev| matches!(prev.role, Role::System | Role::Assistant))
+ {
+ out.push(Message::user(COMPACTED_GAP_NOTE));
+ }
+ out.push(message);
+ }
+ out
+}
+
+/// Merge runs of plain user messages into one turn (on a request copy):
+/// reminders, a compaction summary, carried skills and queued messages can
+/// otherwise reach the provider as several user turns in a row.
+pub fn merge_consecutive_user_turns(messages: &mut Vec) {
+ fn plain_user(message: &Message) -> bool {
+ matches!(message.role, Role::User)
+ && message.tool_call_id.is_none()
+ && message.tool_calls.as_ref().is_none_or(Vec::is_empty)
+ }
+ let mut out: Vec = Vec::with_capacity(messages.len());
+ for message in messages.drain(..) {
+ if let Some(last) = out.last_mut() {
+ if plain_user(last) && plain_user(&message) {
+ if !last.content.is_empty() && !message.content.is_empty() {
+ last.content.push_str("\n\n");
+ }
+ last.content.push_str(&message.content);
+ last.attachments.extend(message.attachments);
+ continue;
+ }
+ }
+ out.push(message);
+ }
+ *messages = out;
+}
+
pub(super) fn carries_skill(message: &Message) -> bool {
message.content.contains(skills::SKILL_OPEN)
}
diff --git a/crates/agente-core/src/context/compaction/semantic.rs b/crates/agente-core/src/context/compaction/semantic.rs
index 999acc24..d839ec6b 100644
--- a/crates/agente-core/src/context/compaction/semantic.rs
+++ b/crates/agente-core/src/context/compaction/semantic.rs
@@ -2,7 +2,9 @@
use async_trait::async_trait;
-use super::normalize::{carry_skills, compaction_boundary, normalize_tool_messages};
+use super::normalize::{
+ carry_skills, compaction_boundary, normalize_tool_messages, repair_role_order,
+};
use super::{CompactionResult, ContextCompactor, Summary, SummaryMetadata, SummaryType};
use crate::context::budget::estimate_message_tokens;
use crate::types::{Message, Role};
@@ -177,10 +179,12 @@ pub fn build_summarization_messages(
]
}
-/// Build a message that carries a compaction summary into the conversation.
+/// Build a message that carries a compaction summary into the conversation:
+/// a user-side context checkpoint, so the turn after the system prompt is a
+/// user turn and an assistant turn kept from before still follows one.
pub(super) fn summary_message(content: &str) -> Message {
Message {
- role: Role::Assistant,
+ role: Role::User,
content: format!("[Conversation summary]\n{content}"),
tool_calls: None,
tool_call_id: None,
@@ -239,7 +243,7 @@ impl ContextCompactor {
let mut result = system_msgs;
result.push(summary_message(&summary_text));
result.extend(recent);
- result = carry_skills(&messages, normalize_tool_messages(result));
+ result = repair_role_order(carry_skills(&messages, normalize_tool_messages(result)));
let compressed_tokens = estimate_message_tokens(&result);
let tokens_saved = original_tokens.saturating_sub(compressed_tokens);
diff --git a/crates/agente-core/src/context/compaction/tests.rs b/crates/agente-core/src/context/compaction/tests.rs
index e6f3b9e3..d19c94f8 100644
--- a/crates/agente-core/src/context/compaction/tests.rs
+++ b/crates/agente-core/src/context/compaction/tests.rs
@@ -675,3 +675,66 @@ fn serialize_conversation_includes_roles_and_tool_calls() {
assert!(text.contains("read_file"));
assert!(text.contains("a.rs"));
}
+
+#[test]
+fn normalize_reports_no_change_for_a_valid_exchange() {
+ let mut messages = vec![create_message(Role::User, "go")];
+ messages.extend(tool_exchange(&["a", "b"]));
+ let (_, changed) = normalize_tool_messages_tracked(messages);
+ assert!(!changed, "a complete exchange must not force a token recount");
+}
+
+#[test]
+fn role_order_after_compaction_never_starts_or_doubles_on_assistant() {
+ let messages = vec![
+ create_message(Role::System, "system"),
+ create_message(Role::Assistant, "kept reply"),
+ create_message(Role::Assistant, "another reply"),
+ create_message(Role::User, "next"),
+ ];
+ let repaired = super::normalize::repair_role_order(messages);
+ let roles: Vec = repaired.iter().map(|m| m.role.clone()).collect();
+ assert_eq!(
+ roles,
+ [
+ Role::System,
+ Role::User,
+ Role::Assistant,
+ Role::User,
+ Role::Assistant,
+ Role::User
+ ]
+ );
+ assert_eq!(repaired[1].content, COMPACTED_GAP_NOTE);
+}
+
+#[test]
+fn consecutive_user_turns_merge_on_the_request_copy() {
+ let mut messages = vec![
+ create_message(Role::System, "system"),
+ create_message(Role::User, "prompt"),
+ create_message(Role::User, "goal reminder"),
+ create_message(Role::User, "budget notice"),
+ ];
+ merge_consecutive_user_turns(&mut messages);
+ assert_eq!(messages.len(), 2);
+ assert_eq!(messages[1].content, "prompt\n\ngoal reminder\n\nbudget notice");
+ assert!(summary_message("x").role == Role::User);
+}
+
+#[test]
+fn a_huge_single_line_recent_tool_result_still_shrinks() {
+ let mut messages = vec![
+ create_message(Role::System, "system"),
+ create_message(Role::User, "read it"),
+ ];
+ let mut exchange = tool_exchange(&["big"]);
+ exchange[1].content = "x".repeat(400_000);
+ messages.extend(exchange);
+ let before = estimate_tokens_for_test(&messages);
+ let compactor = ContextCompactor::new(CompactionStrategy::new(20_000, 8, 0.85));
+ let result = compactor.compact_forced(messages);
+ assert!(result.summary.tokens_saved > 0);
+ assert!(estimate_tokens_for_test(&result.messages) < before / 10);
+ assert!(result.messages.iter().any(|m| m.content.contains("Tool output truncated")));
+}
diff --git a/crates/agente-core/src/context/compaction/trim.rs b/crates/agente-core/src/context/compaction/trim.rs
index 5afcebe0..cfe302a0 100644
--- a/crates/agente-core/src/context/compaction/trim.rs
+++ b/crates/agente-core/src/context/compaction/trim.rs
@@ -2,7 +2,9 @@
use std::collections::HashSet;
-use super::normalize::{carries_skill, carry_skills, compaction_boundary, normalize_tool_messages};
+use super::normalize::{
+ carries_skill, carry_skills, compaction_boundary, normalize_tool_messages, repair_role_order,
+};
use super::{ContextCompactor, Summary, SummaryMetadata, SummaryType};
use crate::context::budget::{estimate_message_tokens, estimated_message_cost};
use crate::types::{Message, Role};
@@ -30,20 +32,46 @@ impl ContextCompactor {
recent_start = compaction_boundary(&messages, keep, 0);
}
let keep_recent = messages.len().saturating_sub(recent_start);
- let recent: Vec = messages[recent_start..].to_vec();
+ let mut recent: Vec = messages[recent_start..].to_vec();
let older: Vec = messages[..recent_start].to_vec();
// Estimate tokens in recent messages (we'll keep all of these)
- let recent_tokens = tokens_from(recent_start);
+ let mut recent_tokens = tokens_from(recent_start);
+
+ // The newest exchange alone can be over the target — one huge read
+ // or a minified single-line result. Recent messages are otherwise
+ // kept whole, so shrink their largest tool outputs (never a skill)
+ // until they fit, or an overflow recovery saves nothing.
+ let mut recent_saved = 0usize;
+ if recent_tokens > target {
+ let mut largest: Vec = recent
+ .iter()
+ .enumerate()
+ .filter(|(_, m)| matches!(m.role, Role::Tool) && !carries_skill(m))
+ .map(|(i, _)| i)
+ .collect();
+ largest.sort_by_key(|&i| std::cmp::Reverse(estimated_message_cost(&recent[i])));
+ for i in largest {
+ if recent_tokens <= target {
+ break;
+ }
+ let before = estimated_message_cost(&recent[i]);
+ self.compress_tool_result(&mut recent[i]);
+ let saved = before.saturating_sub(estimated_message_cost(&recent[i]));
+ recent_tokens = recent_tokens.saturating_sub(saved);
+ recent_saved += saved;
+ }
+ }
let budget_for_older = target.saturating_sub(recent_tokens);
// Compact older messages to fit the budget
- let (compacted_older, tokens_saved) = self.compact_messages(older, budget_for_older);
+ let (compacted_older, older_saved) = self.compact_messages(older, budget_for_older);
+ let tokens_saved = older_saved + recent_saved;
let mut result = compacted_older;
result.extend(recent);
- result = carry_skills(&messages, normalize_tool_messages(result));
+ result = repair_role_order(carry_skills(&messages, normalize_tool_messages(result)));
let compressed_tokens = estimate_message_tokens(&result);
@@ -180,17 +208,25 @@ impl ContextCompactor {
}
fn compress_tool_result(&self, message: &mut Message) {
- // Tool results are often large; compress significantly
- let max_lines = 10;
- let lines: Vec<&str> = message.content.lines().collect();
-
- if lines.len() > max_lines {
- let kept: Vec<&str> = lines.iter().take(max_lines).cloned().collect();
- message.content = format!(
- "{}\n\n... [Tool output truncated: {} total lines] ...",
- kept.join("\n"),
- lines.len()
- );
+ // Tool results are often large; compress significantly. Bytes are
+ // capped as well as lines: minified JSON or a long log line is one
+ // line, and a line cap alone left it whole.
+ const MAX_LINES: usize = 10;
+ const MAX_BYTES: usize = 2_000;
+ let total_lines = message.content.lines().count();
+ let total_bytes = message.content.len();
+ if total_lines <= MAX_LINES && total_bytes <= MAX_BYTES {
+ return;
}
+ let head = message
+ .content
+ .lines()
+ .take(MAX_LINES)
+ .collect::>()
+ .join("\n");
+ let head = crate::util::truncate_at_char_boundary(&head, MAX_BYTES);
+ message.content = format!(
+ "{head}\n\n... [Tool output truncated: {total_lines} lines, {total_bytes} bytes total] ..."
+ );
}
}
diff --git a/crates/agente-core/src/tools/web/extract.rs b/crates/agente-core/src/tools/web/extract.rs
index bbb335c6..2ffb21ac 100644
--- a/crates/agente-core/src/tools/web/extract.rs
+++ b/crates/agente-core/src/tools/web/extract.rs
@@ -60,6 +60,10 @@ pub fn extract(html: &str, base: Option<&reqwest::Url>) -> Page {
.filter(|s| !s.is_empty())
})
.unwrap_or_default();
+ // ` ` (the first one with an href) resolves relative links;
+ // the response URL is the fallback and resolves a relative base itself.
+ let doc_base = document_base(&document, base);
+ let base = doc_base.as_ref().or(base);
let links = extract_links(&document, base, 120);
let Some(body) = document.select(sel("body")).next() else {
@@ -102,6 +106,25 @@ pub fn extract(html: &str, base: Option<&reqwest::Url>) -> Page {
}
}
+/// The document's base URL: the first ` ` resolved against the
+/// response URL, kept only when it is http(s).
+fn document_base(document: &Html, response: Option<&reqwest::Url>) -> Option {
+ let href = document
+ .select(sel("base[href]"))
+ .next()?
+ .value()
+ .attr("href")?
+ .trim();
+ if href.is_empty() {
+ return None;
+ }
+ let url = match response {
+ Some(r) => r.join(href).ok()?,
+ None => reqwest::Url::parse(href).ok()?,
+ };
+ matches!(url.scheme(), "http" | "https").then_some(url)
+}
+
fn extract_links(
document: &Html,
base: Option<&reqwest::Url>,
@@ -184,7 +207,7 @@ const CONTENT_SELECTOR: &str = "main, [role=main], article, #content, #main, #ma
fn content_root<'a>(document: &'a Html, body: ElementRef<'a>, body_chars: usize) -> ElementRef<'a> {
let candidates: Vec<(ElementRef<'a>, usize)> = document
.select(sel(CONTENT_SELECTOR))
- .filter(|el| !skipped(el))
+ .filter(|el| !skipped(el) && !inside_skipped(el, body))
.map(|el| (el, score(el)))
.collect();
let Some(best) = candidates.iter().map(|(_, s)| *s).max() else {
@@ -203,6 +226,15 @@ fn content_root<'a>(document: &'a Html, body: ElementRef<'a>, body_chars: usize)
.unwrap_or(body)
}
+/// Whether an ancestor of `el` (below `body`) is chrome or hidden: a hidden
+/// archive wrapper must not hand its `` to root selection.
+fn inside_skipped(el: &ElementRef, body: ElementRef) -> bool {
+ el.ancestors()
+ .take_while(|node| node.id() != body.id())
+ .filter_map(ElementRef::wrap)
+ .any(|ancestor| skipped(&ancestor))
+}
+
/// Maximum DOM traversal depth to prevent stack overflow on pathological HTML.
const MAX_DEPTH: usize = 128;
@@ -586,7 +618,8 @@ impl<'b> Writer<'b> {
if text.is_empty() {
String::new()
} else if text.contains('`') {
- format!("`` {text} ``")
+ let ticks = "`".repeat(longest_backtick_run(&text) + 1);
+ format!("{ticks} {text} {ticks}")
} else {
format!("`{text}`")
}
@@ -677,22 +710,70 @@ impl<'b> Writer<'b> {
{
return None;
}
- let grid: Vec> = rows
- .iter()
- .map(|row| {
- row.child_elements()
- .filter(|c| matches!(c.value().name(), "td" | "th"))
- .map(|cell| {
- self.sub_with_mode(cell, true)
- .replace('\n', " ")
- .replace('|', "\\|")
- .trim()
- .to_string()
- })
- .collect::>()
- })
- .filter(|row| row.iter().any(|cell| !cell.is_empty()))
- .collect();
+ // Lay cells on a grid: a `rowspan` cell occupies its column in the
+ // rows below and a `colspan` cell the columns beside it, each copy
+ // carrying the value so every row keeps its data under its heading.
+ let span = |cell: &ElementRef, name: &str| {
+ cell.value()
+ .attr(name)
+ .and_then(|v| v.trim().parse::().ok())
+ .map(|n| n.clamp(1, 64))
+ .unwrap_or(1)
+ };
+ // Column -> (rows still covered, value) of a rowspan from above.
+ let mut pending: Vec> = Vec::new();
+ let take_pending =
+ |col: usize, out: &mut Vec, pending: &mut Vec>| {
+ let Some(Some((left, value))) = pending.get_mut(col) else {
+ return false;
+ };
+ out.push(value.clone());
+ *left -= 1;
+ if *left == 0 {
+ pending[col] = None;
+ }
+ true
+ };
+ let mut grid: Vec> = Vec::with_capacity(rows.len());
+ for row in &rows {
+ let mut out: Vec = Vec::new();
+ let mut col = 0;
+ for cell in row
+ .child_elements()
+ .filter(|c| matches!(c.value().name(), "td" | "th"))
+ {
+ while take_pending(col, &mut out, &mut pending) {
+ col += 1;
+ }
+ let text = self
+ .sub_with_mode(cell, true)
+ .replace('\n', " ")
+ .replace('|', "\\|")
+ .trim()
+ .to_string();
+ let (rowspan, colspan) = (span(&cell, "rowspan"), span(&cell, "colspan"));
+ for _ in 0..colspan {
+ if rowspan > 1 {
+ if pending.len() <= col {
+ pending.resize(col + 1, None);
+ }
+ pending[col] = Some((rowspan - 1, text.clone()));
+ }
+ out.push(text.clone());
+ col += 1;
+ }
+ }
+ // Spans from above that reach past this row's last cell.
+ while col < pending.len() {
+ if !take_pending(col, &mut out, &mut pending) {
+ out.push(String::new());
+ }
+ col += 1;
+ }
+ if out.iter().any(|cell| !cell.is_empty()) {
+ grid.push(out);
+ }
+ }
let columns = grid.iter().map(Vec::len).max().unwrap_or(0);
if grid.len() < 2 || columns < 2 {
return None;
@@ -759,10 +840,25 @@ fn code_block(el: ElementRef, depth: usize) -> String {
if text.is_empty() {
return String::new();
}
- let fence = if text.contains("```") { "````" } else { "```" };
+ let fence = "`".repeat(longest_backtick_run(text).max(2) + 1);
format!("{fence}{language}\n{text}\n{fence}")
}
+/// Longest run of consecutive backticks: the fence around a code block must
+/// be longer, or a fence inside the code would close it early.
+fn longest_backtick_run(text: &str) -> usize {
+ let (mut best, mut run) = (0, 0);
+ for ch in text.chars() {
+ if ch == '`' {
+ run += 1;
+ best = best.max(run);
+ } else {
+ run = 0;
+ }
+ }
+ best
+}
+
/// Source whitespace (newlines included) is one space; ` ` adds a real
/// newline through the writer.
fn push_text(out: &mut String, text: &str) {
@@ -1086,4 +1182,77 @@ mod tests {
assert_eq!(page.links[1].domain, "rust-lang.org");
assert!(!page.links[1].same_site);
}
+
+ #[test]
+ fn base_href_resolves_relative_links() {
+ let base = reqwest::Url::parse("https://example.test/docs/intro.html").unwrap();
+ let html = r#"
+ See install for the setup steps.
"#;
+ let page = extract(html, Some(&base));
+ assert!(
+ page.markdown
+ .contains("[install](https://example.test/reference/installation.html)"),
+ "{}",
+ page.markdown
+ );
+ assert_eq!(
+ page.links[0].url,
+ "https://example.test/reference/installation.html"
+ );
+
+ let absolute = extract(
+ r#"y link
"#,
+ Some(&base),
+ );
+ assert_eq!(absolute.links[0].url, "https://other.test/x/y");
+
+ let invalid = extract(
+ r#"y link
"#,
+ Some(&base),
+ );
+ assert_eq!(invalid.links[0].url, "https://example.test/docs/y");
+ }
+
+ #[test]
+ fn hidden_article_does_not_replace_visible_content() {
+ let visible = "Current guide sentence with real words. ".repeat(10);
+ let archived = "Archived guide sentence that is much longer. ".repeat(40);
+ let html = format!(
+ r#"{visible}
+ "#
+ );
+ let out = md(&html);
+ assert!(out.contains("Current guide"), "{out}");
+ assert!(!out.contains("Archived guide"), "{out}");
+ }
+
+ #[test]
+ fn code_fence_outlasts_backtick_runs_inside() {
+ let out = md("````md\nexample\n````\nliteral line ");
+ assert!(
+ out.starts_with("`````\n````md\nexample\n````\nliteral line\n`````"),
+ "{out}"
+ );
+ let three = md("```\nx\n```\ntail ");
+ assert!(three.starts_with("````\n```\nx"), "{three}");
+ let inline = md("Use a``b here
");
+ assert!(inline.contains("``` a``b ```"), "{inline}");
+ }
+
+ #[test]
+ fn rowspan_and_colspan_keep_cells_under_their_headings() {
+ let html = r#"
+ Region Status
+ South Online
+ Offline
+ Total
+
"#;
+ let out = md(html);
+ assert!(
+ out.contains(
+ "| Region | Status |\n| --- | --- |\n| South | Online |\n| South | Offline |\n| Total | Total |"
+ ),
+ "{out}"
+ );
+ }
}
diff --git a/crates/agente-core/src/tools/web/mod.rs b/crates/agente-core/src/tools/web/mod.rs
index 206648a3..7adf69a4 100644
--- a/crates/agente-core/src/tools/web/mod.rs
+++ b/crates/agente-core/src/tools/web/mod.rs
@@ -17,6 +17,7 @@ use std::time::{Duration, Instant};
use futures::StreamExt;
+use super::output::{MAX_OUTPUT_BYTES, MAX_OUTPUT_LINES};
use super::{ToolCore, ToolError, ToolExecutionContext, ToolExecutionMode};
/// A page is read up to this size; html5ever copes with a cut document.
@@ -442,7 +443,7 @@ async fn fetch_page(url: reqwest::Url) -> Result<(Fetched, reqwest::StatusCode),
match classify(&content_type, &bytes) {
Kind::Html => {
- let html = decode(&bytes, &content_type);
+ let html = decode(&bytes, &content_type, true);
let extracted = extract::extract(&html, Some(&final_url));
page.title = extracted.title;
page.description = extracted.description.clone();
@@ -466,13 +467,13 @@ async fn fetch_page(url: reqwest::Url) -> Result<(Fetched, reqwest::StatusCode),
}
}
Kind::Json => {
- let text = decode(&bytes, &content_type);
+ let text = decode(&bytes, &content_type, false);
page.text = serde_json::from_str::(&text)
.ok()
.and_then(|value| serde_json::to_string_pretty(&value).ok())
.unwrap_or(text);
}
- Kind::Text => page.text = decode(&bytes, &content_type),
+ Kind::Text => page.text = decode(&bytes, &content_type, false),
Kind::Pdf => {
return Err(ToolError::ExecutionError(format!(
"{} is a PDF. web_fetch reads HTML, JSON and text; download it (curl -L -o file.pdf ) and extract its text with a PDF tool, or open it in the browser.",
@@ -551,12 +552,17 @@ fn classify(content_type: &str, bytes: &[u8]) -> Kind {
Kind::Binary
}
-/// Bytes to text in the page's own encoding: the header's charset, else a
-/// ` ` in the first bytes, else UTF-8 (a BOM wins over both).
-fn decode(bytes: &[u8], content_type: &str) -> String {
+/// Bytes to text in the page's own encoding: the header's charset, else (for
+/// HTML only) a ` ` declaration in the first bytes, else UTF-8 (a BOM
+/// wins over all). JSON and text never read their body as metadata: a
+/// literal `charset=` string in a JSON value is data.
+fn decode(bytes: &[u8], content_type: &str, html: bool) -> String {
let label = charset_in(content_type).or_else(|| {
+ if !html {
+ return None;
+ }
let head = String::from_utf8_lossy(&bytes[..bytes.len().min(4096)]).to_ascii_lowercase();
- charset_in(&head)
+ meta_charset(&head)
});
let encoding = label
.and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
@@ -565,6 +571,21 @@ fn decode(bytes: &[u8], content_type: &str) -> String {
text.into_owned()
}
+/// The charset a ` ` or ` ` tag declares; `charset=` in the page's prose is not one.
+fn meta_charset(head: &str) -> Option {
+ let mut rest = head;
+ while let Some(start) = rest.find(" ').unwrap_or(tag.len());
+ if let Some(label) = charset_in(&tag[..end]) {
+ return Some(label);
+ }
+ rest = &tag[end..];
+ }
+ None
+}
+
fn charset_in(text: &str) -> Option {
let lower = text.to_ascii_lowercase();
let start = lower.find("charset=")? + "charset=".len();
@@ -598,7 +619,15 @@ fn render_part(page: &Fetched, offset: usize, max_chars: Option) -> Strin
));
return out;
}
- let (part, end) = window(&page.text, offset, max_chars.unwrap_or(usize::MAX));
+ // The registry cuts any result past its byte and line caps, so the part
+ // must fit them with its framing: otherwise the advertised offset would
+ // point past text the model never received.
+ let budget = Budget {
+ chars: max_chars.unwrap_or(usize::MAX),
+ bytes: MAX_OUTPUT_BYTES.saturating_sub(out.len() + FRAMING_RESERVE),
+ lines: MAX_OUTPUT_LINES.saturating_sub(out.lines().count() + 6),
+ };
+ let (part, end) = window(&page.text, offset, budget);
if offset > 0 || end < total {
out.push_str(&format!("Part: characters {offset}–{end} of {total}."));
if end < total {
@@ -617,10 +646,33 @@ fn render_part(page: &Fetched, offset: usize, max_chars: Option) -> Strin
out
}
-/// Up to `max` characters from char `offset`, ending at a paragraph (else
-/// line, else word) boundary in the part's last 40% when the text goes on.
+/// Bytes kept free for the part line and the continuation footer.
+const FRAMING_RESERVE: usize = 256;
+
+/// How much one part may hold: the caller's characters and the registry's
+/// byte and line caps.
+#[derive(Clone, Copy)]
+struct Budget {
+ chars: usize,
+ bytes: usize,
+ lines: usize,
+}
+
+impl Budget {
+ #[cfg(test)]
+ fn chars(chars: usize) -> Self {
+ Self {
+ chars,
+ bytes: usize::MAX,
+ lines: usize::MAX,
+ }
+ }
+}
+
+/// Up to the budget from char `offset`, ending at a paragraph (else line,
+/// else word) boundary in the part's last 40% when the text goes on.
/// Returns the part and the char offset it ends at.
-fn window(text: &str, offset: usize, max: usize) -> (&str, usize) {
+fn window(text: &str, offset: usize, budget: Budget) -> (&str, usize) {
let byte_at = |chars: usize| {
text.char_indices()
.nth(chars)
@@ -629,11 +681,17 @@ fn window(text: &str, offset: usize, max: usize) -> (&str, usize) {
};
let start = byte_at(offset);
let rest = &text[start..];
- let limit = rest
- .char_indices()
- .nth(max)
- .map(|(i, _)| i)
- .unwrap_or(rest.len());
+ let mut limit = rest.len();
+ let mut newlines = 0;
+ for (chars, (i, ch)) in rest.char_indices().enumerate() {
+ if chars >= budget.chars || i + ch.len_utf8() > budget.bytes || newlines >= budget.lines {
+ limit = i;
+ break;
+ }
+ if ch == '\n' {
+ newlines += 1;
+ }
+ }
if limit == rest.len() {
return (rest, offset + rest.chars().count());
}
@@ -762,9 +820,49 @@ mod tests {
assert!(out.contains("URL: "));
}
+ #[test]
+ fn parts_fit_the_output_caps_and_continue_where_they_stopped() {
+ // 150k characters, multibyte and multiline, with a marker at 52k.
+ let mut text = String::new();
+ while text.chars().count() < 52_000 {
+ text.push_str("línea de texto número uno\n");
+ }
+ text.push_str("MARKER\n");
+ while text.chars().count() < 150_000 {
+ text.push_str("más texto después del marcador\n");
+ }
+ let page = Fetched {
+ url: "https://example.test/big".into(),
+ text: text.clone(),
+ ..Fetched::default()
+ };
+ let mut offset = 0;
+ let mut seen = String::new();
+ for limit in [Some(100_000), None, Some(100_000), None, None, None, None, None] {
+ let out = render_part(&page, offset, limit);
+ assert!(!crate::tools::truncate_output(&out).truncated, "part overflowed the caps");
+ let body = out.split_once("\n\n").map(|(_, b)| b).unwrap_or("");
+ let body = body.split("\n\n[").next().unwrap_or("");
+ seen.push_str(body);
+ let Some(next) = out
+ .split("Continue with offset=")
+ .nth(1)
+ .and_then(|r| r.split('.').next())
+ .and_then(|n| n.parse::().ok())
+ else {
+ break;
+ };
+ assert!(next > offset);
+ let delivered: String = text.chars().skip(offset).take(next - offset).collect();
+ assert!(body.starts_with(delivered.trim_end()), "offset skips text");
+ offset = next;
+ }
+ assert!(seen.contains("MARKER"));
+ }
+
#[test]
fn window_counts_characters_not_bytes() {
- let (part, end) = window("été été été", 4, 3);
+ let (part, end) = window("été été été", 4, Budget::chars(3));
assert_eq!(part, "été");
assert_eq!(end, 7);
}
@@ -788,10 +886,25 @@ mod tests {
fn decoding_follows_the_page_charset() {
// "café" in Windows-1252.
let bytes = b"caf\xe9";
- assert_eq!(decode(bytes, "text/plain; charset=windows-1252"), "café");
+ assert_eq!(
+ decode(bytes, "text/plain; charset=windows-1252", false),
+ "café"
+ );
let html = b" caf\xe9";
- assert!(decode(html, "text/html").contains("café"));
- assert_eq!(decode("naïve".as_bytes(), "text/plain"), "naïve");
+ assert!(decode(html, "text/html", true).contains("café"));
+ assert_eq!(decode("naïve".as_bytes(), "text/plain", false), "naïve");
+ }
+
+ #[test]
+ fn literal_charset_text_is_not_metadata() {
+ let json = r#"{"name":"café","note":"charset=windows-1252"}"#;
+ assert!(decode(json.as_bytes(), "application/json", false).contains("café"));
+ let text = "café — set charset=windows-1252 in the config";
+ assert_eq!(decode(text.as_bytes(), "text/plain", false), text);
+ let prose = "café: use charset=windows-1252
";
+ assert!(decode(prose.as_bytes(), "text/html", true).contains("café"));
+ let equiv = b" caf\xe9";
+ assert!(decode(equiv, "text/html", true).contains("café"));
}
#[test]
diff --git a/crates/agente-core/src/tools/web/search.rs b/crates/agente-core/src/tools/web/search.rs
index eae4a737..72878db5 100644
--- a/crates/agente-core/src/tools/web/search.rs
+++ b/crates/agente-core/src/tools/web/search.rs
@@ -352,23 +352,34 @@ fn parse_ddg_html(html: &str) -> Vec {
/// `lite.duckduckgo.com`: links and snippet cells in table rows, in order.
fn parse_ddg_lite(html: &str) -> Vec {
let document = Html::parse_document(html);
- let links: Vec<_> = document.select(&selector("a.result-link")).collect();
- let snippets: Vec = document
- .select(&selector("td.result-snippet"))
- .map(|cell| clip(&collapse_text(cell.text()), SNIPPET_CHARS))
- .collect();
- links
- .into_iter()
- .enumerate()
- .filter_map(|(i, anchor)| {
- let url = resolve_ddg_url(anchor.value().attr("href")?);
- (!url.is_empty()).then(|| Hit {
- title: collapse_text(anchor.text()),
- url,
- snippet: snippets.get(i).cloned().unwrap_or_default(),
- })
- })
- .collect()
+ // Walk links and snippets in document order: a snippet belongs to the
+ // result row above it, so one result without a snippet leaves only its
+ // own empty instead of shifting every later snippet up a result.
+ let mut hits: Vec = Vec::new();
+ let mut open = false;
+ for el in document.select(&selector("a.result-link, td.result-snippet")) {
+ if el.value().name() == "a" {
+ let url = el
+ .value()
+ .attr("href")
+ .map(resolve_ddg_url)
+ .unwrap_or_default();
+ open = !url.is_empty();
+ if open {
+ hits.push(Hit {
+ title: collapse_text(el.text()),
+ url,
+ snippet: String::new(),
+ });
+ }
+ } else if open {
+ if let Some(hit) = hits.last_mut() {
+ hit.snippet = clip(&collapse_text(el.text()), SNIPPET_CHARS);
+ }
+ open = false;
+ }
+ }
+ hits
}
/// DuckDuckGo links are redirect wrappers
@@ -460,6 +471,34 @@ mod tests {
assert!(hits[0].snippet.contains("reliable software"));
}
+ #[test]
+ fn lite_snippets_stay_with_their_own_result() {
+ let row = |n: u8| {
+ format!(r#"R{n} "#)
+ };
+ let snippet = |n: u8| format!(r#"About {n} "#);
+ let html = format!(
+ "{}{}{}sponsored spacer {}{}
",
+ row(1),
+ row(2),
+ snippet(2),
+ row(3),
+ snippet(3)
+ );
+ let hits = parse_ddg_lite(&html);
+ assert_eq!(hits.len(), 3);
+ assert_eq!(hits[0].snippet, "");
+ assert_eq!(hits[1].snippet, "About 2");
+ assert_eq!(hits[2].snippet, "About 3");
+
+ let middle = format!("", row(1), snippet(1), row(2), row(3), snippet(3));
+ let hits = parse_ddg_lite(&middle);
+ assert_eq!(
+ hits.iter().map(|h| h.snippet.as_str()).collect::>(),
+ ["About 1", "", "About 3"]
+ );
+ }
+
#[test]
fn resolve_ddg_url_extracts_uddg_and_prefixes_protocol() {
assert_eq!(
diff --git a/crates/agente-daemon/src/connection/handlers.rs b/crates/agente-daemon/src/connection/handlers.rs
index fef38bf5..635ccfa2 100644
--- a/crates/agente-daemon/src/connection/handlers.rs
+++ b/crates/agente-daemon/src/connection/handlers.rs
@@ -413,8 +413,13 @@ impl Connection {
// delivery and the response may race on separate connection tasks.
let summary = if smart && tokens_after < tokens_before {
snapshot.conversation.iter().find_map(|message| {
- (message.role == agente_protocol::Role::Assistant)
- .then(|| message.content.strip_prefix("[Conversation summary]\n"))
+ // User since the checkpoint became a user turn; Assistant in
+ // sessions compacted before that.
+ matches!(
+ message.role,
+ agente_protocol::Role::User | agente_protocol::Role::Assistant
+ )
+ .then(|| message.content.strip_prefix("[Conversation summary]\n"))
.flatten()
.map(str::to_owned)
})
diff --git a/crates/agente-runtime/src/bridge.rs b/crates/agente-runtime/src/bridge.rs
index fe88fd4d..5b13c0f5 100644
--- a/crates/agente-runtime/src/bridge.rs
+++ b/crates/agente-runtime/src/bridge.rs
@@ -168,7 +168,9 @@ pub(crate) fn forward_legacy_events(
tokens_after,
smart,
} => {
- inner.lock_edits().compacted(session_id);
+ inner
+ .lock_edits()
+ .compacted(session_id, &compacted_conversation);
inner.persist_edits(session_id);
let revision = replace_conversation(&inner, session_id, compacted_conversation);
forwarder.emit(RuntimeEvent::ContextCompacted {
diff --git a/crates/agente-runtime/src/edits.rs b/crates/agente-runtime/src/edits.rs
index a4b1cabe..2b8b2cc6 100644
--- a/crates/agente-runtime/src/edits.rs
+++ b/crates/agente-runtime/src/edits.rs
@@ -10,7 +10,7 @@
use std::collections::HashMap;
use std::path::Path;
-use agente_protocol::SessionId;
+use agente_protocol::{Message, Role, SessionId};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -28,6 +28,14 @@ struct Batch {
conversation_len: usize,
turn_index: usize,
created_at: i64,
+ /// Hash of the turn's user message, so a compaction can find where the
+ /// turn now sits in the shorter conversation.
+ #[serde(default)]
+ anchor: Option,
+ /// Compaction summarized the turn's user message away: the batch no
+ /// longer has a position, only its place in the history.
+ #[serde(default)]
+ unresolved: bool,
}
#[derive(Debug, Default, Serialize, Deserialize)]
@@ -37,7 +45,16 @@ struct History {
/// Set when a turn starts; the batch is recorded when it ends.
#[serde(skip)]
pending_start: Option,
+ #[serde(skip)]
+ pending_anchor: Option,
+ #[serde(skip)]
+ pending_unresolved: bool,
turn_index: usize,
+ /// After a compaction: the first message kept from before it (what the
+ /// summary, carried skills and notes precede). Batches without a
+ /// position are older than it.
+ #[serde(default)]
+ compacted_floor: Option,
}
#[derive(Debug, Default)]
@@ -46,9 +63,18 @@ pub(crate) struct EditLog {
}
impl EditLog {
- pub fn begin_turn(&mut self, session_id: SessionId, conversation_len: usize) {
+ /// `prompt` is the turn's user message, the anchor a later compaction
+ /// uses to find the turn again.
+ pub fn begin_turn(
+ &mut self,
+ session_id: SessionId,
+ conversation_len: usize,
+ prompt: Option<&str>,
+ ) {
let history = self.sessions.entry(session_id).or_default();
history.pending_start = Some(conversation_len);
+ history.pending_anchor = prompt.map(anchor_of);
+ history.pending_unresolved = false;
history.turn_index += 1;
}
@@ -57,6 +83,8 @@ impl EditLog {
pub fn end_turn(&mut self, session_id: SessionId, edits: Vec) {
let history = self.sessions.entry(session_id).or_default();
let start = history.pending_start.take().unwrap_or(0);
+ let anchor = history.pending_anchor.take();
+ let unresolved = std::mem::take(&mut history.pending_unresolved);
let edits = merge(edits);
if edits.is_empty() {
return;
@@ -67,6 +95,8 @@ impl EditLog {
conversation_len: start,
turn_index: history.turn_index,
created_at: chrono::Utc::now().timestamp_millis(),
+ anchor,
+ unresolved,
});
}
@@ -121,14 +151,20 @@ impl EditLog {
let first = history
.undo
.iter()
- .position(|batch| batch.conversation_len > conversation_index)
+ .position(|batch| !batch.unresolved && batch.conversation_len > conversation_index)
.unwrap_or(history.undo.len());
- let edits = merge(
- history.undo[first..]
- .iter()
- .flat_map(|batch| batch.edits.clone())
- .collect(),
- );
+ // Batches whose prompt a compaction summarized away are older than
+ // every message kept from before it. A point inside the compacted
+ // part cannot say which of them came after it: refuse rather than
+ // truncate the conversation and leave their edits on disk.
+ if history
+ .compacted_floor
+ .is_some_and(|floor| conversation_index < floor)
+ && history.undo[..first].iter().any(|batch| batch.unresolved)
+ {
+ return Err(COMPACTED_REWIND.into());
+ }
+ let edits = merge_chain(&history.undo[first..])?;
apply(&edits, project_dir, Side::Before)?;
let batches = history.undo.split_off(first);
let undone = batches.len();
@@ -154,12 +190,7 @@ impl EditLog {
if first == history.undo.len() {
return Ok(Vec::new());
}
- let edits = merge(
- history.undo[first..]
- .iter()
- .flat_map(|batch| batch.edits.clone())
- .collect(),
- );
+ let edits = merge_chain(&history.undo[first..])?;
let paths = apply(&edits, project_dir, Side::Before)?;
let batches = history.undo.split_off(first);
history.redo.extend(batches.into_iter().rev());
@@ -200,15 +231,132 @@ impl EditLog {
self.sessions.remove(&session_id);
}
- /// Keep undo/redo after compaction, without stale conversation positions.
- pub fn compacted(&mut self, session_id: SessionId) {
- if let Some(history) = self.sessions.get_mut(&session_id) {
- for batch in history.undo.iter_mut().chain(&mut history.redo) {
- batch.conversation_len = 0;
+ /// Keep undo/redo after compaction: each batch finds its turn's user
+ /// message in the compacted `conversation` (newest first, so a repeated
+ /// prompt goes to the newest turn); one whose prompt was summarized away
+ /// keeps only its place in the history.
+ pub fn compacted(&mut self, session_id: SessionId, conversation: &[Message]) {
+ let Some(history) = self.sessions.get_mut(&session_id) else {
+ return;
+ };
+ let mut cursor = conversation.len();
+ if history.pending_start.is_some() {
+ match locate(conversation, history.pending_anchor, cursor) {
+ Some(index) => {
+ history.pending_start = Some(index + 1);
+ cursor = index;
+ }
+ None => {
+ history.pending_start = Some(0);
+ history.pending_unresolved = true;
+ }
+ }
+ }
+ for batch in history.undo.iter_mut().rev() {
+ let found = if batch.unresolved {
+ None
+ } else {
+ locate(conversation, batch.anchor, cursor)
+ };
+ match found {
+ Some(index) => {
+ batch.conversation_len = index + 1;
+ cursor = index;
+ }
+ None => {
+ batch.conversation_len = 0;
+ batch.unresolved = true;
+ }
+ }
+ }
+ for batch in &mut history.redo {
+ match locate(conversation, batch.anchor, conversation.len()) {
+ Some(index) => batch.conversation_len = index + 1,
+ None => {
+ batch.conversation_len = 0;
+ batch.unresolved = true;
+ }
+ }
+ }
+ history.compacted_floor = Some(
+ conversation
+ .iter()
+ .position(|message| {
+ !matches!(message.role, Role::System) && !compaction_note(&message.content)
+ })
+ .unwrap_or(conversation.len()),
+ );
+ }
+}
+
+const COMPACTED_REWIND: &str = "This point is in the part of the conversation that was \
+compacted, so its file edits can no longer be matched to it. Use Undo to step back through \
+them instead.";
+
+/// A message compaction itself wrote: the summary, carried skills, a gap
+/// note or the project reminder.
+fn compaction_note(content: &str) -> bool {
+ use agente_core::context::compaction::{CARRIED_SKILLS_HEADING, COMPACTED_GAP_NOTE};
+ content.starts_with("[Conversation summary]")
+ || content.starts_with(CARRIED_SKILLS_HEADING)
+ || content.starts_with(COMPACTED_GAP_NOTE)
+ || content.starts_with(agente_core::context::PROJECT_REMINDER_MARKER)
+}
+
+/// Stable across runs (it is persisted): FNV-1a over the trimmed prompt.
+fn anchor_of(prompt: &str) -> u64 {
+ prompt
+ .trim()
+ .bytes()
+ .fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| {
+ (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
+ })
+}
+
+/// The last user message before `before` whose text hashes to `anchor`.
+fn locate(conversation: &[Message], anchor: Option, before: usize) -> Option {
+ let anchor = anchor?;
+ conversation[..before.min(conversation.len())]
+ .iter()
+ .rposition(|message| {
+ matches!(message.role, Role::User) && anchor_of(&message.content) == anchor
+ })
+}
+
+/// Several batches as one edit per file, refusing when a later batch did
+/// not start from what an earlier one left: the file was changed by hand
+/// between those turns, and restoring the first `before` would erase it.
+fn merge_chain(batches: &[Batch]) -> Result, String> {
+ let mut merged: Vec = Vec::new();
+ for edit in batches.iter().flat_map(|batch| batch.edits.iter()) {
+ match merged.iter_mut().find(|existing| existing.path == edit.path) {
+ Some(existing) => {
+ if existing.after != edit.before {
+ return Err(format!(
+ "{} was changed between the agent's turns; refusing to overwrite",
+ edit.path
+ ));
+ }
+ existing.after = edit.after.clone();
}
- history.pending_start = Some(0);
+ None => merged.push(edit.clone()),
}
}
+ merged.retain(|edit| edit.before != edit.after);
+ Ok(merged)
+}
+
+/// What a file holds now: `None` only when it does not exist. A file that
+/// is there but unreadable or not UTF-8 is not "missing": treating it so let
+/// redo overwrite a file someone recreated with other bytes.
+fn read_current(path: &Path, shown: &str) -> Result, String> {
+ match std::fs::read(path) {
+ Ok(bytes) => String::from_utf8(bytes).map(Some).map_err(|_| {
+ format!("{shown} changed since (it is not UTF-8 text); refusing to overwrite")
+ }),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(format!("{shown}: {error}")),
+ }
}
/// One entry per file: its first `before` and its last `after`.
@@ -254,7 +402,7 @@ enum Side {
/// nothing.
fn apply(edits: &[FileEdit], project_dir: &str, side: Side) -> Result, String> {
for edit in edits {
- let current = std::fs::read_to_string(Path::new(project_dir).join(&edit.path)).ok();
+ let current = read_current(&Path::new(project_dir).join(&edit.path), &edit.path)?;
let (expected, _) = pick(edit, side);
if ¤t != expected {
return Err(format!(
@@ -322,7 +470,7 @@ mod tests {
std::fs::write(dir.join("a.txt"), "v2").unwrap();
std::fs::write(dir.join("new.txt"), "fresh").unwrap();
let mut log = EditLog::default();
- log.begin_turn(session, 2);
+ log.begin_turn(session, 2, None);
log.end_turn(
session,
vec![
@@ -360,7 +508,7 @@ mod tests {
std::fs::write(dir.join("a.txt"), "agent").unwrap();
std::fs::write(dir.join("b.txt"), "mine now").unwrap();
let mut log = EditLog::default();
- log.begin_turn(session, 2);
+ log.begin_turn(session, 2, None);
log.end_turn(
session,
vec![
@@ -391,7 +539,7 @@ mod tests {
std::fs::write(dir.join("a.txt"), "t3").unwrap();
let mut log = EditLog::default();
for (start, before, after) in [(2, "t0", "t1"), (5, "t1", "t2"), (8, "t2", "t3")] {
- log.begin_turn(session, start);
+ log.begin_turn(session, start, None);
log.end_turn(session, vec![edit("a.txt", Some(before), Some(after))]);
}
@@ -410,12 +558,12 @@ mod tests {
let root = dir.to_str().unwrap();
let session = SessionId::new();
let mut log = EditLog::default();
- log.begin_turn(session, 2);
+ log.begin_turn(session, 2, None);
log.end_turn(
session,
vec![edit("a.txt", Some("original"), Some("agent"))],
);
- log.begin_turn(session, 5);
+ log.begin_turn(session, 5, None);
log.end_turn(session, vec![edit("b.txt", None, Some("new"))]);
std::fs::write(dir.join("a.txt"), "hand edited").unwrap();
std::fs::write(dir.join("b.txt"), "new").unwrap();
@@ -425,6 +573,86 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
+ fn message(role: Role, content: &str) -> Message {
+ serde_json::from_value(serde_json::json!({ "role": role, "content": content })).unwrap()
+ }
+
+ #[test]
+ fn redo_refuses_a_recreated_file_that_is_not_utf8() {
+ let dir = project("redo-binary");
+ let root = dir.to_str().unwrap();
+ let session = SessionId::new();
+ std::fs::write(dir.join("a.txt"), "agent text").unwrap();
+ let mut log = EditLog::default();
+ log.begin_turn(session, 2, None);
+ log.end_turn(session, vec![edit("a.txt", None, Some("agent text"))]);
+ log.undo(session, root).unwrap();
+ assert_eq!(read(&dir, "a.txt"), None);
+ std::fs::write(dir.join("a.txt"), [0xff, 0xfe, 0x00, 0x80]).unwrap();
+ assert!(log.redo(session, root).unwrap_err().contains("a.txt"));
+ assert_eq!(
+ std::fs::read(dir.join("a.txt")).unwrap(),
+ [0xff, 0xfe, 0x00, 0x80]
+ );
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn rewind_refuses_to_erase_a_hand_edit_made_between_turns() {
+ let dir = project("rewind-between");
+ let root = dir.to_str().unwrap();
+ let session = SessionId::new();
+ let mut log = EditLog::default();
+ log.begin_turn(session, 2, None);
+ log.end_turn(session, vec![edit("a.txt", Some("orig\n"), Some("agent1\n"))]);
+ // The user adds a line by hand; the next turn keeps it.
+ log.begin_turn(session, 5, None);
+ log.end_turn(
+ session,
+ vec![edit("a.txt", Some("agent1\nmine\n"), Some("agent2\nmine\n"))],
+ );
+ std::fs::write(dir.join("a.txt"), "agent2\nmine\n").unwrap();
+ let error = log.rewind(session, 1, root).unwrap_err();
+ assert!(error.contains("a.txt"), "{error}");
+ assert_eq!(read(&dir, "a.txt").as_deref(), Some("agent2\nmine\n"));
+ assert_eq!(log.checkpoints(session).as_array().unwrap().len(), 2);
+ // Undoing one turn at a time still works and keeps the hand edit.
+ log.undo(session, root).unwrap();
+ assert_eq!(read(&dir, "a.txt").as_deref(), Some("agent1\nmine\n"));
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn rewind_after_compaction_finds_a_retained_prompt() {
+ let dir = project("rewind-compacted");
+ let root = dir.to_str().unwrap();
+ let session = SessionId::new();
+ std::fs::write(dir.join("a.txt"), "t2").unwrap();
+ let mut log = EditLog::default();
+ // Turn 1 ("old task") at 2, turn 2 ("keep this") at 4.
+ log.begin_turn(session, 2, Some("old task"));
+ log.end_turn(session, vec![edit("a.txt", Some("t0"), Some("t1"))]);
+ log.begin_turn(session, 4, Some("keep this"));
+ log.end_turn(session, vec![edit("a.txt", Some("t1"), Some("t2"))]);
+
+ // Compaction summarized turn 1 away and kept turn 2's prompt.
+ let compacted = vec![
+ message(Role::System, "system"),
+ message(Role::User, "[Conversation summary]\nold task done"),
+ message(Role::User, "keep this"),
+ message(Role::Assistant, "done"),
+ ];
+ log.compacted(session, &compacted);
+
+ // A point inside the summary is refused before anything changes.
+ assert!(log.rewind(session, 1, root).is_err());
+ assert_eq!(read(&dir, "a.txt").as_deref(), Some("t2"));
+ // Back to before the retained prompt (now at index 2): turn 2 only.
+ assert_eq!(log.rewind(session, 2, root).unwrap(), 1);
+ assert_eq!(read(&dir, "a.txt").as_deref(), Some("t1"));
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[test]
fn rollback_to_turn_is_atomic_and_preserves_earlier_turns() {
let dir = project("rollback-turn");
@@ -433,11 +661,11 @@ mod tests {
std::fs::write(dir.join("a.txt"), "t3").unwrap();
std::fs::write(dir.join("b.txt"), "b2").unwrap();
let mut log = EditLog::default();
- log.begin_turn(session, 1);
+ log.begin_turn(session, 1, None);
log.end_turn(session, vec![edit("a.txt", Some("t0"), Some("t1"))]);
- log.begin_turn(session, 3);
+ log.begin_turn(session, 3, None);
log.end_turn(session, vec![edit("a.txt", Some("t1"), Some("t2"))]);
- log.begin_turn(session, 5);
+ log.begin_turn(session, 5, None);
log.end_turn(
session,
vec![
diff --git a/crates/agente-runtime/src/sessions.rs b/crates/agente-runtime/src/sessions.rs
index 479fe0ae..a473d1e3 100644
--- a/crates/agente-runtime/src/sessions.rs
+++ b/crates/agente-runtime/src/sessions.rs
@@ -439,7 +439,7 @@ impl RuntimeHandle {
smart: bool,
) -> SessionSnapshot {
self.inner.session_context(session_id, None);
- self.inner.lock_edits().compacted(session_id);
+ self.inner.lock_edits().compacted(session_id, &messages);
self.inner.persist_edits(session_id);
let revision = bridge::replace_conversation(&self.inner, session_id, messages);
self.inner.publish(&self.envelope(
diff --git a/crates/agente-runtime/src/tests.rs b/crates/agente-runtime/src/tests.rs
index 0e29c455..4a5f695e 100644
--- a/crates/agente-runtime/src/tests.rs
+++ b/crates/agente-runtime/src/tests.rs
@@ -8,7 +8,7 @@ fn saved_edits_recover_the_project_and_remain_undoable_after_restart() {
runtime
.open_session(session, project.to_str().unwrap())
.unwrap();
- runtime.inner.lock_edits().begin_turn(session, 3);
+ runtime.inner.lock_edits().begin_turn(session, 3, None);
std::fs::write(project.join("a.txt"), "keep\nnew\n").unwrap();
runtime.inner.lock_edits().end_turn(
session,
@@ -1003,7 +1003,7 @@ fn commit_compaction_after_restart_restores_and_preserves_edit_history() {
runtime
.open_session(session, project.to_str().unwrap())
.unwrap();
- runtime.inner.lock_edits().begin_turn(session, 1);
+ runtime.inner.lock_edits().begin_turn(session, 1, None);
runtime.inner.lock_edits().end_turn(
session,
vec![edits::FileEdit {
diff --git a/crates/agente-runtime/src/turns.rs b/crates/agente-runtime/src/turns.rs
index 34c35907..8ddd51ba 100644
--- a/crates/agente-runtime/src/turns.rs
+++ b/crates/agente-runtime/src/turns.rs
@@ -323,9 +323,10 @@ impl RuntimeHandle {
info.last_active = Utc::now();
});
}
+ let turn_prompt = conversation_index.map(|index| conversation[index].content.as_str());
self.inner
.lock_edits()
- .begin_turn(session_id, conversation.len());
+ .begin_turn(session_id, conversation.len(), turn_prompt);
let task_id = self
.inner
.task_sequence
diff --git a/crates/agente-tui/src/app/keys/session.rs b/crates/agente-tui/src/app/keys/session.rs
index 6a5f8410..266c89ff 100644
--- a/crates/agente-tui/src/app/keys/session.rs
+++ b/crates/agente-tui/src/app/keys/session.rs
@@ -48,7 +48,7 @@ impl App {
let total_items = 1 + filtered_count;
if matches!(key.code, KeyCode::Up | KeyCode::Down) {
- self.state.picker.session_picker_confirm_delete = false;
+ self.state.picker.session_picker_confirm_delete = None;
step_list_selection(
&mut self.state.picker.session_picker_selected,
total_items,
@@ -60,11 +60,24 @@ impl App {
match key.code {
KeyCode::Esc => {
self.state.picker.show_session_picker = false;
- self.state.picker.session_picker_confirm_delete = false;
+ self.state.picker.session_picker_confirm_delete = None;
}
KeyCode::Enter => {
let idx = self.state.picker.session_picker_selected;
- if !self.state.can_replace_session() {
+ let target = (idx > 0)
+ .then(|| {
+ self.state
+ .picker
+ .sessions
+ .iter()
+ .filter(|s| crate::session_picker::session_matches(s, &folder, &query))
+ .nth(idx - 1)
+ .map(|meta| meta.session_id)
+ })
+ .flatten();
+ if target.is_some_and(|id| self.focus_open_session(id)) {
+ self.state.picker.close();
+ } else if !self.state.can_replace_session() {
self.state.add_system_message(
"Stop the agent and running subagents before switching sessions"
.to_string(),
@@ -80,20 +93,24 @@ impl App {
KeyCode::Delete => {
let idx = self.state.picker.session_picker_selected;
if idx > 0 {
- if self.state.picker.session_picker_confirm_delete {
- let folder = self.state.picker.session_picker_folder_input.trim();
- let query = self.state.picker.session_picker_query.to_lowercase();
- let sid = self
- .state
- .picker
- .sessions
- .iter()
- .filter(|session| {
- crate::session_picker::session_matches(session, folder, &query)
- })
- .nth(idx - 1)
- .map(|meta| meta.session_id);
- if let Some(sid) = sid {
+ let folder = self.state.picker.session_picker_folder_input.trim();
+ let query = self.state.picker.session_picker_query.to_lowercase();
+ let selected_id = self
+ .state
+ .picker
+ .sessions
+ .iter()
+ .filter(|session| {
+ crate::session_picker::session_matches(session, folder, &query)
+ })
+ .nth(idx - 1)
+ .map(|meta| meta.session_id);
+ // Confirm only the session the first press armed; a
+ // selection moved since (hover, query) arms the new one.
+ if selected_id.is_some()
+ && self.state.picker.session_picker_confirm_delete == selected_id
+ {
+ if let Some(sid) = selected_id {
self.persistence.delete(sid);
self.state.picker.sessions.retain(|s| s.session_id != sid);
self.state
@@ -102,12 +119,12 @@ impl App {
.retain(|s| s.session_id != sid);
self.state.ui.needs_render = true;
}
- self.state.picker.session_picker_confirm_delete = false;
+ self.state.picker.session_picker_confirm_delete = None;
if self.state.picker.session_picker_selected > 0 {
self.state.picker.session_picker_selected -= 1;
}
} else {
- self.state.picker.session_picker_confirm_delete = true;
+ self.state.picker.session_picker_confirm_delete = selected_id;
}
}
}
diff --git a/crates/agente-tui/src/app/keys/tests.rs b/crates/agente-tui/src/app/keys/tests.rs
index f0c2ff69..b0148c1c 100644
--- a/crates/agente-tui/src/app/keys/tests.rs
+++ b/crates/agente-tui/src/app/keys/tests.rs
@@ -1075,9 +1075,38 @@ fn session_picker_matches_title_and_deletes_from_shared_snapshot() {
assert_eq!(app.state.picker.session_picker_selected, 1);
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
- assert!(app.state.picker.session_picker_confirm_delete);
+ assert_eq!(
+ app.state.picker.session_picker_confirm_delete,
+ Some(s2.session_id)
+ );
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.state.picker.sessions.len(), 1);
assert_eq!(app.state.picker.sessions[0].session_id, s1.session_id);
}
+
+#[test]
+fn a_moved_selection_rearms_delete_instead_of_deleting_another_session() {
+ let mut app = test_app();
+ let mut s1 = agente_core::session::create_session_meta("/tmp/proj-a");
+ s1.title = "First".into();
+ let mut s2 = agente_core::session::create_session_meta("/tmp/proj-a");
+ s2.title = "Second".into();
+ app.state.picker.show_session_picker = true;
+ app.state.picker.session_picker_folder_input = "/tmp/proj-a".into();
+ app.state.picker.sessions = vec![s1.clone(), s2.clone()];
+
+ app.state.picker.session_picker_selected = 1;
+ app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
+ .unwrap();
+ // The pointer moves to the other row (hover-to-select) before the
+ // second press.
+ app.state.picker.session_picker_selected = 2;
+ app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
+ .unwrap();
+ assert_eq!(app.state.picker.sessions.len(), 2, "nothing deleted");
+ assert_eq!(
+ app.state.picker.session_picker_confirm_delete,
+ Some(s2.session_id)
+ );
+}
diff --git a/crates/agente-tui/src/app/persistence.rs b/crates/agente-tui/src/app/persistence.rs
index 288198d7..698918c4 100644
--- a/crates/agente-tui/src/app/persistence.rs
+++ b/crates/agente-tui/src/app/persistence.rs
@@ -234,6 +234,9 @@ impl App {
return Ok(());
}
let id = resolve_session_id(&agente_core::session::list_sessions(), query)?;
+ if self.focus_open_session(id) {
+ return Ok(());
+ }
let data = agente_core::session::load_session(&id)?;
self.open_saved_session(&data);
Ok(())
diff --git a/crates/agente-tui/src/app/tabs.rs b/crates/agente-tui/src/app/tabs.rs
index 587c4e08..c82af654 100644
--- a/crates/agente-tui/src/app/tabs.rs
+++ b/crates/agente-tui/src/app/tabs.rs
@@ -219,6 +219,27 @@ impl App {
self.after_tab_change();
}
+ /// Bring the tab that already has session `id` open to the front.
+ /// Loading it again in another tab would give two tabs one session id
+ /// and one saved snapshot, so the last tab to save would erase the
+ /// other's continuation. Returns whether a tab had it.
+ pub(super) fn focus_open_session(&mut self, id: uuid::Uuid) -> bool {
+ if self.state.session.session_id == id {
+ return true;
+ }
+ let Some(index) = self.tabs.slots.iter().position(|slot| {
+ slot.as_ref()
+ .is_some_and(|tab| tab.state.session.session_id == id)
+ }) else {
+ return false;
+ };
+ self.switch_tab(index);
+ self.state
+ .ui
+ .show_toast("This session is already open in this tab".to_string());
+ true
+ }
+
/// Next (`+1`) or previous (`-1`) tab, wrapping.
pub(super) fn cycle_tab(&mut self, step: isize) {
let len = self.tabs.len() as isize;
@@ -448,6 +469,23 @@ mod tests {
assert_eq!(app.state.input.input_text, "draft two");
}
+ #[test]
+ fn resuming_a_session_open_in_another_tab_focuses_that_tab() {
+ let mut app = test_app();
+ let first = app.state.session.session_id;
+ app.state.input.input_text = "pending draft".into();
+ app.handle_key(KeyEvent::new(KeyCode::F(2), KeyModifiers::NONE))
+ .unwrap();
+ assert_eq!(app.tabs.active(), 1);
+
+ assert!(app.focus_open_session(first));
+ assert_eq!(app.tabs.len(), 2, "no second copy of the session");
+ assert_eq!(app.tabs.active(), 0);
+ assert_eq!(app.state.session.session_id, first);
+ assert_eq!(app.state.input.input_text, "pending draft");
+ assert!(!app.focus_open_session(uuid::Uuid::new_v4()));
+ }
+
#[test]
fn a_background_turn_keeps_running_and_lands_in_its_own_tab() {
let mut app = test_app();
diff --git a/crates/agente-tui/src/session_picker.rs b/crates/agente-tui/src/session_picker.rs
index a98e0666..9103ce95 100644
--- a/crates/agente-tui/src/session_picker.rs
+++ b/crates/agente-tui/src/session_picker.rs
@@ -171,7 +171,11 @@ fn render_session_list(frame: &mut Frame, folder_area: Rect, list_area: Rect, st
} else {
style::muted()
};
- let first = if picker.session_picker_confirm_delete && selected > 0 {
+ let armed = selected > 0
+ && picker.session_picker_confirm_delete.is_some()
+ && filtered.get(selected - 1).map(|meta| meta.session_id)
+ == picker.session_picker_confirm_delete;
+ let first = if armed {
PickItem::row_with_trail(
vec![Span::styled("Delete this session?", style::error())],
vec![Span::styled("Del confirm", style::dim())],
diff --git a/crates/agente-tui/src/state/picker.rs b/crates/agente-tui/src/state/picker.rs
index d2ecbcc3..27a0a089 100644
--- a/crates/agente-tui/src/state/picker.rs
+++ b/crates/agente-tui/src/state/picker.rs
@@ -25,8 +25,10 @@ pub struct SessionPickerState {
pub session_picker_browse_path: String,
/// Selected browse entry
pub session_picker_browse_selected: usize,
- /// Confirm delete session
- pub session_picker_confirm_delete: bool,
+ /// The session a first Delete armed for deletion. Bound to its id, not
+ /// the selected row: hover or a new query can move the selection, and the
+ /// second Delete must never remove a different session.
+ pub session_picker_confirm_delete: Option,
/// Use the picker as a project/folder selector instead of only a session picker.
pub session_picker_project_select: bool,
/// Snapshot of saved sessions loaded when the picker opens (and pruned on
@@ -40,7 +42,7 @@ impl SessionPickerState {
self.show_session_picker = true;
self.session_picker_query.clear();
self.session_picker_selected = 0;
- self.session_picker_confirm_delete = false;
+ self.session_picker_confirm_delete = None;
self.sessions = agente_core::session::list_sessions();
}
@@ -68,7 +70,7 @@ impl SessionPickerState {
self.show_session_picker = false;
self.session_picker_query.clear();
self.session_picker_selected = 0;
- self.session_picker_confirm_delete = false;
+ self.session_picker_confirm_delete = None;
self.session_picker_browsing = false;
self.session_picker_folder_input.clear();
self.session_picker_browse_path.clear();