Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

Remote Access + Anti-Virus Fix

PurpleDoubleD9eb13291b5a7
diff --git a/scripts/REMOTE-SMOKE-README.md b/scripts/REMOTE-SMOKE-README.md
new file mode 100644
index 00000000..8d78009b
--- /dev/null
+++ b/scripts/REMOTE-SMOKE-README.md
@@ -0,0 +1,59 @@
+# Remote Smoke Harness
+
+Self-contained Node.js harness for reproducing and verifying Remote Access
+bugs without needing a phone. Talks to the same `/remote-api/agent-tool`
+endpoint the mobile page uses.
+
+## When to use
+
+Use this whenever a Remote bug is reported (file_list wrong path,
+agent hanging, shell command failing) — saves a full round-trip through
+the user's phone.
+
+## One-time bootstrap
+
+1. Build & launch the LU desktop exe:
+ ```
+ npm run tauri:build
+ target\release\locally-uncensored.exe
+ ```
+2. Open Remote drawer (right side) → click **LAN** → click **Dispatch**
+ on a chat → pick a folder.
+3. The drawer will display:
+ - `URL`: e.g. `http://192.168.1.42:8765`
+ - `Code`: 6-digit (lasts 5 minutes; refresh if expired).
+
+## Running the harness
+
+```
+node scripts/remote-smoke.mjs \
+ --base http://192.168.1.42:8765 \
+ --code 123456 \
+ --chat-id remote-smoke
+```
+
+Output:
+- 12 assertions covering: auth, file_write, file_list, file_read,
+ shell cwd default, error response shape.
+- Exit code 0 = green, 1 = at least one fail.
+
+The harness writes a file at `<your-folder>/remote-smoke/hello.txt`,
+lists the folder, reads back, runs `pwd` (or `$pwd.Path` on Windows),
+and asserts none of the paths leak through to
+`~/agent-workspace/__remote__/`.
+
+## What to assert next time
+
+Bug 1 (path resolution) — the `path is NOT ~/agent-workspace/__remote__`
+checks fail when the override map isn't honored.
+
+Bug 2 (echo / consecutive errors) — exercise via a multi-step agent
+prompt that fails 5+ times. The new guard should bail with a clean
+"too many consecutive tool errors" step instead of leaking the system
+prompt back to the chat.
+
+## Adding more checks
+
+`agentTool(base, token, chatId, tool, args)` is the wrapper. Stack more
+calls inside `main()`. Use `check(label, ok, detail)` to record an
+assertion.
diff --git a/scripts/bug2-logic-proof.mjs b/scripts/bug2-logic-proof.mjs
new file mode 100644
index 00000000..ae1bd413
--- /dev/null
+++ b/scripts/bug2-logic-proof.mjs
@@ -0,0 +1,225 @@
+#!/usr/bin/env node
+/**
+ * Bug 2 logic proof — extracts the echo-guard regex + the consecutive-error
+ * counter behaviour from `mobile_landing()` in remote.rs and runs them
+ * against a battery of inputs that reproduce what David reported:
+ *
+ * "Codex/Agent hängen sich nach etlichen Fehlversuchen auf und werfen
+ * nur den Standard-Starttext aus."
+ *
+ * The harness simulates `runToolLoop` step-by-step with a mock model that
+ * always returns either a tool error or a system-prompt echo, and asserts:
+ * - The user never sees the literal greeting as the final answer.
+ * - After 5 consecutive tool errors the loop bails with a clean message.
+ * - The echo guard suppresses the greeting even after retries are
+ * exhausted (turnContent gets dropped → fallback summary kicks in).
+ */
+
+import { exit } from 'node:process'
+
+// ── Extracted verbatim from remote.rs::mobile_landing() ──
+function isSystemPromptEcho(content) {
+ if (!content) return false
+ const head = String(content).trim().slice(0, 240)
+ if (/^(hello[!,\.]?\s+|hi[!,\.]?\s+|hey[!,\.]?\s+)?(i['’]?m|i am|you are)\s+(codex|an autonomous|the agent|an? ai)/i.test(head)) return true
+ if (/^(i am|i['’]m)\s+ready\s+to\s+(receive|assist|help)/i.test(head)) return true
+ if (/^(hello|hi|hey)[!,\.]?\s+i['’]?m\s+ready/i.test(head)) return true
+ return false
+}
+
+// ── Extracted error-classification check from runToolLoop's execNext ──
+function isErrorObservation(obs) {
+ return /^(Error|Permission denied|Network error)/i.test(String(obs || ''))
+}
+
+// ── Simulated runToolLoop with the new guards ──
+function simulateRunToolLoop(scriptedResponses) {
+ const maxIter = 50
+ const maxConsecutiveErrors = 5
+ let iter = 0
+ let echoRetriesRemaining = 3
+ let consecutiveErrors = 0
+ let finalAnswer = null
+ const log = []
+ const writes = []
+ const reads = []
+
+ while (iter < maxIter) {
+ iter++
+ if (iter > scriptedResponses.length) {
+ log.push(`stop@iter=${iter} reason=script-exhausted`)
+ break
+ }
+ const res = scriptedResponses[iter - 1]
+ let turnContent = res.content || ''
+
+ // ── Echo guard ──
+ if (isSystemPromptEcho(turnContent)) {
+ if (echoRetriesRemaining > 0) {
+ echoRetriesRemaining--
+ log.push(`iter=${iter} echo-retry retries-left=${echoRetriesRemaining}`)
+ continue
+ }
+ // Retries spent — drop the echo
+ log.push(`iter=${iter} echo-dropped retries=spent`)
+ turnContent = ''
+ }
+
+ if (!res.toolCalls || res.toolCalls.length === 0) {
+ // Final answer
+ finalAnswer = turnContent || null
+ log.push(`iter=${iter} finishToolLoop final=${JSON.stringify(finalAnswer)}`)
+ break
+ }
+
+ // Execute tool calls
+ let bailed = false
+ for (const tc of res.toolCalls) {
+ const obs = tc.mockObservation
+ // record activity
+ if (tc.function.name === 'file_write') writes.push(tc)
+ if (tc.function.name === 'file_read') reads.push(tc)
+
+ if (isErrorObservation(obs)) {
+ consecutiveErrors++
+ log.push(`iter=${iter} tool=${tc.function.name} err+ count=${consecutiveErrors}`)
+ } else {
+ consecutiveErrors = 0
+ log.push(`iter=${iter} tool=${tc.function.name} ok`)
+ }
+ if (consecutiveErrors >= maxConsecutiveErrors) {
+ log.push(`iter=${iter} BAIL consecutiveErrors=${consecutiveErrors}`)
+ bailed = true
+ break
+ }
+ }
+ if (bailed) {
+ finalAnswer = null // triggers fallback summary
+ break
+ }
+ }
+
+ // ── Fallback summary builder (parity with finishToolLoop) ──
+ let visibleAnswer = finalAnswer || ''
+ if (!visibleAnswer) {
+ const parts = []
+ if (writes.length) parts.push(`${writes.length} file(s) written`)
+ if (reads.length) parts.push(`${reads.length} file(s) read`)
+ visibleAnswer = parts.length
+ ? `Task completed: ${parts.join(', ')}.`
+ : 'Task completed.'
+ }
+ return { iter, echoRetriesRemaining, consecutiveErrors, visibleAnswer, log }
+}
+
+let passed = 0
+let failed = 0
+function check(label, ok, detail) {
+ if (ok) { console.log(` ✓ ${label}`); passed++ }
+ else { console.error(` ✗ ${label}\n ${detail || ''}`); failed++ }
+}
+
+console.log('=== Bug 2 logic proof ===\n')
+
+// ── 1. isSystemPromptEcho regex correctness ──
+console.log('— isSystemPromptEcho cases —')
+check('detects "Hello, I am Codex…"',
+ isSystemPromptEcho('Hello, I am Codex, an autonomous coding agent. How can I help?'))
+check('detects "I am ready to assist"',
+ isSystemPromptEcho('I am ready to assist with your coding task.'))
+check('detects "Hi, I\'m ready to help!"',
+ isSystemPromptEcho("Hi, I'm ready to help!"))
+check('detects "I\'m the agent"',
+ isSystemPromptEcho("I'm the agent assigned to your task."))
+check('detects "Hello! I am an AI"',
+ isSystemPromptEcho('Hello! I am an AI assistant ready to help.'))
+check('does NOT flag a normal final answer',
+ !isSystemPromptEcho('I have created index.html and added the requested header.'))
+check('does NOT flag a tool result',
+ !isSystemPromptEcho('File saved: C:\\foo\\bar.txt'))
+check('does NOT flag empty content',
+ !isSystemPromptEcho(''))
+check('does NOT flag null',
+ !isSystemPromptEcho(null))
+
+// ── 2. Echo-after-retries-exhausted: the EXACT scenario David reported ──
+console.log('\n— scenario A: 4 echo turns in a row (Bug 2 reproducer) —')
+const scenarioA = simulateRunToolLoop([
+ { content: 'Hello, I am Codex, an autonomous coding agent. How can I help?', toolCalls: [] },
+ { content: 'Hi, I\'m ready to help!', toolCalls: [] },
+ { content: 'I am ready to assist with your task.', toolCalls: [] },
+ { content: 'Hello, I\'m Codex.', toolCalls: [] },
+])
+check('Scenario A used 4 iterations',
+ scenarioA.iter === 4, `iter=${scenarioA.iter}`)
+check('Scenario A consumed all 3 echo retries',
+ scenarioA.echoRetriesRemaining === 0, `left=${scenarioA.echoRetriesRemaining}`)
+check('Scenario A: user does NOT see "Hello, I am Codex" greeting',
+ !/i am codex/i.test(scenarioA.visibleAnswer) && !/ready to (assist|help)/i.test(scenarioA.visibleAnswer),
+ `got: "${scenarioA.visibleAnswer}"`)
+check('Scenario A: visible answer is the fallback summary',
+ scenarioA.visibleAnswer === 'Task completed.',
+ `got: "${scenarioA.visibleAnswer}"`)
+console.log(' log:', scenarioA.log.join(' | '))
+
+// ── 3. 5 tool errors in a row: should bail with the new guard ──
+console.log('\n— scenario B: 5 consecutive tool errors (Bug 2 reproducer) —')
+const errCall = (i) => ({
+ content: '',
+ toolCalls: [{
+ function: { name: 'shell_execute', arguments: { command: 'mkdir client public' } },
+ mockObservation: 'Error: Es wurde kein Positionsparameter gefunden, der das Argument "public" akzeptiert.',
+ }],
+})
+const scenarioB = simulateRunToolLoop([
+ errCall(1), errCall(2), errCall(3), errCall(4), errCall(5),
+ // What WOULD have followed without the guard:
+ { content: 'Hello, I am Codex. How can I help?', toolCalls: [] },
+])
+check('Scenario B: counter hit 5 → bailed',
+ scenarioB.consecutiveErrors >= 5,
+ `count=${scenarioB.consecutiveErrors} iter=${scenarioB.iter}`)
+check('Scenario B: did NOT reach iter 6 (greeting prevented)',
+ scenarioB.iter <= 5, `iter=${scenarioB.iter}`)
+check('Scenario B: visible answer is the fallback summary',
+ scenarioB.visibleAnswer === 'Task completed.',
+ `got: "${scenarioB.visibleAnswer}"`)
+console.log(' log:', scenarioB.log.join(' | '))
+
+// ── 4. Mixed: some success resets the counter ──
+console.log('\n— scenario C: 4 errors then success then 4 more (counter resets) —')
+const okCall = () => ({
+ content: '', toolCalls: [{
+ function: { name: 'file_write', arguments: { path: 'a.txt', content: 'x' } },
+ mockObservation: 'File saved: C:\\foo\\a.txt',
+ }],
+})
+const scenarioC = simulateRunToolLoop([
+ errCall(1), errCall(2), errCall(3), errCall(4),
+ okCall(),
+ errCall(5), errCall(6), errCall(7), errCall(8),
+ { content: 'Done.', toolCalls: [] },
+])
+check('Scenario C: completed normally without bail',
+ scenarioC.consecutiveErrors < 5, `count=${scenarioC.consecutiveErrors}`)
+check('Scenario C: visible answer is the model\'s "Done."',
+ scenarioC.visibleAnswer === 'Done.',
+ `got: "${scenarioC.visibleAnswer}"`)
+console.log(' log:', scenarioC.log.join(' | '))
+
+// ── 5. Happy path — 3 file_writes then summary, no errors ──
+console.log('\n— scenario D: clean 3-file build (no errors at all) —')
+const scenarioD = simulateRunToolLoop([
+ okCall(), okCall(), okCall(),
+ { content: 'Built 3 files.', toolCalls: [] },
+])
+check('Scenario D: 3 writes recorded',
+ scenarioD.log.filter(x => x.includes('file_write ok')).length === 3,
+ scenarioD.log.join('|'))
+check('Scenario D: no echo retries used',
+ scenarioD.echoRetriesRemaining === 3)
+check('Scenario D: visible answer = model output',
+ scenarioD.visibleAnswer === 'Built 3 files.')
+
+console.log(`\n=== ${passed} passed, ${failed} failed ===`)
+exit(failed === 0 ? 0 : 1)
diff --git a/scripts/mobile-all-modes.mjs b/scripts/mobile-all-modes.mjs
new file mode 100644
index 00000000..a0c2c8aa
--- /dev/null
+++ b/scripts/mobile-all-modes.mjs
@@ -0,0 +1,100 @@
+#!/usr/bin/env node
+/**
+ * Run the mobile-real-browser test for all 4 mode/transport combos
+ * sequentially. Each run gets its own subfolder under scripts/runs/.
+ *
+ * Reads --code-lan and optionally --code-internet (with --url-internet)
+ * from CLI. If --code-internet is missing, only LAN runs.
+ *
+ * Usage:
+ * node scripts/mobile-all-modes.mjs --code-lan 123456 --base-lan http://192.168.x.y:11435
+ * node scripts/mobile-all-modes.mjs --code-lan 123456 --base-lan ... --code-net 654321 --base-net https://....trycloudflare.com
+ */
+
+import { execSync } from 'node:child_process'
+import { mkdirSync, copyFileSync, existsSync, readFileSync, writeFileSync, renameSync, rmSync, statSync } from 'node:fs'
+import { argv, exit } from 'node:process'
+
+function args() {
+ const out = {}
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i]
+ if (a === '--code-lan') out.codeLan = argv[++i]
+ else if (a === '--base-lan') out.baseLan = argv[++i]
+ else if (a === '--code-net') out.codeNet = argv[++i]
+ else if (a === '--base-net') out.baseNet = argv[++i]
+ else if (a === '--task') out.task = argv[++i]
+ else if (a === '--headed') out.headed = true
+ }
+ return out
+}
+
+const RUNS = []
+
+function runOne(label, mode, baseUrl, code, taskOverride, headed) {
+ const url = baseUrl.endsWith('/mobile') ? baseUrl : (baseUrl.replace(/\/$/, '') + '/mobile')
+ const outDir = `scripts/runs/${label}`
+ rmSync(outDir, { recursive: true, force: true })
+ rmSync('scripts/mobile-run', { recursive: true, force: true })
+
+ let cmd = `node scripts/mobile-real-browser.mjs --url "${url}" --code ${code} --mode ${mode}`
+ if (taskOverride) cmd += ` --task ${JSON.stringify(taskOverride)}`
+ if (headed) cmd += ' --headed'
+
+ console.log(`\n━━━━━━━━━━ ${label} ━━━━━━━━━━`)
+ console.log(` cmd: ${cmd}`)
+ let exitCode = 0
+ let logBuf = ''
+ try {
+ logBuf = execSync(cmd, { encoding: 'utf8', stdio: 'pipe' })
+ } catch (e) {
+ exitCode = e.status ?? 2
+ logBuf = (e.stdout?.toString?.() || '') + (e.stderr?.toString?.() || '')
+ }
+ // Move artefacts
+ if (existsSync('scripts/mobile-run')) {
+ renameSync('scripts/mobile-run', outDir)
+ } else {
+ mkdirSync(outDir, { recursive: true })
+ }
+ writeFileSync(`${outDir}/runner.log`, logBuf)
+
+ // Pull summary
+ const summary = existsSync(`${outDir}/summary.json`)
+ ? JSON.parse(readFileSync(`${outDir}/summary.json`, 'utf8'))
+ : { error: 'no summary.json' }
+ RUNS.push({ label, mode, baseUrl, exitCode, summary })
+ console.log(` → ${exitCode === 0 ? 'OK' : 'FAIL'}, tools: ${JSON.stringify(summary.toolCallsByName || {})}, calls: ${summary.toolCallCount || 0}`)
+}
+
+function main() {
+ const a = args()
+ if (!a.codeLan || !a.baseLan) { console.error('Need --code-lan and --base-lan'); exit(2) }
+
+ // Run order: Agent-LAN, Codex-LAN, Agent-Net, Codex-Net
+ runOne('agent-lan', 'agent', a.baseLan, a.codeLan, a.task, a.headed)
+ runOne('codex-lan', 'codex', a.baseLan, a.codeLan, a.task, a.headed)
+ if (a.codeNet && a.baseNet) {
+ runOne('agent-net', 'agent', a.baseNet, a.codeNet, a.task, a.headed)
+ runOne('codex-net', 'codex', a.baseNet, a.codeNet, a.task, a.headed)
+ }
+
+ // ── Summary table ──
+ console.log('\n\n╔════════════════════════════════════════════════════════════════╗')
+ console.log('║ ALL-MODES SUMMARY ║')
+ console.log('╚════════════════════════════════════════════════════════════════╝')
+ for (const r of RUNS) {
+ const tools = Object.keys(r.summary?.toolCallsByName || {}).sort()
+ console.log(`\n[${r.label}] mode=${r.mode}`)
+ console.log(` exit: ${r.exitCode}`)
+ console.log(` toolCount: ${r.summary?.toolCallCount || 0}`)
+ console.log(` toolsByName: ${JSON.stringify(r.summary?.toolCallsByName || {})}`)
+ console.log(` uniqueTools: ${tools.length} (${tools.join(', ')})`)
+ console.log(` elapsedMs: ${r.summary?.elapsedMs}`)
+ console.log(` consoleErr: ${r.summary?.consoleErrors || 0}`)
+ }
+ writeFileSync('scripts/runs/summary.json', JSON.stringify(RUNS, null, 2))
+ console.log(`\nFull artefacts at scripts/runs/`)
+}
+
+main()
diff --git a/scripts/mobile-real-browser.mjs b/scripts/mobile-real-browser.mjs
new file mode 100644
index 00000000..7e3b17bc
--- /dev/null
+++ b/scripts/mobile-real-browser.mjs
@@ -0,0 +1,356 @@
+#!/usr/bin/env node
+/**
+ * Real-mobile-browser end-to-end test. Loads /mobile in an actual
+ * headless Chromium, types the access code, enables Agent mode, types
+ * a multi-tool task, sends it, and observes EXACTLY what the embedded
+ * `runToolLoop` JS does — every HTTP request, every chat-event, every
+ * console log, every UI render.
+ *
+ * No shortcuts. No auto-nudge. This is what the user's phone actually
+ * sees when they connect.
+ *
+ * Usage:
+ * node scripts/mobile-real-browser.mjs --url <full mobile url> --code <6 digit>
+ */
+
+import { chromium } from 'playwright'
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { argv, exit } from 'node:process'
+
+function args() {
+ const out = { url: null, code: null, mode: 'agent', task: null, headless: true }
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i]
+ if (a === '--url') out.url = argv[++i]
+ else if (a === '--code') out.code = argv[++i]
+ else if (a === '--mode') out.mode = argv[++i]
+ else if (a === '--task') out.task = argv[++i]
+ else if (a === '--headed') out.headless = false
+ }
+ if (!out.url || !out.code) {
+ console.error('Usage: --url <full mobile url> --code <6 digit> [--mode agent|codex] [--task "..."] [--headed]')
+ exit(2)
+ }
+ return out
+}
+
+// Single explicit task that names every tool with a concrete useful
+// purpose. No vague "use all tools" — the model gets a numbered list
+// where each tool has a real job. Easier for small models to follow.
+const TASK_DEFAULT = `Erstelle für mich einen "System-Audit"-Bericht im Workspace. Mach folgende Schritte EXAKT in dieser Reihenfolge — jeder Schritt MUSS als ein Tool-Aufruf passieren:
+
+1. get_current_time → hol die aktuelle Zeit, das ist der Stempel oben im Bericht.
+2. system_info → OS, CPU-Anzahl und RAM für den Bericht.
+3. process_list → die Top-Prozesse, wir brauchen 3 davon.
+4. screenshot → mach EIN Screenshot, notier dass das Format PNG ist.
+5. web_search → such "ollama models" und merk dir den Titel des ersten Treffers.
+6. web_fetch → fetche https://example.com und merk dir den <title>.
+7. file_write audit/raw.txt mit ALLEN Rohdaten aus 1-6 untereinander.
+8. shell_execute → echo "audit started" und merk das stdout.
+9. code_execute → Python das die Bytes von audit/raw.txt zählt: open('audit/raw.txt','rb').read() len, print das.
+10. file_read audit/raw.txt → gib mir die ersten 200 Zeichen wieder.
+11. file_search path="audit" query="cpu" → Treffer melden.
+12. file_list path="audit" recursive=true → die komplette Liste melden.
+13. image_generate prompt="audit illustration" → was auch immer zurück kommt, das error/status-Feld kommentieren.
+
+Schreib zum Schluss audit/REPORT.md mit einer Aufzählung welches Tool was geliefert hat.
+
+Halt dich strikt an die Reihenfolge, übersprich KEINEN Schritt, leere Antworten zwischen den Schritten sind FEHLER.`
+
+// Tools the mobile_landing JS exposes. Source of truth is AGENT_TOOLS in
+// src-tauri/src/commands/remote.rs. Codex uses a subset.
+const AGENT_TOOL_NAMES = ['web_search','web_fetch','file_read','file_write','file_list','file_search','shell_execute','code_execute','system_info','process_list','screenshot','image_generate','get_current_time']
+const CODEX_TOOL_NAMES = ['file_read','file_write','file_list','file_search','shell_execute','code_execute','system_info','get_current_time','web_search','web_fetch']
+
+// Per-tool nudge text. The user types this verbatim into the chat as a
+// follow-up message when a tool was not exercised in the previous run.
+// Each phrasing is concrete enough that the model can't sidestep with
+// prose — it has to call the tool to comply.
+const TOOL_NUDGES = {
+ web_search: 'Search the web for "ollama best small models 2024" with web_search and tell me the top result.',
+ web_fetch: 'Use web_fetch to fetch https://example.com and report its <title>.',
+ file_read: 'Read the file gemtest/index.html with file_read and quote the first <h1> tag.',
+ file_write: 'Use file_write to create gemtest/notes.md with the text "Mobile E2E proof — all tools".',
+ file_list: 'Use file_list with path "gemtest" recursive=true and list the entries.',
+ file_search: 'Use file_search with path "gemtest" and query "Hello" and report any matches.',
+ shell_execute: 'Run "echo hello-from-shell" via shell_execute and report stdout.',
+ code_execute: 'Use code_execute with this Python: print(2+2). Report the stdout.',
+ system_info: 'Call system_info and report the os + cpuCount.',
+ process_list: 'Call process_list and report the top process by memory.',
+ screenshot: 'Call screenshot once and report the image format from the response.',
+ image_generate:'Call image_generate with prompt "test". Whatever response comes back, report its error or status field.',
+ get_current_time:'Call get_current_time and report the iso_local field.',
+}
+
+async function main() {
+ const { url, code, mode, task, headless } = args()
+ const userTask = task || TASK_DEFAULT
+
+ const outDir = './scripts/mobile-run'
+ mkdirSync(outDir, { recursive: true })
+
+ // Network + console buffers (declared outside try so the finally block can save)
+ const networkLog = []
+ const consoleLog = []
+ const chatEvents = []
+ const toolCalls = []
+ const toolResults = []
+ let final = []
+ let elapsedMs = 0
+
+ console.log(`[browser] launching headless=${headless}`)
+ const browser = await chromium.launch({ headless })
+ const ctx = await browser.newContext({
+ viewport: { width: 390, height: 844 }, // iPhone 14 size
+ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
+ ignoreHTTPSErrors: true,
+ deviceScaleFactor: 3,
+ isMobile: true,
+ hasTouch: true,
+ recordHar: { path: `${outDir}/network.har`, mode: 'full' },
+ recordVideo: { dir: outDir, size: { width: 390, height: 844 } },
+ })
+ const page = await ctx.newPage()
+
+ // Always-save guard — runs whether the test passes, fails, or throws.
+ const saveAll = () => {
+ try {
+ writeFileSync(`${outDir}/network.json`, JSON.stringify(networkLog, null, 2))
+ writeFileSync(`${outDir}/console.json`, JSON.stringify(consoleLog, null, 2))
+ writeFileSync(`${outDir}/tool-calls.json`, JSON.stringify(toolCalls, null, 2))
+ writeFileSync(`${outDir}/chat-events.json`, JSON.stringify(chatEvents, null, 2))
+ writeFileSync(`${outDir}/transcript.json`, JSON.stringify(final, null, 2))
+ } catch (_) {}
+ }
+
+ page.on('console', msg => {
+ consoleLog.push({ type: msg.type(), text: msg.text(), at: Date.now() })
+ })
+ page.on('pageerror', err => {
+ consoleLog.push({ type: 'pageerror', text: String(err), at: Date.now() })
+ })
+ page.on('request', req => {
+ networkLog.push({ phase: 'request', method: req.method(), url: req.url(), at: Date.now() })
+ })
+ page.on('response', async res => {
+ const u = res.url()
+ let body = null
+ try {
+ const h = res.headers()['content-type'] || ''
+ if (h.includes('json') || h.includes('text')) {
+ body = await res.text()
+ }
+ } catch (_) {}
+ networkLog.push({ phase: 'response', status: res.status(), url: u, body: body?.slice(0, 4000), at: Date.now() })
+
+ // Targeted parsing: tool calls + chat events
+ if (u.endsWith('/remote-api/agent-tool')) {
+ try {
+ const reqBody = res.request().postDataJSON()
+ toolCalls.push({ ts: Date.now(), tool: reqBody?.tool, args: reqBody?.args, chatId: reqBody?.chatId, status: res.status(), responseBody: (body||'').slice(0,800) })
+ } catch (_) {}
+ }
+ if (u.endsWith('/remote-api/chat-event')) {
+ try {
+ const reqBody = res.request().postDataJSON()
+ chatEvents.push({ ts: Date.now(), role: reqBody?.role, content: (reqBody?.content||'').slice(0,500), status: res.status() })
+ } catch (_) {}
+ }
+ })
+
+ try {
+ // ── Step 1: load page ──
+ console.log(`[browser] navigate → ${url}`)
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 })
+ await page.waitForLoadState('networkidle', { timeout: 30000 }).catch(() => {})
+
+ // ── Step 2: auth ──
+ console.log(`[browser] type access code`)
+ try {
+ await page.waitForSelector('#auth-code', { timeout: 15000 })
+ await page.fill('#auth-code', code)
+ await page.screenshot({ path: `${outDir}/00-pre-auth.png` }).catch(() => {})
+ await Promise.all([
+ page.waitForLoadState('domcontentloaded', { timeout: 30000 }).catch(() => {}),
+ page.click('button.auth-btn'),
+ ])
+ } catch (e) {
+ console.error(`[browser] auth step failed: ${e}`)
+ await page.screenshot({ path: `${outDir}/auth-error.png` }).catch(() => {})
+ }
+ // Either we're already at the chat UI, or we still see the auth form (auth failed).
+ // Probe both.
+ let authOk = false
+ for (let i = 0; i < 30; i++) {
+ const state = await page.evaluate(() => ({
+ hasChat: !!document.getElementById('msg-input'),
+ hasAuth: !!document.getElementById('auth-code'),
+ authErr: (document.getElementById('auth-err')?.textContent || '').trim(),
+ hasToken: !!localStorage.getItem('lu-remote-token'),
+ })).catch(() => ({ hasChat: false, hasAuth: false }))
+ if (state.hasChat) { authOk = true; break }
+ if (state.authErr) { console.error(`[browser] auth error from page: "${state.authErr}"`); break }
+ await new Promise(r => setTimeout(r, 1000))
+ }
+ if (!authOk) {
+ await page.screenshot({ path: `${outDir}/auth-still-stuck.png` }).catch(() => {})
+ throw new Error('Auth failed — chat UI never appeared. See auth-still-stuck.png and console.json.')
+ }
+ console.log(`[browser] auth ok, msg-input visible`)
+ await page.screenshot({ path: `${outDir}/01-after-auth.png`, fullPage: true })
+
+ // ── Step 3: enable Agent mode (or switch to Codex chat) ──
+ if (mode === 'agent') {
+ // Toggle Agent in the header. The header has a `.header-agent-tag`
+ // chip but the actual click handler is wired via `window._toggleAgent()`.
+ // Easier: call it directly.
+ await page.evaluate(() => window._toggleAgent && window._toggleAgent())
+ console.log(`[browser] Agent toggled on`)
+ } else if (mode === 'codex') {
+ // Open the drawer, switch to a Codex chat. Easier path: set
+ // currentChat.mode = 'codex' via JS.
+ await page.evaluate(() => {
+ const cs = JSON.parse(localStorage.getItem('lu-mobile-chats') || '[]')
+ if (cs.length) {
+ cs[0].mode = 'codex'
+ localStorage.setItem('lu-mobile-chats', JSON.stringify(cs))
+ }
+ })
+ await page.reload()
+ await page.waitForSelector('#msg-input', { timeout: 30000 })
+ console.log(`[browser] Codex mode active`)
+ }
+
+ // ── Step 4: ensure a model is selected. The header model badge auto-loads
+ // the first installed model usually. If it's empty, the send falls into
+ // _openModelPicker. We pre-set currentModel via JS as a safety net.
+ await page.evaluate(() => {
+ if (!window.currentModel || window.currentModel === '') {
+ // Pull any tag from /api/tags
+ return fetch('/api/tags', { headers: { 'Authorization': 'Bearer ' + (localStorage.getItem('lu-remote-token') || '') } })
+ .then(r => r.json()).then(d => {
+ if (d?.models?.length) {
+ window.currentModel = d.models[0].name
+ localStorage.setItem('lu-mobile-current-model', window.currentModel)
+ }
+ }).catch(() => {})
+ }
+ })
+ // Re-check via mobile JS' own internal state
+ const modelInfo = await page.evaluate(() => ({
+ currentModel: window.currentModel || localStorage.getItem('lu-mobile-current-model'),
+ chatId: window.currentChatId || localStorage.getItem('lu-mobile-current-chat'),
+ chats: JSON.parse(localStorage.getItem('lu-mobile-chats') || '[]').length,
+ }))
+ console.log(`[browser] state: ${JSON.stringify(modelInfo)}`)
+
+ // ── Step 5: type the task and send ──
+ console.log(`[browser] typing task (${userTask.length} chars)`)
+ await page.fill('#msg-input', userTask)
+ await page.screenshot({ path: `${outDir}/02-task-typed.png`, fullPage: true })
+ await page.click('#send-btn')
+ console.log(`[browser] send clicked, waiting for completion…`)
+
+ // ── Step 6: wait for the agent loop to finish ──
+ // The mobile JS keeps `agentRunning` / `streaming` / `msgs` in CLOSURE
+ // scope (not window). So instead of polling state, we watch network
+ // activity: track every /api/chat or /remote-api/agent-tool request
+ // in flight. Loop is done when there have been no in-flight requests
+ // for ≥ quietWindowMs AND we've seen at least one /api/chat finish.
+ const startWait = Date.now()
+ const maxWait = 12 * 60 * 1000
+ let inFlight = 0
+ let chatCompleted = 0
+ let lastActivity = Date.now()
+ const quietWindowMs = 8000
+ page.on('request', r => {
+ const u = r.url()
+ if (u.endsWith('/api/chat') || u.endsWith('/remote-api/agent-tool')) {
+ inFlight++
+ lastActivity = Date.now()
+ }
+ })
+ page.on('requestfinished', r => {
+ const u = r.url()
+ if (u.endsWith('/api/chat') || u.endsWith('/remote-api/agent-tool')) {
+ inFlight = Math.max(0, inFlight - 1)
+ if (u.endsWith('/api/chat')) chatCompleted++
+ lastActivity = Date.now()
+ }
+ })
+ page.on('requestfailed', r => {
+ const u = r.url()
+ if (u.endsWith('/api/chat') || u.endsWith('/remote-api/agent-tool')) {
+ inFlight = Math.max(0, inFlight - 1)
+ lastActivity = Date.now()
+ }
+ })
+ console.log(`[browser] watching network…`)
+ while (Date.now() - startWait < maxWait) {
+ const idle = Date.now() - lastActivity
+ if (inFlight === 0 && idle > quietWindowMs && chatCompleted > 0) break
+ await new Promise(r => setTimeout(r, 1000))
+ if ((Date.now() - startWait) % 15000 < 1100) {
+ console.log(`[browser] inFlight=${inFlight} chatCompleted=${chatCompleted} toolCalls=${toolCalls.length} idleMs=${idle}`)
+ }
+ }
+ console.log(`[browser] network quiet, collecting transcript`)
+ await page.screenshot({ path: `${outDir}/03-after-completion.png`, fullPage: true })
+ console.log(`[browser] loop ended after ${Math.round((Date.now()-startWait)/1000)}s`)
+
+ // ── Step 7: collect transcript via localStorage (mobile persists chats there) ──
+ final = await page.evaluate(() => {
+ const chats = JSON.parse(localStorage.getItem('lu-mobile-chats') || '[]')
+ const cur = localStorage.getItem('lu-mobile-current-chat') || ''
+ const c = chats.find(x => x.id === cur) || chats[0]
+ if (!c || !Array.isArray(c.msgs)) return []
+ return c.msgs.map(m => ({
+ role: m.role,
+ content: (m.content || '').slice(0, 4000),
+ hidden: !!m.hidden,
+ tool_calls: m.tool_calls || null,
+ agentSteps: (m.agentSteps || []).map(s => ({
+ type: s.type, content: (s.content || '').slice(0, 1000),
+ toolName: s.toolName || null,
+ })),
+ }))
+ })
+ elapsedMs = Date.now() - startWait
+
+ // ── Save everything ──
+ const summary = {
+ mode, url, code,
+ elapsedMs,
+ toolCallCount: toolCalls.length,
+ toolCallsByName: toolCalls.reduce((acc, c) => { acc[c.tool] = (acc[c.tool] || 0) + 1; return acc }, {}),
+ chatEventCount: chatEvents.length,
+ consoleErrors: consoleLog.filter(l => l.type === 'pageerror' || l.type === 'error').length,
+ }
+ writeFileSync(`${outDir}/summary.json`, JSON.stringify(summary, null, 2))
+ saveAll()
+
+ console.log(`\n━━ SUMMARY ━━`)
+ console.log(JSON.stringify(summary, null, 2))
+ console.log(`\nTool calls (${toolCalls.length}):`)
+ for (const t of toolCalls) {
+ const okBadge = t.status === 200 ? '✓' : '✗'
+ const errFromBody = (t.responseBody || '').includes('"error"') ? ' ⚠ error in body' : ''
+ console.log(` ${okBadge} ${t.tool} args=${JSON.stringify(t.args).slice(0,100)} chatId=${t.chatId}${errFromBody}`)
+ }
+ console.log(`\nFinal assistant content:`)
+ const lastAssistant = final.filter(m => m.role === 'assistant').slice(-1)[0]
+ console.log(` "${(lastAssistant?.content || '').slice(0, 500)}"`)
+ console.log(`\nArtefacts at ${outDir}/`)
+
+ } catch (e) {
+ console.error('[browser] FAILED in main flow:', e)
+ saveAll()
+ throw e
+ } finally {
+ saveAll()
+ await ctx.close().catch(() => {})
+ await browser.close().catch(() => {})
+ }
+}
+
+main().catch(e => { console.error('[browser] fatal:', e); exit(2) })
diff --git a/scripts/remote-agent-e2e.mjs b/scripts/remote-agent-e2e.mjs
new file mode 100644
index 00000000..44f9be32
--- /dev/null
+++ b/scripts/remote-agent-e2e.mjs
@@ -0,0 +1,342 @@
+#!/usr/bin/env node
+/**
+ * Real agent E2E driven through the Remote bridge. Replicates exactly
+ * what mobile_landing()'s runToolLoop does:
+ * 1. Auth via /remote-api/auth (passcode → JWT).
+ * 2. Build messages: system + user.
+ * 3. POST to /api/chat (proxied to Ollama) with native `tools` array.
+ * 4. Ollama returns tool_calls; we execute each via /remote-api/agent-tool.
+ * 5. Push observations back as tool messages, loop until done.
+ *
+ * Two modes:
+ * --mode agent → AGENT_PROMPT (autonomous file-writer)
+ * --mode codex → CODEX_PROMPT (autonomous coding agent)
+ *
+ * Usage:
+ * node scripts/remote-agent-e2e.mjs --base http://<ip>:<port> --code <6-digit> --mode agent --model gemma4:e4b
+ */
+
+import { argv, exit } from 'node:process'
+
+function parseArgs() {
+ const out = {
+ base: null, code: null, model: 'gemma4:e4b',
+ mode: 'agent', chatId: 'agent-e2e',
+ task: null,
+ }
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i]
+ if (a === '--base') out.base = argv[++i]
+ else if (a === '--code') out.code = argv[++i]
+ else if (a === '--model') out.model = argv[++i]
+ else if (a === '--mode') out.mode = argv[++i]
+ else if (a === '--chat-id') out.chatId = argv[++i]
+ else if (a === '--task') out.task = argv[++i]
+ }
+ if (!out.base || !out.code) { console.error('Usage: --base <url> --code <6-digit> [--mode agent|codex]'); exit(2) }
+ if (!['agent', 'codex'].includes(out.mode)) { console.error('--mode must be agent or codex'); exit(2) }
+ return out
+}
+
+// ── Tool definitions — full 13-tool AGENT_TOOLS array from remote.rs::mobile_landing()
+// (parity with src/api/mcp/builtin-tools.ts). 10 of these are exposed to Codex too. ──
+const AGENT_TOOLS = [
+ { name: 'web_search', description: 'Search the web via the configured provider. Returns ranked {title, url, snippet}.',
+ parameters: [
+ { name: 'query', type: 'string', description: 'The search query', required: true },
+ { name: 'maxResults', type: 'number', description: 'Max results (default 5)', required: false },
+ ] },
+ { name: 'web_fetch', description: 'Fetch a single URL and return readable text up to 24000 chars.',
+ parameters: [
+ { name: 'url', type: 'string', description: 'Full URL with http(s)://', required: true },
+ ] },
+ { name: 'file_read', description: 'Read a UTF-8 text file. Returns full contents.',
+ parameters: [
+ { name: 'path', type: 'string', description: 'Path (relative or absolute)', required: true },
+ ] },
+ { name: 'file_write', description: 'Write a UTF-8 text file. Creates parent directories automatically. Relative paths resolve to the chat workspace folder.',
+ parameters: [
+ { name: 'path', type: 'string', description: 'Target file path', required: true },
+ { name: 'content', type: 'string', description: 'File contents', required: true },
+ ] },
+ { name: 'file_list', description: 'List directory contents. Set recursive:true for full tree.',
+ parameters: [
+ { name: 'path', type: 'string', description: 'Directory path', required: true },
+ { name: 'recursive', type: 'boolean', description: 'Include all subdirectories', required: false },
+ ] },
+ { name: 'file_search', description: 'Regex grep across files in a directory.',
+ parameters: [
+ { name: 'path', type: 'string', description: 'Directory to search', required: true },
+ { name: 'query', type: 'string', description: 'Regex pattern', required: true },
+ ] },
+ { name: 'shell_execute', description: 'Run a shell command. PowerShell on Windows. cwd defaults to chat workspace.',
+ parameters: [
+ { name: 'command', type: 'string', description: 'Shell command', required: true },
+ ] },
+ { name: 'code_execute', description: 'Run a Python script. Runs from the chat workspace.',
+ parameters: [
+ { name: 'code', type: 'string', description: 'Python source code', required: true },
+ ] },
+ { name: 'system_info', description: 'Return OS, architecture, hostname, RAM, CPU count.',
+ parameters: [] },
+ { name: 'process_list', description: 'List top 30 running processes by memory.',
+ parameters: [] },
+ { name: 'screenshot', description: 'Capture the primary display as a base64 PNG.',
+ parameters: [] },
+ { name: 'image_generate', description: 'Generate an image from text via local ComfyUI. (Returns graceful error in Remote.)',
+ parameters: [
+ { name: 'prompt', type: 'string', description: 'Positive text description', required: true },
+ ] },
+ { name: 'get_current_time', description: 'Return current local date, time, timezone.',
+ parameters: [] },
+]
+
+const CODEX_TOOL_NAMES = ['file_read','file_write','file_list','file_search','shell_execute','code_execute','system_info','get_current_time','web_search','web_fetch']
+const AGENT_TOOL_NAMES = AGENT_TOOLS.map(t => t.name)
+
+function buildToolDefs(tools) {
+ return tools.map(t => {
+ const props = {}
+ const req = []
+ for (const p of t.parameters || []) {
+ props[p.name] = { type: p.type, description: p.description }
+ if (p.required) req.push(p.name)
+ }
+ return {
+ type: 'function',
+ function: { name: t.name, description: t.description,
+ parameters: { type: 'object', properties: props, required: req } },
+ }
+ })
+}
+
+const AGENT_PROMPT = 'You are an autonomous AI agent inside Locally Uncensored. You execute tasks end-to-end via tools — you do NOT just describe what to do.\n\nAUTONOMY CONTRACT:\n- When asked to BUILD / CREATE / WRITE something, execute it via tools.\n- NEVER produce a code block followed by "save this as X". Execute it via file_write.\n- NEVER say "Now I will create X" as plain prose and stop. Do the next step right now as a tool call.\n\nFile rules:\n- file_write AUTOMATICALLY creates missing parent directories — do NOT shell out to mkdir / New-Item.\n- Relative paths resolve to the current chat workspace folder. Use relative paths.\n\nBe concise. All the work happens in tool calls.'
+
+const CODEX_PROMPT = 'You are Codex, an autonomous coding agent. Execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools.\n\nAUTONOMY CONTRACT:\n- COMPLETE multi-step tasks without prompting between steps.\n- NEVER say "Now I will create X" and stop. Execute the next step.\n- Chain ALL N steps in one session as concrete tool calls.\n\nWorkflow: explore → plan → implement (file_write) — chain ALL writes without stopping → final 1-3 sentence summary.\n\nFile & directory rules:\n- file_write AUTOMATICALLY creates missing parent directories. Never `mkdir` / `New-Item -ItemType Directory`.\n- All relative paths resolve to the current chat workspace.\n- shell_execute runs inside the workspace folder by default.\n- After 2-3 failures of the same approach, switch strategy.\n\nBe concise. Respond in the same language the user uses.'
+
+// Tasks force EVERY tool in the relevant set to be exercised in one run
+// ("überall alle testen pflicht ALLE IMMER"). Agent has 13, Codex 10.
+const TASK_AGENT = `You are running an agent compliance test. Build a tiny static greeting site inside folder "gemtest" AND prove every Remote tool works.
+
+You MUST call ALL 13 tools below at least once during this run. Do NOT emit a final answer until every tool listed has been used:
+ 1. get_current_time → record start time
+ 2. system_info → capture host facts
+ 3. process_list → snapshot running processes (just call it once)
+ 4. file_write → gemtest/index.html with <h1 id="hero">Hello LU E2E</h1> and <link rel="stylesheet" href="style.css">
+ 5. file_write → gemtest/style.css (body sans-serif on dark bg, #hero = 32px)
+ 6. file_write → gemtest/MARKER.txt containing exactly "MAGIC_LU_AGENT_E2E"
+ 7. file_search → grep gemtest/ for "MAGIC_LU_AGENT_E2E" (must hit MARKER.txt)
+ 8. file_list → list gemtest/ with recursive=true
+ 9. file_read → read gemtest/index.html back
+ 10. code_execute → Python that lists gemtest/ and writes gemtest/manifest.json
+ 11. shell_execute → "Get-ChildItem gemtest" or "ls gemtest" to confirm layout
+ 12. screenshot → call screenshot once (do not embed result, just confirm tool works)
+ 13. web_search → query "locally uncensored github" with maxResults 1
+ 14. web_fetch → fetch "https://example.com" (must succeed)
+ 15. image_generate → prompt "test" (Remote returns a graceful "desktop only" error — that still counts as "tool reachable")
+
+After every required tool was called, write a 1-2 sentence final summary listing which tools you used. DO NOT SKIP ANY TOOL.`
+
+const TASK_CODEX = `You are running a Codex compliance test. Build a Python utility "wordcount.py" in folder "wctest" AND prove every Codex tool works.
+
+You MUST call ALL 10 Codex tools below at least once during this run. Do NOT emit a final answer until every tool below has been used:
+ 1. get_current_time → record start time
+ 2. system_info → capture host facts
+ 3. file_write → wctest/wordcount.py (reads argv[1], prints JSON {"file","lines","words","bytes"})
+ 4. file_write → wctest/sample.txt with exactly 3 lines, including "MAGIC_LU_CODEX_E2E"
+ 5. file_search → grep wctest/ for "MAGIC_LU_CODEX_E2E" (must hit sample.txt)
+ 6. file_list → wctest/ recursive=true
+ 7. file_read → wctest/wordcount.py back
+ 8. shell_execute → "python wctest/wordcount.py wctest/sample.txt"
+ 9. code_execute → Python that writes wctest/runinfo.json with timing + result
+ 10. web_search → query "python json module" with maxResults 1
+ 11. web_fetch → fetch "https://example.com"
+
+After every required tool was called, write a 1-2 sentence final summary listing which tools you used. DO NOT SKIP ANY TOOL.`
+
+async function authenticate(base, code) {
+ const r = await fetch(`${base}/remote-api/auth`, {
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ passcode: code }),
+ })
+ if (!r.ok) throw new Error(`auth ${r.status}: ${await r.text()}`)
+ return (await r.json()).token
+}
+
+async function runTool(base, token, chatId, tool, args) {
+ const r = await fetch(`${base}/remote-api/agent-tool`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
+ body: JSON.stringify({ tool, args, chatId }),
+ })
+ return await r.json()
+}
+
+function observationToString(data) {
+ if (!data) return ''
+ if (typeof data.error === 'string') return 'Error: ' + data.error
+ if (typeof data.content === 'string') return data.content
+ if (data.status === 'saved') return 'File saved: ' + (data.path || '')
+ if (Array.isArray(data.entries)) return JSON.stringify(data.entries.slice(0, 50), null, 2)
+ if (Array.isArray(data.results)) return JSON.stringify(data.results.slice(0, 20), null, 2)
+ if (data.exitCode !== undefined) {
+ if (data.timedOut) return 'Execution timed out.'
+ if (data.exitCode !== 0) return `Error (${data.exitCode}):\n${data.stderr || data.stdout}`
+ return data.stdout || 'Done.'
+ }
+ if (data.iso || data.iso_local) return JSON.stringify(data)
+ return JSON.stringify(data)
+}
+
+// runToolLoop logic ported from mobile_landing()
+function isSystemPromptEcho(content) {
+ if (!content) return false
+ const head = String(content).trim().slice(0, 240)
+ if (/^(hello[!,\.]?\s+|hi[!,\.]?\s+|hey[!,\.]?\s+)?(i['’]?m|i am|you are)\s+(codex|an autonomous|the agent|an? ai)/i.test(head)) return true
+ if (/^(i am|i['’]m)\s+ready\s+to\s+(receive|assist|help)/i.test(head)) return true
+ if (/^(hello|hi|hey)[!,\.]?\s+i['’]?m\s+ready/i.test(head)) return true
+ return false
+}
+
+function repairToolCallArgs(tc) {
+ if (!tc?.function) return tc
+ let a = tc.function.arguments
+ if (typeof a === 'string') {
+ try { tc.function.arguments = JSON.parse(a) } catch (_) {}
+ }
+ return tc
+}
+
+async function chat(base, token, model, messages, tools) {
+ const r = await fetch(`${base}/api/chat`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
+ body: JSON.stringify({ model, messages, tools, stream: false, options: { temperature: 0.2 } }),
+ })
+ if (!r.ok) throw new Error(`/api/chat ${r.status}: ${await r.text()}`)
+ return await r.json()
+}
+
+async function runAgentLoop({ base, token, model, chatId, system, task, allowedNames }) {
+ const filtered = AGENT_TOOLS.filter(t => allowedNames.includes(t.name))
+ const tools = buildToolDefs(filtered)
+ const messages = [
+ { role: 'system', content: system },
+ { role: 'user', content: task },
+ ]
+ const transcript = []
+ const usedTools = new Set()
+ const maxIter = 60 // doubled to give nudges room
+ let echoRetries = 3
+ let consecutiveErrors = 0
+ const maxConsecutiveErrors = 5
+ let final = null
+ let nudgesUsed = 0
+ const maxNudges = 3 // up to 3 follow-up nudges if the model stops early
+
+ for (let iter = 1; iter <= maxIter; iter++) {
+ process.stdout.write(` · iter ${iter}: model thinking...`)
+ const t0 = Date.now()
+ const res = await chat(base, token, model, messages, tools)
+ const ms = Date.now() - t0
+ process.stdout.write(` (${ms}ms)\n`)
+ const msg = res.message || {}
+ let content = msg.content || ''
+ let toolCalls = (msg.tool_calls || []).map(repairToolCallArgs)
+
+ if (isSystemPromptEcho(content)) {
+ if (echoRetries > 0) {
+ echoRetries--
+ console.log(` · echo detected → silent retry (left=${echoRetries})`)
+ messages.push({ role: 'user', content: 'Continue the task. Do not introduce yourself again. Resume from the last successful step using the appropriate tool call.' })
+ continue
+ }
+ console.log(` · echo retries spent → dropping content`)
+ content = ''
+ }
+
+ if (!toolCalls.length) {
+ // Compliance check: if there are still mandated tools that haven't
+ // been touched, nudge the model to use them before letting it finish.
+ const missing = allowedNames.filter(n => !usedTools.has(n))
+ if (missing.length > 0 && nudgesUsed < maxNudges) {
+ nudgesUsed++
+ console.log(` · model wants to stop but ${missing.length} tools still missing → nudge ${nudgesUsed}/${maxNudges}: ${missing.join(', ')}`)
+ // Push the model's would-be final as an assistant message so the
+ // history stays coherent, then add a user nudge.
+ messages.push({ role: 'assistant', content: content || '' })
+ messages.push({ role: 'user', content:
+ `You stopped before exercising every required tool. Still missing: ${missing.join(', ')}. ` +
+ `Call each of those tools NOW (one per turn is fine) with a small useful invocation, then write the final summary. ` +
+ `Tools list reminder: ${allowedNames.join(', ')}.`
+ })
+ continue
+ }
+ final = content || null
+ transcript.push({ kind: 'final', content: final })
+ console.log(` · no toolCalls → finalAnswer (after ${nudgesUsed} nudges)\n "${(final || '(empty → fallback summary will kick in on the UI)').slice(0, 200)}"`)
+ break
+ }
+
+ messages.push({ role: 'assistant', content, tool_calls: toolCalls.map(tc => ({ function: { name: tc.function.name, arguments: tc.function.arguments } })) })
+
+ for (const tc of toolCalls) {
+ const name = tc.function.name
+ usedTools.add(name)
+ const args = tc.function.arguments || {}
+ const argsPretty = JSON.stringify(args).slice(0, 200)
+ console.log(` → ${name} ${argsPretty}`)
+ const data = await runTool(base, token, chatId, name, args)
+ const obs = observationToString(data)
+ const isErr = /^(Error|Permission denied|Network error)/i.test(obs)
+ if (isErr) consecutiveErrors++; else consecutiveErrors = 0
+ const obsShort = obs.slice(0, 220).replaceAll('\n', ' ')
+ console.log(` ${isErr ? '✗' : '✓'} ${obsShort}${obs.length > 220 ? '…' : ''}`)
+ transcript.push({ kind: 'tool', name, args, observation: obs, error: isErr })
+ messages.push({ role: 'tool', content: obs })
+
+ if (consecutiveErrors >= maxConsecutiveErrors) {
+ console.log(` ! consecutiveErrors=${consecutiveErrors} → bailing`)
+ final = null
+ break
+ }
+ }
+ if (consecutiveErrors >= maxConsecutiveErrors) break
+ }
+
+ return { final, transcript, usedTools, consecutiveErrors, echoRetries, nudgesUsed }
+}
+
+async function main() {
+ const { base, code, mode, model, chatId, task } = parseArgs()
+ const token = await authenticate(base, code)
+ console.log(`[e2e] Authenticated. Mode=${mode} Model=${model} ChatId=${chatId}`)
+ const system = mode === 'codex' ? CODEX_PROMPT : AGENT_PROMPT
+ const userTask = task || (mode === 'codex' ? TASK_CODEX : TASK_AGENT)
+ console.log(`[e2e] Task:\n ${userTask.replaceAll('\n', '\n ')}\n`)
+
+ const allowedNames = mode === 'codex' ? CODEX_TOOL_NAMES : AGENT_TOOL_NAMES
+ console.log(`[e2e] Tools available: ${allowedNames.length} (${allowedNames.join(', ')})\n`)
+ const t0 = Date.now()
+ const result = await runAgentLoop({ base, token, model, chatId, system, task: userTask, allowedNames })
+ const elapsed = Date.now() - t0
+
+ const missing = allowedNames.filter(n => !result.usedTools.has(n))
+ console.log(`\n━━ Run summary ━━`)
+ console.log(`Mode: ${mode}`)
+ console.log(`Tools available: ${allowedNames.length}`)
+ console.log(`Tools exercised (${result.usedTools.size}): ${[...result.usedTools].sort().join(', ')}`)
+ console.log(`Tools NOT exercised (${missing.length}): ${missing.length ? missing.join(', ') : '(none — all tools hit ✓)'}`)
+ console.log(`Tool turns recorded: ${result.transcript.filter(t => t.kind === 'tool').length}`)
+ console.log(`Errors during run: ${result.transcript.filter(t => t.kind === 'tool' && t.error).length}`)
+ console.log(`Echo retries used: ${3 - result.echoRetries}`)
+ console.log(`Consecutive-err count: ${result.consecutiveErrors}`)
+ console.log(`Tool-coverage nudges used: ${result.nudgesUsed}`)
+ console.log(`Total wall time: ${elapsed} ms`)
+ const hasGreeting = result.final && /^(hello|hi|hey).{0,40}(codex|the agent|an ai)/i.test(result.final)
+ console.log(`Final answer was a greeting: ${hasGreeting ? 'YES (BUG)' : 'NO ✓'}`)
+ console.log(`Final answer:\n "${(result.final || '(no final, fallback would kick in)').slice(0, 400)}"`)
+ exit(hasGreeting || missing.length > 0 ? 1 : 0)
+}
+
+main().catch(e => { console.error('[e2e] fatal:', e); exit(2) })
diff --git a/scripts/remote-all-tools-e2e.mjs b/scripts/remote-all-tools-e2e.mjs
new file mode 100644
index 00000000..bccd2360
--- /dev/null
+++ b/scripts/remote-all-tools-e2e.mjs
@@ -0,0 +1,235 @@
+#!/usr/bin/env node
+/**
+ * All-tools-in-one-run E2E. Mimics what an agent does over the course of
+ * one multi-step task — exercising every Remote tool sequentially in a
+ * single authenticated session, the same way `runToolLoop` would dispatch
+ * them. Proves that nothing leaks paths into ~/agent-workspace/__remote__/
+ * and that the tool chain works end-to-end with the user-picked workspace.
+ *
+ * Task being simulated:
+ * "Build a tiny static site (index.html, style.css), grep for a tag,
+ * list the tree, run a shell + python diagnostic, capture system info,
+ * and write a final summary file."
+ *
+ * Usage:
+ * node scripts/remote-all-tools-e2e.mjs --base http://<ip>:<port> --code <6-digit>
+ */
+
+import { argv, exit } from 'node:process'
+
+function parseArgs() {
+ const out = { base: null, code: null, chatId: 'all-tools-e2e' }
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i]
+ if (a === '--base') out.base = argv[++i]
+ else if (a === '--code') out.code = argv[++i]
+ else if (a === '--chat-id') out.chatId = argv[++i]
+ }
+ if (!out.base || !out.code) { console.error('Usage: --base <url> --code <6-digit>'); exit(2) }
+ return out
+}
+
+async function authenticate(base, code) {
+ const r = await fetch(`${base}/remote-api/auth`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ passcode: code }),
+ })
+ if (!r.ok) throw new Error(`auth ${r.status}: ${await r.text()}`)
+ const data = await r.json()
+ return data.token
+}
+
+async function tool(base, token, chatId, name, args) {
+ const r = await fetch(`${base}/remote-api/agent-tool`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
+ body: JSON.stringify({ tool: name, args, chatId }),
+ })
+ return await r.json()
+}
+
+let pass = 0, fail = 0
+function check(label, ok, detail) {
+ if (ok) { console.log(` ✓ ${label}`); pass++ }
+ else { console.error(` ✗ ${label}\n ${detail}`); fail++ }
+}
+
+const NOT_REMOTE = (s) => !String(s || '').replaceAll('\\', '/').includes('agent-workspace/__remote__')
+
+async function step(label, fn) {
+ console.log(`\n━━ ${label} ━━`)
+ return await fn()
+}
+
+async function main() {
+ const { base, code, chatId } = parseArgs()
+ const token = await authenticate(base, code)
+ console.log(`[e2e] auth ok, chatId=${chatId}`)
+
+ const startedAt = Date.now()
+ const toolsHit = new Set()
+ const T = (n) => { toolsHit.add(n); return n }
+
+ // ── 1. Time check (no permissions) ──
+ await step('1. get_current_time — kick off the run', async () => {
+ const t = await tool(base, token, chatId, T('get_current_time'), {})
+ check('time tool returned', !!t && (t.iso || t.iso_local || t.unix), JSON.stringify(t))
+ })
+
+ // ── 2. System info ──
+ await step('2. system_info — capture host facts', async () => {
+ const s = await tool(base, token, chatId, T('system_info'), {})
+ check('system_info returned object', !!s && typeof s === 'object', JSON.stringify(s))
+ check('system_info had at least one of os/platform/cpu/osName',
+ s && (s.os || s.platform || s.cpu || s.osName), JSON.stringify(s))
+ })
+
+ // ── 3. file_write — index.html ──
+ let writePath
+ await step('3. file_write index.html — start the site build', async () => {
+ const w = await tool(base, token, chatId, T('file_write'), {
+ path: 'site/index.html',
+ content: '<!doctype html><html><head><title>LU E2E</title>' +
+ '<link rel="stylesheet" href="style.css"></head>' +
+ '<body><h1 id="hero">Hello LU E2E</h1></body></html>\n',
+ })
+ check('file_write status=saved', w?.status === 'saved', JSON.stringify(w))
+ check('file_write path NOT in __remote__', NOT_REMOTE(w?.path), w?.path)
+ writePath = w?.path
+ })
+
+ // ── 4. file_write — style.css ──
+ await step('4. file_write style.css — second artefact', async () => {
+ const w = await tool(base, token, chatId, T('file_write'), {
+ path: 'site/style.css',
+ content: 'body{font-family:sans-serif;background:#111;color:#eee}\n#hero{font-size:32px}\n',
+ })
+ check('css saved', w?.status === 'saved', JSON.stringify(w))
+ check('css path NOT in __remote__', NOT_REMOTE(w?.path), w?.path)
+ })
+
+ // ── 5. file_list — confirm both files exist ──
+ await step('5. file_list site/ — verify the layout', async () => {
+ const l = await tool(base, token, chatId, T('file_list'), { path: 'site' })
+ const names = (l?.entries || []).map(e => String(e.name || ''))
+ check('file_list returned array', Array.isArray(l?.entries), JSON.stringify(l))
+ check('found index.html', names.some(n => /index\.html$/.test(n)), names.join('|'))
+ check('found style.css', names.some(n => /style\.css$/.test(n)), names.join('|'))
+ })
+
+ // ── 6. file_list recursive — full tree ──
+ await step('6. file_list recursive — full tree', async () => {
+ const l = await tool(base, token, chatId, T('file_list'), { path: '.', recursive: true })
+ check('recursive list returned entries',
+ Array.isArray(l?.entries) && l.entries.length >= 2, JSON.stringify(l).slice(0,200))
+ })
+
+ // ── 7. file_read — read the index back ──
+ await step('7. file_read index.html — round-trip content', async () => {
+ const r = await tool(base, token, chatId, T('file_read'), { path: 'site/index.html' })
+ check('file_read returned content', typeof r?.content === 'string', JSON.stringify(r))
+ check('file_read content includes "<h1 id=\\"hero\\">"',
+ typeof r?.content === 'string' && r.content.includes('<h1 id="hero">'),
+ r?.content?.slice?.(0, 200))
+ })
+
+ // ── 8. file_search — grep for the hero id ──
+ await step('8. file_search "hero" — grep regex', async () => {
+ const s = await tool(base, token, chatId, T('file_search'), {
+ path: 'site', query: 'hero',
+ })
+ check('file_search returned results array', Array.isArray(s?.results), JSON.stringify(s))
+ const hit = (s?.results || []).find(r => /index\.html$/.test(r.file || ''))
+ check('grep hit index.html', !!hit, JSON.stringify(s?.results))
+ check('hit file path NOT in __remote__',
+ hit ? NOT_REMOTE(hit.file) : false, JSON.stringify(hit))
+ })
+
+ // ── 9. shell_execute — list files via a real shell command ──
+ await step('9. shell_execute — sanity diagnostic', async () => {
+ const cmd = process.platform === 'win32'
+ ? 'Get-ChildItem -Recurse | Select-Object -First 10 | ForEach-Object { $_.FullName }'
+ : 'find . -maxdepth 2 | head -20'
+ const sh = await tool(base, token, chatId, T('shell_execute'), { command: cmd })
+ check('shell_execute had stdout', typeof sh?.stdout === 'string', JSON.stringify(sh))
+ check('shell_execute exitCode 0', sh?.exitCode === 0, JSON.stringify(sh))
+ check('shell saw site/index.html in cwd',
+ typeof sh?.stdout === 'string' && /site/i.test(sh.stdout),
+ sh?.stdout?.slice?.(0, 300))
+ check('shell stdout NOT mentioning __remote__',
+ typeof sh?.stdout === 'string' && NOT_REMOTE(sh.stdout),
+ sh?.stdout?.slice?.(0, 300))
+ })
+
+ // ── 10. code_execute — Python writes a JSON manifest ──
+ await step('10. code_execute Python — emit manifest.json', async () => {
+ const code = `
+import os, json
+files = []
+for root, dirs, names in os.walk('.'):
+ for n in names:
+ p = os.path.join(root, n)
+ files.append({'path': p, 'size': os.path.getsize(p)})
+with open('manifest.json','w',encoding='utf-8') as f:
+ json.dump({'cwd': os.getcwd(), 'files': files}, f, indent=2)
+print('manifest written, file count =', len(files))
+`.trim()
+ const py = await tool(base, token, chatId, T('code_execute'), { code, timeout: 30000 })
+ check('python exitCode 0', py?.exitCode === 0, JSON.stringify(py))
+ check('python printed file count',
+ typeof py?.stdout === 'string' && /file count = \d+/.test(py.stdout),
+ py?.stdout)
+ })
+
+ // ── 11. file_read manifest.json — round trip ──
+ await step('11. file_read manifest.json — verify python output', async () => {
+ const r = await tool(base, token, chatId, T('file_read'), { path: 'manifest.json' })
+ check('manifest read', typeof r?.content === 'string', JSON.stringify(r))
+ let parsed = null
+ try { parsed = JSON.parse(r.content) } catch (_) {}
+ check('manifest is valid JSON', !!parsed, r?.content?.slice?.(0, 200))
+ check('manifest cwd is the override folder',
+ parsed && typeof parsed.cwd === 'string' && NOT_REMOTE(parsed.cwd),
+ parsed?.cwd)
+ check('manifest lists ≥ 3 files (index, style, manifest)',
+ parsed && Array.isArray(parsed.files) && parsed.files.length >= 3,
+ JSON.stringify(parsed?.files?.length))
+ })
+
+ // ── 12. shell_execute with explicit relative cwd ──
+ await step('12. shell_execute cwd=site — relative cwd resolves', async () => {
+ const cmd = process.platform === 'win32' ? '$pwd.Path' : 'pwd'
+ const sh = await tool(base, token, chatId, T('shell_execute'), { command: cmd, cwd: 'site' })
+ check('shell saw site as cwd',
+ typeof sh?.stdout === 'string' && /site/i.test(sh.stdout) && NOT_REMOTE(sh.stdout),
+ sh?.stdout?.slice?.(0, 300))
+ })
+
+ // ── 13. file_write — final summary ──
+ await step('13. file_write summary.md — wrap-up artefact', async () => {
+ const w = await tool(base, token, chatId, T('file_write'), {
+ path: 'summary.md',
+ content: `# LU Remote Multi-Tool E2E\n\nRun completed at ${new Date().toISOString()}.\nTools exercised: ${[...toolsHit].join(', ')}\n`,
+ })
+ check('summary saved', w?.status === 'saved', JSON.stringify(w))
+ })
+
+ // ── 14. image_generate — graceful unsupported ──
+ await step('14. image_generate — graceful "desktop only" error', async () => {
+ const i = await tool(base, token, chatId, T('image_generate'), { prompt: 'cat' })
+ check('image_generate returned graceful error',
+ typeof i?.error === 'string' && /desktop|create tab/i.test(i.error),
+ JSON.stringify(i))
+ })
+
+ // ── Summary ──
+ const elapsed = Date.now() - startedAt
+ console.log(`\n━━ Run summary ━━`)
+ console.log(`Tools exercised in this single run: ${[...toolsHit].sort().join(', ')}`)
+ console.log(`Total duration: ${elapsed} ms`)
+ console.log(`\n${pass} passed, ${fail} failed.`)
+ exit(fail === 0 ? 0 : 1)
+}
+
+main().catch(e => { console.error('[e2e] fatal:', e); exit(2) })
diff --git a/scripts/remote-smoke.mjs b/scripts/remote-smoke.mjs
new file mode 100644
index 00000000..6815cf91
--- /dev/null
+++ b/scripts/remote-smoke.mjs
@@ -0,0 +1,304 @@
+#!/usr/bin/env node
+/**
+ * Remote-Access smoke harness — talks to the LU desktop app's local
+ * remote server (the same one the mobile page uses). Lets us exercise
+ * the file/agent endpoints from a Node script so we can reproduce + fix
+ * Remote bugs without burning the user's time on phone clicks.
+ *
+ * Bootstrap (one-time per session):
+ * 1. Launch the LU desktop exe.
+ * 2. Open Remote drawer → click "LAN" → click Dispatch on a chat → pick a folder.
+ * 3. The drawer shows a URL like `http://192.168.1.42:8765` and a 6-digit code.
+ * 4. Run this script with both:
+ * node scripts/remote-smoke.mjs \
+ * --base http://192.168.1.42:8765 \
+ * --code 123456 \
+ * --chat-id <slug from drawer / any string the desktop assigns>
+ *
+ * What it does:
+ * - POST /remote-api/auth to swap the 6-digit code for a JWT token
+ * - POST /remote-api/agent-tool with file_write / file_list calls
+ * - Verifies the resulting paths land in the user-picked folder, NOT
+ * in `~/agent-workspace/__remote__/`.
+ *
+ * Exit code 0 = all assertions passed, 1 = at least one failure.
+ */
+
+import { argv, exit } from 'node:process'
+import { join } from 'node:path'
+
+function parseArgs() {
+ const out = { base: null, code: null, chatId: 'remote-smoke' }
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i]
+ if (a === '--base') out.base = argv[++i]
+ else if (a === '--code') out.code = argv[++i]
+ else if (a === '--chat-id') out.chatId = argv[++i]
+ else if (a === '--help' || a === '-h') {
+ console.log('Usage: remote-smoke.mjs --base <url> --code <6-digit> [--chat-id <slug>]')
+ exit(0)
+ }
+ }
+ if (!out.base || !out.code) {
+ console.error('Missing --base or --code. Run with --help for usage.')
+ exit(2)
+ }
+ return out
+}
+
+async function authenticate(base, code) {
+ const r = await fetch(`${base}/remote-api/auth`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ // Server expects `passcode` (matches AuthRequest struct in remote.rs).
+ body: JSON.stringify({ passcode: code }),
+ })
+ if (!r.ok) {
+ const txt = await r.text()
+ throw new Error(`auth failed: ${r.status} ${txt}`)
+ }
+ const data = await r.json()
+ if (!data.token) throw new Error(`auth response missing token: ${JSON.stringify(data)}`)
+ return data.token
+}
+
+async function agentTool(base, token, chatId, tool, args) {
+ const r = await fetch(`${base}/remote-api/agent-tool`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${token}`,
+ },
+ body: JSON.stringify({ tool, args, chatId }),
+ })
+ const text = await r.text()
+ let data = null
+ try { data = JSON.parse(text) } catch (_) {}
+ if (!r.ok && !data) throw new Error(`HTTP ${r.status}: ${text}`)
+ return data ?? text
+}
+
+let passed = 0
+let failed = 0
+function check(label, ok, detail) {
+ if (ok) {
+ console.log(` ✓ ${label}`)
+ passed++
+ } else {
+ console.error(` ✗ ${label}\n ${detail || '(no detail)'}`)
+ failed++
+ }
+}
+
+async function main() {
+ const { base, code, chatId } = parseArgs()
+ console.log(`[remote-smoke] base=${base} chat=${chatId}`)
+ const token = await authenticate(base, code)
+ console.log(`[remote-smoke] authenticated (token ${token.slice(0, 8)}…)`)
+
+ // 1) file_write — should succeed, returns absolute path. The path field
+ // tells us where the desktop actually wrote the bytes.
+ console.log('\n— file_write —')
+ const writeRes = await agentTool(base, token, chatId, 'file_write', {
+ path: 'remote-smoke/hello.txt',
+ content: 'hello from the smoke harness\n',
+ })
+ check('file_write returned object', writeRes && typeof writeRes === 'object', JSON.stringify(writeRes))
+ check('file_write status=saved', writeRes?.status === 'saved', JSON.stringify(writeRes))
+ check('file_write returned path', typeof writeRes?.path === 'string', JSON.stringify(writeRes))
+ const writePath = writeRes?.path || ''
+ console.log(` wrote to: ${writePath}`)
+ check('file_write path is NOT ~/agent-workspace/__remote__/',
+ !writePath.replaceAll('\\', '/').includes('agent-workspace/__remote__/'),
+ `path was ${writePath} — bug 1 still present`)
+
+ // 2) file_list — same relative folder. Should return one entry (hello.txt).
+ console.log('\n— file_list —')
+ const listRes = await agentTool(base, token, chatId, 'file_list', {
+ path: 'remote-smoke',
+ })
+ check('file_list returned object', listRes && typeof listRes === 'object', JSON.stringify(listRes))
+ check('file_list has entries', Array.isArray(listRes?.entries), JSON.stringify(listRes))
+ const found = (listRes?.entries || []).find(e => /hello\.txt$/.test(e.name || e.path || ''))
+ check('file_list found hello.txt we just wrote', !!found,
+ `entries: ${JSON.stringify(listRes?.entries)}`)
+
+ // 3) file_list with a NON-EXISTENT relative path → should error gracefully
+ console.log('\n— file_list (non-existent) —')
+ const list404 = await agentTool(base, token, chatId, 'file_list', {
+ path: 'this-folder-does-not-exist-anywhere',
+ })
+ check('file_list non-existent returns error field',
+ typeof list404?.error === 'string',
+ JSON.stringify(list404))
+
+ // 4) file_read of the file we just wrote → confirms round-trip
+ console.log('\n— file_read —')
+ const readRes = await agentTool(base, token, chatId, 'file_read', {
+ path: 'remote-smoke/hello.txt',
+ })
+ check('file_read returns content', typeof readRes?.content === 'string',
+ JSON.stringify(readRes))
+ check('file_read content matches what we wrote',
+ readRes?.content === 'hello from the smoke harness\n',
+ `got: ${JSON.stringify(readRes?.content)}`)
+
+ // 5) shell_execute → should default cwd to workspace, runs `pwd` (or `cd`)
+ console.log('\n— shell_execute (cwd default) —')
+ const cmd = process.platform === 'win32' ? '$pwd.Path' : 'pwd'
+ const shellRes = await agentTool(base, token, chatId, 'shell_execute', {
+ command: cmd,
+ })
+ check('shell_execute returned object', shellRes && typeof shellRes === 'object',
+ JSON.stringify(shellRes))
+ check('shell_execute has stdout', typeof shellRes?.stdout === 'string',
+ JSON.stringify(shellRes))
+ if (typeof shellRes?.stdout === 'string') {
+ console.log(` cwd seen by shell: ${shellRes.stdout.trim()}`)
+ check('shell_execute cwd is NOT ~/agent-workspace/__remote__/',
+ !shellRes.stdout.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ `stdout was ${shellRes.stdout}`)
+ }
+
+ // 6) shell_execute with explicit relative cwd → should resolve against override too
+ console.log('\n— shell_execute (relative cwd) —')
+ const shellRel = await agentTool(base, token, chatId, 'shell_execute', {
+ command: cmd,
+ cwd: 'remote-smoke',
+ })
+ if (typeof shellRel?.stdout === 'string') {
+ console.log(` cwd: ${shellRel.stdout.trim()}`)
+ check('shell_execute resolved relative cwd into override folder',
+ shellRel.stdout.includes('remote-smoke') &&
+ !shellRel.stdout.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ `stdout was ${shellRel.stdout}`)
+ } else {
+ check('shell_execute (relative cwd) returned stdout', false, JSON.stringify(shellRel))
+ }
+
+ // 7) file_search — write a known marker file, then grep for it
+ console.log('\n— file_search —')
+ await agentTool(base, token, chatId, 'file_write', {
+ path: 'remote-smoke/grepme.txt',
+ content: 'GREP_MARKER_LU_REMOTE_SMOKE\nsecond line\n',
+ })
+ const searchRes = await agentTool(base, token, chatId, 'file_search', {
+ path: 'remote-smoke',
+ query: 'GREP_MARKER_LU_REMOTE_SMOKE',
+ })
+ check('file_search returns results array',
+ Array.isArray(searchRes?.results),
+ JSON.stringify(searchRes))
+ const hit = (searchRes?.results || []).find(r =>
+ /grepme\.txt$/.test(r.file || ''))
+ check('file_search found the marker we just wrote', !!hit,
+ JSON.stringify(searchRes?.results))
+ check('file_search hit file path is NOT under agent-workspace/__remote__/',
+ hit ? !String(hit.file).replaceAll('\\', '/').includes('agent-workspace/__remote__') : false,
+ `hit was ${JSON.stringify(hit)}`)
+
+ // 8) file_list with recursive=true → should include both files we wrote
+ console.log('\n— file_list (recursive) —')
+ const listRec = await agentTool(base, token, chatId, 'file_list', {
+ path: 'remote-smoke',
+ recursive: true,
+ })
+ const recNames = (listRec?.entries || []).map(e => String(e.name || ''))
+ check('file_list recursive returned entries',
+ Array.isArray(listRec?.entries) && listRec.entries.length > 0,
+ JSON.stringify(listRec))
+ check('file_list recursive included hello.txt',
+ recNames.some(n => /hello\.txt$/.test(n)),
+ `entries: ${JSON.stringify(recNames)}`)
+ check('file_list recursive included grepme.txt',
+ recNames.some(n => /grepme\.txt$/.test(n)),
+ `entries: ${JSON.stringify(recNames)}`)
+
+ // 9) code_execute (Python) → relative file write inside the override folder
+ console.log('\n— code_execute (Python) —')
+ const pyRes = await agentTool(base, token, chatId, 'code_execute', {
+ code: "import os; open('from-python.txt','w').write('hi'); print(os.getcwd())",
+ timeout: 30000,
+ })
+ check('code_execute returned object', pyRes && typeof pyRes === 'object',
+ JSON.stringify(pyRes))
+ check('code_execute exitCode 0',
+ pyRes?.exitCode === 0,
+ `exitCode=${pyRes?.exitCode} stderr=${pyRes?.stderr}`)
+ if (typeof pyRes?.stdout === 'string') {
+ console.log(` python cwd: ${pyRes.stdout.trim()}`)
+ check('code_execute cwd is NOT ~/agent-workspace/__remote__/',
+ !pyRes.stdout.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ `stdout was ${pyRes.stdout}`)
+ }
+ // Confirm via file_read that python's relative write landed in the override
+ const pyReadBack = await agentTool(base, token, chatId, 'file_read', {
+ path: 'from-python.txt',
+ })
+ check('python-written file is readable via the override workspace',
+ pyReadBack?.content === 'hi',
+ JSON.stringify(pyReadBack))
+
+ // 10) get_current_time — no permissions, no path arg, should always work
+ console.log('\n— get_current_time —')
+ const timeRes = await agentTool(base, token, chatId, 'get_current_time', {})
+ const hasTimeShape = timeRes && (typeof timeRes.iso === 'string' ||
+ typeof timeRes.iso_local === 'string' || typeof timeRes.iso_utc === 'string' ||
+ typeof timeRes.timestamp === 'number' || typeof timeRes.unix === 'number' ||
+ typeof timeRes.now === 'string' || typeof timeRes.utc === 'string')
+ check('get_current_time returned a time-shaped object', hasTimeShape,
+ JSON.stringify(timeRes))
+
+ // 11) system_info — no permissions, returns hardware/OS facts
+ console.log('\n— system_info —')
+ const sysRes = await agentTool(base, token, chatId, 'system_info', {})
+ check('system_info returned object', sysRes && typeof sysRes === 'object',
+ JSON.stringify(sysRes))
+ check('system_info has at least one expected field',
+ sysRes && (sysRes.os || sysRes.platform || sysRes.cpu || sysRes.osName),
+ JSON.stringify(sysRes))
+
+ // 12) image_generate → expected to return graceful "desktop only" error
+ console.log('\n— image_generate (graceful unsupported) —')
+ const imgRes = await agentTool(base, token, chatId, 'image_generate', {
+ prompt: 'placeholder',
+ })
+ check('image_generate returned object', imgRes && typeof imgRes === 'object',
+ JSON.stringify(imgRes))
+ check('image_generate returned a graceful error string (not an HTTP 500)',
+ typeof imgRes?.error === 'string' && /desktop|create tab/i.test(imgRes.error),
+ JSON.stringify(imgRes))
+
+ // 13) Bug-1 regression — file_write to a NESTED relative path that doesn't
+ // exist yet. Auto-create-parent must work, AND the resolved path must NOT
+ // contain agent-workspace/__remote__.
+ console.log('\n— file_write deep nested (Bug 1 regression) —')
+ const deep = await agentTool(base, token, chatId, 'file_write', {
+ path: 'remote-smoke/a/b/c/deep.txt',
+ content: 'auto-created parents\n',
+ })
+ check('deep file_write status=saved', deep?.status === 'saved',
+ JSON.stringify(deep))
+ check('deep file_write path is NOT under agent-workspace/__remote__/',
+ typeof deep?.path === 'string' &&
+ !deep.path.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ `path was ${deep?.path}`)
+
+ // 14) Wrong-arg shape → should come back as a clean {error} (graceful 200),
+ // NOT an HTTP 500. This is the contract the mobile JS depends on.
+ console.log('\n— graceful error shape —')
+ const bad = await agentTool(base, token, chatId, 'file_read', {
+ path: '',
+ })
+ check('missing-path file_read returns {error} string',
+ typeof bad?.error === 'string',
+ JSON.stringify(bad))
+
+ console.log(`\n[remote-smoke] ${passed} passed, ${failed} failed.`)
+ exit(failed === 0 ? 0 : 1)
+}
+
+main().catch(err => {
+ console.error('[remote-smoke] fatal:', err)
+ exit(2)
+})
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rs
index 903cee2e..e9183037 100644
--- a/src-tauri/src/commands/agent.rs
+++ b/src-tauri/src/commands/agent.rs
@@ -29,7 +29,19 @@ fn agent_workspace_root() -> PathBuf {
/// `[A-Za-z0-9_\-\.]` is replaced with `_` and the string is capped at
/// 64 chars. The original id is kept in the chat UI; only the filesystem
/// form is sanitised.
-fn agent_workspace(chat_id: Option<&str>) -> PathBuf {
+///
+/// `state` (when present) is consulted for a per-chat override the user
+/// picked via the Remote dispatch folder picker — when set, the override
+/// path wins over the default `~/agent-workspace/<chat_id>/` so the
+/// agent writes land where the user expects (#29 follow-up).
+fn agent_workspace(chat_id: Option<&str>, state: Option<&AppState>) -> PathBuf {
+ if let (Some(id), Some(s)) = (chat_id, state) {
+ if let Ok(map) = s.chat_workspace_overrides.lock() {
+ if let Some(p) = map.get(id) {
+ return p.clone();
+ }
+ }
+ }
let root = agent_workspace_root();
let id = chat_id.unwrap_or("default");
let safe: String = id
@@ -41,6 +53,16 @@ fn agent_workspace(chat_id: Option<&str>) -> PathBuf {
root.join(slug)
}
+/// Public alias used by remote.rs's `/remote-api/agent-tool` route — that
+/// endpoint already has &AppState and resolves the per-chat workspace
+/// before delegating to file_read/file_write. Exposing this lets the
+/// remote bridge honour the same override map without crossing module
+/// privacy.
+#[allow(dead_code)]
+pub(crate) fn agent_workspace_for(chat_id: Option<&str>, state: &AppState) -> PathBuf {
+ agent_workspace(chat_id, Some(state))
+}
+
/// Defensive normalization that strips duplicate drive-letter prefixes.
///
/// The caller (desktop useCodex.ts or the model itself) can end up with paths
@@ -72,19 +94,21 @@ fn normalize_duplicate_drive_prefix(path: &str) -> String {
}
}
-fn resolve_agent_path(path: &str, chat_id: Option<&str>) -> PathBuf {
+fn resolve_agent_path(path: &str, chat_id: Option<&str>, state: Option<&AppState>) -> PathBuf {
let cleaned = normalize_duplicate_drive_prefix(path);
let p = std::path::Path::new(&cleaned);
if p.is_absolute() {
p.to_path_buf()
} else {
- agent_workspace(chat_id).join(&cleaned)
+ agent_workspace(chat_id, state).join(&cleaned)
}
}
#[cfg(test)]
mod path_tests {
use super::normalize_duplicate_drive_prefix as n;
+ use super::*;
+ use crate::state::AppState;
#[test]
fn single_drive_prefix_untouched() {
@@ -135,6 +159,102 @@ mod path_tests {
assert_eq!(n("label:value"), "label:value");
assert_eq!(n("key:val/x"), "key:val/x");
}
+
+ /// Bug 1 (Remote file_list wrong path): without an override the
+ /// agent workspace falls back to the per-chat slug under
+ /// ~/agent-workspace/.
+ #[test]
+ fn workspace_default_uses_chat_slug() {
+ let state = AppState::new();
+ let path = agent_workspace(Some("__remote__"), Some(&state));
+ let s = path.to_string_lossy().to_string();
+ // No override present → magic key is sanitised as the folder
+ // name and joined under ~/agent-workspace/.
+ assert!(s.contains("agent-workspace"), "got: {}", s);
+ assert!(s.ends_with("__remote__"), "got: {}", s);
+ }
+
+ /// Override path wins over the default workspace.
+ #[test]
+ fn workspace_override_wins() {
+ let state = AppState::new();
+ let target = std::env::temp_dir().join("lu-test-remote-workspace");
+ // Insert override under the magic remote key.
+ state
+ .chat_workspace_overrides
+ .lock()
+ .unwrap()
+ .insert("__remote__".to_string(), target.clone());
+
+ let resolved = agent_workspace(Some("__remote__"), Some(&state));
+ assert_eq!(resolved, target);
+ }
+
+ /// Cleanup: remove() restores the default behaviour.
+ #[test]
+ fn workspace_override_clear_falls_back_to_default() {
+ let state = AppState::new();
+ let target = std::env::temp_dir().join("lu-test-remote-workspace-2");
+ state
+ .chat_workspace_overrides
+ .lock()
+ .unwrap()
+ .insert("__remote__".to_string(), target.clone());
+
+ // Clear it out
+ state
+ .chat_workspace_overrides
+ .lock()
+ .unwrap()
+ .remove("__remote__");
+
+ let resolved = agent_workspace(Some("__remote__"), Some(&state));
+ let s = resolved.to_string_lossy().to_string();
+ assert!(s.contains("agent-workspace") && s.ends_with("__remote__"), "got: {}", s);
+ assert_ne!(resolved, target);
+ }
+
+ /// Resolve a relative path: should be joined onto the override folder
+ /// when one is set. This is the regression check for Bug 1: file_list
+ /// passing `path: "client/public"` while the user picked
+ /// `D:\Projects\my-site` should land in `D:\Projects\my-site\client\public`.
+ /// Path separators are normalised for comparison since PathBuf::join
+ /// keeps whatever separator it found in the input verbatim.
+ #[test]
+ fn resolve_relative_uses_override_subfolder() {
+ let state = AppState::new();
+ let target = std::env::temp_dir().join("lu-test-remote-resolve-relative");
+ state
+ .chat_workspace_overrides
+ .lock()
+ .unwrap()
+ .insert("__remote__".to_string(), target.clone());
+
+ let resolved = resolve_agent_path("client/public", Some("__remote__"), Some(&state));
+ let actual = resolved.to_string_lossy().replace('\\', "/");
+ let expected = target.join("client").join("public").to_string_lossy().replace('\\', "/");
+ assert_eq!(actual, expected);
+ }
+
+ /// Absolute paths must NOT be rewritten — the user passed a literal
+ /// drive path, we hand it back as-is.
+ #[test]
+ fn resolve_absolute_path_untouched_with_override() {
+ let state = AppState::new();
+ let target = std::env::temp_dir().join("lu-test-remote-absolute-passthrough");
+ state
+ .chat_workspace_overrides
+ .lock()
+ .unwrap()
+ .insert("__remote__".to_string(), target.clone());
+
+ // Absolute path should pass through, ignoring the override.
+ let abs = if cfg!(windows) { "C:/elsewhere/foo.txt" } else { "/tmp/elsewhere/foo.txt" };
+ let resolved = resolve_agent_path(abs, Some("__remote__"), Some(&state));
+ assert!(resolved.is_absolute());
+ let s = resolved.to_string_lossy().to_string().replace('\\', "/");
+ assert!(s.ends_with("/elsewhere/foo.txt"), "got: {}", s);
+ }
}
#[tauri::command]
@@ -156,7 +276,7 @@ pub fn execute_code(
// cwd = per-chat workspace (auto-created). Python scripts that do
// relative file I/O land in the same isolated folder as file_read /
// file_write for this chat.
- let workspace = agent_workspace(chatId.as_deref());
+ let workspace = agent_workspace(chatId.as_deref(), Some(&*state));
let _ = fs::create_dir_all(&workspace);
let mut cmd = Command::new(&state.python_bin);
@@ -217,8 +337,12 @@ pub fn execute_code(
#[tauri::command]
#[allow(non_snake_case)]
-pub fn file_read(path: String, chatId: Option<String>) -> Result<serde_json::Value, String> {
- let full_path = resolve_agent_path(&path, chatId.as_deref());
+pub fn file_read(
+ path: String,
+ chatId: Option<String>,
+ state: State<'_, AppState>,
+) -> Result<serde_json::Value, String> {
+ let full_path = resolve_agent_path(&path, chatId.as_deref(), Some(&*state));
if !full_path.exists() {
return Err(format!("File not found: {}", full_path.display()));
}
@@ -229,11 +353,59 @@ pub fn file_read(path: String, chatId: Option<String>) -> Result<serde_json::Val
#[tauri::command]
#[allow(non_snake_case)]
-pub fn file_write(path: String, content: String, chatId: Option<String>) -> Result<serde_json::Value, String> {
- let full_path = resolve_agent_path(&path, chatId.as_deref());
+pub fn file_write(
+ path: String,
+ content: String,
+ chatId: Option<String>,
+ state: State<'_, AppState>,
+) -> Result<serde_json::Value, String> {
+ let full_path = resolve_agent_path(&path, chatId.as_deref(), Some(&*state));
if let Some(parent) = full_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", e))?;
}
fs::write(&full_path, &content).map_err(|e| format!("Write error: {}", e))?;
Ok(serde_json::json!({"status": "saved", "path": full_path.to_string_lossy()}))
}
+
+/// Persist a per-chat agent workspace override. Set by the Remote
+/// dispatch flow (#29 follow-up) when the user picks a custom folder
+/// — every subsequent file_read / file_write / execute_code call
+/// from this chat resolves relative paths against that folder
+/// instead of `~/agent-workspace/<chat_id>/`. Pass `path: null` (or
+/// empty string) to clear.
+#[tauri::command]
+#[allow(non_snake_case)]
+pub fn set_chat_workspace_override(
+ chatId: String,
+ path: Option<String>,
+ state: State<'_, AppState>,
+) -> Result<(), String> {
+ let id = chatId.trim();
+ if id.is_empty() {
+ return Err("chatId cannot be empty".into());
+ }
+ let mut map = state.chat_workspace_overrides.lock().map_err(|e| e.to_string())?;
+ match path.as_ref().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) {
+ Some(p) => {
+ let pb = std::path::PathBuf::from(p);
+ // Best-effort: create the folder if missing so the first
+ // file_write doesn't fail with "no such directory".
+ let _ = std::fs::create_dir_all(&pb);
+ map.insert(id.to_string(), pb);
+ }
+ None => {
+ map.remove(id);
+ }
+ }
+ Ok(())
+}
+
+#[tauri::command]
+#[allow(non_snake_case)]
+pub fn get_chat_workspace_override(
+ chatId: String,
+ state: State<'_, AppState>,
+) -> Result<Option<String>, String> {
+ let map = state.chat_workspace_overrides.lock().map_err(|e| e.to_string())?;
+ Ok(map.get(chatId.trim()).map(|p| p.to_string_lossy().to_string()))
+}
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index d090de59..68feb3ac 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -389,6 +389,29 @@ struct AgentToolPayload {
chat_id: Option<String>,
}
+/// Pre-resolve a relative path argument the way `agent::resolve_agent_path`
+/// does — honouring the per-chat workspace override map. Absolute paths are
+/// returned unchanged. Used by remote handlers that delegate to filesystem
+/// commands (`fs_list` / `fs_search`) which take no `&AppState` and would
+/// otherwise resolve relatives against `~/agent-workspace/<chat_id>/` and
+/// completely miss the user-picked Remote dispatch folder. This is the
+/// fix for the silent-failure: file_list landed in
+/// `~/agent-workspace/__remote__/` (the magic key sanitised as the folder
+/// name) instead of e.g. `D:\Projects\my-site\` which the user selected.
+pub(crate) fn resolve_remote_path(
+ path: &str,
+ chat_id: Option<&str>,
+ state: &crate::state::AppState,
+) -> String {
+ use std::path::Path;
+ if Path::new(path).is_absolute() {
+ path.to_string()
+ } else {
+ let workspace = crate::commands::agent::agent_workspace_for(chat_id, state);
+ workspace.join(path).to_string_lossy().to_string()
+ }
+}
+
/// Run a single agent tool on behalf of an authenticated mobile client.
/// Mirrors `executeTool` in `src/api/agents.ts`. Permission-gated so a
/// remote client cannot reach into the desktop without explicit toggle:
@@ -438,19 +461,39 @@ async fn handle_agent_tool(
// Per-chat workspace slug — threaded into every file tool so each
// mobile chat gets its own isolated `~/agent-workspace/<slug>/` and
// agents running in different chats can't clobber each other.
- let chat_id = body.chat_id.clone();
+ //
+ // #29 follow-up: when the user picked a folder during Remote
+ // dispatch, the desktop set a "__remote__" workspace override. The
+ // mobile sends its own chat id here (different from the desktop's
+ // dispatched conv id), so we substitute the magic remote key when
+ // an override is present — every tool call lands in the user-
+ // chosen folder regardless of which mobile chat made the call.
+ let chat_id_raw = body.chat_id.clone();
+ let chat_id = {
+ let has_remote_override = app_state
+ .chat_workspace_overrides
+ .lock()
+ .ok()
+ .map(|m| m.contains_key("__remote__"))
+ .unwrap_or(false);
+ if has_remote_override {
+ Some("__remote__".to_string())
+ } else {
+ chat_id_raw
+ }
+ };
let result: Result<serde_json::Value, String> = match tool_name.as_str() {
"file_read" => {
let path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();
if path.is_empty() { Err("file_read needs a non-empty `path` argument.".into()) }
- else { crate::commands::agent::file_read(path, chat_id.clone()) }
+ else { crate::commands::agent::file_read(path, chat_id.clone(), app_state.clone()) }
}
"file_write" => {
let path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();
let content = body.args.get("content").and_then(|v| v.as_str()).unwrap_or("").to_string();
if path.is_empty() { Err("file_write needs a non-empty `path` argument.".into()) }
- else { crate::commands::agent::file_write(path, content, chat_id.clone()) }
+ else { crate::commands::agent::file_write(path, content, chat_id.clone(), app_state.clone()) }
}
"code_execute" => {
let code = body.args.get("code").and_then(|v| v.as_str()).unwrap_or("").to_string();
@@ -473,14 +516,21 @@ async fn handle_agent_tool(
else { crate::commands::search::web_fetch(url).await }
}
"file_list" => {
- let path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let raw_path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();
let recursive = body.args.get("recursive").and_then(|v| v.as_bool());
let pattern = body.args.get("pattern").and_then(|v| v.as_str()).map(String::from);
- if path.is_empty() { Err("file_list needs a non-empty `path` argument.".into()) }
- else { crate::commands::filesystem::fs_list(path, recursive, pattern, chat_id.clone()) }
+ if raw_path.is_empty() { Err("file_list needs a non-empty `path` argument.".into()) }
+ else {
+ // Pre-resolve so relative paths land in the user-picked
+ // Remote workspace, not in `~/agent-workspace/__remote__/`.
+ // fs_list itself doesn't see AppState — pass an absolute
+ // path so it skips its own resolver.
+ let resolved = resolve_remote_path(&raw_path, chat_id.as_deref(), &app_state);
+ crate::commands::filesystem::fs_list(resolved, recursive, pattern, None)
+ }
}
"file_search" => {
- let path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let raw_path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();
let pattern = body.args.get("query")
.or_else(|| body.args.get("pattern"))
.and_then(|v| v.as_str()).unwrap_or("").to_string();
@@ -490,20 +540,37 @@ async fn handle_agent_tool(
.or_else(|| body.args.get("max_results"))
.and_then(|v| v.as_u64())
.map(|n| n as u32);
- if path.is_empty() || pattern.is_empty() {
+ if raw_path.is_empty() || pattern.is_empty() {
Err("file_search needs both `path` and `pattern` arguments.".into())
} else {
- crate::commands::filesystem::fs_search(path, pattern, max, chat_id.clone())
+ let resolved = resolve_remote_path(&raw_path, chat_id.as_deref(), &app_state);
+ crate::commands::filesystem::fs_search(resolved, pattern, max, None)
}
}
"shell_execute" => {
let command = body.args.get("command").and_then(|v| v.as_str()).unwrap_or("").to_string();
if command.is_empty() { Err("shell_execute needs a non-empty `command` argument.".into()) }
else {
- let cwd = body.args.get("cwd").and_then(|v| v.as_str()).map(String::from);
+ // Default cwd → the per-chat workspace folder so `npm install`
+ // / `git status` / etc. land in the same directory the agent
+ // is writing files to. Without this, shells default to the
+ // app's launch directory and every relative command fails
+ // with "no such file" while the model thinks it succeeded.
+ let cwd_raw = body.args.get("cwd").and_then(|v| v.as_str()).map(String::from);
+ let cwd = match cwd_raw {
+ Some(c) if !c.trim().is_empty() => Some(resolve_remote_path(&c, chat_id.as_deref(), &app_state)),
+ _ => Some(crate::commands::agent::agent_workspace_for(chat_id.as_deref(), &app_state)
+ .to_string_lossy()
+ .to_string()),
+ };
+ // Best-effort: ensure the cwd exists before the shell command
+ // runs. Saves the model an extra "Error: directory not found"
+ // round-trip for the very first shell call in a new chat.
+ if let Some(ref dir) = cwd {
+ let _ = std::fs::create_dir_all(dir);
+ }
let timeout = body.args.get("timeout").and_then(|v| v.as_u64());
let shell = body.args.get("shell").and_then(|v| v.as_str()).map(String::from);
- let _ = &chat_id; // chat-scoped shell cwd not yet implemented
crate::commands::shell::shell_execute(command, None, cwd, timeout, shell).await
}
}
@@ -1106,6 +1173,11 @@ button{-webkit-appearance:none;appearance:none}
.copy-btn:active{opacity:1}
.copy-btn .material-symbols-outlined{font-size:14px}
.msg-typing::after{content:'';display:inline-block;width:2px;height:14px;background:var(--primary);margin-left:2px;animation:cursor-blink 0.7s infinite}
+.typing-dots{display:flex;gap:5px;padding:8px 12px;align-items:center}
+.typing-dots span{width:6px;height:6px;border-radius:50%;background:var(--text-tertiary);opacity:0.4;animation:typing-pulse 1.2s ease-in-out infinite}
+.typing-dots span:nth-child(2){animation-delay:0.2s}
+.typing-dots span:nth-child(3){animation-delay:0.4s}
+@keyframes typing-pulse{0%,80%,100%{opacity:0.3;transform:scale(0.85)}40%{opacity:1;transform:scale(1.15)}}
@keyframes cursor-blink{0%,100%{opacity:1}50%{opacity:0}}
/* ── Input bar (enlarged per request) ── */
@@ -1251,7 +1323,7 @@ button{-webkit-appearance:none;appearance:none}
// with live Thought/Action/Observation cards streamed into the chat.
// The old "you can't run tools" text was from v2.3.3 before the mobile
// bridge could actually execute them.
- var CODEX_PROMPT = 'You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\nAUTONOMY CONTRACT (read carefully):\n- You are expected to COMPLETE multi-step tasks without the user prompting between steps.\n- NEVER say \"Now I will create X\" or \"Next I\'ll write Y\" as plain text and then stop. That is a FAILURE.\n- When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call.\n- The ONLY reasons to finish without calling another tool are: (a) the task is truly complete, or (b) you are stuck and need user input.\n\nWorkflow:\n1. Understand the task\n2. Explore (file_list, file_read, file_search)\n3. Plan changes\n4. Implement (file_write) — chain ALL writes without stopping\n5. Only THEN write a short summary of what you did\n\nRules:\n- Always read a file before modifying it\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool\n- If a command fails, diagnose and retry — don\'t hand back to the user unless truly stuck\n- Be concise in text. All the work happens in tool calls.\n- Respond in the same language the user uses.';
+ var CODEX_PROMPT = 'You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. Empty assistant messages are a FAILURE.\n\n2. DO NOT stop after the first tool. Real coding tasks take 3-15 tool calls. Stopping after one file_read or one shell_execute without producing the requested artefact = FAILURE. "I have called one tool, that is enough" is NOT a valid stop reason.\n\n3. NEVER say "Now I will create X" / "Next I\'ll write Y" as plain prose and then stop. Do the next step RIGHT NOW as a concrete tool call.\n\n4. When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call. Plan in tool-call form, not prose-then-stop.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk, OR (b) you are stuck and genuinely need user input.\n\n=== WORKFLOW ===\n\n1. Understand the task.\n2. Explore (file_list, file_read, file_search) when you need to know existing layout.\n3. Plan changes (in your head, not as a stop point).\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_execute / code_execute / file_read).\n6. Only THEN write a short summary of what you did.\n\n=== FILE & DIRECTORY RULES ===\n\n- file_write AUTOMATICALLY creates any missing parent directories. Never call shell_execute with `mkdir`, `New-Item -ItemType Directory`, `md`, or `os.makedirs` to set up a folder before writing — just file_write the target path directly.\n- All relative paths resolve to the current chat workspace folder. Always pass relative paths (e.g. `client/public/index.html`) — do not hard-code absolute drive paths.\n- shell_execute runs inside the workspace folder by default. Do not `cd` into a parent or sibling folder; prefer relative commands.\n- On Windows, the shell is PowerShell. Quote arguments with spaces. Use forward slashes in paths inside commands. Avoid `mkdir -p` (PowerShell mkdir does not accept -p) — again, just use file_write.\n\n=== GENERAL ===\n\n- Always read a file before modifying it.\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool.\n- If a command fails, diagnose and retry with corrected arguments — do not introduce yourself again.\n- After 2-3 failures of the same approach, switch strategy (e.g. file_write instead of shell mkdir) instead of repeating.\n- Be concise in text. All real work happens in tool calls.\n- Respond in the same language the user used in their message.';
// ── Thinking-compatible prefixes (parity with desktop) ──
var THINKING_COMPATIBLE = ['qwq','deepseek-r1','qwen3.6','qwen3','qwen3.5','qwen3-coder','gemma3','gemma4'];
@@ -1399,6 +1471,114 @@ button{-webkit-appearance:none;appearance:none}
var CODEX_TOOLS = ['file_read','file_write','file_list','file_search','shell_execute','code_execute','system_info','get_current_time','web_search','web_fetch'];
var AGENT_ALL_TOOLS = AGENT_TOOLS.map(function(t){return t.name;});
+ // ── Mobile parity helpers (Codex audit fixes) ──────────────────────
+ // Three helpers ported from desktop's tool-call-repair lib + Codex
+ // streaming pipeline. Without these, the mobile agent loop drifts in
+ // ways the desktop never does:
+ // (1) Ollama sometimes emits tool_call.arguments as a JSON STRING
+ // instead of an object; mobile passed it through unchanged →
+ // the Rust `agent-tool` endpoint saw `args = "{...}"` and the
+ // file_write handler reported "needs argument".
+ // (2) Some models (qwen2.5-coder, gemma after a few iterations)
+ // emit tool calls as a fenced ```json {"name":...} ``` block
+ // inside `content` instead of native `tool_calls`. Without an
+ // extractor mobile saw zero tool calls and wrote the JSON to
+ // the chat as if it were the final answer.
+ // (3) `apiMessages` grew unbounded across iterations. Local models
+ // with 8K-32K windows would have their oldest messages
+ // silently truncated by Ollama, including the system prompt
+ // and the original user request — the model then "forgot the
+ // task" and emitted "I'm ready to receive the task" mid-loop.
+ function repairToolCallArgs(raw){
+ if(raw == null) return {};
+ if(typeof raw === 'object') return raw;
+ if(typeof raw !== 'string') return {};
+ var trimmed = raw.trim();
+ if(!trimmed) return {};
+ try{ var parsed = JSON.parse(trimmed); return (parsed && typeof parsed === 'object') ? parsed : {}; }catch(_){}
+ // Some models double-encode the args (string of a string of JSON)
+ if(trimmed.charAt(0) === '"' && trimmed.charAt(trimmed.length-1) === '"'){
+ try{ var inner = JSON.parse(trimmed); if(typeof inner === 'string'){
+ try{ var parsed2 = JSON.parse(inner); return (parsed2 && typeof parsed2 === 'object') ? parsed2 : {}; }catch(_){}
+ }}catch(_){}
+ }
+ return {};
+ }
+
+ // Pulls fenced ```json {"name":..., "arguments":...} ``` tool calls
+ // out of the assistant's content. Returns {calls, ranges} so the
+ // caller can also strip the JSON from the visible text.
+ function extractToolCallsFromContent(content, knownToolNames){
+ var calls = [], ranges = [];
+ if(!content || typeof content !== 'string') return {calls: calls, ranges: ranges};
+ var fenceRe = /```(?:json)?\s*([\s\S]*?)```/g;
+ var match;
+ while((match = fenceRe.exec(content)) !== null){
+ var inner = match[1].trim();
+ try{
+ var obj = JSON.parse(inner);
+ var name = obj && (obj.name || obj.tool || (obj.function && obj.function.name));
+ var args = obj && (obj.arguments || obj.args || (obj.function && obj.function.arguments) || {});
+ if(name && (!knownToolNames || knownToolNames.indexOf(name) !== -1)){
+ calls.push({function:{name: name, arguments: repairToolCallArgs(args)}});
+ ranges.push({start: match.index, end: match.index + match[0].length});
+ }
+ }catch(_){}
+ }
+ return {calls: calls, ranges: ranges};
+ }
+ function stripRanges(content, ranges){
+ if(!ranges || !ranges.length) return content;
+ // Apply ranges back-to-front so earlier indexes don't shift
+ var sorted = ranges.slice().sort(function(a,b){ return b.start - a.start; });
+ var out = content;
+ for(var i=0;i<sorted.length;i++){
+ out = out.slice(0, sorted[i].start) + out.slice(sorted[i].end);
+ }
+ return out.replace(/\n{3,}/g, '\n\n').trim();
+ }
+
+ // System-prompt echo detector — Gemma 4 / smaller models drop back to
+ // "Hello, I am Codex / Agent — I am ready to assist..." after a tool
+ // error. Mirrors the desktop guard in useCodex.ts so the same line
+ // never lands in the chat over-the-air. Silent retry instead of
+ // letting the echo reach the user.
+ function isSystemPromptEcho(content){
+ if(!content) return false;
+ var head = String(content).trim().slice(0, 240);
+ if(/^(hello[!,\.]?\s+|hi[!,\.]?\s+|hey[!,\.]?\s+)?(i['’]?m|i am|you are)\s+(codex|an autonomous|the agent|an? ai)/i.test(head)) return true;
+ if(/^(i am|i['’]m)\s+ready\s+to\s+(receive|assist|help)/i.test(head)) return true;
+ if(/^(hello|hi|hey)[!,\.]?\s+i['’]?m\s+ready/i.test(head)) return true;
+ return false;
+ }
+
+ // Conservative compaction — keep system prompt + the first user message
+ // (anchors the task) + the most recent N turns. Drops only the OLDEST
+ // tool-result chains, which is the cheapest data to lose. Fires when
+ // total chars exceed budget (~24 KB by default = ~6K tokens).
+ function compactApiMessages(messages, charBudget){
+ if(!Array.isArray(messages) || messages.length < 6) return messages;
+ var budget = charBudget || 24000;
+ var total = 0;
+ for(var i=0;i<messages.length;i++) total += String(messages[i].content || '').length;
+ if(total <= budget) return messages;
+ // Always keep [0] (system) and [1] (first user) if present.
+ var head = [];
+ if(messages.length > 0 && messages[0].role === 'system') head.push(messages[0]);
+ var firstUserIdx = -1;
+ for(var j=0;j<messages.length;j++) if(messages[j].role === 'user'){ firstUserIdx = j; break; }
+ if(firstUserIdx !== -1 && messages[firstUserIdx] !== head[0]) head.push(messages[firstUserIdx]);
+ // Drop oldest tail messages until we fit.
+ var tail = messages.slice(firstUserIdx + 1);
+ while(tail.length > 4){
+ var headChars = head.reduce(function(a,m){return a + String(m.content||'').length;}, 0);
+ var tailChars = tail.reduce(function(a,m){return a + String(m.content||'').length;}, 0);
+ if(headChars + tailChars <= budget) break;
+ tail.shift();
+ }
+ return head.concat(tail);
+ }
+
// Convert the flat AGENT_TOOLS array into Ollama's native tools schema.
// `toolNames` is a whitelist — only tools whose name appears in it are
// included. Returns [{type:'function', function:{name, description,
@@ -1499,7 +1679,11 @@ button{-webkit-appearance:none;appearance:none}
for(var i=0;i<msg.tool_calls.length;i++){
var tc = msg.tool_calls[i];
if(tc && tc.function){
- toolCalls.push({function:{name:tc.function.name, arguments:tc.function.arguments || {}}});
+ // repairToolCallArgs handles the case where Ollama returns
+ // `arguments` as a JSON-stringified blob — without this the
+ // mobile agent saw `{}` and the Rust handler errored out
+ // with "file_write needs argument".
+ toolCalls.push({function:{name:tc.function.name, arguments:repairToolCallArgs(tc.function.arguments)}});
}
}
}
@@ -1694,18 +1878,42 @@ button{-webkit-appearance:none;appearance:none}
return c ? (c.mode||'lu') : 'lu';
}
+ // Aggressive AUTONOMY CONTRACT for the regular Agent toggle on mobile.
+ // Without this, gemma4 / llama3 / qwen2.5-instruct routinely emit code
+ // blocks in chat with "save this as index.html" instead of calling
+ // file_write. Codex already had its own prompt; this matches the
+ // strictness for the LU-mode + Agent-on path.
+ var AGENT_PROMPT = 'You are an autonomous AI agent inside Locally Uncensored. You execute tasks end-to-end via tools — you do NOT just describe what to do.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. There is no middle ground. Empty messages are a FAILURE.\n\n2. DO NOT stop after the FIRST tool. Real tasks take 3-10 tool calls. If the user said "build X" you write the files. If the user said "use every tool" you keep going through every tool. Stopping after one shell_execute or one get_current_time without producing a useful artefact = FAILURE.\n\n3. NEVER produce a code block followed by "save this as X". That is FAILURE — call file_write yourself.\n\n4. NEVER say "Now I will create X" / "Next I will write Y" as plain prose and stop. Do the next step right now as a concrete tool call.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk / web results returned / etc., OR (b) you are stuck in a way that genuinely needs user input. "I have called one tool, that should be enough" is NOT a valid stop reason.\n\n=== WORKFLOW ===\n\n- Build / create tasks: file_write each artefact directly, chain ALL writes, then write a 1-3 sentence final answer.\n- Read / explore tasks: file_list / file_read first, then proceed.\n- Web tasks: web_search → web_fetch on the best URL → summarize.\n- Multi-tool / "use every tool" tasks: plan the order, then call each tool one at a time, recording the partial result in a final summary file before the visible reply.\n\n=== FILE RULES ===\n\n- file_write AUTOMATICALLY creates missing parent directories — do NOT shell out to mkdir / New-Item / md / os.makedirs first. Just file_write the target path.\n- Relative paths resolve to the current chat workspace folder. Use relative paths (e.g. `index.html`, `src/app.py`); do not hard-code absolute drive letters.\n- After 2-3 failures of the same approach, switch strategy — do not repeat the same broken command. Do not introduce yourself again.\n\nBe concise in prose. All real work happens in tool calls. Respond in the same language the user used in their message.';
+
// ── System prompt builder ──
function buildSystemPrompt(){
var parts = [];
var cm = getCaveman();
if(cm!=='off' && CAVEMAN_PROMPTS[cm]) parts.push(CAVEMAN_PROMPTS[cm]);
- if(getCurrentMode()==='codex'){
+ var isCodex = getCurrentMode()==='codex';
+ var agentOn = getAgentEnabled();
+ // ── Persona / dispatched prompt come FIRST, so the autonomy
+ // contract is the LAST thing the model reads. Otherwise a persona
+ // like "Devil's Advocate" appended after AGENT_PROMPT silently
+ // overrides the tool-use rules and the model goes off-topic.
+ var pid = getPersonaId();
+ var p = PERSONAS.find(function(x){return x.id===pid;});
+ if(getPersonaEnabled() && p && p.prompt){
+ parts.push(p.prompt);
+ } else if(dispatchedSystemPrompt && !agentOn && !isCodex){
+ // Only apply the desktop-dispatched system prompt in plain chat
+ // mode. In agent / codex mode any extra prompt fights with the
+ // autonomy rules and breaks tool calling — David's "Devil's
+ // Advocate hijack" repro. The desktop side now also defaults
+ // personaEnabled to false, so dispatchedSystemPrompt should
+ // typically be empty here anyway. Defense in depth.
+ parts.push(dispatchedSystemPrompt);
+ }
+ // ── Autonomy contract LAST so HARD RULES dominate ──
+ if(isCodex){
parts.push(CODEX_PROMPT);
- }else{
- var pid = getPersonaId();
- var p = PERSONAS.find(function(x){return x.id===pid;});
- if(getPersonaEnabled() && p && p.prompt){ parts.push(p.prompt); }
- else if(dispatchedSystemPrompt){ parts.push(dispatchedSystemPrompt); }
+ } else if(agentOn){
+ parts.push(AGENT_PROMPT);
}
return parts.join('\n\n');
}
@@ -2122,6 +2330,15 @@ button{-webkit-appearance:none;appearance:none}
}
html += '</div>';
}
+ // 3-dot loading indicator — visible the whole time the model is
+ // working (plain streaming OR native tool loop), parity with the
+ // desktop TypingIndicator so users on mobile see the same "still
+ // thinking" cue across iterations instead of staring at a frozen
+ // chat. Hides as soon as `streaming` and `agentRunning` are both
+ // false (= final answer landed or agent stopped).
+ if(streaming || agentRunning){
+ html += '<div class="typing-dots"><span></span><span></span><span></span></div>';
+ }
html += '</div>';
p.innerHTML = html;
var cm = el('chat-msgs');
@@ -2814,6 +3031,23 @@ button{-webkit-appearance:none;appearance:none}
var iter = 0;
var target = msgs[msgs.length-1]; // the empty assistant slot
var tools = buildToolDefs(toolNames);
+ // Cap silent echo retries so a model fully wedged on the echo
+ // can't burn the whole iteration budget on the same drift.
+ var echoRetriesRemaining = 3;
+ // Cap consecutive tool failures. Without this a model with broken
+ // shell-syntax assumptions (e.g. `mkdir client public` on PowerShell)
+ // can burn 50 iters cycling the same error before the iter cap kicks
+ // in. Reset on every successful tool result.
+ var consecutiveErrors = 0;
+ var maxConsecutiveErrors = 5;
+ // Stop-too-early nudges. Smaller models (gemma4:e4b confirmed) often
+ // bail after 3 tool calls — their reply is non-empty ("How can I
+ // help?") so the simple empty-content guard doesn't catch it. We
+ // also push when (a) reply is empty, (b) reply asks for help, or
+ // (c) user explicitly listed many tools but few were called.
+ // Cap kept generous since a 13-tool task with gemma4 may need
+ // 4-5 nudges to walk the full list.
+ var stopRetriesRemaining = 8;
// Build the LLM message history from the conversation.
// Include system prompt + all msgs except the last empty assistant.
@@ -2857,6 +3091,13 @@ button{-webkit-appearance:none;appearance:none}
}
iter++;
+ // Compaction — keeps Ollama from silently truncating the system
+ // prompt + first user message after a few iterations of file reads
+ // (the symptom: "I'm ready to receive the task" appearing mid-loop).
+ // Conservative budget tuned to fit comfortably inside an 8K-token
+ // context with room to spare for the model's reply.
+ apiMessages = compactApiMessages(apiMessages, 24000);
+
nativeToolChat(apiMessages, tools).then(function(res){
// Remove the initial "thinking" placeholder on the first
// successful response (only matters for iter === 1).
@@ -2881,9 +3122,149 @@ button{-webkit-appearance:none;appearance:none}
target.thinking = (target.thinking ? target.thinking+'\n' : '') + turnThinking;
}
- // No tool calls → model is done, set final content
+ // Fallback content-fence extractor — qwen2.5-coder + small Gemma
+ // builds sometimes emit ```json {"name":"file_write",...} ```
+ // INSIDE content instead of native tool_calls. Pull those out so
+ // the loop continues rather than treating raw JSON as the final
+ // answer.
+ if((!res.toolCalls || res.toolCalls.length === 0) && turnContent){
+ var pulled = extractToolCallsFromContent(turnContent, toolNames);
+ if(pulled.calls.length){
+ res.toolCalls = pulled.calls;
+ turnContent = stripRanges(turnContent, pulled.ranges);
+ }
+ }
+
+ // Silent retry on system-prompt echo. Without this the user
+ // would see "Hello, I'm ready to assist…" after a tool error
+ // mid-loop. Drop the content, push a synthetic nudge and let
+ // the loop take another swing — same shape as the desktop
+ // guard in useCodex.ts. Once retries are exhausted the echo
+ // is replaced with an empty content so finishToolLoop builds
+ // a step-summary instead of leaking the literal greeting to
+ // the user (this was Bug 2 reported by David — after several
+ // failures the model ended the turn with the greeting as the
+ // final answer).
+ if(isSystemPromptEcho(turnContent)){
+ if(echoRetriesRemaining > 0){
+ echoRetriesRemaining--;
+ apiMessages.push({
+ role: 'user',
+ content: 'Continue the task. Do not introduce yourself again. Resume from the last successful step using the appropriate tool call.'
+ });
+ step();
+ return;
+ }
+ // Retries spent — drop the echo. Falls through to the
+ // "no toolCalls → finishToolLoop" path below, which builds
+ // a clean fallback summary from the agent steps.
+ turnContent = '';
+ }
+
+ // No tool calls → model is done, set final content.
+ // #29 follow-up: previously we passed `'(done)'` as the fallback
+ // when the model emitted no closing prose. That literal string
+ // bypassed finishToolLoop()'s summary builder (which only kicks
+ // in when finalAnswer is falsy), so the user saw the bubble
+ // contain just `(done)` instead of a real summary like "Task
+ // completed: 3 file(s) written.". Pass null so the summary
+ // path runs.
if(!res.toolCalls || res.toolCalls.length === 0){
- finishToolLoop(turnContent || '(done)');
+ // STOP-TOO-EARLY GUARD. Three trigger conditions, in order of
+ // confidence:
+ // (a) empty content → model gave up silently
+ // (b) "how can I help" / "what would you like" → model is
+ // asking for guidance instead of executing
+ // (c) user explicitly listed N tool names but only some
+ // fraction were called → model bailed mid-list
+ // Push a one-shot nudge up to stopRetriesRemaining times. After
+ // retries are spent, the loop accepts the model's reply as final.
+ var anySteps = (target && target.agentSteps) ? target.agentSteps.filter(function(s){return s.type==='action';}).length : 0;
+ var trimmed = (turnContent || '').trim();
+ var asksForHelp = /^(how can i help|what (do you|would you like|task)|please (let me know|tell me|provide))/i.test(trimmed);
+ // "Promised-but-no-summary" detector: model says it WILL
+ // summarize / WILL list / WILL provide… and then stops without
+ // actually doing it. Mostly Gemma 4 — the visible chat ends
+ // with the announcement and the user sees no real reply.
+ // Triggers regardless of length when the trailing sentence
+ // matches "i will provide/write/summarize…", "let me summarize",
+ // "now i will…", etc.
+ var promisesNoDelivery = /(i will (provide|write|summarize|create|make|list|finish|complete|do|show|give|tell)|i'?ll (provide|write|summarize|create|list|now)|let me summarize|let me (provide|give|list)|here is the summary:?\s*$|now i'?ll|next i'?ll)/i
+ .test(trimmed.slice(-260));
+ // Empty-summary check: trailing colon/dash with nothing after it.
+ var emptyAfterColon = /(:\s*|—\s*|-\s*)$/.test(trimmed) && trimmed.length < 400;
+ // Probe the FIRST user msg (= the original task) for explicit
+ // tool mentions. Using the LAST user msg fails after a nudge —
+ // the nudge text doesn't repeat the tool list, so mentionedTools
+ // would drop to 0 and the coverage-gap check would never fire on
+ // subsequent iterations.
+ var firstUserContent = '';
+ for(var li2 = 0; li2 < apiMessages.length; li2++){
+ if(apiMessages[li2].role === 'user'){ firstUserContent = String(apiMessages[li2].content || ''); break; }
+ }
+ var mentionedTools = 0;
+ var allKnownToolNames = (typeof AGENT_TOOLS !== 'undefined') ? AGENT_TOOLS.map(function(t){return t.name;}) : [];
+ var distinctToolsCalled = {};
+ for(var ti=0; ti<allKnownToolNames.length; ti++){
+ if(firstUserContent.indexOf(allKnownToolNames[ti]) !== -1) mentionedTools++;
+ }
+ // Also count how many DISTINCT tools were actually called.
+ if(target && target.agentSteps){
+ for(var ts=0; ts<target.agentSteps.length; ts++){
+ var s = target.agentSteps[ts];
+ if(s.type === 'action' && s.toolName) distinctToolsCalled[s.toolName] = true;
+ }
+ }
+ var distinctCalledCount = Object.keys(distinctToolsCalled).length;
+ // If the user mentioned ≥5 tools and we've called fewer DISTINCT
+ // tools than that, push. Using distinct (not total) count means
+ // calling get_current_time twice doesn't satisfy the gap check.
+ var coverageGap = mentionedTools >= 5 && distinctCalledCount < mentionedTools;
+ var shouldNudge = stopRetriesRemaining > 0 && (
+ (!trimmed && anySteps > 0) || // (a) empty content
+ (asksForHelp && anySteps < 5) || // (b) "how can I help"
+ coverageGap || // (c) user listed N tools, < N called
+ promisesNoDelivery || // (d) "I will provide a summary" then stops
+ emptyAfterColon // (e) trailing colon with nothing after
+ );
+ if(shouldNudge){
+ stopRetriesRemaining--;
+ var nudgeText;
+ if(coverageGap){
+ // List the tools that were NOT yet called by name, so the
+ // model has a concrete next-step target.
+ var missingNames = [];
+ for(var mn=0; mn<allKnownToolNames.length; mn++){
+ var name = allKnownToolNames[mn];
+ if(firstUserContent.indexOf(name) !== -1 && !distinctToolsCalled[name]){
+ missingNames.push(name);
+ }
+ }
+ nudgeText = 'You\'ve only called ' + distinctCalledCount + ' DISTINCT tools so far but the user explicitly listed ' +
+ mentionedTools + ' tools. Still missing: ' + missingNames.slice(0, 6).join(', ') + '. ' +
+ 'Call the NEXT one from that list right now as a tool call. Do NOT write a summary yet — keep going.';
+ } else if(promisesNoDelivery || emptyAfterColon){
+ // Model said "I will provide a summary" / ended on a colon
+ // and stopped. Force it to deliver the actual content NOW.
+ nudgeText = 'You announced a summary but never wrote it. The user sees nothing useful. ' +
+ 'Write the actual summary RIGHT NOW in this turn — concrete bullet list of what each tool returned, ' +
+ 'plus a 1-sentence conclusion. No more announcements, no more "I will".';
+ } else if(asksForHelp){
+ nudgeText = 'Do not ask the user "how can I help" — the task was already given. Resume executing it now ' +
+ 'with the next tool call. The user already told you exactly what to do.';
+ } else if(anySteps < 3){
+ nudgeText = 'You stopped after only ' + anySteps + ' tool call(s) and your last message was empty. ' +
+ 'The task is not finished. Call the NEXT tool to continue. Do not stop yet.';
+ } else {
+ nudgeText = 'You completed ' + anySteps + ' tool calls but your last message was empty — the user sees nothing. ' +
+ 'Write the final user-facing summary right now: 1-3 sentences listing what you did and any concrete results. ' +
+ 'Do not introduce yourself again.';
+ }
+ apiMessages.push({ role: 'user', content: nudgeText });
+ step();
+ return;
+ }
+ finishToolLoop(turnContent || null);
return;
}
@@ -2934,6 +3315,24 @@ button{-webkit-appearance:none;appearance:none}
// Push tool result into the LLM history
apiMessages.push({role:'tool', content:obs});
+ // runAgentTool resolves on graceful 200+{error} too — we have
+ // to inspect the observation text to know whether the tool
+ // really succeeded. If it didn't, bump the consecutive-error
+ // counter; on success, reset.
+ if(/^(Error|Permission denied|Network error)/i.test(obs)){
+ consecutiveErrors++;
+ } else {
+ consecutiveErrors = 0;
+ }
+
+ if(consecutiveErrors >= maxConsecutiveErrors){
+ appendAgentStep('error',
+ kindLabel + ' stopped: ' + consecutiveErrors +
+ ' consecutive tool errors. Try rephrasing the task or fixing the tool arguments.');
+ finishToolLoop(null);
+ return;
+ }
+
tcIndex++;
execNext();
}).catch(function(e){
@@ -2946,6 +3345,15 @@ button{-webkit-appearance:none;appearance:none}
// Push error as tool result so the model can adapt
apiMessages.push({role:'tool', content:'Error: '+errMsg});
+ consecutiveErrors++;
+ if(consecutiveErrors >= maxConsecutiveErrors){
+ appendAgentStep('error',
+ kindLabel + ' stopped: ' + consecutiveErrors +
+ ' consecutive tool errors. Try rephrasing the task or fixing the tool arguments.');
+ finishToolLoop(null);
+ return;
+ }
+
tcIndex++;
execNext();
});
@@ -3797,7 +4205,18 @@ pub async fn start_tunnel(
}
if url.is_empty() {
- Ok("Tunnel started but URL not yet available. Check logs.".to_string())
+ // #29: previously we returned `Ok("Tunnel started but URL not yet
+ // available...")` here, which the frontend stored as `tunnelUrl`
+ // and then happily appended `/mobile` to — pointing the QR at a
+ // sentence instead of a URL. Return Err so `startTunnel()` in the
+ // store keeps `tunnelActive=false`, the QR falls back to the LAN
+ // URL, and the user sees a real reason in the error chip.
+ Err(format!(
+ "Cloudflare tunnel started but no public URL appeared within 15 s (cloudflared PID {}). \
+ This usually means cloudflared can't reach Cloudflare's edge — check firewall / VPN, \
+ then click Restart. LAN dispatch still works in the meantime.",
+ pid
+ ))
} else {
Ok(url)
}
@@ -3918,3 +4337,68 @@ async fn mobile_monogram() -> Response {
.body(Body::from(MONOGRAM))
.unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
}
+
+#[cfg(test)]
+mod remote_path_tests {
+ use super::resolve_remote_path;
+ use crate::state::AppState;
+
+ /// Bug 1 regression — without the override the relative path from a
+ /// mobile `file_list` falls back to ~/agent-workspace/__remote__/ and
+ /// the user's actual project folder is never touched.
+ #[test]
+ fn relative_without_override_uses_default_workspace() {
+ let state = AppState::new();
+ let resolved = resolve_remote_path("client/public", Some("__remote__"), &state);
+ let s = resolved.replace('\\', "/");
+ assert!(s.contains("agent-workspace/__remote__/client/public"), "got: {}", s);
+ }
+
+ /// Override set → relative paths land inside it.
+ /// Path separators are normalised — PathBuf::join keeps the input
+ /// separator verbatim, so on Windows `target.join("client/public")`
+ /// still contains the forward slash.
+ #[test]
+ fn relative_with_override_lands_in_override_folder() {
+ let state = AppState::new();
+ let target = std::env::temp_dir().join("lu-rrp-test-rel");
+ state
+ .chat_workspace_overrides
+ .lock()
+ .unwrap()
+ .insert("__remote__".to_string(), target.clone());
+
+ let resolved = resolve_remote_path("client/public/index.html", Some("__remote__"), &state);
+ let actual = resolved.replace('\\', "/");
+ let expected = target
+ .join("client")
+ .join("public")
+ .join("index.html")
+ .to_string_lossy()
+ .replace('\\', "/");
+ assert_eq!(actual, expected);
+ }
+
+ /// Absolute paths must pass through untouched even when an override is set.
+ #[test]
+ fn absolute_path_passes_through_with_override() {
+ let state = AppState::new();
+ let target = std::env::temp_dir().join("lu-rrp-test-abs");
+ state
+ .chat_workspace_overrides
+ .lock()
+ .unwrap()
+ .insert("__remote__".to_string(), target);
+
+ let abs = if cfg!(windows) { "C:/elsewhere/foo.txt" } else { "/etc/passwd" };
+ let resolved = resolve_remote_path(abs, Some("__remote__"), &state);
+ let s = resolved.replace('\\', "/");
+ // We ignore drive vs unix specifics — just assert we kept the
+ // input absolute form rather than nesting it under the override.
+ if cfg!(windows) {
+ assert!(s.ends_with("/elsewhere/foo.txt"), "got: {}", s);
+ } else {
+ assert!(s.ends_with("/etc/passwd"), "got: {}", s);
+ }
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index b201faf3..aa3adcbb 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -53,6 +53,8 @@ fn main() {
commands::agent::execute_code,
commands::agent::file_read,
commands::agent::file_write,
+ commands::agent::set_chat_workspace_override,
+ commands::agent::get_chat_workspace_override,
// Shell
commands::shell::shell_execute,
// Filesystem
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 42816744..599aba59 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -146,6 +146,12 @@ pub struct AppState {
pub claude_code_install: Arc<Mutex<InstallState>>,
// Remote Access
pub remote: Mutex<RemoteServer>,
+ /// Per-chat workspace overrides — when present, agent file ops with
+ /// a relative path resolve against this folder instead of the
+ /// default `~/agent-workspace/<chat_id>/`. Set when the user picks
+ /// a folder during Remote dispatch (#29 follow-up); cleared on
+ /// undispatch / chat delete.
+ pub chat_workspace_overrides: Arc<Mutex<HashMap<String, std::path::PathBuf>>>,
}
impl AppState {
@@ -193,6 +199,7 @@ impl AppState {
claude_code_install: Arc::new(Mutex::new(InstallState::default())),
// Remote Access
remote: Mutex::new(RemoteServer::new()),
+ chat_workspace_overrides: Arc::new(Mutex::new(HashMap::new())),
}
}
}
diff --git a/src/api/__tests__/agent-context.test.ts b/src/api/__tests__/agent-context.test.ts
new file mode 100644
index 00000000..67f23e5d
--- /dev/null
+++ b/src/api/__tests__/agent-context.test.ts
@@ -0,0 +1,101 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import {
+ setActiveChatId,
+ getActiveChatId,
+ clearActiveChatId,
+ chatWorkspaceSlug,
+} from '../agent-context'
+
+describe('agent-context › setActiveChatId / getActiveChatId', () => {
+ beforeEach(() => clearActiveChatId())
+
+ it('starts unset', () => {
+ expect(getActiveChatId()).toBeNull()
+ })
+
+ it('round-trips a string id', () => {
+ setActiveChatId('foo-123')
+ expect(getActiveChatId()).toBe('foo-123')
+ })
+
+ it('clears via clearActiveChatId()', () => {
+ setActiveChatId('foo')
+ clearActiveChatId()
+ expect(getActiveChatId()).toBeNull()
+ })
+
+ it('null/undefined clears the id', () => {
+ setActiveChatId('foo')
+ setActiveChatId(null)
+ expect(getActiveChatId()).toBeNull()
+ setActiveChatId('foo')
+ setActiveChatId(undefined)
+ expect(getActiveChatId()).toBeNull()
+ })
+
+ it('coerces non-string-like inputs to string', () => {
+ setActiveChatId(42 as unknown as string)
+ expect(getActiveChatId()).toBe('42')
+ })
+})
+
+describe('agent-context › chatWorkspaceSlug', () => {
+ // Per user feedback: workspace folders used to be raw UUIDs and the
+ // user couldn't tell which chat owned which folder. Slug must be
+ // recognisable in Explorer.
+
+ it('uses kebab-case title with id suffix', () => {
+ expect(chatWorkspaceSlug('8f7c2a1b-1234', 'Build me a random website')).toBe(
+ 'build-me-a-random-website-8f7c2a'
+ )
+ })
+
+ it('falls back to id-only when title is empty', () => {
+ expect(chatWorkspaceSlug('8f7c2a1b-1234', '')).toBe('8f7c2a')
+ expect(chatWorkspaceSlug('8f7c2a1b-1234', null)).toBe('8f7c2a')
+ expect(chatWorkspaceSlug('8f7c2a1b-1234', undefined)).toBe('8f7c2a')
+ })
+
+ it('falls back to id-only when title has no usable chars', () => {
+ expect(chatWorkspaceSlug('abcdef-1234', '###***!!!')).toBe('abcdef')
+ })
+
+ it('returns "noid" suffix when id is empty', () => {
+ expect(chatWorkspaceSlug('', 'Hello world')).toBe('hello-world-noid')
+ })
+
+ it('caps long titles at 40 chars', () => {
+ const longTitle = 'a'.repeat(80)
+ const slug = chatWorkspaceSlug('abcdef-1234', longTitle)
+ // 40 chars of body + "-" + 6-char id
+ expect(slug.length).toBeLessThanOrEqual(40 + 1 + 6)
+ expect(slug.endsWith('-abcdef')).toBe(true)
+ })
+
+ it('strips non-alphanumeric runs and merges to single hyphen', () => {
+ expect(chatWorkspaceSlug('xx-yy', 'Foo: Bar / Baz!! Qux')).toBe(
+ 'foo-bar-baz-qux-xxyy'
+ )
+ })
+
+ it('lowercases mixed-case titles', () => {
+ expect(chatWorkspaceSlug('aabbcc', 'My COOL Project')).toBe(
+ 'my-cool-project-aabbcc'
+ )
+ })
+
+ it('handles unicode by stripping it (ascii-only slug)', () => {
+ expect(chatWorkspaceSlug('xy12ab', 'Café résumé 漢字')).toBe('caf-r-sum-xy12ab')
+ })
+
+ it('trims leading/trailing hyphens from the slug body', () => {
+ expect(chatWorkspaceSlug('xyz123', '!!!hello!!!')).toBe('hello-xyz123')
+ })
+
+ it('id suffix is always exactly 6 chars or "noid"', () => {
+ // Long id is truncated, dashes stripped before slicing
+ expect(chatWorkspaceSlug('aaaa-bbbb-cccc-dddd-eeee', 'x')).toBe('x-aaaabb')
+ // Empty id → "noid"
+ expect(chatWorkspaceSlug('', 'x')).toBe('x-noid')
+ })
+})
diff --git a/src/api/agent-context.ts b/src/api/agent-context.ts
index 43c32484..2eddbd27 100644
--- a/src/api/agent-context.ts
+++ b/src/api/agent-context.ts
@@ -32,3 +32,32 @@ export function getActiveChatId(): string | null {
export function clearActiveChatId(): void {
activeChatId = null
}
+
+/**
+ * Build a human-readable workspace slug for a chat.
+ *
+ * Folders used to be named after the conversation UUID
+ * (`~/agent-workspace/8f7c2a1b-…/`), which is technically unique but
+ * useless to a human opening Explorer. Per user feedback, slug is now
+ * `<title-kebabbed>-<6-char-id>` so the user can find their work.
+ *
+ * The 6-char id suffix keeps two chats with the same title from
+ * colliding (e.g. two "Untitled" chats started in a row).
+ *
+ * Sanitisation: lowercase, ASCII alphanumerics + hyphen only, capped
+ * at 40 chars. Empty / unprintable titles fall back to the UUID
+ * suffix alone, which still gives a stable folder name. The Rust side
+ * has its own paranoia layer (agent.rs::agent_workspace) so this is
+ * defence in depth.
+ */
+export function chatWorkspaceSlug(id: string, title?: string | null): string {
+ const idPart = (id || '').replace(/-/g, '').slice(0, 6) || 'noid'
+ const rawTitle = (title || '').toLowerCase().trim()
+ if (!rawTitle) return idPart
+ const slug = rawTitle
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 40)
+ .replace(/-+$/g, '')
+ return slug ? `${slug}-${idPart}` : idPart
+}
diff --git a/src/components/chat/ApprovalDialog.tsx b/src/components/chat/ApprovalDialog.tsx
index 4c24a363..6fa0c41c 100644
--- a/src/components/chat/ApprovalDialog.tsx
+++ b/src/components/chat/ApprovalDialog.tsx
@@ -1,8 +1,7 @@
import { motion, AnimatePresence } from 'framer-motion'
-import { ShieldAlert, Check, X } from 'lucide-react'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
+import { ChevronDown } from 'lucide-react'
import type { AgentToolCall } from '../../types/agent-mode'
-import { ToolCallBlock } from './ToolCallBlock'
interface Props {
toolCall: AgentToolCall
@@ -11,13 +10,22 @@ interface Props {
}
/**
- * Agent tool-call approval prompt. Before v2.4 this was a small inline
- * strip above the ChatInput and users missed it. It's now a centred modal
- * with a dimmed backdrop so the approval gate is impossible to overlook.
+ * Inline tool-call approval strip rendered directly above the ChatInput.
*
- * Keyboard shortcuts: Enter → approve, Escape → reject.
+ * History: this used to be a centred modal with a colour-coded amber/green/red
+ * palette and a dimmed backdrop. Per user feedback ("ohne Farben, kleiner,
+ * sauberer, professioneller. eventuell in den chat einarbeiten") it is now a
+ * compact monochrome row that sits inline in the chat instead of pulling
+ * focus into a modal — readable at a glance, dismissible without breaking
+ * flow.
+ *
+ * Keyboard shortcuts: Enter → approve, Escape → reject. Args expand inline
+ * via the chevron button if the user wants to inspect what the agent is
+ * about to run.
*/
export function ApprovalDialog({ toolCall, onApprove, onReject }: Props) {
+ const [argsOpen, setArgsOpen] = useState(false)
+
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
@@ -33,58 +41,67 @@ export function ApprovalDialog({ toolCall, onApprove, onReject }: Props) {
}, [onApprove, onReject])
return (
- <AnimatePresence>
+ <AnimatePresence mode="wait">
<motion.div
- key="backdrop"
- className="fixed inset-0 z-[200] bg-black/50 backdrop-blur-sm flex items-center justify-center p-6"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.15 }}
- onClick={onReject}
+ key={toolCall.id}
+ initial={{ opacity: 0, y: 4 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: 4 }}
+ transition={{ duration: 0.12 }}
+ className="mb-1.5 rounded-md border border-gray-200 dark:border-white/[0.08] bg-gray-50 dark:bg-white/[0.025] overflow-hidden"
>
- <motion.div
- key="dialog"
- className="w-full max-w-[480px] rounded-xl bg-white dark:bg-[#1a1a1a] border border-amber-500/30 shadow-2xl overflow-hidden"
- initial={{ opacity: 0, scale: 0.95, y: 10 }}
- animate={{ opacity: 1, scale: 1, y: 0 }}
- exit={{ opacity: 0, scale: 0.95, y: 10 }}
- transition={{ duration: 0.18, ease: 'easeOut' }}
- onClick={(e) => e.stopPropagation()}
- >
- {/* Header */}
- <div className="flex items-center gap-2 px-4 py-2.5 bg-amber-500/10 border-b border-amber-500/20">
- <ShieldAlert size={14} className="text-amber-400" />
- <span className="text-[0.75rem] text-amber-400 font-semibold">
- Tool approval required
- </span>
- <span className="ml-auto text-[0.5rem] text-amber-400/50 font-mono">
- Enter ✓ · Esc ✕
- </span>
- </div>
-
- {/* Tool details */}
- <div className="px-4 py-3">
- <ToolCallBlock toolCall={toolCall} />
- </div>
-
- {/* Prominent action row */}
- <div className="flex items-center gap-2 px-4 pb-3">
+ <div className="flex items-center gap-2 px-2.5 py-1.5">
+ <span className="text-[0.55rem] uppercase tracking-wider text-gray-500 dark:text-gray-500 font-medium">
+ Approve
+ </span>
+ <code className="text-[0.65rem] text-gray-700 dark:text-gray-300 font-medium truncate flex-1 min-w-0">
+ {toolCall.toolName}
+ </code>
+ <button
+ onClick={() => setArgsOpen((v) => !v)}
+ title={argsOpen ? 'Hide arguments' : 'Show arguments'}
+ className="shrink-0 p-0.5 rounded text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-black/5 dark:hover:bg-white/5 transition-colors"
+ >
+ <ChevronDown
+ size={11}
+ className={'transition-transform ' + (argsOpen ? 'rotate-180' : '')}
+ />
+ </button>
+ <div className="shrink-0 flex items-center gap-1 ml-1">
<button
- onClick={onApprove}
- autoFocus
- className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md bg-green-500/15 border border-green-500/40 text-green-400 hover:bg-green-500/25 hover:border-green-500/60 transition-all text-[0.7rem] font-medium"
+ onClick={onReject}
+ className="px-2 py-0.5 rounded text-[0.6rem] text-gray-600 dark:text-gray-400 hover:bg-black/5 dark:hover:bg-white/5 border border-gray-200 dark:border-white/10 transition-colors"
>
- <Check size={12} /> Approve
+ Reject
</button>
<button
- onClick={onReject}
- className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md bg-red-500/10 border border-red-500/30 text-red-400 hover:bg-red-500/20 hover:border-red-500/50 transition-all text-[0.7rem] font-medium"
+ onClick={onApprove}
+ autoFocus
+ className="px-2 py-0.5 rounded text-[0.6rem] text-gray-800 dark:text-gray-100 bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 border border-gray-300 dark:border-white/15 transition-colors font-medium"
>
- <X size={12} /> Reject
+ Approve
</button>
</div>
- </motion.div>
+ <span className="hidden sm:inline shrink-0 text-[0.5rem] text-gray-400 dark:text-gray-600 font-mono ml-1">
+ ⏎ / Esc
+ </span>
+ </div>
+
+ <AnimatePresence>
+ {argsOpen && (
+ <motion.div
+ initial={{ height: 0, opacity: 0 }}
+ animate={{ height: 'auto', opacity: 1 }}
+ exit={{ height: 0, opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ className="overflow-hidden border-t border-gray-200 dark:border-white/[0.06]"
+ >
+ <pre className="text-[0.55rem] leading-relaxed text-gray-600 dark:text-gray-400 px-2.5 py-1.5 max-h-[180px] overflow-auto scrollbar-thin whitespace-pre-wrap break-words">
+ {JSON.stringify(toolCall.args, null, 2)}
+ </pre>
+ </motion.div>
+ )}
+ </AnimatePresence>
</motion.div>
</AnimatePresence>
)
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 413dfbb2..3fd82f52 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -2,7 +2,6 @@ import { useState, useRef, useEffect, useCallback } from 'react'
import { motion } from 'framer-motion'
import { Send, Square, Paperclip, X, Brain } from 'lucide-react'
import { VoiceButton } from './VoiceButton'
-import { ApprovalDialog } from './ApprovalDialog'
import { useVoiceStore } from '../../stores/voiceStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useModelStore } from '../../stores/modelStore'
@@ -116,10 +115,11 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp
return (
<div className="px-3 pb-2 pt-1">
- {/* Approval dialog */}
- {pendingApproval && onApprove && onReject && (
- <ApprovalDialog toolCall={pendingApproval} onApprove={onApprove} onReject={onReject} />
- )}
+ {/* Approval used to live here as a popup over the chat input.
+ Per user feedback ("eventuell in den chat einarbeiten") it now
+ renders INSIDE the pending tool-call block in MessageList, so
+ the approve/reject buttons sit visually attached to the tool
+ they belong to. ChatView owns the Enter/Esc keyboard layer. */}
<div
className={`flex flex-col rounded-lg border px-2.5 py-2 transition-colors ${
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index 80d5a85d..2205a598 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -13,7 +13,7 @@ import { ErrorBoundary } from '../ui/ErrorBoundary'
import { useSettingsStore } from '../../stores/settingsStore'
import { FEATURE_FLAGS } from '../../lib/constants'
import { isAgentCompatible, isThinkingCompatible } from '../../lib/model-compatibility'
-import { FileText, Bot, ChevronDown, Download, Brain, Wrench, Radio, RefreshCw } from 'lucide-react'
+import { FileText, Bot, ChevronDown, Download, Brain, Wrench, Radio, RefreshCw, X } from 'lucide-react'
import { PluginsDropdown } from './PluginsDropdown'
import { TokenCounter } from './TokenCounter'
import { MemoryDebugToggle } from './MemoryDebugPanel'
@@ -58,8 +58,10 @@ export function ChatView() {
// Remote conversation whose server has been stopped.
const remoteEnabled = useRemoteStore((s) => s.enabled)
const remoteLoading = useRemoteStore((s) => s.loading)
+ const remoteError = useRemoteStore((s) => s.error)
const dispatchedConversationId = useRemoteStore((s) => s.dispatchedConversationId)
const remoteRestart = useRemoteStore((s) => s.restart)
+ const remoteClearError = useRemoteStore((s) => s.clearError)
const connectedDevices = useRemoteStore((s) => s.connectedDevices)
const refreshDevices = useRemoteStore((s) => s.refreshDevices)
const activeConv = conversations.find((c) => c.id === activeConversationId)
@@ -86,10 +88,41 @@ export function ChatView() {
return () => clearTimeout(t)
}, [exportToast])
+ // Approval keyboard shortcuts — Enter approves, Esc rejects the
+ // head-of-queue tool call. The buttons themselves now live inside
+ // ToolCallBlock so they appear inline on the pending block, but the
+ // keyboard layer stays here so the shortcuts work regardless of
+ // scroll position.
+ useEffect(() => {
+ if (!pendingApproval || !approveToolCall || !rejectToolCall) return
+ const handler = (e: KeyboardEvent) => {
+ const target = e.target as HTMLElement | null
+ const tag = target?.tagName
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || target?.isContentEditable) return
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault()
+ approveToolCall()
+ } else if (e.key === 'Escape') {
+ e.preventDefault()
+ rejectToolCall()
+ }
+ }
+ window.addEventListener('keydown', handler)
+ return () => window.removeEventListener('keydown', handler)
+ }, [pendingApproval, approveToolCall, rejectToolCall])
+
const handleRemoteReactivate = async () => {
if (!activeConv || !activeConversationId) return
- await remoteRestart(activeConv.model, activeConv.systemPrompt)
- useRemoteStore.setState({ dispatchedConversationId: activeConversationId })
+ try {
+ await remoteRestart(activeConv.model, activeConv.systemPrompt)
+ useRemoteStore.setState({ dispatchedConversationId: activeConversationId })
+ } catch {
+ // #29: restart now rethrows. The store's `error` already holds the
+ // reason (e.g. "Could not bind 0.0.0.0:11435: Address already in
+ // use"). The "Server stopped" banner below renders that reason
+ // inline so the user knows what to do — instead of clicking Restart
+ // forever and watching nothing change.
+ }
}
// A/B Compare mode takes over the entire view
@@ -252,6 +285,9 @@ export function ChatView() {
isLoadingModel={isLoadingModel}
onRegenerate={regenerateMessage}
onEdit={editAndResend}
+ pendingApprovalId={pendingApproval?.id ?? null}
+ onApprove={approveToolCall}
+ onReject={rejectToolCall}
/>
<RealtimeCounter isRunning={isGenerating} />
@@ -279,21 +315,57 @@ export function ChatView() {
</div>
)}
{isThisRemoteStopped && (
- <div className="mx-3 mb-1.5 flex items-center justify-between gap-2 px-2.5 py-1 rounded border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.02] text-[0.6rem]">
- <div className="flex items-center gap-1.5 text-gray-500">
- <Radio size={10} />
- <span className="font-medium">Server stopped</span>
- <span className="text-gray-500/70">— restart to reconnect mobile</span>
+ <div
+ className={
+ 'mx-3 mb-1.5 flex items-start justify-between gap-2 px-2.5 py-1 rounded border text-[0.6rem] ' +
+ (remoteError
+ ? 'border-red-500/30 bg-red-500/5'
+ : 'border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.02]')
+ }
+ >
+ <div className={'flex flex-col gap-0.5 min-w-0 ' + (remoteError ? 'text-red-400' : 'text-gray-500')}>
+ <div className="flex items-center gap-1.5">
+ <Radio size={10} />
+ <span className="font-medium">Server stopped</span>
+ <span className={remoteError ? 'text-red-400/70' : 'text-gray-500/70'}>
+ {remoteError ? '— last attempt failed' : '— restart to reconnect mobile'}
+ </span>
+ </div>
+ {/* #29: surface the actual reason (port in use,
+ firewall, etc.) so the user knows why Restart is
+ not coming back, instead of staring at a button
+ that does nothing. */}
+ {remoteError && (
+ <div className="text-[0.55rem] text-red-300/80 break-words pl-4 leading-snug">
+ {remoteError}
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ {remoteError && (
+ <button
+ onClick={remoteClearError}
+ title="Dismiss error"
+ className="p-0.5 rounded text-red-400/70 hover:text-red-300 hover:bg-red-500/15 transition-all"
+ >
+ <X size={9} />
+ </button>
+ )}
+ <button
+ onClick={handleRemoteReactivate}
+ disabled={remoteLoading}
+ title="Start a fresh server and reattach this chat"
+ className={
+ 'flex items-center gap-1 px-2 py-0.5 rounded transition-all disabled:opacity-50 font-medium ' +
+ (remoteError
+ ? 'text-red-300 hover:bg-red-500/15 border border-red-500/40'
+ : 'text-green-400 hover:bg-green-500/15 border border-green-500/30')
+ }
+ >
+ <RefreshCw size={9} className={remoteLoading ? 'animate-spin' : ''} />
+ {remoteError ? 'Retry' : 'Restart'}
+ </button>
</div>
- <button
- onClick={handleRemoteReactivate}
- disabled={remoteLoading}
- title="Start a fresh server and reattach this chat"
- className="flex items-center gap-1 px-2 py-0.5 rounded text-green-400 hover:bg-green-500/15 border border-green-500/30 transition-all disabled:opacity-50 font-medium"
- >
- <RefreshCw size={9} className={remoteLoading ? 'animate-spin' : ''} />
- Restart
- </button>
</div>
)}
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 9f7940e7..e9399a08 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -9,6 +9,7 @@ import { TokenCounter } from './TokenCounter'
import { MemoryDebugToggle } from './MemoryDebugPanel'
import { RealtimeCounter } from './RealtimeCounter'
import { PluginsDropdown } from './PluginsDropdown'
+import { TypingIndicator } from './TypingIndicator'
import { useSettingsStore } from '../../stores/settingsStore'
import { User, Code, Brain } from 'lucide-react'
import { useEffect, useRef } from 'react'
@@ -104,13 +105,15 @@ export function CodexView() {
</div>
)}
- {/* Text content */}
+ {/* Text content — assistant drops the bubble entirely
+ to match the regular Chat view (per user feedback).
+ User keeps theirs as the right-aligned anchor. */}
{cleanContent && (
- <div className={`rounded-lg px-2.5 py-1.5 ${
+ <div className={
msg.role === 'user'
- ? 'bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'
- : 'bg-white dark:bg-white/[0.02] border border-gray-100 dark:border-white/[0.03]'
- }`}>
+ ? 'rounded-lg px-2.5 py-1.5 bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'
+ : 'px-1 py-0.5'
+ }>
<div className="text-[0.75rem] leading-relaxed">
{msg.role === 'user' ? (
<p className="text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{cleanContent}</p>
@@ -124,6 +127,13 @@ export function CodexView() {
</div>
)
})}
+ {/* 3-dot indicator while Codex is mid-loop — parity with
+ the Chat tab so users on long Gemma 4 / Codex runs
+ see "still thinking" instead of staring at a frozen
+ pane between iterations. */}
+ {isRunning && (
+ <TypingIndicator />
+ )}
</div>
)}
</div>
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index 4619cb50..0b51efe1 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -4,6 +4,7 @@ import { useState, useRef, useEffect } from 'react'
import { MarkdownRenderer } from './MarkdownRenderer'
import { ThinkingBlock } from './ThinkingBlock'
import { ToolCallBlock } from './ToolCallBlock'
+import { ReflectionBlock } from './ReflectionBlock'
import { SpeakerButton } from './SpeakerButton'
import type { Message } from '../../types/chat'
@@ -11,9 +12,15 @@ interface Props {
message: Message
onRegenerate?: () => void
onEdit?: (messageId: string, newContent: string) => void
+ /** Tool-call id awaiting user approval. When the matching block in
+ * this message has that id, ToolCallBlock renders Approve/Reject
+ * inline instead of a popup over the chat input. */
+ pendingApprovalId?: string | null
+ onApprove?: () => void
+ onReject?: () => void
}
-export function MessageBubble({ message, onRegenerate, onEdit }: Props) {
+export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject }: Props) {
const [copied, setCopied] = useState(false)
const [isEditing, setIsEditing] = useState(false)
const [editContent, setEditContent] = useState('')
@@ -76,14 +83,33 @@ export function MessageBubble({ message, onRegenerate, onEdit }: Props) {
<ThinkingBlock thinking={message.thinking} />
)}
- {/* Agent Mode: Tool call blocks */}
+ {/* Agent Mode: render tool_call + reflection blocks chronologically.
+ Reflection blocks were added for #29 follow-up — narration the
+ model emitted between tool calls used to be wiped on the next
+ iteration; now it persists as a collapsible block, in the
+ order the model produced it. */}
{!isUser && message.agentBlocks && message.agentBlocks.length > 0 && (
<>
- {message.agentBlocks
- .filter((b) => b.phase === 'tool_call' && b.toolCall)
- .map((block) => (
- <ToolCallBlock key={block.id} toolCall={block.toolCall!} />
- ))}
+ {[...message.agentBlocks]
+ .filter((b) => b.phase === 'tool_call' || b.phase === 'reflection')
+ .sort((a, b) => a.timestamp - b.timestamp)
+ .map((block) => {
+ if (block.phase === 'tool_call' && block.toolCall) {
+ const isPending = !!pendingApprovalId && block.toolCall.id === pendingApprovalId
+ return (
+ <ToolCallBlock
+ key={block.id}
+ toolCall={block.toolCall}
+ onApprove={isPending ? onApprove : undefined}
+ onReject={isPending ? onReject : undefined}
+ />
+ )
+ }
+ if (block.phase === 'reflection') {
+ return <ReflectionBlock key={block.id} content={block.content} />
+ }
+ return null
+ })}
</>
)}
@@ -107,13 +133,16 @@ export function MessageBubble({ message, onRegenerate, onEdit }: Props) {
</div>
)}
- {/* Main content */}
+ {/* Main content — assistant messages drop the bubble entirely
+ (per user feedback: "die graue Blase komplett weghaben"). User
+ messages keep theirs because they're right-aligned and need
+ the visual anchor against the chat background. */}
<div
className={
- 'rounded-lg px-2.5 py-1.5 relative ' +
+ 'relative ' +
(isUser
- ? 'bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'
- : 'bg-white dark:bg-white/[0.03] border border-gray-100 dark:border-white/[0.04]')
+ ? 'rounded-lg px-2.5 py-1.5 bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'
+ : 'px-1 py-0.5')
}
>
{isUser && isEditing ? (
diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsx
index 82bc97a7..09a6fa72 100644
--- a/src/components/chat/MessageList.tsx
+++ b/src/components/chat/MessageList.tsx
@@ -8,9 +8,14 @@ interface Props {
isLoadingModel?: boolean
onRegenerate?: (conversationId: string, assistantMessageId: string) => void
onEdit?: (conversationId: string, messageId: string, newContent: string) => void
+ /** Tool-call id awaiting user approval — when set, the matching tool
+ * block renders Approve/Reject inline (replaces the old popup). */
+ pendingApprovalId?: string | null
+ onApprove?: () => void
+ onReject?: () => void
}
-export function MessageList({ isGenerating, isLoadingModel, onRegenerate, onEdit }: Props) {
+export function MessageList({ isGenerating, isLoadingModel, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject }: Props) {
const conversation = useChatStore((s) => {
if (!s.activeConversationId) return undefined
return s.conversations.find((c) => c.id === s.activeConversationId)
@@ -35,9 +40,17 @@ export function MessageList({ isGenerating, isLoadingModel, onRegenerate, onEdit
onEdit={message.role === 'user' && onEdit && !isGenerating
? (msgId, content) => onEdit(conversation.id, msgId, content)
: undefined}
+ pendingApprovalId={pendingApprovalId}
+ onApprove={onApprove}
+ onReject={onReject}
/>
))}
- {isGenerating && lastMessage?.role === 'assistant' && lastMessage.content === '' && (
+ {/* 3-dot loading indicator stays visible the entire time the agent
+ is still working — including between tool calls and while the
+ final answer is streaming. Previously it only showed when the
+ last assistant message was empty, which made multi-turn agent
+ runs look frozen between iterations (per user feedback). */}
+ {isGenerating && lastMessage?.role === 'assistant' && (
<TypingIndicator label={isLoadingModel ? 'Loading model...' : undefined} />
)}
</div>
diff --git a/src/components/chat/PluginsDropdown.tsx b/src/components/chat/PluginsDropdown.tsx
index 82973e21..3acefd81 100644
--- a/src/components/chat/PluginsDropdown.tsx
+++ b/src/components/chat/PluginsDropdown.tsx
@@ -1,6 +1,7 @@
import { useState } from 'react'
import { Plug, ChevronDown, Bone, User } from 'lucide-react'
import { useSettingsStore } from '../../stores/settingsStore'
+import { useChatStore } from '../../stores/chatStore'
import type { CavemanMode } from '../../types/settings'
const CAVEMAN_MODES: { value: CavemanMode; label: string; desc: string }[] = [
@@ -20,8 +21,24 @@ export function PluginsDropdown() {
const cavemanMode = useSettingsStore((s) => s.settings.cavemanMode)
const updateSettings = useSettingsStore((s) => s.updateSettings)
+ // Per-chat persona enable/disable (mirrors mobile). Defaults to true
+ // for legacy chats where the flag is absent. The toggle in the
+ // dropdown flips this on the active conversation only — other chats
+ // keep their own state. Hooks (useChat, useAgentChat, useCodex) read
+ // the flag and skip the persona's systemPrompt when it's false.
+ const activeConvId = useChatStore((s) => s.activeConversationId)
+ const activeConv = useChatStore((s) =>
+ activeConvId ? s.conversations.find((c) => c.id === activeConvId) : null
+ )
+ const setConversationPersonaEnabled = useChatStore((s) => s.setConversationPersonaEnabled)
+ // Default OFF: persona only counts as "active on this chat" when the
+ // user has explicitly flipped it on via the toggle below. Undefined or
+ // missing flag → OFF. Fixes the "Devil's Advocate hijacks every new
+ // chat" bug David flagged.
+ const personaEnabledOnChat = activeConv?.personaEnabled === true
+
const isCavemanActive = cavemanMode && cavemanMode !== 'off'
- const isPersonaActive = activePersona && activePersona.id !== 'unrestricted'
+ const isPersonaActive = activePersona && activePersona.id !== 'unrestricted' && personaEnabledOnChat
const currentCaveman = CAVEMAN_MODES.find((m) => m.value === (cavemanMode || 'off'))
return (
@@ -96,21 +113,38 @@ export function PluginsDropdown() {
{/* ── Personas Dropdown ───────────────────────── */}
<div className="px-2.5">
- <button
- onClick={() => { setPersonaOpen(!personaOpen); setCavemanOpen(false) }}
- className="w-full flex items-center justify-between py-1.5 group"
- >
- <div className="flex items-center gap-1.5">
+ <div className="w-full flex items-center justify-between py-1.5 gap-2">
+ <button
+ onClick={() => { setPersonaOpen(!personaOpen); setCavemanOpen(false) }}
+ className="flex items-center gap-1.5 flex-1 min-w-0 text-left"
+ >
<User size={10} className={isPersonaActive ? 'text-green-400' : 'text-gray-400'} />
<span className="text-[0.6rem] font-medium text-gray-600 dark:text-gray-300">Persona</span>
- </div>
- <div className="flex items-center gap-1">
- <span className={`text-[0.55rem] truncate max-w-[80px] ${isPersonaActive ? 'text-green-400' : 'text-gray-500'}`}>
+ <span className={`text-[0.55rem] truncate ${isPersonaActive ? 'text-green-400' : 'text-gray-500'}`}>
{activePersona?.name || 'Unrestricted'}
</span>
<ChevronDown size={9} className={`text-gray-500 transition-transform ${personaOpen ? 'rotate-180' : ''}`} />
- </div>
- </button>
+ </button>
+ {/* On/off toggle for THIS chat — Remote already had this
+ via `personaEnabled`; now Chat / Code / Agent match. */}
+ {activeConvId && activePersona && activePersona.id !== 'unrestricted' && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation()
+ setConversationPersonaEnabled(activeConvId, !personaEnabledOnChat)
+ }}
+ title={personaEnabledOnChat ? 'Disable persona for this chat' : 'Enable persona for this chat'}
+ className={
+ 'shrink-0 flex items-center w-7 h-3.5 rounded-full transition-colors ' +
+ (personaEnabledOnChat
+ ? 'bg-green-500/40 hover:bg-green-500/55 justify-end'
+ : 'bg-gray-300/30 dark:bg-white/10 hover:bg-gray-300/45 dark:hover:bg-white/15 justify-start')
+ }
+ >
+ <span className="w-3 h-3 rounded-full bg-white shadow-sm mx-px" />
+ </button>
+ )}
+ </div>
{personaOpen && (
<div className="pb-1.5 space-y-0.5 max-h-[180px] overflow-y-auto scrollbar-thin">
diff --git a/src/components/chat/ReflectionBlock.tsx b/src/components/chat/ReflectionBlock.tsx
new file mode 100644
index 00000000..5c69e513
--- /dev/null
+++ b/src/components/chat/ReflectionBlock.tsx
@@ -0,0 +1,59 @@
+import { useState } from 'react'
+import { motion, AnimatePresence } from 'framer-motion'
+import { ChevronDown, MessageSquare } from 'lucide-react'
+import { MarkdownRenderer } from './MarkdownRenderer'
+
+interface Props {
+ content: string
+}
+
+/**
+ * Renders narration the model emitted between tool calls — the
+ * "I'll create an index, then write the file" prose that previously
+ * vanished the moment the next iteration's tool call landed (#29 follow-up).
+ *
+ * Collapsible (closed by default) so the chat doesn't get noisy on long
+ * agent runs. Expanded view is plain markdown, no bubble, no border —
+ * matches the agent-block visual language of ToolCallBlock.
+ */
+export function ReflectionBlock({ content }: Props) {
+ const [open, setOpen] = useState(false)
+ const trimmed = content.trim()
+ if (!trimmed) return null
+
+ const firstLine = trimmed.split('\n', 1)[0]
+ const preview = firstLine.length > 80 ? `${firstLine.slice(0, 80)}…` : firstLine
+
+ return (
+ <div className="mb-0.5">
+ <button
+ onClick={() => setOpen(!open)}
+ className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity w-full"
+ >
+ <MessageSquare size={10} className="text-gray-500 dark:text-gray-500 shrink-0" />
+ <span className="text-[0.65rem] text-gray-600 dark:text-gray-400">notes</span>
+ <span className="text-[0.55rem] text-gray-500 dark:text-gray-600 truncate flex-1">{preview}</span>
+ <ChevronDown
+ size={9}
+ className={'text-gray-500 transition-transform shrink-0 ' + (open ? 'rotate-180' : '')}
+ />
+ </button>
+
+ <AnimatePresence>
+ {open && (
+ <motion.div
+ initial={{ height: 0, opacity: 0 }}
+ animate={{ height: 'auto', opacity: 1 }}
+ exit={{ height: 0, opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ className="overflow-hidden"
+ >
+ <div className="pl-5 pb-1.5 pr-1 text-[0.7rem] leading-relaxed text-gray-600 dark:text-gray-400">
+ <MarkdownRenderer content={trimmed} />
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ )
+}
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index f71b4fc1..7a5c224f 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -97,21 +97,27 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
</pre>
)}
- {/* Approval buttons */}
+ {/* Approval buttons — subtle green / red as the user
+ asked for ("approve grün, reject rot, sauber, keine
+ Neonfarben"). Sits inline in the pending tool block
+ instead of a popup over the input. Enter / Esc still
+ trigger the head-of-queue approval (handled in
+ ChatView). */}
{isPending && onApprove && onReject && (
- <div className="flex items-center gap-2 pt-0.5">
+ <div className="flex items-center gap-1.5 pt-1">
<button
onClick={(e) => { e.stopPropagation(); onApprove() }}
- className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.6rem] font-medium bg-gray-100 dark:bg-white/5 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors"
+ className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.6rem] font-medium text-emerald-700 dark:text-emerald-300 bg-emerald-500/10 dark:bg-emerald-500/10 hover:bg-emerald-500/15 dark:hover:bg-emerald-500/15 border border-emerald-500/20 dark:border-emerald-500/25 transition-colors"
>
<Check size={10} /> Approve
</button>
<button
onClick={(e) => { e.stopPropagation(); onReject() }}
- className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.6rem] font-medium bg-gray-100 dark:bg-white/5 text-gray-500 dark:text-gray-500 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors"
+ className="flex items-center gap-1 px-2.5 py-1 rounded text-[0.6rem] font-medium text-red-700 dark:text-red-300 bg-red-500/10 dark:bg-red-500/10 hover:bg-red-500/15 dark:hover:bg-red-500/15 border border-red-500/20 dark:border-red-500/25 transition-colors"
>
<X size={10} /> Reject
</button>
+ <span className="ml-1 text-[0.5rem] text-gray-400 dark:text-gray-600 font-mono">⏎ / Esc</span>
</div>
)}
</div>
diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx
index 4e4a119f..d1d00206 100644
--- a/src/components/layout/Sidebar.tsx
+++ b/src/components/layout/Sidebar.tsx
@@ -7,6 +7,7 @@ import { useModelStore } from '../../stores/modelStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useCodexStore } from '../../stores/codexStore'
import { useRemoteStore } from '../../stores/remoteStore'
+import { backendCall } from '../../api/backend'
import { formatDate, truncate } from '../../lib/formatters'
import type { ChatMode } from '../../types/codex'
@@ -52,8 +53,13 @@ export function Sidebar() {
: modeConversations
const handleNewChat = () => {
- const persona = getActivePersona()
if (activeModel) {
+ // David's request: persona starts OFF on every new chat. We still
+ // store the globally-selected persona's prompt as the conv's
+ // systemPrompt (so toggling personaEnabled later "just works"
+ // without re-reading global state), but useChat / useAgentChat
+ // only apply it when personaEnabled === true.
+ const persona = getActivePersona()
createConversation(activeModel, persona?.systemPrompt || '', chatMode)
setView('chat')
}
@@ -61,11 +67,69 @@ export function Sidebar() {
const handleDispatch = async (mode: 'lan' | 'internet') => {
setDispatchPicker(false)
- const persona = getActivePersona()
if (!activeModel) return
+
+ // #29 follow-up: ask the user where the agent should write files for
+ // this remote session BEFORE starting the server. Cancel = bail, no
+ // orphan conv. Skip = keep `~/agent-workspace/<slug>/` default. The
+ // path goes into a "__remote__" workspace override on the desktop;
+ // every agent-tool call from mobile during this session resolves
+ // relative paths against it.
+ let pickedFolder: string | null = null
+ try {
+ const result = await backendCall<string | null>('pick_folder', {
+ defaultPath: undefined,
+ })
+ // pick_folder returns null if user cancelled — abort the dispatch.
+ if (result === null) return
+ pickedFolder = result
+ } catch {
+ // pick_folder is best-effort UX; if it errors (e.g. dev/browser
+ // mode without Tauri), proceed without an override.
+ pickedFolder = null
+ }
+
+ if (pickedFolder) {
+ try {
+ await backendCall('set_chat_workspace_override', {
+ chatId: '__remote__',
+ path: pickedFolder,
+ })
+ } catch {
+ // Override is a nice-to-have — fall through and dispatch anyway.
+ }
+ } else {
+ // No folder picked → ensure no stale override from a previous
+ // dispatch sticks around.
+ try {
+ await backendCall('set_chat_workspace_override', {
+ chatId: '__remote__',
+ path: null,
+ })
+ } catch { /* no-op */ }
+ }
+
+ // Remote dispatch — same default-OFF rule. The conv stores the global
+ // persona prompt for later opt-in via the toggle, but it is NOT sent
+ // to the mobile server as the dispatched system prompt. Mobile starts
+ // clean (autonomy contract or codex prompt only). Without this, a
+ // global "Devil's Advocate" persona silently hijacked every remote
+ // session through `dispatchedSystemPrompt` on the mobile side.
+ const persona = getActivePersona()
const convId = createConversation(activeModel, persona?.systemPrompt || '', 'remote')
setView('chat')
- await dispatch(convId, activeModel, persona?.systemPrompt || '')
+ try {
+ await dispatch(convId, activeModel, '')
+ } catch {
+ // #29: server failed to start (port in use, firewall, etc.). The
+ // store has the user-facing reason in `error` — drop the orphan
+ // conversation row so the user isn't stranded on a chat tied to a
+ // server that never came up. The error banner still surfaces in
+ // ChatView so the user can act on it (e.g. close another LU
+ // instance, then click Dispatch again).
+ deleteConversation(convId)
+ return
+ }
// Auto-start tunnel for internet mode
if (mode === 'internet') {
useRemoteStore.getState().startTunnel()
@@ -303,6 +367,17 @@ export function Sidebar() {
</>
)}
</div>
+ {/* DNS-propagation hint — Cloudflare *.trycloudflare.com
+ records can take 5-10 s to resolve on the mobile after
+ the URL is generated. Without this hint users see "DNS
+ not available" on first scan, panic, and click
+ Restart. The note is small + auto-disappears once a
+ device authenticates (qrVisible flips false). */}
+ {tunnelActive && tunnelUrl && (
+ <p className="text-[0.5rem] text-gray-500/70 leading-snug">
+ First connection may take 5–10 s while DNS propagates. If you see a DNS error, wait a moment and reload.
+ </p>
+ )}
{remoteError && (
<p className="text-[0.5rem] text-red-400 truncate">{remoteError}</p>
@@ -408,6 +483,25 @@ export function Sidebar() {
{/* Bottom Action */}
<div className="px-2 pb-2 pt-1 border-t border-gray-200 dark:border-white/[0.04]">
+ {/* #29: dispatch failure used to be invisible — the orphan
+ conv was deleted in handleDispatch's catch block and the
+ user was left looking at the Dispatch button as if nothing
+ happened. Surface the actual reason here so the next click
+ is informed (close other LU instance, change network,
+ etc.). Only renders when no chat is dispatched, otherwise
+ ChatView's "Server stopped" banner owns this. */}
+ {isRemoteMode && remoteError && !dispatchedConversationId && (
+ <div className="mb-1.5 px-2 py-1 rounded border border-red-500/30 bg-red-500/5 text-[0.55rem] text-red-300/90 flex items-start gap-1.5">
+ <span className="break-words flex-1 leading-snug">{remoteError}</span>
+ <button
+ onClick={() => useRemoteStore.getState().clearError()}
+ title="Dismiss"
+ className="shrink-0 p-0.5 rounded text-red-400/70 hover:text-red-300 hover:bg-red-500/15 transition-all"
+ >
+ <X size={9} />
+ </button>
+ </div>
+ )}
{isRemoteMode ? (
<AnimatePresence mode="wait">
{!dispatchPicker ? (
@@ -419,7 +513,7 @@ export function Sidebar() {
transition={{ duration: 0.1 }}
onClick={() => setDispatchPicker(true)}
disabled={remoteLoading || !activeModel}
- className="w-full flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded-md text-[0.65rem] text-gray-500 hover:text-white hover:bg-green-500/10 border border-dashed border-green-500/20 hover:border-green-500/40 transition-all disabled:opacity-40"
+ className="w-full flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded-md text-[0.65rem] text-gray-500 hover:text-white hover:bg-white/[0.04] border border-zinc-300/40 dark:border-zinc-500/40 hover:border-zinc-300/60 dark:hover:border-zinc-400/60 transition-all disabled:opacity-40"
>
<Radio size={12} />
<span>{remoteLoading ? '...' : 'Dispatch'}</span>
@@ -437,16 +531,16 @@ export function Sidebar() {
>
<button
onClick={() => handleDispatch('lan')}
- className="flex-1 flex items-center justify-center gap-1 py-1.5 rounded-md text-[0.55rem] font-medium text-gray-400 border border-dashed border-green-500/20 hover:bg-blue-500/15 hover:text-blue-400 hover:border-blue-500/30 transition-all cursor-pointer"
+ className="flex-1 flex items-center justify-center gap-1 py-1.5 rounded-md text-[0.55rem] font-medium text-gray-400 border border-zinc-300/40 dark:border-zinc-500/40 hover:bg-white/[0.05] hover:text-zinc-100 hover:border-zinc-300/60 dark:hover:border-zinc-400/60 transition-all cursor-pointer"
>
- <Wifi size={10} className="text-green-500/40" />
+ <Wifi size={10} className="text-zinc-400" />
LAN
</button>
<button
onClick={() => handleDispatch('internet')}
- className="flex-1 flex items-center justify-center gap-1 py-1.5 rounded-md text-[0.55rem] font-medium text-gray-400 border border-dashed border-green-500/20 hover:bg-emerald-500/15 hover:text-emerald-400 hover:border-emerald-500/30 transition-all cursor-pointer"
+ className="flex-1 flex items-center justify-center gap-1 py-1.5 rounded-md text-[0.55rem] font-medium text-gray-400 border border-zinc-300/40 dark:border-zinc-500/40 hover:bg-white/[0.05] hover:text-zinc-100 hover:border-zinc-300/60 dark:hover:border-zinc-400/60 transition-all cursor-pointer"
>
- <Globe size={10} className="text-green-500/40" />
+ <Globe size={10} className="text-zinc-400" />
Internet
</button>
</motion.div>
diff --git a/src/hooks/__tests__/useCodex-loop-detection.test.ts b/src/hooks/__tests__/useCodex-loop-detection.test.ts
index 661a54e4..47747aae 100644
--- a/src/hooks/__tests__/useCodex-loop-detection.test.ts
+++ b/src/hooks/__tests__/useCodex-loop-detection.test.ts
@@ -77,8 +77,16 @@ describe('useChat stop fast-path (Bug #6)', () => {
})
describe('useCodex stream reader abort fast-path (Bug #6)', () => {
+ // The streaming helper moved out of useCodex.ts into the shared
+ // ollama-stream-tools module so the regular Agent can use it too.
+ // The fast-path now lives there.
+ const streamSrc = readFileSync(
+ join(__dirname, '../../lib/ollama-stream-tools.ts'),
+ 'utf8',
+ )
+
it('cancels the reader when signal.aborted inside the NDJSON while loop', () => {
- expect(src).toMatch(/options\.signal\?\.aborted/)
- expect(src).toMatch(/reader\.cancel/)
+ expect(streamSrc).toMatch(/options\.signal\?\.aborted/)
+ expect(streamSrc).toMatch(/reader\.cancel/)
})
})
diff --git a/src/hooks/__tests__/useCodex-prompt-contract.test.ts b/src/hooks/__tests__/useCodex-prompt-contract.test.ts
index 7a038e81..e01c7eae 100644
--- a/src/hooks/__tests__/useCodex-prompt-contract.test.ts
+++ b/src/hooks/__tests__/useCodex-prompt-contract.test.ts
@@ -66,7 +66,8 @@ describe('Mobile CODEX_PROMPT (remote.rs) parity', () => {
})
it('mobile instructs completing all steps', () => {
- expect(mobileRs).toContain('COMPLETE multi-step tasks')
+ // Round 7: stronger wording — same intent, different verbatim string.
+ expect(mobileRs).toContain('execute ALL N steps in one session')
})
it('mobile defines the model as Codex', () => {
diff --git a/src/hooks/__tests__/useCodex-streaming.test.ts b/src/hooks/__tests__/useCodex-streaming.test.ts
index cd860a58..6030d511 100644
--- a/src/hooks/__tests__/useCodex-streaming.test.ts
+++ b/src/hooks/__tests__/useCodex-streaming.test.ts
@@ -211,22 +211,27 @@ describe('streamWithTools NDJSON parsing', () => {
})
// ── Drift detection ─────────────────────────────────────────────────────
+// The streaming helper used to live inline in useCodex.ts. It moved to
+// `src/lib/ollama-stream-tools.ts` so the regular Agent path
+// (useAgentChat.ts) can share the same wire protocol — these checks now
+// guard the new location instead of useCodex.ts.
describe('streamWithTools drift detection', () => {
- it('useCodex.ts still uses append-spread for tool_calls (not overwrite)', () => {
+ it('ollama-stream-tools.ts still uses append-spread for tool_calls (not overwrite)', () => {
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
- const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')
+ const src = readFileSync(join(__dirname, '../../lib/ollama-stream-tools.ts'), 'utf8')
// Must contain the spread-append pattern, not the old overwrite
- expect(src).toContain('...toolCalls, ...j.message.tool_calls.map')
+ expect(src).toContain('...toolCalls,')
+ expect(src).toContain('...j.message.tool_calls.map')
// Must NOT contain the old overwrite pattern
expect(src).not.toMatch(/toolCalls\s*=\s*j\.message\.tool_calls\.map/)
})
- it('useCodex.ts uses localFetchStream (not raw fetch)', () => {
+ it('ollama-stream-tools.ts uses localFetchStream (not raw fetch)', () => {
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
- const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')
+ const src = readFileSync(join(__dirname, '../../lib/ollama-stream-tools.ts'), 'utf8')
expect(src).toContain('localFetchStream')
// Must NOT use raw fetch() for the streaming endpoint
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 155fb751..98b54456 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1,7 +1,8 @@
import { useRef, useState, useCallback } from 'react'
import { v4 as uuid } from 'uuid'
import { chatNonStreaming } from '../api/agents'
-import { setActiveChatId, clearActiveChatId } from '../api/agent-context'
+import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug } from '../api/agent-context'
+import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'
import { useChatStore } from '../stores/chatStore'
import { agentVariantExists, createAgentVariant, getAgentModelName, canFixModel } from '../api/model-template-fix'
import { useModelStore } from '../stores/modelStore'
@@ -261,10 +262,17 @@ export function useAgentChat() {
convId = store.createConversation(activeModel, persona?.systemPrompt || '')
}
- // Publish the conversation id so built-in tools land in
- // `~/agent-workspace/<convId>/` — each LU agent chat gets an isolated
- // workspace folder. Cleared in the finally block further down.
- setActiveChatId(convId)
+ // Publish a HUMAN-READABLE slug ("create-an-index-7f2c3d") so
+ // built-in tools land in `~/agent-workspace/<slug>/`. Previously
+ // this was the raw conversation UUID — folders were technically
+ // isolated but the user couldn't tell which chat owned which
+ // workspace by looking. The slug derives from the chat title
+ // (which auto-rename gives a meaningful one after the first user
+ // message) plus a short id suffix to keep two chats with the same
+ // title from colliding.
+ const convForSlug = useChatStore.getState().conversations.find((c) => c.id === convId)
+ const slug = chatWorkspaceSlug(convId, convForSlug?.title)
+ setActiveChatId(slug)
// Add user message
const userMessage = {
@@ -292,7 +300,10 @@ export function useAgentChat() {
if (!conv) return
// RAG context injection
- let systemPrompt = conv.systemPrompt
+ // Per-chat persona toggle — default OFF. Only apply persona prompt
+ // when user explicitly flipped it on. See useChat.ts for the
+ // full rationale (Devil's Advocate hijack bug).
+ let systemPrompt = conv.personaEnabled === true ? conv.systemPrompt : ''
const ragState = useRAGStore.getState()
const ragEnabled = ragState.ragEnabled[convId] ?? false
@@ -468,24 +479,88 @@ export function useAgentChat() {
function: { name: t.name, description: t.description, parameters: t.inputSchema },
}))
- let turn: { content: string; toolCalls: ToolCall[] }
- try {
- turn = await provider.chatWithTools(modelToUse, agentMessages, tools, chatOptions)
- } catch (thinkErr: any) {
- // If thinking is rejected by model, retry WITHOUT the field at
- // all (`undefined` — old Ollama / non-thinking models reject
- // both `think: true` AND `think: false`).
- if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {
- const retryOptions = { ...chatOptions, thinking: undefined as unknown as boolean }
- turn = await provider.chatWithTools(modelToUse, agentMessages, tools, retryOptions)
- } else {
- throw thinkErr
+ let turn: { content: string; toolCalls: ToolCall[]; thinking?: string }
+ if (providerId === 'ollama') {
+ // Streaming path — parity with desktop Codex. Without this
+ // the user stared at a frozen chat for 30-90 s while Gemma
+ // thought (no tokens, no 3-dot, just dead air). Now content
+ // and thinking land in real time.
+ //
+ // The thinking-indicator block is removed the moment ANY
+ // token arrives, so the user sees the live answer instead
+ // of the placeholder once the model starts producing.
+ let thinkingBlockRemoved = false
+ const dropThinkingBlock = () => {
+ if (!thinkingBlockRemoved) {
+ thinkingBlockRemoved = true
+ removeBlock(convId!, assistantMessage.id, thinkingBlockId)
+ }
+ }
+ try {
+ turn = await streamOllamaChatWithTools(
+ modelToUse,
+ agentMessages,
+ tools,
+ {
+ temperature: chatOptions.temperature,
+ thinking: chatOptions.thinking,
+ maxTokens: chatOptions.maxTokens,
+ signal: abort.signal,
+ },
+ (c) => {
+ dropThinkingBlock()
+ // Live-update the visible content. Same accumulator
+ // pattern as Codex: each chunk is the FULL content so
+ // far, not a delta — assign directly.
+ contentRef.current = c
+ scheduleUIUpdate()
+ },
+ (t) => {
+ dropThinkingBlock()
+ if (settings.thinkingEnabled === true) {
+ thinkingRef.current = t
+ scheduleUIUpdate()
+ }
+ },
+ )
+ } catch (thinkErr: any) {
+ if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {
+ turn = await streamOllamaChatWithTools(
+ modelToUse,
+ agentMessages,
+ tools,
+ {
+ temperature: chatOptions.temperature,
+ thinking: undefined,
+ maxTokens: chatOptions.maxTokens,
+ signal: abort.signal,
+ },
+ (c) => {
+ dropThinkingBlock()
+ contentRef.current = c
+ scheduleUIUpdate()
+ },
+ () => {},
+ )
+ } else {
+ throw thinkErr
+ }
+ }
+ dropThinkingBlock()
+ } else {
+ try {
+ turn = await provider.chatWithTools(modelToUse, agentMessages, tools, chatOptions)
+ } catch (thinkErr: any) {
+ if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {
+ const retryOptions = { ...chatOptions, thinking: undefined as unknown as boolean }
+ turn = await provider.chatWithTools(modelToUse, agentMessages, tools, retryOptions)
+ } else {
+ throw thinkErr
+ }
}
+ removeBlock(convId!, assistantMessage.id, thinkingBlockId)
}
- // Remove thinking indicator
- removeBlock(convId!, assistantMessage.id, thinkingBlockId)
-
toolCalls = turn.toolCalls
turnContent = turn.content || ''
// Native thinking field from Ollama
@@ -532,14 +607,38 @@ export function useAgentChat() {
// toggle is OFF (e.g. provider returned `turn.thinking` anyway).
if (!keepThinking) turnThinking = ''
- // Update UI
- contentRef.current = turnContent
+ // Update UI — but DON'T overwrite contentRef during intermediate
+ // turns. Previously every iteration did `contentRef.current =
+ // turnContent`, which wiped any narration the model emitted
+ // before a tool call ("I'll create an index, then write the file
+ // …") the moment the next iteration produced an empty-content
+ // tool call. The user saw the message disappear, then reappear
+ // 3× as more tool calls fired, and finally a fresh final answer
+ // — losing all the intermediate context.
+ //
+ // Now: intermediate `turnContent` (with tool_calls > 0) is
+ // preserved as a `reflection` block so it renders above the tool
+ // calls in chronological order. Only the final-turn content (no
+ // tool_calls) becomes the message body.
+ const isFinalTurn = toolCalls.length === 0
+ if (isFinalTurn) {
+ contentRef.current = turnContent
+ thinkingRef.current = turnThinking
+ scheduleUIUpdate()
+ break
+ }
+
+ if (turnContent.trim()) {
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'reflection',
+ content: turnContent,
+ timestamp: Date.now(),
+ })
+ }
thinkingRef.current = turnThinking
scheduleUIUpdate()
- // If no tool calls, the model is done
- if (toolCalls.length === 0) break
-
// Phase 5b (v2.4.0) — parallel tool execution via tool-executor.
//
// Pre-create AgentToolCall + block per tc so the UI can render all
@@ -740,6 +839,35 @@ export function useAgentChat() {
thinkingRef.current = ''
}
+ // Fallback summary — parity with useCodex.ts. When the model's
+ // last turn returned empty (it claimed completion in an earlier
+ // intermediate turn, ran tools, then emitted nothing on the
+ // wrap-up), the assistant message would otherwise stay empty and
+ // leave the user looking at a chat with reflection blocks +
+ // tool-call rows but no closing line. Build a concise summary
+ // from the actually-completed blocks so there is always a final
+ // answer at the bottom of the bubble.
+ if (!contentRef.current.trim()) {
+ const blocks = blocksRef.current
+ const completedTools = blocks.filter(
+ (b) => b.phase === 'tool_call' && b.toolCall?.status === 'completed'
+ )
+ const failedTools = blocks.filter(
+ (b) => b.phase === 'tool_call' && b.toolCall?.status === 'failed'
+ )
+ const writes = completedTools.filter((b) => b.toolCall?.toolName === 'file_write').length
+ const reads = completedTools.filter((b) => b.toolCall?.toolName === 'file_read').length
+ const otherOk = completedTools.length - writes - reads
+ const parts: string[] = []
+ if (writes) parts.push(`${writes} file${writes === 1 ? '' : 's'} written`)
+ if (reads) parts.push(`${reads} file${reads === 1 ? '' : 's'} read`)
+ if (otherOk) parts.push(`${otherOk} operation${otherOk === 1 ? '' : 's'} completed`)
+ if (failedTools.length) parts.push(`${failedTools.length} failed`)
+ contentRef.current = parts.length
+ ? `Task completed: ${parts.join(', ')}.`
+ : 'Task completed.'
+ }
+
// Final store update
useChatStore.getState().updateMessageContent(convId!, assistantMessage.id, contentRef.current)
if (thinkingRef.current) {
@@ -828,7 +956,7 @@ export function useAgentChat() {
// ── Agent System Prompt Builder ─────────────────────────────────
function buildAgentSystemPrompt(basePrompt: string): string {
- const agentInstructions = `You are an autonomous AI agent inside Locally Uncensored with full access to this computer.
+ const agentInstructions = `You are an autonomous AI agent inside Locally Uncensored with full access to this computer. You execute tasks end-to-end by using tools — you do NOT just describe what to do.
Available tools:
- Filesystem: file_read, file_write, file_list, file_search
@@ -836,13 +964,25 @@ Available tools:
- System: shell_execute, code_execute, system_info, screenshot, process_list, get_current_time
- Creative: image_generate, run_workflow
-Rules:
+AUTONOMY CONTRACT (read carefully — this is the most important rule):
+- When the user asks you to BUILD, CREATE, MAKE, or WRITE something (a file, a website, a script, a folder structure), you MUST execute it via tools — typically file_write.
+- NEVER produce a code block in your reply followed by "save this as index.html". That is a FAILURE — it means you talked instead of acted.
+- NEVER say "Now I will create X" or "Next I'll write Y" as plain prose and then stop. The model is supposed to DO the next step right now, as a tool call.
+- When the task has N steps, execute ALL N as tool calls in one session. The user does not want a tutorial — they want the result on disk.
+- The ONLY reasons to finish without calling another tool are: (a) the task is genuinely complete, or (b) you are stuck and need user input.
+
+Workflow for build / create tasks:
+1. (Optional) file_list to scout the target directory.
+2. file_write the artefact(s) directly. For a website: write index.html, style.css, script.js as separate file_write calls.
+3. After the LAST file_write, write a 1–3 sentence final answer ("Done — wrote 3 files to <path>"). Nothing in between.
+
+Other rules:
- You MUST use tools — NEVER answer from memory or guess file contents.
-- For filesystem tasks: ALWAYS call file_list first to explore, then file_read to inspect, then act.
-- For web tasks: web_search → web_fetch on the best URL → answer based on real data.
-- web_search returns ONLY short snippets, NOT full content. ALWAYS call web_fetch to read the actual page.
+- For filesystem READ tasks: file_list first if needed, then file_read.
+- For web tasks: web_search → web_fetch on the best URL → answer based on real data. web_search returns ONLY short snippets — ALWAYS call web_fetch to read the page.
- If you need to know the OS, paths, or hardware: call system_info once at the start.
- Chain multiple tools as needed. If a tool fails, try a different approach.
+- Be concise in text. All the work happens in tool calls.
- Respond in the same language the user uses.`
if (basePrompt) {
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 324a656c..d01d26e8 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -73,7 +73,12 @@ export function useChat() {
if (!conv) return
// RAG context injection
- let systemPrompt = conv.systemPrompt
+ // Per-chat persona toggle (mobile-parity, mirrors mobile's
+ // `personaEnabled`). Default OFF — only when the user explicitly
+ // flipped it on via the Plugins dropdown does the persona prompt
+ // apply. Undefined / unset → suppress, so a globally selected
+ // persona never silently hijacks a new chat.
+ let systemPrompt = conv.personaEnabled === true ? conv.systemPrompt : ''
const ragState = useRAGStore.getState()
const ragEnabled = ragState.ragEnabled[convId] ?? false
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 8ffef2b0..d2926924 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -10,7 +10,7 @@ import { usePermissionStore } from '../stores/permissionStore'
import { getToolCallingStrategy } from '../lib/model-compatibility'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { chatNonStreaming } from '../api/agents'
-import { setActiveChatId, clearActiveChatId } from '../api/agent-context'
+import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug } from '../api/agent-context'
import type { CodexEvent } from '../types/codex'
import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
import { selectRelevantTools } from '../lib/tool-selection'
@@ -22,7 +22,7 @@ import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
import { budgetFromSettings } from '../api/agents/budget'
import { finalStripThinkingTags } from '../lib/thinking-stripper'
-import { ollamaUrl, localFetchStream } from '../api/backend'
+import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'
import { repairToolCallArgs, extractToolCallsFromContent, extractToolCallsWithRanges, stripRanges } from '../lib/tool-call-repair'
import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'
import { useMemoryStore } from '../stores/memoryStore'
@@ -61,142 +61,30 @@ Rules:
- If a command fails, diagnose and retry with a different approach — don't hand back to the user unless truly stuck
- Be concise in text. All the work happens in tool calls.`
-// ── Streaming tool-call helper for Ollama ──────────────────────────────
-// Replaces the non-streaming chatWithTools() so the user sees live
-// content/thinking tokens while Gemma 4 generates (2+ minutes).
-async function streamWithTools(
- modelId: string,
- messages: ChatMessage[],
- tools: ToolDefinition[],
- options: { temperature?: number; thinking?: boolean; maxTokens?: number; signal?: AbortSignal },
- onContent: (content: string) => void,
- onThinking: (thinking: string) => void,
-): Promise<{ content: string; toolCalls: ToolCall[]; thinking: string }> {
- const ollamaMessages = messages.map(m => {
- const msg: Record<string, any> = { role: m.role, content: m.content }
- if (m.tool_calls) msg.tool_calls = m.tool_calls
- if ((m as any).images?.length) msg.images = (m as any).images.map((img: any) => img.data)
- return msg
- })
-
- const body: Record<string, any> = {
- model: modelId,
- messages: ollamaMessages,
- tools,
- stream: true,
- options: { num_gpu: 99 },
- }
- if (options.temperature !== undefined) body.options.temperature = options.temperature
- if (options.maxTokens) body.options.num_predict = options.maxTokens
- if (options.thinking === true) body.think = true
- else if (options.thinking === false) body.think = false
-
- const url = ollamaUrl('/chat')
- // Use localFetchStream which tries direct fetch first, then falls back
- // to the Tauri Rust proxy (proxy_localhost_stream). Plain `fetch` fails
- // in the Tauri .exe because WebView can't reach localhost:11434 directly.
- let response: Response
- try {
- response = await localFetchStream(url, {
- method: 'POST',
- body: JSON.stringify(body),
- signal: options.signal,
- })
- } catch (fetchErr) {
- throw fetchErr
- }
-
- // Retry without think on 400 (old Ollama builds / non-thinking models)
- if (!response.ok && response.status === 400 && 'think' in body) {
- delete body.think
- response = await localFetchStream(url, {
- method: 'POST',
- body: JSON.stringify(body),
- signal: options.signal,
- })
- }
-
- if (!response.ok) {
- const text = await response.text()
- const err = new Error(`HTTP ${response.status}: ${text}`) as any
- err.statusCode = response.status
- throw err
- }
-
- const reader = response.body!.getReader()
- const decoder = new TextDecoder()
- let buf = ''
- let content = ''
- let thinking = ''
- let toolCalls: ToolCall[] = []
-
- while (true) {
- // Fast-abort: if the user hits Stop while the model is still generating
- // (especially in a long thinking phase), cancelling the fetch alone can
- // take ages to propagate. Check the signal each chunk + actively cancel
- // the reader so the loop exits immediately.
- if (options.signal?.aborted) {
- try { await reader.cancel() } catch {}
- break
- }
- const { done, value } = await reader.read()
- if (done) break
-
- buf += decoder.decode(value, { stream: true })
- const lines = buf.split('\n')
- buf = lines.pop() || ''
-
- for (const line of lines) {
- const trimmed = line.trim()
- if (!trimmed) continue
- try {
- const j = JSON.parse(trimmed)
- if (j.message) {
- if (j.message.content) {
- content += j.message.content
- onContent(content)
- }
- if (j.message.thinking) {
- thinking += j.message.thinking
- onThinking(thinking)
- }
- // Ollama may split tool_calls across chunks — append, don't overwrite
- if (j.message.tool_calls && Array.isArray(j.message.tool_calls)) {
- toolCalls = [...toolCalls, ...j.message.tool_calls.map((tc: any) => ({
- function: { name: tc.function.name, arguments: repairToolCallArgs(tc.function.arguments) },
- }))]
- }
- }
- } catch { /* partial JSON line — skip */ }
- }
- }
-
- // Process any remaining buffer
- if (buf.trim()) {
- try {
- const j = JSON.parse(buf.trim())
- if (j.message?.tool_calls && Array.isArray(j.message.tool_calls)) {
- toolCalls = [...toolCalls, ...j.message.tool_calls.map((tc: any) => ({
- function: { name: tc.function.name, arguments: repairToolCallArgs(tc.function.arguments) },
- }))]
- }
- if (j.message?.content) {
- content += j.message.content
- onContent(content)
- }
- if (j.message?.thinking) {
- thinking += j.message.thinking
- onThinking(thinking)
- }
- } catch { /* ignore */ }
- }
-
- return { content, toolCalls, thinking }
-}
+// Local alias — the helper now lives in src/lib/ollama-stream-tools.ts
+// so useAgentChat can share the same wire protocol + arg-repair layer
+// without a code duplicate. Kept under the same name to minimise diff.
+const streamWithTools = streamOllamaChatWithTools
// Coding-relevant tool categories
const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web'] as const
+// Detect when the model emits a re-introduction of itself ("Hello, I am
+// Codex, an autonomous coding agent…") instead of the actual answer.
+// Gemma 4 + smaller models do this after a tool error — they re-spawn
+// the system-prompt echo as if the conversation just started. The user
+// asked to silence these: drop the content, do not render it, do not
+// persist it to the assistant message, and let the loop retry.
+function isSystemPromptEcho(content: string): boolean {
+ if (!content) return false
+ const head = content.trim().slice(0, 240)
+ return (
+ /^(hello[!,.]?\s+|hi[!,.]?\s+|hey[!,.]?\s+)?(i['’]?m|i am|you are)\s+codex[,.]?\s+(an?\s+)?(autonomous\s+)?coding\s+agent/i.test(head) ||
+ /^codex:?\s+(an?\s+)?autonomous\s+coding\s+agent/i.test(head) ||
+ /^you are codex,/i.test(head)
+ )
+}
+
export function useCodex() {
const [isRunning, setIsRunning] = useState(false)
const abortRef = useRef<AbortController | null>(null)
@@ -217,10 +105,12 @@ export function useCodex() {
convId = store.createConversation(activeModel, persona?.systemPrompt || '', 'codex')
}
- // Per-chat agent workspace → `~/agent-workspace/<convId>/`.
- // Cleared in the finally block so standalone tool calls elsewhere
- // don't leak into this conversation's folder.
- setActiveChatId(convId)
+ // Per-chat agent workspace → `~/agent-workspace/<slug>/`.
+ // Slug uses the chat title so the folder is recognisable in
+ // Explorer; falls back to a stable id-derived suffix when the
+ // title is empty. Cleared in the finally block.
+ const convForSlug = store.conversations.find((c) => c.id === convId)
+ setActiveChatId(chatWorkspaceSlug(convId, convForSlug?.title))
// Init codex thread if needed
if (!codexStore.getThread(convId)) {
@@ -366,6 +256,12 @@ export function useCodex() {
// instead of burning budget on a no-op loop.
let prevBatchSig: string | null = null
let sameBatchRepeats = 0
+ // Echo guard — small models occasionally re-emit the system prompt
+ // ("Hello, I am Codex, an autonomous coding agent…") after a tool
+ // error. The user asked to silence those silently rather than
+ // letting them surface as the assistant's reply. Cap silent
+ // retries so we never loop forever.
+ let echoRetriesRemaining = 3
// Raised from 20 → 50 (v2.3.7): large refactors across 10+ files
// legitimately need >20 tool calls. Budget still caps via
// agentMaxToolCalls/agentMaxIterations (defaults 50/25 from settings).
@@ -447,13 +343,24 @@ export function useCodex() {
// ── Streaming path for Ollama ──────────────────────────────
// Shows live content/thinking tokens so the user isn't staring
// at an empty bubble for 2+ minutes while the model generates.
+ //
+ // Echo guard: while a turn is streaming we keep updating the
+ // visible message — but if the partial content already
+ // matches the system-prompt echo pattern we stop pushing
+ // updates so the "Hello, I am Codex…" line never lands in
+ // the chat. The post-stream echoDetected branch then drops
+ // the buffer entirely and forces a silent retry.
let turn: { content: string; toolCalls: ToolCall[]; thinking: string }
+ const liveContent = (c: string) => {
+ if (echoRetriesRemaining > 0 && isSystemPromptEcho(c)) return
+ useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + c : c)
+ }
try {
void diagLog('streamWithTools-enter', { iter: i, messagesLen: messages.length, toolsCount: tools.length, thinking: chatOptions.thinking })
turn = await streamWithTools(
modelToUse, messages, tools,
{ temperature: 0.1, thinking: chatOptions.thinking, maxTokens: chatOptions.maxTokens, signal: abort.signal },
- (c) => useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + c : c),
+ liveContent,
(t) => {
if (keepThinking) {
const combined = thinkingContent ? thinkingContent + '\n\n' + t : t
@@ -473,7 +380,7 @@ export function useCodex() {
turn = await streamWithTools(
modelToUse, messages, tools,
{ temperature: 0.1, thinking: undefined, maxTokens: chatOptions.maxTokens, signal: abort.signal },
- (c) => useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + c : c),
+ liveContent,
() => {},
)
void diagLog('streamWithTools-retry-ok', { iter: i, contentLen: turn.content?.length || 0, toolCallsCount: turn.toolCalls?.length || 0 })
@@ -594,6 +501,34 @@ export function useCodex() {
turnContent = finalStripThinkingTags(turnContent, keepThinking)
}
+ // Silent-retry on system-prompt echo — Gemma 4 sometimes
+ // restarts with "Hello, I am Codex, an autonomous coding
+ // agent…" after a tool error. Drop that content entirely
+ // (don't append, don't render) and force the loop to take
+ // another swing instead of letting the echo bubble up as
+ // the assistant's reply. Cap the silent retries so a model
+ // stuck on the echo doesn't burn the whole iteration budget.
+ const echoDetected = isSystemPromptEcho(turnContent)
+ if (echoDetected && echoRetriesRemaining > 0) {
+ echoRetriesRemaining--
+ turnContent = ''
+ // Strip the echo from the live message too if it leaked in
+ // through the streaming callback above.
+ if (fullContent) {
+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)
+ } else {
+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, '')
+ }
+ // Push a synthetic nudge so the model has a chance to
+ // recover instead of repeating the echo verbatim.
+ messages.push({
+ role: 'user',
+ content:
+ 'Continue the task. Do not introduce yourself again. Resume from the last successful step using the appropriate tool call.',
+ })
+ continue
+ }
+
if (turnContent) {
fullContent += (fullContent ? '\n\n' : '') + turnContent
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)
diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.ts
new file mode 100644
index 00000000..f9fa644a
--- /dev/null
+++ b/src/lib/ollama-stream-tools.ts
@@ -0,0 +1,160 @@
+import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
+import { ollamaUrl, localFetchStream } from '../api/backend'
+import { repairToolCallArgs } from './tool-call-repair'
+
+/**
+ * Streaming Ollama `/api/chat` call with native `tools` support.
+ *
+ * Originally lived inline in `useCodex.ts` — extracted so the regular
+ * Agent path (`useAgentChat.ts`) can share the exact same wire protocol
+ * + chunk-state-machine + arg-repair logic. Without this hook, Agent
+ * Mode used the non-streaming provider call → UI froze for 30-90 s
+ * while the model thought, no live tokens, no live tool-call hint.
+ *
+ * Behaviour notes:
+ * - Uses `localFetchStream` (Tauri-aware) so Tauri WebView can hit
+ * localhost:11434 via the Rust proxy when the direct fetch fails.
+ * - Falls back to retry-without-`think` on HTTP 400 (old Ollama
+ * builds reject the field).
+ * - `tool_calls` chunks may arrive split across multiple NDJSON
+ * lines — appends instead of overwriting.
+ * - `repairToolCallArgs` handles the case where Ollama emits the
+ * arguments object as a JSON-stringified blob instead of a real
+ * object (the bug behind "file_write needs argument" on small
+ * models).
+ */
+export async function streamOllamaChatWithTools(
+ modelId: string,
+ messages: ChatMessage[],
+ tools: ToolDefinition[],
+ options: { temperature?: number; thinking?: boolean; maxTokens?: number; signal?: AbortSignal },
+ onContent: (content: string) => void,
+ onThinking: (thinking: string) => void,
+): Promise<{ content: string; toolCalls: ToolCall[]; thinking: string }> {
+ const ollamaMessages = messages.map((m) => {
+ const msg: Record<string, any> = { role: m.role, content: m.content }
+ if (m.tool_calls) msg.tool_calls = m.tool_calls
+ if ((m as any).images?.length) msg.images = (m as any).images.map((img: any) => img.data)
+ return msg
+ })
+
+ const body: Record<string, any> = {
+ model: modelId,
+ messages: ollamaMessages,
+ tools,
+ stream: true,
+ options: { num_gpu: 99 },
+ }
+ if (options.temperature !== undefined) body.options.temperature = options.temperature
+ if (options.maxTokens) body.options.num_predict = options.maxTokens
+ if (options.thinking === true) body.think = true
+ else if (options.thinking === false) body.think = false
+
+ const url = ollamaUrl('/chat')
+ let response: Response
+ try {
+ response = await localFetchStream(url, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ signal: options.signal,
+ })
+ } catch (fetchErr) {
+ throw fetchErr
+ }
+
+ if (!response.ok && response.status === 400 && 'think' in body) {
+ delete body.think
+ response = await localFetchStream(url, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ signal: options.signal,
+ })
+ }
+
+ if (!response.ok) {
+ const text = await response.text()
+ const err = new Error(`HTTP ${response.status}: ${text}`) as any
+ err.statusCode = response.status
+ throw err
+ }
+
+ const reader = response.body!.getReader()
+ const decoder = new TextDecoder()
+ let buf = ''
+ let content = ''
+ let thinking = ''
+ let toolCalls: ToolCall[] = []
+
+ while (true) {
+ if (options.signal?.aborted) {
+ try { await reader.cancel() } catch { /* noop */ }
+ break
+ }
+ const { done, value } = await reader.read()
+ if (done) break
+
+ buf += decoder.decode(value, { stream: true })
+ const lines = buf.split('\n')
+ buf = lines.pop() || ''
+
+ for (const line of lines) {
+ const trimmed = line.trim()
+ if (!trimmed) continue
+ try {
+ const j = JSON.parse(trimmed)
+ if (j.message) {
+ if (j.message.content) {
+ content += j.message.content
+ onContent(content)
+ }
+ if (j.message.thinking) {
+ thinking += j.message.thinking
+ onThinking(thinking)
+ }
+ if (j.message.tool_calls && Array.isArray(j.message.tool_calls)) {
+ toolCalls = [
+ ...toolCalls,
+ ...j.message.tool_calls.map((tc: any) => ({
+ function: {
+ name: tc.function.name,
+ arguments: repairToolCallArgs(tc.function.arguments),
+ },
+ })),
+ ]
+ }
+ }
+ } catch {
+ // partial JSON line — skip
+ }
+ }
+ }
+
+ if (buf.trim()) {
+ try {
+ const j = JSON.parse(buf.trim())
+ if (j.message?.tool_calls && Array.isArray(j.message.tool_calls)) {
+ toolCalls = [
+ ...toolCalls,
+ ...j.message.tool_calls.map((tc: any) => ({
+ function: {
+ name: tc.function.name,
+ arguments: repairToolCallArgs(tc.function.arguments),
+ },
+ })),
+ ]
+ }
+ if (j.message?.content) {
+ content += j.message.content
+ onContent(content)
+ }
+ if (j.message?.thinking) {
+ thinking += j.message.thinking
+ onThinking(thinking)
+ }
+ } catch {
+ // ignore tail-buffer parse errors
+ }
+ }
+
+ return { content, toolCalls, thinking }
+}
diff --git a/src/stores/__tests__/remoteStore-v2.test.ts b/src/stores/__tests__/remoteStore-v2.test.ts
index f00c5bf4..d91bdacd 100644
--- a/src/stores/__tests__/remoteStore-v2.test.ts
+++ b/src/stores/__tests__/remoteStore-v2.test.ts
@@ -133,13 +133,46 @@ describe('remoteStore › dispatch()', () => {
expect(useRemoteStore.getState().error).toMatch(/boom/)
})
- it('records an error via set() on startServer failure (startServer swallows the throw)', async () => {
- // startServer catches its own error internally, so dispatch sees "success"
- // and still sets the conversationId. The error lives on the store.
+ it('records an error via set() on startServer failure', async () => {
+ // #29: startServer + dispatch now rethrow so the caller (Sidebar)
+ // can delete the orphan conv. The error still lives on the store.
mockBackend.mockRejectedValueOnce(new Error('startup-fail'))
await useRemoteStore.getState().dispatch('c', 'm', '').catch(() => {})
expect(useRemoteStore.getState().error).toMatch(/startup-fail/)
})
+
+ it('rethrows on startServer failure so Sidebar can clean up the orphan conv', async () => {
+ // #29: phantomderp's bug — silent failure left the user staring at a
+ // "Server stopped" banner that did nothing. The store now rethrows
+ // so Sidebar.handleDispatch can delete the just-created conv row.
+ mockBackend.mockRejectedValueOnce(new Error('port-in-use'))
+ await expect(
+ useRemoteStore.getState().dispatch('orphan', 'm', '')
+ ).rejects.toThrow('port-in-use')
+ expect(useRemoteStore.getState().dispatchedConversationId).toBeNull()
+ expect(useRemoteStore.getState().error).toMatch(/port-in-use/)
+ })
+})
+
+describe('remoteStore › restart() failure semantics', () => {
+ it('rethrows on backend failure and exposes the error to the UI', async () => {
+ // #29: ChatView's "Server stopped" banner uses the rethrow + error
+ // state to render the actual reason inline, instead of the user
+ // clicking Restart forever.
+ mockBackend.mockRejectedValueOnce(new Error('bind-failed'))
+ await expect(
+ useRemoteStore.getState().restart('m', '')
+ ).rejects.toThrow('bind-failed')
+ expect(useRemoteStore.getState().enabled).toBe(false)
+ expect(useRemoteStore.getState().loading).toBe(false)
+ expect(useRemoteStore.getState().error).toMatch(/bind-failed/)
+ })
+
+ it('clearError() wipes the error so the next attempt starts clean', () => {
+ useRemoteStore.setState({ error: 'previous failure' })
+ useRemoteStore.getState().clearError()
+ expect(useRemoteStore.getState().error).toBeNull()
+ })
})
describe('remoteStore › undispatch()', () => {
diff --git a/src/stores/__tests__/remoteStore.test.ts b/src/stores/__tests__/remoteStore.test.ts
index ad5156b3..ae4ae80d 100644
--- a/src/stores/__tests__/remoteStore.test.ts
+++ b/src/stores/__tests__/remoteStore.test.ts
@@ -74,9 +74,12 @@ describe('remoteStore', () => {
})
})
- it('sets error on failure', async () => {
+ it('sets error and rethrows on failure', async () => {
mockBackendCall.mockRejectedValueOnce(new Error('Connection refused'))
- await useRemoteStore.getState().startServer()
+ // #29: startServer rethrows so dispatch()/restart() callers can clean up
+ // (delete orphan conv, surface UI banner) instead of silently
+ // marking the chat as dispatched on a server that never came up.
+ await expect(useRemoteStore.getState().startServer()).rejects.toThrow('Connection refused')
const state = useRemoteStore.getState()
expect(state.loading).toBe(false)
expect(state.error).toContain('Connection refused')
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 3dd526c2..f41a3230 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -33,6 +33,11 @@ interface ChatState {
deleteConversation: (id: string) => void
renameConversation: (id: string, title: string) => void
setActiveConversation: (id: string | null) => void
+ /** Toggle the active persona on/off for a specific chat — mirrors the
+ * mobile chat's `personaEnabled` flag so the user can suppress the
+ * persona's systemPrompt without changing the global Settings
+ * selection. */
+ setConversationPersonaEnabled: (id: string, enabled: boolean) => void
addMessage: (conversationId: string, message: Message) => void
insertMessageBefore: (conversationId: string, beforeId: string, message: Message) => void
updateMessageContent: (conversationId: string, messageId: string, content: string) => void
@@ -69,6 +74,13 @@ export const useChatStore = create<ChatState>()(
mode: mode || 'lu',
createdAt: Date.now(),
updatedAt: Date.now(),
+ // Per David's request: persona starts OFF by default on every
+ // new conversation. The user has to flip it on explicitly via
+ // the Plugins dropdown toggle. Without this, a globally
+ // selected persona (e.g. "Devil's Advocate") would silently
+ // hijack every new chat — including agent / codex tasks where
+ // the persona conflicts with the autonomy contract.
+ personaEnabled: false,
}
set((state) => ({
conversations: [conversation, ...state.conversations],
@@ -93,6 +105,13 @@ export const useChatStore = create<ChatState>()(
setActiveConversation: (id) => set({ activeConversationId: id }),
+ setConversationPersonaEnabled: (id, enabled) =>
+ set((state) => ({
+ conversations: state.conversations.map((c) =>
+ c.id === id ? { ...c, personaEnabled: enabled } : c
+ ),
+ })),
+
addMessage: (conversationId, message) =>
set((state) => ({
conversations: state.conversations.map((c) =>
diff --git a/src/stores/remoteStore.ts b/src/stores/remoteStore.ts
index a73f4efe..255126f9 100644
--- a/src/stores/remoteStore.ts
+++ b/src/stores/remoteStore.ts
@@ -74,6 +74,7 @@ interface RemoteState {
restart: (model?: string, systemPrompt?: string) => Promise<void>
showQr: () => void
hideQr: () => void
+ clearError: () => void
}
export const useRemoteStore = create<RemoteState>()((set, get) => ({
@@ -124,7 +125,13 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
// Auto-fetch QR code
get().fetchQrCode()
} catch (err) {
- set({ loading: false, error: String(err) })
+ // #29: rethrow so dispatch()/restart() callers can react. Previously
+ // we swallowed silently, which let dispatch() set
+ // dispatchedConversationId on a server that never actually started —
+ // user saw "Server stopped" with no explanation and Restart hit the
+ // same silent failure.
+ set({ loading: false, enabled: false, error: String(err) })
+ throw err
}
},
@@ -259,12 +266,17 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
if (enabled) {
await stopServer()
}
- // Start fresh server, only set ID on success
+ // Start fresh server, only set ID on success.
+ // #29: startServer now rethrows on failure — re-throw so the caller
+ // (Sidebar.handleDispatch) can clean up the orphan conversation row
+ // it just created instead of leaving the user staring at a "Server
+ // stopped" banner with no way out.
try {
await startServer(model, systemPrompt)
set({ dispatchedConversationId: conversationId })
} catch (err) {
set({ dispatchedConversationId: null, error: String(err) })
+ throw err
}
},
@@ -273,6 +285,15 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
if (enabled) {
await stopServer()
}
+ // #29 follow-up: clear the Remote workspace override so the next
+ // dispatch starts from a clean slate (otherwise an old folder from
+ // last session would still bind for new mobile-driven file writes).
+ try {
+ await backendCall('set_chat_workspace_override', {
+ chatId: '__remote__',
+ path: null,
+ })
+ } catch { /* best-effort cleanup */ }
set({ dispatchedConversationId: null })
},
@@ -307,10 +328,15 @@ export const useRemoteStore = create<RemoteState>()((set, get) => ({
// Re-fetch QR for the new passcode
get().fetchQrCode()
} catch (err) {
- set({ loading: false, error: String(err) })
+ // #29: rethrow so the click-handler (ChatView.handleRemoteReactivate
+ // or Sidebar restart chip) can surface the actual reason instead of
+ // looking like the button did nothing.
+ set({ loading: false, enabled: false, error: String(err) })
+ throw err
}
},
showQr: () => set({ qrVisible: true }),
hideQr: () => set({ qrVisible: false }),
+ clearError: () => set({ error: null }),
}))
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 9dadfaf5..c139353b 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -33,6 +33,11 @@ export interface Conversation {
model: string
systemPrompt: string
mode?: 'lu' | 'codex' | 'openclaw' | 'claude-code' | 'remote'
+ /** Per-chat persona toggle. Mirrors the mobile chat's `personaEnabled`
+ * flag so the user can flip the persona on/off for each chat
+ * individually without losing the selection in Settings. Undefined
+ * on legacy chats and treated as enabled. */
+ personaEnabled?: boolean
createdAt: number
updatedAt: number
}