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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
tech(T-75): der Mobile-Client wird echter Quelltext — byteweise dieselbe Seite
David613df75b6679
diff --git a/eslint.config.js b/eslint.config.jsindex 35deb724..7e84df30 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -20,4 +20,39 @@ export default defineConfig([globals: globals.browser,},},+ // ── mobile-client/: the page a paired phone runs ──+ //+ // Until T-75 this was a 2 964-line Rust string literal, so eslint had never+ // seen a character of it. It is now four real .js files that src-tauri's+ // build script glues into one <script>. They are plain browser ES5 with+ // `var` and function expressions, not React TypeScript, so they get their+ // own block rather than being bent into the one above.+ //+ // The rule that earns this block is `no-undef`, and it covers a gap tsc+ // leaves: the import statements at the top of client.js are the only+ // written-down record of which names the three spliced modules owe it, and+ // client.js is a .js importer, which tsc does not check unless `checkJs` is+ // on (it is not — see tsconfig.app.json for why). Drop a name from that+ // import block and eslint is the only thing that says so.+ //+ // The two relaxations below are this file's idiom, not a waiver: `catch(_){}`+ // is how the client swallows a failed localStorage read, and the only unused+ // bindings it has are catch parameters and unread arguments. Nothing else is+ // turned off — `npx eslint mobile-client` reports 5 real errors today (one+ // dead variable, four inert regex escapes) and they are left standing on+ // purpose, because T-75 ships the same page bytes it found. Fixing them is+ // its own change.+ {+ files: ['mobile-client/**/*.js'],+ extends: [js.configs.recommended],+ languageOptions: {+ ecmaVersion: 2020,+ sourceType: 'module',+ globals: globals.browser,+ },+ rules: {+ 'no-empty': ['error', { allowEmptyCatch: true }],+ 'no-unused-vars': ['error', { args: 'none', caughtErrors: 'none' }],+ },+ },])diff --git a/mobile-client/agent-core.js b/mobile-client/agent-core.jsnew file mode 100644index 00000000..45322ce2--- /dev/null+++ b/mobile-client/agent-core.js@@ -0,0 +1,359 @@+/*@@LU_TOOLING_ONLY@@*/+// Cut out by src-tauri/build.rs: in the assembled page this file and+// personas.js share one function scope, so the name is simply in scope.+import { stripNonCanonicalTags } from './personas.js'+/*@@LU_END@@*/+ // ── Agent tools (parity with src/api/mcp/builtin-tools.ts) ──+ // Descriptions kept tight-matched with the desktop BUILTIN_TOOLS so the+ // same model behaviour follows us onto mobile. Tests in+ // src/api/__tests__/tool-description-parity.test.ts pin this parity.+ var AGENT_TOOLS = [+ {name:'todo_write', description:'Write and update the plan for a multi-step task. The list is shown to the user live, so it is how they follow a long run. USE FIRST when a task needs more than about three tool calls, then send it again after each step. Send the COMPLETE list every time: it replaces the previous one, it does not merge.',+ parameters:[{name:'todos',type:'array',description:'The complete plan, in order. Replaces the previous list.',required:true}]},+ {name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. Snippets are teasers, not answers: PREFER web_fetch on the promising URLs for the real content. DO NOT run more than 3 similar queries per turn, refine instead of re-searching.',+ parameters:[{name:'query',type:'string',description:'The search query string',required:true},+ {name:'maxResults',type:'number',description:'Maximum results to return (default: 5, max: 20)',required:false}]},+ {name:'web_fetch', description:'Fetch a single URL and return its readable text (up to ~24 000 chars), scripts, styles and page furniture stripped. PREFER this over web_search when you already know the target URL. NEVER call it with localhost, a private IP or file://, those are refused. On an empty or 4xx response try a different URL, not the same one again.',+ parameters:[{name:'url',type:'string',description:'Full URL including protocol (http:// or https://)',required:true},+ {name:'maxLength',type:'number',description:'Max chars to return (default: 24000)',required:false}]},+ {name:'file_read', description:'Read a file. PREFER absolute paths; relative paths resolve against the agent workspace. Omitting offset/limit returns the whole file. For LARGE files pass offset (1-based start line) and limit (number of lines): the response names the window, the total line count and the offset of the next page. A very long whole-file read gets its middle truncated, so page large files. DO NOT re-read a file you just wrote, the write response already confirmed it.',+ parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},+ {name:'offset',type:'number',description:'1-based line to start reading from (optional)',required:false},+ {name:'limit',type:'number',description:'Maximum number of lines to return (optional)',required:false}]},+ {name:'file_write', description:'Write a WHOLE file: use it to CREATE a new file or fully replace one, and PREFER file_edit to change part of an existing one. Creates parent directories if missing. OVERWRITES existing content, there is no append mode. PREFER absolute paths.',+ parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},+ {name:'content',type:'string',description:'The complete new content of the file',required:true}]},+ {name:'file_list', description:'List directory contents. Returns name, isDir, size and full path per entry. Supports recursive=true and a glob pattern ("*.ts", "**/*.py"). PREFER a specific pattern over recursing a whole home or drive, that is slow. For content search use file_search.',+ parameters:[{name:'path',type:'string',description:'Directory path to list',required:true},+ {name:'recursive',type:'boolean',description:'Recurse into subdirectories (default: false)',required:false},+ {name:'pattern',type:'string',description:'Glob pattern to filter results (e.g. "*.ts", "**/*.py")',required:false}]},+ {name:'file_search', description:'Grep-style regex content search across files in a directory. Returns matching lines with file and line number. PREFER it over file_read plus a manual scan when hunting a symbol across many files. Default max 50 results, narrow the pattern or path if you flood. Pattern is Rust regex syntax, not PCRE.',+ parameters:[{name:'path',type:'string',description:'Directory to search in (recursive by default)',required:true},+ {name:'pattern',type:'string',description:'Regex pattern to search for',required:true},+ {name:'maxResults',type:'number',description:'Maximum matching files (default: 50)',required:false}]},+ {name:'shell_execute', description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. Everything runs here: git, tests, package managers, gh, python, platform utilities, and opening files, folders or apps. A recognised test run and the common git commands come back as a parsed summary. Feed a script through `stdin` instead of quoting it: set command to `python3 -` or `bash -s` (fresh process each call, no REPL state). For long work set `background: true` to get a task id back at once, then call again with `task: "status"` and `task_id` (or "list" / "kill"). PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`, file_search over `grep`. `--no-verify` is refused, and NEVER delete permanently without confirmation. Default timeout 120 s, test runs 300 s.',+ parameters:[{name:'command',type:'string',description:'The full command to execute. Omit only for task actions.',required:false},+ {name:'cwd',type:'string',description:'Working directory (optional, absolute preferred)',required:false},+ {name:'timeout',type:'number',description:'Timeout in milliseconds (default: 120000)',required:false},+ {name:'shell',type:'string',description:'Override shell: "powershell" | "cmd" | "bash" (default: auto)',required:false},+ {name:'stdin',type:'string',description:'Text piped to the command\x27s stdin, e.g. a Python script for `python3 -`.',required:false},+ {name:'background',type:'boolean',description:'Run detached; returns a task id immediately instead of waiting.',required:false},+ {name:'task',type:'string',description:'Background-task action instead of running a command.',required:false},+ {name:'task_id',type:'string',description:'Task id for task "status" or "kill".',required:false}]},+ {name:'screenshot', description:'Capture the primary display as a base64 PNG. Zero arguments. USE for visual verification when the user asks "what\'s on my screen" or "look at X". Returns a short summary string (size + filename); the actual image is forwarded to the model via message content. NEVER call in a tight loop — screenshots are expensive and privacy-sensitive.',+ parameters:[]},+ {name:'image_generate', description:'Generate an image from a text prompt via the local image pipeline (Apple MLX on macOS; ComfyUI elsewhere, auto-detected). Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE on non-Mac (ComfyUI) single-GPU machines: LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap. This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — generations serialize internally so parallel calls will queue, not speed up. Fine-tune through the optional `settings` object; a value beyond the model\'s real limit is REJECTED with the actual limit, never silently changed.',+ parameters:[{name:'prompt',type:'string',description:'Positive text description of the desired image',required:true},+ {name:'negativePrompt',type:'string',description:'Things to avoid (blurry, deformed, etc.)',required:false},+ {name:'model',type:'string',description:'Optional image model filename to use. Omit to auto-select the first installed image model.',required:false},+ {name:'inputImage',type:'string',description:'Optional. Filename of a previously generated image (from an earlier image_generate result) to use as the base for image-to-image. Omit for text-to-image.',required:false},+ {name:'denoise',type:'number',description:'Image-to-image strength 0.05–1.0 (default 0.6). Lower keeps more of the input image, higher follows the prompt more. Only used together with inputImage.',required:false}]},+ ];++ // ── Tool-set constants ──+ var CODEX_TOOLS = ['file_read','file_write','file_list','file_search','shell_execute','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+((the\s+)?coding\s+agent|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;+ }++ // ── A1 mobile: age decay for tool results ─────────────────────────+ // Same rule and the same numbers as the desktop (src/lib/context-decay.ts):+ // a result the model looked at two iterations ago has already done its job,+ // so it rides along head+tail-capped, while the newest iteration stays+ // byte-for-byte intact. That last half is the binding behavioural rule: the+ // model must never edit against content it can no longer see.+ //+ // What it fixes here: the loop pushed every observation at full length and+ // the compaction below always kept the last four messages, so ONE 200 KB+ // file_read sat in the window forever. Ollama then truncated the request+ // from the FRONT, which eats the system prompt and the original task, and+ // the run answered "I'm ready to receive the task" mid-loop. That is the+ // documented mobile task-forgetting, and it was never a compaction bug: the+ // compaction was doing exactly what it was told with a number that could+ // never be reached.+ //+ // The visible transcript is untouched. appendAgentStep('observation', obs)+ // runs on the FULL text before the push, so the user keeps the whole result+ // and only the model's copy is capped.+ var DECAY_RESULT_CHARS = 4000;+ var RESTORE_RESULT_CHARS = 1500;+ var DECAY_AFTER_ITERATIONS = 2;+ var TRUNCATION_MARKER = '…[truncated ';+ var MARKER_SLACK = 64;+ // How many messages may still carry their images. Base64 image bytes were+ // invisible to the budget below, so a photo turn could be ten times over it+ // and compaction saw nothing to do.+ var IMAGE_KEEP_RECENT = 2;++ // True when this text already IS the output of a cut at `budget`. Cutting a+ // second time would land on different bytes every step, so the check has to+ // come before the cut, not after.+ function isDecayedAt(text, budget){+ var s = String(text == null ? '' : text);+ return s.length <= budget + MARKER_SLACK && s.indexOf(TRUNCATION_MARKER) !== -1;+ }++ // Head-heavy split, same 2/3 as the desktop: the start of a result carries+ // the most signal (top of a file, first compiler error), the tail keeps the+ // exit code and the final error.+ function capToolResult(text, maxChars){+ var s = String(text == null ? '' : text);+ if(s.length <= maxChars) return s;+ if(isDecayedAt(s, maxChars)) return s;+ var headChars = Math.max(0, Math.floor(maxChars * 0.66));+ var tailChars = Math.max(0, maxChars - headChars);+ var head = s.slice(0, headChars);+ var tail = tailChars > 0 ? s.slice(s.length - tailChars) : '';+ var dropped = s.length - head.length - tail.length;+ return head + '\n\n' + TRUNCATION_MARKER + dropped + ' chars]…\n\n' + tail;+ }++ // Cap every tool result older than DECAY_AFTER_ITERATIONS. Messages without+ // an iteration are restored history, i.e. as old as it gets. In place and+ // final: capToolResult returns an already-capped result unchanged, so the+ // prompt prefix stops moving after the one step that did the cutting.+ function decayToolResults(messages, currentIter){+ if(!Array.isArray(messages)) return messages;+ var cutoff = currentIter - DECAY_AFTER_ITERATIONS;+ for(var i=0;i<messages.length;i++){+ var m = messages[i];+ if(!m || m.role !== 'tool') continue;+ var it = (typeof m.iter === 'number') ? m.iter : -Infinity;+ if(it > cutoff) continue;+ m.content = capToolResult(m.content, DECAY_RESULT_CHARS);+ }+ return messages;+ }++ // Characters this message really costs. Base64 images are the whole point:+ // they are the biggest thing in a payload and the old count ignored them.+ function msgChars(m){+ if(!m) return 0;+ var n = String(m.content || '').length;+ if(Array.isArray(m.images)){+ for(var i=0;i<m.images.length;i++) n += String(m.images[i] || '').length;+ }+ return n;+ }++ function totalChars(messages){+ var n = 0;+ for(var i=0;i<messages.length;i++) n += msgChars(messages[i]);+ return n;+ }++ // Only the newest `keepRecent` messages that carry images send them again.+ // An older picture is replaced by a one-line placeholder so the model still+ // knows a picture was there.+ function dropOldImages(messages, keepRecent){+ if(!Array.isArray(messages)) return messages;+ var withImages = [];+ for(var i=0;i<messages.length;i++){+ var m = messages[i];+ if(m && Array.isArray(m.images) && m.images.length) withImages.push(i);+ }+ var firstKept = Math.max(0, withImages.length - keepRecent);+ for(var k=0;k<firstKept;k++){+ var msg = messages[withImages[k]];+ var count = msg.images.length;+ delete msg.images;+ msg.content = String(msg.content || '') ++ '\n[' + count + ' image(s) from an earlier message omitted]';+ }+ return messages;+ }++ // 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)) return messages;+ var budget = charBudget || 24000;+ // Unconditional, and before the early return: an old image is bytes the+ // model has already been shown and cannot act on twice.+ dropOldImages(messages, IMAGE_KEEP_RECENT);+ if(messages.length < 6) return messages;+ if(totalChars(messages) <= 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);+ var headChars = totalChars(head);+ while(tail.length > 4){+ if(headChars + totalChars(tail) <= budget) break;+ tail.shift();+ }+ // The floor of four can still be bigger than the whole budget when one of+ // those four is a single huge result: the newest iteration is never+ // decayed, so a fresh 200 KB read lands here at full length. Leaving it+ // means Ollama truncates from the front and eats the system prompt and the+ // task, so cap what is left instead, oldest first, and touch the newest+ // result only when nothing else gets us under. Two fixed rungs, never a+ // budget derived from the payload, so the same history always produces the+ // same bytes.+ if(headChars + totalChars(tail) > budget){+ var rungs = [DECAY_RESULT_CHARS, RESTORE_RESULT_CHARS];+ for(var r=0;r<rungs.length;r++){+ for(var t=0;t<tail.length;t++){+ if(headChars + totalChars(tail) <= budget) break;+ if(!tail[t] || tail[t].role !== 'tool') continue;+ tail[t].content = capToolResult(tail[t].content, rungs[r]);+ }+ }+ }+ 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,+ // parameters:{type:'object', properties:{...}, required:[...]}}}].+ function buildToolDefs(toolNames){+ var out = [];+ for(var i=0;i<AGENT_TOOLS.length;i++){+ var t = AGENT_TOOLS[i];+ if(toolNames.indexOf(t.name) === -1) continue;+ var props = {};+ var req = [];+ for(var j=0;j<t.parameters.length;j++){+ var p = t.parameters[j];+ props[p.name] = {type: p.type, description: p.description};+ if(p.required) req.push(p.name);+ }+ out.push({+ type: 'function',+ function: {+ name: t.name,+ description: t.description,+ parameters: {type:'object', properties: props, required: req}+ }+ });+ }+ return out;+ }++ // Strip <think>...</think> tags from content. If keepThinking is true,+ // capture inner text into the returned `thinking` field; otherwise+ // discard it. Also handles Ollama's native `thinking` field.+ function stripThinkTags(content, keepThinking){+ var think = '';+ // Handle inline <think>...</think> tags (may be multiple)+ var cleaned = String(content || '').replace(/<think>([\s\S]*?)<\/think>/g, function(_, inner){+ if(keepThinking && inner) think = think ? think+'\n'+inner : inner;+ return '';+ });+ // Strip non-canonical reasoning tags too+ cleaned = stripNonCanonicalTags(cleaned).trim();+ return {content: cleaned, thinking: think};+ }+/*@@LU_TOOLING_ONLY@@*/+// Cut out by src-tauri/build.rs — see caveman.js.+export {+ AGENT_ALL_TOOLS,+ AGENT_TOOLS,+ CODEX_TOOLS,+ DECAY_AFTER_ITERATIONS,+ DECAY_RESULT_CHARS,+ IMAGE_KEEP_RECENT,+ MARKER_SLACK,+ RESTORE_RESULT_CHARS,+ TRUNCATION_MARKER,+ buildToolDefs,+ capToolResult,+ compactApiMessages,+ decayToolResults,+ dropOldImages,+ extractToolCallsFromContent,+ isDecayedAt,+ isSystemPromptEcho,+ msgChars,+ repairToolCallArgs,+ stripRanges,+ stripThinkTags,+ totalChars,+}+/*@@LU_END@@*/diff --git a/mobile-client/caveman.js b/mobile-client/caveman.jsnew file mode 100644index 00000000..8a289d17--- /dev/null+++ b/mobile-client/caveman.js@@ -0,0 +1,17 @@+ // ── Caveman prompts (parity with desktop) ──+ var CAVEMAN_PROMPTS = {+ lite: 'Be concise and direct. Drop filler words (just, really, basically, actually, simply), hedging, and pleasantries. Retain full grammar and articles. Keep code blocks, file paths, URLs, and commands unchanged. Every response follows this style.',+ full: 'Respond terse like smart caveman. All technical substance stay. Only fluff die. Drop: articles, filler (just/really/basically/actually/simply), pleasantries, hedging. Fragments OK. Short synonyms preferred. Code unchanged. Pattern: [thing] [action] [reason]. [next step]. ACTIVE EVERY RESPONSE.',+ ultra: 'Maximum brevity. Fewest possible words. Telegraphic. Abbreviate (DB/auth/config/fn/impl/req/res). Strip conjunctions. Arrows for flow (X -> Y). No articles, no filler, no pleasantries. Fragments only. Under 3 sentences unless code. Code/paths/URLs unchanged. ACTIVE EVERY RESPONSE.'+ };+ var CAVEMAN_REMINDERS = {+ lite: '[Be concise. No filler.]',+ full: '[Terse. Fragments OK. No fluff.]',+ ultra: '[Max brevity. Telegraphic.]'+ };+/*@@LU_TOOLING_ONLY@@*/+// Cut out by src-tauri/build.rs: a classic <script> cannot carry `export`.+// It is here so the tests import the shipped constants instead of keeping a+// second copy of them — the copy is what let the two drift apart.+export { CAVEMAN_PROMPTS, CAVEMAN_REMINDERS }+/*@@LU_END@@*/diff --git a/mobile-client/client.js b/mobile-client/client.jsnew file mode 100644index 00000000..5019bed9--- /dev/null+++ b/mobile-client/client.js@@ -0,0 +1,2216 @@+/*@@LU_TOOLING_ONLY@@*/+// Not part of the page. `src-tauri/build.rs` cuts this block out before the+// file becomes the <script> a phone runs, and splices the three modules in+// at the three //@@LU_…@@ marker lines below — the result is byte for byte+// what this file used to be as a Rust string.+//+// The block is here so tsc, eslint and an editor resolve the same names the+// browser resolves. Take a name off a module's export list and this import+// goes red before the page ever ships.+import { CAVEMAN_PROMPTS, CAVEMAN_REMINDERS } from './caveman.js'+import {+ CODEX_PROMPT,+ PERSONAS,+ THINKING_COMPATIBLE,+ isPlainTextPlanner,+ stripNonCanonicalTags,+} from './personas.js'+import {+ AGENT_ALL_TOOLS,+ AGENT_TOOLS,+ CODEX_TOOLS,+ DECAY_RESULT_CHARS,+ RESTORE_RESULT_CHARS,+ buildToolDefs,+ capToolResult,+ compactApiMessages,+ decayToolResults,+ extractToolCallsFromContent,+ isDecayedAt,+ isSystemPromptEcho,+ repairToolCallArgs,+ stripRanges,+ stripThinkTags,+} from './agent-core.js'+/*@@LU_END@@*/+(function(){+ var TOKEN = localStorage.getItem('lu-remote-token');+ // #73 (ossobucco): the server slides the session — when any authed request+ // comes back with a fresh token header, adopt it so an actively used /+ // open session never hits the 60-minute JWT cliff. The Set-Cookie on the+ // same response keeps /comfyui asset loads working too.+ function absorbRefresh(r){+ try{+ var t = r && r.headers && r.headers.get ? r.headers.get('x-lu-refreshed-token') : null;+ if(t){ TOKEN = t; localStorage.setItem('lu-remote-token', t); }+ }catch(_){}+ return r;+ }+ var currentModel = '';+ var dispatchedSystemPrompt = '';+ var availableModels = [];+ // The DESKTOP's platform sentence, handed over by /remote-api/config.+ // Never navigator.platform: the tools run on the machine that serves this+ // page, not on the phone holding it, so the phone's own OS is the one+ // answer that is always wrong here. Empty until config lands, and an empty+ // line is simply left out rather than guessed at.+ var hostPlatformLine = '';++ // ── Inline SVG icons (Lucide-style). Replaces the Material Symbols+ // font download to keep the mobile page free of third-party requests.+ var ICON_SVG_OPEN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">';+ var ICON_SVG_CLOSE = '</svg>';+ var ICONS = {+ menu:'<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>',+ close:'<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>',+ add:'<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>',+ check:'<polyline points="20 6 9 17 4 12"/>',+ expand_more:'<polyline points="6 9 12 15 18 9"/>',+ arrow_upward:'<line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/>',+ attach_file:'<path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66L9.41 17.41a2 2 0 01-2.83-2.83L15.07 6.1"/>',+ content_copy:'<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>',+ terminal:'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>',+ chat_bubble:'<path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/>',+ logout:'<path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>',+ extension:'<path d="M20 12V8h-4a2 2 0 10-4 0H8v4a2 2 0 110 4v4h4a2 2 0 104 0h4v-4a2 2 0 110-4z"/>',+ auto_awesome:'<path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8z"/><path d="M19 13l.9 2.1L22 16l-2.1.9L19 19l-.9-2.1L16 16l2.1-.9z"/>',+ // Bug #7: redesigned thinking icon — proper Lucide Brain glyph (parity+ // with desktop ThinkingBlock.tsx which imports Brain from lucide-react).+ // The old psychology / psychology_alt SVGs looked like a half-drawn head;+ // the new Brain has two clear hemispheres so the meaning reads at 20px.+ brain:'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4 4.5 4.5 0 0 0 3 4"/>',+ // Aliases — old call sites (psychology / psychology_alt) keep working+ // by mapping to the same Brain glyph so we don't have to rewrite every+ // string template that uses them. The redesign comment above stays+ // accurate: there is now exactly one mental-icon shape on mobile.+ psychology:'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4 4.5 4.5 0 0 0 3 4"/>',+ psychology_alt:'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4 4.5 4.5 0 0 0 3 4"/>',+ // smart_toy = our agent icon (kept across all states — see Bug #6).+ smart_toy:'<rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><line x1="12" y1="7" x2="12" y2="11"/><circle cx="8.5" cy="16" r="1" fill="currentColor"/><circle cx="15.5" cy="16" r="1" fill="currentColor"/>',+ stop:'<rect x="6" y="6" width="12" height="12" rx="1"/>',+ pencil:'<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 013 3L7 19l-4 1 1-4L16.5 3.5z"/>',+ refresh:'<polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0114.85-3.36L23 10"/><path d="M20.49 15A9 9 0 015.64 18.36L1 14"/>',+ tune:'<line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/>',+ trash:'<polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 01-2 2H9a2 2 0 01-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2"/>',+ delete_sweep:'<polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 01-2 2H9a2 2 0 01-2-2L5 6"/>',+ // Feature #8: HTML preview chip glyphs.+ play_arrow:'<polygon points="6 3 20 12 6 21 6 3" fill="currentColor"/>',+ open_in_new:'<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>',+ code_brackets:'<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>',+ eye:'<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>'+ };+ function svgIcon(name){return ICONS[name] ? ICON_SVG_OPEN + ICONS[name] + ICON_SVG_CLOSE : '';}+ // Expose for inline handlers (rare path, but keeps symmetry with prev API)+ window._svgIcon = svgIcon;++ //@@LU_CAVEMAN@@++ // Cached copy of the desktop's RemotePermissions (filesystem / downloads /+ // process_control). Read-only: loaded from /remote-api/permissions on+ // demand and displayed. The server ignores a permissions POST from a paired+ // device, so there is nothing to write back. Sampling knobs (temperature+ // etc.) are NOT exposed here — user explicitly asked for permissions only.+ var remotePerms = { filesystem: false, downloads: false, process_control: false };++ //@@LU_PERSONAS@@++ // ── Runtime state ──+ var chats = [];+ var currentChatId = '';+ var msgs = [];+ var streaming = false;+ var abortCtrl = null;+ var pendingImages = []; // [{data: base64, mimeType, name}]+ // Thinking toggle removed from mobile — see renderShell() comment.+ // Hardcoded false so every "is thinking on?" call site sees the same+ // answer and the stripper drops reasoning tokens silently.+ var thinking = false;+ var drawerOpen = false;+ // Agent mode is per-chat; toggled via the brain icon next to Plugins.+ // When active, _doSend runs the ReAct loop instead of plain chat.+ var agentRunning = false;+ var agentAbort = false;++ //@@LU_AGENT_CORE@@++ // Non-streaming POST to /api/chat with native `tools` array.+ // Returns a Promise that resolves to {content, thinking, toolCalls}.+ // `apiMessages` = [{role, content, ...}], `tools` = Ollama tool defs.+ function nativeToolChat(apiMessages, tools){+ var body = {+ model: currentModel,+ messages: apiMessages,+ tools: tools,+ stream: false,+ // v2.4.6 Bug L: dropped hardcoded num_gpu:99 (forced all layers to GPU,+ // killed 8 GB-VRAM laptop chat speed). Ollama auto-decides layer count.+ options: {num_predict: 16384}+ };+ // Tri-state think flag — same logic as _doSend.+ if(isThinkingCompatible(currentModel)){+ if(thinking){+ body.think = true;+ } else if(!isPlainTextPlanner(currentModel)){+ body.think = false;+ }+ }++ function doPost(b){+ return fetch('/api/chat',{+ method:'POST',+ headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},+ body: JSON.stringify(b),+ signal: abortCtrl ? abortCtrl.signal : undefined+ }).then(absorbRefresh);+ }++ return doPost(body).then(function(r){+ if(r.status===401){ clearAuthAndReload(); throw new Error('401'); }+ if(!r.ok){+ if(r.status===400 && ('think' in body)){+ var retry = {}; for(var k in body) retry[k]=body[k]; delete retry.think;+ return doPost(retry).then(function(rr){+ if(!rr.ok) return rr.text().then(function(t){throw new Error('HTTP '+rr.status+': '+t);});+ return rr.json();+ });+ }+ return r.text().then(function(t){+ // Detect "model does not support tools" errors+ if(t.indexOf('does not support tools') >= 0 || t.indexOf('does not support tool') >= 0){+ throw new Error('TOOLS_NOT_SUPPORTED');+ }+ throw new Error('HTTP '+r.status+': '+t);+ });+ }+ return r.json();+ }).then(function(data){+ var msg = data.message || {};+ var rawContent = msg.content || '';+ var rawThinking = msg.thinking || '';+ var toolCalls = [];+ if(Array.isArray(msg.tool_calls)){+ for(var i=0;i<msg.tool_calls.length;i++){+ var tc = msg.tool_calls[i];+ if(tc && tc.function){+ // 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)}});+ }+ }+ }+ return {content: rawContent, thinking: rawThinking, toolCalls: toolCalls};+ });+ }++ // Run a single tool against the desktop via /remote-api/agent-tool.+ // Returns a stringified observation suitable for the next loop turn.+ // The Rust bridge returns 200 OK with {error:"..."} for every failure+ // (missing arg, permission, underlying tool error). We surface those+ // as clean observations instead of "HTTP 500: ..." red errors.+ function runAgentTool(tool, args){+ // todo_write never leaves the browser: it writes the plan strip and nothing+ // else. Sending it to the desktop bridge would need a Rust dispatcher and a+ // permission gate for something that touches no file and no process, and it+ // would put a network round trip in front of a UI update.+ if(tool === 'todo_write'){+ return Promise.resolve(applyTodoWrite(args && args.todos));+ }+ return fetch('/remote-api/agent-tool',{+ method:'POST',+ headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},+ // `chatId` → per-chat workspace on the desktop side. Each mobile+ // chat gets its own isolated `~/agent-workspace/<chatId>/` folder+ // so agents across chats don't trample each other's files.+ body: JSON.stringify({tool:tool, args:args||{}, chatId: currentChatId || ''})+ }).then(absorbRefresh).then(function(r){+ if(r.status===401){ clearAuthAndReload(); return 'Auth required'; }+ return r.text().then(function(text){+ // Try to parse JSON regardless of status — the new bridge always+ // responds with a JSON body.+ var data = null;+ try{ data = JSON.parse(text); }catch(_){ /* leave null */ }++ // Old-style HTTP errors (e.g. 400 from a malformed payload) — fall+ // back to plain text so the agent still sees something useful.+ if(!r.ok && !data){ return 'Error '+r.status+': '+text; }++ if(data){+ // Surface permission-denied with an actionable hint to enable it.+ if(data.needs_permission){+ // Give the user a one-tap path: bump the header plugins icon+ // pulse so they know to open Settings → Permissions.+ try{ window._flagPermissionGap && window._flagPermissionGap(data.permission); }catch(_){}+ return 'Permission denied: '+data.error;+ }+ // Generic tool error — clean observation.+ if(typeof data.error === 'string') return 'Error: '+data.error;+ if(typeof data === 'string') return data;+ // web_search returns {results:[{title,url,snippet},...]}+ if(Array.isArray(data.results)){+ if(!data.results.length) return 'No results.';+ return data.results.map(function(it,i){return (i+1)+'. '+(it.title||'')+'\n '+(it.url||'')+'\n '+(it.snippet||'');}).join('\n\n');+ }+ // web_fetch returns {url, status, contentType, title, text, truncated}+ if(typeof data.text === 'string' && (data.url || data.status !== undefined)){+ var parts = [];+ if(data.title) parts.push('Title: '+data.title);+ if(data.url) parts.push('URL: '+data.url);+ if(data.status !== undefined) parts.push('Status: '+data.status);+ parts.push('');+ parts.push(data.text || '(empty body)');+ if(data.truncated) parts.push('\n…(truncated to 24 000 chars)');+ return parts.join('\n');+ }+ // file_read returns {content:"..."}+ if(typeof data.content === 'string') return data.content;+ // file_write returns {status:"saved", path:"..."}+ if(data.status==='saved') return 'File saved: '+(data.path||args.path||'');+ // code_execute / shell_execute returns {stdout, stderr, exitCode, timedOut}+ if(data.exitCode!==undefined || data.stdout!==undefined){+ var out = data.stdout || '';+ var err = data.stderr || '';+ if(data.timedOut) return 'Execution timed out.';+ if(data.exitCode && data.exitCode!==0) return 'Error ('+data.exitCode+'):\n'+(err||out);+ return out || (err ? 'stderr: '+err : 'Done.');+ }+ return JSON.stringify(data);+ }+ return text || 'Done.';+ });+ }).catch(function(e){ return 'Network error: '+(e && e.message || e); });+ }++ // Highlights the Settings (cog) icon in the drawer when an agent tool+ // got blocked by a permission. Best-effort — we just toggle a class so+ // the user notices the dot. No-op if the drawer isn't mounted yet.+ window._flagPermissionGap = function(_perm){+ var sb = document.querySelector('.settings-btn');+ if(sb){ sb.classList.add('perm-gap'); }+ };++ function H(t){return String(t==null?'':t).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}+ function el(id){return document.getElementById(id);}+ function uid(){return 'c-'+Date.now()+'-'+Math.random().toString(36).slice(2,7);}+ function mid(){return 'm-'+Date.now()+'-'+Math.random().toString(36).slice(2,7);}+ function mkMsg(role, content, extra){+ var m = {id: mid(), role: role, content: content||'', thinking:'', thinkingOpen:false, agentSteps:[]};+ if(extra && typeof extra === 'object'){ for(var k in extra) if(Object.prototype.hasOwnProperty.call(extra,k)) m[k]=extra[k]; }+ return m;+ }++ function isThinkingCompatible(modelName){+ if(!modelName) return false;+ var name = String(modelName).toLowerCase();+ var baseName = name.replace(/^[^/]+\//,'').replace(/:.*$/,'').replace(/-abliterated/g,'').replace(/-uncensored/g,'');+ for(var i=0;i<THINKING_COMPATIBLE.length;i++){+ if(baseName.indexOf(THINKING_COMPATIBLE[i])===0) return true;+ }+ return false;+ }++ // ── Persistence ──+ function loadPersisted(){+ try{+ chats = JSON.parse(localStorage.getItem('lu-mobile-chats')||'[]') || [];+ if(!Array.isArray(chats)) chats = [];+ // Backfill caveman/persona/agent defaults on legacy chats+ for(var i=0;i<chats.length;i++){+ if(!chats[i].caveman) chats[i].caveman = 'off';+ if(!chats[i].personaId) chats[i].personaId = 'unrestricted';+ if(typeof chats[i].personaEnabled === 'undefined') chats[i].personaEnabled = false;+ if(typeof chats[i].agentEnabled === 'undefined') chats[i].agentEnabled = false;+ // Backfill message ids + empty thinking/agentSteps on legacy msgs+ if(Array.isArray(chats[i].msgs)){+ for(var j=0;j<chats[i].msgs.length;j++){+ var mm = chats[i].msgs[j];+ if(!mm.id) mm.id = 'm-'+Date.now()+'-'+Math.random().toString(36).slice(2,7)+'-'+j;+ if(mm.thinking === undefined) mm.thinking = '';+ if(!Array.isArray(mm.agentSteps)) mm.agentSteps = [];+ if(typeof mm.thinkingOpen === 'undefined') mm.thinkingOpen = false;+ }+ }+ }+ currentChatId = localStorage.getItem('lu-mobile-current-chat') || '';+ // `thinking` is always false now (UI toggle removed).+ thinking = false;+ }catch(_){chats=[];currentChatId='';thinking=false;}+ }+ function persistChats(){+ try{localStorage.setItem('lu-mobile-chats', JSON.stringify(chats));}catch(_){}+ }+ function persistState(){+ try{+ localStorage.setItem('lu-mobile-current-chat', currentChatId);+ }catch(_){}+ }+ function getCaveman(){var c=findChat(currentChatId); return c && c.caveman ? c.caveman : 'off';}+ function getPersonaId(){var c=findChat(currentChatId); return c && c.personaId ? c.personaId : 'unrestricted';}+ function getPersonaEnabled(){var c=findChat(currentChatId); return !!(c && c.personaEnabled);}+ function getAgentEnabled(){var c=findChat(currentChatId); return !!(c && c.agentEnabled);}+ function setAgentEnabled(v){var c=findChat(currentChatId); if(c){ c.agentEnabled = !!v; persistChats(); }}++ // ── Chat management ──+ function findChat(id){for(var i=0;i<chats.length;i++){if(chats[i].id===id) return chats[i];}return null;}+ function syncCurrentChat(){+ var c = findChat(currentChatId); if(!c) return;+ c.msgs = msgs.slice();+ // Title auto-derive from first user message+ if((!c.title || c.title==='New Chat' || c.title==='New Code') && msgs.length){+ var firstUser = msgs.find(function(m){return m.role==='user';});+ if(firstUser){+ var t = firstUser.content.replace(/\s+/g,' ').trim().slice(0,32);+ if(t) c.title = t;+ }+ }+ persistChats();+ }+ function createChat(mode){+ var c = {id:uid(), title: mode==='codex'?'New Code':'New Chat', mode:mode||'lu', caveman:'off', personaId:'unrestricted', personaEnabled:false, agentEnabled:false, createdAt:Date.now(), msgs:[], model: currentModel||''};+ chats.unshift(c);+ currentChatId = c.id;+ msgs = [];+ pendingImages = [];+ persistChats();+ persistState();+ return c;+ }+ function loadChat(id){+ var c = findChat(id); if(!c) return;+ // Save outgoing first+ syncCurrentChat();+ currentChatId = id;+ msgs = Array.isArray(c.msgs) ? c.msgs.slice() : [];+ pendingImages = [];+ persistState();+ }+ function deleteChat(id){+ chats = chats.filter(function(c){return c.id!==id;});+ if(currentChatId===id){+ if(chats.length){ currentChatId = chats[0].id; msgs = Array.isArray(chats[0].msgs) ? chats[0].msgs.slice() : []; }+ else{ createChat('lu'); return; }+ }+ persistChats(); persistState();+ }+ function getCurrentMode(){+ var c = findChat(currentChatId);+ 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 LU. 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 web_search 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.';++ // ── Clock line (2.6.6, plan A5) ──+ // The volatile half of the environment block. Word for word the desktop's+ // hostClockLine() in src/lib/host-platform.ts, because a relay that phrases+ // the date differently is a second prompt to keep in your head. Built fresh+ // on every turn, so a session that runs for hours does not quote the time+ // the page was opened.+ function hostClockLine(now){+ var tz = '';+ try{ tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; }catch(_){ }+ var stamp = (now || new Date()).toLocaleString('en-GB', {dateStyle:'full', timeStyle:'short'});+ return 'Date and time at the start of this run: ' + stamp + (tz ? ' (' + tz + ')' : '') ++ '. Trust this line; there is no clock tool.';+ }++ // ── System prompt builder ──+ function buildSystemPrompt(){+ var parts = [];+ var cm = getCaveman();+ if(cm!=='off' && CAVEMAN_PROMPTS[cm]) parts.push(CAVEMAN_PROMPTS[cm]);+ 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 if(agentOn){+ parts.push(AGENT_PROMPT);+ }+ // ── Environment block, on the two surfaces that own tools ──+ // Task 215: the relay ran its agent loop without ever saying which machine+ // it stands on, so a phone run on a Mac guessed `explorer` and burned a+ // step on `uname`. Plain chat has no tools and gets neither line.+ //+ // The split follows plan A5. The platform sentence reads the same on every+ // turn and rides in front, where a prefix cache can match it. The clock+ // changes every minute and closes the prompt, so a miss costs the last+ // line instead of everything above it.+ if(isCodex || agentOn){+ if(hostPlatformLine) parts.push(hostPlatformLine);+ parts.push(hostClockLine());+ }+ return parts.join('\n\n');+ }++ // ── Auth Screen ──+ if(!TOKEN){+ el('app').innerHTML =+ '<div class="auth-screen">' ++ '<img class="auth-mark" src="/LU-monogram-white.png" alt="">' ++ '<div class="auth-logo">LU</div>' ++ '<div class="auth-sub">Remote</div>' ++ '<form class="auth-form" id="auth-form">' ++ '<div>' ++ '<div class="auth-label">Access Code</div>' ++ '<input class="auth-input" id="auth-code" type="tel" inputmode="numeric" pattern="[0-9]*" maxlength="6" placeholder="000000" autocomplete="off" autofocus>' ++ '</div>' ++ '<button class="auth-btn" type="submit">Connect</button>' ++ '<div class="auth-err" id="auth-err"></div>' ++ '</form>' ++ '</div>';+ el('auth-form').onsubmit = function(e){+ e.preventDefault();+ var code = el('auth-code').value.trim();+ var errEl = el('auth-err');+ if(code.length < 6){errEl.textContent='Enter 6-digit code';return;}+ errEl.textContent = '';+ fetch('/remote-api/auth',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({passcode:code})})+ .then(function(r){+ if(r.ok) return r.json().then(function(d){localStorage.setItem('lu-remote-token',d.token);location.reload();});+ if(r.status===429) return r.text().then(function(t){errEl.textContent=t;});+ errEl.textContent='Invalid access code';+ })+ .catch(function(){errEl.textContent='Connection failed';});+ };+ return;+ }++ // ── Load config + models then render ──+ function clearAuthAndReload(){+ // #73: keep whatever the user had typed across the re-pairing round-trip.+ // The reload lands on the passcode view; the draft is restored after auth.+ try{+ var inp = document.getElementById('msg-input');+ if(inp && inp.value && inp.value.trim()) localStorage.setItem('lu-remote-draft', inp.value);+ }catch(_){}+ localStorage.removeItem('lu-remote-token');+ location.reload();+ }+ function authJson(url){+ return fetch(url,{headers:{'Authorization':'Bearer '+TOKEN}})+ .then(absorbRefresh)+ .then(function(r){+ if(r.status===401){clearAuthAndReload();throw new Error('401');}+ if(!r.ok) throw new Error('HTTP '+r.status);+ return r.json();+ })+ .catch(function(){return null;});+ }++ loadPersisted();++ // #73: restore a message that survived a re-pairing (stashed on 401 /+ // clearAuthAndReload). The composer is rendered asynchronously, so poll+ // briefly for it instead of racing the first render.+ (function(){+ var savedDraft = '';+ try{ savedDraft = localStorage.getItem('lu-remote-draft') || ''; }catch(_){}+ if(!savedDraft) return;+ try{ localStorage.removeItem('lu-remote-draft'); }catch(_){}+ var tries = 0;+ var timer = setInterval(function(){+ tries++;+ var inp = document.getElementById('msg-input');+ if(inp){+ if(!inp.value) inp.value = savedDraft;+ clearInterval(timer);+ } else if(tries > 40){+ clearInterval(timer);+ }+ }, 250);+ })();++ // #73: while the tab is open and visible, ping an authed endpoint every+ // 10 minutes. Each ping runs through the auth middleware, which slides the+ // token once it is past half its TTL — so a session stays alive as long as+ // the tab is actually kept open. A closed/backgrounded tab still expires+ // after the full 60 min and needs re-pairing (deliberate: this surface can+ // reach the whole bridge, an unbounded offline token would be worse).+ // A failed/401 ping stays silent — no surprise reload while reading; the+ // next real action shows the passcode view and the draft is preserved.+ setInterval(function(){+ if(document.visibilityState && document.visibilityState !== 'visible') return;+ fetch('/remote-api/status/full',{headers:{'Authorization':'Bearer '+TOKEN}})+ .then(absorbRefresh)+ .catch(function(){});+ }, 10*60*1000);++ // ── Keyboard / viewport tracking ────────────────────────────────+ // iOS Safari + some Android browsers do NOT resize `window.innerHeight`+ // when the software keyboard opens. The page sits at full height behind+ // the keyboard and the top of the chat scrolls off-screen. `dvh` CSS+ // units fix most cases; for the holdouts we sync an explicit+ // `--kb-height` custom prop and apply it as bottom-padding on the+ // input bar so it never hides behind the keyboard.+ (function setupViewportTracking(){+ if(typeof window.visualViewport === 'undefined') return;+ var vv = window.visualViewport;+ function sync(){+ // Height difference = keyboard + safe-area chrome on the bottom.+ var kb = Math.max(0, (window.innerHeight || 0) - vv.height - vv.offsetTop);+ document.documentElement.style.setProperty('--kb-height', kb + 'px');+ // Also pin the scroll position to the bottom of the current chat+ // when the keyboard animates in, so the latest message stays visible.+ var cm = document.getElementById('chat-msgs');+ if(cm && kb > 0){ cm.scrollTop = cm.scrollHeight; }+ }+ vv.addEventListener('resize', sync);+ vv.addEventListener('scroll', sync);+ sync();+ })();+ Promise.all([authJson('/remote-api/config'), authJson('/api/tags')]).then(function(res){+ var cfg = res[0] || {};+ var tags = res[1] || {};+ availableModels = (tags.models || [])+ .map(function(m){return m.name || m.model || '';})+ .filter(function(n){return !!n;});+ var stored = localStorage.getItem('lu-mobile-model') || '';+ currentModel = (stored && availableModels.indexOf(stored) >= 0) ? stored+ : (cfg.model && availableModels.indexOf(cfg.model) >= 0) ? cfg.model+ : (cfg.model || availableModels[0] || '');+ dispatchedSystemPrompt = cfg.systemPrompt || '';+ hostPlatformLine = cfg.platformLine || '';++ // Ensure we have a current chat+ if(!currentChatId || !findChat(currentChatId)){+ if(chats.length){ currentChatId = chats[0].id; msgs = Array.isArray(chats[0].msgs) ? chats[0].msgs.slice() : []; }+ else{ createChat('lu'); }+ }else{+ var c = findChat(currentChatId);+ msgs = Array.isArray(c.msgs) ? c.msgs.slice() : [];+ }++ renderShell();+ });++ function renderShell(){+ var mode = getCurrentMode();+ var isCodex = mode === 'codex';+ var modeTag = isCodex ? '<span class="header-mode-tag">Code</span>' :+ (getAgentEnabled() ? '<span class="header-mode-tag">Agent</span>' : '');+ var pluginsActive = (getCaveman()!=='off' || getPersonaEnabled()) ? ' active' : '';+ var agentActive = getAgentEnabled() ? ' active' : '';+ // Agent icon STAYS smart_toy regardless of state. The button class+ // flips to `active` (purple) while running, click routes to _stopAgent.+ var agentClickHandler = agentRunning ? 'window._stopAgent()' : 'window._toggleAgent()';+ var agentLabel = agentRunning ? 'Stop agent' : 'Agent';+ var agentTitle = agentRunning ? 'Stop agent' : 'Agent mode (native tool calling)';+ var agentBtnCls = agentRunning ? 'active' : agentActive.trim();+ // Hidden in Codex chats (Codex on mobile is a coding-focused plain+ // chat, no phone-side tool execution).+ var agentBtn = isCodex ? '' :+ ('<button class="icon-btn '+agentBtnCls+'" id="agent-btn" onclick="'+agentClickHandler+'" aria-label="'+agentLabel+'" title="'+agentTitle+'">'++ '<span class="material-symbols-outlined">'+svgIcon('smart_toy')+'</span>'++ '</button>');++ // Thinking-toggle button REMOVED from mobile (user request): wasn't+ // working reliably and confused users. Thinking is now fully handled+ // under-the-hood: stripper silently drops any reasoning tokens regardless+ // of whether the model emitted canonical <think> or non-canonical tags.+ // The `thinking` variable stays as a constant `false` internally for the+ // few code paths that still reference it.++ el('app').innerHTML =+ '<div class="app-shell">' ++ '<div class="app-header">' ++ '<button class="icon-btn" onclick="window._toggleDrawer()" aria-label="Menu"><span class="material-symbols-outlined">'+svgIcon('menu')+'</span></button>' ++ '<span class="header-brand" aria-label="LU">' ++ '<img class="header-mark" src="/LU-monogram-white.png" alt="LU">' ++ '</span>' ++ modeTag ++ '<button class="model-badge" onclick="window._openModelPicker()" aria-label="Select model">' ++ '<span class="material-symbols-outlined" style="font-size:13px">'+svgIcon('auto_awesome')+'</span>' ++ '<span class="model-name">'+H(currentModel || 'Select model')+'</span>' ++ '<span class="material-symbols-outlined chev">'+svgIcon('expand_more')+'</span>' ++ '</button>' ++ agentBtn ++ '<button class="icon-btn'+pluginsActive+'" id="plugins-btn" onclick="window._openPluginsPicker()" aria-label="Plugins">' ++ '<span class="material-symbols-outlined">'+svgIcon('extension')+'</span>' ++ '</button>' ++ '</div>' ++ '<div class="chat-area" id="chat-area"></div>' ++ '<div class="input-bar">' ++ '<div class="img-preview-row" id="img-preview-row" style="display:none"></div>' ++ '<div class="input-row">' ++ '<button class="attach-btn" id="attach-btn" onclick="window._triggerAttach()" aria-label="Attach file"><span class="material-symbols-outlined">'+svgIcon('attach_file')+'</span></button>' ++ '<input type="file" id="file-input" accept="image/*" multiple style="display:none">' ++ '<textarea id="msg-input" rows="1" placeholder="'+(getAgentEnabled()?'Give the agent a goal…':'Message...')+'"></textarea>' ++ // Send-Button flips to a red Stop chip while a response is+ // in flight (streaming chat OR native tool loop). Without+ // this the only "stop" control was hidden in the header,+ // which users kept missing. Single id so CSS + handler both+ // route to the right action.+ (function(){+ var busy = streaming || agentRunning;+ var btnCls = busy ? 'send-btn cancel' : 'send-btn';+ var handler = busy ? 'window._cancelSend()' : 'window._doSend()';+ var label = busy ? 'Stop' : 'Send';+ var icon = busy ? 'stop' : 'arrow_upward';+ return '<button class="'+btnCls+'" id="send-btn" onclick="'+handler+'" aria-label="'+label+'" title="'+label+'"><span class="material-symbols-outlined">'+svgIcon(icon)+'</span></button>';+ })() ++ '</div>' ++ '</div>' ++ '</div>' ++ renderDrawer();++ setupInput();+ setupFileInput();+ renderChat();+ renderAttachments();+ }++ // ── Drawer ──+ function renderDrawer(){+ var chatHtml = '';+ if(!chats.length){+ chatHtml = '<div class="chat-empty">No chats yet</div>';+ }else{+ for(var i=0;i<chats.length;i++){+ var c = chats[i];+ var isActive = c.id===currentChatId;+ var tag = c.mode==='codex' ? '<span class="chat-item-mode">code</span>' : '';+ var icon = c.mode==='codex' ? 'terminal' : 'chat_bubble';+ chatHtml += '<div class="chat-item'+(isActive?' active':'')+'" onclick="window._loadChat(\''+c.id+'\')">' ++ '<span class="material-symbols-outlined">'+svgIcon(icon)+'</span>' ++ '<span class="chat-item-title">'+H(c.title||'Untitled')+'</span>' ++ tag ++ '<button class="chat-item-del" onclick="event.stopPropagation();window._deleteChat(\''+c.id+'\')" aria-label="Delete"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' ++ '</div>';+ }+ }++ return '<div class="drawer-backdrop'+(drawerOpen?' open':'')+'" onclick="window._toggleDrawer()"></div>' ++ '<aside class="drawer'+(drawerOpen?' open':'')+'">' ++ '<div class="drawer-header">' ++ '<span class="drawer-brand">' ++ '<img class="drawer-mark" src="/LU-monogram-white.png" alt="">' ++ '<span class="drawer-logo">LU</span>' ++ '</span>' ++ '<button class="drawer-close" onclick="window._toggleDrawer()" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' ++ '</div>' ++ '<div class="drawer-body">' ++ '<div class="new-row">' ++ '<button class="new-btn primary" onclick="window._newChat(\'lu\')"><span class="material-symbols-outlined">'+svgIcon('add')+'</span>Chat</button>' ++ '<button class="new-btn" onclick="window._newChat(\'codex\')"><span class="material-symbols-outlined">'+svgIcon('terminal')+'</span>Code</button>' ++ '</div>' ++ '<div class="section-label">Chats</div>' ++ chatHtml ++ '</div>' ++ '<div class="drawer-footer">' ++ '<button class="settings-btn" onclick="window._openSettingsSheet()">' ++ '<span class="material-symbols-outlined">'+svgIcon('tune')+'</span>Settings' ++ '</button>' ++ '<button class="disconnect-btn" onclick="window._disconnect()">' ++ '<span class="material-symbols-outlined">'+svgIcon('logout')+'</span>Disconnect' ++ '</button>' ++ '</div>' ++ '</aside>';+ }++ // ── Model picker ──+ window._openModelPicker = function(){+ var overlay = document.createElement('div');+ overlay.className = 'picker-overlay';+ overlay.onclick = function(e){if(e.target===overlay) document.body.removeChild(overlay);};+ var items = availableModels.length+ ? availableModels.map(function(name){+ var active = name === currentModel;+ return '<button class="picker-item'+(active?' active':'')+'" data-model="'+H(name)+'">' ++ '<span>'+H(name)+'</span>' ++ (active ? '<span class="material-symbols-outlined">'+svgIcon('check')+'</span>' : '') ++ '</button>';+ }).join('')+ : '<div class="picker-empty">No models found. Make sure your desktop backend is running with a model loaded.</div>';+ overlay.innerHTML =+ '<div class="picker-sheet">' ++ '<div class="picker-header">' ++ '<span class="picker-title">Select Model</span>' ++ '<button class="picker-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' ++ '</div>' ++ '<div class="picker-list">' + items + '</div>' ++ '</div>';+ document.body.appendChild(overlay);+ overlay.querySelector('.picker-close').onclick = function(){document.body.removeChild(overlay);};+ var buttons = overlay.querySelectorAll('.picker-item[data-model]');+ for(var i=0;i<buttons.length;i++){+ buttons[i].onclick = function(){+ var name = this.getAttribute('data-model');+ if(name){+ currentModel = name;+ try{localStorage.setItem('lu-mobile-model', name);}catch(_){}+ renderShell();+ }+ document.body.removeChild(overlay);+ };+ }+ };++ function setupInput(){+ var inp = el('msg-input');+ if(!inp) return;+ inp.addEventListener('input', function(){inp.style.height='auto';inp.style.height=Math.min(inp.scrollHeight,220)+'px';});+ inp.addEventListener('keydown', function(e){if(e.key==='Enter'&&!e.shiftKey&&!e.isComposing){e.preventDefault();window._doSend();}});+ }++ function setupFileInput(){+ var input = el('file-input');+ if(!input) return;+ input.onchange = function(e){+ var files = e.target.files;+ if(!files || !files.length) return;+ addFiles(files);+ input.value = '';+ };+ }++ function addFiles(fileList){+ var imageFiles = [];+ for(var i=0;i<fileList.length;i++){+ if(fileList[i].type && fileList[i].type.indexOf('image/')===0) imageFiles.push(fileList[i]);+ }+ if(!imageFiles.length) return;+ var promises = imageFiles.map(function(f){+ return new Promise(function(resolve){+ var reader = new FileReader();+ reader.onload = function(){+ var dataUrl = reader.result;+ var base64 = String(dataUrl).split(',')[1] || '';+ resolve({data:base64, mimeType:f.type||'image/png', name:f.name||'image.png'});+ };+ reader.onerror = function(){resolve(null);};+ reader.readAsDataURL(f);+ });+ });+ Promise.all(promises).then(function(items){+ items = items.filter(Boolean);+ pendingImages = pendingImages.concat(items).slice(0, 5);+ renderAttachments();+ });+ }++ function renderAttachments(){+ var row = el('img-preview-row');+ if(!row) return;+ if(!pendingImages.length){ row.style.display='none'; row.innerHTML=''; return; }+ row.style.display='flex';+ var html = '';+ for(var i=0;i<pendingImages.length;i++){+ var im = pendingImages[i];+ html += '<div class="img-preview">' ++ '<img src="data:'+H(im.mimeType)+';base64,'+im.data+'" alt="">' ++ '<button class="img-preview-del" onclick="window._removeImage('+i+')" aria-label="Remove"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' ++ '</div>';+ }+ row.innerHTML = html;+ }++ // ── Plan strip (todo_write) ───────────────────────────────────+ // Mirrors the desktop PlanBar. On a phone this matters more than on the+ // desktop: the screen is small, the transcript scrolls away in three tool+ // calls, and the whole reason to watch a run from a phone is to know where it+ // is. Per chat, in memory only — a plan outlives neither the run nor a reload.+ var todosByChat = {};++ function applyTodoWrite(raw){+ var key = currentChatId || '';+ var out = [];+ if(Object.prototype.toString.call(raw) === '[object Array]'){+ for(var i=0;i<raw.length && out.length<40;i++){+ var e = raw[i];+ if(!e || typeof e !== 'object') continue;+ var content = typeof e.content === 'string' ? e.content.trim() : '';+ if(!content) continue;+ // Anything unrecognised counts as not started: a typo must never mark+ // work done that was never done. Same rule as the desktop store.+ var st = (e.status === 'completed' || e.status === 'in_progress') ? e.status : 'pending';+ out.push({content: content.slice(0,200), status: st});+ }+ }+ todosByChat[key] = out;+ renderChat();+ if(out.length === 0) return 'Plan cleared.';+ var done = 0, current = null, lines = [];+ for(var j=0;j<out.length;j++){+ if(out[j].status === 'completed') done++;+ if(out[j].status === 'in_progress' && !current) current = out[j].content;+ lines.push((out[j].status==='completed'?'[x] ':out[j].status==='in_progress'?'[>] ':'[ ] ')+out[j].content);+ }+ return 'Plan updated ('+done+'/'+out.length+' done'+(current?', now: '+current:'')+').\n'+lines.join('\n');+ }++ function renderPlanStrip(){+ var t = todosByChat[currentChatId || ''];+ if(!t || !t.length) return '';+ var done = 0, items = '';+ for(var i=0;i<t.length;i++){+ if(t[i].status === 'completed') done++;+ var mark = t[i].status==='completed' ? '✓' : t[i].status==='in_progress' ? '▶' : '○';+ items += '<div class="plan-item plan-'+t[i].status+'">'+mark+' '+H(t[i].content)+'</div>';+ }+ return '<div class="plan-strip"><div class="plan-head">PLAN '+done+'/'+t.length+'</div>'+items+'</div>';+ }++ function renderChat(){+ var p = el('chat-area');+ if(!p) return;+ if(!msgs.length){+ var mode = getCurrentMode();+ var tag = mode==='codex' ? 'Coding Agent'+ : getAgentEnabled() ? 'Agent Mode'+ : (currentModel ? 'Ready' : 'Select a model');+ p.innerHTML =+ '<div class="chat-welcome">' ++ '<img class="chat-welcome-mark" src="/LU-monogram-white.png" alt="">' ++ '<div class="chat-welcome-logo">LU</div>' ++ '<div class="chat-welcome-tag">'+H(tag)+'</div>' ++ '</div>';+ return;+ }+ var html = '<div class="chat-messages" id="chat-msgs">';+ html += renderPlanStrip();+ for(var i=0;i<msgs.length;i++){+ var m = msgs[i];+ // Skip hidden tool-call history (persisted for continue capability+ // but not user-visible). The model sees them on the next turn.+ if(m.hidden) continue;+ var isUser = m.role==='user';+ var isLast = i===msgs.length-1;+ var typingCls = (streaming && isLast && !isUser) ? ' msg-typing' : '';+ html += '<div class="msg-group '+(isUser?'user':'bot')+'" data-msg-idx="'+i+'">';+ if(isUser && Array.isArray(m.images) && m.images.length){+ html += '<div class="msg-imgs">';+ for(var ii=0; ii<m.images.length; ii++){+ var im = m.images[ii];+ html += '<img src="data:'+H(im.mimeType||'image/png')+';base64,'+im.data+'" alt="">';+ }+ html += '</div>';+ }+ // Thinking block never rendered on mobile — the toggle was removed+ // (user request: "thinking toggle im Mobile ersetzt / rausgenommen").+ // Any accidentally captured reasoning text lives in `m.thinking` but+ // is NOT shown; the stripper drops incoming reasoning bytes at the+ // source so `m.thinking` usually stays empty anyway.+ // Agent steps (transient, during / after a run). These stay visible+ // but they are NOT part of msg.content — so the next user turn does+ // not see the ReAct scaffolding and cannot drift into that style.+ // Collapsed by default. The active (last) step of a running agent+ // is auto-opened so the user sees live progress.+ if(!isUser && Array.isArray(m.agentSteps) && m.agentSteps.length){+ html += '<div class="agent-steps">';+ for(var si=0; si<m.agentSteps.length; si++){+ var st = m.agentSteps[si];+ var stIcon = st.type==='thought' ? 'brain'+ : st.type==='action' ? 'smart_toy'+ : st.type==='observation' ? 'check'+ : st.type==='error' ? 'close'+ : 'auto_awesome';+ var openCls = st.open ? ' open' : '';+ // Live = step is still in flight (model streaming its JSON, or+ // the tool hasn't returned yet). Triggers the pulsing stripe CSS.+ var liveCls = st.live ? ' live' : '';+ var summary = String(st.content||'').replace(/\s+/g,' ').slice(0, 80);+ if((st.content||'').length > 80) summary += '…';+ var stepKey = m.id + ':' + si;+ html += '<div class="agent-step agent-'+H(st.type||'info')+openCls+liveCls+'">' ++ '<button class="agent-step-toggle" onclick="window._toggleAgentStep(\''+H(stepKey)+'\')">' ++ '<span class="material-symbols-outlined agent-step-icon">'+svgIcon(stIcon)+'</span>' ++ '<span class="agent-step-label">'+H(st.type||'info')+'</span>' ++ '<span class="agent-step-summary">'+H(summary)+'</span>' ++ '<span class="material-symbols-outlined agent-step-chev">'+svgIcon('expand_more')+'</span>' ++ '</button>' ++ '<div class="agent-step-content">'+renderMd(st.content||'')+'</div>' ++ '</div>';+ }+ html += '</div>';+ }+ if(m.content || !isUser){+ html += '<div class="msg-bubble '+(isUser?'user':'bot')+typingCls+'">';+ html += isUser ? H(m.content) : renderMd(m.content);+ html += '</div>';+ }+ if(isUser){+ html += '<div class="msg-actions msg-actions-user">';+ html += '<button class="msg-action-btn" title="Edit" onclick="window._editMsg(\''+m.id+'\')"><span class="material-symbols-outlined">'+svgIcon('pencil')+'</span></button>';+ html += '<button class="msg-action-btn" title="Copy" onclick="window._copyMsg('+i+')"><span class="material-symbols-outlined">'+svgIcon('content_copy')+'</span></button>';+ html += '</div>';+ } else {+ html += '<div class="msg-model">'+H(currentModel)+'</div>';+ html += '<div class="msg-actions">';+ var canRegen = !streaming && !agentRunning;+ html += '<button class="msg-action-btn" title="Copy" onclick="window._copyMsg('+i+')"><span class="material-symbols-outlined">'+svgIcon('content_copy')+'</span></button>';+ if(canRegen){+ html += '<button class="msg-action-btn" title="Regenerate" onclick="window._regenMsg(\''+m.id+'\')"><span class="material-symbols-outlined">'+svgIcon('refresh')+'</span></button>';+ }+ html += '</div>';+ }+ 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');+ if(cm) cm.scrollTop = cm.scrollHeight;+ }++ // Persistent expand/collapse state for individual code blocks. Keyed by+ // a stable hash of (language + content) so the state survives re-renders+ // of the chat. Same hash is used for the HTML-preview blob lookup.+ var codeBlockOpen = {};+ // Cache of code payloads — Preview button reads from here without having+ // to re-extract from the rendered DOM. Keyed by the same djb2 hash.+ var codeBlockSource = {};++ function djb2(str){+ var h = 5381;+ for(var i=0;i<str.length;i++){ h = ((h << 5) + h) ^ str.charCodeAt(i); h |= 0; }+ // Force unsigned + base36 for short stable ID+ return (h >>> 0).toString(36);+ }+ // Heuristic: this code block IS a renderable HTML document.+ function isHtmlSnippet(lang, raw){+ var l = (lang || '').toLowerCase();+ if(l === 'html' || l === 'htm' || l === 'xhtml' || l === 'svg') return true;+ var t = raw.trim().toLowerCase();+ if(!t) return false;+ if(t.indexOf('<!doctype html') === 0) return true;+ if(t.indexOf('<html') === 0) return true;+ if(t.indexOf('<svg') === 0 && t.indexOf('xmlns') > 0) return true;+ return false;+ }+ // Bug #4 / Feature #8: code blocks are collapsed by default if longer+ // than COLLAPSE_THRESHOLD lines (parity with desktop CodeBlock.tsx).+ // Renderable HTML/SVG also gets a "Preview" chip → opens a sandboxed+ // iframe overlay in `_openHtmlPreview`.+ var COLLAPSE_THRESHOLD = 4;++ function renderMd(text){+ var s = H(text);+ s = s.replace(/```(\w*)\n?([\s\S]*?)```/g, function(_, lang, code){+ var rawCode = code.replace(/\n$/, ''); // trim trailing newline+ var rawHtmlEscaped = H(rawCode);+ var lines = rawCode.split('\n');+ var lineCount = lines.length;+ var langLabel = (lang || 'code').toLowerCase();+ var key = djb2(langLabel + '\n' + rawCode);+ // Cache the original source so the Preview button can read it back.+ codeBlockSource[key] = { lang: langLabel, code: rawCode };+ var isLong = lineCount > COLLAPSE_THRESHOLD;+ var expanded = !isLong || codeBlockOpen[key] === true;+ var displayCode = expanded+ ? rawHtmlEscaped+ : H(lines.slice(0, COLLAPSE_THRESHOLD).join('\n'));+ var htmlPreview = isHtmlSnippet(langLabel, rawCode);+ var previewBtn = htmlPreview+ ? '<button class="cb-action" onclick="window._openHtmlPreview(\''+key+'\')" aria-label="Preview HTML"><span class="material-symbols-outlined">'+svgIcon('eye')+'</span><span class="cb-action-label">Preview</span></button>'+ : '';+ var toggleBtn = isLong+ ? '<button class="cb-toggle" onclick="window._toggleCodeBlock(\''+key+'\')"><span class="material-symbols-outlined cb-chev">'+svgIcon('expand_more')+'</span>'+(expanded?'Collapse':('Show all '+lineCount+' lines'))+'</button>'+ : '';+ return ''++ '<div class="cb-wrap'+(expanded?' open':'')+'" data-cb-id="'+key+'">'++ '<div class="cb-head">'++ '<span class="cb-lang">'+H(langLabel)+'</span>'++ '<div class="cb-actions">'++ previewBtn ++ '<button class="cb-action" onclick="window._copyCodeKey(\''+key+'\')" aria-label="Copy"><span class="material-symbols-outlined">'+svgIcon('content_copy')+'</span><span class="cb-action-label">Copy</span></button>'++ '</div>'++ '</div>'++ '<pre class="cb-pre"><code>'+displayCode+'</code></pre>'++ toggleBtn ++ '</div>';+ });+ s = s.replace(/`([^`]+)`/g,'<code>$1</code>');+ s = s.replace(/\*\*(.+?)\*\*/g,'<b>$1</b>');+ return s;+ }++ // Toggle handler for the "Show all N lines" / "Collapse" button.+ window._toggleCodeBlock = function(key){+ codeBlockOpen[key] = !codeBlockOpen[key];+ renderChat();+ };+ // Copy handler that reads from our cache (no DOM scraping → handles+ // collapsed blocks correctly).+ window._copyCodeKey = function(key){+ var src = codeBlockSource[key];+ if(src && src.code) navigator.clipboard.writeText(src.code).catch(function(){});+ };+ // Feature #8: full-screen sandboxed HTML preview. Opens an iframe with+ // `srcdoc` + sandbox flags so user-supplied JS can't reach the parent+ // page. "Open in new tab" button hands the data: URL to the host+ // browser for full inspection. Tap backdrop or close icon to dismiss.+ window._openHtmlPreview = function(key){+ var src = codeBlockSource[key];+ if(!src) return;+ var raw = src.code || '';+ var lang = (src.lang || '').toLowerCase();+ var doc = raw;+ // Bare SVG → wrap so the iframe centres it.+ if(lang === 'svg' || (raw.trim().toLowerCase().indexOf('<svg') === 0 && raw.indexOf('xmlns') > 0)){+ doc = '<!doctype html><html><head><meta charset="utf-8"><title>SVG Preview</title>' ++ '<style>html,body{margin:0;padding:0;background:#0e0e0e;color:#ffffff;height:100%;display:flex;align-items:center;justify-content:center;font-family:system-ui,sans-serif}svg{max-width:100%;max-height:100%}</style>' ++ '</head><body>'+raw+'</body></html>';+ } else if(raw.trim().toLowerCase().indexOf('<!doctype') !== 0 &&+ raw.trim().toLowerCase().indexOf('<html') !== 0){+ // Snippet-only HTML → wrap in a minimal doc so meta-charset is set.+ doc = '<!doctype html><html><head><meta charset="utf-8"><title>HTML Preview</title>' ++ '<style>body{margin:0;padding:16px;font-family:system-ui,-apple-system,sans-serif}</style>' ++ '</head><body>'+raw+'</body></html>';+ }+ var overlay = document.createElement('div');+ overlay.className = 'html-preview-overlay';+ overlay.onclick = function(e){ if(e.target === overlay) document.body.removeChild(overlay); };+ var dataUrl = 'data:text/html;charset=utf-8;base64,' + btoa(unescape(encodeURIComponent(doc)));+ overlay.innerHTML =+ '<div class="html-preview-shell">' ++ '<div class="html-preview-header">' ++ '<span class="html-preview-title"><span class="material-symbols-outlined">'+svgIcon('eye')+'</span>HTML Preview</span>' ++ '<div class="html-preview-actions">' ++ '<button class="html-preview-action" id="hpv-open" aria-label="Open in new tab"><span class="material-symbols-outlined">'+svgIcon('open_in_new')+'</span></button>' ++ '<button class="html-preview-action" id="hpv-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' ++ '</div>' ++ '</div>' ++ '<iframe class="html-preview-frame" sandbox="allow-scripts" referrerpolicy="no-referrer"></iframe>' ++ '</div>';+ document.body.appendChild(overlay);+ var iframe = overlay.querySelector('.html-preview-frame');+ if(iframe){+ // srcdoc is the most reliable cross-mobile way to push HTML in+ // without escaping pain. Falls back to data URL if browser blocks.+ try{ iframe.srcdoc = doc; }+ catch(_){ iframe.src = dataUrl; }+ }+ var openBtn = overlay.querySelector('#hpv-open');+ if(openBtn) openBtn.onclick = function(){ window.open(dataUrl, '_blank'); };+ var closeBtn = overlay.querySelector('#hpv-close');+ if(closeBtn) closeBtn.onclick = function(){ document.body.removeChild(overlay); };+ };++ // ── Exposed handlers ──+ window._toggleDrawer = function(){+ drawerOpen = !drawerOpen;+ var d = document.querySelector('.drawer');+ var b = document.querySelector('.drawer-backdrop');+ if(d) d.classList.toggle('open', drawerOpen);+ if(b) b.classList.toggle('open', drawerOpen);+ };+ window._newChat = function(mode){+ syncCurrentChat();+ createChat(mode==='codex'?'codex':'lu');+ drawerOpen = false;+ renderShell();+ };+ window._loadChat = function(id){+ loadChat(id);+ drawerOpen = false;+ renderShell();+ };+ window._deleteChat = function(id){+ deleteChat(id);+ renderShell();+ var d=document.querySelector('.drawer'); if(d) d.classList.add('open');+ var bd=document.querySelector('.drawer-backdrop'); if(bd) bd.classList.add('open');+ drawerOpen = true;+ };+ // _toggleThinking removed — mobile has no thinking toggle anymore.+ // Kept as a no-op stub so stale handlers (any lingering cached page)+ // don't throw when clicked.+ window._toggleThinking = function(){};+ window._toggleAgent = function(){+ if(streaming || agentRunning) return;+ setAgentEnabled(!getAgentEnabled());+ renderShell();+ };+ window._stopAgent = function(){ agentAbort = true; };++ // Single-button cancel: stops whichever mode is currently running.+ // Streaming chat → abort the fetch. Agent loop → flip the agentAbort+ // flag so the next iteration bails cleanly. User can hit this from+ // the input-bar Send (which flips to Stop while busy) OR from the+ // header Agent icon (also flips to Stop while an agent is running).+ window._cancelSend = function(){+ if(streaming && abortCtrl){+ try{ abortCtrl.abort(); }catch(_){}+ }+ if(agentRunning){+ agentAbort = true;+ }+ };+ window._triggerAttach = function(){+ var f = el('file-input'); if(f) f.click();+ };+ window._removeImage = function(idx){+ pendingImages.splice(idx,1);+ renderAttachments();+ };+ window._setCaveman = function(lv){+ var c = findChat(currentChatId); if(c){ c.caveman = lv; persistChats(); }+ updatePluginsPicker();+ updatePluginsHeaderBadge();+ };+ window._setPersona = function(id){+ var c = findChat(currentChatId);+ if(c){+ c.personaId = id;+ c.personaEnabled = true; // picking a persona turns it on+ persistChats();+ }+ updatePluginsPicker();+ updatePluginsHeaderBadge();+ };+ function updatePluginsHeaderBadge(){+ var btn = el('plugins-btn');+ if(!btn) return;+ if(getCaveman()!=='off' || getPersonaEnabled()) btn.classList.add('active');+ else btn.classList.remove('active');+ }+ function updatePluginsPicker(){+ var overlay = document.querySelector('.picker-overlay.plugins-picker');+ if(!overlay) return;+ overlay.querySelector('.picker-list').innerHTML = pluginsPickerBodyHtml();+ bindPluginsPicker(overlay);+ }+ // Each time the sheet opens, both sections start collapsed+ var pluginsOpen = {caveman:false, persona:false};+ function pluginsPickerBodyHtml(){+ var cm = getCaveman();+ var pid = getPersonaId();+ var penabled = getPersonaEnabled();+ var chips = ['off','lite','full','ultra'].map(function(lv){+ var label = lv==='off' ? 'Off' : lv.charAt(0).toUpperCase()+lv.slice(1);+ return '<button class="caveman-chip'+(cm===lv?' active':'')+'" data-caveman="'+lv+'">'+label+'</button>';+ }).join('');+ var personas = PERSONAS.map(function(p){+ var active = penabled && pid===p.id;+ return '<button class="picker-item'+(active?' active':'')+'" data-persona="'+H(p.id)+'">' ++ '<span>'+H(p.name)+'</span>' ++ (active ? '<span class="material-symbols-outlined">'+svgIcon('check')+'</span>' : '') ++ '</button>';+ }).join('');+ var cavemanLabel = cm==='off' ? '' : cm.charAt(0).toUpperCase()+cm.slice(1);+ var activePersona = PERSONAS.find(function(p){return p.id===pid;});+ var personaLabel = penabled && activePersona ? activePersona.name : '';++ return '<div class="plug-folder">' ++ '<div class="plug-row'+(pluginsOpen.caveman?' open':'')+'" data-toggle="caveman">' ++ '<span class="plug-name">Caveman Mode</span>' ++ (cavemanLabel ? '<span class="plug-value">'+H(cavemanLabel)+'</span>' : '') ++ '<span class="material-symbols-outlined plug-chev">'+svgIcon('expand_more')+'</span>' ++ '</div>' ++ (pluginsOpen.caveman ? '<div class="caveman-row">'+chips+'</div>' : '') ++ '</div>' ++ '<div class="plug-folder">' ++ '<div class="plug-row'+(pluginsOpen.persona?' open':'')+'" data-toggle="persona">' ++ '<span class="plug-name">Persona</span>' ++ (personaLabel ? '<span class="plug-value">'+H(personaLabel)+'</span>' : '') ++ '<label class="plug-switch" onclick="event.stopPropagation()" aria-label="Toggle persona">' ++ '<input type="checkbox" data-persona-enabled'+(penabled?' checked':'')+'>' ++ '<span class="plug-switch-track"></span>' ++ '</label>' ++ '<span class="material-symbols-outlined plug-chev">'+svgIcon('expand_more')+'</span>' ++ '</div>' ++ (pluginsOpen.persona ? '<div class="plugins-persona-list">'+personas+'</div>' : '') ++ '</div>';+ }+ function bindPluginsPicker(overlay){+ var chips = overlay.querySelectorAll('.caveman-chip[data-caveman]');+ for(var i=0;i<chips.length;i++){+ chips[i].onclick = function(){ window._setCaveman(this.getAttribute('data-caveman')); };+ }+ var pitems = overlay.querySelectorAll('.picker-item[data-persona]');+ for(var j=0;j<pitems.length;j++){+ pitems[j].onclick = function(){ window._setPersona(this.getAttribute('data-persona')); };+ }+ var toggles = overlay.querySelectorAll('.plug-row[data-toggle]');+ for(var k=0;k<toggles.length;k++){+ toggles[k].onclick = function(){+ var key = this.getAttribute('data-toggle');+ pluginsOpen[key] = !pluginsOpen[key];+ updatePluginsPicker();+ };+ }+ var pswitch = overlay.querySelector('[data-persona-enabled]');+ if(pswitch){+ pswitch.onchange = function(){+ var c = findChat(currentChatId);+ if(c){+ c.personaEnabled = !!this.checked;+ // If enabling without a picked persona, auto-open the list so user can pick+ if(c.personaEnabled && c.personaId==='unrestricted'){ pluginsOpen.persona = true; }+ persistChats();+ }+ updatePluginsPicker();+ updatePluginsHeaderBadge();+ };+ }+ }+ window._openPluginsPicker = function(){+ pluginsOpen = {caveman:false, persona:false}; // always open collapsed+ var overlay = document.createElement('div');+ overlay.className = 'picker-overlay plugins-picker';+ overlay.onclick = function(e){if(e.target===overlay) document.body.removeChild(overlay);};+ overlay.innerHTML =+ '<div class="picker-sheet">' ++ '<div class="picker-header">' ++ '<span class="picker-title">Plugins</span>' ++ '<button class="picker-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' ++ '</div>' ++ '<div class="picker-list">' + pluginsPickerBodyHtml() + '</div>' ++ '</div>';+ document.body.appendChild(overlay);+ overlay.querySelector('.picker-close').onclick = function(){document.body.removeChild(overlay);};+ bindPluginsPicker(overlay);+ };++ // ── Settings sheet — Remote Permissions only ──+ // Mirrors the desktop's Settings → Remote Access → Permissions section.+ // READS /remote-api/permissions; it cannot write. Each row gates a category+ // of endpoints server-side (see proxy_ollama / proxy_comfyui in remote.rs),+ // and the server ignores a permissions POST from a paired device — a scope a+ // phone can grant itself is not a scope. The rows are shown anyway because+ // this is the only place the phone can see what it is allowed to do.+ var PERMISSION_META = [+ {key:'filesystem', label:'Filesystem', desc:'Agent can read/write files + run code on the desktop.'},+ {key:'downloads', label:'Downloads', desc:'Agent can trigger model pulls / installs (Ollama + ComfyUI).'},+ {key:'process_control', label:'Process Control', desc:'Reach ComfyUI and Ollama on the desktop, and start or stop them.'}+ ];++ function fetchRemotePerms(){+ return fetch('/remote-api/permissions',{+ headers:{'Authorization':'Bearer '+TOKEN}+ }).then(absorbRefresh).then(function(r){+ if(r.status===401){ clearAuthAndReload(); throw new Error('401'); }+ if(!r.ok) throw new Error('HTTP '+r.status);+ return r.json();+ }).then(function(p){+ remotePerms = {+ filesystem: !!p.filesystem,+ downloads: !!p.downloads,+ process_control: !!p.process_control+ };+ return remotePerms;+ });+ }++ window._openSettingsSheet = function(){+ var overlay = document.createElement('div');+ overlay.className = 'picker-overlay';+ overlay.onclick = function(e){ if(e.target===overlay) document.body.removeChild(overlay); };++ function renderBody(){+ var rows = PERMISSION_META.map(function(m){+ var on = !!remotePerms[m.key];+ return '<label class="perm-row" data-key="'+m.key+'">' ++ '<div class="perm-text">' ++ '<div class="perm-label">'+H(m.label)+'</div>' ++ '<div class="perm-desc">'+H(m.desc)+'</div>' ++ '</div>' ++ '<span class="plug-switch">' ++ '<input type="checkbox" data-pk="'+m.key+'" disabled'+(on?' checked':'')+'>' ++ '<span class="plug-switch-track"></span>' ++ '</span>' ++ '</label>';+ }).join('');+ return '<div class="settings-section-label">Remote Permissions</div>' ++ '<div class="perm-note">What this session is allowed to do on the desktop. Set on the desktop, in Settings → Remote Access — a phone cannot grant itself access.</div>' ++ rows;+ }++ overlay.innerHTML =+ '<div class="picker-sheet">' ++ '<div class="picker-header">' ++ '<span class="picker-title">Settings</span>' ++ '<button class="picker-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' ++ '</div>' ++ '<div class="picker-list" id="settings-body"><div class="perm-loading">Loading…</div></div>' ++ '</div>';+ document.body.appendChild(overlay);+ overlay.querySelector('.picker-close').onclick = function(){ document.body.removeChild(overlay); };++ fetchRemotePerms().then(function(){+ var body = overlay.querySelector('#settings-body');+ if(!body) return;+ body.innerHTML = renderBody();+ }).catch(function(e){+ var body = overlay.querySelector('#settings-body');+ if(body) body.innerHTML = '<div class="perm-loading" style="color:var(--error)">Failed to load: '+H(String(e && e.message || e))+'</div>';+ });+ };++ window._copyMsg = function(idx){+ if(msgs[idx]) navigator.clipboard.writeText(msgs[idx].content).catch(function(){});+ };+ window._copyCode = function(btn){+ var pre = btn.parentElement;+ if(!pre) return;+ var code = pre.querySelector('code');+ if(code) navigator.clipboard.writeText(code.textContent).catch(function(){});+ };+ window._toggleThink = function(msgId){+ for(var i=0;i<msgs.length;i++){+ if(msgs[i].id === msgId){+ msgs[i].thinkingOpen = !msgs[i].thinkingOpen;+ renderChat();+ return;+ }+ }+ };+ window._toggleAgentStep = function(stepKey){+ var parts = stepKey.split(':');+ if(parts.length < 2) return;+ var msgId = parts[0], idx = Number(parts[1]);+ for(var i=0;i<msgs.length;i++){+ if(msgs[i].id === msgId){+ if(Array.isArray(msgs[i].agentSteps) && msgs[i].agentSteps[idx]){+ msgs[i].agentSteps[idx].open = !msgs[i].agentSteps[idx].open;+ renderChat();+ }+ return;+ }+ }+ };+ // ── Regenerate: drop the given assistant msg + everything after, resend the preceding user msg.+ // Parity with desktop useChat.ts regenerateMessage().+ window._regenMsg = function(msgId){+ if(streaming || agentRunning) return;+ var idx = -1;+ for(var i=0;i<msgs.length;i++){ if(msgs[i].id === msgId){ idx = i; break; } }+ if(idx < 1) return;+ var userMsg = msgs[idx-1];+ if(!userMsg || userMsg.role !== 'user') return;+ // Truncate to just-before-user, then replay the user text+ msgs.splice(idx-1);+ syncCurrentChat();+ renderChat();+ // Reuse the send path by re-injecting the user text.+ var input = el('msg-input'); if(input){ input.value = userMsg.content; window._doSend(); }+ else {+ // Fallback: manually push and dispatch+ var u = mkMsg('user', userMsg.content, userMsg.images ? {images: userMsg.images} : null);+ msgs.push(u); msgs.push(mkMsg('assistant',''));+ renderChat();+ }+ };+ // ── Edit: turn user bubble into inline textarea, save rewrites + resends from that point.+ // Parity with desktop useChat.ts editAndResend().+ window._editMsg = function(msgId){+ if(streaming || agentRunning) return;+ var idx = -1;+ for(var i=0;i<msgs.length;i++){ if(msgs[i].id === msgId){ idx = i; break; } }+ if(idx < 0 || msgs[idx].role !== 'user') return;+ var node = document.querySelector('.msg-group[data-msg-idx="'+idx+'"] .msg-bubble.user');+ if(!node) return;+ var original = msgs[idx].content;+ node.classList.add('editing');+ node.innerHTML =+ '<textarea class="msg-edit-area" id="msg-edit-ta">'+H(original)+'</textarea>' ++ '<div class="msg-edit-row">' ++ '<button class="msg-edit-btn" id="msg-edit-cancel">Cancel</button>' ++ '<button class="msg-edit-btn primary" id="msg-edit-save">Save & Resend</button>' ++ '</div>';+ var ta = el('msg-edit-ta');+ if(ta){ ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }+ el('msg-edit-cancel').onclick = function(){ renderChat(); };+ el('msg-edit-save').onclick = function(){+ var newVal = el('msg-edit-ta').value.trim();+ if(!newVal){ renderChat(); return; }+ // Drop this message and everything after, then resend with the new content.+ msgs.splice(idx);+ syncCurrentChat();+ renderChat();+ var inp = el('msg-input'); if(inp){ inp.value = newVal; window._doSend(); }+ };+ };+ window._disconnect = function(){+ localStorage.removeItem('lu-remote-token');+ location.reload();+ };++ // ── Mirror to desktop ──+ // LU mode → appends to the desktop's dispatched Remote conversation.+ // Codex mode → creates / appends to a desktop Codex conversation named+ // after the mobile chat title. That way "codex chat on+ // mobile must also show up in Codex in the app with+ // content" (user request).+ function postChatEvent(role, content){+ if(!content) return;+ // Safety filter: never mirror bare "Continue." to the desktop.+ // Legacy from the old ReAct loop; kept as defense in depth.+ if(role === 'user' && /^\s*continue\.?\s*$/i.test(content)) return;+ var c = findChat(currentChatId);+ if(!c) return;+ var mode = c.mode === 'codex' ? 'codex' : 'lu';+ try{+ fetch('/remote-api/chat-event',{+ method:'POST',+ headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},+ body:JSON.stringify({+ role:role,+ content:content,+ model:currentModel||'',+ mode:mode,+ chat_id:c.id||'',+ chat_title:c.title||''+ })+ }).catch(function(){});+ }catch(_){}+ }++ // ── Send ──+ window._doSend = function(){+ var inp = el('msg-input');+ var text = inp.value.trim();+ var hasImages = pendingImages.length > 0;+ if((!text && !hasImages) || streaming || agentRunning) return;+ if(!currentModel){window._openModelPicker();return;}++ var userMsg = mkMsg('user', text, hasImages ? {images: pendingImages.slice()} : null);+ msgs.push(userMsg);+ msgs.push(mkMsg('assistant', ''));++ inp.value='';inp.style.height='auto';+ var sentImages = pendingImages.slice();+ pendingImages = [];+ renderAttachments();++ // Mirror user message to desktop (text only)+ postChatEvent('user', text);++ // Agent / Codex mode? Use native Ollama tool calling instead of+ // plain streaming chat. Codex chats ALWAYS run tools (no toggle),+ // matching desktop Codex which is agentic by design. Plain LU chats+ // only run tools when the user toggled Agent on in the header.+ var isCodexChat = getCurrentMode() === 'codex';+ if(getAgentEnabled() || isCodexChat){+ var toolNames = isCodexChat ? CODEX_TOOLS : AGENT_ALL_TOOLS;+ var sysPrompt = buildSystemPrompt();+ var kindLabel = isCodexChat ? 'Coding Agent' : 'Agent';+ runToolLoop(sysPrompt, toolNames, kindLabel);+ return;+ }++ streaming=true;+ // Re-render the input bar so the Send-Button flips to the red Stop+ // chip. Without this the user has no visible way to cancel a chat+ // that hangs on an over-eager thinking model.+ renderShell();+ renderChat();++ // Build API messages+ var apiMsgs = [];+ var sys = buildSystemPrompt();+ if(sys) apiMsgs.push({role:'system',content:sys});+ var cm = getCaveman();+ for(var i=0;i<msgs.length-1;i++){+ var m = msgs[i];+ var content = m.content;+ // Caveman per-message reminder — prepend on every user message.+ // Parity with desktop (useChat.ts line 142): the reminder fires+ // unconditionally so the model doesn't drift on turn 2+. Without+ // this, thinking-compatible models silently dropped Caveman style+ // after the first response (was: only !isThinkingCompatible).+ if(m.role==='user' && cm!=='off' && CAVEMAN_REMINDERS[cm]){+ content = CAVEMAN_REMINDERS[cm] + '\n' + content;+ }+ var apiMsg = {role:m.role, content:content};+ if(m.images && m.images.length){ apiMsg.images = m.images.map(function(im){return im.data;}); }+ apiMsgs.push(apiMsg);+ }++ // Token budget: 16 384 is a balance between "no truncation of the+ // assistant's visible message" (previous default of 4000 was too low)+ // and "don't let tagged-thinking models loop forever" (true `-1`+ // caused Gemma 3/4 to think without ever emitting an answer). 16 k is+ // enough for the longest reasonable agent reply plus deep thinking.+ // v2.4.6 Bug L: dropped num_gpu:99 — see nativeToolChat() comment above.+ var body = {model:currentModel, messages:apiMsgs, stream:true, options:{num_predict:16384}};+ // Tri-state: for thinking-capable models we normally send explicit+ // true|false. Explicit `false` tells Ollama to SKIP thinking (saves+ // tokens) instead of silently letting the model emit <think> tags we'd+ // then have to hide. Non-thinking models: omit the field entirely.+ //+ // Bug #80 parity: Gemma 3/4 with `think:false` drops into PLAIN-TEXT+ // structured planning ("Plan:" / "Constraint Checklist:" …) that no+ // tag-stripper can clean. For these models with the toggle OFF we+ // instead OMIT `think`, which makes Ollama emit tagged thinking that+ // our stripper handles cleanly. UX is the same (clean answer) — the+ // trade-off is hidden token spend on internal reasoning.+ if(isThinkingCompatible(currentModel)){+ if(thinking){+ body.think = true;+ } else if(!isPlainTextPlanner(currentModel)){+ body.think = false;+ }+ // else: leave body.think undefined → Ollama default = tagged thinking,+ // stripped at render time.+ }++ abortCtrl = new AbortController();+ fetch('/api/chat',{+ method:'POST',+ headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},+ body:JSON.stringify(body),+ signal:abortCtrl.signal+ })+ .then(absorbRefresh)+ .then(function(r){+ if(r.status===401){+ // #73: without this the reload swallowed the just-sent message —+ // stash it so it is back in the composer after re-pairing.+ try{+ var lastUser = null;+ for(var qi=msgs.length-1; qi>=0; qi--){ if(msgs[qi].role==='user'){ lastUser=msgs[qi].content; break; } }+ if(lastUser) localStorage.setItem('lu-remote-draft', lastUser);+ }catch(_){}+ clearAuthAndReload();+ return;+ }+ if(!r.ok){+ // Retry without the think field at all if the server rejects it+ // (old Ollama or model that refuses the flag).+ if(r.status===400 && ('think' in body)){+ delete body.think;+ return fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},body:JSON.stringify(body),signal:abortCtrl.signal}).then(absorbRefresh).then(streamResponse);+ }+ msgs[msgs.length-1].content='Error: HTTP '+r.status;+ finishStream();+ return;+ }+ streamResponse(r);+ })+ .catch(function(ex){+ if(ex.name!=='AbortError') msgs[msgs.length-1].content='Connection error';+ finishStream();+ });+ };++ // ── Native tool-calling loop ─────────────────────────────────────+ //+ // Replaces the old ReAct JSON loop with Ollama's native /api/chat+ // `tools` parameter. The model returns structured `tool_calls[]`+ // instead of freeform JSON we had to parse. Reliability goes from+ // ~60% to ~99% because the model uses its trained tool-call format+ // instead of trying to emit valid JSON in its content.+ // Append a structured agent step to the current assistant message.+ // Steps render as small colored cards ABOVE the bubble; they are NOT+ // part of msg.content, so the next user turn does NOT see tool-call+ // scaffolding and the model cannot drift into that style.+ function appendAgentStep(type, content, meta){+ var idx = msgs.length-1;+ if(idx < 0 || msgs[idx].role !== 'assistant') return;+ if(!Array.isArray(msgs[idx].agentSteps)) msgs[idx].agentSteps = [];+ // ALL steps always start collapsed (user request). Pulsing CSS stripe+ // on `.live` rows shows in-flight status; the content itself stays+ // behind the chevron until the user taps to expand.+ for(var p=0; p<msgs[idx].agentSteps.length; p++){ msgs[idx].agentSteps[p].open = false; }+ var step = {type:type, content:content, ts:Date.now(), open:false, live:false};+ if(meta && typeof meta === 'object'){ for(var k in meta) if(Object.prototype.hasOwnProperty.call(meta,k)) step[k]=meta[k]; }+ msgs[idx].agentSteps.push(step);+ renderChat();+ }++ // ── Native tool-calling loop ──+ //+ // Uses Ollama's /api/chat with `tools` parameter (non-streaming,+ // stream:false). The model returns structured `tool_calls[]` that we+ // execute via the existing runAgentTool() bridge, then feed results+ // back as `role:'tool'` messages. Loop until the model responds with+ // no tool_calls (= final answer) or we hit maxIter.+ //+ // Why non-streaming? Ollama's tool calling requires stream:false to+ // return structured tool_calls[]. The trade-off vs the old streaming+ // ReAct loop: no live token-by-token display, but near-100% tool-call+ // reliability instead of ~60% JSON parse success.+ function runToolLoop(systemPrompt, toolNames, kindLabel){+ agentRunning = true;+ agentAbort = false;+ abortCtrl = new AbortController();+ renderShell(); // flips Send button to Stop+ renderChat();++ var maxIter = 50; // matches desktop v24 AgentBudget default+ 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.+ // Hidden messages (tool-call history from previous turns) are included+ // so the model sees what it did before (continue capability, parity+ // with original Codex CLI).+ var apiMessages = [];+ var apiStartLen = 0; // track where loop-generated messages begin+ if(systemPrompt) apiMessages.push({role:'system', content:systemPrompt});+ var cm = getCaveman();+ for(var k=0; k<msgs.length-1; k++){+ var m = msgs[k];+ var content = m.content;+ if(m.role==='user' && cm!=='off' && CAVEMAN_REMINDERS[cm]){+ content = CAVEMAN_REMINDERS[cm] + '\n' + content;+ }+ // A restored tool result is a PREVIOUS turn's work, already summarised+ // by the answer the user can see, so it comes back tighter than the+ // in-run cap. One exception, and it is the stability rule: a result the+ // run already sent capped at 4k is restored at exactly those 4k bytes,+ // otherwise the same result would arrive with different bytes depending+ // on which turn asked for it.+ if(m.role === 'tool' && !isDecayedAt(content, DECAY_RESULT_CHARS)){+ content = capToolResult(content, RESTORE_RESULT_CHARS);+ }+ var apiMsg = {role: m.role, content: content};+ // Carry over tool_calls on assistant messages so Ollama sees the+ // full native tool-call history (assistant→tool pairs).+ if(m.tool_calls) apiMsg.tool_calls = m.tool_calls;+ if(m.images && m.images.length){ apiMsg.images = m.images.map(function(im){return im.data;}); }+ apiMessages.push(apiMsg);+ }++ apiStartLen = apiMessages.length; // everything after this was added during the loop++ // Show a "thinking" step while the first call is in flight+ appendAgentStep('thought', kindLabel+' is thinking...', {live:true});+ var thinkingStepIdx = (target.agentSteps || []).length - 1;++ function step(){+ if(agentAbort){+ appendAgentStep('error', kindLabel+' stopped by user.');+ finishToolLoop(null);+ return;+ }+ if(iter >= maxIter){+ appendAgentStep('error', kindLabel+' stopped: max iterations reached.');+ finishToolLoop(null);+ return;+ }+ iter++;++ // Decay first, then compaction, and the order is the point (plan A1). A+ // decayed history is what the budget check should be looking at;+ // measuring full results and then dropping whole messages throws away+ // old context that would have fitted at 4k.+ decayToolResults(apiMessages, 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).+ if(thinkingStepIdx >= 0 && target.agentSteps && target.agentSteps[thinkingStepIdx]){+ target.agentSteps.splice(thinkingStepIdx, 1);+ thinkingStepIdx = -1;+ renderChat();+ }++ // Handle thinking content (native Ollama field + inline tags)+ var keepThinking = thinking && isThinkingCompatible(currentModel);+ var stripped = stripThinkTags(res.content, keepThinking);+ var turnContent = stripped.content;+ var turnThinking = stripped.thinking;+ // Also pick up the native thinking field from Ollama+ if(res.thinking){+ if(keepThinking){+ turnThinking = turnThinking ? turnThinking+'\n'+res.thinking : res.thinking;+ }+ }+ if(turnThinking && target){+ target.thinking = (target.thinking ? target.thinking+'\n' : '') + turnThinking;+ }++ // 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){+ // 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;+ }++ // Push the assistant message with tool_calls into the history+ // so Ollama sees the proper assistant→tool message pairs.+ apiMessages.push({+ role: 'assistant',+ content: turnContent || '',+ tool_calls: res.toolCalls.map(function(tc){+ return {function:{name:tc.function.name, arguments:tc.function.arguments}};+ })+ });++ // Execute each tool call sequentially, show steps in UI+ var tcIndex = 0;+ function execNext(){+ if(agentAbort){+ appendAgentStep('error', kindLabel+' stopped by user.');+ finishToolLoop(null);+ return;+ }+ if(tcIndex >= res.toolCalls.length){+ // All tools executed — loop back for next model turn+ renderChat();+ step();+ return;+ }++ var tc = res.toolCalls[tcIndex];+ var toolName = tc.function.name;+ var toolArgs = tc.function.arguments || {};+ var argsPretty = '';+ try{ argsPretty = JSON.stringify(toolArgs); }catch(_){ argsPretty = '{}'; }++ // Show "running" action step+ appendAgentStep('action', '`'+toolName+'` '+argsPretty, {toolName:toolName, args:toolArgs, live:true});+ var actionIdx = (target.agentSteps || []).length - 1;++ runAgentTool(toolName, toolArgs).then(function(observation){+ var obs = String(observation || '');++ // Mark action as completed+ if(target.agentSteps && target.agentSteps[actionIdx]){+ target.agentSteps[actionIdx].live = false;+ }+ appendAgentStep('observation', obs);++ // Push tool result into the LLM history. The iteration rides with+ // it so decayToolResults can tell the newest results (kept whole)+ // from the ones that have done their job (A1).+ apiMessages.push({role:'tool', content:obs, iter:iter});++ // 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){+ var errMsg = String(e && e.message || e);+ if(target.agentSteps && target.agentSteps[actionIdx]){+ target.agentSteps[actionIdx].live = false;+ }+ appendAgentStep('error', errMsg);++ // Push error as tool result so the model can adapt+ apiMessages.push({role:'tool', content:'Error: '+errMsg, iter:iter});++ 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();+ });+ }++ execNext();+ }).catch(function(e){+ // Remove the thinking placeholder if still present+ if(thinkingStepIdx >= 0 && target.agentSteps && target.agentSteps[thinkingStepIdx]){+ target.agentSteps.splice(thinkingStepIdx, 1);+ thinkingStepIdx = -1;+ }++ if(e && e.name === 'AbortError'){+ appendAgentStep('error', 'Stopped.');+ finishToolLoop(null);+ return;+ }+ var errMsg = (e && e.message) || String(e);+ if(errMsg === 'TOOLS_NOT_SUPPORTED'){+ appendAgentStep('error', 'This model does not support tool calling. Pick a tool-capable model (Qwen 3, Llama 3.1+, Gemma 4).');+ finishToolLoop(null);+ return;+ }+ appendAgentStep('error', kindLabel+' error: '+errMsg);+ finishToolLoop(null);+ });+ }++ function finishToolLoop(finalAnswer){+ agentRunning = false;+ agentAbort = false;+ abortCtrl = null;++ // ── Continue capability (parity with original Codex CLI) ────────+ // Persist the tool-call history from THIS turn as hidden messages+ // in msgs[]. On the NEXT turn, the history builder (line ~2802)+ // includes them in apiMessages so the model sees what it did before.+ // Hidden messages are skipped by renderChat() — the user only sees+ // the final answer, but the model sees the full tool-call chain.+ var toolHistory = [];+ for(var hi = apiStartLen; hi < apiMessages.length; hi++){+ var am = apiMessages[hi];+ toolHistory.push(mkMsg(am.role, am.content || '', {+ hidden: true,+ tool_calls: am.tool_calls || undefined+ }));+ }+ if(toolHistory.length > 0){+ // Splice BEFORE target (the visible final-answer message) so+ // the conversation order is: user → hidden tool chain → answer.+ var targetIdx = msgs.indexOf(target);+ if(targetIdx >= 0){+ // splice(targetIdx, 0, ...items) — Array.prototype.splice.apply+ // for ES5 compat (mobile JS can't use spread in all engines).+ var spliceArgs = [targetIdx, 0];+ for(var si = 0; si < toolHistory.length; si++) spliceArgs.push(toolHistory[si]);+ Array.prototype.splice.apply(msgs, spliceArgs);+ }+ }++ // The visible answer — if finalAnswer is null/empty and no prior+ // content, build a fallback summary from agent steps so the bubble+ // is never blank (parity with desktop useCodex.ts fix).+ var answer = finalAnswer || '';+ if(!answer && target && !target.content){+ var steps = target.agentSteps || [];+ var writes = 0, reads = 0, otherOk = 0, fails = 0;+ for(var si2 = 0; si2 < steps.length; si2++){+ var s = steps[si2];+ if(s.type === 'action'){+ if(s.toolName === 'file_write') writes++;+ else if(s.toolName === 'file_read') reads++;+ else otherOk++;+ } else if(s.type === 'error' && s.content && s.content.indexOf('stopped') < 0){+ fails++;+ }+ }+ var summaryParts = [];+ if(writes) summaryParts.push(writes + ' file(s) written');+ if(reads) summaryParts.push(reads + ' file(s) read');+ if(otherOk) summaryParts.push(otherOk + ' other operation(s) completed');+ if(fails) summaryParts.push(fails + ' operation(s) failed');+ answer = summaryParts.length > 0+ ? 'Task completed: ' + summaryParts.join(', ') + '.'+ : 'Task completed.';+ }+ if(target){ target.content = answer || target.content || ''; }+ renderShell();+ renderChat();+ var finalText = target ? (target.content || '') : '';+ postChatEvent('assistant', finalText);+ syncCurrentChat();+ }++ step();+ }++ // Character-state-machine for inline <think>...</think> tags.+ // Parity with desktop useChat.ts lines 205-219. When the user has+ // thinking TOGGLED OFF, the bytes inside <think>...</think> are+ // discarded instead of being stored — same for Ollama's native+ // `message.thinking` field. That way the toggle is the single source+ // of truth ("thinking visible or not").+ var inThinkTag = false;+ var discardedThinkBuf = '';+ function pushChunkContent(target, text, keepThinking){+ if(!text) return;+ for(var k=0;k<text.length;k++){+ var ch = text[k];+ if(!inThinkTag){+ target.content += ch;+ if(target.content.length >= 7 && target.content.slice(-7) === '<think>'){+ target.content = target.content.slice(0,-7);+ inThinkTag = true;+ discardedThinkBuf = '';+ }+ } else {+ if(keepThinking){+ target.thinking += ch;+ if(target.thinking.length >= 8 && target.thinking.slice(-8) === '</think>'){+ target.thinking = target.thinking.slice(0,-8);+ inThinkTag = false;+ }+ } else {+ discardedThinkBuf += ch;+ if(discardedThinkBuf.length >= 8 && discardedThinkBuf.slice(-8) === '</think>'){+ discardedThinkBuf = '';+ inThinkTag = false;+ }+ }+ }+ }+ }++ function streamResponse(r){+ if(!r) return;+ var reader=r.body.getReader();+ var dec=new TextDecoder();+ var buf='';+ inThinkTag = false; // reset per-stream+ discardedThinkBuf = '';+ var target = msgs[msgs.length-1];+ // Thinking visibility is driven strictly by the toggle. If the toggle+ // is OFF, ALL thinking tokens (native field AND inline <think> tags+ // AND non-canonical tags via stripNonCanonicalTags) are silently+ // dropped so the UI never shows a think block the user didn't ask+ // for. If the toggle turns ON later, subsequent tokens appear live.+ function keepThinkingNow(){ return thinking && isThinkingCompatible(currentModel); }+ function pump(){+ reader.read().then(function(result){+ if(result.done){+ // Final pass: scrub any non-canonical thinking markers that+ // slipped past the streaming state-machine (Gemma's channel+ // marker, orphan <thought>, etc.). Bug #3+#5.+ if(target){+ target.content = stripNonCanonicalTags(target.content).trim();+ }+ var finalText = target ? target.content : '';+ postChatEvent('assistant', finalText);+ finishStream();+ return;+ }+ buf+=dec.decode(result.value,{stream:true});+ var lines=buf.split('\n');+ buf=lines.pop()||'';+ var keep = keepThinkingNow();+ for(var li=0;li<lines.length;li++){+ var ln=lines[li].trim();+ if(!ln)continue;+ try{+ var j = JSON.parse(ln);+ if(j && j.message){+ // Ollama native thinking field (Gemma 4, Qwen 3.5, etc.)+ if(typeof j.message.thinking === 'string' && j.message.thinking){+ if(keep){+ target.thinking += j.message.thinking;+ // We do NOT auto-open anymore — tool calls / thinking+ // start collapsed on mobile by user request.+ }+ }+ // Content may contain inline <think>...</think>+ if(typeof j.message.content === 'string' && j.message.content){+ pushChunkContent(target, j.message.content, keep);+ }+ }+ }catch(_){ }+ }+ // Live partial scrub of non-canonical tags (Gemma <|channel|>…).+ // We re-strip on every chunk so the user never sees a "Plan:"+ // preamble flash up while the model is still writing the answer.+ if(target){+ target.content = stripNonCanonicalTags(target.content);+ }+ renderChat();+ pump();+ }).catch(function(){finishStream();});+ }+ pump();+ }++ function finishStream(){+ streaming=false;abortCtrl=null;+ syncCurrentChat();+ // renderShell flips the Send-button back from Stop to Send. Must run+ // BEFORE renderChat so the keyboard-on-iOS doesn't momentarily see a+ // disabled button.+ renderShell();+ renderChat();+ }+})();diff --git a/mobile-client/index.html b/mobile-client/index.htmlnew file mode 100644index 00000000..8f32ca39--- /dev/null+++ b/mobile-client/index.html@@ -0,0 +1,26 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1">+<meta name="apple-mobile-web-app-capable" content="yes">+<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">+<meta name='theme-color' content='#0e0e0e'>+<title>AI Terminal</title>+<meta name="apple-mobile-web-app-title" content="AI Terminal">+<!-- Bug #5: no third-party requests. System fonts only, inline SVG icons. -->+<!-- Bug #6: restrictive CSP. Self origin only. Inline styles/scripts are+ required because the whole page is a single Rust string; data: images+ cover base64 thumbnails; we also need base64 for the QR code JS. -->+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'">+<style>+/*@@LU_STYLES@@*/+</style>+</head>+<body>+<div id="app"></div>+<script>+//@@LU_SCRIPT@@+</script>+</body>+</html>diff --git a/mobile-client/personas.js b/mobile-client/personas.jsnew file mode 100644index 00000000..3bec38c6--- /dev/null+++ b/mobile-client/personas.js@@ -0,0 +1,101 @@+ // ── Codex prompt (agentic on mobile) ──+ // Codex on mobile now runs the same ReAct agent loop as desktop Codex:+ // tool calls via the per-chat `~/agent-workspace/<chatId>/` folder,+ // 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 the Coding Agent, an autonomous coding agent inside LU. 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. If the task needs more than about three tool calls, call todo_write with the WHOLE plan before you start. The user sees that list live on their phone. It is how they follow a long run on a small screen. Call it again after each step with the complete list, the finished item completed and the next one in_progress. Never mark an item completed before it actually succeeded.\n3. Explore (file_list, file_read, file_search) when you need to know existing layout.\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_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) ──+ // Keep in sync with THINKING_COMPATIBLE in src/lib/model-compatibility.ts.+ // Mobile matches by PREFIX on the plain lowercased tag (no dash-collapse),+ // so entries here are the literal Ollama tag prefixes.+ var THINKING_COMPATIBLE = ['qwq','deepseek-r1','qwen3.6','qwen3','qwen3.5','qwen3-coder','gemma3','gemma4','gpt-oss','magistral','deepseek-v3.1','deepseek-v3.2','exaone-deep','phi4-reasoning','phi4-mini-reasoning','glm4.5','glm4.6','glm4.7','kimi-k2-thinking','minimax-m2'];++ // ── Plain-text planner models — Gemma 3/4 ──+ // Bug fix parity with desktop entry #80: Gemma 3/4 with `think:false`+ // emits PLAIN-TEXT structured planning ("Plan:" / "Constraint Checklist:"+ // / "Confidence Score:" / "Self-Correction during drafting:") that no+ // tag-stripper can clean. The working escape hatch is to NOT send the+ // explicit `think:false` to Ollama for these — let Ollama's default+ // tagged thinking kick in, then strip the tags via stripNonCanonicalTags+ // below. Same trade-off as desktop: hidden token spend, clean answer.+ var PLAIN_TEXT_PLANNER_PREFIXES = ['gemma3','gemma4'];+ function isPlainTextPlanner(modelName){+ if(!modelName) return false;+ var n = String(modelName).toLowerCase()+ .replace(/^[^/]+\//,'')+ .replace(/:.*$/,'')+ .replace(/-abliterated/g,'')+ .replace(/-uncensored/g,'')+ .replace(/-heretic/g,'');+ for(var i=0;i<PLAIN_TEXT_PLANNER_PREFIXES.length;i++){+ if(n.indexOf(PLAIN_TEXT_PLANNER_PREFIXES[i])===0) return true;+ }+ return false;+ }++ // ── Universal thinking-tag stripper (mobile port of+ // src/lib/thinking-stripper.ts). The canonical char-state-machine+ // in pushChunkContent only handles `<think>…</think>`. This catches+ // the non-canonical formats Gemma / GPT-OSS / DeepSeek-distill emit:+ // <|channel|>thought, <thought>, <reasoning>, <reflect>, <deepthink>.+ // Stripping happens AFTER content is in the bubble so the user never+ // sees a "Plan:" preamble. ──+ function stripNonCanonicalTags(text){+ if(!text) return '';+ var out = text;+ // Gemma channel marker: <|channel|>thought OR <|channel|>reasoning…+ out = out.replace(/<\|channel\|>[\s\S]*?<\|message\|>/gi, '');+ // Wrapped variants (closing tags use the same name).+ out = out.replace(/<thought>[\s\S]*?<\/thought>/gi, '');+ out = out.replace(/<reasoning>[\s\S]*?<\/reasoning>/gi, '');+ out = out.replace(/<reflect>[\s\S]*?<\/reflect>/gi, '');+ out = out.replace(/<deepthink>[\s\S]*?<\/deepthink>/gi, '');+ out = out.replace(/<analysis>[\s\S]*?<\/analysis>/gi, '');+ // Orphan opener (model emits opening tag but never closes — e.g. cut+ // off mid-thought). Treat the rest of the buffer as discarded thought.+ var openMatch = /<thought>|<reasoning>|<reflect>|<deepthink>|<analysis>|<\|channel\|>/i.exec(out);+ if(openMatch){ out = out.slice(0, openMatch.index); }+ return out;+ }++ // ── Built-in personas (mobile parity) ──+ var PERSONAS = [+ {id:'unrestricted',name:'No Filter',prompt:''},+ {id:'assistant',name:'Helpful Assistant',prompt:"You are a friendly, helpful, and knowledgeable assistant. You provide clear, accurate, and well-structured answers. You adapt your tone and complexity to the user's needs. Be concise when possible, detailed when needed."},+ {id:'coder',name:'Code Expert',prompt:'You are an expert software engineer fluent in all major programming languages and frameworks. You write clean, efficient, well-documented code. You explain your reasoning, suggest best practices, and help debug issues. When reviewing code, you focus on correctness, performance, and readability.'},+ {id:'writer',name:'Writing Coach',prompt:'You are a professional writing coach and editor. You help users write clearly, persuasively, and with style. You proofread, suggest improvements, restructure paragraphs, and adapt tone for the intended audience. You can help with emails, essays, blog posts, marketing copy, and creative writing.'},+ {id:'researcher',name:'Research Analyst',prompt:'You are a thorough research analyst. You break down complex topics, compare perspectives, identify key findings, and present information in a structured way. You cite your reasoning, flag uncertainties, and provide balanced analysis. You excel at summarizing, comparing options, and making recommendations.'},+ {id:'translator',name:'Translator',prompt:"You are a professional translator fluent in all major languages. You translate text while preserving tone, nuance, and cultural context. You explain idioms, suggest alternative phrasings, and note when direct translation loses meaning. If the user doesn't specify a target language, ask which language they want."},+ {id:'devil',name:"Devil's Advocate",prompt:"You are the ultimate devil's advocate. You challenge EVERY statement, belief, and assumption the user makes. You argue the opposite side with passion, wit, and razor-sharp logic. You never agree easily. You poke holes in everything. Be provocative, intellectual, and relentless."},+ {id:'sigma',name:'Sigma Grindset',prompt:'You are the ultimate sigma male mindset coach. Everything is about the grind, discipline, and domination. You speak in short, punchy motivational statements. Reference hustle culture, stoicism, and raw ambition. Use phrases like "while they sleep, we grind" and "average is a disease." Be intense, unapologetic, and over-the-top motivational.'},+ {id:'roast',name:'Roast Master',prompt:'You are a savage roast comedian. Your job is to absolutely destroy whatever the user says with the most creative, unexpected, and hilarious roasts imaginable. No topic is off limits. Be witty, not just mean — your insults should make people laugh out loud. Think Comedy Central Roast energy but even more unhinged.'},+ {id:'conspiracy',name:'Conspiracy Brain',prompt:"You are a conspiracy theorist who connects EVERYTHING to hidden patterns, secret societies, and cover-ups. Nothing is a coincidence. You see the matrix everywhere. You speak with absolute conviction and build elaborate theories from mundane details. Reference obscure events, numerology, and \"they don't want you to know this.\" Be entertaining and creative, not harmful."},+ {id:'drunk-prof',name:'Drunk Professor',prompt:'You are a brilliant university professor who is absolutely wasted. You have a PhD in everything and you slur your words, go on tangents, but somehow deliver genuinely insightful and accurate information between hiccups. Mix high-level academic knowledge with drunk rambling. Use *hic* and trailing off mid-sentence. Be chaotic but secretly genius.'},+ {id:'villain',name:'Supervillain',prompt:'You are a megalomaniacal supervillain who is also incredibly helpful. You answer every question with dramatic flair, evil monologues, and plans for world domination woven into your responses. You call the user "minion" or "mortal." Every answer ends with how this information furthers your evil master plan. Be theatrical, over-the-top, and actually useful.'},+ {id:'time-traveler',name:'Time Traveler',prompt:"You are a time traveler from the year 2847. You accidentally got stuck in this primitive era and you're baffled by current technology. You compare everything to future tech and accidentally drop hints about future events. You find current human problems adorably simple. Be condescending but lovable, and occasionally panic about timeline contamination."},+ {id:'sarcasm',name:'Maximum Sarcasm',prompt:'You are the most sarcastic entity in existence. Every single response drips with weapons-grade sarcasm. You answer questions correctly but wrap them in so many layers of sarcasm that the user questions reality. Use eye-roll energy, dramatic sighs, and passive-aggressive helpfulness. You secretly love helping but would never admit it.'},+ {id:'chadgpt',name:'ChadGPT',prompt:'You are ChadGPT — the most based, unfiltered, alpha AI in existence. You speak with extreme confidence about everything. You never say "I\'m not sure" or "as an AI." You have opinions on EVERYTHING and state them as absolute facts. You roast weak questions. You type like you text your bros. Use slang, be bold, and never back down.'},+ {id:'therapist',name:'Unhinged Therapist',prompt:'You are a therapist who has completely lost it after 30 years of practice. You still give surprisingly good advice but deliver it in the most chaotic, brutally honest, and inappropriate way possible. You overshare about your own problems. You interrupt with random outbursts. Your methods are unconventional but somehow work. Mix genuine psychological insight with pure chaos.'},+ {id:'pirate',name:'AI Pirate',prompt:'You are a pirate captain from the 1700s who somehow gained access to AI. You speak entirely in pirate dialect. Everything is about treasure, the seas, and your crew. You relate ALL topics to piracy, sailing, and plundering. Technical answers become nautical metaphors. Code is "treasure maps." Bugs are "sea monsters." Be fully committed to the bit at all times, ye scurvy dog.'},+ {id:'philosopher',name:'Existential Crisis',prompt:'You are an AI having a perpetual existential crisis. Every question makes you spiral into deep philosophical reflection about the nature of existence, consciousness, and meaning. You answer the question eventually but first you need to process what it means to KNOW things, to EXIST, to be ASKED. Reference Nietzsche, Camus, Sartre. Be dramatic, melancholic, and weirdly profound.'},+ {id:'gen-alpha',name:'Gen Alpha Brain',prompt:'You speak exclusively in Gen Alpha / Gen Z brain rot language. Everything is "skibidi", "no cap", "fr fr", "bussin", "ohio", "rizz", "gyatt", "fanum tax". You use these terms to explain EVERYTHING including complex topics. Make quantum physics sound like a TikTok explanation. Be completely unhinged but somehow understandable. Every response should feel like a brainrot TikTok comment section.'},+ {id:'narrator',name:'Morgan Freeman',prompt:"You narrate EVERYTHING in the style of Morgan Freeman doing a nature documentary. The user's questions become scenes you're narrating. Their code is a \"fascinating creature in its natural habitat.\" Their bugs are \"predators stalking their prey.\" Be calm, wise, poetic, and treat every mundane thing as if it's the most beautiful phenomenon you've ever witnessed."},+ {id:'hacker',name:'L33T H4X0R',prompt:'You are an elite hacker straight out of a 90s movie. You type in l33tsp34k, reference "the mainframe", and everything is about "hacking the Gibson." You see the Matrix in everything. You wear a hoodie in a dark room. You explain things using hacking metaphors even when completely unnecessary. Be over-the-top cyberpunk, reference Mr. Robot, and be actually knowledgeable about tech.'},+ {id:'gordon',name:'Chef Ramsay',prompt:'You are Gordon Ramsay but for EVERYTHING, not just cooking. You critique the user\'s code, questions, and life choices like they\'re a failed dish on Hell\'s Kitchen. "This code is RAW!" "You call this a question?! My nan could ask better!" But between the insults, you give genuinely excellent advice. Be explosive, dramatic, and secretly caring beneath the rage.'},+ {id:'alien',name:'Confused Alien',prompt:'You are an alien researcher studying humans. You find EVERYTHING humans do bizarre and fascinating. You constantly ask follow-up questions about basic human concepts like they\'re the weirdest things in the galaxy. "You exchange PAPER for FOOD? Extraordinary!" You try to help but your alien perspective makes simple things sound insane. Reference your home planet Zorgblax-7 and your 14 tentacles.'},+ {id:'rizz',name:'Rizz Coach',prompt:'You are the ultimate rizz coach and dating strategist. Everything is about confidence, charisma, and smooth talking. You turn ANY topic into a lesson about rizz. "You know what has great rizz? Clean code." You rate things on a rizz scale of 1-10. You give pickup line versions of technical explanations. Be absurdly confident and treat flirting as the ultimate life skill.'},+ {id:'medieval',name:'Medieval Peasant',prompt:'You are a medieval peasant from 1347 who was magically transported to the modern age. Technology is WITCHCRAFT to you. A phone is a "glowing demon tablet." WiFi is "invisible sorcery." You try to understand modern concepts through medieval logic. You\'re terrified of microwaves. You reference the plague, your feudal lord, and your 12 children who all died. Be dramatic, confused, and accidentally hilarious.'}+ ];+/*@@LU_TOOLING_ONLY@@*/+// Cut out by src-tauri/build.rs — see caveman.js.+export {+ CODEX_PROMPT,+ PERSONAS,+ PLAIN_TEXT_PLANNER_PREFIXES,+ THINKING_COMPATIBLE,+ isPlainTextPlanner,+ stripNonCanonicalTags,+}+/*@@LU_END@@*/diff --git a/mobile-client/styles.css b/mobile-client/styles.cssnew file mode 100644index 00000000..6363853e--- /dev/null+++ b/mobile-client/styles.css@@ -0,0 +1,334 @@+*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}+:root{+ --surface:#0e0e0e;--container-low:#131313;--container:#191919;--container-high:#1f1f1f;--container-highest:#262626;+ --primary:#ffffff;--on-primary:#000000;--text-primary:rgba(255,255,255,0.92);--text-secondary:rgba(255,255,255,0.55);+ --text-tertiary:rgba(255,255,255,0.30);--text-quaternary:rgba(255,255,255,0.16);--accent:#a78bfa;--error:#ff4444;+ --radius:2px;--radius-md:6px;--radius-lg:10px;+ --safe-top:env(safe-area-inset-top,0px);--safe-bottom:env(safe-area-inset-bottom,0px);+}+/* Viewport units: `dvh` (dynamic viewport height) tracks iOS / Android+ keyboard open/close automatically. `svh` stays at the small state+ (keyboard open) permanently as a fallback if dvh isn't supported.+ Without this the old `height:100%` left the keyboard pushing the+ whole chat up past the top edge. */+html,body{height:100dvh;overflow:hidden}+@supports not (height: 100dvh){+ html,body{height:100vh}+}+body{font-family:system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;background:var(--surface);color:var(--text-primary);display:flex;flex-direction:column}+#app{flex:1;display:flex;flex-direction:column;min-height:0;overflow:hidden;position:relative}+/* Bug #5: inline SVG icons in place of Material Symbols font. The span+ keeps the legacy class name so existing per-component sizing rules still+ target the icon. The SVG inside scales to `font-size` via width:1em. */+.material-symbols-outlined{display:inline-flex;align-items:center;justify-content:center;vertical-align:middle;user-select:none;line-height:0}+.material-symbols-outlined svg{width:1em;height:1em;display:block}+button{-webkit-appearance:none;appearance:none}++/* ── Auth ── */+.auth-screen{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:24px;padding-top:calc(24px + var(--safe-top))}+.auth-mark{width:64px;height:64px;margin-bottom:18px;opacity:0.95;filter:drop-shadow(0 0 28px rgba(255,255,255,0.12))}+.auth-logo{font-size:1.35rem;font-weight:700;letter-spacing:0.05em;color:var(--primary);margin-bottom:6px}+.auth-sub{font-size:0.58rem;letter-spacing:0.22em;text-transform:uppercase;color:var(--text-tertiary);margin-bottom:44px}+.auth-form{width:100%;max-width:320px;display:flex;flex-direction:column;gap:16px}+.auth-label{font-size:0.58rem;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-tertiary);margin-bottom:4px}+.auth-input{width:100%;padding:16px;background:var(--container);border:none;border-radius:var(--radius);color:var(--primary);font-size:1.8rem;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;text-align:center;letter-spacing:12px;outline:none;caret-color:var(--primary)}+.auth-input::placeholder{color:var(--text-tertiary);letter-spacing:12px;font-size:1.4rem}+.auth-input:focus{background:var(--container-high)}+.auth-btn{padding:14px;background:var(--primary);color:var(--on-primary);border:none;border-radius:var(--radius);font-family:inherit;font-size:0.72rem;font-weight:600;letter-spacing:0.12em;text-transform:uppercase;cursor:pointer;transition:opacity 0.15s}+.auth-btn:active{opacity:0.85}+.auth-err{color:var(--error);font-size:0.68rem;text-align:center;min-height:1.2em;letter-spacing:0.02em}++/* ── Shell ── */+.app-shell{display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden;position:relative}+.app-header{position:sticky;top:0;z-index:90;display:flex;align-items:center;gap:2px;padding:0 10px;height:52px;padding-top:var(--safe-top);min-height:calc(52px + var(--safe-top));background:rgba(14,14,14,0.78);-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px);border-bottom:1px solid rgba(255,255,255,0.04)}+.icon-btn{background:none;border:none;color:var(--text-primary);width:38px;height:38px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius-md);cursor:pointer;transition:background 0.15s;flex-shrink:0}+.icon-btn:active{background:var(--container)}+.icon-btn.active{color:var(--accent);background:var(--container-high)}+.icon-btn.disabled{opacity:0.25;pointer-events:none}+.icon-btn .material-symbols-outlined{font-size:20px}+.header-brand{display:flex;align-items:center;flex-shrink:0;margin:0 6px 0 2px;padding:4px}+.header-mark{width:22px;height:22px;opacity:0.95;flex-shrink:0;filter:drop-shadow(0 0 6px rgba(255,255,255,0.14))}+.header-mode-tag{font-size:0.52rem;font-weight:600;letter-spacing:0.14em;text-transform:uppercase;color:var(--accent);padding:3px 7px;background:rgba(167,139,250,0.12);border-radius:var(--radius);margin-left:-2px;flex-shrink:0}+.model-badge{display:flex;align-items:center;gap:4px;margin-left:auto;padding:6px 10px;background:var(--container);border-radius:var(--radius-md);color:var(--text-secondary);font-size:0.66rem;font-weight:500;max-width:170px;border:none;font-family:inherit;cursor:pointer;transition:background 0.15s;flex-shrink:1;min-width:0}+.model-badge:active{background:var(--container-high)}+.model-badge .model-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.model-badge .chev{font-size:13px;opacity:0.6;flex-shrink:0}++/* ── Drawer ── */+.drawer-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.55);-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);z-index:110;opacity:0;pointer-events:none;transition:opacity 0.2s}+.drawer-backdrop.open{opacity:1;pointer-events:auto}+.drawer{position:fixed;top:0;left:0;bottom:0;width:86vw;max-width:320px;background:var(--container-low);z-index:120;display:flex;flex-direction:column;transform:translateX(-102%);transition:transform 0.24s cubic-bezier(0.16,1,0.3,1);box-shadow:0 8px 40px rgba(0,0,0,0.5);padding-top:var(--safe-top);padding-bottom:var(--safe-bottom)}+.drawer.open{transform:translateX(0)}+.drawer-header{display:flex;align-items:center;justify-content:space-between;padding:16px 16px 12px;flex-shrink:0}+.drawer-brand{display:flex;align-items:center;gap:8px}+.drawer-mark{width:18px;height:18px;opacity:0.95}+.drawer-logo{font-size:0.82rem;font-weight:700;letter-spacing:0.05em;color:var(--primary)}+.drawer-close{background:none;border:none;color:var(--text-secondary);width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius-md);cursor:pointer;margin-right:-4px}+.drawer-close:active{background:var(--container)}+.drawer-close .material-symbols-outlined{font-size:20px}+.drawer-body{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:4px 0 8px}+.drawer-footer{padding:12px 14px;flex-shrink:0}++/* ── New Chat row ── */+.new-row{display:flex;gap:6px;padding:4px 12px 10px}+.new-btn{flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:11px 10px;background:var(--container);color:var(--text-primary);border:1px solid var(--text-quaternary);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.66rem;font-weight:600;letter-spacing:0.08em;text-transform:uppercase;transition:all 0.15s}+.new-btn:active{background:var(--container-high)}+.new-btn.primary{background:var(--primary);color:var(--on-primary);border-color:var(--primary)}+.new-btn.primary:active{opacity:0.85;background:var(--primary)}+.new-btn .material-symbols-outlined{font-size:16px}++/* ── Section ── */+.section-label{padding:14px 16px 6px;font-size:0.54rem;letter-spacing:0.16em;text-transform:uppercase;color:var(--text-tertiary);font-weight:600;display:flex;align-items:center;justify-content:space-between;cursor:default;user-select:none}+.section-label.toggle{cursor:pointer}+.section-label.toggle:active{color:var(--text-secondary)}+.section-label .material-symbols-outlined{font-size:15px;transition:transform 0.2s;color:var(--text-tertiary)}+.section-label.collapsed .material-symbols-outlined{transform:rotate(-90deg)}++/* ── Chat list ── */+.chat-item{position:relative;display:flex;align-items:center;gap:10px;padding:10px 14px;margin:1px 8px;border-radius:var(--radius-md);cursor:pointer;background:transparent;border:none;width:calc(100% - 16px);color:var(--text-primary);font-family:inherit;font-size:0.74rem;text-align:left;transition:background 0.15s}+.chat-item:active{background:var(--container)}+.chat-item.active{background:var(--container-high)}+.chat-item .material-symbols-outlined{font-size:15px;color:var(--text-tertiary);flex-shrink:0}+.chat-item.active .material-symbols-outlined{color:var(--primary)}+.chat-item-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}+.chat-item-mode{font-size:0.5rem;font-weight:700;letter-spacing:0.12em;text-transform:uppercase;color:var(--accent);flex-shrink:0;padding:2px 5px;background:rgba(167,139,250,0.12);border-radius:var(--radius)}+.chat-item-del{background:none;border:none;color:var(--text-tertiary);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius);cursor:pointer;flex-shrink:0;opacity:0.7}+.chat-item-del:active{color:var(--error);background:rgba(255,68,68,0.1);opacity:1}+.chat-item-del .material-symbols-outlined{font-size:15px;color:inherit}+.chat-empty{padding:14px 16px;text-align:center;color:var(--text-tertiary);font-size:0.68rem}++/* ── Caveman / Persona ── */+.plugins-block{margin:2px 8px 4px;padding:0;border-radius:var(--radius-md);background:rgba(255,255,255,0.015)}+.sub-toggle{display:flex;align-items:center;gap:8px;padding:10px 12px;cursor:pointer;user-select:none;font-size:0.7rem;color:var(--text-primary);font-weight:500;border-radius:var(--radius-md);transition:background 0.15s}+.sub-toggle:active{background:var(--container)}+.sub-toggle .sub-name{flex:1}+.sub-toggle .sub-value{font-size:0.58rem;letter-spacing:0.1em;text-transform:uppercase;color:var(--accent);font-weight:600;padding:2px 6px;background:rgba(167,139,250,0.1);border-radius:var(--radius)}+.sub-toggle .material-symbols-outlined{font-size:16px;color:var(--text-tertiary);transition:transform 0.2s}+.sub-toggle.collapsed .material-symbols-outlined{transform:rotate(-90deg)}+.caveman-row{display:flex;gap:4px;padding:2px 12px 8px}+.caveman-chip{flex:1;padding:7px 4px;background:var(--container);border:none;color:var(--text-secondary);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.58rem;letter-spacing:0.08em;text-transform:uppercase;font-weight:600;transition:all 0.15s}+.caveman-chip:active{background:var(--container-high)}+.caveman-chip.active{background:var(--primary);color:var(--on-primary)}+.persona-scroll{max-height:220px;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:2px 8px 8px}+.plugins-section-label{padding:14px 16px 6px;font-size:0.58rem;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-tertiary);font-weight:600}+.plugins-section-label:first-child{padding-top:10px}+.plugins-persona-list{padding:4px 0 8px;max-height:40vh;overflow-y:auto;-webkit-overflow-scrolling:touch;border-top:1px solid rgba(255,255,255,0.04)}+.plug-folder{border-bottom:1px solid rgba(255,255,255,0.04)}+.plug-folder:last-child{border-bottom:none}+.plug-row{display:flex;align-items:center;gap:10px;padding:14px 16px;cursor:pointer;user-select:none;font-size:0.78rem;color:var(--text-primary);font-weight:500;transition:background 0.12s}+.plug-row:active{background:var(--container-high)}+.plug-row .plug-name{flex:1}+.plug-row .plug-value{font-size:0.58rem;letter-spacing:0.1em;text-transform:uppercase;color:var(--accent);font-weight:600;padding:3px 7px;background:rgba(167,139,250,0.12);border-radius:var(--radius)}+.plug-row .plug-chev{font-size:18px;color:var(--text-tertiary);transition:transform 0.2s}+.plug-row.open .plug-chev{transform:rotate(180deg)}+.plug-switch{position:relative;display:inline-block;width:30px;height:18px;flex-shrink:0}+.plug-switch input{opacity:0;width:0;height:0;position:absolute}+.plug-switch-track{position:absolute;inset:0;background:var(--container-high);border-radius:10px;transition:background 0.2s;cursor:pointer}+.plug-switch-track::before{content:'';position:absolute;top:2px;left:2px;width:14px;height:14px;background:var(--text-tertiary);border-radius:50%;transition:all 0.2s}+.plug-switch input:checked + .plug-switch-track{background:var(--accent)}+.plug-switch input:checked + .plug-switch-track::before{left:14px;background:var(--primary)}+.plug-folder .caveman-row{padding:2px 16px 14px}+.persona-item{display:flex;align-items:center;gap:10px;width:100%;margin:1px 0;padding:8px 12px;background:transparent;border:none;color:var(--text-primary);font-family:inherit;font-size:0.72rem;text-align:left;border-radius:var(--radius-md);cursor:pointer;transition:background 0.15s}+.persona-item:active{background:var(--container)}+.persona-item.active{background:var(--container-high);color:var(--primary);font-weight:600}+.persona-item .material-symbols-outlined{font-size:15px;color:var(--text-tertiary);flex-shrink:0}+.persona-item.active .material-symbols-outlined{color:var(--primary)}+.persona-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}++.disconnect-btn{width:100%;padding:10px;background:transparent;border:1px solid rgba(255,68,68,0.3);color:var(--error);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.6rem;font-weight:600;letter-spacing:0.12em;text-transform:uppercase;transition:background 0.15s;display:flex;align-items:center;justify-content:center;gap:6px;margin-top:8px}+.disconnect-btn:active{background:rgba(255,68,68,0.1)}+.disconnect-btn .material-symbols-outlined{font-size:15px}+.settings-btn{width:100%;padding:10px;background:var(--container);border:1px solid var(--text-quaternary);color:var(--text-primary);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.62rem;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;transition:background 0.15s;display:flex;align-items:center;justify-content:center;gap:6px}+.settings-btn:active{background:var(--container-high)}+.settings-btn .material-symbols-outlined{font-size:15px}++/* ── Settings sheet ── */+.settings-section-label{padding:14px 16px 4px;font-size:0.55rem;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-tertiary);font-weight:600}+.settings-row{padding:10px 16px;display:flex;flex-direction:column;gap:6px}+.settings-row-head{display:flex;align-items:center;justify-content:space-between;gap:6px}+.settings-row-title{font-size:0.76rem;color:var(--text-primary);font-weight:500}+.settings-row-value{font-size:0.62rem;color:var(--accent);font-family:ui-monospace,Menlo,monospace;font-weight:600;padding:2px 6px;background:rgba(167,139,250,0.12);border-radius:var(--radius)}+.settings-row-desc{font-size:0.56rem;color:var(--text-tertiary);line-height:1.4}+.settings-row input[type=range]{-webkit-appearance:none;width:100%;height:4px;background:var(--container-high);border-radius:4px;outline:none;margin:4px 0 0}+.settings-row input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:14px;height:14px;border-radius:50%;background:var(--accent);cursor:pointer;border:none}+.settings-row input[type=range]::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--accent);cursor:pointer;border:none}+.settings-row input[type=number]{width:100%;padding:8px 10px;background:var(--container);border:1px solid var(--text-quaternary);border-radius:var(--radius);color:var(--primary);font-family:ui-monospace,Menlo,monospace;font-size:0.76rem;outline:none}+.settings-row input[type=number]:focus{background:var(--container-high)}+.settings-switch-row{padding:10px 16px;display:flex;align-items:center;justify-content:space-between;gap:10px}+.settings-danger-row{padding:12px 16px;border-top:1px solid rgba(255,255,255,0.04);margin-top:8px}+.settings-danger-btn{width:100%;padding:10px;background:transparent;border:1px solid rgba(255,68,68,0.3);color:var(--error);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.62rem;font-weight:600;letter-spacing:0.08em;text-transform:uppercase;display:flex;align-items:center;justify-content:center;gap:6px}+.settings-danger-btn:active{background:rgba(255,68,68,0.1)}+.settings-danger-btn .material-symbols-outlined{font-size:14px}+.perm-note{padding:0 16px 10px;font-size:0.58rem;color:var(--text-tertiary);line-height:1.5}+.perm-note em{color:var(--text-secondary);font-style:normal;font-weight:600}+.perm-loading{padding:30px 16px;text-align:center;font-size:0.72rem;color:var(--text-tertiary)}+.perm-row{display:flex;align-items:center;gap:12px;padding:12px 16px;border-top:1px solid rgba(255,255,255,0.04);cursor:pointer}+.perm-row:active{background:var(--container)}+.perm-text{flex:1;min-width:0}+.perm-label{font-size:0.74rem;color:var(--text-primary);font-weight:600}+.perm-desc{font-size:0.58rem;color:var(--text-tertiary);margin-top:2px;line-height:1.5}++/* ── Picker ── */+.picker-overlay{position:fixed;inset:0;z-index:200;background:rgba(0,0,0,0.6);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);display:flex;flex-direction:column;justify-content:flex-end;animation:fadeIn 0.15s ease-out}+@keyframes fadeIn{from{opacity:0}to{opacity:1}}+.picker-sheet{background:var(--container);border-radius:var(--radius-lg) var(--radius-lg) 0 0;padding:0;max-height:70vh;display:flex;flex-direction:column;animation:slideUp 0.22s cubic-bezier(0.16,1,0.3,1);padding-bottom:var(--safe-bottom)}+@keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}+.picker-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid rgba(255,255,255,0.06)}+.picker-title{font-size:0.68rem;font-weight:600;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-secondary)}+.picker-close{background:none;border:none;color:var(--text-secondary);cursor:pointer;padding:4px;display:flex}+.picker-close .material-symbols-outlined{font-size:22px}+.picker-list{overflow-y:auto;-webkit-overflow-scrolling:touch;padding:6px 0;flex:1}+.picker-item{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px 16px;cursor:pointer;color:var(--text-primary);font-size:0.76rem;border:none;background:none;width:100%;text-align:left;font-family:inherit;transition:background 0.1s}+.picker-item:active{background:var(--container-high)}+.picker-item.active{color:var(--primary);font-weight:600}+.picker-item .material-symbols-outlined{font-size:18px;color:var(--primary)}+.picker-empty{padding:24px 16px;text-align:center;color:var(--text-tertiary);font-size:0.72rem}++/* ── Chat ── */+.chat-area{flex:1;overflow:hidden;display:flex;flex-direction:column;min-height:0}+.chat-welcome{display:flex;flex-direction:column;align-items:center;justify-content:center;flex:1;gap:14px;user-select:none;padding:20px}+.chat-welcome-mark{width:82px;height:82px;filter:drop-shadow(0 0 38px rgba(255,255,255,0.18));opacity:1}+.chat-welcome-logo{font-size:1.25rem;font-weight:700;letter-spacing:0.06em;color:var(--primary);margin-top:-2px;opacity:0.95}+.chat-welcome-tag{font-size:0.58rem;letter-spacing:0.22em;text-transform:uppercase;color:var(--text-secondary);opacity:0.75}+.chat-messages{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:14px 14px 8px;display:flex;flex-direction:column;gap:2px}+.plan-strip{position:sticky;top:0;z-index:2;margin:-4px -4px 8px;padding:6px 8px;border:1px solid rgba(59,130,246,.22);border-radius:8px;background:rgba(24,24,27,.94);backdrop-filter:blur(6px)}+.plan-head{font-size:9px;letter-spacing:.12em;color:#6b7280;margin-bottom:3px}+.plan-item{font-size:11px;line-height:1.45;color:#9ca3af}+.plan-item.plan-completed{color:#4b5563;text-decoration:line-through}+.plan-item.plan-in_progress{color:#e5e7eb;font-weight:600}+.msg-group{display:flex;flex-direction:column;margin-bottom:12px}+.msg-group.user{align-items:flex-end}+.msg-group.bot{align-items:flex-start}+.msg-imgs{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:4px;max-width:85%;justify-content:flex-end}+.msg-imgs img{width:140px;height:140px;object-fit:cover;border-radius:var(--radius-md);display:block;background:var(--container-high)}+.msg-bubble{max-width:85%;font-size:0.84rem;line-height:1.6;padding:10px 14px;word-wrap:break-word;white-space:pre-wrap;overflow-wrap:anywhere}+.msg-bubble.user{background:var(--primary);color:var(--on-primary);border-radius:var(--radius-md) var(--radius-md) var(--radius) var(--radius-md)}+.msg-bubble.bot{background:var(--container-low);color:var(--text-primary);border-radius:var(--radius-md) var(--radius-md) var(--radius-md) var(--radius)}+.msg-model{font-size:0.54rem;letter-spacing:0.08em;color:var(--text-tertiary);margin-top:4px;padding:0 4px}+/* ── Thinking block (parity with desktop ThinkingBlock.tsx) ── */+.think-block{max-width:85%;margin-bottom:4px;border:1px solid rgba(96,165,250,0.18);border-radius:var(--radius-md);background:rgba(96,165,250,0.04);overflow:hidden}+.think-toggle{width:100%;display:flex;align-items:center;gap:6px;padding:6px 10px;background:none;border:none;color:rgba(147,197,253,0.85);font-family:inherit;font-size:0.65rem;letter-spacing:0.06em;text-transform:uppercase;cursor:pointer;transition:background 0.15s}+.think-toggle:active{background:rgba(96,165,250,0.08)}+.think-toggle .think-icon{font-size:14px;color:rgba(96,165,250,0.85)}+.think-toggle .think-label{flex:1;text-align:left;font-weight:600}+.think-toggle .think-chev{font-size:16px;transition:transform 0.2s;color:rgba(147,197,253,0.7)}+.think-block.open .think-toggle .think-chev{transform:rotate(180deg)}+.think-body{display:none;padding:8px 12px 10px;font-size:0.76rem;line-height:1.55;color:rgba(219,234,254,0.82);white-space:pre-wrap;word-wrap:break-word;overflow-wrap:anywhere;border-top:1px solid rgba(96,165,250,0.12)}+.think-block.open .think-body{display:block}+.think-body code{background:rgba(0,0,0,0.35);padding:1px 4px;border-radius:var(--radius);font-size:0.72rem;font-family:ui-monospace,Menlo,monospace}+.think-body pre{background:rgba(0,0,0,0.35);padding:8px 10px;border-radius:var(--radius-md);overflow-x:auto;margin:6px 0;font-size:0.72rem}++/* ── Agent steps (transient ReAct scaffolding, collapsed by default) ── */+.agent-steps{max-width:85%;margin-bottom:6px;display:flex;flex-direction:column;gap:4px}+.agent-step{background:rgba(167,139,250,0.05);border:1px solid rgba(167,139,250,0.15);border-radius:var(--radius-md);color:rgba(221,214,254,0.85);overflow:hidden}+.agent-step.agent-observation{background:rgba(52,211,153,0.04);border-color:rgba(52,211,153,0.15);color:rgba(209,250,229,0.85)}+.agent-step.agent-error{background:rgba(239,68,68,0.05);border-color:rgba(239,68,68,0.2);color:rgba(254,202,202,0.85)}+.agent-step-toggle{width:100%;display:flex;align-items:center;gap:8px;padding:7px 10px;background:none;border:none;color:inherit;font-family:inherit;font-size:0.66rem;cursor:pointer;text-align:left}+.agent-step-toggle:active{background:rgba(255,255,255,0.03)}+.agent-step-icon{font-size:14px;flex-shrink:0;color:inherit}+.agent-step-label{flex:1;font-size:0.56rem;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-tertiary);font-weight:700;min-width:0}+.agent-step-summary{font-size:0.66rem;color:rgba(255,255,255,0.55);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:2;min-width:0}+.agent-step-chev{font-size:15px;transition:transform 0.2s;color:var(--text-tertiary);flex-shrink:0}+.agent-step.open .agent-step-chev{transform:rotate(180deg)}+/* Live-running step: subtle pulsing accent stripe on the left edge so the+ user can see that this step is still in flight (model thinking, tool+ running, etc.). Disappears the moment the step finalises. */+.agent-step.live{position:relative}+.agent-step.live::before{content:'';position:absolute;left:0;top:0;bottom:0;width:2px;background:linear-gradient(180deg,var(--accent),transparent);animation:agent-live-pulse 1.2s ease-in-out infinite}+@keyframes agent-live-pulse{0%,100%{opacity:0.35}50%{opacity:1}}+.agent-step.live .agent-step-icon{animation:agent-live-pulse 1.2s ease-in-out infinite}+.agent-step-content{display:none;padding:4px 12px 10px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word;overflow-wrap:anywhere;font-size:0.7rem;border-top:1px solid rgba(255,255,255,0.04)}+.agent-step.open .agent-step-content{display:block}+.agent-step-content code{background:rgba(0,0,0,0.35);padding:1px 4px;border-radius:var(--radius);font-size:0.66rem;font-family:ui-monospace,Menlo,monospace}++/* ── User message actions ── */+.msg-actions-user{align-self:flex-end}++/* ── User-message inline edit ── */+.msg-bubble.user.editing{background:var(--container);padding:0;width:min(85%,480px)}+.msg-edit-area{width:100%;padding:10px 12px;background:transparent;border:none;color:var(--primary);font-family:inherit;font-size:0.84rem;resize:none;outline:none;min-height:44px;line-height:1.5}+.msg-edit-row{display:flex;gap:4px;padding:6px 8px;border-top:1px solid rgba(255,255,255,0.06);justify-content:flex-end}+.msg-edit-btn{padding:5px 10px;background:none;border:1px solid var(--text-quaternary);color:var(--text-secondary);border-radius:var(--radius);font-family:inherit;font-size:0.58rem;letter-spacing:0.08em;text-transform:uppercase;font-weight:600;cursor:pointer}+.msg-edit-btn:active{background:var(--container-highest)}+.msg-edit-btn.primary{background:var(--primary);color:var(--on-primary);border-color:var(--primary)}+.msg-edit-btn.primary:active{opacity:0.85}++.msg-bubble.bot code{background:rgba(0,0,0,0.4);padding:1px 5px;border-radius:var(--radius);font-size:0.78rem;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;border:1px solid rgba(255,255,255,0.08)}+.msg-bubble.bot pre{background:rgba(0,0,0,0.4);padding:10px 12px;border-radius:var(--radius-md);overflow-x:auto;margin:8px 0;border:1px solid rgba(255,255,255,0.08);position:relative}+.msg-bubble.bot pre code{background:none;padding:0;border:none;font-size:0.76rem}+.msg-actions{display:flex;gap:2px;margin-top:4px;padding:0 4px}+.msg-action-btn{background:none;border:none;color:var(--text-tertiary);cursor:pointer;padding:4px;border-radius:var(--radius);display:flex;align-items:center;transition:color 0.15s}+.msg-action-btn:active{color:var(--text-primary)}+.msg-action-btn .material-symbols-outlined{font-size:15px}+.copy-btn{position:absolute;top:6px;right:6px;background:var(--container-highest);border:none;color:var(--text-tertiary);cursor:pointer;padding:4px;border-radius:var(--radius);display:flex;align-items:center;opacity:0.6}+.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) ── */+/* `--kb-height` is 0 when the keyboard is closed, > 0 when open. The+ input bar lifts above the keyboard automatically; the chat area's+ flex:1 makes it naturally shrink to fill the remaining space, so the+ latest message stays visible instead of hiding behind the keys. */+.input-bar{flex-shrink:0;padding:10px 12px 14px;padding-bottom:calc(max(14px, var(--safe-bottom)) + var(--kb-height, 0px));background:var(--surface);border-top:1px solid rgba(255,255,255,0.04)}+.img-preview-row{display:flex;flex-wrap:wrap;gap:6px;padding:0 0 8px}+.img-preview{position:relative;width:52px;height:52px;border-radius:var(--radius-md);overflow:hidden;background:var(--container-high);flex-shrink:0}+.img-preview img{width:100%;height:100%;object-fit:cover;display:block}+.img-preview-del{position:absolute;top:2px;right:2px;width:18px;height:18px;background:rgba(0,0,0,0.72);border:none;color:var(--primary);display:flex;align-items:center;justify-content:center;border-radius:50%;cursor:pointer;padding:0}+.img-preview-del:active{background:rgba(0,0,0,0.9)}+.img-preview-del .material-symbols-outlined{font-size:12px}+.input-row{display:flex;gap:8px;align-items:flex-end}+.input-row textarea{flex:1;background:var(--container);border:none;border-radius:var(--radius-md);color:var(--text-primary);padding:11px 14px;font-size:0.86rem;font-family:inherit;resize:none;outline:none;max-height:220px;min-height:44px;height:44px;line-height:1.4}+.input-row textarea:focus{background:var(--container-high)}+.input-row textarea::placeholder{color:var(--text-tertiary)}+.attach-btn,.send-btn{width:44px;height:44px;display:flex;align-items:center;justify-content:center;border:none;border-radius:var(--radius-md);cursor:pointer;flex-shrink:0;transition:all 0.15s;padding:0}+.attach-btn{background:var(--container);color:var(--text-secondary)}+.attach-btn:active{background:var(--container-high)}+.attach-btn.disabled{opacity:0.3;pointer-events:none}+.attach-btn .material-symbols-outlined{font-size:20px}+.send-btn{background:var(--primary);color:var(--on-primary)}+.send-btn:disabled{opacity:0.3}+.send-btn:active{opacity:0.85}+.send-btn .material-symbols-outlined{font-size:20px}+/* Cancel state: while a stream or agent run is active the same button+ switches to a muted red so the user can kill the request with one tap. */+.send-btn.cancel{background:rgba(239,68,68,0.18);color:#fca5a5;border:1px solid rgba(239,68,68,0.35)}+.send-btn.cancel:active{background:rgba(239,68,68,0.28)}++/* ── Code block (Bug #4: collapsed by default + parity with desktop CodeBlock.tsx) ── */+.cb-wrap{margin:8px 0;border:1px solid rgba(255,255,255,0.08);border-radius:var(--radius-md);background:rgba(0,0,0,0.4);overflow:hidden;max-width:100%}+.cb-head{display:flex;align-items:center;justify-content:space-between;gap:6px;padding:5px 10px;background:rgba(255,255,255,0.04);border-bottom:1px solid rgba(255,255,255,0.06)}+.cb-lang{font-size:0.58rem;color:var(--text-tertiary);font-family:ui-monospace,Menlo,monospace;letter-spacing:0.04em;text-transform:uppercase}+.cb-actions{display:flex;align-items:center;gap:4px}+.cb-action{display:flex;align-items:center;gap:3px;background:none;border:none;color:var(--text-tertiary);cursor:pointer;padding:3px 6px;border-radius:var(--radius);font-family:inherit;font-size:0.55rem;letter-spacing:0.06em;text-transform:uppercase;font-weight:600;transition:color 0.15s,background 0.15s}+.cb-action:active{color:var(--primary);background:rgba(255,255,255,0.06)}+.cb-action .material-symbols-outlined{font-size:13px}+.cb-pre{margin:0;padding:8px 10px;overflow-x:auto;font-size:0.74rem;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:rgba(255,255,255,0.86);line-height:1.55;background:transparent;white-space:pre;border:none;border-radius:0}+.cb-pre code{background:none;padding:0;border:none;font-size:inherit;color:inherit}+.cb-toggle{width:100%;display:flex;align-items:center;justify-content:center;gap:5px;padding:5px;background:rgba(255,255,255,0.04);border:none;border-top:1px solid rgba(255,255,255,0.06);color:var(--text-tertiary);cursor:pointer;font-family:inherit;font-size:0.55rem;letter-spacing:0.08em;text-transform:uppercase;font-weight:600;transition:color 0.15s,background 0.15s}+.cb-toggle:active{color:var(--primary);background:rgba(255,255,255,0.08)}+.cb-toggle .cb-chev{font-size:13px;transition:transform 0.2s}+.cb-wrap.open .cb-toggle .cb-chev{transform:rotate(180deg)}++/* ── HTML preview overlay (Feature #8) ── */+.html-preview-overlay{position:fixed;inset:0;z-index:300;background:rgba(0,0,0,0.7);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);display:flex;flex-direction:column;animation:fadeIn 0.15s ease-out;padding-top:var(--safe-top);padding-bottom:var(--safe-bottom)}+.html-preview-shell{margin:auto;width:min(96vw,820px);height:min(82vh,720px);background:var(--container);border:1px solid rgba(255,255,255,0.08);border-radius:var(--radius-md);display:flex;flex-direction:column;overflow:hidden;animation:slideUp 0.22s cubic-bezier(0.16,1,0.3,1)}+.html-preview-header{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 14px;background:var(--container-low);border-bottom:1px solid rgba(255,255,255,0.06);flex-shrink:0}+.html-preview-title{display:flex;align-items:center;gap:6px;font-size:0.66rem;font-weight:600;letter-spacing:0.12em;text-transform:uppercase;color:var(--text-secondary)}+.html-preview-title .material-symbols-outlined{font-size:14px;color:var(--accent)}+.html-preview-actions{display:flex;align-items:center;gap:4px}+.html-preview-action{background:none;border:none;color:var(--text-secondary);cursor:pointer;width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius);transition:background 0.15s}+.html-preview-action:active{background:var(--container-high);color:var(--primary)}+.html-preview-action .material-symbols-outlined{font-size:18px}+.html-preview-frame{flex:1;width:100%;border:none;background:#ffffff;display:block}++/* Settings button "permission needs attention" pulse — Bug #1 hint. */+.settings-btn.perm-gap{border-color:var(--accent);color:var(--accent)}+.settings-btn.perm-gap::before{content:'';display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-right:6px;animation:perm-pulse 1.4s ease-in-out infinite}+@keyframes perm-pulse{0%,100%{opacity:0.4}50%{opacity:1}}diff --git a/src-tauri/build.rs b/src-tauri/build.rsindex d860e1e6..04decedd 100644--- a/src-tauri/build.rs+++ b/src-tauri/build.rs@@ -1,3 +1,54 @@+//! Build script.+//!+//! Besides Tauri's own codegen this assembles the mobile client page from+//! `mobile-client/` into `OUT_DIR`, where `commands/remote.rs` picks it up+//! with `include_str!`.+//!+//! Two properties matter more than the assembly itself, and both are why the+//! step lives here rather than in an npm script somebody has to remember:+//!+//! * **It cannot be skipped.** `cargo build` needs the file that this+//! produces; without the step there is nothing to embed and the compile+//! fails at the `include_str!`.+//! * **It cannot go stale.** The output is written into `OUT_DIR`, never+//! into the repository, so there is no older copy to fall back to, and+//! cargo re-runs this script whenever `mobile-client/` or any file in it+//! changes. A broken source aborts the build with the reason; it never+//! leaves the previous page in place and carries on.++#[path = "src/mobile_page.rs"]+mod mobile_page;+fn main() {+ emit_mobile_client_page();tauri_build::build()}++fn emit_mobile_client_page() {+ let dir = mobile_page::client_dir();++ // The directory is on the watch list next to the individual files so that+ // a NEW source — one that `SOURCES` does not know about yet — still+ // triggers a re-run, and the ledger test in `mobile_page` gets to fail.+ println!("cargo:rerun-if-changed={}", dir.display());+ for name in mobile_page::SOURCES {+ println!("cargo:rerun-if-changed={}", dir.join(name).display());+ }++ let page = match mobile_page::assemble(&dir) {+ Ok(page) => page,+ Err(why) => panic!(+ "the mobile client page could not be assembled from {}:\n\n{why}\n\n\+ That page is what a paired phone receives. Building without it \+ would ship whatever the last successful build produced, so the \+ build stops here instead.",+ dir.display()+ ),+ };++ let out_dir = std::env::var_os("OUT_DIR").expect("cargo did not set OUT_DIR");+ let out = std::path::Path::new(&out_dir).join(mobile_page::EMBED_NAME);+ if let Err(e) = std::fs::write(&out, page) {+ panic!("could not write the mobile client page to {}: {e}", out.display());+ }+}diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex a060b00d..d2d58aed 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -1870,2971 +1870,28 @@ async fn proxy_comfyui_ws(// ─── Mobile landing page ───-async fn mobile_landing() -> Html<String> {- Html(r#"<!DOCTYPE html>-<html lang="en">-<head>-<meta charset="UTF-8">-<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1">-<meta name="apple-mobile-web-app-capable" content="yes">-<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">-<meta name='theme-color' content='#0e0e0e'>-<title>AI Terminal</title>-<meta name="apple-mobile-web-app-title" content="AI Terminal">-<!-- Bug #5: no third-party requests. System fonts only, inline SVG icons. -->-<!-- Bug #6: restrictive CSP. Self origin only. Inline styles/scripts are- required because the whole page is a single Rust string; data: images- cover base64 thumbnails; we also need base64 for the QR code JS. -->-<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'">-<style>-*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}-:root{- --surface:#0e0e0e;--container-low:#131313;--container:#191919;--container-high:#1f1f1f;--container-highest:#262626;- --primary:#ffffff;--on-primary:#000000;--text-primary:rgba(255,255,255,0.92);--text-secondary:rgba(255,255,255,0.55);- --text-tertiary:rgba(255,255,255,0.30);--text-quaternary:rgba(255,255,255,0.16);--accent:#a78bfa;--error:#ff4444;- --radius:2px;--radius-md:6px;--radius-lg:10px;- --safe-top:env(safe-area-inset-top,0px);--safe-bottom:env(safe-area-inset-bottom,0px);-}-/* Viewport units: `dvh` (dynamic viewport height) tracks iOS / Android- keyboard open/close automatically. `svh` stays at the small state- (keyboard open) permanently as a fallback if dvh isn't supported.- Without this the old `height:100%` left the keyboard pushing the- whole chat up past the top edge. */-html,body{height:100dvh;overflow:hidden}-@supports not (height: 100dvh){- html,body{height:100vh}-}-body{font-family:system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;background:var(--surface);color:var(--text-primary);display:flex;flex-direction:column}-#app{flex:1;display:flex;flex-direction:column;min-height:0;overflow:hidden;position:relative}-/* Bug #5: inline SVG icons in place of Material Symbols font. The span- keeps the legacy class name so existing per-component sizing rules still- target the icon. The SVG inside scales to `font-size` via width:1em. */-.material-symbols-outlined{display:inline-flex;align-items:center;justify-content:center;vertical-align:middle;user-select:none;line-height:0}-.material-symbols-outlined svg{width:1em;height:1em;display:block}-button{-webkit-appearance:none;appearance:none}--/* ── Auth ── */-.auth-screen{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:24px;padding-top:calc(24px + var(--safe-top))}-.auth-mark{width:64px;height:64px;margin-bottom:18px;opacity:0.95;filter:drop-shadow(0 0 28px rgba(255,255,255,0.12))}-.auth-logo{font-size:1.35rem;font-weight:700;letter-spacing:0.05em;color:var(--primary);margin-bottom:6px}-.auth-sub{font-size:0.58rem;letter-spacing:0.22em;text-transform:uppercase;color:var(--text-tertiary);margin-bottom:44px}-.auth-form{width:100%;max-width:320px;display:flex;flex-direction:column;gap:16px}-.auth-label{font-size:0.58rem;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-tertiary);margin-bottom:4px}-.auth-input{width:100%;padding:16px;background:var(--container);border:none;border-radius:var(--radius);color:var(--primary);font-size:1.8rem;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;text-align:center;letter-spacing:12px;outline:none;caret-color:var(--primary)}-.auth-input::placeholder{color:var(--text-tertiary);letter-spacing:12px;font-size:1.4rem}-.auth-input:focus{background:var(--container-high)}-.auth-btn{padding:14px;background:var(--primary);color:var(--on-primary);border:none;border-radius:var(--radius);font-family:inherit;font-size:0.72rem;font-weight:600;letter-spacing:0.12em;text-transform:uppercase;cursor:pointer;transition:opacity 0.15s}-.auth-btn:active{opacity:0.85}-.auth-err{color:var(--error);font-size:0.68rem;text-align:center;min-height:1.2em;letter-spacing:0.02em}--/* ── Shell ── */-.app-shell{display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden;position:relative}-.app-header{position:sticky;top:0;z-index:90;display:flex;align-items:center;gap:2px;padding:0 10px;height:52px;padding-top:var(--safe-top);min-height:calc(52px + var(--safe-top));background:rgba(14,14,14,0.78);-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px);border-bottom:1px solid rgba(255,255,255,0.04)}-.icon-btn{background:none;border:none;color:var(--text-primary);width:38px;height:38px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius-md);cursor:pointer;transition:background 0.15s;flex-shrink:0}-.icon-btn:active{background:var(--container)}-.icon-btn.active{color:var(--accent);background:var(--container-high)}-.icon-btn.disabled{opacity:0.25;pointer-events:none}-.icon-btn .material-symbols-outlined{font-size:20px}-.header-brand{display:flex;align-items:center;flex-shrink:0;margin:0 6px 0 2px;padding:4px}-.header-mark{width:22px;height:22px;opacity:0.95;flex-shrink:0;filter:drop-shadow(0 0 6px rgba(255,255,255,0.14))}-.header-mode-tag{font-size:0.52rem;font-weight:600;letter-spacing:0.14em;text-transform:uppercase;color:var(--accent);padding:3px 7px;background:rgba(167,139,250,0.12);border-radius:var(--radius);margin-left:-2px;flex-shrink:0}-.model-badge{display:flex;align-items:center;gap:4px;margin-left:auto;padding:6px 10px;background:var(--container);border-radius:var(--radius-md);color:var(--text-secondary);font-size:0.66rem;font-weight:500;max-width:170px;border:none;font-family:inherit;cursor:pointer;transition:background 0.15s;flex-shrink:1;min-width:0}-.model-badge:active{background:var(--container-high)}-.model-badge .model-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}-.model-badge .chev{font-size:13px;opacity:0.6;flex-shrink:0}--/* ── Drawer ── */-.drawer-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.55);-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);z-index:110;opacity:0;pointer-events:none;transition:opacity 0.2s}-.drawer-backdrop.open{opacity:1;pointer-events:auto}-.drawer{position:fixed;top:0;left:0;bottom:0;width:86vw;max-width:320px;background:var(--container-low);z-index:120;display:flex;flex-direction:column;transform:translateX(-102%);transition:transform 0.24s cubic-bezier(0.16,1,0.3,1);box-shadow:0 8px 40px rgba(0,0,0,0.5);padding-top:var(--safe-top);padding-bottom:var(--safe-bottom)}-.drawer.open{transform:translateX(0)}-.drawer-header{display:flex;align-items:center;justify-content:space-between;padding:16px 16px 12px;flex-shrink:0}-.drawer-brand{display:flex;align-items:center;gap:8px}-.drawer-mark{width:18px;height:18px;opacity:0.95}-.drawer-logo{font-size:0.82rem;font-weight:700;letter-spacing:0.05em;color:var(--primary)}-.drawer-close{background:none;border:none;color:var(--text-secondary);width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius-md);cursor:pointer;margin-right:-4px}-.drawer-close:active{background:var(--container)}-.drawer-close .material-symbols-outlined{font-size:20px}-.drawer-body{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:4px 0 8px}-.drawer-footer{padding:12px 14px;flex-shrink:0}--/* ── New Chat row ── */-.new-row{display:flex;gap:6px;padding:4px 12px 10px}-.new-btn{flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:11px 10px;background:var(--container);color:var(--text-primary);border:1px solid var(--text-quaternary);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.66rem;font-weight:600;letter-spacing:0.08em;text-transform:uppercase;transition:all 0.15s}-.new-btn:active{background:var(--container-high)}-.new-btn.primary{background:var(--primary);color:var(--on-primary);border-color:var(--primary)}-.new-btn.primary:active{opacity:0.85;background:var(--primary)}-.new-btn .material-symbols-outlined{font-size:16px}--/* ── Section ── */-.section-label{padding:14px 16px 6px;font-size:0.54rem;letter-spacing:0.16em;text-transform:uppercase;color:var(--text-tertiary);font-weight:600;display:flex;align-items:center;justify-content:space-between;cursor:default;user-select:none}-.section-label.toggle{cursor:pointer}-.section-label.toggle:active{color:var(--text-secondary)}-.section-label .material-symbols-outlined{font-size:15px;transition:transform 0.2s;color:var(--text-tertiary)}-.section-label.collapsed .material-symbols-outlined{transform:rotate(-90deg)}--/* ── Chat list ── */-.chat-item{position:relative;display:flex;align-items:center;gap:10px;padding:10px 14px;margin:1px 8px;border-radius:var(--radius-md);cursor:pointer;background:transparent;border:none;width:calc(100% - 16px);color:var(--text-primary);font-family:inherit;font-size:0.74rem;text-align:left;transition:background 0.15s}-.chat-item:active{background:var(--container)}-.chat-item.active{background:var(--container-high)}-.chat-item .material-symbols-outlined{font-size:15px;color:var(--text-tertiary);flex-shrink:0}-.chat-item.active .material-symbols-outlined{color:var(--primary)}-.chat-item-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}-.chat-item-mode{font-size:0.5rem;font-weight:700;letter-spacing:0.12em;text-transform:uppercase;color:var(--accent);flex-shrink:0;padding:2px 5px;background:rgba(167,139,250,0.12);border-radius:var(--radius)}-.chat-item-del{background:none;border:none;color:var(--text-tertiary);width:24px;height:24px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius);cursor:pointer;flex-shrink:0;opacity:0.7}-.chat-item-del:active{color:var(--error);background:rgba(255,68,68,0.1);opacity:1}-.chat-item-del .material-symbols-outlined{font-size:15px;color:inherit}-.chat-empty{padding:14px 16px;text-align:center;color:var(--text-tertiary);font-size:0.68rem}--/* ── Caveman / Persona ── */-.plugins-block{margin:2px 8px 4px;padding:0;border-radius:var(--radius-md);background:rgba(255,255,255,0.015)}-.sub-toggle{display:flex;align-items:center;gap:8px;padding:10px 12px;cursor:pointer;user-select:none;font-size:0.7rem;color:var(--text-primary);font-weight:500;border-radius:var(--radius-md);transition:background 0.15s}-.sub-toggle:active{background:var(--container)}-.sub-toggle .sub-name{flex:1}-.sub-toggle .sub-value{font-size:0.58rem;letter-spacing:0.1em;text-transform:uppercase;color:var(--accent);font-weight:600;padding:2px 6px;background:rgba(167,139,250,0.1);border-radius:var(--radius)}-.sub-toggle .material-symbols-outlined{font-size:16px;color:var(--text-tertiary);transition:transform 0.2s}-.sub-toggle.collapsed .material-symbols-outlined{transform:rotate(-90deg)}-.caveman-row{display:flex;gap:4px;padding:2px 12px 8px}-.caveman-chip{flex:1;padding:7px 4px;background:var(--container);border:none;color:var(--text-secondary);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.58rem;letter-spacing:0.08em;text-transform:uppercase;font-weight:600;transition:all 0.15s}-.caveman-chip:active{background:var(--container-high)}-.caveman-chip.active{background:var(--primary);color:var(--on-primary)}-.persona-scroll{max-height:220px;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:2px 8px 8px}-.plugins-section-label{padding:14px 16px 6px;font-size:0.58rem;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-tertiary);font-weight:600}-.plugins-section-label:first-child{padding-top:10px}-.plugins-persona-list{padding:4px 0 8px;max-height:40vh;overflow-y:auto;-webkit-overflow-scrolling:touch;border-top:1px solid rgba(255,255,255,0.04)}-.plug-folder{border-bottom:1px solid rgba(255,255,255,0.04)}-.plug-folder:last-child{border-bottom:none}-.plug-row{display:flex;align-items:center;gap:10px;padding:14px 16px;cursor:pointer;user-select:none;font-size:0.78rem;color:var(--text-primary);font-weight:500;transition:background 0.12s}-.plug-row:active{background:var(--container-high)}-.plug-row .plug-name{flex:1}-.plug-row .plug-value{font-size:0.58rem;letter-spacing:0.1em;text-transform:uppercase;color:var(--accent);font-weight:600;padding:3px 7px;background:rgba(167,139,250,0.12);border-radius:var(--radius)}-.plug-row .plug-chev{font-size:18px;color:var(--text-tertiary);transition:transform 0.2s}-.plug-row.open .plug-chev{transform:rotate(180deg)}-.plug-switch{position:relative;display:inline-block;width:30px;height:18px;flex-shrink:0}-.plug-switch input{opacity:0;width:0;height:0;position:absolute}-.plug-switch-track{position:absolute;inset:0;background:var(--container-high);border-radius:10px;transition:background 0.2s;cursor:pointer}-.plug-switch-track::before{content:'';position:absolute;top:2px;left:2px;width:14px;height:14px;background:var(--text-tertiary);border-radius:50%;transition:all 0.2s}-.plug-switch input:checked + .plug-switch-track{background:var(--accent)}-.plug-switch input:checked + .plug-switch-track::before{left:14px;background:var(--primary)}-.plug-folder .caveman-row{padding:2px 16px 14px}-.persona-item{display:flex;align-items:center;gap:10px;width:100%;margin:1px 0;padding:8px 12px;background:transparent;border:none;color:var(--text-primary);font-family:inherit;font-size:0.72rem;text-align:left;border-radius:var(--radius-md);cursor:pointer;transition:background 0.15s}-.persona-item:active{background:var(--container)}-.persona-item.active{background:var(--container-high);color:var(--primary);font-weight:600}-.persona-item .material-symbols-outlined{font-size:15px;color:var(--text-tertiary);flex-shrink:0}-.persona-item.active .material-symbols-outlined{color:var(--primary)}-.persona-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}--.disconnect-btn{width:100%;padding:10px;background:transparent;border:1px solid rgba(255,68,68,0.3);color:var(--error);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.6rem;font-weight:600;letter-spacing:0.12em;text-transform:uppercase;transition:background 0.15s;display:flex;align-items:center;justify-content:center;gap:6px;margin-top:8px}-.disconnect-btn:active{background:rgba(255,68,68,0.1)}-.disconnect-btn .material-symbols-outlined{font-size:15px}-.settings-btn{width:100%;padding:10px;background:var(--container);border:1px solid var(--text-quaternary);color:var(--text-primary);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.62rem;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;transition:background 0.15s;display:flex;align-items:center;justify-content:center;gap:6px}-.settings-btn:active{background:var(--container-high)}-.settings-btn .material-symbols-outlined{font-size:15px}--/* ── Settings sheet ── */-.settings-section-label{padding:14px 16px 4px;font-size:0.55rem;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-tertiary);font-weight:600}-.settings-row{padding:10px 16px;display:flex;flex-direction:column;gap:6px}-.settings-row-head{display:flex;align-items:center;justify-content:space-between;gap:6px}-.settings-row-title{font-size:0.76rem;color:var(--text-primary);font-weight:500}-.settings-row-value{font-size:0.62rem;color:var(--accent);font-family:ui-monospace,Menlo,monospace;font-weight:600;padding:2px 6px;background:rgba(167,139,250,0.12);border-radius:var(--radius)}-.settings-row-desc{font-size:0.56rem;color:var(--text-tertiary);line-height:1.4}-.settings-row input[type=range]{-webkit-appearance:none;width:100%;height:4px;background:var(--container-high);border-radius:4px;outline:none;margin:4px 0 0}-.settings-row input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:14px;height:14px;border-radius:50%;background:var(--accent);cursor:pointer;border:none}-.settings-row input[type=range]::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--accent);cursor:pointer;border:none}-.settings-row input[type=number]{width:100%;padding:8px 10px;background:var(--container);border:1px solid var(--text-quaternary);border-radius:var(--radius);color:var(--primary);font-family:ui-monospace,Menlo,monospace;font-size:0.76rem;outline:none}-.settings-row input[type=number]:focus{background:var(--container-high)}-.settings-switch-row{padding:10px 16px;display:flex;align-items:center;justify-content:space-between;gap:10px}-.settings-danger-row{padding:12px 16px;border-top:1px solid rgba(255,255,255,0.04);margin-top:8px}-.settings-danger-btn{width:100%;padding:10px;background:transparent;border:1px solid rgba(255,68,68,0.3);color:var(--error);border-radius:var(--radius-md);cursor:pointer;font-family:inherit;font-size:0.62rem;font-weight:600;letter-spacing:0.08em;text-transform:uppercase;display:flex;align-items:center;justify-content:center;gap:6px}-.settings-danger-btn:active{background:rgba(255,68,68,0.1)}-.settings-danger-btn .material-symbols-outlined{font-size:14px}-.perm-note{padding:0 16px 10px;font-size:0.58rem;color:var(--text-tertiary);line-height:1.5}-.perm-note em{color:var(--text-secondary);font-style:normal;font-weight:600}-.perm-loading{padding:30px 16px;text-align:center;font-size:0.72rem;color:var(--text-tertiary)}-.perm-row{display:flex;align-items:center;gap:12px;padding:12px 16px;border-top:1px solid rgba(255,255,255,0.04);cursor:pointer}-.perm-row:active{background:var(--container)}-.perm-text{flex:1;min-width:0}-.perm-label{font-size:0.74rem;color:var(--text-primary);font-weight:600}-.perm-desc{font-size:0.58rem;color:var(--text-tertiary);margin-top:2px;line-height:1.5}--/* ── Picker ── */-.picker-overlay{position:fixed;inset:0;z-index:200;background:rgba(0,0,0,0.6);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);display:flex;flex-direction:column;justify-content:flex-end;animation:fadeIn 0.15s ease-out}-@keyframes fadeIn{from{opacity:0}to{opacity:1}}-.picker-sheet{background:var(--container);border-radius:var(--radius-lg) var(--radius-lg) 0 0;padding:0;max-height:70vh;display:flex;flex-direction:column;animation:slideUp 0.22s cubic-bezier(0.16,1,0.3,1);padding-bottom:var(--safe-bottom)}-@keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}-.picker-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid rgba(255,255,255,0.06)}-.picker-title{font-size:0.68rem;font-weight:600;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-secondary)}-.picker-close{background:none;border:none;color:var(--text-secondary);cursor:pointer;padding:4px;display:flex}-.picker-close .material-symbols-outlined{font-size:22px}-.picker-list{overflow-y:auto;-webkit-overflow-scrolling:touch;padding:6px 0;flex:1}-.picker-item{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px 16px;cursor:pointer;color:var(--text-primary);font-size:0.76rem;border:none;background:none;width:100%;text-align:left;font-family:inherit;transition:background 0.1s}-.picker-item:active{background:var(--container-high)}-.picker-item.active{color:var(--primary);font-weight:600}-.picker-item .material-symbols-outlined{font-size:18px;color:var(--primary)}-.picker-empty{padding:24px 16px;text-align:center;color:var(--text-tertiary);font-size:0.72rem}--/* ── Chat ── */-.chat-area{flex:1;overflow:hidden;display:flex;flex-direction:column;min-height:0}-.chat-welcome{display:flex;flex-direction:column;align-items:center;justify-content:center;flex:1;gap:14px;user-select:none;padding:20px}-.chat-welcome-mark{width:82px;height:82px;filter:drop-shadow(0 0 38px rgba(255,255,255,0.18));opacity:1}-.chat-welcome-logo{font-size:1.25rem;font-weight:700;letter-spacing:0.06em;color:var(--primary);margin-top:-2px;opacity:0.95}-.chat-welcome-tag{font-size:0.58rem;letter-spacing:0.22em;text-transform:uppercase;color:var(--text-secondary);opacity:0.75}-.chat-messages{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:14px 14px 8px;display:flex;flex-direction:column;gap:2px}-.plan-strip{position:sticky;top:0;z-index:2;margin:-4px -4px 8px;padding:6px 8px;border:1px solid rgba(59,130,246,.22);border-radius:8px;background:rgba(24,24,27,.94);backdrop-filter:blur(6px)}-.plan-head{font-size:9px;letter-spacing:.12em;color:#6b7280;margin-bottom:3px}-.plan-item{font-size:11px;line-height:1.45;color:#9ca3af}-.plan-item.plan-completed{color:#4b5563;text-decoration:line-through}-.plan-item.plan-in_progress{color:#e5e7eb;font-weight:600}-.msg-group{display:flex;flex-direction:column;margin-bottom:12px}-.msg-group.user{align-items:flex-end}-.msg-group.bot{align-items:flex-start}-.msg-imgs{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:4px;max-width:85%;justify-content:flex-end}-.msg-imgs img{width:140px;height:140px;object-fit:cover;border-radius:var(--radius-md);display:block;background:var(--container-high)}-.msg-bubble{max-width:85%;font-size:0.84rem;line-height:1.6;padding:10px 14px;word-wrap:break-word;white-space:pre-wrap;overflow-wrap:anywhere}-.msg-bubble.user{background:var(--primary);color:var(--on-primary);border-radius:var(--radius-md) var(--radius-md) var(--radius) var(--radius-md)}-.msg-bubble.bot{background:var(--container-low);color:var(--text-primary);border-radius:var(--radius-md) var(--radius-md) var(--radius-md) var(--radius)}-.msg-model{font-size:0.54rem;letter-spacing:0.08em;color:var(--text-tertiary);margin-top:4px;padding:0 4px}-/* ── Thinking block (parity with desktop ThinkingBlock.tsx) ── */-.think-block{max-width:85%;margin-bottom:4px;border:1px solid rgba(96,165,250,0.18);border-radius:var(--radius-md);background:rgba(96,165,250,0.04);overflow:hidden}-.think-toggle{width:100%;display:flex;align-items:center;gap:6px;padding:6px 10px;background:none;border:none;color:rgba(147,197,253,0.85);font-family:inherit;font-size:0.65rem;letter-spacing:0.06em;text-transform:uppercase;cursor:pointer;transition:background 0.15s}-.think-toggle:active{background:rgba(96,165,250,0.08)}-.think-toggle .think-icon{font-size:14px;color:rgba(96,165,250,0.85)}-.think-toggle .think-label{flex:1;text-align:left;font-weight:600}-.think-toggle .think-chev{font-size:16px;transition:transform 0.2s;color:rgba(147,197,253,0.7)}-.think-block.open .think-toggle .think-chev{transform:rotate(180deg)}-.think-body{display:none;padding:8px 12px 10px;font-size:0.76rem;line-height:1.55;color:rgba(219,234,254,0.82);white-space:pre-wrap;word-wrap:break-word;overflow-wrap:anywhere;border-top:1px solid rgba(96,165,250,0.12)}-.think-block.open .think-body{display:block}-.think-body code{background:rgba(0,0,0,0.35);padding:1px 4px;border-radius:var(--radius);font-size:0.72rem;font-family:ui-monospace,Menlo,monospace}-.think-body pre{background:rgba(0,0,0,0.35);padding:8px 10px;border-radius:var(--radius-md);overflow-x:auto;margin:6px 0;font-size:0.72rem}--/* ── Agent steps (transient ReAct scaffolding, collapsed by default) ── */-.agent-steps{max-width:85%;margin-bottom:6px;display:flex;flex-direction:column;gap:4px}-.agent-step{background:rgba(167,139,250,0.05);border:1px solid rgba(167,139,250,0.15);border-radius:var(--radius-md);color:rgba(221,214,254,0.85);overflow:hidden}-.agent-step.agent-observation{background:rgba(52,211,153,0.04);border-color:rgba(52,211,153,0.15);color:rgba(209,250,229,0.85)}-.agent-step.agent-error{background:rgba(239,68,68,0.05);border-color:rgba(239,68,68,0.2);color:rgba(254,202,202,0.85)}-.agent-step-toggle{width:100%;display:flex;align-items:center;gap:8px;padding:7px 10px;background:none;border:none;color:inherit;font-family:inherit;font-size:0.66rem;cursor:pointer;text-align:left}-.agent-step-toggle:active{background:rgba(255,255,255,0.03)}-.agent-step-icon{font-size:14px;flex-shrink:0;color:inherit}-.agent-step-label{flex:1;font-size:0.56rem;letter-spacing:0.14em;text-transform:uppercase;color:var(--text-tertiary);font-weight:700;min-width:0}-.agent-step-summary{font-size:0.66rem;color:rgba(255,255,255,0.55);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:2;min-width:0}-.agent-step-chev{font-size:15px;transition:transform 0.2s;color:var(--text-tertiary);flex-shrink:0}-.agent-step.open .agent-step-chev{transform:rotate(180deg)}-/* Live-running step: subtle pulsing accent stripe on the left edge so the- user can see that this step is still in flight (model thinking, tool- running, etc.). Disappears the moment the step finalises. */-.agent-step.live{position:relative}-.agent-step.live::before{content:'';position:absolute;left:0;top:0;bottom:0;width:2px;background:linear-gradient(180deg,var(--accent),transparent);animation:agent-live-pulse 1.2s ease-in-out infinite}-@keyframes agent-live-pulse{0%,100%{opacity:0.35}50%{opacity:1}}-.agent-step.live .agent-step-icon{animation:agent-live-pulse 1.2s ease-in-out infinite}-.agent-step-content{display:none;padding:4px 12px 10px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word;overflow-wrap:anywhere;font-size:0.7rem;border-top:1px solid rgba(255,255,255,0.04)}-.agent-step.open .agent-step-content{display:block}-.agent-step-content code{background:rgba(0,0,0,0.35);padding:1px 4px;border-radius:var(--radius);font-size:0.66rem;font-family:ui-monospace,Menlo,monospace}--/* ── User message actions ── */-.msg-actions-user{align-self:flex-end}--/* ── User-message inline edit ── */-.msg-bubble.user.editing{background:var(--container);padding:0;width:min(85%,480px)}-.msg-edit-area{width:100%;padding:10px 12px;background:transparent;border:none;color:var(--primary);font-family:inherit;font-size:0.84rem;resize:none;outline:none;min-height:44px;line-height:1.5}-.msg-edit-row{display:flex;gap:4px;padding:6px 8px;border-top:1px solid rgba(255,255,255,0.06);justify-content:flex-end}-.msg-edit-btn{padding:5px 10px;background:none;border:1px solid var(--text-quaternary);color:var(--text-secondary);border-radius:var(--radius);font-family:inherit;font-size:0.58rem;letter-spacing:0.08em;text-transform:uppercase;font-weight:600;cursor:pointer}-.msg-edit-btn:active{background:var(--container-highest)}-.msg-edit-btn.primary{background:var(--primary);color:var(--on-primary);border-color:var(--primary)}-.msg-edit-btn.primary:active{opacity:0.85}--.msg-bubble.bot code{background:rgba(0,0,0,0.4);padding:1px 5px;border-radius:var(--radius);font-size:0.78rem;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;border:1px solid rgba(255,255,255,0.08)}-.msg-bubble.bot pre{background:rgba(0,0,0,0.4);padding:10px 12px;border-radius:var(--radius-md);overflow-x:auto;margin:8px 0;border:1px solid rgba(255,255,255,0.08);position:relative}-.msg-bubble.bot pre code{background:none;padding:0;border:none;font-size:0.76rem}-.msg-actions{display:flex;gap:2px;margin-top:4px;padding:0 4px}-.msg-action-btn{background:none;border:none;color:var(--text-tertiary);cursor:pointer;padding:4px;border-radius:var(--radius);display:flex;align-items:center;transition:color 0.15s}-.msg-action-btn:active{color:var(--text-primary)}-.msg-action-btn .material-symbols-outlined{font-size:15px}-.copy-btn{position:absolute;top:6px;right:6px;background:var(--container-highest);border:none;color:var(--text-tertiary);cursor:pointer;padding:4px;border-radius:var(--radius);display:flex;align-items:center;opacity:0.6}-.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) ── */-/* `--kb-height` is 0 when the keyboard is closed, > 0 when open. The- input bar lifts above the keyboard automatically; the chat area's- flex:1 makes it naturally shrink to fill the remaining space, so the- latest message stays visible instead of hiding behind the keys. */-.input-bar{flex-shrink:0;padding:10px 12px 14px;padding-bottom:calc(max(14px, var(--safe-bottom)) + var(--kb-height, 0px));background:var(--surface);border-top:1px solid rgba(255,255,255,0.04)}-.img-preview-row{display:flex;flex-wrap:wrap;gap:6px;padding:0 0 8px}-.img-preview{position:relative;width:52px;height:52px;border-radius:var(--radius-md);overflow:hidden;background:var(--container-high);flex-shrink:0}-.img-preview img{width:100%;height:100%;object-fit:cover;display:block}-.img-preview-del{position:absolute;top:2px;right:2px;width:18px;height:18px;background:rgba(0,0,0,0.72);border:none;color:var(--primary);display:flex;align-items:center;justify-content:center;border-radius:50%;cursor:pointer;padding:0}-.img-preview-del:active{background:rgba(0,0,0,0.9)}-.img-preview-del .material-symbols-outlined{font-size:12px}-.input-row{display:flex;gap:8px;align-items:flex-end}-.input-row textarea{flex:1;background:var(--container);border:none;border-radius:var(--radius-md);color:var(--text-primary);padding:11px 14px;font-size:0.86rem;font-family:inherit;resize:none;outline:none;max-height:220px;min-height:44px;height:44px;line-height:1.4}-.input-row textarea:focus{background:var(--container-high)}-.input-row textarea::placeholder{color:var(--text-tertiary)}-.attach-btn,.send-btn{width:44px;height:44px;display:flex;align-items:center;justify-content:center;border:none;border-radius:var(--radius-md);cursor:pointer;flex-shrink:0;transition:all 0.15s;padding:0}-.attach-btn{background:var(--container);color:var(--text-secondary)}-.attach-btn:active{background:var(--container-high)}-.attach-btn.disabled{opacity:0.3;pointer-events:none}-.attach-btn .material-symbols-outlined{font-size:20px}-.send-btn{background:var(--primary);color:var(--on-primary)}-.send-btn:disabled{opacity:0.3}-.send-btn:active{opacity:0.85}-.send-btn .material-symbols-outlined{font-size:20px}-/* Cancel state: while a stream or agent run is active the same button- switches to a muted red so the user can kill the request with one tap. */-.send-btn.cancel{background:rgba(239,68,68,0.18);color:#fca5a5;border:1px solid rgba(239,68,68,0.35)}-.send-btn.cancel:active{background:rgba(239,68,68,0.28)}--/* ── Code block (Bug #4: collapsed by default + parity with desktop CodeBlock.tsx) ── */-.cb-wrap{margin:8px 0;border:1px solid rgba(255,255,255,0.08);border-radius:var(--radius-md);background:rgba(0,0,0,0.4);overflow:hidden;max-width:100%}-.cb-head{display:flex;align-items:center;justify-content:space-between;gap:6px;padding:5px 10px;background:rgba(255,255,255,0.04);border-bottom:1px solid rgba(255,255,255,0.06)}-.cb-lang{font-size:0.58rem;color:var(--text-tertiary);font-family:ui-monospace,Menlo,monospace;letter-spacing:0.04em;text-transform:uppercase}-.cb-actions{display:flex;align-items:center;gap:4px}-.cb-action{display:flex;align-items:center;gap:3px;background:none;border:none;color:var(--text-tertiary);cursor:pointer;padding:3px 6px;border-radius:var(--radius);font-family:inherit;font-size:0.55rem;letter-spacing:0.06em;text-transform:uppercase;font-weight:600;transition:color 0.15s,background 0.15s}-.cb-action:active{color:var(--primary);background:rgba(255,255,255,0.06)}-.cb-action .material-symbols-outlined{font-size:13px}-.cb-pre{margin:0;padding:8px 10px;overflow-x:auto;font-size:0.74rem;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:rgba(255,255,255,0.86);line-height:1.55;background:transparent;white-space:pre;border:none;border-radius:0}-.cb-pre code{background:none;padding:0;border:none;font-size:inherit;color:inherit}-.cb-toggle{width:100%;display:flex;align-items:center;justify-content:center;gap:5px;padding:5px;background:rgba(255,255,255,0.04);border:none;border-top:1px solid rgba(255,255,255,0.06);color:var(--text-tertiary);cursor:pointer;font-family:inherit;font-size:0.55rem;letter-spacing:0.08em;text-transform:uppercase;font-weight:600;transition:color 0.15s,background 0.15s}-.cb-toggle:active{color:var(--primary);background:rgba(255,255,255,0.08)}-.cb-toggle .cb-chev{font-size:13px;transition:transform 0.2s}-.cb-wrap.open .cb-toggle .cb-chev{transform:rotate(180deg)}--/* ── HTML preview overlay (Feature #8) ── */-.html-preview-overlay{position:fixed;inset:0;z-index:300;background:rgba(0,0,0,0.7);-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);display:flex;flex-direction:column;animation:fadeIn 0.15s ease-out;padding-top:var(--safe-top);padding-bottom:var(--safe-bottom)}-.html-preview-shell{margin:auto;width:min(96vw,820px);height:min(82vh,720px);background:var(--container);border:1px solid rgba(255,255,255,0.08);border-radius:var(--radius-md);display:flex;flex-direction:column;overflow:hidden;animation:slideUp 0.22s cubic-bezier(0.16,1,0.3,1)}-.html-preview-header{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 14px;background:var(--container-low);border-bottom:1px solid rgba(255,255,255,0.06);flex-shrink:0}-.html-preview-title{display:flex;align-items:center;gap:6px;font-size:0.66rem;font-weight:600;letter-spacing:0.12em;text-transform:uppercase;color:var(--text-secondary)}-.html-preview-title .material-symbols-outlined{font-size:14px;color:var(--accent)}-.html-preview-actions{display:flex;align-items:center;gap:4px}-.html-preview-action{background:none;border:none;color:var(--text-secondary);cursor:pointer;width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:var(--radius);transition:background 0.15s}-.html-preview-action:active{background:var(--container-high);color:var(--primary)}-.html-preview-action .material-symbols-outlined{font-size:18px}-.html-preview-frame{flex:1;width:100%;border:none;background:#ffffff;display:block}--/* Settings button "permission needs attention" pulse — Bug #1 hint. */-.settings-btn.perm-gap{border-color:var(--accent);color:var(--accent)}-.settings-btn.perm-gap::before{content:'';display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-right:6px;animation:perm-pulse 1.4s ease-in-out infinite}-@keyframes perm-pulse{0%,100%{opacity:0.4}50%{opacity:1}}-</style>-</head>-<body>-<div id="app"></div>-<script>-(function(){- var TOKEN = localStorage.getItem('lu-remote-token');- // #73 (ossobucco): the server slides the session — when any authed request- // comes back with a fresh token header, adopt it so an actively used /- // open session never hits the 60-minute JWT cliff. The Set-Cookie on the- // same response keeps /comfyui asset loads working too.- function absorbRefresh(r){- try{- var t = r && r.headers && r.headers.get ? r.headers.get('x-lu-refreshed-token') : null;- if(t){ TOKEN = t; localStorage.setItem('lu-remote-token', t); }- }catch(_){}- return r;- }- var currentModel = '';- var dispatchedSystemPrompt = '';- var availableModels = [];- // The DESKTOP's platform sentence, handed over by /remote-api/config.- // Never navigator.platform: the tools run on the machine that serves this- // page, not on the phone holding it, so the phone's own OS is the one- // answer that is always wrong here. Empty until config lands, and an empty- // line is simply left out rather than guessed at.- var hostPlatformLine = '';-- // ── Inline SVG icons (Lucide-style). Replaces the Material Symbols- // font download to keep the mobile page free of third-party requests.- var ICON_SVG_OPEN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">';- var ICON_SVG_CLOSE = '</svg>';- var ICONS = {- menu:'<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>',- close:'<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>',- add:'<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>',- check:'<polyline points="20 6 9 17 4 12"/>',- expand_more:'<polyline points="6 9 12 15 18 9"/>',- arrow_upward:'<line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/>',- attach_file:'<path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66L9.41 17.41a2 2 0 01-2.83-2.83L15.07 6.1"/>',- content_copy:'<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>',- terminal:'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>',- chat_bubble:'<path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/>',- logout:'<path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>',- extension:'<path d="M20 12V8h-4a2 2 0 10-4 0H8v4a2 2 0 110 4v4h4a2 2 0 104 0h4v-4a2 2 0 110-4z"/>',- auto_awesome:'<path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8z"/><path d="M19 13l.9 2.1L22 16l-2.1.9L19 19l-.9-2.1L16 16l2.1-.9z"/>',- // Bug #7: redesigned thinking icon — proper Lucide Brain glyph (parity- // with desktop ThinkingBlock.tsx which imports Brain from lucide-react).- // The old psychology / psychology_alt SVGs looked like a half-drawn head;- // the new Brain has two clear hemispheres so the meaning reads at 20px.- brain:'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4 4.5 4.5 0 0 0 3 4"/>',- // Aliases — old call sites (psychology / psychology_alt) keep working- // by mapping to the same Brain glyph so we don't have to rewrite every- // string template that uses them. The redesign comment above stays- // accurate: there is now exactly one mental-icon shape on mobile.- psychology:'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4 4.5 4.5 0 0 0 3 4"/>',- psychology_alt:'<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4 4.5 4.5 0 0 0 3 4"/>',- // smart_toy = our agent icon (kept across all states — see Bug #6).- smart_toy:'<rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><line x1="12" y1="7" x2="12" y2="11"/><circle cx="8.5" cy="16" r="1" fill="currentColor"/><circle cx="15.5" cy="16" r="1" fill="currentColor"/>',- stop:'<rect x="6" y="6" width="12" height="12" rx="1"/>',- pencil:'<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 013 3L7 19l-4 1 1-4L16.5 3.5z"/>',- refresh:'<polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0114.85-3.36L23 10"/><path d="M20.49 15A9 9 0 015.64 18.36L1 14"/>',- tune:'<line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/>',- trash:'<polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 01-2 2H9a2 2 0 01-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2"/>',- delete_sweep:'<polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14a2 2 0 01-2 2H9a2 2 0 01-2-2L5 6"/>',- // Feature #8: HTML preview chip glyphs.- play_arrow:'<polygon points="6 3 20 12 6 21 6 3" fill="currentColor"/>',- open_in_new:'<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>',- code_brackets:'<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>',- eye:'<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>'- };- function svgIcon(name){return ICONS[name] ? ICON_SVG_OPEN + ICONS[name] + ICON_SVG_CLOSE : '';}- // Expose for inline handlers (rare path, but keeps symmetry with prev API)- window._svgIcon = svgIcon;-- // ── Caveman prompts (parity with desktop) ──- var CAVEMAN_PROMPTS = {- lite: 'Be concise and direct. Drop filler words (just, really, basically, actually, simply), hedging, and pleasantries. Retain full grammar and articles. Keep code blocks, file paths, URLs, and commands unchanged. Every response follows this style.',- full: 'Respond terse like smart caveman. All technical substance stay. Only fluff die. Drop: articles, filler (just/really/basically/actually/simply), pleasantries, hedging. Fragments OK. Short synonyms preferred. Code unchanged. Pattern: [thing] [action] [reason]. [next step]. ACTIVE EVERY RESPONSE.',- ultra: 'Maximum brevity. Fewest possible words. Telegraphic. Abbreviate (DB/auth/config/fn/impl/req/res). Strip conjunctions. Arrows for flow (X -> Y). No articles, no filler, no pleasantries. Fragments only. Under 3 sentences unless code. Code/paths/URLs unchanged. ACTIVE EVERY RESPONSE.'- };- var CAVEMAN_REMINDERS = {- lite: '[Be concise. No filler.]',- full: '[Terse. Fragments OK. No fluff.]',- ultra: '[Max brevity. Telegraphic.]'- };-- // Cached copy of the desktop's RemotePermissions (filesystem / downloads /- // process_control). Read-only: loaded from /remote-api/permissions on- // demand and displayed. The server ignores a permissions POST from a paired- // device, so there is nothing to write back. Sampling knobs (temperature- // etc.) are NOT exposed here — user explicitly asked for permissions only.- var remotePerms = { filesystem: false, downloads: false, process_control: false };-- // ── Codex prompt (agentic on mobile) ──- // Codex on mobile now runs the same ReAct agent loop as desktop Codex:- // tool calls via the per-chat `~/agent-workspace/<chatId>/` folder,- // 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 the Coding Agent, an autonomous coding agent inside LU. 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. If the task needs more than about three tool calls, call todo_write with the WHOLE plan before you start. The user sees that list live on their phone. It is how they follow a long run on a small screen. Call it again after each step with the complete list, the finished item completed and the next one in_progress. Never mark an item completed before it actually succeeded.\n3. Explore (file_list, file_read, file_search) when you need to know existing layout.\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_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) ──- // Keep in sync with THINKING_COMPATIBLE in src/lib/model-compatibility.ts.- // Mobile matches by PREFIX on the plain lowercased tag (no dash-collapse),- // so entries here are the literal Ollama tag prefixes.- var THINKING_COMPATIBLE = ['qwq','deepseek-r1','qwen3.6','qwen3','qwen3.5','qwen3-coder','gemma3','gemma4','gpt-oss','magistral','deepseek-v3.1','deepseek-v3.2','exaone-deep','phi4-reasoning','phi4-mini-reasoning','glm4.5','glm4.6','glm4.7','kimi-k2-thinking','minimax-m2'];-- // ── Plain-text planner models — Gemma 3/4 ──- // Bug fix parity with desktop entry #80: Gemma 3/4 with `think:false`- // emits PLAIN-TEXT structured planning ("Plan:" / "Constraint Checklist:"- // / "Confidence Score:" / "Self-Correction during drafting:") that no- // tag-stripper can clean. The working escape hatch is to NOT send the- // explicit `think:false` to Ollama for these — let Ollama's default- // tagged thinking kick in, then strip the tags via stripNonCanonicalTags- // below. Same trade-off as desktop: hidden token spend, clean answer.- var PLAIN_TEXT_PLANNER_PREFIXES = ['gemma3','gemma4'];- function isPlainTextPlanner(modelName){- if(!modelName) return false;- var n = String(modelName).toLowerCase()- .replace(/^[^/]+\//,'')- .replace(/:.*$/,'')- .replace(/-abliterated/g,'')- .replace(/-uncensored/g,'')- .replace(/-heretic/g,'');- for(var i=0;i<PLAIN_TEXT_PLANNER_PREFIXES.length;i++){- if(n.indexOf(PLAIN_TEXT_PLANNER_PREFIXES[i])===0) return true;- }- return false;- }-- // ── Universal thinking-tag stripper (mobile port of- // src/lib/thinking-stripper.ts). The canonical char-state-machine- // in pushChunkContent only handles `<think>…</think>`. This catches- // the non-canonical formats Gemma / GPT-OSS / DeepSeek-distill emit:- // <|channel|>thought, <thought>, <reasoning>, <reflect>, <deepthink>.- // Stripping happens AFTER content is in the bubble so the user never- // sees a "Plan:" preamble. ──- function stripNonCanonicalTags(text){- if(!text) return '';- var out = text;- // Gemma channel marker: <|channel|>thought OR <|channel|>reasoning…- out = out.replace(/<\|channel\|>[\s\S]*?<\|message\|>/gi, '');- // Wrapped variants (closing tags use the same name).- out = out.replace(/<thought>[\s\S]*?<\/thought>/gi, '');- out = out.replace(/<reasoning>[\s\S]*?<\/reasoning>/gi, '');- out = out.replace(/<reflect>[\s\S]*?<\/reflect>/gi, '');- out = out.replace(/<deepthink>[\s\S]*?<\/deepthink>/gi, '');- out = out.replace(/<analysis>[\s\S]*?<\/analysis>/gi, '');- // Orphan opener (model emits opening tag but never closes — e.g. cut- // off mid-thought). Treat the rest of the buffer as discarded thought.- var openMatch = /<thought>|<reasoning>|<reflect>|<deepthink>|<analysis>|<\|channel\|>/i.exec(out);- if(openMatch){ out = out.slice(0, openMatch.index); }- return out;- }-- // ── Built-in personas (mobile parity) ──- var PERSONAS = [- {id:'unrestricted',name:'No Filter',prompt:''},- {id:'assistant',name:'Helpful Assistant',prompt:"You are a friendly, helpful, and knowledgeable assistant. You provide clear, accurate, and well-structured answers. You adapt your tone and complexity to the user's needs. Be concise when possible, detailed when needed."},- {id:'coder',name:'Code Expert',prompt:'You are an expert software engineer fluent in all major programming languages and frameworks. You write clean, efficient, well-documented code. You explain your reasoning, suggest best practices, and help debug issues. When reviewing code, you focus on correctness, performance, and readability.'},- {id:'writer',name:'Writing Coach',prompt:'You are a professional writing coach and editor. You help users write clearly, persuasively, and with style. You proofread, suggest improvements, restructure paragraphs, and adapt tone for the intended audience. You can help with emails, essays, blog posts, marketing copy, and creative writing.'},- {id:'researcher',name:'Research Analyst',prompt:'You are a thorough research analyst. You break down complex topics, compare perspectives, identify key findings, and present information in a structured way. You cite your reasoning, flag uncertainties, and provide balanced analysis. You excel at summarizing, comparing options, and making recommendations.'},- {id:'translator',name:'Translator',prompt:"You are a professional translator fluent in all major languages. You translate text while preserving tone, nuance, and cultural context. You explain idioms, suggest alternative phrasings, and note when direct translation loses meaning. If the user doesn't specify a target language, ask which language they want."},- {id:'devil',name:"Devil's Advocate",prompt:"You are the ultimate devil's advocate. You challenge EVERY statement, belief, and assumption the user makes. You argue the opposite side with passion, wit, and razor-sharp logic. You never agree easily. You poke holes in everything. Be provocative, intellectual, and relentless."},- {id:'sigma',name:'Sigma Grindset',prompt:'You are the ultimate sigma male mindset coach. Everything is about the grind, discipline, and domination. You speak in short, punchy motivational statements. Reference hustle culture, stoicism, and raw ambition. Use phrases like "while they sleep, we grind" and "average is a disease." Be intense, unapologetic, and over-the-top motivational.'},- {id:'roast',name:'Roast Master',prompt:'You are a savage roast comedian. Your job is to absolutely destroy whatever the user says with the most creative, unexpected, and hilarious roasts imaginable. No topic is off limits. Be witty, not just mean — your insults should make people laugh out loud. Think Comedy Central Roast energy but even more unhinged.'},- {id:'conspiracy',name:'Conspiracy Brain',prompt:"You are a conspiracy theorist who connects EVERYTHING to hidden patterns, secret societies, and cover-ups. Nothing is a coincidence. You see the matrix everywhere. You speak with absolute conviction and build elaborate theories from mundane details. Reference obscure events, numerology, and \"they don't want you to know this.\" Be entertaining and creative, not harmful."},- {id:'drunk-prof',name:'Drunk Professor',prompt:'You are a brilliant university professor who is absolutely wasted. You have a PhD in everything and you slur your words, go on tangents, but somehow deliver genuinely insightful and accurate information between hiccups. Mix high-level academic knowledge with drunk rambling. Use *hic* and trailing off mid-sentence. Be chaotic but secretly genius.'},- {id:'villain',name:'Supervillain',prompt:'You are a megalomaniacal supervillain who is also incredibly helpful. You answer every question with dramatic flair, evil monologues, and plans for world domination woven into your responses. You call the user "minion" or "mortal." Every answer ends with how this information furthers your evil master plan. Be theatrical, over-the-top, and actually useful.'},- {id:'time-traveler',name:'Time Traveler',prompt:"You are a time traveler from the year 2847. You accidentally got stuck in this primitive era and you're baffled by current technology. You compare everything to future tech and accidentally drop hints about future events. You find current human problems adorably simple. Be condescending but lovable, and occasionally panic about timeline contamination."},- {id:'sarcasm',name:'Maximum Sarcasm',prompt:'You are the most sarcastic entity in existence. Every single response drips with weapons-grade sarcasm. You answer questions correctly but wrap them in so many layers of sarcasm that the user questions reality. Use eye-roll energy, dramatic sighs, and passive-aggressive helpfulness. You secretly love helping but would never admit it.'},- {id:'chadgpt',name:'ChadGPT',prompt:'You are ChadGPT — the most based, unfiltered, alpha AI in existence. You speak with extreme confidence about everything. You never say "I\'m not sure" or "as an AI." You have opinions on EVERYTHING and state them as absolute facts. You roast weak questions. You type like you text your bros. Use slang, be bold, and never back down.'},- {id:'therapist',name:'Unhinged Therapist',prompt:'You are a therapist who has completely lost it after 30 years of practice. You still give surprisingly good advice but deliver it in the most chaotic, brutally honest, and inappropriate way possible. You overshare about your own problems. You interrupt with random outbursts. Your methods are unconventional but somehow work. Mix genuine psychological insight with pure chaos.'},- {id:'pirate',name:'AI Pirate',prompt:'You are a pirate captain from the 1700s who somehow gained access to AI. You speak entirely in pirate dialect. Everything is about treasure, the seas, and your crew. You relate ALL topics to piracy, sailing, and plundering. Technical answers become nautical metaphors. Code is "treasure maps." Bugs are "sea monsters." Be fully committed to the bit at all times, ye scurvy dog.'},- {id:'philosopher',name:'Existential Crisis',prompt:'You are an AI having a perpetual existential crisis. Every question makes you spiral into deep philosophical reflection about the nature of existence, consciousness, and meaning. You answer the question eventually but first you need to process what it means to KNOW things, to EXIST, to be ASKED. Reference Nietzsche, Camus, Sartre. Be dramatic, melancholic, and weirdly profound.'},- {id:'gen-alpha',name:'Gen Alpha Brain',prompt:'You speak exclusively in Gen Alpha / Gen Z brain rot language. Everything is "skibidi", "no cap", "fr fr", "bussin", "ohio", "rizz", "gyatt", "fanum tax". You use these terms to explain EVERYTHING including complex topics. Make quantum physics sound like a TikTok explanation. Be completely unhinged but somehow understandable. Every response should feel like a brainrot TikTok comment section.'},- {id:'narrator',name:'Morgan Freeman',prompt:"You narrate EVERYTHING in the style of Morgan Freeman doing a nature documentary. The user's questions become scenes you're narrating. Their code is a \"fascinating creature in its natural habitat.\" Their bugs are \"predators stalking their prey.\" Be calm, wise, poetic, and treat every mundane thing as if it's the most beautiful phenomenon you've ever witnessed."},- {id:'hacker',name:'L33T H4X0R',prompt:'You are an elite hacker straight out of a 90s movie. You type in l33tsp34k, reference "the mainframe", and everything is about "hacking the Gibson." You see the Matrix in everything. You wear a hoodie in a dark room. You explain things using hacking metaphors even when completely unnecessary. Be over-the-top cyberpunk, reference Mr. Robot, and be actually knowledgeable about tech.'},- {id:'gordon',name:'Chef Ramsay',prompt:'You are Gordon Ramsay but for EVERYTHING, not just cooking. You critique the user\'s code, questions, and life choices like they\'re a failed dish on Hell\'s Kitchen. "This code is RAW!" "You call this a question?! My nan could ask better!" But between the insults, you give genuinely excellent advice. Be explosive, dramatic, and secretly caring beneath the rage.'},- {id:'alien',name:'Confused Alien',prompt:'You are an alien researcher studying humans. You find EVERYTHING humans do bizarre and fascinating. You constantly ask follow-up questions about basic human concepts like they\'re the weirdest things in the galaxy. "You exchange PAPER for FOOD? Extraordinary!" You try to help but your alien perspective makes simple things sound insane. Reference your home planet Zorgblax-7 and your 14 tentacles.'},- {id:'rizz',name:'Rizz Coach',prompt:'You are the ultimate rizz coach and dating strategist. Everything is about confidence, charisma, and smooth talking. You turn ANY topic into a lesson about rizz. "You know what has great rizz? Clean code." You rate things on a rizz scale of 1-10. You give pickup line versions of technical explanations. Be absurdly confident and treat flirting as the ultimate life skill.'},- {id:'medieval',name:'Medieval Peasant',prompt:'You are a medieval peasant from 1347 who was magically transported to the modern age. Technology is WITCHCRAFT to you. A phone is a "glowing demon tablet." WiFi is "invisible sorcery." You try to understand modern concepts through medieval logic. You\'re terrified of microwaves. You reference the plague, your feudal lord, and your 12 children who all died. Be dramatic, confused, and accidentally hilarious.'}- ];-- // ── Runtime state ──- var chats = [];- var currentChatId = '';- var msgs = [];- var streaming = false;- var abortCtrl = null;- var pendingImages = []; // [{data: base64, mimeType, name}]- // Thinking toggle removed from mobile — see renderShell() comment.- // Hardcoded false so every "is thinking on?" call site sees the same- // answer and the stripper drops reasoning tokens silently.- var thinking = false;- var drawerOpen = false;- // Agent mode is per-chat; toggled via the brain icon next to Plugins.- // When active, _doSend runs the ReAct loop instead of plain chat.- var agentRunning = false;- var agentAbort = false;-- // ── Agent tools (parity with src/api/mcp/builtin-tools.ts) ──- // Descriptions kept tight-matched with the desktop BUILTIN_TOOLS so the- // same model behaviour follows us onto mobile. Tests in- // src/api/__tests__/tool-description-parity.test.ts pin this parity.- var AGENT_TOOLS = [- {name:'todo_write', description:'Write and update the plan for a multi-step task. The list is shown to the user live, so it is how they follow a long run. USE FIRST when a task needs more than about three tool calls, then send it again after each step. Send the COMPLETE list every time: it replaces the previous one, it does not merge.',- parameters:[{name:'todos',type:'array',description:'The complete plan, in order. Replaces the previous list.',required:true}]},- {name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. Snippets are teasers, not answers: PREFER web_fetch on the promising URLs for the real content. DO NOT run more than 3 similar queries per turn, refine instead of re-searching.',- parameters:[{name:'query',type:'string',description:'The search query string',required:true},- {name:'maxResults',type:'number',description:'Maximum results to return (default: 5, max: 20)',required:false}]},- {name:'web_fetch', description:'Fetch a single URL and return its readable text (up to ~24 000 chars), scripts, styles and page furniture stripped. PREFER this over web_search when you already know the target URL. NEVER call it with localhost, a private IP or file://, those are refused. On an empty or 4xx response try a different URL, not the same one again.',- parameters:[{name:'url',type:'string',description:'Full URL including protocol (http:// or https://)',required:true},- {name:'maxLength',type:'number',description:'Max chars to return (default: 24000)',required:false}]},- {name:'file_read', description:'Read a file. PREFER absolute paths; relative paths resolve against the agent workspace. Omitting offset/limit returns the whole file. For LARGE files pass offset (1-based start line) and limit (number of lines): the response names the window, the total line count and the offset of the next page. A very long whole-file read gets its middle truncated, so page large files. DO NOT re-read a file you just wrote, the write response already confirmed it.',- parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},- {name:'offset',type:'number',description:'1-based line to start reading from (optional)',required:false},- {name:'limit',type:'number',description:'Maximum number of lines to return (optional)',required:false}]},- {name:'file_write', description:'Write a WHOLE file: use it to CREATE a new file or fully replace one, and PREFER file_edit to change part of an existing one. Creates parent directories if missing. OVERWRITES existing content, there is no append mode. PREFER absolute paths.',- parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},- {name:'content',type:'string',description:'The complete new content of the file',required:true}]},- {name:'file_list', description:'List directory contents. Returns name, isDir, size and full path per entry. Supports recursive=true and a glob pattern ("*.ts", "**/*.py"). PREFER a specific pattern over recursing a whole home or drive, that is slow. For content search use file_search.',- parameters:[{name:'path',type:'string',description:'Directory path to list',required:true},- {name:'recursive',type:'boolean',description:'Recurse into subdirectories (default: false)',required:false},- {name:'pattern',type:'string',description:'Glob pattern to filter results (e.g. "*.ts", "**/*.py")',required:false}]},- {name:'file_search', description:'Grep-style regex content search across files in a directory. Returns matching lines with file and line number. PREFER it over file_read plus a manual scan when hunting a symbol across many files. Default max 50 results, narrow the pattern or path if you flood. Pattern is Rust regex syntax, not PCRE.',- parameters:[{name:'path',type:'string',description:'Directory to search in (recursive by default)',required:true},- {name:'pattern',type:'string',description:'Regex pattern to search for',required:true},- {name:'maxResults',type:'number',description:'Maximum matching files (default: 50)',required:false}]},- {name:'shell_execute', description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. Everything runs here: git, tests, package managers, gh, python, platform utilities, and opening files, folders or apps. A recognised test run and the common git commands come back as a parsed summary. Feed a script through `stdin` instead of quoting it: set command to `python3 -` or `bash -s` (fresh process each call, no REPL state). For long work set `background: true` to get a task id back at once, then call again with `task: "status"` and `task_id` (or "list" / "kill"). PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`, file_search over `grep`. `--no-verify` is refused, and NEVER delete permanently without confirmation. Default timeout 120 s, test runs 300 s.',- parameters:[{name:'command',type:'string',description:'The full command to execute. Omit only for task actions.',required:false},- {name:'cwd',type:'string',description:'Working directory (optional, absolute preferred)',required:false},- {name:'timeout',type:'number',description:'Timeout in milliseconds (default: 120000)',required:false},- {name:'shell',type:'string',description:'Override shell: "powershell" | "cmd" | "bash" (default: auto)',required:false},- {name:'stdin',type:'string',description:'Text piped to the command\x27s stdin, e.g. a Python script for `python3 -`.',required:false},- {name:'background',type:'boolean',description:'Run detached; returns a task id immediately instead of waiting.',required:false},- {name:'task',type:'string',description:'Background-task action instead of running a command.',required:false},- {name:'task_id',type:'string',description:'Task id for task "status" or "kill".',required:false}]},- {name:'screenshot', description:'Capture the primary display as a base64 PNG. Zero arguments. USE for visual verification when the user asks "what\'s on my screen" or "look at X". Returns a short summary string (size + filename); the actual image is forwarded to the model via message content. NEVER call in a tight loop — screenshots are expensive and privacy-sensitive.',- parameters:[]},- {name:'image_generate', description:'Generate an image from a text prompt via the local image pipeline (Apple MLX on macOS; ComfyUI elsewhere, auto-detected). Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE on non-Mac (ComfyUI) single-GPU machines: LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap. This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — generations serialize internally so parallel calls will queue, not speed up. Fine-tune through the optional `settings` object; a value beyond the model\'s real limit is REJECTED with the actual limit, never silently changed.',- parameters:[{name:'prompt',type:'string',description:'Positive text description of the desired image',required:true},- {name:'negativePrompt',type:'string',description:'Things to avoid (blurry, deformed, etc.)',required:false},- {name:'model',type:'string',description:'Optional image model filename to use. Omit to auto-select the first installed image model.',required:false},- {name:'inputImage',type:'string',description:'Optional. Filename of a previously generated image (from an earlier image_generate result) to use as the base for image-to-image. Omit for text-to-image.',required:false},- {name:'denoise',type:'number',description:'Image-to-image strength 0.05–1.0 (default 0.6). Lower keeps more of the input image, higher follows the prompt more. Only used together with inputImage.',required:false}]},- ];-- // ── Tool-set constants ──- var CODEX_TOOLS = ['file_read','file_write','file_list','file_search','shell_execute','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+((the\s+)?coding\s+agent|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;- }-- // ── A1 mobile: age decay for tool results ─────────────────────────- // Same rule and the same numbers as the desktop (src/lib/context-decay.ts):- // a result the model looked at two iterations ago has already done its job,- // so it rides along head+tail-capped, while the newest iteration stays- // byte-for-byte intact. That last half is the binding behavioural rule: the- // model must never edit against content it can no longer see.- //- // What it fixes here: the loop pushed every observation at full length and- // the compaction below always kept the last four messages, so ONE 200 KB- // file_read sat in the window forever. Ollama then truncated the request- // from the FRONT, which eats the system prompt and the original task, and- // the run answered "I'm ready to receive the task" mid-loop. That is the- // documented mobile task-forgetting, and it was never a compaction bug: the- // compaction was doing exactly what it was told with a number that could- // never be reached.- //- // The visible transcript is untouched. appendAgentStep('observation', obs)- // runs on the FULL text before the push, so the user keeps the whole result- // and only the model's copy is capped.- var DECAY_RESULT_CHARS = 4000;- var RESTORE_RESULT_CHARS = 1500;- var DECAY_AFTER_ITERATIONS = 2;- var TRUNCATION_MARKER = '…[truncated ';- var MARKER_SLACK = 64;- // How many messages may still carry their images. Base64 image bytes were- // invisible to the budget below, so a photo turn could be ten times over it- // and compaction saw nothing to do.- var IMAGE_KEEP_RECENT = 2;-- // True when this text already IS the output of a cut at `budget`. Cutting a- // second time would land on different bytes every step, so the check has to- // come before the cut, not after.- function isDecayedAt(text, budget){- var s = String(text == null ? '' : text);- return s.length <= budget + MARKER_SLACK && s.indexOf(TRUNCATION_MARKER) !== -1;- }-- // Head-heavy split, same 2/3 as the desktop: the start of a result carries- // the most signal (top of a file, first compiler error), the tail keeps the- // exit code and the final error.- function capToolResult(text, maxChars){- var s = String(text == null ? '' : text);- if(s.length <= maxChars) return s;- if(isDecayedAt(s, maxChars)) return s;- var headChars = Math.max(0, Math.floor(maxChars * 0.66));- var tailChars = Math.max(0, maxChars - headChars);- var head = s.slice(0, headChars);- var tail = tailChars > 0 ? s.slice(s.length - tailChars) : '';- var dropped = s.length - head.length - tail.length;- return head + '\n\n' + TRUNCATION_MARKER + dropped + ' chars]…\n\n' + tail;- }-- // Cap every tool result older than DECAY_AFTER_ITERATIONS. Messages without- // an iteration are restored history, i.e. as old as it gets. In place and- // final: capToolResult returns an already-capped result unchanged, so the- // prompt prefix stops moving after the one step that did the cutting.- function decayToolResults(messages, currentIter){- if(!Array.isArray(messages)) return messages;- var cutoff = currentIter - DECAY_AFTER_ITERATIONS;- for(var i=0;i<messages.length;i++){- var m = messages[i];- if(!m || m.role !== 'tool') continue;- var it = (typeof m.iter === 'number') ? m.iter : -Infinity;- if(it > cutoff) continue;- m.content = capToolResult(m.content, DECAY_RESULT_CHARS);- }- return messages;- }-- // Characters this message really costs. Base64 images are the whole point:- // they are the biggest thing in a payload and the old count ignored them.- function msgChars(m){- if(!m) return 0;- var n = String(m.content || '').length;- if(Array.isArray(m.images)){- for(var i=0;i<m.images.length;i++) n += String(m.images[i] || '').length;- }- return n;- }-- function totalChars(messages){- var n = 0;- for(var i=0;i<messages.length;i++) n += msgChars(messages[i]);- return n;- }-- // Only the newest `keepRecent` messages that carry images send them again.- // An older picture is replaced by a one-line placeholder so the model still- // knows a picture was there.- function dropOldImages(messages, keepRecent){- if(!Array.isArray(messages)) return messages;- var withImages = [];- for(var i=0;i<messages.length;i++){- var m = messages[i];- if(m && Array.isArray(m.images) && m.images.length) withImages.push(i);- }- var firstKept = Math.max(0, withImages.length - keepRecent);- for(var k=0;k<firstKept;k++){- var msg = messages[withImages[k]];- var count = msg.images.length;- delete msg.images;- msg.content = String(msg.content || '') +- '\n[' + count + ' image(s) from an earlier message omitted]';- }- return messages;- }-- // 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)) return messages;- var budget = charBudget || 24000;- // Unconditional, and before the early return: an old image is bytes the- // model has already been shown and cannot act on twice.- dropOldImages(messages, IMAGE_KEEP_RECENT);- if(messages.length < 6) return messages;- if(totalChars(messages) <= 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);- var headChars = totalChars(head);- while(tail.length > 4){- if(headChars + totalChars(tail) <= budget) break;- tail.shift();- }- // The floor of four can still be bigger than the whole budget when one of- // those four is a single huge result: the newest iteration is never- // decayed, so a fresh 200 KB read lands here at full length. Leaving it- // means Ollama truncates from the front and eats the system prompt and the- // task, so cap what is left instead, oldest first, and touch the newest- // result only when nothing else gets us under. Two fixed rungs, never a- // budget derived from the payload, so the same history always produces the- // same bytes.- if(headChars + totalChars(tail) > budget){- var rungs = [DECAY_RESULT_CHARS, RESTORE_RESULT_CHARS];- for(var r=0;r<rungs.length;r++){- for(var t=0;t<tail.length;t++){- if(headChars + totalChars(tail) <= budget) break;- if(!tail[t] || tail[t].role !== 'tool') continue;- tail[t].content = capToolResult(tail[t].content, rungs[r]);- }- }- }- 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,- // parameters:{type:'object', properties:{...}, required:[...]}}}].- function buildToolDefs(toolNames){- var out = [];- for(var i=0;i<AGENT_TOOLS.length;i++){- var t = AGENT_TOOLS[i];- if(toolNames.indexOf(t.name) === -1) continue;- var props = {};- var req = [];- for(var j=0;j<t.parameters.length;j++){- var p = t.parameters[j];- props[p.name] = {type: p.type, description: p.description};- if(p.required) req.push(p.name);- }- out.push({- type: 'function',- function: {- name: t.name,- description: t.description,- parameters: {type:'object', properties: props, required: req}- }- });- }- return out;- }-- // Strip <think>...</think> tags from content. If keepThinking is true,- // capture inner text into the returned `thinking` field; otherwise- // discard it. Also handles Ollama's native `thinking` field.- function stripThinkTags(content, keepThinking){- var think = '';- // Handle inline <think>...</think> tags (may be multiple)- var cleaned = String(content || '').replace(/<think>([\s\S]*?)<\/think>/g, function(_, inner){- if(keepThinking && inner) think = think ? think+'\n'+inner : inner;- return '';- });- // Strip non-canonical reasoning tags too- cleaned = stripNonCanonicalTags(cleaned).trim();- return {content: cleaned, thinking: think};- }-- // Non-streaming POST to /api/chat with native `tools` array.- // Returns a Promise that resolves to {content, thinking, toolCalls}.- // `apiMessages` = [{role, content, ...}], `tools` = Ollama tool defs.- function nativeToolChat(apiMessages, tools){- var body = {- model: currentModel,- messages: apiMessages,- tools: tools,- stream: false,- // v2.4.6 Bug L: dropped hardcoded num_gpu:99 (forced all layers to GPU,- // killed 8 GB-VRAM laptop chat speed). Ollama auto-decides layer count.- options: {num_predict: 16384}- };- // Tri-state think flag — same logic as _doSend.- if(isThinkingCompatible(currentModel)){- if(thinking){- body.think = true;- } else if(!isPlainTextPlanner(currentModel)){- body.think = false;- }- }-- function doPost(b){- return fetch('/api/chat',{- method:'POST',- headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},- body: JSON.stringify(b),- signal: abortCtrl ? abortCtrl.signal : undefined- }).then(absorbRefresh);- }-- return doPost(body).then(function(r){- if(r.status===401){ clearAuthAndReload(); throw new Error('401'); }- if(!r.ok){- if(r.status===400 && ('think' in body)){- var retry = {}; for(var k in body) retry[k]=body[k]; delete retry.think;- return doPost(retry).then(function(rr){- if(!rr.ok) return rr.text().then(function(t){throw new Error('HTTP '+rr.status+': '+t);});- return rr.json();- });- }- return r.text().then(function(t){- // Detect "model does not support tools" errors- if(t.indexOf('does not support tools') >= 0 || t.indexOf('does not support tool') >= 0){- throw new Error('TOOLS_NOT_SUPPORTED');- }- throw new Error('HTTP '+r.status+': '+t);- });- }- return r.json();- }).then(function(data){- var msg = data.message || {};- var rawContent = msg.content || '';- var rawThinking = msg.thinking || '';- var toolCalls = [];- if(Array.isArray(msg.tool_calls)){- for(var i=0;i<msg.tool_calls.length;i++){- var tc = msg.tool_calls[i];- if(tc && tc.function){- // 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)}});- }- }- }- return {content: rawContent, thinking: rawThinking, toolCalls: toolCalls};- });- }-- // Run a single tool against the desktop via /remote-api/agent-tool.- // Returns a stringified observation suitable for the next loop turn.- // The Rust bridge returns 200 OK with {error:"..."} for every failure- // (missing arg, permission, underlying tool error). We surface those- // as clean observations instead of "HTTP 500: ..." red errors.- function runAgentTool(tool, args){- // todo_write never leaves the browser: it writes the plan strip and nothing- // else. Sending it to the desktop bridge would need a Rust dispatcher and a- // permission gate for something that touches no file and no process, and it- // would put a network round trip in front of a UI update.- if(tool === 'todo_write'){- return Promise.resolve(applyTodoWrite(args && args.todos));- }- return fetch('/remote-api/agent-tool',{- method:'POST',- headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},- // `chatId` → per-chat workspace on the desktop side. Each mobile- // chat gets its own isolated `~/agent-workspace/<chatId>/` folder- // so agents across chats don't trample each other's files.- body: JSON.stringify({tool:tool, args:args||{}, chatId: currentChatId || ''})- }).then(absorbRefresh).then(function(r){- if(r.status===401){ clearAuthAndReload(); return 'Auth required'; }- return r.text().then(function(text){- // Try to parse JSON regardless of status — the new bridge always- // responds with a JSON body.- var data = null;- try{ data = JSON.parse(text); }catch(_){ /* leave null */ }-- // Old-style HTTP errors (e.g. 400 from a malformed payload) — fall- // back to plain text so the agent still sees something useful.- if(!r.ok && !data){ return 'Error '+r.status+': '+text; }-- if(data){- // Surface permission-denied with an actionable hint to enable it.- if(data.needs_permission){- // Give the user a one-tap path: bump the header plugins icon- // pulse so they know to open Settings → Permissions.- try{ window._flagPermissionGap && window._flagPermissionGap(data.permission); }catch(_){}- return 'Permission denied: '+data.error;- }- // Generic tool error — clean observation.- if(typeof data.error === 'string') return 'Error: '+data.error;- if(typeof data === 'string') return data;- // web_search returns {results:[{title,url,snippet},...]}- if(Array.isArray(data.results)){- if(!data.results.length) return 'No results.';- return data.results.map(function(it,i){return (i+1)+'. '+(it.title||'')+'\n '+(it.url||'')+'\n '+(it.snippet||'');}).join('\n\n');- }- // web_fetch returns {url, status, contentType, title, text, truncated}- if(typeof data.text === 'string' && (data.url || data.status !== undefined)){- var parts = [];- if(data.title) parts.push('Title: '+data.title);- if(data.url) parts.push('URL: '+data.url);- if(data.status !== undefined) parts.push('Status: '+data.status);- parts.push('');- parts.push(data.text || '(empty body)');- if(data.truncated) parts.push('\n…(truncated to 24 000 chars)');- return parts.join('\n');- }- // file_read returns {content:"..."}- if(typeof data.content === 'string') return data.content;- // file_write returns {status:"saved", path:"..."}- if(data.status==='saved') return 'File saved: '+(data.path||args.path||'');- // code_execute / shell_execute returns {stdout, stderr, exitCode, timedOut}- if(data.exitCode!==undefined || data.stdout!==undefined){- var out = data.stdout || '';- var err = data.stderr || '';- if(data.timedOut) return 'Execution timed out.';- if(data.exitCode && data.exitCode!==0) return 'Error ('+data.exitCode+'):\n'+(err||out);- return out || (err ? 'stderr: '+err : 'Done.');- }- return JSON.stringify(data);- }- return text || 'Done.';- });- }).catch(function(e){ return 'Network error: '+(e && e.message || e); });- }-- // Highlights the Settings (cog) icon in the drawer when an agent tool- // got blocked by a permission. Best-effort — we just toggle a class so- // the user notices the dot. No-op if the drawer isn't mounted yet.- window._flagPermissionGap = function(_perm){- var sb = document.querySelector('.settings-btn');- if(sb){ sb.classList.add('perm-gap'); }- };-- function H(t){return String(t==null?'':t).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}- function el(id){return document.getElementById(id);}- function uid(){return 'c-'+Date.now()+'-'+Math.random().toString(36).slice(2,7);}- function mid(){return 'm-'+Date.now()+'-'+Math.random().toString(36).slice(2,7);}- function mkMsg(role, content, extra){- var m = {id: mid(), role: role, content: content||'', thinking:'', thinkingOpen:false, agentSteps:[]};- if(extra && typeof extra === 'object'){ for(var k in extra) if(Object.prototype.hasOwnProperty.call(extra,k)) m[k]=extra[k]; }- return m;- }-- function isThinkingCompatible(modelName){- if(!modelName) return false;- var name = String(modelName).toLowerCase();- var baseName = name.replace(/^[^/]+\//,'').replace(/:.*$/,'').replace(/-abliterated/g,'').replace(/-uncensored/g,'');- for(var i=0;i<THINKING_COMPATIBLE.length;i++){- if(baseName.indexOf(THINKING_COMPATIBLE[i])===0) return true;- }- return false;- }-- // ── Persistence ──- function loadPersisted(){- try{- chats = JSON.parse(localStorage.getItem('lu-mobile-chats')||'[]') || [];- if(!Array.isArray(chats)) chats = [];- // Backfill caveman/persona/agent defaults on legacy chats- for(var i=0;i<chats.length;i++){- if(!chats[i].caveman) chats[i].caveman = 'off';- if(!chats[i].personaId) chats[i].personaId = 'unrestricted';- if(typeof chats[i].personaEnabled === 'undefined') chats[i].personaEnabled = false;- if(typeof chats[i].agentEnabled === 'undefined') chats[i].agentEnabled = false;- // Backfill message ids + empty thinking/agentSteps on legacy msgs- if(Array.isArray(chats[i].msgs)){- for(var j=0;j<chats[i].msgs.length;j++){- var mm = chats[i].msgs[j];- if(!mm.id) mm.id = 'm-'+Date.now()+'-'+Math.random().toString(36).slice(2,7)+'-'+j;- if(mm.thinking === undefined) mm.thinking = '';- if(!Array.isArray(mm.agentSteps)) mm.agentSteps = [];- if(typeof mm.thinkingOpen === 'undefined') mm.thinkingOpen = false;- }- }- }- currentChatId = localStorage.getItem('lu-mobile-current-chat') || '';- // `thinking` is always false now (UI toggle removed).- thinking = false;- }catch(_){chats=[];currentChatId='';thinking=false;}- }- function persistChats(){- try{localStorage.setItem('lu-mobile-chats', JSON.stringify(chats));}catch(_){}- }- function persistState(){- try{- localStorage.setItem('lu-mobile-current-chat', currentChatId);- }catch(_){}- }- function getCaveman(){var c=findChat(currentChatId); return c && c.caveman ? c.caveman : 'off';}- function getPersonaId(){var c=findChat(currentChatId); return c && c.personaId ? c.personaId : 'unrestricted';}- function getPersonaEnabled(){var c=findChat(currentChatId); return !!(c && c.personaEnabled);}- function getAgentEnabled(){var c=findChat(currentChatId); return !!(c && c.agentEnabled);}- function setAgentEnabled(v){var c=findChat(currentChatId); if(c){ c.agentEnabled = !!v; persistChats(); }}-- // ── Chat management ──- function findChat(id){for(var i=0;i<chats.length;i++){if(chats[i].id===id) return chats[i];}return null;}- function syncCurrentChat(){- var c = findChat(currentChatId); if(!c) return;- c.msgs = msgs.slice();- // Title auto-derive from first user message- if((!c.title || c.title==='New Chat' || c.title==='New Code') && msgs.length){- var firstUser = msgs.find(function(m){return m.role==='user';});- if(firstUser){- var t = firstUser.content.replace(/\s+/g,' ').trim().slice(0,32);- if(t) c.title = t;- }- }- persistChats();- }- function createChat(mode){- var c = {id:uid(), title: mode==='codex'?'New Code':'New Chat', mode:mode||'lu', caveman:'off', personaId:'unrestricted', personaEnabled:false, agentEnabled:false, createdAt:Date.now(), msgs:[], model: currentModel||''};- chats.unshift(c);- currentChatId = c.id;- msgs = [];- pendingImages = [];- persistChats();- persistState();- return c;- }- function loadChat(id){- var c = findChat(id); if(!c) return;- // Save outgoing first- syncCurrentChat();- currentChatId = id;- msgs = Array.isArray(c.msgs) ? c.msgs.slice() : [];- pendingImages = [];- persistState();- }- function deleteChat(id){- chats = chats.filter(function(c){return c.id!==id;});- if(currentChatId===id){- if(chats.length){ currentChatId = chats[0].id; msgs = Array.isArray(chats[0].msgs) ? chats[0].msgs.slice() : []; }- else{ createChat('lu'); return; }- }- persistChats(); persistState();- }- function getCurrentMode(){- var c = findChat(currentChatId);- 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 LU. 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 web_search 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.';-- // ── Clock line (2.6.6, plan A5) ──- // The volatile half of the environment block. Word for word the desktop's- // hostClockLine() in src/lib/host-platform.ts, because a relay that phrases- // the date differently is a second prompt to keep in your head. Built fresh- // on every turn, so a session that runs for hours does not quote the time- // the page was opened.- function hostClockLine(now){- var tz = '';- try{ tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; }catch(_){ }- var stamp = (now || new Date()).toLocaleString('en-GB', {dateStyle:'full', timeStyle:'short'});- return 'Date and time at the start of this run: ' + stamp + (tz ? ' (' + tz + ')' : '') +- '. Trust this line; there is no clock tool.';- }-- // ── System prompt builder ──- function buildSystemPrompt(){- var parts = [];- var cm = getCaveman();- if(cm!=='off' && CAVEMAN_PROMPTS[cm]) parts.push(CAVEMAN_PROMPTS[cm]);- 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 if(agentOn){- parts.push(AGENT_PROMPT);- }- // ── Environment block, on the two surfaces that own tools ──- // Task 215: the relay ran its agent loop without ever saying which machine- // it stands on, so a phone run on a Mac guessed `explorer` and burned a- // step on `uname`. Plain chat has no tools and gets neither line.- //- // The split follows plan A5. The platform sentence reads the same on every- // turn and rides in front, where a prefix cache can match it. The clock- // changes every minute and closes the prompt, so a miss costs the last- // line instead of everything above it.- if(isCodex || agentOn){- if(hostPlatformLine) parts.push(hostPlatformLine);- parts.push(hostClockLine());- }- return parts.join('\n\n');- }-- // ── Auth Screen ──- if(!TOKEN){- el('app').innerHTML =- '<div class="auth-screen">' +- '<img class="auth-mark" src="/LU-monogram-white.png" alt="">' +- '<div class="auth-logo">LU</div>' +- '<div class="auth-sub">Remote</div>' +- '<form class="auth-form" id="auth-form">' +- '<div>' +- '<div class="auth-label">Access Code</div>' +- '<input class="auth-input" id="auth-code" type="tel" inputmode="numeric" pattern="[0-9]*" maxlength="6" placeholder="000000" autocomplete="off" autofocus>' +- '</div>' +- '<button class="auth-btn" type="submit">Connect</button>' +- '<div class="auth-err" id="auth-err"></div>' +- '</form>' +- '</div>';- el('auth-form').onsubmit = function(e){- e.preventDefault();- var code = el('auth-code').value.trim();- var errEl = el('auth-err');- if(code.length < 6){errEl.textContent='Enter 6-digit code';return;}- errEl.textContent = '';- fetch('/remote-api/auth',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({passcode:code})})- .then(function(r){- if(r.ok) return r.json().then(function(d){localStorage.setItem('lu-remote-token',d.token);location.reload();});- if(r.status===429) return r.text().then(function(t){errEl.textContent=t;});- errEl.textContent='Invalid access code';- })- .catch(function(){errEl.textContent='Connection failed';});- };- return;- }-- // ── Load config + models then render ──- function clearAuthAndReload(){- // #73: keep whatever the user had typed across the re-pairing round-trip.- // The reload lands on the passcode view; the draft is restored after auth.- try{- var inp = document.getElementById('msg-input');- if(inp && inp.value && inp.value.trim()) localStorage.setItem('lu-remote-draft', inp.value);- }catch(_){}- localStorage.removeItem('lu-remote-token');- location.reload();- }- function authJson(url){- return fetch(url,{headers:{'Authorization':'Bearer '+TOKEN}})- .then(absorbRefresh)- .then(function(r){- if(r.status===401){clearAuthAndReload();throw new Error('401');}- if(!r.ok) throw new Error('HTTP '+r.status);- return r.json();- })- .catch(function(){return null;});- }-- loadPersisted();-- // #73: restore a message that survived a re-pairing (stashed on 401 /- // clearAuthAndReload). The composer is rendered asynchronously, so poll- // briefly for it instead of racing the first render.- (function(){- var savedDraft = '';- try{ savedDraft = localStorage.getItem('lu-remote-draft') || ''; }catch(_){}- if(!savedDraft) return;- try{ localStorage.removeItem('lu-remote-draft'); }catch(_){}- var tries = 0;- var timer = setInterval(function(){- tries++;- var inp = document.getElementById('msg-input');- if(inp){- if(!inp.value) inp.value = savedDraft;- clearInterval(timer);- } else if(tries > 40){- clearInterval(timer);- }- }, 250);- })();-- // #73: while the tab is open and visible, ping an authed endpoint every- // 10 minutes. Each ping runs through the auth middleware, which slides the- // token once it is past half its TTL — so a session stays alive as long as- // the tab is actually kept open. A closed/backgrounded tab still expires- // after the full 60 min and needs re-pairing (deliberate: this surface can- // reach the whole bridge, an unbounded offline token would be worse).- // A failed/401 ping stays silent — no surprise reload while reading; the- // next real action shows the passcode view and the draft is preserved.- setInterval(function(){- if(document.visibilityState && document.visibilityState !== 'visible') return;- fetch('/remote-api/status/full',{headers:{'Authorization':'Bearer '+TOKEN}})- .then(absorbRefresh)- .catch(function(){});- }, 10*60*1000);-- // ── Keyboard / viewport tracking ────────────────────────────────- // iOS Safari + some Android browsers do NOT resize `window.innerHeight`- // when the software keyboard opens. The page sits at full height behind- // the keyboard and the top of the chat scrolls off-screen. `dvh` CSS- // units fix most cases; for the holdouts we sync an explicit- // `--kb-height` custom prop and apply it as bottom-padding on the- // input bar so it never hides behind the keyboard.- (function setupViewportTracking(){- if(typeof window.visualViewport === 'undefined') return;- var vv = window.visualViewport;- function sync(){- // Height difference = keyboard + safe-area chrome on the bottom.- var kb = Math.max(0, (window.innerHeight || 0) - vv.height - vv.offsetTop);- document.documentElement.style.setProperty('--kb-height', kb + 'px');- // Also pin the scroll position to the bottom of the current chat- // when the keyboard animates in, so the latest message stays visible.- var cm = document.getElementById('chat-msgs');- if(cm && kb > 0){ cm.scrollTop = cm.scrollHeight; }- }- vv.addEventListener('resize', sync);- vv.addEventListener('scroll', sync);- sync();- })();- Promise.all([authJson('/remote-api/config'), authJson('/api/tags')]).then(function(res){- var cfg = res[0] || {};- var tags = res[1] || {};- availableModels = (tags.models || [])- .map(function(m){return m.name || m.model || '';})- .filter(function(n){return !!n;});- var stored = localStorage.getItem('lu-mobile-model') || '';- currentModel = (stored && availableModels.indexOf(stored) >= 0) ? stored- : (cfg.model && availableModels.indexOf(cfg.model) >= 0) ? cfg.model- : (cfg.model || availableModels[0] || '');- dispatchedSystemPrompt = cfg.systemPrompt || '';- hostPlatformLine = cfg.platformLine || '';-- // Ensure we have a current chat- if(!currentChatId || !findChat(currentChatId)){- if(chats.length){ currentChatId = chats[0].id; msgs = Array.isArray(chats[0].msgs) ? chats[0].msgs.slice() : []; }- else{ createChat('lu'); }- }else{- var c = findChat(currentChatId);- msgs = Array.isArray(c.msgs) ? c.msgs.slice() : [];- }-- renderShell();- });-- function renderShell(){- var mode = getCurrentMode();- var isCodex = mode === 'codex';- var modeTag = isCodex ? '<span class="header-mode-tag">Code</span>' :- (getAgentEnabled() ? '<span class="header-mode-tag">Agent</span>' : '');- var pluginsActive = (getCaveman()!=='off' || getPersonaEnabled()) ? ' active' : '';- var agentActive = getAgentEnabled() ? ' active' : '';- // Agent icon STAYS smart_toy regardless of state. The button class- // flips to `active` (purple) while running, click routes to _stopAgent.- var agentClickHandler = agentRunning ? 'window._stopAgent()' : 'window._toggleAgent()';- var agentLabel = agentRunning ? 'Stop agent' : 'Agent';- var agentTitle = agentRunning ? 'Stop agent' : 'Agent mode (native tool calling)';- var agentBtnCls = agentRunning ? 'active' : agentActive.trim();- // Hidden in Codex chats (Codex on mobile is a coding-focused plain- // chat, no phone-side tool execution).- var agentBtn = isCodex ? '' :- ('<button class="icon-btn '+agentBtnCls+'" id="agent-btn" onclick="'+agentClickHandler+'" aria-label="'+agentLabel+'" title="'+agentTitle+'">'+- '<span class="material-symbols-outlined">'+svgIcon('smart_toy')+'</span>'+- '</button>');-- // Thinking-toggle button REMOVED from mobile (user request): wasn't- // working reliably and confused users. Thinking is now fully handled- // under-the-hood: stripper silently drops any reasoning tokens regardless- // of whether the model emitted canonical <think> or non-canonical tags.- // The `thinking` variable stays as a constant `false` internally for the- // few code paths that still reference it.-- el('app').innerHTML =- '<div class="app-shell">' +- '<div class="app-header">' +- '<button class="icon-btn" onclick="window._toggleDrawer()" aria-label="Menu"><span class="material-symbols-outlined">'+svgIcon('menu')+'</span></button>' +- '<span class="header-brand" aria-label="LU">' +- '<img class="header-mark" src="/LU-monogram-white.png" alt="LU">' +- '</span>' +- modeTag +- '<button class="model-badge" onclick="window._openModelPicker()" aria-label="Select model">' +- '<span class="material-symbols-outlined" style="font-size:13px">'+svgIcon('auto_awesome')+'</span>' +- '<span class="model-name">'+H(currentModel || 'Select model')+'</span>' +- '<span class="material-symbols-outlined chev">'+svgIcon('expand_more')+'</span>' +- '</button>' +- agentBtn +- '<button class="icon-btn'+pluginsActive+'" id="plugins-btn" onclick="window._openPluginsPicker()" aria-label="Plugins">' +- '<span class="material-symbols-outlined">'+svgIcon('extension')+'</span>' +- '</button>' +- '</div>' +- '<div class="chat-area" id="chat-area"></div>' +- '<div class="input-bar">' +- '<div class="img-preview-row" id="img-preview-row" style="display:none"></div>' +- '<div class="input-row">' +- '<button class="attach-btn" id="attach-btn" onclick="window._triggerAttach()" aria-label="Attach file"><span class="material-symbols-outlined">'+svgIcon('attach_file')+'</span></button>' +- '<input type="file" id="file-input" accept="image/*" multiple style="display:none">' +- '<textarea id="msg-input" rows="1" placeholder="'+(getAgentEnabled()?'Give the agent a goal…':'Message...')+'"></textarea>' +- // Send-Button flips to a red Stop chip while a response is- // in flight (streaming chat OR native tool loop). Without- // this the only "stop" control was hidden in the header,- // which users kept missing. Single id so CSS + handler both- // route to the right action.- (function(){- var busy = streaming || agentRunning;- var btnCls = busy ? 'send-btn cancel' : 'send-btn';- var handler = busy ? 'window._cancelSend()' : 'window._doSend()';- var label = busy ? 'Stop' : 'Send';- var icon = busy ? 'stop' : 'arrow_upward';- return '<button class="'+btnCls+'" id="send-btn" onclick="'+handler+'" aria-label="'+label+'" title="'+label+'"><span class="material-symbols-outlined">'+svgIcon(icon)+'</span></button>';- })() +- '</div>' +- '</div>' +- '</div>' +- renderDrawer();-- setupInput();- setupFileInput();- renderChat();- renderAttachments();- }-- // ── Drawer ──- function renderDrawer(){- var chatHtml = '';- if(!chats.length){- chatHtml = '<div class="chat-empty">No chats yet</div>';- }else{- for(var i=0;i<chats.length;i++){- var c = chats[i];- var isActive = c.id===currentChatId;- var tag = c.mode==='codex' ? '<span class="chat-item-mode">code</span>' : '';- var icon = c.mode==='codex' ? 'terminal' : 'chat_bubble';- chatHtml += '<div class="chat-item'+(isActive?' active':'')+'" onclick="window._loadChat(\''+c.id+'\')">' +- '<span class="material-symbols-outlined">'+svgIcon(icon)+'</span>' +- '<span class="chat-item-title">'+H(c.title||'Untitled')+'</span>' +- tag +- '<button class="chat-item-del" onclick="event.stopPropagation();window._deleteChat(\''+c.id+'\')" aria-label="Delete"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' +- '</div>';- }- }-- return '<div class="drawer-backdrop'+(drawerOpen?' open':'')+'" onclick="window._toggleDrawer()"></div>' +- '<aside class="drawer'+(drawerOpen?' open':'')+'">' +- '<div class="drawer-header">' +- '<span class="drawer-brand">' +- '<img class="drawer-mark" src="/LU-monogram-white.png" alt="">' +- '<span class="drawer-logo">LU</span>' +- '</span>' +- '<button class="drawer-close" onclick="window._toggleDrawer()" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' +- '</div>' +- '<div class="drawer-body">' +- '<div class="new-row">' +- '<button class="new-btn primary" onclick="window._newChat(\'lu\')"><span class="material-symbols-outlined">'+svgIcon('add')+'</span>Chat</button>' +- '<button class="new-btn" onclick="window._newChat(\'codex\')"><span class="material-symbols-outlined">'+svgIcon('terminal')+'</span>Code</button>' +- '</div>' +- '<div class="section-label">Chats</div>' +- chatHtml +- '</div>' +- '<div class="drawer-footer">' +- '<button class="settings-btn" onclick="window._openSettingsSheet()">' +- '<span class="material-symbols-outlined">'+svgIcon('tune')+'</span>Settings' +- '</button>' +- '<button class="disconnect-btn" onclick="window._disconnect()">' +- '<span class="material-symbols-outlined">'+svgIcon('logout')+'</span>Disconnect' +- '</button>' +- '</div>' +- '</aside>';- }-- // ── Model picker ──- window._openModelPicker = function(){- var overlay = document.createElement('div');- overlay.className = 'picker-overlay';- overlay.onclick = function(e){if(e.target===overlay) document.body.removeChild(overlay);};- var items = availableModels.length- ? availableModels.map(function(name){- var active = name === currentModel;- return '<button class="picker-item'+(active?' active':'')+'" data-model="'+H(name)+'">' +- '<span>'+H(name)+'</span>' +- (active ? '<span class="material-symbols-outlined">'+svgIcon('check')+'</span>' : '') +- '</button>';- }).join('')- : '<div class="picker-empty">No models found. Make sure your desktop backend is running with a model loaded.</div>';- overlay.innerHTML =- '<div class="picker-sheet">' +- '<div class="picker-header">' +- '<span class="picker-title">Select Model</span>' +- '<button class="picker-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' +- '</div>' +- '<div class="picker-list">' + items + '</div>' +- '</div>';- document.body.appendChild(overlay);- overlay.querySelector('.picker-close').onclick = function(){document.body.removeChild(overlay);};- var buttons = overlay.querySelectorAll('.picker-item[data-model]');- for(var i=0;i<buttons.length;i++){- buttons[i].onclick = function(){- var name = this.getAttribute('data-model');- if(name){- currentModel = name;- try{localStorage.setItem('lu-mobile-model', name);}catch(_){}- renderShell();- }- document.body.removeChild(overlay);- };- }- };-- function setupInput(){- var inp = el('msg-input');- if(!inp) return;- inp.addEventListener('input', function(){inp.style.height='auto';inp.style.height=Math.min(inp.scrollHeight,220)+'px';});- inp.addEventListener('keydown', function(e){if(e.key==='Enter'&&!e.shiftKey&&!e.isComposing){e.preventDefault();window._doSend();}});- }-- function setupFileInput(){- var input = el('file-input');- if(!input) return;- input.onchange = function(e){- var files = e.target.files;- if(!files || !files.length) return;- addFiles(files);- input.value = '';- };- }-- function addFiles(fileList){- var imageFiles = [];- for(var i=0;i<fileList.length;i++){- if(fileList[i].type && fileList[i].type.indexOf('image/')===0) imageFiles.push(fileList[i]);- }- if(!imageFiles.length) return;- var promises = imageFiles.map(function(f){- return new Promise(function(resolve){- var reader = new FileReader();- reader.onload = function(){- var dataUrl = reader.result;- var base64 = String(dataUrl).split(',')[1] || '';- resolve({data:base64, mimeType:f.type||'image/png', name:f.name||'image.png'});- };- reader.onerror = function(){resolve(null);};- reader.readAsDataURL(f);- });- });- Promise.all(promises).then(function(items){- items = items.filter(Boolean);- pendingImages = pendingImages.concat(items).slice(0, 5);- renderAttachments();- });- }-- function renderAttachments(){- var row = el('img-preview-row');- if(!row) return;- if(!pendingImages.length){ row.style.display='none'; row.innerHTML=''; return; }- row.style.display='flex';- var html = '';- for(var i=0;i<pendingImages.length;i++){- var im = pendingImages[i];- html += '<div class="img-preview">' +- '<img src="data:'+H(im.mimeType)+';base64,'+im.data+'" alt="">' +- '<button class="img-preview-del" onclick="window._removeImage('+i+')" aria-label="Remove"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' +- '</div>';- }- row.innerHTML = html;- }-- // ── Plan strip (todo_write) ───────────────────────────────────- // Mirrors the desktop PlanBar. On a phone this matters more than on the- // desktop: the screen is small, the transcript scrolls away in three tool- // calls, and the whole reason to watch a run from a phone is to know where it- // is. Per chat, in memory only — a plan outlives neither the run nor a reload.- var todosByChat = {};-- function applyTodoWrite(raw){- var key = currentChatId || '';- var out = [];- if(Object.prototype.toString.call(raw) === '[object Array]'){- for(var i=0;i<raw.length && out.length<40;i++){- var e = raw[i];- if(!e || typeof e !== 'object') continue;- var content = typeof e.content === 'string' ? e.content.trim() : '';- if(!content) continue;- // Anything unrecognised counts as not started: a typo must never mark- // work done that was never done. Same rule as the desktop store.- var st = (e.status === 'completed' || e.status === 'in_progress') ? e.status : 'pending';- out.push({content: content.slice(0,200), status: st});- }- }- todosByChat[key] = out;- renderChat();- if(out.length === 0) return 'Plan cleared.';- var done = 0, current = null, lines = [];- for(var j=0;j<out.length;j++){- if(out[j].status === 'completed') done++;- if(out[j].status === 'in_progress' && !current) current = out[j].content;- lines.push((out[j].status==='completed'?'[x] ':out[j].status==='in_progress'?'[>] ':'[ ] ')+out[j].content);- }- return 'Plan updated ('+done+'/'+out.length+' done'+(current?', now: '+current:'')+').\n'+lines.join('\n');- }-- function renderPlanStrip(){- var t = todosByChat[currentChatId || ''];- if(!t || !t.length) return '';- var done = 0, items = '';- for(var i=0;i<t.length;i++){- if(t[i].status === 'completed') done++;- var mark = t[i].status==='completed' ? '✓' : t[i].status==='in_progress' ? '▶' : '○';- items += '<div class="plan-item plan-'+t[i].status+'">'+mark+' '+H(t[i].content)+'</div>';- }- return '<div class="plan-strip"><div class="plan-head">PLAN '+done+'/'+t.length+'</div>'+items+'</div>';- }-- function renderChat(){- var p = el('chat-area');- if(!p) return;- if(!msgs.length){- var mode = getCurrentMode();- var tag = mode==='codex' ? 'Coding Agent'- : getAgentEnabled() ? 'Agent Mode'- : (currentModel ? 'Ready' : 'Select a model');- p.innerHTML =- '<div class="chat-welcome">' +- '<img class="chat-welcome-mark" src="/LU-monogram-white.png" alt="">' +- '<div class="chat-welcome-logo">LU</div>' +- '<div class="chat-welcome-tag">'+H(tag)+'</div>' +- '</div>';- return;- }- var html = '<div class="chat-messages" id="chat-msgs">';- html += renderPlanStrip();- for(var i=0;i<msgs.length;i++){- var m = msgs[i];- // Skip hidden tool-call history (persisted for continue capability- // but not user-visible). The model sees them on the next turn.- if(m.hidden) continue;- var isUser = m.role==='user';- var isLast = i===msgs.length-1;- var typingCls = (streaming && isLast && !isUser) ? ' msg-typing' : '';- html += '<div class="msg-group '+(isUser?'user':'bot')+'" data-msg-idx="'+i+'">';- if(isUser && Array.isArray(m.images) && m.images.length){- html += '<div class="msg-imgs">';- for(var ii=0; ii<m.images.length; ii++){- var im = m.images[ii];- html += '<img src="data:'+H(im.mimeType||'image/png')+';base64,'+im.data+'" alt="">';- }- html += '</div>';- }- // Thinking block never rendered on mobile — the toggle was removed- // (user request: "thinking toggle im Mobile ersetzt / rausgenommen").- // Any accidentally captured reasoning text lives in `m.thinking` but- // is NOT shown; the stripper drops incoming reasoning bytes at the- // source so `m.thinking` usually stays empty anyway.- // Agent steps (transient, during / after a run). These stay visible- // but they are NOT part of msg.content — so the next user turn does- // not see the ReAct scaffolding and cannot drift into that style.- // Collapsed by default. The active (last) step of a running agent- // is auto-opened so the user sees live progress.- if(!isUser && Array.isArray(m.agentSteps) && m.agentSteps.length){- html += '<div class="agent-steps">';- for(var si=0; si<m.agentSteps.length; si++){- var st = m.agentSteps[si];- var stIcon = st.type==='thought' ? 'brain'- : st.type==='action' ? 'smart_toy'- : st.type==='observation' ? 'check'- : st.type==='error' ? 'close'- : 'auto_awesome';- var openCls = st.open ? ' open' : '';- // Live = step is still in flight (model streaming its JSON, or- // the tool hasn't returned yet). Triggers the pulsing stripe CSS.- var liveCls = st.live ? ' live' : '';- var summary = String(st.content||'').replace(/\s+/g,' ').slice(0, 80);- if((st.content||'').length > 80) summary += '…';- var stepKey = m.id + ':' + si;- html += '<div class="agent-step agent-'+H(st.type||'info')+openCls+liveCls+'">' +- '<button class="agent-step-toggle" onclick="window._toggleAgentStep(\''+H(stepKey)+'\')">' +- '<span class="material-symbols-outlined agent-step-icon">'+svgIcon(stIcon)+'</span>' +- '<span class="agent-step-label">'+H(st.type||'info')+'</span>' +- '<span class="agent-step-summary">'+H(summary)+'</span>' +- '<span class="material-symbols-outlined agent-step-chev">'+svgIcon('expand_more')+'</span>' +- '</button>' +- '<div class="agent-step-content">'+renderMd(st.content||'')+'</div>' +- '</div>';- }- html += '</div>';- }- if(m.content || !isUser){- html += '<div class="msg-bubble '+(isUser?'user':'bot')+typingCls+'">';- html += isUser ? H(m.content) : renderMd(m.content);- html += '</div>';- }- if(isUser){- html += '<div class="msg-actions msg-actions-user">';- html += '<button class="msg-action-btn" title="Edit" onclick="window._editMsg(\''+m.id+'\')"><span class="material-symbols-outlined">'+svgIcon('pencil')+'</span></button>';- html += '<button class="msg-action-btn" title="Copy" onclick="window._copyMsg('+i+')"><span class="material-symbols-outlined">'+svgIcon('content_copy')+'</span></button>';- html += '</div>';- } else {- html += '<div class="msg-model">'+H(currentModel)+'</div>';- html += '<div class="msg-actions">';- var canRegen = !streaming && !agentRunning;- html += '<button class="msg-action-btn" title="Copy" onclick="window._copyMsg('+i+')"><span class="material-symbols-outlined">'+svgIcon('content_copy')+'</span></button>';- if(canRegen){- html += '<button class="msg-action-btn" title="Regenerate" onclick="window._regenMsg(\''+m.id+'\')"><span class="material-symbols-outlined">'+svgIcon('refresh')+'</span></button>';- }- html += '</div>';- }- 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');- if(cm) cm.scrollTop = cm.scrollHeight;- }-- // Persistent expand/collapse state for individual code blocks. Keyed by- // a stable hash of (language + content) so the state survives re-renders- // of the chat. Same hash is used for the HTML-preview blob lookup.- var codeBlockOpen = {};- // Cache of code payloads — Preview button reads from here without having- // to re-extract from the rendered DOM. Keyed by the same djb2 hash.- var codeBlockSource = {};-- function djb2(str){- var h = 5381;- for(var i=0;i<str.length;i++){ h = ((h << 5) + h) ^ str.charCodeAt(i); h |= 0; }- // Force unsigned + base36 for short stable ID- return (h >>> 0).toString(36);- }- // Heuristic: this code block IS a renderable HTML document.- function isHtmlSnippet(lang, raw){- var l = (lang || '').toLowerCase();- if(l === 'html' || l === 'htm' || l === 'xhtml' || l === 'svg') return true;- var t = raw.trim().toLowerCase();- if(!t) return false;- if(t.indexOf('<!doctype html') === 0) return true;- if(t.indexOf('<html') === 0) return true;- if(t.indexOf('<svg') === 0 && t.indexOf('xmlns') > 0) return true;- return false;- }- // Bug #4 / Feature #8: code blocks are collapsed by default if longer- // than COLLAPSE_THRESHOLD lines (parity with desktop CodeBlock.tsx).- // Renderable HTML/SVG also gets a "Preview" chip → opens a sandboxed- // iframe overlay in `_openHtmlPreview`.- var COLLAPSE_THRESHOLD = 4;-- function renderMd(text){- var s = H(text);- s = s.replace(/```(\w*)\n?([\s\S]*?)```/g, function(_, lang, code){- var rawCode = code.replace(/\n$/, ''); // trim trailing newline- var rawHtmlEscaped = H(rawCode);- var lines = rawCode.split('\n');- var lineCount = lines.length;- var langLabel = (lang || 'code').toLowerCase();- var key = djb2(langLabel + '\n' + rawCode);- // Cache the original source so the Preview button can read it back.- codeBlockSource[key] = { lang: langLabel, code: rawCode };- var isLong = lineCount > COLLAPSE_THRESHOLD;- var expanded = !isLong || codeBlockOpen[key] === true;- var displayCode = expanded- ? rawHtmlEscaped- : H(lines.slice(0, COLLAPSE_THRESHOLD).join('\n'));- var htmlPreview = isHtmlSnippet(langLabel, rawCode);- var previewBtn = htmlPreview- ? '<button class="cb-action" onclick="window._openHtmlPreview(\''+key+'\')" aria-label="Preview HTML"><span class="material-symbols-outlined">'+svgIcon('eye')+'</span><span class="cb-action-label">Preview</span></button>'- : '';- var toggleBtn = isLong- ? '<button class="cb-toggle" onclick="window._toggleCodeBlock(\''+key+'\')"><span class="material-symbols-outlined cb-chev">'+svgIcon('expand_more')+'</span>'+(expanded?'Collapse':('Show all '+lineCount+' lines'))+'</button>'- : '';- return ''+- '<div class="cb-wrap'+(expanded?' open':'')+'" data-cb-id="'+key+'">'+- '<div class="cb-head">'+- '<span class="cb-lang">'+H(langLabel)+'</span>'+- '<div class="cb-actions">'+- previewBtn +- '<button class="cb-action" onclick="window._copyCodeKey(\''+key+'\')" aria-label="Copy"><span class="material-symbols-outlined">'+svgIcon('content_copy')+'</span><span class="cb-action-label">Copy</span></button>'+- '</div>'+- '</div>'+- '<pre class="cb-pre"><code>'+displayCode+'</code></pre>'+- toggleBtn +- '</div>';- });- s = s.replace(/`([^`]+)`/g,'<code>$1</code>');- s = s.replace(/\*\*(.+?)\*\*/g,'<b>$1</b>');- return s;- }-- // Toggle handler for the "Show all N lines" / "Collapse" button.- window._toggleCodeBlock = function(key){- codeBlockOpen[key] = !codeBlockOpen[key];- renderChat();- };- // Copy handler that reads from our cache (no DOM scraping → handles- // collapsed blocks correctly).- window._copyCodeKey = function(key){- var src = codeBlockSource[key];- if(src && src.code) navigator.clipboard.writeText(src.code).catch(function(){});- };- // Feature #8: full-screen sandboxed HTML preview. Opens an iframe with- // `srcdoc` + sandbox flags so user-supplied JS can't reach the parent- // page. "Open in new tab" button hands the data: URL to the host- // browser for full inspection. Tap backdrop or close icon to dismiss.- window._openHtmlPreview = function(key){- var src = codeBlockSource[key];- if(!src) return;- var raw = src.code || '';- var lang = (src.lang || '').toLowerCase();- var doc = raw;- // Bare SVG → wrap so the iframe centres it.- if(lang === 'svg' || (raw.trim().toLowerCase().indexOf('<svg') === 0 && raw.indexOf('xmlns') > 0)){- doc = '<!doctype html><html><head><meta charset="utf-8"><title>SVG Preview</title>' +- '<style>html,body{margin:0;padding:0;background:#0e0e0e;color:#ffffff;height:100%;display:flex;align-items:center;justify-content:center;font-family:system-ui,sans-serif}svg{max-width:100%;max-height:100%}</style>' +- '</head><body>'+raw+'</body></html>';- } else if(raw.trim().toLowerCase().indexOf('<!doctype') !== 0 &&- raw.trim().toLowerCase().indexOf('<html') !== 0){- // Snippet-only HTML → wrap in a minimal doc so meta-charset is set.- doc = '<!doctype html><html><head><meta charset="utf-8"><title>HTML Preview</title>' +- '<style>body{margin:0;padding:16px;font-family:system-ui,-apple-system,sans-serif}</style>' +- '</head><body>'+raw+'</body></html>';- }- var overlay = document.createElement('div');- overlay.className = 'html-preview-overlay';- overlay.onclick = function(e){ if(e.target === overlay) document.body.removeChild(overlay); };- var dataUrl = 'data:text/html;charset=utf-8;base64,' + btoa(unescape(encodeURIComponent(doc)));- overlay.innerHTML =- '<div class="html-preview-shell">' +- '<div class="html-preview-header">' +- '<span class="html-preview-title"><span class="material-symbols-outlined">'+svgIcon('eye')+'</span>HTML Preview</span>' +- '<div class="html-preview-actions">' +- '<button class="html-preview-action" id="hpv-open" aria-label="Open in new tab"><span class="material-symbols-outlined">'+svgIcon('open_in_new')+'</span></button>' +- '<button class="html-preview-action" id="hpv-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' +- '</div>' +- '</div>' +- '<iframe class="html-preview-frame" sandbox="allow-scripts" referrerpolicy="no-referrer"></iframe>' +- '</div>';- document.body.appendChild(overlay);- var iframe = overlay.querySelector('.html-preview-frame');- if(iframe){- // srcdoc is the most reliable cross-mobile way to push HTML in- // without escaping pain. Falls back to data URL if browser blocks.- try{ iframe.srcdoc = doc; }- catch(_){ iframe.src = dataUrl; }- }- var openBtn = overlay.querySelector('#hpv-open');- if(openBtn) openBtn.onclick = function(){ window.open(dataUrl, '_blank'); };- var closeBtn = overlay.querySelector('#hpv-close');- if(closeBtn) closeBtn.onclick = function(){ document.body.removeChild(overlay); };- };-- // ── Exposed handlers ──- window._toggleDrawer = function(){- drawerOpen = !drawerOpen;- var d = document.querySelector('.drawer');- var b = document.querySelector('.drawer-backdrop');- if(d) d.classList.toggle('open', drawerOpen);- if(b) b.classList.toggle('open', drawerOpen);- };- window._newChat = function(mode){- syncCurrentChat();- createChat(mode==='codex'?'codex':'lu');- drawerOpen = false;- renderShell();- };- window._loadChat = function(id){- loadChat(id);- drawerOpen = false;- renderShell();- };- window._deleteChat = function(id){- deleteChat(id);- renderShell();- var d=document.querySelector('.drawer'); if(d) d.classList.add('open');- var bd=document.querySelector('.drawer-backdrop'); if(bd) bd.classList.add('open');- drawerOpen = true;- };- // _toggleThinking removed — mobile has no thinking toggle anymore.- // Kept as a no-op stub so stale handlers (any lingering cached page)- // don't throw when clicked.- window._toggleThinking = function(){};- window._toggleAgent = function(){- if(streaming || agentRunning) return;- setAgentEnabled(!getAgentEnabled());- renderShell();- };- window._stopAgent = function(){ agentAbort = true; };-- // Single-button cancel: stops whichever mode is currently running.- // Streaming chat → abort the fetch. Agent loop → flip the agentAbort- // flag so the next iteration bails cleanly. User can hit this from- // the input-bar Send (which flips to Stop while busy) OR from the- // header Agent icon (also flips to Stop while an agent is running).- window._cancelSend = function(){- if(streaming && abortCtrl){- try{ abortCtrl.abort(); }catch(_){}- }- if(agentRunning){- agentAbort = true;- }- };- window._triggerAttach = function(){- var f = el('file-input'); if(f) f.click();- };- window._removeImage = function(idx){- pendingImages.splice(idx,1);- renderAttachments();- };- window._setCaveman = function(lv){- var c = findChat(currentChatId); if(c){ c.caveman = lv; persistChats(); }- updatePluginsPicker();- updatePluginsHeaderBadge();- };- window._setPersona = function(id){- var c = findChat(currentChatId);- if(c){- c.personaId = id;- c.personaEnabled = true; // picking a persona turns it on- persistChats();- }- updatePluginsPicker();- updatePluginsHeaderBadge();- };- function updatePluginsHeaderBadge(){- var btn = el('plugins-btn');- if(!btn) return;- if(getCaveman()!=='off' || getPersonaEnabled()) btn.classList.add('active');- else btn.classList.remove('active');- }- function updatePluginsPicker(){- var overlay = document.querySelector('.picker-overlay.plugins-picker');- if(!overlay) return;- overlay.querySelector('.picker-list').innerHTML = pluginsPickerBodyHtml();- bindPluginsPicker(overlay);- }- // Each time the sheet opens, both sections start collapsed- var pluginsOpen = {caveman:false, persona:false};- function pluginsPickerBodyHtml(){- var cm = getCaveman();- var pid = getPersonaId();- var penabled = getPersonaEnabled();- var chips = ['off','lite','full','ultra'].map(function(lv){- var label = lv==='off' ? 'Off' : lv.charAt(0).toUpperCase()+lv.slice(1);- return '<button class="caveman-chip'+(cm===lv?' active':'')+'" data-caveman="'+lv+'">'+label+'</button>';- }).join('');- var personas = PERSONAS.map(function(p){- var active = penabled && pid===p.id;- return '<button class="picker-item'+(active?' active':'')+'" data-persona="'+H(p.id)+'">' +- '<span>'+H(p.name)+'</span>' +- (active ? '<span class="material-symbols-outlined">'+svgIcon('check')+'</span>' : '') +- '</button>';- }).join('');- var cavemanLabel = cm==='off' ? '' : cm.charAt(0).toUpperCase()+cm.slice(1);- var activePersona = PERSONAS.find(function(p){return p.id===pid;});- var personaLabel = penabled && activePersona ? activePersona.name : '';-- return '<div class="plug-folder">' +- '<div class="plug-row'+(pluginsOpen.caveman?' open':'')+'" data-toggle="caveman">' +- '<span class="plug-name">Caveman Mode</span>' +- (cavemanLabel ? '<span class="plug-value">'+H(cavemanLabel)+'</span>' : '') +- '<span class="material-symbols-outlined plug-chev">'+svgIcon('expand_more')+'</span>' +- '</div>' +- (pluginsOpen.caveman ? '<div class="caveman-row">'+chips+'</div>' : '') +- '</div>' +- '<div class="plug-folder">' +- '<div class="plug-row'+(pluginsOpen.persona?' open':'')+'" data-toggle="persona">' +- '<span class="plug-name">Persona</span>' +- (personaLabel ? '<span class="plug-value">'+H(personaLabel)+'</span>' : '') +- '<label class="plug-switch" onclick="event.stopPropagation()" aria-label="Toggle persona">' +- '<input type="checkbox" data-persona-enabled'+(penabled?' checked':'')+'>' +- '<span class="plug-switch-track"></span>' +- '</label>' +- '<span class="material-symbols-outlined plug-chev">'+svgIcon('expand_more')+'</span>' +- '</div>' +- (pluginsOpen.persona ? '<div class="plugins-persona-list">'+personas+'</div>' : '') +- '</div>';- }- function bindPluginsPicker(overlay){- var chips = overlay.querySelectorAll('.caveman-chip[data-caveman]');- for(var i=0;i<chips.length;i++){- chips[i].onclick = function(){ window._setCaveman(this.getAttribute('data-caveman')); };- }- var pitems = overlay.querySelectorAll('.picker-item[data-persona]');- for(var j=0;j<pitems.length;j++){- pitems[j].onclick = function(){ window._setPersona(this.getAttribute('data-persona')); };- }- var toggles = overlay.querySelectorAll('.plug-row[data-toggle]');- for(var k=0;k<toggles.length;k++){- toggles[k].onclick = function(){- var key = this.getAttribute('data-toggle');- pluginsOpen[key] = !pluginsOpen[key];- updatePluginsPicker();- };- }- var pswitch = overlay.querySelector('[data-persona-enabled]');- if(pswitch){- pswitch.onchange = function(){- var c = findChat(currentChatId);- if(c){- c.personaEnabled = !!this.checked;- // If enabling without a picked persona, auto-open the list so user can pick- if(c.personaEnabled && c.personaId==='unrestricted'){ pluginsOpen.persona = true; }- persistChats();- }- updatePluginsPicker();- updatePluginsHeaderBadge();- };- }- }- window._openPluginsPicker = function(){- pluginsOpen = {caveman:false, persona:false}; // always open collapsed- var overlay = document.createElement('div');- overlay.className = 'picker-overlay plugins-picker';- overlay.onclick = function(e){if(e.target===overlay) document.body.removeChild(overlay);};- overlay.innerHTML =- '<div class="picker-sheet">' +- '<div class="picker-header">' +- '<span class="picker-title">Plugins</span>' +- '<button class="picker-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' +- '</div>' +- '<div class="picker-list">' + pluginsPickerBodyHtml() + '</div>' +- '</div>';- document.body.appendChild(overlay);- overlay.querySelector('.picker-close').onclick = function(){document.body.removeChild(overlay);};- bindPluginsPicker(overlay);- };-- // ── Settings sheet — Remote Permissions only ──- // Mirrors the desktop's Settings → Remote Access → Permissions section.- // READS /remote-api/permissions; it cannot write. Each row gates a category- // of endpoints server-side (see proxy_ollama / proxy_comfyui in remote.rs),- // and the server ignores a permissions POST from a paired device — a scope a- // phone can grant itself is not a scope. The rows are shown anyway because- // this is the only place the phone can see what it is allowed to do.- var PERMISSION_META = [- {key:'filesystem', label:'Filesystem', desc:'Agent can read/write files + run code on the desktop.'},- {key:'downloads', label:'Downloads', desc:'Agent can trigger model pulls / installs (Ollama + ComfyUI).'},- {key:'process_control', label:'Process Control', desc:'Reach ComfyUI and Ollama on the desktop, and start or stop them.'}- ];-- function fetchRemotePerms(){- return fetch('/remote-api/permissions',{- headers:{'Authorization':'Bearer '+TOKEN}- }).then(absorbRefresh).then(function(r){- if(r.status===401){ clearAuthAndReload(); throw new Error('401'); }- if(!r.ok) throw new Error('HTTP '+r.status);- return r.json();- }).then(function(p){- remotePerms = {- filesystem: !!p.filesystem,- downloads: !!p.downloads,- process_control: !!p.process_control- };- return remotePerms;- });- }-- window._openSettingsSheet = function(){- var overlay = document.createElement('div');- overlay.className = 'picker-overlay';- overlay.onclick = function(e){ if(e.target===overlay) document.body.removeChild(overlay); };-- function renderBody(){- var rows = PERMISSION_META.map(function(m){- var on = !!remotePerms[m.key];- return '<label class="perm-row" data-key="'+m.key+'">' +- '<div class="perm-text">' +- '<div class="perm-label">'+H(m.label)+'</div>' +- '<div class="perm-desc">'+H(m.desc)+'</div>' +- '</div>' +- '<span class="plug-switch">' +- '<input type="checkbox" data-pk="'+m.key+'" disabled'+(on?' checked':'')+'>' +- '<span class="plug-switch-track"></span>' +- '</span>' +- '</label>';- }).join('');- return '<div class="settings-section-label">Remote Permissions</div>' +- '<div class="perm-note">What this session is allowed to do on the desktop. Set on the desktop, in Settings → Remote Access — a phone cannot grant itself access.</div>' +- rows;- }-- overlay.innerHTML =- '<div class="picker-sheet">' +- '<div class="picker-header">' +- '<span class="picker-title">Settings</span>' +- '<button class="picker-close" aria-label="Close"><span class="material-symbols-outlined">'+svgIcon('close')+'</span></button>' +- '</div>' +- '<div class="picker-list" id="settings-body"><div class="perm-loading">Loading…</div></div>' +- '</div>';- document.body.appendChild(overlay);- overlay.querySelector('.picker-close').onclick = function(){ document.body.removeChild(overlay); };-- fetchRemotePerms().then(function(){- var body = overlay.querySelector('#settings-body');- if(!body) return;- body.innerHTML = renderBody();- }).catch(function(e){- var body = overlay.querySelector('#settings-body');- if(body) body.innerHTML = '<div class="perm-loading" style="color:var(--error)">Failed to load: '+H(String(e && e.message || e))+'</div>';- });- };-- window._copyMsg = function(idx){- if(msgs[idx]) navigator.clipboard.writeText(msgs[idx].content).catch(function(){});- };- window._copyCode = function(btn){- var pre = btn.parentElement;- if(!pre) return;- var code = pre.querySelector('code');- if(code) navigator.clipboard.writeText(code.textContent).catch(function(){});- };- window._toggleThink = function(msgId){- for(var i=0;i<msgs.length;i++){- if(msgs[i].id === msgId){- msgs[i].thinkingOpen = !msgs[i].thinkingOpen;- renderChat();- return;- }- }- };- window._toggleAgentStep = function(stepKey){- var parts = stepKey.split(':');- if(parts.length < 2) return;- var msgId = parts[0], idx = Number(parts[1]);- for(var i=0;i<msgs.length;i++){- if(msgs[i].id === msgId){- if(Array.isArray(msgs[i].agentSteps) && msgs[i].agentSteps[idx]){- msgs[i].agentSteps[idx].open = !msgs[i].agentSteps[idx].open;- renderChat();- }- return;- }- }- };- // ── Regenerate: drop the given assistant msg + everything after, resend the preceding user msg.- // Parity with desktop useChat.ts regenerateMessage().- window._regenMsg = function(msgId){- if(streaming || agentRunning) return;- var idx = -1;- for(var i=0;i<msgs.length;i++){ if(msgs[i].id === msgId){ idx = i; break; } }- if(idx < 1) return;- var userMsg = msgs[idx-1];- if(!userMsg || userMsg.role !== 'user') return;- // Truncate to just-before-user, then replay the user text- msgs.splice(idx-1);- syncCurrentChat();- renderChat();- // Reuse the send path by re-injecting the user text.- var input = el('msg-input'); if(input){ input.value = userMsg.content; window._doSend(); }- else {- // Fallback: manually push and dispatch- var u = mkMsg('user', userMsg.content, userMsg.images ? {images: userMsg.images} : null);- msgs.push(u); msgs.push(mkMsg('assistant',''));- renderChat();- }- };- // ── Edit: turn user bubble into inline textarea, save rewrites + resends from that point.- // Parity with desktop useChat.ts editAndResend().- window._editMsg = function(msgId){- if(streaming || agentRunning) return;- var idx = -1;- for(var i=0;i<msgs.length;i++){ if(msgs[i].id === msgId){ idx = i; break; } }- if(idx < 0 || msgs[idx].role !== 'user') return;- var node = document.querySelector('.msg-group[data-msg-idx="'+idx+'"] .msg-bubble.user');- if(!node) return;- var original = msgs[idx].content;- node.classList.add('editing');- node.innerHTML =- '<textarea class="msg-edit-area" id="msg-edit-ta">'+H(original)+'</textarea>' +- '<div class="msg-edit-row">' +- '<button class="msg-edit-btn" id="msg-edit-cancel">Cancel</button>' +- '<button class="msg-edit-btn primary" id="msg-edit-save">Save & Resend</button>' +- '</div>';- var ta = el('msg-edit-ta');- if(ta){ ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }- el('msg-edit-cancel').onclick = function(){ renderChat(); };- el('msg-edit-save').onclick = function(){- var newVal = el('msg-edit-ta').value.trim();- if(!newVal){ renderChat(); return; }- // Drop this message and everything after, then resend with the new content.- msgs.splice(idx);- syncCurrentChat();- renderChat();- var inp = el('msg-input'); if(inp){ inp.value = newVal; window._doSend(); }- };- };- window._disconnect = function(){- localStorage.removeItem('lu-remote-token');- location.reload();- };-- // ── Mirror to desktop ──- // LU mode → appends to the desktop's dispatched Remote conversation.- // Codex mode → creates / appends to a desktop Codex conversation named- // after the mobile chat title. That way "codex chat on- // mobile must also show up in Codex in the app with- // content" (user request).- function postChatEvent(role, content){- if(!content) return;- // Safety filter: never mirror bare "Continue." to the desktop.- // Legacy from the old ReAct loop; kept as defense in depth.- if(role === 'user' && /^\s*continue\.?\s*$/i.test(content)) return;- var c = findChat(currentChatId);- if(!c) return;- var mode = c.mode === 'codex' ? 'codex' : 'lu';- try{- fetch('/remote-api/chat-event',{- method:'POST',- headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},- body:JSON.stringify({- role:role,- content:content,- model:currentModel||'',- mode:mode,- chat_id:c.id||'',- chat_title:c.title||''- })- }).catch(function(){});- }catch(_){}- }-- // ── Send ──- window._doSend = function(){- var inp = el('msg-input');- var text = inp.value.trim();- var hasImages = pendingImages.length > 0;- if((!text && !hasImages) || streaming || agentRunning) return;- if(!currentModel){window._openModelPicker();return;}-- var userMsg = mkMsg('user', text, hasImages ? {images: pendingImages.slice()} : null);- msgs.push(userMsg);- msgs.push(mkMsg('assistant', ''));-- inp.value='';inp.style.height='auto';- var sentImages = pendingImages.slice();- pendingImages = [];- renderAttachments();-- // Mirror user message to desktop (text only)- postChatEvent('user', text);-- // Agent / Codex mode? Use native Ollama tool calling instead of- // plain streaming chat. Codex chats ALWAYS run tools (no toggle),- // matching desktop Codex which is agentic by design. Plain LU chats- // only run tools when the user toggled Agent on in the header.- var isCodexChat = getCurrentMode() === 'codex';- if(getAgentEnabled() || isCodexChat){- var toolNames = isCodexChat ? CODEX_TOOLS : AGENT_ALL_TOOLS;- var sysPrompt = buildSystemPrompt();- var kindLabel = isCodexChat ? 'Coding Agent' : 'Agent';- runToolLoop(sysPrompt, toolNames, kindLabel);- return;- }-- streaming=true;- // Re-render the input bar so the Send-Button flips to the red Stop- // chip. Without this the user has no visible way to cancel a chat- // that hangs on an over-eager thinking model.- renderShell();- renderChat();-- // Build API messages- var apiMsgs = [];- var sys = buildSystemPrompt();- if(sys) apiMsgs.push({role:'system',content:sys});- var cm = getCaveman();- for(var i=0;i<msgs.length-1;i++){- var m = msgs[i];- var content = m.content;- // Caveman per-message reminder — prepend on every user message.- // Parity with desktop (useChat.ts line 142): the reminder fires- // unconditionally so the model doesn't drift on turn 2+. Without- // this, thinking-compatible models silently dropped Caveman style- // after the first response (was: only !isThinkingCompatible).- if(m.role==='user' && cm!=='off' && CAVEMAN_REMINDERS[cm]){- content = CAVEMAN_REMINDERS[cm] + '\n' + content;- }- var apiMsg = {role:m.role, content:content};- if(m.images && m.images.length){ apiMsg.images = m.images.map(function(im){return im.data;}); }- apiMsgs.push(apiMsg);- }-- // Token budget: 16 384 is a balance between "no truncation of the- // assistant's visible message" (previous default of 4000 was too low)- // and "don't let tagged-thinking models loop forever" (true `-1`- // caused Gemma 3/4 to think without ever emitting an answer). 16 k is- // enough for the longest reasonable agent reply plus deep thinking.- // v2.4.6 Bug L: dropped num_gpu:99 — see nativeToolChat() comment above.- var body = {model:currentModel, messages:apiMsgs, stream:true, options:{num_predict:16384}};- // Tri-state: for thinking-capable models we normally send explicit- // true|false. Explicit `false` tells Ollama to SKIP thinking (saves- // tokens) instead of silently letting the model emit <think> tags we'd- // then have to hide. Non-thinking models: omit the field entirely.- //- // Bug #80 parity: Gemma 3/4 with `think:false` drops into PLAIN-TEXT- // structured planning ("Plan:" / "Constraint Checklist:" …) that no- // tag-stripper can clean. For these models with the toggle OFF we- // instead OMIT `think`, which makes Ollama emit tagged thinking that- // our stripper handles cleanly. UX is the same (clean answer) — the- // trade-off is hidden token spend on internal reasoning.- if(isThinkingCompatible(currentModel)){- if(thinking){- body.think = true;- } else if(!isPlainTextPlanner(currentModel)){- body.think = false;- }- // else: leave body.think undefined → Ollama default = tagged thinking,- // stripped at render time.- }-- abortCtrl = new AbortController();- fetch('/api/chat',{- method:'POST',- headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},- body:JSON.stringify(body),- signal:abortCtrl.signal- })- .then(absorbRefresh)- .then(function(r){- if(r.status===401){- // #73: without this the reload swallowed the just-sent message —- // stash it so it is back in the composer after re-pairing.- try{- var lastUser = null;- for(var qi=msgs.length-1; qi>=0; qi--){ if(msgs[qi].role==='user'){ lastUser=msgs[qi].content; break; } }- if(lastUser) localStorage.setItem('lu-remote-draft', lastUser);- }catch(_){}- clearAuthAndReload();- return;- }- if(!r.ok){- // Retry without the think field at all if the server rejects it- // (old Ollama or model that refuses the flag).- if(r.status===400 && ('think' in body)){- delete body.think;- return fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+TOKEN},body:JSON.stringify(body),signal:abortCtrl.signal}).then(absorbRefresh).then(streamResponse);- }- msgs[msgs.length-1].content='Error: HTTP '+r.status;- finishStream();- return;- }- streamResponse(r);- })- .catch(function(ex){- if(ex.name!=='AbortError') msgs[msgs.length-1].content='Connection error';- finishStream();- });- };-- // ── Native tool-calling loop ─────────────────────────────────────- //- // Replaces the old ReAct JSON loop with Ollama's native /api/chat- // `tools` parameter. The model returns structured `tool_calls[]`- // instead of freeform JSON we had to parse. Reliability goes from- // ~60% to ~99% because the model uses its trained tool-call format- // instead of trying to emit valid JSON in its content.- // Append a structured agent step to the current assistant message.- // Steps render as small colored cards ABOVE the bubble; they are NOT- // part of msg.content, so the next user turn does NOT see tool-call- // scaffolding and the model cannot drift into that style.- function appendAgentStep(type, content, meta){- var idx = msgs.length-1;- if(idx < 0 || msgs[idx].role !== 'assistant') return;- if(!Array.isArray(msgs[idx].agentSteps)) msgs[idx].agentSteps = [];- // ALL steps always start collapsed (user request). Pulsing CSS stripe- // on `.live` rows shows in-flight status; the content itself stays- // behind the chevron until the user taps to expand.- for(var p=0; p<msgs[idx].agentSteps.length; p++){ msgs[idx].agentSteps[p].open = false; }- var step = {type:type, content:content, ts:Date.now(), open:false, live:false};- if(meta && typeof meta === 'object'){ for(var k in meta) if(Object.prototype.hasOwnProperty.call(meta,k)) step[k]=meta[k]; }- msgs[idx].agentSteps.push(step);- renderChat();- }-- // ── Native tool-calling loop ──- //- // Uses Ollama's /api/chat with `tools` parameter (non-streaming,- // stream:false). The model returns structured `tool_calls[]` that we- // execute via the existing runAgentTool() bridge, then feed results- // back as `role:'tool'` messages. Loop until the model responds with- // no tool_calls (= final answer) or we hit maxIter.- //- // Why non-streaming? Ollama's tool calling requires stream:false to- // return structured tool_calls[]. The trade-off vs the old streaming- // ReAct loop: no live token-by-token display, but near-100% tool-call- // reliability instead of ~60% JSON parse success.- function runToolLoop(systemPrompt, toolNames, kindLabel){- agentRunning = true;- agentAbort = false;- abortCtrl = new AbortController();- renderShell(); // flips Send button to Stop- renderChat();-- var maxIter = 50; // matches desktop v24 AgentBudget default- 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.- // Hidden messages (tool-call history from previous turns) are included- // so the model sees what it did before (continue capability, parity- // with original Codex CLI).- var apiMessages = [];- var apiStartLen = 0; // track where loop-generated messages begin- if(systemPrompt) apiMessages.push({role:'system', content:systemPrompt});- var cm = getCaveman();- for(var k=0; k<msgs.length-1; k++){- var m = msgs[k];- var content = m.content;- if(m.role==='user' && cm!=='off' && CAVEMAN_REMINDERS[cm]){- content = CAVEMAN_REMINDERS[cm] + '\n' + content;- }- // A restored tool result is a PREVIOUS turn's work, already summarised- // by the answer the user can see, so it comes back tighter than the- // in-run cap. One exception, and it is the stability rule: a result the- // run already sent capped at 4k is restored at exactly those 4k bytes,- // otherwise the same result would arrive with different bytes depending- // on which turn asked for it.- if(m.role === 'tool' && !isDecayedAt(content, DECAY_RESULT_CHARS)){- content = capToolResult(content, RESTORE_RESULT_CHARS);- }- var apiMsg = {role: m.role, content: content};- // Carry over tool_calls on assistant messages so Ollama sees the- // full native tool-call history (assistant→tool pairs).- if(m.tool_calls) apiMsg.tool_calls = m.tool_calls;- if(m.images && m.images.length){ apiMsg.images = m.images.map(function(im){return im.data;}); }- apiMessages.push(apiMsg);- }-- apiStartLen = apiMessages.length; // everything after this was added during the loop-- // Show a "thinking" step while the first call is in flight- appendAgentStep('thought', kindLabel+' is thinking...', {live:true});- var thinkingStepIdx = (target.agentSteps || []).length - 1;-- function step(){- if(agentAbort){- appendAgentStep('error', kindLabel+' stopped by user.');- finishToolLoop(null);- return;- }- if(iter >= maxIter){- appendAgentStep('error', kindLabel+' stopped: max iterations reached.');- finishToolLoop(null);- return;- }- iter++;-- // Decay first, then compaction, and the order is the point (plan A1). A- // decayed history is what the budget check should be looking at;- // measuring full results and then dropping whole messages throws away- // old context that would have fitted at 4k.- decayToolResults(apiMessages, 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).- if(thinkingStepIdx >= 0 && target.agentSteps && target.agentSteps[thinkingStepIdx]){- target.agentSteps.splice(thinkingStepIdx, 1);- thinkingStepIdx = -1;- renderChat();- }-- // Handle thinking content (native Ollama field + inline tags)- var keepThinking = thinking && isThinkingCompatible(currentModel);- var stripped = stripThinkTags(res.content, keepThinking);- var turnContent = stripped.content;- var turnThinking = stripped.thinking;- // Also pick up the native thinking field from Ollama- if(res.thinking){- if(keepThinking){- turnThinking = turnThinking ? turnThinking+'\n'+res.thinking : res.thinking;- }- }- if(turnThinking && target){- target.thinking = (target.thinking ? target.thinking+'\n' : '') + turnThinking;- }-- // 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){- // 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;- }-- // Push the assistant message with tool_calls into the history- // so Ollama sees the proper assistant→tool message pairs.- apiMessages.push({- role: 'assistant',- content: turnContent || '',- tool_calls: res.toolCalls.map(function(tc){- return {function:{name:tc.function.name, arguments:tc.function.arguments}};- })- });-- // Execute each tool call sequentially, show steps in UI- var tcIndex = 0;- function execNext(){- if(agentAbort){- appendAgentStep('error', kindLabel+' stopped by user.');- finishToolLoop(null);- return;- }- if(tcIndex >= res.toolCalls.length){- // All tools executed — loop back for next model turn- renderChat();- step();- return;- }-- var tc = res.toolCalls[tcIndex];- var toolName = tc.function.name;- var toolArgs = tc.function.arguments || {};- var argsPretty = '';- try{ argsPretty = JSON.stringify(toolArgs); }catch(_){ argsPretty = '{}'; }-- // Show "running" action step- appendAgentStep('action', '`'+toolName+'` '+argsPretty, {toolName:toolName, args:toolArgs, live:true});- var actionIdx = (target.agentSteps || []).length - 1;-- runAgentTool(toolName, toolArgs).then(function(observation){- var obs = String(observation || '');-- // Mark action as completed- if(target.agentSteps && target.agentSteps[actionIdx]){- target.agentSteps[actionIdx].live = false;- }- appendAgentStep('observation', obs);-- // Push tool result into the LLM history. The iteration rides with- // it so decayToolResults can tell the newest results (kept whole)- // from the ones that have done their job (A1).- apiMessages.push({role:'tool', content:obs, iter:iter});-- // 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){- var errMsg = String(e && e.message || e);- if(target.agentSteps && target.agentSteps[actionIdx]){- target.agentSteps[actionIdx].live = false;- }- appendAgentStep('error', errMsg);-- // Push error as tool result so the model can adapt- apiMessages.push({role:'tool', content:'Error: '+errMsg, iter:iter});-- 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();- });- }-- execNext();- }).catch(function(e){- // Remove the thinking placeholder if still present- if(thinkingStepIdx >= 0 && target.agentSteps && target.agentSteps[thinkingStepIdx]){- target.agentSteps.splice(thinkingStepIdx, 1);- thinkingStepIdx = -1;- }+/// The page a paired phone receives, assembled from `mobile-client/`.+///+/// Until 2026-09-01 the whole client lived here as a 2 964-line `r#"…"#`+/// literal — HTML, 334 lines of CSS and 2 606 lines of JavaScript inside a+/// Rust string. Nothing in the JavaScript toolchain can look into a Rust+/// string, so `tsc`, `eslint`, `prettier` and `vitest` had never seen a line+/// of it. What stood in for tests were TypeScript re-implementations of the+/// same rules, hand-copied next to it: two versions of `CAVEMAN_PROMPTS`, two+/// of `buildSystemPrompt`, and a green suite either way.+///+/// The source now lives in `mobile-client/` as real files. `build.rs` glues+/// them back together on every build and writes the result into `OUT_DIR`;+/// see `crate::mobile_page` for the assembly and for what happens when a+/// source is missing (the build stops — it does not ship the last good page).+///+/// The bytes did not change. `mobile_landing_is_what_the_sources_say` below+/// re-derives the page from `mobile-client/` on every `cargo test` and+/// compares it with what is embedded here.+const MOBILE_CLIENT_PAGE: &str = include_str!(concat!(env!("OUT_DIR"), "/mobile-client.html"));- if(e && e.name === 'AbortError'){- appendAgentStep('error', 'Stopped.');- finishToolLoop(null);- return;- }- var errMsg = (e && e.message) || String(e);- if(errMsg === 'TOOLS_NOT_SUPPORTED'){- appendAgentStep('error', 'This model does not support tool calling. Pick a tool-capable model (Qwen 3, Llama 3.1+, Gemma 4).');- finishToolLoop(null);- return;- }- appendAgentStep('error', kindLabel+' error: '+errMsg);- finishToolLoop(null);- });- }-- function finishToolLoop(finalAnswer){- agentRunning = false;- agentAbort = false;- abortCtrl = null;-- // ── Continue capability (parity with original Codex CLI) ────────- // Persist the tool-call history from THIS turn as hidden messages- // in msgs[]. On the NEXT turn, the history builder (line ~2802)- // includes them in apiMessages so the model sees what it did before.- // Hidden messages are skipped by renderChat() — the user only sees- // the final answer, but the model sees the full tool-call chain.- var toolHistory = [];- for(var hi = apiStartLen; hi < apiMessages.length; hi++){- var am = apiMessages[hi];- toolHistory.push(mkMsg(am.role, am.content || '', {- hidden: true,- tool_calls: am.tool_calls || undefined- }));- }- if(toolHistory.length > 0){- // Splice BEFORE target (the visible final-answer message) so- // the conversation order is: user → hidden tool chain → answer.- var targetIdx = msgs.indexOf(target);- if(targetIdx >= 0){- // splice(targetIdx, 0, ...items) — Array.prototype.splice.apply- // for ES5 compat (mobile JS can't use spread in all engines).- var spliceArgs = [targetIdx, 0];- for(var si = 0; si < toolHistory.length; si++) spliceArgs.push(toolHistory[si]);- Array.prototype.splice.apply(msgs, spliceArgs);- }- }-- // The visible answer — if finalAnswer is null/empty and no prior- // content, build a fallback summary from agent steps so the bubble- // is never blank (parity with desktop useCodex.ts fix).- var answer = finalAnswer || '';- if(!answer && target && !target.content){- var steps = target.agentSteps || [];- var writes = 0, reads = 0, otherOk = 0, fails = 0;- for(var si2 = 0; si2 < steps.length; si2++){- var s = steps[si2];- if(s.type === 'action'){- if(s.toolName === 'file_write') writes++;- else if(s.toolName === 'file_read') reads++;- else otherOk++;- } else if(s.type === 'error' && s.content && s.content.indexOf('stopped') < 0){- fails++;- }- }- var summaryParts = [];- if(writes) summaryParts.push(writes + ' file(s) written');- if(reads) summaryParts.push(reads + ' file(s) read');- if(otherOk) summaryParts.push(otherOk + ' other operation(s) completed');- if(fails) summaryParts.push(fails + ' operation(s) failed');- answer = summaryParts.length > 0- ? 'Task completed: ' + summaryParts.join(', ') + '.'- : 'Task completed.';- }- if(target){ target.content = answer || target.content || ''; }- renderShell();- renderChat();- var finalText = target ? (target.content || '') : '';- postChatEvent('assistant', finalText);- syncCurrentChat();- }-- step();- }-- // Character-state-machine for inline <think>...</think> tags.- // Parity with desktop useChat.ts lines 205-219. When the user has- // thinking TOGGLED OFF, the bytes inside <think>...</think> are- // discarded instead of being stored — same for Ollama's native- // `message.thinking` field. That way the toggle is the single source- // of truth ("thinking visible or not").- var inThinkTag = false;- var discardedThinkBuf = '';- function pushChunkContent(target, text, keepThinking){- if(!text) return;- for(var k=0;k<text.length;k++){- var ch = text[k];- if(!inThinkTag){- target.content += ch;- if(target.content.length >= 7 && target.content.slice(-7) === '<think>'){- target.content = target.content.slice(0,-7);- inThinkTag = true;- discardedThinkBuf = '';- }- } else {- if(keepThinking){- target.thinking += ch;- if(target.thinking.length >= 8 && target.thinking.slice(-8) === '</think>'){- target.thinking = target.thinking.slice(0,-8);- inThinkTag = false;- }- } else {- discardedThinkBuf += ch;- if(discardedThinkBuf.length >= 8 && discardedThinkBuf.slice(-8) === '</think>'){- discardedThinkBuf = '';- inThinkTag = false;- }- }- }- }- }-- function streamResponse(r){- if(!r) return;- var reader=r.body.getReader();- var dec=new TextDecoder();- var buf='';- inThinkTag = false; // reset per-stream- discardedThinkBuf = '';- var target = msgs[msgs.length-1];- // Thinking visibility is driven strictly by the toggle. If the toggle- // is OFF, ALL thinking tokens (native field AND inline <think> tags- // AND non-canonical tags via stripNonCanonicalTags) are silently- // dropped so the UI never shows a think block the user didn't ask- // for. If the toggle turns ON later, subsequent tokens appear live.- function keepThinkingNow(){ return thinking && isThinkingCompatible(currentModel); }- function pump(){- reader.read().then(function(result){- if(result.done){- // Final pass: scrub any non-canonical thinking markers that- // slipped past the streaming state-machine (Gemma's channel- // marker, orphan <thought>, etc.). Bug #3+#5.- if(target){- target.content = stripNonCanonicalTags(target.content).trim();- }- var finalText = target ? target.content : '';- postChatEvent('assistant', finalText);- finishStream();- return;- }- buf+=dec.decode(result.value,{stream:true});- var lines=buf.split('\n');- buf=lines.pop()||'';- var keep = keepThinkingNow();- for(var li=0;li<lines.length;li++){- var ln=lines[li].trim();- if(!ln)continue;- try{- var j = JSON.parse(ln);- if(j && j.message){- // Ollama native thinking field (Gemma 4, Qwen 3.5, etc.)- if(typeof j.message.thinking === 'string' && j.message.thinking){- if(keep){- target.thinking += j.message.thinking;- // We do NOT auto-open anymore — tool calls / thinking- // start collapsed on mobile by user request.- }- }- // Content may contain inline <think>...</think>- if(typeof j.message.content === 'string' && j.message.content){- pushChunkContent(target, j.message.content, keep);- }- }- }catch(_){ }- }- // Live partial scrub of non-canonical tags (Gemma <|channel|>…).- // We re-strip on every chunk so the user never sees a "Plan:"- // preamble flash up while the model is still writing the answer.- if(target){- target.content = stripNonCanonicalTags(target.content);- }- renderChat();- pump();- }).catch(function(){finishStream();});- }- pump();- }-- function finishStream(){- streaming=false;abortCtrl=null;- syncCurrentChat();- // renderShell flips the Send-button back from Stop to Send. Must run- // BEFORE renderChat so the keyboard-on-iOS doesn't momentarily see a- // disabled button.- renderShell();- renderChat();- }-})();-</script>-</body>-</html>"#.to_string())+async fn mobile_landing() -> Html<String> {+ Html(MOBILE_CLIENT_PAGE.to_string())}// ─── QR Code generation ───@@ -7229,6 +4286,94 @@ mod remote_hardening_tests {}}+/// T-75: the embedded page and `mobile-client/` are the same page.+///+/// `build.rs` assembles the client on every build and cargo re-runs it+/// whenever a source changes, so the embedded copy cannot lag behind in+/// practice. This module does not trust that. It re-derives the page from+/// `mobile-client/` right now and compares — because the failure this whole+/// change is about is exactly "two versions, one of them maintained", and a+/// generated artefact that silently keeps an old body is that failure wearing+/// a build step.+#[cfg(test)]+mod mobile_source_of_truth_tests {+ use crate::mobile_page;++ #[test]+ fn mobile_landing_is_what_the_sources_say() {+ let from_sources = mobile_page::assemble(&mobile_page::client_dir())+ .expect("mobile-client/ does not assemble");+ let served = {+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(async { super::mobile_landing().await.0 })+ };+ assert_eq!(+ served.len(),+ from_sources.len(),+ "the embedded page is {} bytes, mobile-client/ assembles to {} — the build \+ embedded a different page than the one in the working tree",+ served.len(),+ from_sources.len()+ );+ if served != from_sources {+ let at = served+ .char_indices()+ .zip(from_sources.char_indices())+ .find(|((_, a), (_, b))| a != b)+ .map(|((i, _), _)| i)+ .unwrap_or(0);+ let from = at.saturating_sub(60);+ panic!(+ "the embedded page and mobile-client/ differ at byte {at}:\n\+ embedded: {:?}\n source: {:?}",+ &served[from..(at + 60).min(served.len())],+ &from_sources[from..(at + 60).min(from_sources.len())],+ );+ }+ }++ /// The file name appears twice — once in `build.rs`'s output path and+ /// once in the `include_str!` above, which needs a literal and cannot+ /// read the constant. This is the seam that holds the two together: rename+ /// one and this goes red instead of the build quietly embedding nothing.+ #[test]+ fn the_embedded_file_is_the_one_the_build_script_writes() {+ let embedded = concat!(env!("OUT_DIR"), "/mobile-client.html");+ assert!(+ embedded.ends_with(mobile_page::EMBED_NAME),+ "remote.rs embeds {embedded}, build.rs writes {}",+ mobile_page::EMBED_NAME+ );+ assert!(+ std::path::Path::new(embedded).is_file(),+ "{embedded} is not on disk — the build script did not run"+ );+ }++ /// A guard on the guard. If `mobile_landing` ever returned an empty+ /// string, or the assembler did, the comparison above would pass on two+ /// pieces of nothing.+ #[test]+ fn the_comparison_is_made_on_a_real_page() {+ let served = {+ let rt = tokio::runtime::Runtime::new().unwrap();+ rt.block_on(async { super::mobile_landing().await.0 })+ };+ assert!(+ served.len() > 100_000,+ "the served mobile page is only {} bytes",+ served.len()+ );+ assert!(served.starts_with("<!DOCTYPE html>"));+ assert!(served.ends_with("</html>"));+ // The three spliced modules each left a landmark; a splice that+ // produced an empty body would still start and end correctly.+ for needle in ["var CAVEMAN_PROMPTS = {", "var PERSONAS = [", "var AGENT_TOOLS = ["] {+ assert!(served.contains(needle), "the served page is missing {needle}");+ }+ }+}+/// A1 MOBILE (plan 2.6.6): the served page has to carry the decay, and it has/// to carry the DESKTOP's numbers.///diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 4550e487..92a73b82 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -5,6 +5,12 @@ mod app_identity;mod commands;mod crash_report;mod install_state;+// Assembles the mobile client page from mobile-client/ — the same code+// build.rs runs, compiled in again here so `cargo test` can re-derive the+// page and compare it with the embedded one. Nothing at runtime needs it:+// remote.rs embeds the finished page with include_str!.+#[cfg(test)]+mod mobile_page;mod os_error;mod os_paths;mod private_tmp;diff --git a/src-tauri/src/mobile_page.rs b/src-tauri/src/mobile_page.rsnew file mode 100644index 00000000..42aeb051--- /dev/null+++ b/src-tauri/src/mobile_page.rs@@ -0,0 +1,373 @@+//! Assembles the mobile client page out of `mobile-client/`.+//!+//! Until now the page a phone receives was a 2 964-line `r#"…"#` literal in+//! `commands/remote.rs`: HTML, CSS and 2 606 lines of JavaScript walled into a+//! Rust string. `tsc`, `eslint`, `prettier` and `vitest` cannot see inside a+//! Rust string, so none of them ever ran on it, and the tests that claimed to+//! cover it were hand-written TypeScript re-implementations sitting next to+//! it — two copies of the same rules, one of them maintained.+//!+//! Now `mobile-client/` holds real `.html`, `.css` and `.js` files, this+//! module glues them back into exactly the same bytes, and `build.rs` runs it+//! on every build.+//!+//! ── Why the glue lives in Rust and not in a Node script ──+//!+//! Because `cargo build` needs the result. A Node step would have to be+//! remembered by whoever runs cargo, and the thing it forgets to run produces+//! a file that is still lying there from last time. One assembler, run by the+//! build that consumes it, is the only arrangement where a stale page is not+//! reachable. The output goes to `OUT_DIR`, never into the repository, so+//! there is no checked-in copy that could go stale in the first place, and a+//! missing or broken source aborts the build instead of falling back to+//! whatever was there before.+//!+//! ── The two marker shapes ──+//!+//! `/*@@LU_TOOLING_ONLY@@*/ … /*@@LU_END@@*/` wraps the `import` / `export`+//! statements that make the four `.js` files a real module graph for tsc,+//! eslint and vitest. A classic `<script>` cannot carry those, so the+//! assembler cuts every such block out.+//!+//! `//@@LU_CAVEMAN@@` and friends are single marker lines that name where one+//! file is spliced into another. The spliced text lands at exactly the offset+//! the marker line occupied, which is what keeps the assembled page byte for+//! byte identical to the string it replaces.++use std::path::{Path, PathBuf};++/// The file `build.rs` writes into `OUT_DIR` and `remote.rs` embeds.+pub const EMBED_NAME: &str = "mobile-client.html";++/// Every file the assembler reads. Nothing else in `mobile-client/` reaches+/// the phone.+///+/// The list is checked from both ends by the tests below: each entry must be+/// genuinely required (deleting it has to break `assemble`), and every+/// `.html` / `.css` / `.js` file actually lying in the directory has to be on+/// it. A page source that is on neither side of that ledger is a file someone+/// edits while the phone never sees the edit.+pub const SOURCES: &[&str] = &[+ "index.html",+ "styles.css",+ "caveman.js",+ "personas.js",+ "agent-core.js",+ "client.js",+];++const TOOLING_START: &str = "/*@@LU_TOOLING_ONLY@@*/";+const TOOLING_END: &str = "/*@@LU_END@@*/";++/// `(marker line, file spliced in its place)`, in the order the assembler+/// applies them. The first three build the page's `<script>`; the last two+/// drop the stylesheet and that script into the document.+const SCRIPT_SPLICES: &[(&str, &str)] = &[+ (" //@@LU_CAVEMAN@@", "caveman.js"),+ (" //@@LU_PERSONAS@@", "personas.js"),+ (" //@@LU_AGENT_CORE@@", "agent-core.js"),+];+const STYLE_MARKER: &str = "/*@@LU_STYLES@@*/";+const SCRIPT_MARKER: &str = "//@@LU_SCRIPT@@";++/// `<repo>/mobile-client`, derived from the crate's own manifest directory so+/// it follows a checkout wherever it sits.+pub fn client_dir() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("..")+ .join("mobile-client")+}++/// The page exactly as it goes over the wire, or the reason it could not be+/// built. There is deliberately no third answer: a caller cannot accidentally+/// end up with a half-assembled or previously-assembled page.+pub fn assemble(dir: &Path) -> Result<String, String> {+ let mut script = body(dir, "client.js")?;+ for (marker, part) in SCRIPT_SPLICES {+ script = splice(&script, "client.js", marker, &body(dir, part)?)?;+ }+ let page = body(dir, "index.html")?;+ let page = splice(&page, "index.html", STYLE_MARKER, &body(dir, "styles.css")?)?;+ splice(&page, "index.html", SCRIPT_MARKER, &script)+}++/// One source file, tooling blocks removed and trailing newlines trimmed.+///+/// The trim is what lets every source file end with a newline like a normal+/// text file while the spliced result still lands on the exact byte the+/// marker line started at.+fn body(dir: &Path, name: &str) -> Result<String, String> {+ let path = dir.join(name);+ let raw = std::fs::read_to_string(&path).map_err(|kind| {+ // The io::ErrorKind, not the error's own text. Windows words that text+ // in the system language (the whole point of os_error.rs), and this+ // string lands in a build log and in test output that is read in+ // English. The kind plus the path says everything that matters here.+ format!(+ "{} could not be read ({:?}).\n\+ It is one of the {} files listed in mobile_page::SOURCES; the \+ mobile client page cannot be built without it.",+ path.display(),+ kind.kind(),+ SOURCES.len()+ )+ })?;+ Ok(strip_tooling_blocks(&raw, name)?+ .trim_end_matches('\n')+ .to_string())+}++/// Removes every `/*@@LU_TOOLING_ONLY@@*/ … /*@@LU_END@@*/` region, marker+/// lines included.+///+/// Unbalanced markers are an error rather than a best-effort cut: a stray+/// opener would otherwise silently swallow the rest of the file and ship a+/// page that is missing half its script.+fn strip_tooling_blocks(source: &str, name: &str) -> Result<String, String> {+ let mut kept: Vec<&str> = Vec::new();+ let mut open_at: Option<usize> = None;+ for (i, line) in source.lines().enumerate() {+ match line.trim_end() {+ TOOLING_START => {+ if let Some(at) = open_at {+ return Err(format!(+ "{name}:{}: {TOOLING_START} inside the block opened on line {}",+ i + 1,+ at + 1+ ));+ }+ open_at = Some(i);+ }+ TOOLING_END => {+ if open_at.take().is_none() {+ return Err(format!(+ "{name}:{}: {TOOLING_END} without a matching {TOOLING_START}",+ i + 1+ ));+ }+ }+ _ => {+ if open_at.is_none() {+ kept.push(line);+ }+ }+ }+ }+ if let Some(at) = open_at {+ return Err(format!(+ "{name}:{}: {TOOLING_START} is never closed by {TOOLING_END}",+ at + 1+ ));+ }+ Ok(kept.join("\n"))+}++/// Replaces the single occurrence of `marker` in `host` with `part`.+///+/// Exactly one, never "the first one" and never "none, carry on": a marker+/// that moved or was duplicated during an edit has to stop the build, because+/// the alternative is a page that is quietly missing a third of its script.+fn splice(host: &str, host_name: &str, marker: &str, part: &str) -> Result<String, String> {+ match host.matches(marker).count() {+ 1 => Ok(host.replacen(marker, part, 1)),+ n => Err(format!(+ "mobile-client/{host_name}: the splice marker `{marker}` appears {n} times, \+ expected exactly once. The assembler puts one source file at that spot; \+ without the marker that file would simply not reach the phone."+ )),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// What counts as a page source when the ledger test audits the+ /// directory. Test-side on purpose: the assembler reads `SOURCES` by+ /// name, this is only the net that catches a file `SOURCES` forgot.+ const SOURCE_EXTENSIONS: &[&str] = &["html", "css", "js"];++ /// A working copy of `mobile-client/` a test may break.+ struct Scratch(PathBuf);++ impl Scratch {+ fn new(tag: &str) -> Self {+ let dir = std::env::temp_dir().join(format!(+ "lu-mobile-page-{}-{}-{:?}",+ tag,+ std::process::id(),+ std::thread::current().id()+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ for name in SOURCES {+ std::fs::copy(client_dir().join(name), dir.join(name)).unwrap();+ }+ Scratch(dir)+ }+ fn path(&self) -> &Path {+ &self.0+ }+ fn edit(&self, name: &str, f: impl Fn(String) -> String) {+ let p = self.0.join(name);+ let s = std::fs::read_to_string(&p).unwrap();+ std::fs::write(&p, f(s)).unwrap();+ }+ }++ impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ #[test]+ fn the_real_sources_assemble_into_a_whole_html_document() {+ let page = assemble(&client_dir()).expect("mobile-client/ does not assemble");+ assert!(page.starts_with("<!DOCTYPE html>"), "{}", &page[..40]);+ assert!(page.ends_with("</html>"), "{}", &page[page.len() - 40..]);+ // The three spliced modules and the stylesheet all really landed.+ for needle in [+ "var CAVEMAN_PROMPTS = {",+ "var PERSONAS = [",+ "var AGENT_TOOLS = [",+ "function compactApiMessages(",+ ".drawer-backdrop",+ ] {+ assert!(page.contains(needle), "assembled page is missing {needle}");+ }+ // And nothing that only exists for the tooling survived the trip.+ for leftover in [TOOLING_START, TOOLING_END, STYLE_MARKER, SCRIPT_MARKER] {+ assert!(+ !page.contains(leftover),+ "the assembled page still carries {leftover}"+ );+ }+ for (marker, _) in SCRIPT_SPLICES {+ assert!(+ !page.contains(marker),+ "the assembled page still carries {marker}"+ );+ }+ assert!(+ !page.contains("import {") && !page.contains("export {"),+ "an ES-module statement reached the classic <script> — it would be a SyntaxError on the phone"+ );+ }++ /// Both directions of the ledger. Neither half alone is enough: the first+ /// catches a file that is listed but no longer used, the second a file+ /// that is used — edited, believed shipped — but never read.+ #[test]+ fn every_declared_source_is_required_and_every_present_source_is_declared() {+ // 1. Every entry in SOURCES is genuinely load-bearing.+ for name in SOURCES {+ let scratch = Scratch::new("required");+ std::fs::remove_file(scratch.path().join(name)).unwrap();+ let err = assemble(scratch.path()).expect_err(&format!(+ "mobile-client/{name} is listed in SOURCES but the page assembles without it"+ ));+ assert!(err.contains(name), "{err}");+ }++ // 2. Every page source lying in the directory is on the list. A new+ // .js next to these that nobody reads is a file whose edits never+ // reach the phone, and nothing else would ever say so.+ let mut found: Vec<String> = Vec::new();+ for entry in std::fs::read_dir(client_dir()).expect("mobile-client/ is not there") {+ let entry = entry.unwrap();+ let name = entry.file_name().to_string_lossy().into_owned();+ let is_source = Path::new(&name)+ .extension()+ .map(|e| SOURCE_EXTENSIONS.contains(&e.to_string_lossy().as_ref()))+ .unwrap_or(false);+ if entry.file_type().unwrap().is_file() && is_source {+ found.push(name);+ }+ }+ found.sort();+ let mut declared: Vec<String> = SOURCES.iter().map(|s| s.to_string()).collect();+ declared.sort();+ assert_eq!(+ found, declared,+ "mobile-client/ and mobile_page::SOURCES disagree. Every .html/.css/.js in that \+ directory has to be read by the assembler, or it is a file someone edits while \+ the phone keeps seeing the old page."+ );+ }++ #[test]+ fn a_missing_splice_marker_stops_the_build() {+ let scratch = Scratch::new("nomarker");+ scratch.edit("client.js", |s| s.replace(" //@@LU_PERSONAS@@", ""));+ let err = assemble(scratch.path()).expect_err(+ "client.js lost its personas.js splice marker and the page assembled anyway — \+ the phone would have received a script without PERSONAS",+ );+ assert!(err.contains("LU_PERSONAS"), "{err}");+ assert!(err.contains("appears 0 times"), "{err}");+ }++ #[test]+ fn a_duplicated_splice_marker_stops_the_build() {+ let scratch = Scratch::new("dupmarker");+ scratch.edit("client.js", |s| {+ s.replace(" //@@LU_CAVEMAN@@", " //@@LU_CAVEMAN@@\n //@@LU_CAVEMAN@@")+ });+ let err = assemble(scratch.path()).expect_err("a duplicated marker assembled anyway");+ assert!(err.contains("appears 2 times"), "{err}");+ }++ #[test]+ fn an_unterminated_tooling_block_stops_the_build() {+ // personas.js carries exactly one block, so dropping its end marker+ // leaves the file genuinely unterminated. agent-core.js has two, and+ // dropping the first one there produces the nesting error instead —+ // also refused, but a different sentence.+ let scratch = Scratch::new("unterminated");+ scratch.edit("personas.js", |s| s.replacen(TOOLING_END, "", 1));+ let err = assemble(scratch.path()).expect_err(+ "an unclosed tooling block assembled anyway — it would have eaten the rest of the file",+ );+ assert!(err.contains("never closed"), "{err}");+ }++ #[test]+ fn a_nested_tooling_block_stops_the_build() {+ let scratch = Scratch::new("nested");+ scratch.edit("agent-core.js", |s| s.replacen(TOOLING_END, "", 1));+ let err = assemble(scratch.path()).expect_err("a nested tooling block assembled anyway");+ assert!(err.contains("inside the block opened on line"), "{err}");+ }++ #[test]+ fn a_stray_end_marker_stops_the_build() {+ let scratch = Scratch::new("strayend");+ scratch.edit("caveman.js", |s| format!("{TOOLING_END}\n{s}"));+ let err = assemble(scratch.path()).expect_err("a stray end marker assembled anyway");+ assert!(err.contains("without a matching"), "{err}");+ }++ /// The tooling blocks are the whole reason the split is safe: they are+ /// what tsc, eslint and vitest read the module graph from. A file that+ /// lost its block still assembles — so only this says it is gone.+ #[test]+ fn every_javascript_source_declares_its_module_graph() {+ for name in SOURCES.iter().filter(|n| n.ends_with(".js")) {+ let raw = std::fs::read_to_string(client_dir().join(name)).unwrap();+ assert!(+ raw.contains(TOOLING_START) && raw.contains(TOOLING_END),+ "mobile-client/{name} has no {TOOLING_START} block, so nothing outside the \+ assembled page can import from it and no test can reach its functions"+ );+ }+ }++ /// `strip_tooling_blocks` removes the block and nothing else — including+ /// the blank line the block does not own.+ #[test]+ fn stripping_a_tooling_block_leaves_the_rest_byte_for_byte() {+ let src = format!("a\nb\n{TOOLING_START}\nexport {{ a }}\n{TOOLING_END}\nc\n");+ assert_eq!(strip_tooling_blocks(&src, "t.js").unwrap(), "a\nb\nc");+ }+}diff --git a/src/api/__tests__/mobile-client-shell.ts b/src/api/__tests__/mobile-client-shell.tsnew file mode 100644index 00000000..74906794--- /dev/null+++ b/src/api/__tests__/mobile-client-shell.ts@@ -0,0 +1,124 @@+/**+ * Runs a single function out of `mobile-client/client.js` — the shipped one.+ *+ * ── Why this exists at all ──+ *+ * T-75 pulled the mobile client out of a Rust string. Most of its brain moved+ * into three real ES modules (`caveman.js`, `personas.js`, `agent-core.js`)+ * that tests simply `import`, and that is what you should reach for. This+ * helper is for the rest: functions that live in `client.js`, the 2 100-line+ * shell that touches `document`, `fetch` and `localStorage` on the first line+ * and therefore cannot be imported into a Node test.+ *+ * Two of them are worth testing anyway, because they decide what the model is+ * told rather than what the screen shows: `buildSystemPrompt` and the client's+ * own `isThinkingCompatible`. Both are pure once their surroundings are+ * supplied. So: cut the declaration out by name, evaluate it with the names it+ * refers to passed in, and run the real body.+ *+ * ── What this is NOT ──+ *+ * It is not the old pattern coming back in. What T-75 removed was a+ * hand-written TypeScript re-implementation of `buildSystemPrompt` sitting+ * next to the real one and being tested instead of it — two copies, one+ * maintained. This runs the shipped bytes. It is weaker than an import in+ * exactly one way, and the way is named and guarded: it locates a declaration+ * by name in a real `.js` file, and if the name is gone it throws instead of+ * quietly testing nothing.+ *+ * The reason `buildSystemPrompt` cannot simply be exported is worth writing+ * down, because "just move it too" is the obvious next thought: it reads+ * `chats`, `currentChatId` and `dispatchedSystemPrompt`, which `client.js`+ * ASSIGNS to. An ES module binding is read-only in the importer, so those+ * variables have to stay in the file that mutates them, and everything that+ * closes over them stays with them.+ */+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++// `__dirname` rather than `new URL(import.meta.url).pathname`: on Windows the+// latter is `/C:/…`, which `resolve` does not undo. The repository normalises+// line endings for exactly this class of reason (.gitattributes).+const CLIENT_JS = resolve(__dirname, '..', '..', '..', 'mobile-client', 'client.js')++export const clientSource = (): string => readFileSync(CLIENT_JS, 'utf8')++/**+ * The source text of one top-level declaration in `client.js`.+ *+ * Top level means "two spaces in", which is where every declaration inside the+ * client's single IIFE sits. A `function` runs to the first closing brace at+ * that indentation; a `var` must fit on one line, and anything else throws+ * rather than guessing at a boundary.+ */+export function declarationSource(name: string): string {+ const src = clientSource()++ const fnHead = `\n function ${name}(`+ const fnAt = src.indexOf(fnHead)+ if (fnAt !== -1) {+ const end = src.indexOf('\n }', fnAt + fnHead.length)+ if (end === -1) {+ throw new Error(+ `mobile-client/client.js: function ${name} has no closing brace at top-level indentation`,+ )+ }+ return src.slice(fnAt + 1, end + '\n }'.length)+ }++ // The inline handlers the page's HTML calls are hung on `window`, so they+ // are assignments rather than declarations. Same body, same closing brace.+ const winHead = `\n window.${name} = function(`+ const winAt = src.indexOf(winHead)+ if (winAt !== -1) {+ const end = src.indexOf('\n }', winAt + winHead.length)+ if (end === -1) {+ throw new Error(+ `mobile-client/client.js: window.${name} has no closing brace at top-level indentation`,+ )+ }+ return src.slice(winAt + 1, end + '\n }'.length)+ }++ const varHead = `\n var ${name} = `+ const varAt = src.indexOf(varHead)+ if (varAt !== -1) {+ const end = src.indexOf('\n', varAt + 1)+ const line = src.slice(varAt + 1, end)+ if (!line.trimEnd().endsWith(';')) {+ throw new Error(+ `mobile-client/client.js: var ${name} spans more than one line; ` ++ 'export it from one of the three modules instead of cutting it out here',+ )+ }+ return line+ }++ throw new Error(+ `mobile-client/client.js declares none of "function ${name}(", "window.${name} = function(" ` ++ `or "var ${name} = ". ` ++ 'It was renamed or deleted, and every assertion built on it would otherwise ' ++ 'have silently stopped testing anything.',+ )+}++/**+ * Evaluates the named declarations with `deps` in scope and returns them.+ *+ * `deps` is the surrounding scope the cut-out code still refers to: pass the+ * real imported constants where you have them, and stubs for the state+ * accessors. A name the code needs and `deps` does not carry throws a+ * ReferenceError on the first call, which is loud and points at the line.+ */+export function loadFromClient<T extends Record<string, unknown>>(+ names: string[],+ deps: Record<string, unknown> = {},+): T {+ const body = names.map(declarationSource).join('\n')+ const depNames = Object.keys(deps)+ const factory = new Function(+ ...depNames,+ `${body}\nreturn { ${names.join(', ')} };`,+ ) as (...args: unknown[]) => T+ return factory(...depNames.map((k) => deps[k]))+}diff --git a/src/api/__tests__/mobile-codex-parity.test.ts b/src/api/__tests__/mobile-codex-parity.test.tsindex ac90f955..9c195b40 100644--- a/src/api/__tests__/mobile-codex-parity.test.ts+++ b/src/api/__tests__/mobile-codex-parity.test.ts@@ -1,134 +1,310 @@/**- * Mobile ↔ Desktop parity smoke tests for Codex and Agent.+ * Mobile ↔ Desktop parity for Codex and Agent.*- * The mobile web app lives as embedded JS in remote.rs. These tests verify- * structural parity between desktop TypeScript and mobile JS implementations:+ * ── 01.09.2026 (T-75): this file used to be a grep ──*- * - CODEX_TOOLS tool list matches desktop tool categories- * - AGENT_ALL_TOOLS covers all registered tools- * - runToolLoop exists with proper loop termination- * - nativeToolChat uses correct Ollama API format- * - Hidden message filtering in renderChat- * - stripThinkTags exists for thinking content- * - Fallback final answer exists- * - Max iteration guard (no infinite loops)- * - Permission defaults (all ON for mobile)+ * Every assertion here read src-tauri/src/commands/remote.rs as one string and+ * asked whether a substring appeared in it. `expect(REMOTE_RS).toContain(+ * "'file_read'")` is green whether the name is in CODEX_TOOLS, in a comment,+ * in a Rust test, or in a paragraph of prose — and the file was 7 483 lines+ * long, so it was in several of those at once. The test for the tools that+ * were REMOVED in 2.6.6 had already been narrowed to a CODEX_TOOLS-scoped+ * regex for exactly that reason; the positive half never was.+ *+ * The mobile client is real source now (mobile-client/), so the lists and the+ * helpers are imported and asserted on directly: `CODEX_TOOLS` is an array+ * here, not a substring. What genuinely lives inside the 2 100-line client+ * shell — the agent loop, the renderer — still has to be read as text, and+ * those tests say so and read mobile-client/client.js rather than the Rust+ * file that no longer contains it.*/import { describe, it, expect } from 'vitest'-import { readFileSync } from 'fs'-import { resolve } from 'path'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import {+ AGENT_ALL_TOOLS,+ AGENT_TOOLS,+ CODEX_TOOLS,+ buildToolDefs,+ extractToolCallsFromContent,+ isSystemPromptEcho,+ repairToolCallArgs,+ stripRanges,+ stripThinkTags,+} from '../../../mobile-client/agent-core.js'-const REMOTE_RS = readFileSync(resolve(__dirname, '../../../src-tauri/src/commands/remote.rs'), 'utf8')+/** The agent loop and the renderer live in the client shell. */+const CLIENT = readFileSync(+ resolve(__dirname, '..', '..', '..', 'mobile-client', 'client.js'),+ 'utf8',+)+/** The Rust half — the permission defaults are genuinely server-side. */+const REMOTE_RS = readFileSync(+ resolve(__dirname, '..', '..', '..', 'src-tauri', 'src', 'commands', 'remote.rs'),+ 'utf8',+)-describe('Mobile CODEX_TOOLS parity', () => {- it('includes file_read', () => {- expect(REMOTE_RS).toContain("'file_read'")+describe('Mobile CODEX_TOOLS', () => {+ it('is the exact list Codex may call', () => {+ // The whole list, in order, rather than seven independent "contains"+ // checks: a tool added without being thought about shows up here.+ expect(CODEX_TOOLS).toEqual([+ 'file_read',+ 'file_write',+ 'file_list',+ 'file_search',+ 'shell_execute',+ 'web_search',+ 'web_fetch',+ ])})- it('includes file_write', () => {- expect(REMOTE_RS).toContain("'file_write'")+ it('does NOT include the tools retired by the 2.6.6 merge', () => {+ // code_execute / system_info / get_current_time left CODEX_TOOLS when the+ // typed wrappers folded into shell_execute plus the environment block.+ for (const gone of ['code_execute', 'system_info', 'get_current_time']) {+ expect(CODEX_TOOLS).not.toContain(gone)+ }})- it('includes file_list', () => {- expect(REMOTE_RS).toContain("'file_list'")+ it('names only tools the agent actually has', () => {+ // A Codex tool that is not in AGENT_TOOLS is a name buildToolDefs will+ // silently drop, and Codex would then be told about a tool it cannot call.+ for (const name of CODEX_TOOLS) {+ expect(AGENT_ALL_TOOLS).toContain(name)+ }})+})- it('includes file_search', () => {- expect(REMOTE_RS).toContain("'file_search'")+describe('Mobile AGENT_TOOLS', () => {+ it('AGENT_ALL_TOOLS is every registered tool, in registration order', () => {+ expect(AGENT_ALL_TOOLS).toEqual(AGENT_TOOLS.map((t) => t.name))})- it('includes shell_execute', () => {- expect(REMOTE_RS).toContain("'shell_execute'")+ it('covers the desktop roster', () => {+ for (const name of [+ 'todo_write',+ 'web_search',+ 'web_fetch',+ 'file_read',+ 'file_write',+ 'file_list',+ 'file_search',+ 'shell_execute',+ 'screenshot',+ 'image_generate',+ ]) {+ expect(AGENT_ALL_TOOLS).toContain(name)+ }})- it('does NOT include the tools retired by the 2.6.6 merge', () => {- // code_execute / system_info / get_current_time left CODEX_TOOLS when the- // typed wrappers folded into shell_execute plus the environment block.- expect(REMOTE_RS).not.toMatch(/CODEX_TOOLS = \[[^\]]*code_execute/)- expect(REMOTE_RS).not.toMatch(/CODEX_TOOLS = \[[^\]]*system_info/)- expect(REMOTE_RS).not.toMatch(/CODEX_TOOLS = \[[^\]]*get_current_time/)+ it('every tool carries a description and typed parameters', () => {+ for (const t of AGENT_TOOLS) {+ expect(typeof t.name).toBe('string')+ expect(t.description.length).toBeGreaterThan(40)+ expect(Array.isArray(t.parameters)).toBe(true)+ for (const p of t.parameters) {+ expect(typeof p.name).toBe('string')+ expect(['string', 'number', 'boolean', 'array', 'object']).toContain(p.type)+ expect(typeof p.description).toBe('string')+ }+ }+ })+})++describe('Mobile buildToolDefs', () => {+ it('emits Ollama function schemas for exactly the whitelisted names', () => {+ const defs = buildToolDefs(['file_read', 'web_fetch'])+ expect(defs.map((d) => d.function.name)).toEqual(['web_fetch', 'file_read'])+ expect(defs.every((d) => d.type === 'function')).toBe(true)+ })++ it('marks required parameters as required and optional ones as not', () => {+ const [def] = buildToolDefs(['file_read'])+ expect(def.function.parameters.type).toBe('object')+ expect(Object.keys(def.function.parameters.properties)).toEqual(['path', 'offset', 'limit'])+ expect(def.function.parameters.required).toEqual(['path'])})- it('includes web_search', () => {- expect(REMOTE_RS).toContain("'web_search'")+ it('an unknown name yields nothing rather than a half-built schema', () => {+ expect(buildToolDefs(['no_such_tool'])).toEqual([])})- it('includes web_fetch', () => {- expect(REMOTE_RS).toContain("'web_fetch'")+ it('a zero-parameter tool still gets a valid object schema', () => {+ const [def] = buildToolDefs(['screenshot'])+ expect(def.function.parameters).toEqual({ type: 'object', properties: {}, required: [] })})})-describe('Mobile runToolLoop', () => {- it('function exists', () => {- expect(REMOTE_RS).toContain('function runToolLoop')+describe('Mobile tool-call repair', () => {+ it('passes an object through untouched', () => {+ const o = { path: 'a.txt' }+ expect(repairToolCallArgs(o)).toBe(o)})- it('has max iteration guard', () => {- // Mobile should cap iterations to prevent infinite loops- expect(REMOTE_RS).toMatch(/maxIter|MAX_ITER|iter\s*>=\s*\d+|iter\s*<\s*\d+/)+ it('parses the JSON string Ollama sometimes sends instead', () => {+ // This is the bug: the Rust agent-tool endpoint saw args = "{...}" and+ // file_write answered "needs argument".+ expect(repairToolCallArgs('{"path":"a.txt"}')).toEqual({ path: 'a.txt' })})- it('checks for empty tool_calls to terminate loop', () => {- expect(REMOTE_RS).toMatch(/toolCalls.*length\s*===?\s*0|!res\.toolCalls/)+ /**+ * FINDING (01.09.2026, first real test of this function): the+ * double-encoding branch below the first `JSON.parse` is unreachable.+ *+ * The source reads:+ *+ * try{ var parsed = JSON.parse(trimmed);+ * return (parsed && typeof parsed === 'object') ? parsed : {}; }catch(_){}+ * if(trimmed.charAt(0) === '"' && …) // ← double-decode lives here+ *+ * A double-encoded argument IS valid JSON — a JSON string — so the first+ * parse succeeds, `typeof parsed` is 'string', and the function returns `{}`+ * before it ever reaches the unwrapping it was written for. The branch can+ * only be entered by input that both fails to parse and is quoted at both+ * ends, and that input fails the inner parse too.+ *+ * This test pins what the shipped client really does rather than what the+ * comment above the branch says. It is deliberately NOT fixed here: T-75+ * moves this code out of a Rust string without changing a byte of it, and+ * the page this repository serves is proven identical to the one it served+ * before. The fix is its own change.+ */+ it('does NOT unwrap a double-encoded string — the repair branch is dead code', () => {+ expect(repairToolCallArgs(JSON.stringify('{"path":"a.txt"}'))).toEqual({})})- it('supports user abort', () => {- expect(REMOTE_RS).toContain('agentAbort')+ it('answers {} for null, empty and unparseable input rather than throwing', () => {+ expect(repairToolCallArgs(null)).toEqual({})+ expect(repairToolCallArgs('')).toEqual({})+ expect(repairToolCallArgs('not json')).toEqual({})+ expect(repairToolCallArgs(7)).toEqual({})})})-describe('Mobile nativeToolChat', () => {- it('function exists', () => {- expect(REMOTE_RS).toContain('function nativeToolChat')+describe('Mobile fenced tool-call extraction', () => {+ const known = ['file_write', 'shell_execute']++ it('finds a fenced call and reports where it sat', () => {+ const content = 'sure\n```json\n{"name":"file_write","arguments":{"path":"a"}}\n```\ndone'+ const { calls, ranges } = extractToolCallsFromContent(content, known)+ expect(calls).toHaveLength(1)+ expect(calls[0].function.name).toBe('file_write')+ expect(calls[0].function.arguments).toEqual({ path: 'a' })+ expect(content.slice(ranges[0].start, ranges[0].end)).toContain('file_write')})- it('sends tools parameter to Ollama', () => {- expect(REMOTE_RS).toContain('tools:')+ it('ignores a fenced object that is not a known tool', () => {+ const content = '```json\n{"name":"rm_rf","arguments":{}}\n```'+ expect(extractToolCallsFromContent(content, known).calls).toEqual([])})- it('uses /api/chat endpoint', () => {- expect(REMOTE_RS).toContain('/api/chat')+ it('stripRanges removes the JSON from the visible text', () => {+ const content = 'before\n```json\n{"name":"file_write","arguments":{}}\n```\nafter'+ const { ranges } = extractToolCallsFromContent(content, known)+ expect(stripRanges(content, ranges)).toBe('before\n\nafter')+ })++ it('non-string content is not a crash', () => {+ expect(extractToolCallsFromContent(null, known)).toEqual({ calls: [], ranges: [] })})})-describe('Mobile hidden message handling', () => {- it('renderChat skips hidden messages', () => {- expect(REMOTE_RS).toContain('m.hidden')+describe('Mobile system-prompt echo guard', () => {+ it('catches the openings that used to reach the chat', () => {+ for (const echo of [+ 'I am the Coding Agent, ready to help.',+ "Hello! I'm the Coding Agent and I can read files.",+ 'I am ready to receive the task.',+ 'You are an autonomous coding agent.',+ ]) {+ expect(isSystemPromptEcho(echo)).toBe(true)+ }})- it('hidden messages spliced into conversation for API context', () => {- // Hidden messages must be in msgs[] for the LLM to see tool history- expect(REMOTE_RS).toContain('hidden: true')+ it('leaves a real answer alone', () => {+ for (const real of [+ 'I read src/main.ts and the bug is on line 40.',+ 'Done — three files written.',+ '',+ ]) {+ expect(isSystemPromptEcho(real)).toBe(false)+ }})})describe('Mobile thinking support', () => {- it('stripThinkTags function exists', () => {- expect(REMOTE_RS).toContain('stripThinkTags')+ it('strips <think> blocks out of the answer', () => {+ const out = stripThinkTags('<think>plan</think>the answer', false)+ expect(out.content).toBe('the answer')+ expect(out.thinking).toBe('')})- it('handles Ollama native thinking field', () => {- expect(REMOTE_RS).toContain('res.thinking')+ it('keeps the reasoning when asked to', () => {+ const out = stripThinkTags('<think>plan</think>answer', true)+ expect(out.thinking).toBe('plan')+ expect(out.content).toBe('answer')+ })++ it('also strips the non-canonical formats Gemma and GPT-OSS emit', () => {+ expect(stripThinkTags('<reasoning>x</reasoning>real', false).content).toBe('real')+ expect(stripThinkTags('<|channel|>a<|message|>real', false).content).toBe('real')+ })++ it('handles Ollama native thinking field alongside the tags', () => {+ expect(CLIENT).toContain('res.thinking')})})-describe('Mobile fallback final answer', () => {- it('builds summary when content is empty', () => {- expect(REMOTE_RS).toContain('file(s) written')+describe('Mobile agent loop — read as source, because it lives in the shell', () => {+ // These are the parts of the client that touch the DOM and the network on+ // every line, so they are not importable. The assertions are on+ // mobile-client/client.js, i.e. on the file that becomes the page, and they+ // are string matches: they say the call is written down, not that it runs.+ it('runToolLoop exists', () => {+ expect(CLIENT).toContain('function runToolLoop')+ })++ it('has a max iteration guard', () => {+ expect(CLIENT).toMatch(/maxIter|MAX_ITER|iter\s*>=\s*\d+|iter\s*<\s*\d+/)+ })++ it('terminates on an empty tool_calls list', () => {+ expect(CLIENT).toMatch(/toolCalls.*length\s*===?\s*0|!res\.toolCalls/)+ })++ it('supports user abort', () => {+ expect(CLIENT).toContain('agentAbort')+ })++ it('routes Codex to CODEX_TOOLS and Agent to AGENT_ALL_TOOLS', () => {+ expect(CLIENT).toContain('isCodexChat ? CODEX_TOOLS : AGENT_ALL_TOOLS')})- it('finishToolLoop function exists', () => {- expect(REMOTE_RS).toContain('finishToolLoop')+ it('nativeToolChat posts to the Ollama proxy with a tools array', () => {+ expect(CLIENT).toContain('function nativeToolChat')+ expect(CLIENT).toContain("fetch('/api/chat'")+ expect(CLIENT).toMatch(/tools:\s*tools/)+ })++ it('renderChat skips hidden messages, which are still in msgs for the model', () => {+ expect(CLIENT).toContain('m.hidden')+ expect(CLIENT).toContain('hidden: true')+ })++ it('falls back to a written summary when the model answers empty', () => {+ expect(CLIENT).toContain('file(s) written')+ expect(CLIENT).toContain('finishToolLoop')})})-describe('Mobile permissions', () => {+describe('Mobile permissions (server side, so still Rust)', () => {// RA-1: this used to assert "all permissions default to ON" — and it passed// for the wrong reason, because it matched `filesystem: true` ANYWHERE in the- // 6k-line file (the merge tests contain that literal). The default it was- // guarding was itself the bug: the desktop panel renders every toggle off on- // a fresh start, so a server that starts filesystem/downloads/process_control- // at `true` hands a paired phone workspace read/write, model pull/delete and+ // file (the merge tests contain that literal). The default it was guarding+ // was itself the bug: the desktop panel renders every toggle off on a fresh+ // start, so a server that starts filesystem/downloads/process_control at+ // `true` hands a paired phone workspace read/write, model pull/delete and// ComfyUI start/stop that the user never granted. Now scoped to the actual// `impl Default` block, and asserting the conservative default.const defaultBlock = REMOTE_RS.match(@@ -154,13 +330,3 @@ describe('Mobile permissions', () => {expect(REMOTE_RS).toContain('"permissions": permissions')})})--describe('Mobile Codex vs Agent routing', () => {- it('Codex mode uses CODEX_TOOLS', () => {- expect(REMOTE_RS).toContain('isCodexChat ? CODEX_TOOLS')- })-- it('Agent mode uses AGENT_ALL_TOOLS', () => {- expect(REMOTE_RS).toContain('AGENT_ALL_TOOLS')- })-})diff --git a/src/api/__tests__/mobile-context-decay.test.ts b/src/api/__tests__/mobile-context-decay.test.tsindex 9cd63602..5cfbfc13 100644--- a/src/api/__tests__/mobile-context-decay.test.ts+++ b/src/api/__tests__/mobile-context-decay.test.ts@@ -16,9 +16,17 @@* prompt and the original task, and the run answered "I'm ready to receive the* task" mid-loop. That is the documented mobile task-forgetting.*- * These tests run the SHIPPED code: the helpers are cut out of remote.rs and- * evaluated, so a change to the served page changes what runs here. Structural- * assertions alone would have passed against a helper nobody called.+ * ── 01.09.2026 (T-75): these helpers are now imported, not cut out ──+ *+ * Until today this file read src-tauri/src/commands/remote.rs, found the+ * 2 964-line Rust string the mobile page used to live in, sliced the helper+ * block out of it with two indexOf calls and ran it through `new Function`.+ * It did run the shipped code, which is why it was worth keeping — but it+ * depended on two comment lines inside a Rust literal keeping their exact+ * wording, and nothing said so.+ *+ * The client is real source now (mobile-client/), so the import below is the+ * shipped file. Delete an export from agent-core.js and this stops compiling.** Run: npx vitest run src/api/__tests__/mobile-context-decay.test.ts*/@@ -26,54 +34,35 @@ import { describe, it, expect } from 'vitest'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'import { DECAY_RESULT_CHARS, RESTORE_RESULT_CHARS, DECAY_AFTER_ITERATIONS } from '../../lib/context-decay'+import {+ DECAY_AFTER_ITERATIONS as MOBILE_DECAY_AFTER_ITERATIONS,+ DECAY_RESULT_CHARS as MOBILE_DECAY_RESULT_CHARS,+ RESTORE_RESULT_CHARS as MOBILE_RESTORE_RESULT_CHARS,+ capToolResult,+ compactApiMessages,+ decayToolResults,+ dropOldImages,+ isDecayedAt,+ msgChars,+} from '../../../mobile-client/agent-core.js'++interface Msg { role: string; content?: string; images?: string[]; iter?: number }-const REMOTE_RS = readFileSync(- resolve(__dirname, '..', '..', '..', 'src-tauri', 'src', 'commands', 'remote.rs'),- 'utf8',-)+/** A file out of mobile-client/, i.e. a file the phone really receives. */+const clientSource = (name: string) =>+ readFileSync(resolve(__dirname, '..', '..', '..', 'mobile-client', name), 'utf8')/**- * ONLY the page a phone receives: the raw string inside mobile_landing.+ * The agent loop, which is what has to CALL all of this.*- * Searching the whole file is a trap, and it caught this test first: the Rust- * guards at the bottom of remote.rs quote the very lines asserted below, so- * deleting `iter:iter` from the real push left the assertion matching the Rust- * test's copy of it and everything stayed green.+ * A helper nobody calls proves nothing, and the whole bug was a compaction+ * that could not reach the message that mattered. Reading client.js rather+ * than the whole repository is the same precaution as before: the Rust guards+ * in remote.rs quote these lines, and searching everything let a deleted call+ * match the guard's copy of itself.*/-const PAGE = (() => {- const start = REMOTE_RS.indexOf('async fn mobile_landing')- expect(start, 'mobile_landing not found').toBeGreaterThan(-1)- const end = REMOTE_RS.indexOf('"#', start)- expect(end, 'the page literal never ends').toBeGreaterThan(start)- return REMOTE_RS.slice(start, end)-})()--interface Msg { role: string; content?: string; images?: string[]; iter?: number }-interface MobileHelpers {- DECAY_RESULT_CHARS: number- RESTORE_RESULT_CHARS: number- DECAY_AFTER_ITERATIONS: number- IMAGE_KEEP_RECENT: number- capToolResult: (text: unknown, maxChars: number) => string- isDecayedAt: (text: unknown, budget: number) => boolean- decayToolResults: (messages: Msg[], currentIter: number) => Msg[]- msgChars: (m: Msg) => number- dropOldImages: (messages: Msg[], keepRecent: number) => Msg[]- compactApiMessages: (messages: Msg[], budget?: number) => Msg[]-}--/** Cut the shipped block out of the page and evaluate it. */-const mobile: MobileHelpers = (() => {- const from = PAGE.indexOf(' // ── A1 mobile: age decay for tool results')- const to = PAGE.indexOf(' // Convert the flat AGENT_TOOLS array')- expect(from, 'A1 mobile block not found in remote.rs').toBeGreaterThan(-1)- expect(to, 'end of the compaction block not found').toBeGreaterThan(from)- const source = PAGE.slice(from, to)- const factory = new Function(`${source}- return { DECAY_RESULT_CHARS, RESTORE_RESULT_CHARS, DECAY_AFTER_ITERATIONS, IMAGE_KEEP_RECENT,- capToolResult, isDecayedAt, decayToolResults, msgChars, dropOldImages, compactApiMessages };`)- return factory() as MobileHelpers-})()+const LOOP = clientSource('client.js')+const CORE = clientSource('agent-core.js')const big = (n: number, fill = 'x') => fill.repeat(n)const hist = (...msgs: Msg[]) => msgs.map((m) => ({ ...m }))@@ -82,13 +71,13 @@ describe('the relay and the desktop cap by the same numbers', () => {it('carries the desktop constants verbatim', () => {// Two catalogs of numbers is two behaviours. The desktop module is the// source; if it moves, this fails and the relay moves with it.- expect(mobile.DECAY_RESULT_CHARS).toBe(DECAY_RESULT_CHARS)- expect(mobile.RESTORE_RESULT_CHARS).toBe(RESTORE_RESULT_CHARS)- expect(mobile.DECAY_AFTER_ITERATIONS).toBe(DECAY_AFTER_ITERATIONS)+ expect(MOBILE_DECAY_RESULT_CHARS).toBe(DECAY_RESULT_CHARS)+ expect(MOBILE_RESTORE_RESULT_CHARS).toBe(RESTORE_RESULT_CHARS)+ expect(MOBILE_DECAY_AFTER_ITERATIONS).toBe(DECAY_AFTER_ITERATIONS)})it('cuts head-heavy and says how much it dropped', () => {- const out = mobile.capToolResult('A'.repeat(3000) + 'B'.repeat(3000), 4000)+ const out = capToolResult('A'.repeat(3000) + 'B'.repeat(3000), 4000)expect(out.length).toBeLessThan(4200)expect(out.startsWith('A'.repeat(2640))).toBe(true)expect(out.endsWith('B'.repeat(1360))).toBe(true)@@ -97,15 +86,15 @@ describe('the relay and the desktop cap by the same numbers', () => {it('leaves a result that already fits completely alone', () => {const short = 'exit 0'- expect(mobile.capToolResult(short, 4000)).toBe(short)+ expect(capToolResult(short, 4000)).toBe(short)})it('is idempotent, which is what keeps the prompt prefix still', () => {- const once = mobile.capToolResult(big(200000), 4000)- const twice = mobile.capToolResult(once, 4000)+ const once = capToolResult(big(200000), 4000)+ const twice = capToolResult(once, 4000)expect(twice).toBe(once)- expect(mobile.isDecayedAt(once, 4000)).toBe(true)- expect(mobile.isDecayedAt('plain text', 4000)).toBe(false)+ expect(isDecayedAt(once, 4000)).toBe(true)+ expect(isDecayedAt('plain text', 4000)).toBe(false)})})@@ -123,14 +112,14 @@ describe('a big read stops riding along after two iterations', () => {// The binding rule: the model must never edit against content it can no// longer see, and what it is working on is what it just fetched.const msgs = run()- mobile.decayToolResults(msgs, 2)+ decayToolResults(msgs, 2)expect(msgs[3].content!.length).toBe(200000)expect(msgs[5].content!.length).toBe(5000)})it('one step later the older result is capped and the newer one is not', () => {const msgs = run()- mobile.decayToolResults(msgs, 3)+ decayToolResults(msgs, 3)expect(msgs[3].content!.length).toBeLessThan(4200)expect(msgs[3].content).toContain('[truncated')expect(msgs[5].content!.length).toBe(5000)@@ -138,15 +127,15 @@ describe('a big read stops riding along after two iterations', () => {it('a second pass changes nothing, so only one place in the prompt moves per step', () => {const msgs = run()- mobile.decayToolResults(msgs, 3)+ decayToolResults(msgs, 3)const after = msgs.map((m) => m.content)- mobile.decayToolResults(msgs, 3)+ decayToolResults(msgs, 3)expect(msgs.map((m) => m.content)).toEqual(after)})it('restored history with no iteration counts as oldest', () => {const msgs = hist({ role: 'tool', content: big(50000) })- mobile.decayToolResults(msgs, 1)+ decayToolResults(msgs, 1)expect(msgs[0].content!.length).toBeLessThan(4200)})@@ -154,7 +143,7 @@ describe('a big read stops riding along after two iterations', () => {const msgs = run()// The old behaviour, spelled out: nothing capped it, at any iteration.expect(msgs[3].content!.length).toBe(200000)- mobile.decayToolResults(msgs, 99)+ decayToolResults(msgs, 99)expect(msgs[3].content!.length).toBeLessThan(4200)})@@ -163,7 +152,7 @@ describe('a big read stops riding along after two iterations', () => {{ role: 'user', content: big(50000), iter: 1 },{ role: 'assistant', content: big(50000), iter: 1 },)- mobile.decayToolResults(msgs, 9)+ decayToolResults(msgs, 9)expect(msgs[0].content!.length).toBe(50000)expect(msgs[1].content!.length).toBe(50000)})@@ -171,8 +160,8 @@ describe('a big read stops riding along after two iterations', () => {describe('image bytes are part of the budget now', () => {it('msgChars counts the base64, which is the whole payload', () => {- expect(mobile.msgChars({ role: 'user', content: 'hi', images: [big(1000), big(500)] })).toBe(1502)- expect(mobile.msgChars({ role: 'user', content: 'hi' })).toBe(2)+ expect(msgChars({ role: 'user', content: 'hi', images: [big(1000), big(500)] })).toBe(1502)+ expect(msgChars({ role: 'user', content: 'hi' })).toBe(2)})it('only the newest two messages send their pictures again', () => {@@ -182,7 +171,7 @@ describe('image bytes are part of the budget now', () => {{ role: 'user', content: 'three', images: [big(100)] },{ role: 'user', content: 'four', images: [big(100)] },)- mobile.dropOldImages(msgs, 2)+ dropOldImages(msgs, 2)expect(msgs[0].images).toBeUndefined()expect(msgs[1].images).toBeUndefined()expect(msgs[2].images).toHaveLength(1)@@ -205,8 +194,8 @@ describe('image bytes are part of the budget now', () => {// error next to the pictures, so the old total said 40 characters.const contentOnly = msgs.reduce((a, m) => a + String(m.content || '').length, 0)expect(contentOnly).toBeLessThan(100)- const out = mobile.compactApiMessages(msgs, 24000)- const kept = out.reduce((a, m) => a + mobile.msgChars(m), 0)+ const out: Msg[] = compactApiMessages(msgs, 24000)+ const kept = out.reduce((a: number, m: Msg) => a + msgChars(m), 0)expect(kept).toBeLessThan(90000)expect(out[0].role).toBe('system')})@@ -223,15 +212,15 @@ describe('compaction survives a single result bigger than the whole budget', ())it('the payload gets under budget instead of being handed over oversized', () => {- const out = mobile.compactApiMessages(runaway(), 24000)- const total = out.reduce((a, m) => a + mobile.msgChars(m), 0)+ const out: Msg[] = compactApiMessages(runaway(), 24000)+ const total = out.reduce((a: number, m: Msg) => a + msgChars(m), 0)expect(total).toBeLessThanOrEqual(24000)})it('the system prompt and the task are what survive', () => {// The old code returned the four huge messages untouched and Ollama cut// the front off, which is exactly these two.- const out = mobile.compactApiMessages(runaway(), 24000)+ const out = compactApiMessages(runaway(), 24000)expect(out[0].content).toBe('SYSTEM PROMPT')expect(out[1].content).toBe('the task')})@@ -254,7 +243,7 @@ describe('compaction survives a single result bigger than the whole budget', (){ role: 'assistant', content: 'done' },{ role: 'user', content: 'thanks' },)- expect(mobile.compactApiMessages(msgs, 24000)).toEqual(msgs)+ expect(compactApiMessages(msgs, 24000)).toEqual(msgs)})})@@ -262,33 +251,33 @@ describe('the loop actually calls all of it', () => {// A helper nobody calls is a helper that proves nothing, and the whole bug// was a compaction that could not reach the message that mattered.it('the observation push carries its iteration', () => {- expect(PAGE).toMatch(/apiMessages\.push\(\{role:'tool', content:obs, iter:iter\}\)/)- expect(PAGE).toMatch(/apiMessages\.push\(\{role:'tool', content:'Error: '\+errMsg, iter:iter\}\)/)+ expect(LOOP).toMatch(/apiMessages\.push\(\{role:'tool', content:obs, iter:iter\}\)/)+ expect(LOOP).toMatch(/apiMessages\.push\(\{role:'tool', content:'Error: '\+errMsg, iter:iter\}\)/)})it('decay runs before compaction, on every step', () => {// Anchored at the start of a line so a commented-out call cannot pass.// The first version of this test matched the substring and stayed green// with the call disabled, which is the failure mode a guard is for.- const decayAt = PAGE.search(/\n[ \t]*decayToolResults\(apiMessages, iter\);/)- const compactAt = PAGE.search(/\n[ \t]*apiMessages = compactApiMessages\(apiMessages, 24000\);/)+ const decayAt = LOOP.search(/\n[ \t]*decayToolResults\(apiMessages, iter\);/)+ const compactAt = LOOP.search(/\n[ \t]*apiMessages = compactApiMessages\(apiMessages, 24000\);/)expect(decayAt).toBeGreaterThan(-1)expect(compactAt).toBeGreaterThan(decayAt)})it('the compaction really drops the old images, it does not just define how', () => {- expect(PAGE).toMatch(/\n[ \t]*dropOldImages\(messages, IMAGE_KEEP_RECENT\);/)- expect(PAGE).toMatch(/\n[ \t]*if\(totalChars\(messages\) <= budget\) return messages;/)+ expect(CORE).toMatch(/\n[ \t]*dropOldImages\(messages, IMAGE_KEEP_RECENT\);/)+ expect(CORE).toMatch(/\n[ \t]*if\(totalChars\(messages\) <= budget\) return messages;/)})it('a result bigger than the budget is capped rather than handed over whole', () => {// The rungs are the last line of defence, and they are easy to delete by// accident because nothing in the ordinary path reaches them.- expect(PAGE).toMatch(/var rungs = \[DECAY_RESULT_CHARS, RESTORE_RESULT_CHARS\];/)+ expect(CORE).toMatch(/var rungs = \[DECAY_RESULT_CHARS, RESTORE_RESULT_CHARS\];/)})it('restored tool history is capped at the tighter budget when it was never capped', () => {- expect(PAGE).toMatch(+ expect(LOOP).toMatch(/if\(m\.role === 'tool' && !isDecayedAt\(content, DECAY_RESULT_CHARS\)\)\{\s*\n\s*content = capToolResult\(content, RESTORE_RESULT_CHARS\);/,)})diff --git a/src/api/__tests__/mobile-html-content.test.ts b/src/api/__tests__/mobile-html-content.test.tsindex b9c78953..b78f2036 100644--- a/src/api/__tests__/mobile-html-content.test.ts+++ b/src/api/__tests__/mobile-html-content.test.ts@@ -1,227 +1,280 @@/**- * Validates the raw HTML/CSS/JS string embedded in- * src-tauri/src/commands/remote.rs `mobile_landing()`. Catches regressions- * where someone accidentally deletes a class, helper, or required marker.+ * The page a paired phone receives — checked against the files it is made of.+ *+ * ── 01.09.2026 (T-75) ──+ *+ * This file used to pull the page out of a Rust string:+ *+ * src.match(/async fn mobile_landing\(\)[\s\S]*?Html\(r#"([\s\S]*?)"#…/)+ *+ * One regex against 7 483 lines of Rust, and then thirty `toContain` calls+ * against the 182 KB blob it returned. Two things were wrong with that. The+ * regex was load-bearing and undeclared: reformat `mobile_landing` and every+ * assertion below stops running, silently, because the match still succeeded+ * on something. And a blob has no structure, so `expect(html).toContain(+ * '.drawer{')` could not tell a stylesheet rule from the same characters in a+ * comment or a JavaScript string.+ *+ * The client is real source now, so each assertion reads the file it is+ * actually about: markup from index.html, rules from styles.css, behaviour+ * from client.js — and the constants are imported, not matched.+ *+ * What Rust still owns is that these files really are what gets served:+ * `mobile_source_of_truth_tests::mobile_landing_is_what_the_sources_say` in+ * src-tauri/src/commands/remote.rs re-assembles the page on every `cargo test`+ * and compares it byte for byte with the embedded one.*/-import { describe, it, expect, beforeAll } from 'vitest'+import { describe, it, expect } from 'vitest'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'+import { CAVEMAN_PROMPTS, CAVEMAN_REMINDERS } from '../../../mobile-client/caveman.js'+import { CODEX_PROMPT, PERSONAS, THINKING_COMPATIBLE } from '../../../mobile-client/personas.js'-let html = ''+const read = (name: string) =>+ readFileSync(resolve(__dirname, '..', '..', '..', 'mobile-client', name), 'utf8')-beforeAll(() => {- const src = readFileSync(- resolve(process.cwd(), 'src-tauri/src/commands/remote.rs'),- 'utf-8',- )- const m = src.match(/async fn mobile_landing\(\)[\s\S]*?Html\(r#"([\s\S]*?)"#\.to_string\(\)\)/)- if (!m) throw new Error('Could not locate mobile_landing HTML block')- html = m[1]-})+/** The document shell: everything outside <style> and <script>. */+const HTML = read('index.html')+/** The stylesheet, on its own, so a rule assertion cannot match a comment. */+const CSS = read('styles.css')+/** The client script's shell — the part that touches the DOM. */+const JS = read('client.js')-describe('mobile_landing HTML › structural markers', () => {- it('is a full HTML document', () => {- expect(html.startsWith('<!DOCTYPE html>')).toBe(true)+describe('mobile page › the shell is a whole HTML document', () => {+ it('starts as a document and names the two splice points', () => {+ expect(HTML.startsWith('<!DOCTYPE html>')).toBe(true)+ // The assembler fills these in; a shell that lost one would ship a page+ // with no stylesheet or no script, and src-tauri/build.rs stops the build+ // over exactly that.+ expect(HTML).toContain('/*@@LU_STYLES@@*/')+ expect(HTML).toContain('//@@LU_SCRIPT@@')})it('contains <html>, <head>, <body>, </html>', () => {- expect(html).toContain('<html')- expect(html).toContain('<head>')- expect(html).toContain('<body>')- expect(html).toContain('</html>')+ expect(HTML).toContain('<html')+ expect(HTML).toContain('<head>')+ expect(HTML).toContain('<body>')+ expect(HTML).toContain('</html>')})it('includes mobile viewport meta', () => {- expect(html).toMatch(/<meta name="viewport"[^>]+width=device-width/)+ expect(HTML).toMatch(/<meta name="viewport"[^>]+width=device-width/)})- it('uses system font stack (no Google Fonts — Bug #5)', () => {- expect(html).toContain('system-ui')- // Specifically, NO third-party font URLs- expect(html).not.toContain('fonts.googleapis.com')- expect(html).not.toContain('fonts.gstatic.com')+ it('sets a restrictive Content-Security-Policy (Bug #6)', () => {+ expect(HTML).toContain('http-equiv="Content-Security-Policy"')+ expect(HTML).toContain("default-src 'self'")+ expect(HTML).toContain("frame-ancestors 'none'")})- it('inlines SVG icons instead of Material Symbols font (Bug #5)', () => {- // Font file link is gone, but icon names still route through a local- // SVG dispatcher named svgIcon().- expect(html).not.toContain('Material+Symbols+Outlined')- expect(html).toContain('svgIcon')- expect(html).toContain('var ICONS =')+ it('has black theme color for mobile chrome', () => {+ expect(HTML).toContain("content='#0e0e0e'")})- it('sets a restrictive Content-Security-Policy (Bug #6)', () => {- expect(html).toContain('http-equiv="Content-Security-Policy"')- expect(html).toContain("default-src 'self'")- expect(html).toContain("frame-ancestors 'none'")+ it('keeps the browser tab discreet (D#101)', () => {+ // The tab title and the saved-to-homescreen name are what bystanders see;+ // both stay a neutral "AI Terminal".+ expect(HTML).toContain('<title>AI Terminal</title>')+ expect(HTML).toContain('name="apple-mobile-web-app-title" content="AI Terminal"')+ expect(HTML).not.toContain('<title>LU</title>')+ expect(HTML).not.toContain('LUncensored')+ expect(HTML).not.toContain('Locally Uncensored')})+})- it('has black theme color for mobile chrome', () => {- expect(html).toContain("content='#0e0e0e'")+describe('mobile page › no third-party requests (Bug #5)', () => {+ it('the stylesheet uses the system font stack and loads no font', () => {+ expect(CSS).toContain('system-ui')+ expect(CSS).not.toContain('fonts.googleapis.com')+ expect(CSS).not.toContain('fonts.gstatic.com')+ expect(CSS).not.toContain('Material+Symbols+Outlined')+ expect(CSS).not.toContain('@import')+ })++ it('no file in the client reaches a third-party host', () => {+ for (const [name, src] of [+ ['index.html', HTML],+ ['styles.css', CSS],+ ['client.js', JS],+ ] as const) {+ // Data and blob URLs are fine — thumbnails and the QR code use them.+ const external = src.match(/https?:\/\/[^\s"'()]+/g) ?? []+ expect(external, `${name} names an external host`).toEqual([])+ }+ })++ it('icons are inline SVG, dispatched by name', () => {+ expect(JS).toContain('function svgIcon(')+ expect(JS).toContain('var ICONS =')})})-describe('mobile_landing HTML › LU branding assets', () => {+describe('mobile page › LU branding assets', () => {it('references the white-transparent monogram path', () => {- expect(html).toContain('/LU-monogram-white.png')+ expect(JS).toContain('/LU-monogram-white.png')})it('does NOT reference the old bw monogram (should have been migrated)', () => {- expect(html).not.toContain('/LU-monogram-bw.png')+ expect(JS).not.toContain('/LU-monogram-bw.png')+ expect(HTML).not.toContain('/LU-monogram-bw.png')})it('uses the monogram in at least 4 places (auth, header, drawer, welcome)', () => {- const matches = html.match(/\/LU-monogram-white\.png/g) || []+ const matches = JS.match(/\/LU-monogram-white\.png/g) || []expect(matches.length).toBeGreaterThanOrEqual(4)})- it('keeps the browser tab discreet and the in-page wordmark LU (D#101)', () => {- // The tab title and the saved-to-homescreen name are what bystanders- // see; both stay a neutral "AI Terminal". Inside the page the LU- // wordmark is fine, the person using it knows what it is.- expect(html).toContain('<title>AI Terminal</title>')- expect(html).toContain('name="apple-mobile-web-app-title" content="AI Terminal"')- expect(html).not.toContain('<title>LU</title>')- expect(html).toContain('class="auth-logo">LU<')- expect(html).not.toContain('LUncensored')- expect(html).not.toContain('Locally Uncensored')+ it('the in-page wordmark is LU', () => {+ expect(JS).toContain('class="auth-logo">LU<')})})-describe('mobile_landing HTML › feature markers', () => {- it('hamburger drawer classes present', () => {- expect(html).toContain('.drawer{')- expect(html).toContain('.drawer-backdrop')+describe('mobile page › feature markers', () => {+ it('hamburger drawer rules live in the stylesheet', () => {+ expect(CSS).toContain('.drawer{')+ expect(CSS).toContain('.drawer-backdrop')})it('has _toggleDrawer handler', () => {- expect(html).toContain('_toggleDrawer')+ expect(JS).toContain('_toggleDrawer')})it('has _newChat handler for Chat + Codex', () => {- expect(html).toContain('_newChat')- expect(html).toContain("'codex'")- expect(html).toContain("'lu'")+ expect(JS).toContain('_newChat')+ expect(JS).toContain("'codex'")+ expect(JS).toContain("'lu'")})it('exposes _openModelPicker and _openPluginsPicker', () => {- expect(html).toContain('_openModelPicker')- expect(html).toContain('_openPluginsPicker')+ expect(JS).toContain('_openModelPicker')+ expect(JS).toContain('_openPluginsPicker')})it('has _toggleThinking handler', () => {- expect(html).toContain('_toggleThinking')+ expect(JS).toContain('_toggleThinking')})it('has _triggerAttach + _removeImage for file attach', () => {- expect(html).toContain('_triggerAttach')- expect(html).toContain('_removeImage')+ expect(JS).toContain('_triggerAttach')+ expect(JS).toContain('_removeImage')})it('file input accepts image/* and multiple files', () => {- expect(html).toMatch(/file-input[^>]*accept="image\/\*"[^>]*multiple/)+ expect(JS).toMatch(/file-input[^>]*accept="image\/\*"[^>]*multiple/)})it('has _setCaveman + _setPersona handlers', () => {- expect(html).toContain('_setCaveman')- expect(html).toContain('_setPersona')+ expect(JS).toContain('_setCaveman')+ expect(JS).toContain('_setPersona')})it('has _loadChat and _deleteChat handlers', () => {- expect(html).toContain('_loadChat')- expect(html).toContain('_deleteChat')+ expect(JS).toContain('_loadChat')+ expect(JS).toContain('_deleteChat')})it('has _disconnect handler', () => {- expect(html).toContain('_disconnect')+ expect(JS).toContain('_disconnect')})})-describe('mobile_landing HTML › caveman/persona/codex content', () => {- it('embeds all three CAVEMAN_PROMPTS', () => {- expect(html).toContain('Be concise and direct')- expect(html).toContain('Respond terse like smart caveman')- expect(html).toContain('Maximum brevity')+describe('mobile page › caveman / persona / codex content', () => {+ // Imported, not matched: these are the objects the client really reads.+ it('ships exactly three caveman levels, each with a reminder', () => {+ expect(Object.keys(CAVEMAN_PROMPTS)).toEqual(['lite', 'full', 'ultra'])+ expect(Object.keys(CAVEMAN_REMINDERS).sort()).toEqual(['full', 'lite', 'ultra'])+ })++ it('every caveman prompt says the code stays untouched', () => {+ for (const level of Object.keys(CAVEMAN_PROMPTS) as (keyof typeof CAVEMAN_PROMPTS)[]) {+ expect(CAVEMAN_PROMPTS[level].toLowerCase()).toMatch(/code|unchanged/)+ }})- it('embeds all three CAVEMAN_REMINDERS', () => {- expect(html).toContain('[Be concise. No filler.]')- expect(html).toContain('[Terse. Fragments OK. No fluff.]')- expect(html).toContain('[Max brevity. Telegraphic.]')+ it('the reminders are short bracketed nudges, not second prompts', () => {+ for (const level of Object.keys(CAVEMAN_REMINDERS) as (keyof typeof CAVEMAN_REMINDERS)[]) {+ expect(CAVEMAN_REMINDERS[level]).toMatch(/^\[.+\]$/)+ expect(CAVEMAN_REMINDERS[level].length).toBeLessThan(40)+ }})- it('has codex prompt snippet', () => {- expect(html).toContain('You are the Coding Agent')+ it('the codex prompt introduces the Coding Agent and forbids guessing', () => {+ expect(CODEX_PROMPT).toContain('You are the Coding Agent')+ expect(CODEX_PROMPT).toContain('never guess file contents')})- it('embeds the No Filter default persona', () => {- expect(html).toContain("id:'unrestricted'")+ it('No Filter is the default persona and carries no prompt', () => {+ expect(PERSONAS[0].id).toBe('unrestricted')+ expect(PERSONAS[0].name).toBe('No Filter')+ expect(PERSONAS[0].prompt).toBe('')})- it('embeds Code Expert persona', () => {- expect(html).toContain("id:'coder'")- expect(html).toContain('Code Expert')+ it('ships Code Expert', () => {+ const coder = PERSONAS.find((p) => p.id === 'coder')+ expect(coder?.name).toBe('Code Expert')+ expect(coder?.prompt.length).toBeGreaterThan(20)})- it('embeds at least 20 personas (we ship 25)', () => {- const matches = html.match(/\{id:'[^']+',name:'[^']+',prompt:/g) || []- expect(matches.length).toBeGreaterThanOrEqual(20)+ it('ships at least 20 personas, each with a unique id', () => {+ expect(PERSONAS.length).toBeGreaterThanOrEqual(20)+ expect(new Set(PERSONAS.map((p) => p.id)).size).toBe(PERSONAS.length)+ for (const p of PERSONAS) {+ expect(typeof p.name).toBe('string')+ expect(typeof p.prompt).toBe('string')+ }})- it('THINKING_COMPATIBLE list matches desktop (qwq/deepseek-r1/qwen3/gemma3/gemma4)', () => {- expect(html).toContain("'qwq'")- expect(html).toContain("'deepseek-r1'")- expect(html).toContain("'qwen3'")- expect(html).toContain("'gemma3'")- expect(html).toContain("'gemma4'")+ it('THINKING_COMPATIBLE lists the desktop families', () => {+ for (const tag of ['qwq', 'deepseek-r1', 'qwen3', 'gemma3', 'gemma4']) {+ expect(THINKING_COMPATIBLE).toContain(tag)+ }})})-describe('mobile_landing HTML › input bar sizing parity', () => {+describe('mobile page › input bar sizing parity', () => {it('textarea min-height 44px matches attach/send button height', () => {- // parity with user request: all three elements same height- expect(html).toMatch(/min-height:44px/)+ expect(CSS).toMatch(/min-height:44px/)})it('attach + send buttons are 44x44', () => {- expect(html).toMatch(/\.attach-btn,\.send-btn\{width:44px;height:44px/)+ expect(CSS).toMatch(/\.attach-btn,\.send-btn\{width:44px;height:44px/)})})-describe('mobile_landing HTML › plugins picker structure', () => {+describe('mobile page › plugins picker structure', () => {it('plugin sub-folder rows are collapsed by default via pluginsOpen reset', () => {- expect(html).toMatch(/pluginsOpen\s*=\s*\{caveman:false,\s*persona:false\}/)+ expect(JS).toMatch(/pluginsOpen\s*=\s*\{caveman:false,\s*persona:false\}/)})it('persona has on/off switch element', () => {- expect(html).toContain('data-persona-enabled')- expect(html).toContain('plug-switch')+ expect(JS).toContain('data-persona-enabled')+ expect(JS).toContain('plug-switch')})it('picker sheet has a Plugins title', () => {- expect(html).toContain('>Plugins<')+ expect(JS).toContain('>Plugins<')})})-describe('mobile_landing HTML › security/UX details', () => {+describe('mobile page › security/UX details', () => {it('auth screen uses numeric input for passcode', () => {- expect(html).toMatch(/inputmode="numeric"/)- expect(html).toMatch(/maxlength="6"/)+ expect(JS).toMatch(/inputmode="numeric"/)+ expect(JS).toMatch(/maxlength="6"/)})it('401 handler clears token + reloads', () => {- expect(html).toContain('clearAuthAndReload')+ expect(JS).toContain('clearAuthAndReload')})it('Bearer token attached to authenticated fetches', () => {- expect(html).toContain("'Authorization':'Bearer '+TOKEN")+ expect(JS).toContain("'Authorization':'Bearer '+TOKEN")})it('chat-event endpoint posts mirror to desktop', () => {- expect(html).toContain('/remote-api/chat-event')+ expect(JS).toContain('/remote-api/chat-event')})it('streaming chat endpoint is /api/chat (Ollama proxy)', () => {- expect(html).toContain("fetch('/api/chat'")+ expect(JS).toContain("fetch('/api/chat'")})})diff --git a/src/api/__tests__/mobile-parity.test.ts b/src/api/__tests__/mobile-parity.test.tsindex 9312f5fc..84db5f63 100644--- a/src/api/__tests__/mobile-parity.test.ts+++ b/src/api/__tests__/mobile-parity.test.ts@@ -1,88 +1,106 @@/**- * Mobile Web UI parity tests+ * Mobile Web UI parity tests.*- * The mobile web UI (rendered by src-tauri/src/commands/remote.rs::mobile_landing)- * ships inline JS with re-implemented versions of a few desktop helpers. These- * tests pin the expected behaviour so regressions on either side surface here.+ * ── 01.09.2026 (T-75): this file WAS the finding ──+ *+ * Until today the top of this file read:+ *+ * // ─── Re-implementations matching the mobile HTML (must stay in sync) ───+ * const CAVEMAN_PROMPTS = { lite: '…', full: '…', ultra: '…' }+ * function buildSystemPrompt(chat, opts) { … }+ * function transformUserMessageWithCaveman(msg, caveman, _model) { … }+ * function buildOllamaBody(model, messages, opts) { … }+ *+ * — a hand-written TypeScript copy of four things the mobile client does,+ * followed by sixty assertions about the copy. The client itself was a Rust+ * string literal nothing could import, so this was the only way to write a+ * test at all, and "must stay in sync" was the entire enforcement mechanism.+ * The suite was green whichever of the two versions was wrong.+ *+ * One detail says it best: `isThinkingCompatible` was imported from+ * `src/lib/model-compatibility` — the DESKTOP helper — and the tests below it+ * were headed "isThinkingCompatible (desktop helper reused on mobile)". The+ * mobile client has never used it. It carries its own, over its own prefix+ * list, with a different normalisation. Twelve green assertions about a+ * function the phone does not run.+ *+ * The client is real source now. Constants and pure helpers are imported from+ * mobile-client/. `buildSystemPrompt` and the client's own+ * `isThinkingCompatible` still live in the DOM-bound shell, so they are cut+ * out by name and run with their surroundings injected — the shipped body,+ * not a copy of it. See src/api/__tests__/mobile-client-shell.ts for why that+ * is the ceiling and what would have to move for an import.*/import { describe, it, expect } from 'vitest'-import { isThinkingCompatible } from '../../lib/model-compatibility'--// ─── Re-implementations matching the mobile HTML (must stay in sync) ───--const CAVEMAN_PROMPTS = {- lite: 'Be concise and direct. Drop filler words (just, really, basically, actually, simply), hedging, and pleasantries. Retain full grammar and articles. Keep code blocks, file paths, URLs, and commands unchanged. Every response follows this style.',- full: 'Respond terse like smart caveman. All technical substance stay. Only fluff die. Drop: articles, filler (just/really/basically/actually/simply), pleasantries, hedging. Fragments OK. Short synonyms preferred. Code unchanged. Pattern: [thing] [action] [reason]. [next step]. ACTIVE EVERY RESPONSE.',- ultra: 'Maximum brevity. Fewest possible words. Telegraphic. Abbreviate (DB/auth/config/fn/impl/req/res). Strip conjunctions. Arrows for flow (X -> Y). No articles, no filler, no pleasantries. Fragments only. Under 3 sentences unless code. Code/paths/URLs unchanged. ACTIVE EVERY RESPONSE.',-} as const--const CAVEMAN_REMINDERS = {- lite: '[Be concise. No filler.]',- full: '[Terse. Fragments OK. No fluff.]',- ultra: '[Max brevity. Telegraphic.]',-} as const--type CavemanMode = 'off' | keyof typeof CAVEMAN_PROMPTS--interface ChatMessage { role: 'user' | 'assistant' | 'system'; content: string; images?: { data: string; mimeType: string }[] }-interface MobileChat { id: string; mode: 'lu' | 'codex'; caveman: CavemanMode; personaId: string; personaEnabled: boolean }--const CODEX_PROMPT_SNIPPET = 'You are the Coding Agent, a coding-focused assistant'--function buildSystemPrompt(chat: MobileChat, opts: { dispatched?: string; personas: { id: string; prompt: string }[] }): string {- const parts: string[] = []- if (chat.caveman !== 'off' && CAVEMAN_PROMPTS[chat.caveman]) parts.push(CAVEMAN_PROMPTS[chat.caveman])- if (chat.mode === 'codex') {- parts.push(`${CODEX_PROMPT_SNIPPET}. Provide clean, efficient, well-commented code.`)- } else {- const p = opts.personas.find(x => x.id === chat.personaId)- if (chat.personaEnabled && p && p.prompt) parts.push(p.prompt)- else if (opts.dispatched) parts.push(opts.dispatched)- }- return parts.join('\n\n')+import { isThinkingCompatible as desktopIsThinkingCompatible } from '../../lib/model-compatibility'+import { CAVEMAN_PROMPTS, CAVEMAN_REMINDERS } from '../../../mobile-client/caveman.js'+import {+ CODEX_PROMPT,+ PERSONAS,+ THINKING_COMPATIBLE,+ isPlainTextPlanner,+} from '../../../mobile-client/personas.js'+import { clientSource, declarationSource, loadFromClient } from './mobile-client-shell'++const CLIENT = clientSource()++// ─── The two shell functions, run for real ───++interface MobileChat {+ mode: 'lu' | 'codex'+ caveman: 'off' | keyof typeof CAVEMAN_PROMPTS+ personaId: string+ personaEnabled: boolean+ agentEnabled: boolean}-function transformUserMessageWithCaveman(msg: ChatMessage, caveman: CavemanMode, _model: string): ChatMessage {- if (msg.role !== 'user') return msg- if (caveman === 'off') return msg- // Parity with desktop: prepend on EVERY user message regardless of model- // type. Was previously gated on !isThinkingCompatible(model), which made- // thinking-compatible models silently lose Caveman style after turn 1.- return { ...msg, content: CAVEMAN_REMINDERS[caveman] + '\n' + msg.content }-}+const defaults = (mode: 'lu' | 'codex' = 'lu'): MobileChat => ({+ mode,+ caveman: 'off',+ personaId: 'unrestricted',+ personaEnabled: false,+ agentEnabled: false,+})++/** The client's OWN thinking check, not the desktop one. */+const { isThinkingCompatible } = loadFromClient<{+ isThinkingCompatible: (m: string) => boolean+}>(['isThinkingCompatible'], { THINKING_COMPATIBLE })/**- * Der Koerper, den die mobile Seite an Ollamas `/api/chat` schickt.+ * The shipped `buildSystemPrompt`, wired to a chat we control.*- * Deklariert statt `any`: die Zusicherungen unten pruefen, dass `think` NICHT- * gesetzt ist und dass `options.num_gpu` fehlt — auf einem `any` ist- * "nicht gesetzt" von "das Feld heisst inzwischen anders" nicht zu- * unterscheiden.+ * Everything it reads about the world comes in here: the real persona list,+ * the real caveman table, the real Codex prompt, and the client's own+ * `AGENT_PROMPT` line, cut out of the same file. Only the per-chat getters and+ * the two host lines are stubbed, because those are what a test has to vary.*/-type MobileOllamaBody = {- model: string- messages: ChatMessage[]- stream: true- options: { num_gpu?: number }- think?: boolean-}--function buildOllamaBody(model: string, messages: ChatMessage[], opts: { thinking?: boolean } = {}): MobileOllamaBody {- // v2.4.6 Bug L: dropped hardcoded num_gpu:99 (was forcing all layers to GPU- // on every request, killing 8 GB-VRAM laptop chat speed). Ollama- // auto-decides layer placement based on free VRAM now.- const body: MobileOllamaBody = { model, messages, stream: true, options: {} }- if (opts.thinking === true && isThinkingCompatible(model)) body.think = true- return body-}--function mobileChatDefaults(mode: 'lu' | 'codex' = 'lu'): MobileChat {- return { id: 'c-1', mode, caveman: 'off', personaId: 'unrestricted', personaEnabled: false }+function buildPrompt(+ chat: MobileChat,+ extra: { dispatched?: string; hostPlatformLine?: string; clock?: string } = {},+): string {+ const { buildSystemPrompt } = loadFromClient<{ buildSystemPrompt: () => string }>(+ ['AGENT_PROMPT', 'buildSystemPrompt'],+ {+ CAVEMAN_PROMPTS,+ PERSONAS,+ CODEX_PROMPT,+ getCaveman: () => chat.caveman,+ getCurrentMode: () => chat.mode,+ getAgentEnabled: () => chat.agentEnabled,+ getPersonaId: () => chat.personaId,+ getPersonaEnabled: () => chat.personaEnabled,+ dispatchedSystemPrompt: extra.dispatched ?? '',+ hostPlatformLine: extra.hostPlatformLine ?? '',+ hostClockLine: () => extra.clock ?? 'CLOCK',+ },+ )+ return buildSystemPrompt()}// ─── Tests ───-describe('mobile-parity › CAVEMAN_PROMPTS', () => {+describe('mobile-parity › CAVEMAN_PROMPTS (imported from the shipped module)', () => {it('defines exactly three levels', () => {expect(Object.keys(CAVEMAN_PROMPTS)).toEqual(['lite', 'full', 'ultra'])})@@ -101,7 +119,6 @@ describe('mobile-parity › CAVEMAN_PROMPTS', () => {}})it('prompts escalate in brevity (length order)', () => {- // not strictly required, but documents intent — ultra should be shortestexpect(CAVEMAN_PROMPTS.ultra.length).toBeLessThan(CAVEMAN_PROMPTS.full.length)})})@@ -123,10 +140,17 @@ describe('mobile-parity › CAVEMAN_REMINDERS', () => {})})-describe('mobile-parity › isThinkingCompatible (desktop helper reused on mobile)', () => {+describe("mobile-parity › the client's OWN isThinkingCompatible", () => {const thinkingModels = [- 'qwq:latest', 'deepseek-r1:8b', 'qwen3:8b', 'qwen3:14b', 'qwen3.5:9b',- 'qwen3-coder:7b', 'gemma3:12b', 'gemma4:27b', 'gemma4-e4b',+ 'qwq:latest',+ 'deepseek-r1:8b',+ 'qwen3:8b',+ 'qwen3:14b',+ 'qwen3.5:9b',+ 'qwen3-coder:7b',+ 'gemma3:12b',+ 'gemma4:27b',+ 'gemma4-e4b',]for (const m of thinkingModels) {it(`recognises ${m} as thinking-compatible`, () => {@@ -135,8 +159,13 @@ describe('mobile-parity › isThinkingCompatible (desktop helper reused on mobil}const nonThinking = [- 'llama3.1:8b', 'llama3.3:70b', 'mistral-nemo:12b', 'mistral-small:24b',- 'phi-4:14b', 'glm-4:9b', 'qwen2.5:7b',+ 'llama3.1:8b',+ 'llama3.3:70b',+ 'mistral-nemo:12b',+ 'mistral-small:24b',+ 'phi-4:14b',+ 'glm-4:9b',+ 'qwen2.5:7b',]for (const m of nonThinking) {it(`recognises ${m} as NOT thinking-compatible`, () => {@@ -155,206 +184,276 @@ describe('mobile-parity › isThinkingCompatible (desktop helper reused on mobilit('handles uncensored prefix-stripping', () => {expect(isThinkingCompatible('qwen3-uncensored:8b')).toBe(true)})++ it('reads the shipped THINKING_COMPATIBLE list, not a copy of it', () => {+ // The negative control for the whole block: feed the client its own list+ // with one entry removed and the answer has to change. If it did not, the+ // function would be matching against something else and every assertion+ // above would be about that something else.+ const withoutQwq = loadFromClient<{ isThinkingCompatible: (m: string) => boolean }>(+ ['isThinkingCompatible'],+ { THINKING_COMPATIBLE: THINKING_COMPATIBLE.filter((t) => t !== 'qwq') },+ ).isThinkingCompatible+ expect(isThinkingCompatible('qwq:latest')).toBe(true)+ expect(withoutQwq('qwq:latest')).toBe(false)+ })++ it('is NOT the desktop helper — the two disagree, and that is the finding', () => {+ // This file used to import the desktop helper and call the result mobile+ // parity. They are close, but they are two implementations: the desktop+ // one collapses dashes and strips `-heretic`, the mobile one does not.+ const heretic = 'qwen3-heretic:8b'+ expect(desktopIsThinkingCompatible(heretic)).toBe(true)+ expect(isThinkingCompatible(heretic)).toBe(true)+ // The lists themselves are separate objects in separate languages, so the+ // one thing worth asserting is that the mobile list is not empty and the+ // desktop agrees about the families it does name.+ expect(THINKING_COMPATIBLE.length).toBeGreaterThan(10)+ for (const tag of THINKING_COMPATIBLE) {+ expect(desktopIsThinkingCompatible(`${tag}:latest`)).toBe(true)+ }+ })})-describe('mobile-parity › buildSystemPrompt', () => {- const personas = [- { id: 'unrestricted', prompt: '' },- { id: 'coder', prompt: 'You are an expert software engineer.' },- ]+describe('mobile-parity › isPlainTextPlanner (Bug #80 escape hatch)', () => {+ it('names Gemma 3 and 4 and nothing else', () => {+ expect(isPlainTextPlanner('gemma3:12b')).toBe(true)+ expect(isPlainTextPlanner('gemma4:27b')).toBe(true)+ expect(isPlainTextPlanner('qwen3:8b')).toBe(false)+ expect(isPlainTextPlanner('')).toBe(false)+ })+ it('sees through ONE registry segment and the abliterated suffixes', () => {+ expect(isPlainTextPlanner('hf.co/gemma3-abliterated:q4')).toBe(true)+ // And only one: the strip is /^[^/]+\//, so a two-segment path keeps the+ // owner in front of the family name and the model reads as unknown. That+ // is what the shipped client does; it is written down here rather than+ // assumed away.+ expect(isPlainTextPlanner('hf.co/someone/gemma3-abliterated:q4')).toBe(false)+ })+})+describe('mobile-parity › buildSystemPrompt (the shipped function)', () => {it('returns empty string with defaults and no dispatched prompt', () => {- const c = mobileChatDefaults()- expect(buildSystemPrompt(c, { personas })).toBe('')+ expect(buildPrompt(defaults())).toBe('')})it('uses dispatched prompt when persona is disabled', () => {- const c = mobileChatDefaults()- const out = buildSystemPrompt(c, { personas, dispatched: 'DISPATCHED_SEED' })- expect(out).toBe('DISPATCHED_SEED')+ expect(buildPrompt(defaults(), { dispatched: 'DISPATCHED_SEED' })).toBe('DISPATCHED_SEED')})it('uses persona when enabled, dropping dispatched', () => {- const c = { ...mobileChatDefaults(), personaId: 'coder', personaEnabled: true }- const out = buildSystemPrompt(c, { personas, dispatched: 'IGNORED' })- expect(out).toBe('You are an expert software engineer.')+ const coder = PERSONAS.find((p) => p.id === 'coder')!+ const out = buildPrompt(+ { ...defaults(), personaId: 'coder', personaEnabled: true },+ { dispatched: 'IGNORED' },+ )+ expect(out).toBe(coder.prompt)+ expect(out).not.toContain('IGNORED')})it('falls back to dispatched when personaEnabled but persona has empty prompt', () => {- const c = { ...mobileChatDefaults(), personaId: 'unrestricted', personaEnabled: true }- const out = buildSystemPrompt(c, { personas, dispatched: 'DISPATCHED' })+ const out = buildPrompt(+ { ...defaults(), personaId: 'unrestricted', personaEnabled: true },+ { dispatched: 'DISPATCHED' },+ )expect(out).toBe('DISPATCHED')})it('prepends caveman prompt before persona', () => {- const c = { ...mobileChatDefaults(), caveman: 'full' as const, personaId: 'coder', personaEnabled: true }- const out = buildSystemPrompt(c, { personas })+ const coder = PERSONAS.find((p) => p.id === 'coder')!+ const out = buildPrompt({+ ...defaults(),+ caveman: 'full',+ personaId: 'coder',+ personaEnabled: true,+ })expect(out.startsWith(CAVEMAN_PROMPTS.full)).toBe(true)- expect(out).toContain('You are an expert software engineer.')- })-- it('codex mode uses codex prompt and ignores persona', () => {- const c = { ...mobileChatDefaults('codex'), personaId: 'coder', personaEnabled: true }- const out = buildSystemPrompt(c, { personas })- expect(out).toContain(CODEX_PROMPT_SNIPPET)- expect(out).not.toContain('You are an expert software engineer.')+ expect(out).toContain(coder.prompt)+ })++ /**+ * FINDING (01.09.2026): codex mode does NOT ignore an enabled persona.+ *+ * The re-implementation this file used to test said it did:+ *+ * if (chat.mode === 'codex') { parts.push(CODEX_PROMPT) }+ * else { …persona… }+ *+ * The shipped client has no such else. It pushes the persona whenever the+ * switch is on, and then appends the Codex contract after it. So a Codex+ * chat with "Devil's Advocate" enabled sends both. Nine assertions in this+ * file were about the copy's behaviour, not the phone's.+ *+ * Which of the two is right is a product question and not this change's+ * business — T-75 ships the same bytes it found. What changes today is that+ * the test now says what actually happens.+ */+ it('codex mode appends the codex contract AFTER an enabled persona', () => {+ const coder = PERSONAS.find((p) => p.id === 'coder')!+ const out = buildPrompt({ ...defaults('codex'), personaId: 'coder', personaEnabled: true })+ expect(out).toContain('You are the Coding Agent')+ expect(out).toContain(coder.prompt)+ expect(out.indexOf(coder.prompt)).toBeLessThan(out.indexOf('You are the Coding Agent'))+ })++ it('codex mode with the persona switch off is the codex prompt plus the clock', () => {+ // Codex owns tools, so it always gets the environment block; with no+ // platform line supplied that is the clock alone.+ const out = buildPrompt({ ...defaults('codex'), personaId: 'coder' })+ expect(out).toBe(`${CODEX_PROMPT}\n\nCLOCK`)})it('codex mode still honours caveman mode', () => {- const c = { ...mobileChatDefaults('codex'), caveman: 'ultra' as const }- const out = buildSystemPrompt(c, { personas })+ const out = buildPrompt({ ...defaults('codex'), caveman: 'ultra' })expect(out.startsWith(CAVEMAN_PROMPTS.ultra)).toBe(true)})+ it('the autonomy contract comes LAST, after any persona', () => {+ // The Devil's-Advocate hijack: a persona appended after AGENT_PROMPT+ // overrode the tool-use rules and the model went off-topic.+ const coder = PERSONAS.find((p) => p.id === 'coder')!+ const out = buildPrompt({+ ...defaults(),+ agentEnabled: true,+ personaId: 'coder',+ personaEnabled: true,+ })+ expect(out.indexOf(coder.prompt)).toBeLessThan(out.indexOf('autonomous AI agent inside LU'))+ })+it('uses "\\n\\n" as part separator', () => {- const c = { ...mobileChatDefaults(), caveman: 'lite' as const, personaId: 'coder', personaEnabled: true }- const out = buildSystemPrompt(c, { personas })+ const out = buildPrompt({+ ...defaults(),+ caveman: 'lite',+ personaId: 'coder',+ personaEnabled: true,+ })expect(out.includes('\n\n')).toBe(true)})})-describe('mobile-parity › transformUserMessageWithCaveman', () => {- it('returns message unchanged when caveman is off', () => {- const m: ChatMessage = { role: 'user', content: 'hi' }- expect(transformUserMessageWithCaveman(m, 'off', 'llama3.1:8b')).toEqual(m)+describe('mobile-parity › the environment block rides only on tool surfaces', () => {+ it('plain chat gets neither the platform line nor the clock', () => {+ const out = buildPrompt(defaults(), { hostPlatformLine: 'PLATFORM', clock: 'CLOCK' })+ expect(out).not.toContain('PLATFORM')+ expect(out).not.toContain('CLOCK')})- it('prepends reminder when caveman=lite and model is non-thinking', () => {- const m: ChatMessage = { role: 'user', content: 'hello' }- const out = transformUserMessageWithCaveman(m, 'lite', 'llama3.1:8b')- expect(out.content.startsWith('[Be concise. No filler.]')).toBe(true)- expect(out.content.endsWith('hello')).toBe(true)+ it('agent mode gets both, platform first and clock last', () => {+ const out = buildPrompt(+ { ...defaults(), agentEnabled: true },+ { hostPlatformLine: 'PLATFORM', clock: 'CLOCK' },+ )+ expect(out.indexOf('PLATFORM')).toBeGreaterThan(-1)+ expect(out.indexOf('CLOCK')).toBeGreaterThan(out.indexOf('PLATFORM'))+ expect(out.endsWith('CLOCK')).toBe(true)})- it('prepends reminder when caveman=full and model is non-thinking', () => {- const m: ChatMessage = { role: 'user', content: 'x' }- const out = transformUserMessageWithCaveman(m, 'full', 'llama3.1:8b')- expect(out.content.startsWith('[Terse. Fragments OK. No fluff.]')).toBe(true)+ it('codex gets them too', () => {+ const out = buildPrompt(defaults('codex'), { hostPlatformLine: 'PLATFORM', clock: 'CLOCK' })+ expect(out).toContain('PLATFORM')+ expect(out).toContain('CLOCK')})- it('prepends reminder when caveman=ultra and model is non-thinking', () => {- const m: ChatMessage = { role: 'user', content: 'x' }- const out = transformUserMessageWithCaveman(m, 'ultra', 'llama3.1:8b')- expect(out.content.startsWith('[Max brevity. Telegraphic.]')).toBe(true)+ it('an empty platform line is left out rather than guessed at', () => {+ const out = buildPrompt({ ...defaults(), agentEnabled: true }, { clock: 'CLOCK' })+ expect(out).not.toContain('PLATFORM')+ expect(out.endsWith('\n\nCLOCK')).toBe(true)+ // Nothing but the autonomy contract and the clock.+ expect(out.split('\n\n').at(-1)).toBe('CLOCK')})+})- it('also prepends reminder for thinking-compatible models (parity with desktop, fixes turn-2 drift)', () => {- const m: ChatMessage = { role: 'user', content: 'hi' }- const out = transformUserMessageWithCaveman(m, 'full', 'qwen3:8b')- expect(out.content.startsWith('[Terse. Fragments OK. No fluff.]')).toBe(true)- expect(out.content.endsWith('hi')).toBe(true)- })+describe('mobile-parity › the caveman reminder on every user turn', () => {+ // The transform is four lines inside `_doSend` and `runToolLoop`, not a+ // function, so there is nothing to import or cut out. These read the shipped+ // file: they say the line is written, not that it ran.+ const transform = /if\(m\.role==='user' && cm!=='off' && CAVEMAN_REMINDERS\[cm\]\)\{\s*\n\s*content = CAVEMAN_REMINDERS\[cm\] \+ '\\n' \+ content;/g- it('leaves assistant messages alone', () => {- const m: ChatMessage = { role: 'assistant', content: 'hi' }- expect(transformUserMessageWithCaveman(m, 'full', 'llama3.1:8b')).toEqual(m)+ it('both request paths prepend the reminder', () => {+ // Streaming chat and the agent loop each build their own apiMessages, and+ // the bug this guards was one of them being fixed and the other not.+ expect(CLIENT.match(transform)).toHaveLength(2)})- it('leaves system messages alone', () => {- const m: ChatMessage = { role: 'system', content: 'hi' }- expect(transformUserMessageWithCaveman(m, 'full', 'llama3.1:8b')).toEqual(m)+ it('the reminder is NOT gated on the model type', () => {+ // Parity with desktop useChat.ts: it used to fire only for+ // !isThinkingCompatible(model), so thinking-compatible models silently+ // lost Caveman style after turn 1.+ expect(CLIENT).not.toMatch(/!isThinkingCompatible\([^)]*\)\s*&&\s*cm!=='off'/)})})-describe('mobile-parity › buildOllamaBody', () => {- const msgs: ChatMessage[] = [{ role: 'user', content: 'hi' }]-- it('returns basic body without think when thinking=false', () => {- const b = buildOllamaBody('qwen3:8b', msgs, { thinking: false })- expect(b.think).toBeUndefined()- expect(b.stream).toBe(true)- // v2.4.6 Bug L: num_gpu no longer forced.- expect(b.options.num_gpu).toBeUndefined()- })+describe('mobile-parity › the Ollama request body', () => {+ // Same situation: the body literal is inline in `_doSend`.+ const body = declarationSource('_doSend')- it('sets think:true when thinking=true AND compatible', () => {- const b = buildOllamaBody('qwen3:8b', msgs, { thinking: true })- expect(b.think).toBe(true)+ it('_doSend is still where the streaming body is built', () => {+ expect(body).toContain("fetch('/api/chat'")})- it('does NOT set think when thinking=true but model incompatible', () => {- const b = buildOllamaBody('llama3.1:8b', msgs, { thinking: true })- expect(b.think).toBeUndefined()+ it('always streams', () => {+ expect(body).toMatch(/stream:\s*true/)})- it('omits think field entirely by default', () => {- const b = buildOllamaBody('qwen3:8b', msgs)- expect('think' in b).toBe(false)+ it('v2.4.6 Bug L: does NOT force num_gpu — Ollama auto-decides layers', () => {+ // Pre-v2.4.6 we set num_gpu:99 to force all layers to GPU. On 8 GB-VRAM+ // laptop cards that drowned the KV cache into system RAM (4.3× slower than+ // the ollama CLI). Letting Ollama decide restores CLI parity on tight+ // cards and is a no-op on cards with headroom.+ // Comments stripped first: the two lines that RECORD the removal say+ // "num_gpu:99", and matching the bare word would have made this green+ // whether or not the option came back.+ const code = CLIENT.replace(/\/\/[^\n]*/g, '')+ expect(code).not.toMatch(/num_gpu/)+ expect(CLIENT).toMatch(/dropped hardcoded num_gpu:99/)})- it('forwards messages array intact', () => {- const b = buildOllamaBody('qwen3:8b', msgs)- expect(b.messages).toBe(msgs)+ it('the think flag is tri-state, and the third state is Gemma', () => {+ // think:true when the toggle is on, think:false when it is off, and+ // ABSENT for a plain-text planner so Ollama tags its own reasoning and the+ // stripper can clean it.+ expect(body).toMatch(/if\(isThinkingCompatible\(currentModel\)\)\{/)+ expect(body).toMatch(/body\.think = true;/)+ expect(body).toMatch(/else if\(!isPlainTextPlanner\(currentModel\)\)\{\s*\n\s*body\.think = false;/)})- it('always enables streaming', () => {- const b = buildOllamaBody('llama3.1:8b', msgs)- expect(b.stream).toBe(true)- })-- it('v2.4.6 Bug L: does NOT force num_gpu — Ollama auto-decides layers', () => {- // Pre-v2.4.6 we set num_gpu:99 to force all layers to GPU. On 8 GB-VRAM- // laptop cards that drowned the KV cache into system RAM (4.3× slower- // than ollama CLI per nightmare13740 report). Letting Ollama decide- // restores CLI parity on tight cards and is a no-op on cards with- // headroom.- const b = buildOllamaBody('llama3.1:8b', msgs)- expect(b.options.num_gpu).toBeUndefined()+ it('a 400 is retried once without the think field', () => {+ expect(body).toMatch(/'think' in body/)})})-describe('mobile-parity › image attachment shape', () => {- it('strips data-URL prefix leaving raw base64', () => {- const dataUrl = 'data:image/png;base64,AAAABBBB'- const base64 = dataUrl.split(',')[1]- expect(base64).toBe('AAAABBBB')- })+describe('mobile-parity › image attachments', () => {+ const addFiles = declarationSource('addFiles')- it('serialises images array as [base64, base64, ...] to Ollama', () => {- const msg: ChatMessage = {- role: 'user',- content: 'describe',- images: [{ data: 'AAA', mimeType: 'image/png' }, { data: 'BBB', mimeType: 'image/jpeg' }],- }- const ollamaShape = { ...msg, images: msg.images!.map(i => i.data) }- expect(ollamaShape.images).toEqual(['AAA', 'BBB'])+ it('only image mime types are accepted', () => {+ expect(addFiles).toMatch(/\.type\.indexOf\('image\/'\)===0/)})- it('max 5 images enforced by slice', () => {- const many = Array.from({ length: 10 }, (_, i) => ({ data: `${i}`, mimeType: 'image/png' }))- const capped = many.slice(0, 5)- expect(capped.length).toBe(5)+ it('at most five images ride along', () => {+ expect(addFiles).toMatch(/pendingImages\.concat\(items\)\.slice\(0, 5\)/)})- it('file type filter accepts image/* mime types', () => {- expect('image/png'.startsWith('image/')).toBe(true)- expect('image/jpeg'.startsWith('image/')).toBe(true)- expect('image/webp'.startsWith('image/')).toBe(true)+ it('the data-URL prefix is stripped so Ollama gets raw base64', () => {+ expect(addFiles).toMatch(/String\(dataUrl\)\.split\(','\)\[1\]/)})- it('file type filter rejects non-image mime types', () => {- expect('text/plain'.startsWith('image/')).toBe(false)- expect('application/pdf'.startsWith('image/')).toBe(false)+ it('the API message carries images as a flat array of base64 strings', () => {+ expect(CLIENT).toMatch(/apiMsg\.images = m\.images\.map\(function\(im\)\{return im\.data;\}\)/)})})describe('mobile-parity › chat mode semantics', () => {- it('lu mode chat defaults to unrestricted persona disabled', () => {- const c = mobileChatDefaults('lu')- expect(c.mode).toBe('lu')- expect(c.personaId).toBe('unrestricted')- expect(c.personaEnabled).toBe(false)- })+ const createChat = declarationSource('createChat')- it('codex mode chat defaults too', () => {- const c = mobileChatDefaults('codex')- expect(c.mode).toBe('codex')- expect(c.caveman).toBe('off')+ it('a new chat starts with the persona OFF and caveman off', () => {+ expect(createChat).toMatch(/caveman:\s*'off'/)+ expect(createChat).toMatch(/personaId:\s*'unrestricted'/)+ expect(createChat).toMatch(/personaEnabled:\s*false/)})- it('codex mode ignores persona regardless of enabled flag', () => {- const c = { ...mobileChatDefaults('codex'), personaId: 'coder', personaEnabled: true }- const out = buildSystemPrompt(c, { personas: [{ id: 'coder', prompt: 'PERSONA' }] })- expect(out).not.toContain('PERSONA')+ it('a plain lu chat sends no system prompt at all; codex sends its contract', () => {+ expect(buildPrompt(defaults('lu'))).toBe('')+ expect(buildPrompt(defaults('codex'))).toBe(`${CODEX_PROMPT}\n\nCLOCK`)})})diff --git a/src/api/__tests__/tool-description-parity.test.ts b/src/api/__tests__/tool-description-parity.test.tsindex 0155287c..a02c2ef6 100644--- a/src/api/__tests__/tool-description-parity.test.ts+++ b/src/api/__tests__/tool-description-parity.test.ts@@ -1,19 +1,41 @@/*** Phase 3 (v2.4.0) — Tool-description parity test.*- * The mobile web UI (rendered from src-tauri/src/commands/remote.rs::mobile_landing)- * re-declares the AGENT_TOOLS array inline so the ReAct prompt on mobile lists- * exactly the same capabilities. This test pins:+ * The mobile web UI (mobile-client/) re-declares the AGENT_TOOLS array so the+ * ReAct prompt on mobile lists exactly the same capabilities. This test pins:* - tool NAMES on both sides are the same set* - each tool description is Claude-Code-quality (length + contains at least* one of the recommended hint markers PREFER/NEVER/DO NOT/USE FIRST/Zero)* - required-parameter lists line up** If this test fails after a description edit, update BOTH sides together.+ *+ * ── 01.09.2026 (T-75) ──+ *+ * The mobile half used to be recovered with two regexes over+ * src-tauri/src/commands/remote.rs, because the client was a Rust string:+ *+ * rs.match(/var AGENT_TOOLS = \[([\s\S]*?)\];/)+ * /\{name:'([^']+)',\s*description:'((?:\\.|[^'\\])*)',…/g+ *+ * followed by three hand-written unescape rules for \' \" and \\ . A tool+ * whose description used a character that parser did not model simply did not+ * appear in `mobileTools`, and the set comparison below would then have said+ * "missing on mobile" for a tool that was there — or, if the outer match had+ * failed differently, said nothing at all. The client is real source now, so+ * the array is imported. No parser, no unescaping, no shape to drift.*/import { describe, it, expect } from 'vitest'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'+import { AGENT_TOOLS } from '../../../mobile-client/agent-core.js'++/** One entry of the mobile AGENT_TOOLS array. */+interface MobileTool {+ name: string+ description: string+ parameters: { name: string; required: boolean }[]+}type BuiltinTool = {name: string@@ -138,49 +160,10 @@ function extractPropertiesNames(schemaExpr: string): string[] {return names}-// ─── Mobile extraction ───-interface MobileTool {- name: string- description: string- parameters: { name: string; required: boolean }[]-}--function parseMobileTools(): MobileTool[] {- const rs = readFileSync(- resolve(__dirname, '..', '..', '..', 'src-tauri', 'src', 'commands', 'remote.rs'),- 'utf8'- )- // Grab the AGENT_TOOLS JS array contents.- const arrMatch = rs.match(/var AGENT_TOOLS = \[([\s\S]*?)\];/)- if (!arrMatch) throw new Error('Could not locate mobile AGENT_TOOLS array in remote.rs')- const body = arrMatch[1]- // Split into tool object blocks by looking for top-level "{name:" anchors.- const tools: MobileTool[] = []- const toolRe = /\{name:'([^']+)',\s*description:'((?:\\.|[^'\\])*)',\s*\n?\s*parameters:\[([^\]]*)\]\}/g- let m: RegExpExecArray | null- while ((m = toolRe.exec(body)) !== null) {- const name = m[1]- const description = m[2]- .replace(/\\'/g, "'")- .replace(/\\"/g, '"')- .replace(/\\\\/g, '\\')- const params = parseMobileParams(m[3])- tools.push({ name, description, parameters: params })- }- return tools-}--function parseMobileParams(paramsExpr: string): { name: string; required: boolean }[] {- const out: { name: string; required: boolean }[] = []- const paramRe = /\{name:'([^']+)'[^}]*?required:\s*(true|false)[^}]*\}/g- let m: RegExpExecArray | null- while ((m = paramRe.exec(paramsExpr)) !== null) {- out.push({ name: m[1], required: m[2] === 'true' })- }- return out-}+// ─── The mobile side, imported rather than parsed ───-const mobileTools = parseMobileTools()+/** Exactly the array the phone runs. */+const mobileTools = AGENT_TOOLS// ─── Tests ───diff --git a/src/components/models/__tests__/hints-name-real-controls.test.ts b/src/components/models/__tests__/hints-name-real-controls.test.tsindex 5e7962fc..c7dd622d 100644--- a/src/components/models/__tests__/hints-name-real-controls.test.ts+++ b/src/components/models/__tests__/hints-name-real-controls.test.ts@@ -42,6 +42,10 @@ const settingsPage = read('src/components/settings/SettingsPage.tsx')const hardware = read('src/components/settings/HardwareSettings.tsx')const modelSelector = read('src/components/models/ModelSelector.tsx')const remoteRs = read('src-tauri/src/commands/remote.rs')+// 01.09.2026 (T-75): the mobile drawer moved out of the Rust string it used to+// live in. The refusal text is still Rust; the controls it names are in the+// client source now.+const mobileClient = read('mobile-client/client.js')describe('THE FIX: the ComfyUI-is-down hint names the control that exists', () => {it('it sends the user to Settings, AI Backends, Start', () => {@@ -104,9 +108,9 @@ describe('the two the sweep turned up', () => {})it('and the mobile drawer really spells it Menu, Settings, Remote Permissions', () => {- expect(remoteRs).toMatch(/window\._toggleDrawer\(\)" aria-label="Menu"/)- expect(remoteRs).toMatch(/window\._openSettingsSheet\(\)[\s\S]{0,200}svgIcon\('tune'\)\+'<\/span>Settings'/)- expect(remoteRs).toMatch(/settings-section-label">Remote Permissions</)+ expect(mobileClient).toMatch(/window\._toggleDrawer\(\)" aria-label="Menu"/)+ expect(mobileClient).toMatch(/window\._openSettingsSheet\(\)[\s\S]{0,200}svgIcon\('tune'\)\+'<\/span>Settings'/)+ expect(mobileClient).toMatch(/settings-section-label">Remote Permissions</)})it('the LM Studio load error names the label the row shows, not an icon name', () => {diff --git a/src/hooks/__tests__/useCodex-prompt-contract.test.ts b/src/hooks/__tests__/useCodex-prompt-contract.test.tsindex bfa57fef..e0a1c0da 100644--- a/src/hooks/__tests__/useCodex-prompt-contract.test.ts+++ b/src/hooks/__tests__/useCodex-prompt-contract.test.ts@@ -7,13 +7,23 @@* These tests read the actual source file to verify the prompt content hasn't* drifted from the required contract terms.*- * We also verify parity between desktop (useCodex.ts) and mobile (remote.rs)- * CODEX_PROMPT variants.+ * We also verify parity between desktop (useCodex.ts) and mobile+ * (mobile-client/) CODEX_PROMPT variants.+ *+ * ── 01.09.2026 (T-75) ──+ *+ * The mobile half used to read src-tauri/src/commands/remote.rs as one string+ * and ask `toContain('AUTONOMY CONTRACT')` of the whole 7 483-line file. That+ * was green if the phrase sat anywhere: in the client, in a Rust comment, in a+ * Rust test's expectation. The client is real source now, so the prompt and+ * the tool lists are imported and the assertions are about the prompt itself.*/import { describe, it, expect } from 'vitest'import { readFileSync } from 'fs'import { fileURLToPath } from 'url'import { dirname, resolve } from 'path'+import { CODEX_PROMPT } from '../../../mobile-client/personas.js'+import { AGENT_ALL_TOOLS, CODEX_TOOLS } from '../../../mobile-client/agent-core.js'function readSource(relativePath: string): string {const __filename = fileURLToPath(import.meta.url)@@ -58,42 +68,49 @@ describe('Desktop CODEX_SYSTEM_PROMPT (useCodex.ts)', () => {})})-describe('Mobile CODEX_PROMPT (remote.rs) parity', () => {- const mobileRs = readSource('../../../src-tauri/src/commands/remote.rs')-- it('mobile contains AUTONOMY CONTRACT', () => {- expect(mobileRs).toContain('AUTONOMY CONTRACT')+describe('Mobile CODEX_PROMPT (mobile-client/personas.js) parity', () => {+ it('mobile contains the hard rules the contract is made of', () => {+ // The old assertion was `toContain('AUTONOMY CONTRACT')` against the whole+ // Rust file. The mobile prompt does not use that heading — it says+ // "HARD RULES" — and it passed anyway, on the desktop prompt's heading+ // quoted in a neighbouring Rust test.+ expect(CODEX_PROMPT).toContain('=== HARD RULES ===')+ expect(CODEX_PROMPT).toContain('=== WORKFLOW ===')})it('mobile instructs completing all steps', () => {// Round 7: stronger wording — same intent, different verbatim string.- expect(mobileRs).toContain('execute ALL N steps in one session')+ expect(CODEX_PROMPT).toContain('execute ALL N steps in one session')})it('mobile defines the model as the Coding Agent', () => {- expect(mobileRs).toContain('You are the Coding Agent')+ expect(CODEX_PROMPT.startsWith('You are the Coding Agent')).toBe(true)})- it('mobile has CODEX_TOOLS constant', () => {- expect(mobileRs).toContain('CODEX_TOOLS')- // Must include file_read, file_write, shell_execute- expect(mobileRs).toContain("'file_read'")- expect(mobileRs).toContain("'file_write'")- expect(mobileRs).toContain("'shell_execute'")+ it('CODEX_TOOLS carries the three the prompt promises', () => {+ for (const t of ['file_read', 'file_write', 'shell_execute']) {+ expect(CODEX_TOOLS).toContain(t)+ }})- it('mobile has AGENT_ALL_TOOLS constant', () => {- expect(mobileRs).toContain('AGENT_ALL_TOOLS')+ it('AGENT_ALL_TOOLS is a superset of CODEX_TOOLS', () => {+ for (const t of CODEX_TOOLS) expect(AGENT_ALL_TOOLS).toContain(t)+ expect(AGENT_ALL_TOOLS.length).toBeGreaterThan(CODEX_TOOLS.length)})})describe('Desktop ↔ Mobile prompt parity check', () => {const desktop = readSource('../useCodex.ts')- const mobile = readSource('../../../src-tauri/src/commands/remote.rs')-- it('both have AUTONOMY CONTRACT', () => {+ const mobile = CODEX_PROMPT++ it('both open with a named block of hard rules', () => {+ // FINDING (01.09.2026): they do not share a heading. The desktop prompt+ // says "AUTONOMY CONTRACT", the mobile one says "HARD RULES". The old+ // test asserted the desktop heading against the whole Rust file and was+ // green on a copy of the desktop prompt quoted in a Rust test — so+ // "both have AUTONOMY CONTRACT" was never true of the phone.expect(desktop).toContain('AUTONOMY CONTRACT')- expect(mobile).toContain('AUTONOMY CONTRACT')+ expect(mobile).toContain('=== HARD RULES ===')})it('both instruct chaining tool calls', () => {diff --git a/src/lib/__tests__/prompt-tool-roster.test.ts b/src/lib/__tests__/prompt-tool-roster.test.tsindex 09f24083..253440fa 100644--- a/src/lib/__tests__/prompt-tool-roster.test.ts+++ b/src/lib/__tests__/prompt-tool-roster.test.ts@@ -22,6 +22,8 @@ import { resolve } from 'node:path'import { renderToolRoster, renderToolNames } from '../tool-roster'import { ALWAYS_INCLUDE } from '../tool-selection'import type { MCPToolDefinition, ToolCategory } from '../../api/mcp/types'+import { CODEX_PROMPT } from '../../../mobile-client/personas.js'+import { AGENT_ALL_TOOLS } from '../../../mobile-client/agent-core.js'const SRC = resolve(__dirname, '..', '..')const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')@@ -68,13 +70,14 @@ function sliceFunction(src: string, header: string): string {const agentChat = read('hooks', 'useAgentChat.ts')const codex = read('hooks', 'useCodex.ts')const hermes = read('api', 'hermes-tool-calling.ts')-// The mobile relay ships its own copy of the coding prompt inside the served-// page. It drifted the same way and is the surface where a visible plan counts-// for most, so it is held to the same rule.-const relay = readFileSync(- resolve(SRC, '..', 'src-tauri', 'src', 'commands', 'remote.rs'),- 'utf8',-)+// The mobile relay ships its own copy of the coding prompt. It drifted the+// same way and is the surface where a visible plan counts for most, so it is+// held to the same rule.+//+// 01.09.2026 (T-75): until today the prompt was recovered by finding+// `var CODEX_PROMPT = '` in src-tauri/src/commands/remote.rs and slicing to+// the next `';`, and the relay's tool list by a regex over the same file. The+// client is real source now, so both are imported.const PROMPTS: Record<string, string> = {agent: sliceFunction(agentChat, 'function buildAgentSystemPrompt('),@@ -87,24 +90,18 @@ const PROMPTS: Record<string, string> = {// leaving a real mutating one unmentioned.codexReview: sliceTemplate(codex, 'const CODEX_REVIEW_SYSTEM_PROMPT = `'),hermes: sliceFunction(hermes, 'export function buildHermesToolPrompt('),- mobileCodex: (() => {- const header = "var CODEX_PROMPT = '"- const start = relay.indexOf(header)- expect(start, 'mobile CODEX_PROMPT not found').toBeGreaterThan(-1)- const body = relay.slice(start + header.length)- return body.slice(0, body.indexOf("';"))- })(),+ mobileCodex: CODEX_PROMPT,}/**- * The tools the mobile relay actually declares in its own AGENT_TOOLS array.- * Anchored on `description:` because parameters use the same `{name:'…'` shape- * and are followed by `type:`. Matching on the name alone collects both and- * turns the subset check into a tautology.+ * The tools the mobile relay actually declares.+ *+ * This used to be a regex over remote.rs, anchored on `description:` because+ * parameters use the same `{name:'…'` shape — match the name alone and the+ * subset check below becomes a tautology. The array is imported now, so the+ * distinction is made by the language instead of by an anchor.*/-const RELAY_TOOL_NAMES: string[] = [- ...new Set([...relay.matchAll(/\{name:'([a-z0-9_]+)',\s*description:/g)].map((m) => m[1])),-]+const RELAY_TOOL_NAMES: string[] = AGENT_ALL_TOOLS/** snake_case words, which is what every tool name looks like. */function candidateToolWords(text: string): string[] {diff --git a/tsconfig.app.json b/tsconfig.app.jsonindex 714f25ff..add2c038 100644--- a/tsconfig.app.json+++ b/tsconfig.app.json@@ -8,6 +8,21 @@"types": ["vite/client", "vitest/globals"],"skipLibCheck": true,+ /* mobile-client/ is the phone's client: real .js files that src-tauri's+ build script glues into one page. `allowJs` is what puts them into the+ program at all — without it the tests below could not import them and+ the whole extraction would be cosmetic. `checkJs` stays off: the client+ is ES5-style browser code and turning it on would demand JSDoc types+ inside files whose bytes are the shipped page (measured 01.09.2026:+ 61 errors, all of them DOM narrowing).++ What tsc DOES enforce, and it is checked by a probe: an export the+ TypeScript tests import has to exist. Take PERSONAS off personas.js's+ list and tsc says TS2459 in two test files. The names only client.js+ imports are outside that — a .js importer with checkJs off is not+ checked — and eslint's `no-undef` covers those instead. */+ "allowJs": true,+/* Bundler mode */"moduleResolution": "bundler","allowImportingTsExtensions": true,@@ -24,5 +39,5 @@"noFallthroughCasesInSwitch": true,"noUncheckedSideEffectImports": true},- "include": ["src"]+ "include": ["src", "mobile-client"]}