Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Keep composer attachments, model choices and home interactions stable

wyt31cc2ef2afd9
diff --git a/scripts/build-home-scenes.cjs b/scripts/build-home-scenes.cjs
new file mode 100644
index 00000000..c5cc8922
--- /dev/null
+++ b/scripts/build-home-scenes.cjs
@@ -0,0 +1,224 @@
+#!/usr/bin/env node
+/* Derive the homepage use-case scenes' desktop UI layer from the renderer.
+ *
+ * Web/home.html renders use-case scenes with the same class names as the
+ * Orkas desktop UI inside `.oks-ui` containers. This script copies the
+ * renderer tokens and every style rule whose classes are all used by that
+ * markup, scoped under `.oks-ui`, and copies the desktop UI labels the scenes
+ * show into each homepage locale catalog as `pcui.*`. It then copies each scene
+ * into its use-case landing page with a derived scene catalog. Rerun it after a
+ * desktop UI or scene change; `--check` fails when committed outputs are stale.
+ * Run: node PC/scripts/build-home-scenes.cjs [--check]
+ */
+const fs = require('node:fs');
+const path = require('node:path');
+
+const root = path.resolve(__dirname, '../..');
+const SOURCE = 'PC/src/renderer/style.css';
+const MARKUP = 'Web/home.html';
+const OUTPUT = 'Web/home-scene-ui.css';
+const UI_LOCALES = 'PC/src/renderer/locales';
+const HOME_LOCALES = 'Web/seo/locales/home';
+// Desktop labels shown verbatim in the scenes.
+const UI_KEYS = ['auto.title', 'auto.status_enabled', 'auto.device_current',
+ 'project.todo.title', 'project.todo.status_todo', 'project.todo.status_progress', 'project.todo.status_review',
+ 'apps.title', 'apps.publish_published', 'apps.view_details',
+ 'apps.publish_address', 'apps.publish_visit', 'apps.publish_published_at', 'apps.publish_updated_at', 'apps.publish_trend', 'apps.publish_update', 'apps.publish_unpublish', 'common.copy',
+ 'project.tab_tasks', 'project.tab_auto', 'project.resources.title', 'project.resources.agents_tab', 'project.resources.files_tab', 'sidebar.bucket.last7'];
+// Example figures rendered through desktop templates that take values.
+const TEMPLATES = { 'apps.publish_pv': { total: '1,286', today: '42' } };
+// Example last-run times per scenario, formatted through the desktop template.
+const LAST_RUNS = { marketing: '10-19 09:00', ops: '10-19 08:30', ops2: '10-19 10:00', client: '10-17 16:00', client2: '10-20 08:00', launch: '10-16 17:00' };
+const SCOPE = '.oks-ui';
+
+function stripComments(css) {
+ return css.replace(/\/\*[\s\S]*?\*\//g, '');
+}
+
+// Split top-level blocks: [{prelude, body}] where body is the text inside braces.
+function blocks(css) {
+ const out = [];
+ let i = 0;
+ while (i < css.length) {
+ const open = css.indexOf('{', i);
+ if (open < 0) break;
+ const prelude = css.slice(i, open).trim();
+ let depth = 1, j = open + 1;
+ while (j < css.length && depth) {
+ if (css[j] === '{') depth++;
+ else if (css[j] === '}') depth--;
+ j++;
+ }
+ out.push({ prelude: prelude.replace(/^[^{}]*;/, '').trim(), body: css.slice(open + 1, j - 1) });
+ i = j;
+ }
+ return out;
+}
+
+function splitSelectors(prelude) {
+ const parts = [];
+ let depth = 0, start = 0;
+ for (let i = 0; i < prelude.length; i++) {
+ const c = prelude[i];
+ if (c === '(' || c === '[') depth++;
+ else if (c === ')' || c === ']') depth--;
+ else if (c === ',' && !depth) { parts.push(prelude.slice(start, i).trim()); start = i + 1; }
+ }
+ parts.push(prelude.slice(start).trim());
+ return parts.filter(Boolean);
+}
+
+function usedClasses(html) {
+ const used = new Set();
+ const re = /<[^>]+class="([^"]*\boks-ui\b[^"]*)"[^>]*>/g;
+ let match;
+ while ((match = re.exec(html))) {
+ // Collect from the opening `.oks-ui` tag to the end of its figure.
+ const end = html.indexOf('</figure>', match.index);
+ if (end < 0) throw Error('`.oks-ui` markup must live inside a <figure>');
+ for (const attr of html.slice(match.index, end).matchAll(/class="([^"]*)"/g)) {
+ for (const name of attr[1].split(/\s+/)) if (name) used.add(name);
+ }
+ }
+ if (!used.size) throw Error('No `.oks-ui` markup found in ' + MARKUP);
+ return used;
+}
+
+function scopeSelector(selector, used) {
+ if (/^(html|body|:root)\b/.test(selector) || selector.includes('#')) return null;
+ const classes = [...selector.matchAll(/\.(-?[A-Za-z_][\w-]*)/g)].map(m => m[1]);
+ if (!classes.length || !classes.every(name => used.has(name))) return null;
+ return `${SCOPE} ${selector}`;
+}
+
+function rules(css, used, keyframes) {
+ const out = [];
+ for (const { prelude, body } of blocks(css)) {
+ if (/^@(media|supports)\b/.test(prelude)) {
+ const inner = rules(body, used, keyframes);
+ if (inner.length) out.push(`${prelude} {\n${inner.map(rule => ' ' + rule).join('\n')}\n}`);
+ continue;
+ }
+ if (prelude.startsWith('@')) continue;
+ const selectors = splitSelectors(prelude).map(s => scopeSelector(s, used)).filter(Boolean);
+ if (!selectors.length) continue;
+ const declarations = body.trim().replace(/\s+/g, ' ');
+ for (const match of declarations.matchAll(/animation(?:-name)?\s*:\s*([\w-]+)/g)) keyframes.add(match[1]);
+ out.push(`${selectors.join(', ')} { ${declarations} }`);
+ }
+ return out;
+}
+
+function buildCss(source, markup) {
+ const css = stripComments(source);
+ const used = usedClasses(markup);
+ const top = blocks(css);
+ const tokens = top.filter(b => b.prelude === ':root').map(b => b.body.trim().replace(/\s+/g, ' ')).join(' ');
+ const base = top.filter(b => b.prelude === 'body').map(b => b.body).join(';')
+ .split(';').map(d => d.trim()).filter(d => /^(font-family|color)\s*:/.test(d)).join('; ');
+ const keyframes = new Set();
+ const body = rules(css, used, keyframes);
+ const frames = top.filter(b => keyframes.has((b.prelude.match(/^@keyframes\s+([\w-]+)/) || [])[1]))
+ .map(b => `${b.prelude} { ${b.body.trim().replace(/\s+/g, ' ')} }`);
+ return [
+ `/* Generated by PC/scripts/build-home-scenes.cjs from ${SOURCE}. Do not edit. */`,
+ `${SCOPE} { ${tokens} ${base}; }`,
+ ...body,
+ ...frames,
+ '',
+ ].join('\n');
+}
+
+function catalogs() {
+ const out = {};
+ for (const file of fs.readdirSync(path.join(root, HOME_LOCALES)).filter(f => f.endsWith('.json')).sort()) {
+ const homeFile = path.join(root, HOME_LOCALES, file);
+ const ui = JSON.parse(fs.readFileSync(path.join(root, UI_LOCALES, file), 'utf8'));
+ const home = JSON.parse(fs.readFileSync(homeFile, 'utf8'));
+ for (const key of Object.keys(home)) if (key.startsWith('pcui.')) delete home[key];
+ for (const key of UI_KEYS) {
+ if (typeof ui[key] !== 'string') throw Error(`Missing desktop label ${key} in ${file}`);
+ home['pcui.' + key] = ui[key];
+ }
+ for (const [key, values] of Object.entries(TEMPLATES)) {
+ if (typeof ui[key] !== 'string') throw Error(`Missing desktop label ${key} in ${file}`);
+ home['pcui.' + key] = ui[key].replace(/\{(\w+)\}/g, (_, name) => values[name]);
+ }
+ for (const [scenario, when] of Object.entries(LAST_RUNS)) {
+ home[`pcui.auto.last_run.${scenario}`] = ui['auto.last_run'].replace('{when}', when);
+ }
+ out[homeFile] = JSON.stringify(home, null, 2) + '\n';
+ }
+ return out;
+}
+
+// Each homepage scene is also the example on its use-case landing page.
+const LANDING_PAGES = { marketing: 'content-writing', ops: 'ecommerce', client: 'client-projects', launch: 'product-launch', apps: 'build-apps' };
+const SCENE_LOCALES = 'Web/seo/locales/scenes';
+
+function sceneFigure(html, scenario, source) {
+ const pattern = new RegExp(`<figure class="business-shot[^"]*"[^>]*data-i18n-aria-label="business\\.${scenario}\\.visual"[^>]*>[\\s\\S]*?</figure>`);
+ const match = html.match(pattern);
+ if (!match) throw Error(`Missing ${scenario} scene in ${source}`);
+ return { pattern, figure: match[0] };
+}
+
+function landingPages(markup) {
+ const out = {};
+ for (const [scenario, slug] of Object.entries(LANDING_PAGES)) {
+ const file = path.join(root, 'Web/use', slug, 'index.html');
+ const page = fs.readFileSync(file, 'utf8');
+ // Landing pages live two levels below the homepage.
+ const figure = sceneFigure(markup, scenario, MARKUP).figure.replace(/(src|href)="\.\/res\//g, '$1="../../res/');
+ out[file] = page.replace(sceneFigure(page, scenario, file).pattern, () => figure);
+ }
+ return out;
+}
+
+// Landing pages keep their own catalogs; scene copy comes from a derived
+// catalog so homepage-only keys never override page metadata.
+function sceneCatalogs(markup, homeCatalogs) {
+ const keys = new Set();
+ for (const scenario of Object.keys(LANDING_PAGES)) {
+ for (const match of sceneFigure(markup, scenario, MARKUP).figure.matchAll(/data-i18n(?:-aria-label)?="([^"]+)"/g)) keys.add(match[1]);
+ }
+ const out = {};
+ for (const [homeFile, text] of Object.entries(homeCatalogs)) {
+ const home = JSON.parse(text), scene = {};
+ for (const key of [...keys].sort()) {
+ if (typeof home[key] !== 'string') throw Error(`Missing scene key ${key} in ${path.basename(homeFile)}`);
+ scene[key] = home[key];
+ }
+ out[path.join(root, SCENE_LOCALES, path.basename(homeFile))] = JSON.stringify(scene, null, 2) + '\n';
+ }
+ return out;
+}
+
+function outputs() {
+ const markup = fs.readFileSync(path.join(root, MARKUP), 'utf8');
+ const css = buildCss(fs.readFileSync(path.join(root, SOURCE), 'utf8'), markup);
+ const home = catalogs();
+ return { [path.join(root, OUTPUT)]: css, ...home, ...landingPages(markup), ...sceneCatalogs(markup, home) };
+}
+
+function main() {
+ const files = outputs();
+ if (process.argv.includes('--check')) {
+ const stale = Object.entries(files)
+ .filter(([file, text]) => !fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== text)
+ .map(([file]) => path.relative(root, file));
+ if (stale.length) {
+ console.error(`Stale homepage scene outputs: ${stale.join(', ')}. Run: node PC/scripts/build-home-scenes.cjs`);
+ process.exitCode = 1;
+ }
+ return;
+ }
+ for (const [file, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, text);
+ }
+ process.stdout.write(`Wrote ${Object.keys(files).length} homepage scene outputs\n`);
+}
+
+if (require.main === module) main();
+module.exports = { buildCss, outputs, UI_KEYS, LAST_RUNS, TEMPLATES, LANDING_PAGES };
diff --git a/src/renderer/modules/chat-input-form.js b/src/renderer/modules/chat-input-form.js
index df169e56..39aa44ca 100644
--- a/src/renderer/modules/chat-input-form.js
+++ b/src/renderer/modules/chat-input-form.js
@@ -16,6 +16,7 @@
// Cleared on successful submit, on reset, and whenever the form re-renders
// as already-submitted (server-side values are authoritative then).
const _formDrafts = new Map();
+ const _attachmentOrder = Symbol('attachmentOrder');
function _draftKey(cid, formId) {
return `${cid || ''}::${formId || ''}`;
}
@@ -319,10 +320,14 @@
? opts.presetValue.filter((x) => typeof x === 'string' && x)
: (typeof opts.presetValue === 'string' && opts.presetValue ? [opts.presetValue] : []);
for (const name of names) {
- entries.push({
+ const savedIndex = ctx.attachmentOrder.indexOf(name);
+ const ent = {
tempId: 'fp-preset-' + Math.random().toString(36).slice(2, 8),
name, localName: name, status: 'ready',
- });
+ selectionBatch: savedIndex >= 0 ? savedIndex : ctx.nextSelection++, selectionIndex: 0,
+ };
+ entries.push(ent);
+ ctx.attachmentEntries.push(ent);
}
}
@@ -354,6 +359,8 @@
x.addEventListener('click', () => {
const i = entries.indexOf(ent);
if (i >= 0) entries.splice(i, 1);
+ const selectedIndex = ctx.attachmentEntries.indexOf(ent);
+ if (selectedIndex >= 0) ctx.attachmentEntries.splice(selectedIndex, 1);
_renderChips();
if (ctx && typeof ctx.onChange === 'function') ctx.onChange();
});
@@ -433,6 +440,7 @@
picker.addEventListener('click', async () => {
if (disabled) return;
+ const selectionBatch = ctx.nextSelection++;
let picked = [];
try {
const res = await window.orkas.invoke('common.pickFiles', {
@@ -446,14 +454,19 @@
}
if (!picked.length) return;
// single-file mode: replace any prior selection
- if (!multiple) entries.length = 0;
+ if (!multiple) {
+ ctx.attachmentEntries = ctx.attachmentEntries.filter((entry) => !entries.includes(entry));
+ entries.length = 0;
+ }
for (const file of picked) {
const ent = {
+ selectionBatch, selectionIndex: picked.indexOf(file),
tempId: 'fp-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8),
localName: file.name,
status: 'uploading',
};
entries.push(ent);
+ ctx.attachmentEntries.push(ent);
_uploadFile(ent, file);
}
_renderChips();
@@ -592,6 +605,12 @@
const fields = [];
const fieldCtx = {
cid: opts.cid,
+ attachmentEntries: [],
+ attachmentOrder: draftValues?.[_attachmentOrder] || [],
+ nextSelection: (draftValues?.[_attachmentOrder] || []).length,
+ attachmentNames: () => fieldCtx.attachmentEntries.filter((entry) => entry.status === 'ready')
+ .slice().sort((a, b) => a.selectionBatch - b.selectionBatch || a.selectionIndex - b.selectionIndex)
+ .map((entry) => entry.name),
onChange: () => {
_refreshSubmitState();
if (submitted) return;
@@ -599,6 +618,7 @@
for (const f of fields) {
try { snap[f.field.id] = f.read(); } catch (_) { /* skip */ }
}
+ snap[_attachmentOrder] = fieldCtx.attachmentNames();
_formDrafts.set(draftKey, snap);
},
};
@@ -713,7 +733,8 @@
const encoded = encodeChatFormSubmission(form, values);
// De-dupe attachment names (a file dropped into both the form and the
// composer would otherwise appear twice on the user message).
- const dedupAttachments = Array.from(new Set(attachmentNames));
+ const selected = new Set(attachmentNames);
+ const dedupAttachments = Array.from(new Set(fieldCtx.attachmentNames().filter((name) => selected.has(name))));
try {
if (opts.onSubmit) await opts.onSubmit(encoded, values, dedupAttachments);
// Submission left our hands; once the bubble re-renders as
diff --git a/src/renderer/modules/context-menu.js b/src/renderer/modules/context-menu.js
index a1366f98..b80ca7fd 100644
--- a/src/renderer/modules/context-menu.js
+++ b/src/renderer/modules/context-menu.js
@@ -1,6 +1,6 @@
// ─── Generic right-click context menu ───
// Small floating menu anchored at the cursor; items are { label, onClick,
-// disabled?, icon? }. There's exactly one menu instance at a time — opening a new
+// disabled?, danger?, icon? }. There's exactly one menu instance at a time — opening a new
// menu closes the previous one. A row may provide a leading `icon`, a
// structured Agent `avatar`, and/or a `trailingIcon` for selection state.
// Dismissers: outside click, Escape, scroll,
@@ -43,7 +43,7 @@ function showContextMenu(event, items) {
_ctxMenuItems.forEach((it, idx) => {
const btn = document.createElement('button');
btn.type = 'button';
- btn.className = `context-menu-item${it.disabled ? ' is-disabled' : ''}`;
+ btn.className = `context-menu-item${it.danger ? ' is-danger' : ''}${it.disabled ? ' is-disabled' : ''}`;
btn.dataset.contextMenuIdx = String(idx);
btn.setAttribute('role', 'menuitem');
btn.setAttribute('tabindex', '-1');
diff --git a/src/renderer/modules/home.js b/src/renderer/modules/home.js
index c6a41288..289d386b 100644
--- a/src/renderer/modules/home.js
+++ b/src/renderer/modules/home.js
@@ -265,11 +265,29 @@ function _homeTodoRowHtml(task, index) {
source: pid
? t('new_chat.home.source.project_todo', { project: task.project_name || _homeProjectName(pid) })
: t('new_chat.home.source.global_todo'),
- details: [_homeTodoStatusLabel(status), updated ? t('new_chat.home.time.updated', { time: updated }) : ''],
+ details: [_homeTodoStatusLabel(status), _homeTodoDueLabel(task), updated ? t('new_chat.home.time.updated', { time: updated }) : ''],
action: t('new_chat.home.action.view'),
});
}
+/** "Due Oct 25" or "Overdue since Oct 25" for a dated to-do; empty otherwise. */
+function _homeTodoDueLabel(task) {
+ const dueAt = typeof task.due_at === 'string' ? task.due_at : '';
+ const parts = /^\d{4}-\d{2}-\d{2}$/.test(dueAt) ? dueAt.split('-').map(Number) : null;
+ if (!parts) return '';
+ const now = new Date();
+ const pad = (value) => String(value).padStart(2, '0');
+ const today = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
+ const date = new Date(parts[0], parts[1] - 1, parts[2]);
+ let label = dueAt;
+ try {
+ label = new Intl.DateTimeFormat(_homeLocale(), {
+ month: 'short', day: 'numeric', ...(parts[0] === now.getFullYear() ? {} : { year: 'numeric' }),
+ }).format(date);
+ } catch (_) { /* keep the stored text */ }
+ return t(task.status !== 'done' && dueAt < today ? 'project.todo.due_overdue' : 'project.todo.due_on', { date: label });
+}
+
function _homeRunRowHtml(run, section, index) {
// Legacy unread records default to completed for presentation only.
const displayStatus = ['completed', 'failed', 'waiting_input', 'stopped'].includes(run.status)
diff --git a/test/e2e/chat_e2e_attachment_failures.spec.ts b/test/e2e/chat_e2e_attachment_failures.spec.ts
new file mode 100644
index 00000000..e96f1b97
--- /dev/null
+++ b/test/e2e/chat_e2e_attachment_failures.spec.ts
@@ -0,0 +1,57 @@
+import { readFileSync } from 'node:fs';
+import { expect, test } from './fixtures/orkas';
+
+
+test('reports a native picker failure, keeps cancellation neutral, and lets the user retry', async ({ orkas }, info) => {
+ const page = orkas.page!;
+ await page.locator('#new-chat-btn').click();
+
+ for (const [locale, width, height] of [['en', 1440, 900], ['zh', 800, 600]] as const) {
+ await page.setViewportSize({ width, height });
+ await page.evaluate(lang => (window as any).setLang(lang), locale);
+ await orkas.cancelNextFileDialog();
+ await orkas.electronApp!.evaluate(({ dialog }) => {
+ const cancel = dialog.showOpenDialog;
+ (globalThis as any).__attachmentPickerSettled = false;
+ (dialog as any).showOpenDialog = async (...args: any[]) => {
+ try { return await (cancel as any)(...args); }
+ finally { (globalThis as any).__attachmentPickerSettled = true; }
+ };
+ });
+ await page.locator('#new-chat-attach-btn').click();
+ await expect.poll(() => orkas.electronApp!.evaluate(() => (globalThis as any).__attachmentPickerSettled)).toBe(true);
+ await expect(page.locator('#new-chat-attachments .chat-attach-chip')).toHaveCount(0);
+ await expect(page.locator('.ui-dialog-overlay.open')).toHaveCount(0);
+
+ // Fault only the OS picker boundary; the actual IPC failure envelope,
+ // renderer result, localized shared dialog and recovery remain real.
+ await orkas.electronApp!.evaluate(({ dialog }) => {
+ const original = dialog.showOpenDialog;
+ (dialog as any).showOpenDialog = async () => {
+ dialog.showOpenDialog = original;
+ throw new Error('fixture_picker_unavailable');
+ };
+ });
+ await page.locator('#new-chat-attach-btn').click();
+ const alert = page.locator('.ui-dialog-overlay.open');
+ await expect(alert.locator('[role="alertdialog"]')).toBeVisible();
+ await expect(alert.locator('.ui-dialog-message')).toHaveText(locale === 'en' ? 'Upload failed' : '上传失败');
+ await expect(alert.locator('[data-act="ok"]')).toBeFocused();
+ await page.screenshot({ path: info.outputPath(`picker-failure-${locale}.png`) });
+ await page.keyboard.press('Escape');
+ await expect(alert).toHaveCount(0);
+ await expect(page.locator('#new-chat-attach-btn')).toBeFocused();
+
+ const body = `Intact retry bytes ${locale}`;
+ const file = orkas.createFixtureFile(`retry-${locale}.txt`, body);
+ await orkas.selectFilesOnNextDialog([file]);
+ await page.locator('#new-chat-attach-btn').click();
+ await expect(page.locator('#new-chat-attachments .chat-attach-label')).toContainText([`retry-${locale}.txt`]);
+ const pending = await orkas.invoke<any>('conversations.attachments.list', { cid: 'main_chat' });
+ const stored = pending.items.find((item: any) => item.name === `retry-${locale}.txt`);
+ expect(stored?.bytes).toBe(Buffer.byteLength(body));
+ expect(readFileSync(file, 'utf8')).toBe(body);
+ await page.locator('#new-chat-attachments .chat-attach-remove').click();
+ await expect(page.locator('#new-chat-attachments .chat-attach-chip')).toHaveCount(0);
+ }
+});
diff --git a/test/e2e/chat_e2e_attachment_order.spec.ts b/test/e2e/chat_e2e_attachment_order.spec.ts
new file mode 100644
index 00000000..84352f13
--- /dev/null
+++ b/test/e2e/chat_e2e_attachment_order.spec.ts
@@ -0,0 +1,53 @@
+import { Jimp } from 'jimp';
+import { expect, test } from './fixtures/orkas';
+
+
+test('keeps image selection, bubble, persisted history and model pixels in order for new and existing chats', async ({ modelOrkas }, info) => {
+ let page = modelOrkas.page!;
+ await page.evaluate(() => (window as any).setLang('en'));
+ await page.locator('#new-chat-btn').click();
+ const colors = [0xDC2020FF, 0x20B040FF, 0x2040DCFF];
+ for (const [turn, prefix] of ['new-chat', 'chat'].entries()) {
+ const names = [`z-first-${turn}.png`, `a-second-${turn}.png`, `m-third-${turn}.png`];
+ const paths = [];
+ for (let index = 0; index < names.length; index += 1) {
+ paths.push(modelOrkas.createFixtureFile(names[index], await new Jimp({ width: 32, height: 32, color: colors[index] }).getBuffer('image/png')));
+ }
+ await modelOrkas.selectFilesOnNextDialog(paths);
+ await page.locator(`#${prefix}-attach-btn`).click();
+ await expect(page.locator(`#${prefix}-attachments .chat-attach-label`)).toHaveText(names);
+ await page.locator(`#${prefix}-input`).fill('Compare the three images in the order I added them.');
+ await page.locator(`#${prefix}-send-btn`).click();
+ const bubbles = page.locator('#chat-history .chat-message.user');
+ await expect(bubbles).toHaveCount(turn + 1);
+ await expect(bubbles.nth(turn).locator('.chat-msg-attach .chat-attach-label')).toHaveText(names);
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toHaveCount(turn + 1);
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ await expect.poll(() => modelOrkas.modelRequests.length).toBe(turn + 1);
+ const request = modelOrkas.modelRequests[turn] as any;
+ // The fixture also projects Responses requests into text-only messages for
+ // legacy tests. Inspect the original wire input to verify image bytes.
+ const user = [...(request.input || request.messages)].reverse().find((message: any) => message.role === 'user');
+ const parts = Array.isArray(user.content) ? user.content : [{ type: 'text', text: user.content }];
+ const text = parts.filter((part: any) => ['text', 'input_text'].includes(part.type)).map((part: any) => part.text).join('\n');
+ const files = [...text.matchAll(/<file name="([^"]+)"[^>]*image_order="(\d+)"/g)];
+ expect(files.map((match) => [match[1], Number(match[2])])).toEqual(names.map((name, index) => [name, index + 1]));
+ const images = parts.filter((part: any) => ['image_url', 'input_image'].includes(part.type));
+ expect(images).toHaveLength(3);
+ for (let index = 0; index < images.length; index += 1) {
+ const url = typeof images[index].image_url === 'string' ? images[index].image_url : images[index].image_url.url;
+ const decoded = await Jimp.read(Buffer.from(url.split(',')[1], 'base64'));
+ const pixel = decoded.getPixelColor(0, 0);
+ for (const shift of [24, 16, 8]) expect(Math.abs(((pixel >>> shift) & 255) - ((colors[index] >>> shift) & 255))).toBeLessThan(15);
+ }
+ await bubbles.nth(turn).screenshot({ path: info.outputPath(`${prefix}-attachment-order.png`) });
+ }
+ const cid = await page.locator('#conversation-list .conv-item.active').getAttribute('data-cid');
+ expect(cid).toBeTruthy();
+ page = await modelOrkas.relaunch();
+ await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ for (const turn of [0, 1]) {
+ await expect(page.locator('#chat-history .chat-message.user').nth(turn).locator('.chat-msg-attach .chat-attach-label'))
+ .toHaveText([`z-first-${turn}.png`, `a-second-${turn}.png`, `m-third-${turn}.png`]);
+ }
+});
diff --git a/test/e2e/chat_e2e_cli_recovery.spec.ts b/test/e2e/chat_e2e_cli_recovery.spec.ts
index 0262bc16..9b9ff07f 100644
--- a/test/e2e/chat_e2e_cli_recovery.spec.ts
+++ b/test/e2e/chat_e2e_cli_recovery.spec.ts
@@ -468,6 +468,66 @@ test.describe('CLI failed-turn recovery', () => {
// bounded wait below.
test.describe.configure({ timeout: 120_000 });
+ for (const fault of ['version_unknown', 'initialize_exit'] as const) {
+ test(`Hermes ${fault} remains visible after reopening and recovers once after repair`, async ({ cliOrkas }, testInfo) => {
+ const name = 'HermesStartupRecoveryE2E';
+ const { page, agentId } = await createCliAgent(cliOrkas, name, 'hermes');
+ const agentsBefore = await cliOrkas.invoke<{ agents: Array<{ agent_id: string }> }>('agents.list');
+ // Finish any startup version probe before changing its executable's
+ // response: force-detect intentionally joins an already running probe.
+ expect((await cliOrkas.invoke<any>('localAgents.detect', { type: 'hermes' })).entry.available).toBe(true);
+ writeFileSync(cliOrkas.cliStatePath, JSON.stringify({ ...cliOrkas.readCliState(), hermesFault: fault }));
+ const detected = await cliOrkas.invoke<any>('localAgents.detect', { type: 'hermes' });
+ expect(detected.entry).toMatchObject(fault === 'version_unknown'
+ ? { available: false, error: 'version_unknown' }
+ : { available: true, version: '99.0.0' });
+ const cid = await sendNewChat(page, `@${name} Only reply OK. Do not call tools.`);
+ const failureText = fault === 'version_unknown'
+ ? 'could not be identified' : 'stopped before completing the task';
+ const failedBubble = page.locator('#chat-history .chat-message.assistant');
+ await expect(failedBubble).toContainText(failureText, { timeout: 30_000 });
+ await expect(failedBubble.locator('.bubble-retry-btn')).toBeVisible();
+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ const before = cliOrkas.readCliState();
+ expect(before.hermesInitializations || 0).toBe(fault === 'initialize_exit' ? 1 : 0);
+ expect(before.nextSession).toBe(0);
+ expect(before.invocations).toHaveLength(0);
+ const saved = await cliOrkas.invoke<any>('conversations.history', { cid });
+ const failures = saved.history.filter((row: any) => row.from === agentId);
+ expect(failures).toHaveLength(1);
+ expect(failures[0]).toMatchObject({
+ failure_kind: fault === 'version_unknown' ? 'dependency' : 'runtime',
+ failure_code: fault === 'version_unknown' ? 'version_unknown' : 'cli_failed',
+ });
+ expect(failures[0].text).toContain(failureText);
+
+ const reopened = await cliOrkas.relaunch();
+ await reopened.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ await expect(reopened.locator('#chat-history .chat-message.assistant')).toContainText(failureText);
+ expect(cliOrkas.readCliState().hermesInitializations || 0).toBe(before.hermesInitializations || 0);
+ await reopened.screenshot({ path: testInfo.outputPath(`hermes-${fault}-reopened.png`) });
+ writeFileSync(cliOrkas.cliStatePath, JSON.stringify({ ...cliOrkas.readCliState(), hermesFault: undefined }));
+ const repaired = await cliOrkas.invoke<any>('localAgents.detect', { type: 'hermes' });
+ expect(repaired.entry).toMatchObject({ available: true, version: '99.0.0' });
+ const retry = reopened.locator('#chat-history .bubble-retry-btn').last();
+ await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();
+ await retry.click();
+ await expect(reopened.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ hasText: 'E2E_HERMES_FIRST_OK',
+ })).toHaveCount(1, { timeout: 30_000 });
+ await expect(reopened.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ const after = cliOrkas.readCliState();
+ expect(after.hermesInitializations).toBe((before.hermesInitializations || 0) + 1);
+ expect(after.nextSession).toBe(1);
+ expect(after.invocations).toHaveLength(1);
+ expect(after.toolExecutions).toBe(0);
+ const history = await cliOrkas.invoke<any>('conversations.history', { cid });
+ expect(history.history.filter((row: any) => row.from === agentId && row.text === 'E2E_HERMES_FIRST_OK')).toHaveLength(1);
+ const agentsAfter = await cliOrkas.invoke<{ agents: Array<{ agent_id: string }> }>('agents.list');
+ expect(agentsAfter.agents.map(agent => agent.agent_id).sort()).toEqual(agentsBefore.agents.map(agent => agent.agent_id).sort());
+ });
+ }
+
test('persists tool-state provenance across app relaunch and resumes the same native session', async ({ cliOrkas }) => {
const { page } = await createCliAgent(cliOrkas, 'OpenCodeResumeE2E', 'opencode');
const conversationId = await sendNewChat(page, '@OpenCodeResumeE2E E2E_CLI_RESUME_AFTER_RELAUNCH');
@@ -765,6 +825,53 @@ test.describe('CLI failed-turn recovery', () => {
});
test.describe('native question history', () => {
+
+ test('stops a running CLI from the composer, withdraws its question and remains usable after reload', async ({ cliOrkas }, testInfo) => {
+ const name = 'CodexStopRecovery';
+ const { page, agentId } = await createCliAgent(cliOrkas, name, 'codex');
+ const cid = await sendNewChat(page, `@${name} E2E_CODEX_SEND_NOW_ACTIVE E2E_CODEX_ASYNC_QUESTION`);
+ const question = page.locator('#chat-cli-questions');
+ await expect(question.getByRole('button', { name: 'Send answer', exact: true })).toBeVisible();
+ const childPid = cliOrkas.readCliState().codexThreadRequests?.at(-1)?.pid;
+ if (!childPid) throw new Error('The running CLI process was not recorded');
+ expect(() => process.kill(childPid, 0)).not.toThrow();
+ const stop = page.locator('#chat-send-btn');
+ await expect(stop).toHaveClass(/\bstreaming\b/);
+ await stop.click();
+ await expect(question).toBeHidden();
+ await expect(stop).not.toHaveClass(/\b(streaming|aborting)\b/, { timeout: 15_000 });
+ await expect(stop).toBeEnabled();
+ await expect.poll(() => {
+ try { process.kill(childPid, 0); return false; }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') return true;
+ throw error;
+ }
+ }, { timeout: 15_000 }).toBe(true);
+ await expect.poll(() => {
+ try { return JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.terminalStatus; }
+ catch { return null; }
+ }).toBe('cancelled');
+ expect(cliOrkas.readCliState().invocations).toHaveLength(1);
+ expect(cliOrkas.readCliState().invocations[0].questionAnswers).toBeUndefined();
+
+ await Promise.all([
+ page.waitForEvent('domcontentloaded'),
+ cliOrkas.electronApp!.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.reload()),
+ ]);
+ await page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`).click();
+ await expect(question).toBeHidden();
+ await expect(stop).not.toHaveClass(/\b(streaming|aborting)\b/);
+ await sendFollowUp(page, `@${name} E2E_CODEX_AFTER_STOP`);
+ await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {
+ hasText: 'E2E_CODEX_DEFAULT_OK',
+ })).toBeVisible({ timeout: 30_000 });
+ expect(cliOrkas.readCliState().invocations).toHaveLength(2);
+ expect(cliOrkas.readCliState().invocations[1].prompt.trimEnd()).toMatch(/E2E_CODEX_AFTER_STOP$/);
+ await expect.poll(() => JSON.parse(readFileSync(cliSessionFile(cliOrkas, cid), 'utf8'))[agentId]?.terminalStatus)
+ .toBe('completed');
+ await page.screenshot({ path: testInfo.outputPath('cli-stop-recovered.png'), fullPage: true });
+ });
for (const cli of ['claude', 'codex'] as const) {
test(`shows a native ${cli} answer once in the conversation and retains it after reload`, async ({ cliOrkas }, testInfo) => {
const name = cli === 'claude' ? 'ClaudeQuestionHistory' : 'CodexQuestionHistory';
diff --git a/test/e2e/composer_e2e_model_snapshot.spec.ts b/test/e2e/composer_e2e_model_snapshot.spec.ts
new file mode 100644
index 00000000..59c09c7b
--- /dev/null
+++ b/test/e2e/composer_e2e_model_snapshot.spec.ts
@@ -0,0 +1,50 @@
+import { expect, test } from './fixtures/orkas';
+import { holdInvokeResponse } from './fixtures/held-invoke-response';
+
+for (const update of ['newer-read', 'selection'] as const) {
+ test(`keeps the chosen model after a delayed list response and ${update}`, async ({ orkas: app }, testInfo) => {
+ const page = app.page!;
+ const next = await app.invoke<any>('auth.addCustomModelEntry', {
+ label: 'next-fixture', baseUrl: 'https://gateway.example.test/v1', model: 'fixture-next-model', apiKey: 'synthetic-next-key',
+ });
+ const old = await app.invoke<any>('auth.addCustomModelEntry', {
+ label: 'old-fixture', baseUrl: 'https://gateway.example.test/v1', model: 'fixture-old-model', apiKey: 'synthetic-old-key',
+ });
+ expect(next.ok && old.ok).toBe(true);
+ await page.evaluate(async () => { await (window as any)._refreshComposerModelEntries(); });
+ const chip = page.locator('[data-composer-model-chip="new-chat"]');
+ await expect(chip.locator('.composer-model-chip-name')).toHaveText('fixture-old-model');
+ if (update === 'selection') {
+ await chip.click();
+ await expect(page.locator('#composer-model-menu')).toBeVisible();
+ }
+ await holdInvokeResponse(app.electronApp!, 'auth.listComposerEntries');
+ try {
+ await page.evaluate(() => { const host = window as any; host.__modelReadSettled = false; host.__pendingModelRead = host._refreshComposerModelEntries().then(() => { host.__modelReadSettled = true; }); });
+ await expect.poll(() => app.electronApp!.evaluate(() => (globalThis as any).__heldInvokeResponse.ready)).toBe(true);
+ expect((await app.electronApp!.evaluate(() => (globalThis as any).__heldInvokeResponse.entryIds))[0]).toBe(old.entryId);
+ expect(await page.evaluate(() => (window as any).__modelReadSettled)).toBe(false);
+ if (update === 'selection') {
+ await page.locator('#composer-model-menu .composer-model-menu-select').filter({ hasText: 'next-fixture' }).click();
+ } else {
+ expect((await app.invoke<any>('auth.selectEntry', { entryId: next.entryId })).ok).toBe(true);
+ await page.evaluate(async () => { await (window as any)._refreshComposerModelEntries(); });
+ }
+ await expect(chip.locator('.composer-model-chip-name')).toHaveText('fixture-next-model');
+ expect((await app.invoke<any>('auth.listComposerEntries')).entries[0].entryId).toBe(next.entryId);
+ expect(await page.evaluate(() => (window as any).__modelReadSettled)).toBe(false);
+ await app.electronApp!.evaluate(() => (globalThis as any).__heldInvokeResponse.release());
+ const afterOldRead = await page.evaluate(async () => {
+ await (window as any).__pendingModelRead;
+ return document.querySelector('[data-composer-model-chip="new-chat"] .composer-model-chip-name')?.textContent;
+ });
+ expect(afterOldRead).toBe('fixture-next-model');
+ expect((await app.invoke<any>('auth.listComposerEntries')).entries[0].entryId).toBe(next.entryId);
+ await chip.screenshot({ path: testInfo.outputPath('current-model-chip.png') });
+ } finally {
+ await app.electronApp!.evaluate(() => {
+ const control = (globalThis as any).__heldInvokeResponse; control.release(); control.restore();
+ });
+ }
+ });
+}
diff --git a/test/renderer/chat-input-form.test.ts b/test/renderer/chat-input-form.test.ts
index a6b22d34..30b509a8 100644
--- a/test/renderer/chat-input-form.test.ts
+++ b/test/renderer/chat-input-form.test.ts
@@ -159,6 +159,40 @@ const baseMessage = {
};
describe('chat input form widget', () => {
+ it('preserves selection order across file fields, upload completion and draft rerender', async () => {
+ const context = loadFormModule();
+ const releases = new Map<string, () => void>();
+ let picked = ['z-first.png', 'm-second.png'];
+ context.window.orkas = { invoke: async () => ({ files: picked.map((name) => ({ name,
+ arrayBuffer: async () => new Uint8Array([1]).buffer })) }) };
+ context.apiFetch = async (_url: string, opts: any) => {
+ const name = decodeURIComponent(opts.headers['X-Filename']);
+ await new Promise<void>((resolve) => releases.set(name, resolve));
+ return { json: async () => ({ ok: true, info: { name } }) };
+ };
+ const form = { form_id: 'order1234', fields: [
+ { id: 'a', type: 'file', multiple: true }, { id: 'b', type: 'file', multiple: true },
+ ] };
+ const submissions: any[] = [];
+ const opts = { cid: 'order', onSubmit: (_text: string, values: any, attachments: string[]) => submissions.push({ values, attachments }) };
+ const container = new FakeElement('div');
+ context.window.renderChatInputForm(container, { form }, opts);
+ const pickers = container.querySelectorAll('button').filter((button) => button.className.includes('file-picker'));
+ const pick = async (index: number) => {
+ await pickers[index].dispatch('click');
+ };
+ await pick(1);
+ picked = ['a-third.png'];
+ await pick(0);
+ for (const name of ['a-third.png', 'm-second.png', 'z-first.png']) releases.get(name)!();
+ for (let i = 0; i < 8; i += 1) await Promise.resolve();
+ const restored = new FakeElement('div');
+ context.window.renderChatInputForm(restored, { form }, opts);
+ await restored.querySelectorAll('button').find((button) => button.textContent === 'Submit')!.dispatch('click');
+ expect(submissions).toEqual([{ values: { a: ['a-third.png'], b: ['z-first.png', 'm-second.png'] },
+ attachments: ['z-first.png', 'm-second.png', 'a-third.png'] }]);
+ });
+
describe('PC unanswered values', () => {
it('requires actual answers for missing typed values and preserves zero and false', async () => {
const context = loadFormModule();
diff --git a/test/renderer/composer-abort-restore.test.ts b/test/renderer/composer-abort-restore.test.ts
index 0991ee90..9e7fa715 100644
--- a/test/renderer/composer-abort-restore.test.ts
+++ b/test/renderer/composer-abort-restore.test.ts
@@ -1,5 +1,5 @@
import { composerAccessorSource } from './composer-test-source';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as vm from 'node:vm';
@@ -233,13 +233,16 @@ describe('composer restore after a user stop', () => {
});
describe('stop and settlement wiring', () => {
- function runAbort(options: Record<string, unknown>) {
+ function runAbort(options: Record<string, unknown>, tracked = true) {
const restore = vi.fn();
const context: any = {
Map,
Set,
Promise,
- pendingConvs: new Map([['conv-a', { controller: { abort: vi.fn() }, aborted: false }]]),
+ pendingConvs: new Map(tracked ? [['conv-a', { controller: { abort: vi.fn() }, aborted: false }]] : []),
+ _latestActiveTurns: new Map([['conv-a', [{ actor: 'cli-a', turn_id: 'old-turn', steerable: true }]],
+ ['conv-other', [{ actor: 'cli-b', turn_id: 'other-turn', steerable: true }]]]),
+ window: { CliAsyncInput: { setActiveTurns: vi.fn() } },
_groupPlaceholders: new Map(),
currentCid: 'conv-a',
_trackTaskStopClick: vi.fn(),
@@ -249,6 +252,7 @@ describe('stop and settlement wiring', () => {
setGroupConversationBusy: vi.fn(),
apiFetch: vi.fn(() => ({ catch: () => ({ finally: () => {} }) })),
_refreshTaskSurfacesAfterAbort: vi.fn(),
+ _beginTaskSurfaceAbortRefresh: vi.fn(() => ({ settled: false })),
_updateConvSidebarBadge: vi.fn(),
_updateConvSendUI: vi.fn(),
_streamingMarkAborted: vi.fn(),
@@ -262,14 +266,25 @@ describe('stop and settlement wiring', () => {
${extractFunction('abortConvStream')}
`, context, { filename: 'abort.js' });
context.abortConvStream('conv-a', options);
- return restore;
+ return { restore, context };
}
it('restores only when the user pressed stop', () => {
- expect(runAbort({ userInitiated: true })).toHaveBeenCalledWith('conv-a');
+ expect(runAbort({ userInitiated: true }).restore).toHaveBeenCalledWith('conv-a');
// Conversation delete and missing-conversation recovery also abort; neither
// is an edit intent, so the composer must be left alone.
- expect(runAbort({})).not.toHaveBeenCalled();
+ expect(runAbort({}).restore).not.toHaveBeenCalled();
+ });
+
+ it.each([true, false])('expires questions only for the stopped conversation after streams detach (tracked=%s)', tracked => {
+ const { context } = runAbort({ userInitiated: true }, tracked);
+ expect(context._latestActiveTurns.get('conv-a')).toEqual([]);
+ expect(context._latestActiveTurns.get('conv-other')).toEqual([
+ { actor: 'cli-b', turn_id: 'other-turn', steerable: true },
+ ]);
+ expect(context.window.CliAsyncInput.setActiveTurns).toHaveBeenCalledExactlyOnceWith('conv-a', []);
+ // Invalidating the view must not submit or cancel an answer on the user's behalf.
+ expect(context.apiFetch).toHaveBeenCalledExactlyOnceWith('/api/conversations/conv-a/abort', { method: 'POST' });
});
it('drops the snapshot when the turn settles', () => {
@@ -307,3 +322,247 @@ describe('stop and settlement wiring', () => {
expect([...offViewDirty]).toEqual(['conv-a', 'conv-other']);
});
});
+
+
+function loadAbortTaskSurfaceLifecycle() {
+ const abortReplies: Array<() => void> = [];
+ const owners = new Map();
+ const resync = vi.fn();
+ const streams: Array<{ read: ReturnType<typeof vi.fn>; event: (event: unknown) => void; finish: () => void }> = [];
+ const primaryHooks: any[] = [];
+ const context: any = {
+ Map, Set, Promise, setTimeout, clearTimeout,
+ _taskSurfaceAbortRefreshOwners: owners,
+ _forgottenTaskSurfaceObservers: new WeakSet(),
+ _convChatCtrls: new Map(), _groupObserverReservations: new Map(), _groupObserverCtrls: new Map(),
+ AbortController, TextDecoder,
+ _startRuntimeActorRecovery: vi.fn(),
+ isConvPending: () => false, isGroupConversationBusy: () => false,
+ _conversationHistoryLoad: null, _lastGroupWorkEventAt: new Map(),
+ _isConversationDisplayVisible: () => true, _syncTaskBoardForRuntimeState: vi.fn(),
+ _createStreamingAssistantMessage: () => null, startPolling: vi.fn(),
+ _finishStreamingMsg: vi.fn(),
+ createChatController: vi.fn((config: any) => {
+ primaryHooks.push(config.hooks);
+ return { abort: vi.fn(), send: vi.fn() };
+ }),
+ pendingConvs: new Map(), currentCid: '',
+ window: {
+ TaskBoard: { resync },
+ ConversationInfo: { refreshFiles: vi.fn() },
+ CliAsyncInput: { setActiveTurns: vi.fn(), forget: vi.fn() },
+ },
+ _groupPlaceholders: new Map(), _recipientByCid: {},
+ _saveRecipientMap: vi.fn(), setGroupConversationBusy: vi.fn(),
+ _stopRuntimeActorRecovery: vi.fn(), _stopGroupEventObserver: vi.fn(),
+ _restoreSentComposerSnapshot: vi.fn(), _updateConvSidebarBadge: vi.fn(),
+ _updateConvSendUI: vi.fn(), stopPolling: vi.fn(),
+ document: { getElementById: () => null },
+ uiConfirm: vi.fn(async () => true), uiAlert: vi.fn(async () => {}),
+ t: (key: string) => key, _projectIdForConversation: () => 'project-owner',
+ _removeConversationFromSidebar: vi.fn(), _logConversationManageResult: vi.fn(),
+ _convLog: { warn: vi.fn() }, setView: vi.fn(),
+ deletionSucceeds: true,
+ };
+ for (const key of [
+ '_autoRecipientByCid', '_serverFloorByCid', '_serverFloorRevisionByCid',
+ '_pendingFloorResetByCid', '_latestInFlight', '_latestActiveTurns',
+ '_liveDisplayWatermarks', '_conversationInfoFileRefreshTimers',
+ '_quotesByCid', '_groupMembersCache', '_settledConvTurns',
+ '_chatAttachmentRevisions', 'pollMsgCounts',
+ ]) context[key] = new Map();
+ context._offViewLiveDisplayDirty = new Set();
+ context._failedConvs = new Set();
+ context.apiFetch = vi.fn((url: string, options: { signal?: AbortSignal } = {}) => {
+ if (url.endsWith('/events/stream')) {
+ // Real response/reader protocol: even after AbortSignal changes, an
+ // already queued IPC read can resolve later. The test owns that boundary.
+ let resolveRead: ((reply: { done: boolean; value?: Uint8Array }) => void) | undefined;
+ const read = vi.fn(() => new Promise(resolve => { resolveRead = resolve; }));
+ streams.push({
+ read,
+ event: event => {
+ if (!resolveRead) throw new Error('observer has not started reading');
+ const resolve = resolveRead;
+ resolveRead = undefined;
+ resolve({ done: false, value: new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`) });
+ },
+ finish: () => {
+ if (!resolveRead) throw new Error('observer has no pending read');
+ const resolve = resolveRead;
+ resolveRead = undefined;
+ resolve({ done: true });
+ },
+ });
+ return Promise.resolve({ ok: true, body: { getReader: () => ({ read }) } });
+ }
+ if (url.endsWith('/abort')) return new Promise(resolve => {
+ abortReplies.push(() => resolve({ ok: true }));
+ });
+ return Promise.resolve({
+ ok: context.deletionSucceeds,
+ status: context.deletionSucceeds ? 200 : 500,
+ json: async () => ({ ok: context.deletionSucceeds }),
+ });
+ });
+ vm.createContext(context);
+ vm.runInContext([
+ extractFunction('_forgetConversationRuntime'),
+ extractFunction('_beginTaskSurfaceAbortRefresh'),
+ extractFunction('_refreshTaskSurfacesAfterAbort'),
+ extractFunction('_forgetCidRecipient'),
+ extractFunction('_settleConversationPlaceholdersOnAbort'),
+ extractFunction('_taskBoardEventBypassesViewGuard'),
+ conversationSource.slice(conversationSource.indexOf('function _handleGroupBusEvent('), conversationSource.indexOf('\nfunction ', conversationSource.indexOf('function _handleGroupBusEvent(') + 1)),
+ extractFunction('_handleStreamEvent'),
+ extractFunction('_makeConvChatController'),
+ extractFunction('_observerShouldDeferCleanup'),
+ extractFunction('_isPrimaryOwnedLiveEvent'),
+ extractFunction('_nowForStreamYield'),
+ extractFunction('_makeStreamPaintYield'),
+ extractFunction('_observeConversationRunFromPlanAction'),
+ extractFunction('abortConvStream'),
+ 'async ' + extractFunction('_deleteConversationWithConfirm'),
+ ].join('\n'), context);
+ context._forgetConvLocal = vi.fn((cid: string) => context._forgetCidRecipient(cid));
+ return { context, owners, resync, abortReplies, streams, primaryHooks };
+}
+
+describe('abort task-surface refresh lifetime', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('refreshes an incoming bus abort without a local Stop and stops it after confirmed forget', async () => {
+ const { context, owners, resync } = loadAbortTaskSurfaceLifecycle();
+ const cid = 'project-task';
+ context.currentCid = cid;
+ context._convChatCtrls.set(cid, context._makeConvChatController(cid));
+ context._handleStreamEvent(cid, null, { type: 'event', event: { stream: 'group', data: { type: 'aborted' } } });
+ expect(resync).toHaveBeenCalledExactlyOnceWith(cid);
+ context._forgetCidRecipient(cid);
+ await vi.advanceTimersByTimeAsync(5000);
+ context._handleStreamEvent(cid, null, { type: 'event', event: { stream: 'group', data: { type: 'aborted' } } });
+ expect(resync).toHaveBeenCalledTimes(1);
+ expect(owners.size).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('restores a live run while an activated old observer and primary onDone unwind', async () => {
+ const { context, streams, primaryHooks } = loadAbortTaskSurfaceLifecycle();
+ const cid = 'project-task';
+ context.currentCid = cid;
+ const oldDone = vi.fn();
+ const oldPrimary = context._makeConvChatController(cid, { onDone: oldDone });
+ context._convChatCtrls.set(cid, oldPrimary);
+ // Drive the actual primary factory hook. It creates pending state and
+ // attaches the actual paired observer, just as a started send does.
+ primaryHooks[0].onAssistantStart(null, cid);
+ await vi.advanceTimersByTimeAsync(0);
+ const oldObserver = context._groupObserverReservations.get(cid);
+ expect(context.pendingConvs.get(cid).controller).toBe(oldPrimary);
+ expect(context.setGroupConversationBusy).toHaveBeenCalledWith(cid, true);
+ expect(streams[0].read).toHaveBeenCalledTimes(1);
+ // At least one valid event traverses the real decoder and observer loop.
+ // A paired process event stays owned by its primary and is not duplicated.
+ const ownsLiveEvent = vi.spyOn(context, '_isPrimaryOwnedLiveEvent');
+ streams[0].event({ type: 'process', actor_id: 'commander', event: { type: 'text_delta', text: 'working' } });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ownsLiveEvent).toHaveBeenCalledWith(expect.objectContaining({ type: 'process' }));
+ expect(streams[0].read).toHaveBeenCalledTimes(2);
+ const other = { abort: vi.fn() };
+ context._convChatCtrls.set('other-task', other);
+ context._forgetCidRecipient(cid);
+ expect(oldPrimary.abort).toHaveBeenCalledTimes(1);
+ expect(context._convChatCtrls.has(cid)).toBe(false);
+ expect(context._groupObserverReservations.has(cid)).toBe(false);
+ expect(context._groupObserverCtrls.has(cid)).toBe(false);
+ const restoredPrimary = context._makeConvChatController(cid);
+ context._convChatCtrls.set(cid, restoredPrimary);
+ primaryHooks[1].onAssistantStart(null, cid);
+ await vi.advanceTimersByTimeAsync(0);
+ const restoredObserver = context._groupObserverReservations.get(cid);
+ expect(restoredPrimary).not.toBe(oldPrimary);
+ expect(restoredObserver).toBeTruthy();
+ expect(restoredObserver).not.toBe(oldObserver);
+ expect(streams[1].read).toHaveBeenCalledTimes(1);
+ const refreshFiles = context.window.ConversationInfo.refreshFiles;
+ refreshFiles.mockClear();
+ // The old stream finally is deliberately released only AFTER the restored
+ // primary and shared subscription exist. No obsolete file/history lookup
+ // or settlement may run against that restored conversation.
+ streams[0].finish();
+ await vi.advanceTimersByTimeAsync(0);
+ primaryHooks[0].onDone(null, cid, { aborted: true });
+ expect(oldDone).toHaveBeenCalledExactlyOnceWith({ aborted: true });
+ expect(refreshFiles).not.toHaveBeenCalled();
+ expect(context._convChatCtrls.get(cid)).toBe(restoredPrimary);
+ expect(context.pendingConvs.get(cid).controller).toBe(restoredPrimary);
+ expect(context._groupObserverReservations.get(cid)).toBe(restoredObserver);
+ expect(context._finishStreamingMsg).not.toHaveBeenCalled();
+ expect(other.abort).not.toHaveBeenCalled();
+ expect(context._convChatCtrls.get('other-task')).toBe(other);
+ expect(context._convLog.warn).not.toHaveBeenCalled();
+ context._forgetCidRecipient(cid);
+ streams[1].finish();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('keeps immediate and settled refreshes for a project conversation outside the sidebar cache', async () => {
+ const { context, resync, owners, abortReplies } = loadAbortTaskSurfaceLifecycle();
+ context.abortConvStream('project-task', { userInitiated: true });
+ expect(resync).toHaveBeenCalledExactlyOnceWith('project-task');
+ abortReplies[0]();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(resync).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1499);
+ expect(resync).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(resync).toHaveBeenCalledTimes(3);
+ expect(owners.size).toBe(0);
+ expect(context._restoreSentComposerSnapshot).toHaveBeenCalledExactlyOnceWith('project-task');
+ });
+
+ it('preserves failed-delete recovery and cancels delayed work only after successful retry', async () => {
+ const { context, owners, resync, abortReplies } = loadAbortTaskSurfaceLifecycle();
+ context.deletionSucceeds = false;
+ expect(await context._deleteConversationWithConfirm('project-task')).toBe(false);
+ expect(context._forgetConvLocal).not.toHaveBeenCalled();
+ expect(context.uiAlert).toHaveBeenCalled();
+ abortReplies[0]();
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(resync).toHaveBeenLastCalledWith('project-task');
+ expect(resync).toHaveBeenCalledTimes(3);
+ context.deletionSucceeds = true;
+ expect(await context._deleteConversationWithConfirm('project-task')).toBe(true);
+ expect(context._forgetConvLocal).toHaveBeenCalledExactlyOnceWith('project-task');
+ const afterDelete = resync.mock.calls.length;
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(5000);
+ abortReplies[1]();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(resync).toHaveBeenCalledTimes(afterDelete);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(owners.size).toBe(0);
+ });
+
+ it('keeps other conversations alive and rejects a late old abort after the same cid is restored', async () => {
+ const { context, owners, resync, abortReplies } = loadAbortTaskSurfaceLifecycle();
+ context.abortConvStream('project-task');
+ context.abortConvStream('other-task');
+ context._forgetCidRecipient('project-task');
+ context.abortConvStream('project-task');
+ const restoredOwner = owners.get('project-task');
+ const beforeOldReply = resync.mock.calls.length;
+ abortReplies[0]();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(resync).toHaveBeenCalledTimes(beforeOldReply);
+ expect(owners.get('project-task')).toBe(restoredOwner);
+ abortReplies[1]();
+ abortReplies[2]();
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(resync.mock.calls.filter(([cid]) => cid === 'other-task')).toHaveLength(3);
+ expect(resync.mock.calls.filter(([cid]) => cid === 'project-task')).toHaveLength(4);
+ expect(owners.size).toBe(0);
+ });
+});
diff --git a/test/renderer/composer-popover-coordination.test.ts b/test/renderer/composer-popover-coordination.test.ts
index 6d8e3aeb..39f56fa5 100644
--- a/test/renderer/composer-popover-coordination.test.ts
+++ b/test/renderer/composer-popover-coordination.test.ts
@@ -120,10 +120,12 @@ function delayedModelPicker() {
listeners.get(name)!.add(listener);
},
removeEventListener(name: string, listener: unknown) { listeners.get(name)?.delete(listener); },
+ dispatchEvent(event: { type: string }) { [...(listeners.get(event.type) || [])].forEach((fn: any) => fn(event)); return true; },
};
const pending: Array<() => void> = [];
const timers: Array<() => void> = [];
const context = vm.createContext({
+ CustomEvent: class { constructor(public type: string, public detail: unknown) { this.detail = (detail as any)?.detail; } },
document: {
...eventTarget, body,
createElement: () => new Element(),
@@ -147,6 +149,8 @@ function delayedModelPicker() {
const api = vm.runInContext('({ open: _toggleComposerModelMenu, close: _closeComposerModelMenu, peer: _closeOtherComposerPopovers })', context);
return {
...api,
+ context,
+ emit: (name: string, event: unknown = {}) => [...(listeners.get(name) || [])].forEach((fn: any) => fn(event)),
anchor: () => new Element(),
release: () => pending.splice(0).forEach((resolve) => resolve()),
flushTimers: () => timers.splice(0).forEach((fn) => fn()),
@@ -281,3 +285,57 @@ describe('composer popover coordination', () => {
expect(workspaceOpen).toContain("_closeOtherComposerPopovers('workspace')");
});
});
+
+
+describe('composer model snapshot ordering', () => {
+ const oldEntries = [{ entryId: 'entry-a', provider: 'custom', model: 'old', modelName: 'Old' }];
+ const newEntries = [{ entryId: 'entry-b', provider: 'custom', model: 'new', modelName: 'New' }];
+ it.each(['read', 'event', 'selection', 'version'])('does not replace newer %s state with an older list response', async cause => {
+ const picker = delayedModelPicker();
+ const context = picker.context;
+ let release!: (value: unknown) => void;
+ const gate = new Promise(resolve => { release = resolve; });
+ let reads = 0;
+ context.window.orkas.invoke = async (channel: string) => {
+ if (channel === 'auth.listComposerEntries') return ++reads === 1 ? gate : { ok: true, entries: newEntries };
+ return { ok: true, entries: newEntries };
+ };
+ if (cause !== 'read') {
+ picker.emit('DOMContentLoaded'); // Starts the actual boot read and installs the real event listener.
+ }
+ const pending = cause === 'read' ? vm.runInContext('_refreshComposerModelEntries()', context) : undefined;
+ try {
+ if (cause === 'read') await vm.runInContext('_refreshComposerModelEntries()', context);
+ else if (cause === 'event') picker.emit('orkas:model-entries-changed', { detail: { entries: newEntries } });
+ else {
+ context.__entries = oldEntries.map(entry => ({ ...entry }));
+ vm.runInContext('_composerModelEntries = __entries;', context);
+ if (cause === 'selection') {
+ context.__selected = newEntries[0];
+ await vm.runInContext('_selectComposerModel(__selected, "new-chat")', context);
+ } else {
+ await vm.runInContext('_updateComposerModelVersion(__entries[0], "new-chat", {id:"new",name:"New"}, null, null)', context);
+ }
+ }
+ const expected = vm.runInContext('JSON.stringify(_composerModelEntries)', context);
+ release({ ok: true, entries: oldEntries }); await pending;
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(vm.runInContext('JSON.stringify(_composerModelEntries)', context)).toBe(expected);
+ expect(JSON.parse(expected)[0].model).toBe('new');
+ } finally { release({ ok: true, entries: [] }); await pending; picker.close(); }
+ });
+
+ it.each(['rejected', 'malformed'])('retains the published entries when the latest read is %s', async outcome => {
+ const picker = delayedModelPicker();
+ const context = picker.context;
+ context.window.orkas.invoke = async () => ({ ok: true, entries: newEntries });
+ await vm.runInContext('_refreshComposerModelEntries()', context);
+ context.window.orkas.invoke = async () => {
+ if (outcome === 'rejected') throw new Error('controlled transport failure');
+ return { ok: true, entries: null };
+ };
+ await vm.runInContext('_refreshComposerModelEntries()', context);
+ expect(vm.runInContext('JSON.stringify(_composerModelEntries)', context)).toBe(JSON.stringify(newEntries));
+ picker.close();
+ });
+});
diff --git a/test/renderer/context-menu.test.ts b/test/renderer/context-menu.test.ts
index f090bb78..f7fe8905 100644
--- a/test/renderer/context-menu.test.ts
+++ b/test/renderer/context-menu.test.ts
@@ -174,6 +174,18 @@ async function flushPromises(): Promise<void> {
}
describe('context menu', () => {
+ it('marks destructive actions while preserving neutral and disabled actions', () => {
+ const harness = createHarness();
+ harness.window.showContextMenu({ clientX: 20, clientY: 20 }, [
+ { label: 'Edit', onClick: vi.fn() },
+ { label: 'Delete', danger: true, onClick: vi.fn() },
+ { label: 'Unavailable', danger: true, disabled: true, onClick: vi.fn() },
+ ]);
+ const buttons = harness.menu()!.querySelectorAll('.context-menu-item');
+ expect(buttons.map(button => button.classList.contains('is-danger'))).toEqual([false, true, true]);
+ expect(buttons[2].disabled).toBe(true);
+ });
+
it('filters invalid items, clamps to the viewport, and focuses the first enabled action', () => {
const harness = createHarness();
harness.window.showContextMenu(
diff --git a/test/renderer/home.test.ts b/test/renderer/home.test.ts
index 5f78e4fb..1eeff586 100644
--- a/test/renderer/home.test.ts
+++ b/test/renderer/home.test.ts
@@ -68,8 +68,6 @@ function loadHome(options: {
'home-groups': element(),
'home-explore-context': element(),
};
- const clicks: Array<[string, any]> = [];
- const events: Array<[string, any]> = [];
const views: any[][] = [];
const invokes: Array<[string, any]> = [];
const forgotten: string[] = [];
@@ -96,16 +94,11 @@ function loadHome(options: {
loadRendererFeature: vi.fn(async () => {}),
focusTodo: vi.fn(),
showContextMenu: (_anchor: any, items: any[]) => { menus.push(items); },
- Monitor: {
- click: (action: string, data: any) => { clicks.push([action, data]); },
- event: (action: string, data: any) => { events.push([action, data]); },
- },
document: { getElementById: (id: string) => els[id] || null },
};
context.window = {
uiIconHtml,
innerHeight: 720,
- Monitor: true,
addEventListener() {},
TaskUnread: { list: () => options.unread || [] },
loadConnectorNavTarget: async (id: string) => ({ name: { feishu: '飞书', dingtalk: '钉钉', gmail: 'Gmail', 'm365-mail': 'Microsoft 365 邮箱' }[id] || id }),
@@ -131,7 +124,7 @@ function loadHome(options: {
for (let i = 0; i < 4; i += 1) await new Promise((resolve) => setImmediate(resolve));
};
return {
- context, els, clicks, events, views, invokes, forgotten, menus, timers, settle,
+ context, els, views, invokes, forgotten, menus, timers, settle,
state: () => els['panel-new-chat'].dataset.homeState,
html: () => els['home-groups'].innerHTML as string,
data: () => JSON.parse(vm.runInContext('JSON.stringify(_homeData)', context)),
@@ -159,6 +152,32 @@ describe('Commander home states', () => {
);
});
+ it('shows a dated to-do\'s day on its row and flags one past its day while it is open', async () => {
+ const pad = (value: number) => String(value).padStart(2, '0');
+ const day = (offset: number) => {
+ const date = new Date();
+ date.setDate(date.getDate() + offset);
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+ };
+ const h = loadHome({
+ todos: {
+ total: 3,
+ tasks: [
+ { id: 't_due', project_id: '', project_name: '', status: 'todo', content: '发上线邮件', due_at: day(2) },
+ { id: 't_late', project_id: '', project_name: '', status: 'todo', content: '交周报', due_at: day(-2) },
+ { id: 't_plain', project_id: '', project_name: '', status: 'todo', content: '整理访谈' },
+ ],
+ },
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+ const html = h.html();
+ const metaOf = (title: string) => new RegExp(`${title}</span><span class="home-row-meta"><span class="home-row-source">[^<]*</span>([^<]*)`).exec(html)?.[1] || '';
+ expect(metaOf('发上线邮件')).toMatch(/^[^·]+ · .+ 到期$/);
+ expect(metaOf('交周报')).toMatch(/^[^·]+ · 已逾期(.+)$/);
+ expect(metaOf('整理访谈')).not.toMatch(/到期|逾期/);
+ });
+
it('groups open to-dos, automation runs and other finished tasks in that order', async () => {
const h = loadHome({
todos: {
@@ -440,7 +459,6 @@ describe('Commander home Connectors link', () => {
h.els['home-explore-context'].fire('click', click({}));
expect(h.views).toEqual([]);
- expect(h.clicks).toEqual([]);
h.els['home-explore-context'].fire('click', click({ '[data-home-connect]': element() }));
expect(h.views).toEqual([['connectors', null, { entryPoint: 'home' }]]);
await h.settle();
diff --git a/test/renderer/new-chat-home.test.ts b/test/renderer/new-chat-home.test.ts
index e29429d8..fb515829 100644
--- a/test/renderer/new-chat-home.test.ts
+++ b/test/renderer/new-chat-home.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
+import * as vm from 'node:vm';
const root = path.join(__dirname, '../..');
@@ -28,11 +29,27 @@ describe('new chat home surface', () => {
expect(sidebarFooter.match(/<button\b/g)).toHaveLength(1);
});
- it('keeps voice input filtered from the open-source composer', () => {
+ it('exposes localized voice input through the public ticket API', () => {
const html = read('src/renderer/index.html');
+ const button = /<button\b[^>]*id="new-chat-mic-btn"[^>]*>[\s\S]*?<\/button>/.exec(html)?.[0];
+ expect(button).toBeTruthy();
+ expect(button).toContain('type="button"');
+ expect(button).toContain('data-i18n-title="chat.mic_title"');
+ expect(button).toContain('data-ui-icon="mic"');
+ expect(html.match(/id="new-chat-mic-btn"/g)).toHaveLength(1);
+ expect(html).toContain('<script src="./modules/voice-input.js"></script>');
+ const preload = read('src/main/preload.js');
+ expect(preload).toContain("createSession: () => invoke('voiceInput.createSession')");
+ expect(preload).toContain("ensureMicrophoneAccess: () => invoke('voiceInput.ensureMicrophoneAccess')");
+ });
- expect(html).not.toContain('id="new-chat-mic-btn"');
- expect(html).not.toContain('data-ui-icon="mic"');
+ it('hides the microphone when the public ticket capability is unavailable', () => {
+ const button = { dataset: {} as Record<string, string>, style: {} as Record<string, string> };
+ const context: any = { window: { orkas: {} }, document: { addEventListener() {} } };
+ vm.createContext(context);
+ vm.runInContext(read('src/renderer/modules/voice-input.js'), context);
+ context.window.VoiceInput.attach(button, { value: 'Keep this draft' });
+ expect(button.style.display).toBe('none');
});
it('keeps external CLI onboarding on the AI Team header only', () => {