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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Interactive web-app artifacts: chat-app:// protocol + create_artifact tool + 'My Apps' library
wytb9617379751f
diff --git a/CLAUDE.md b/CLAUDE.mdindex eb548708..0ec81dc5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -116,6 +116,8 @@ PC/data/│ ├── chats/<cid>.jsonl + chats/<cid>/{members,state,plan,visibility/} group-chat runtime state (see §5)│ ├── chats/{skill,agent}/<id>/chat.{json,jsonl} edit sessions│ ├── chat_attachments/<cid>/ Main-conversation attachment pool (zero pre-processing)+ │ ├── chat_artifacts/<cid>/<artifactId>/ LLM-generated interactive web-app bundles (`create_artifact`); served read-only via `chat-app://`; purged by cid on conv delete (see §5)+ │ ├── saved_apps/<appId>/ User-kept copies of `create_artifact` apps ("My Apps" tab); conversation-independent; never auto-purged; opened via `shell.openPath` (file://) (see §5)│ ├── sessions/<sid>.jsonl core-agent PersistentSession│ ├── contexts/ KB user-managed directory tree + .kb/vector.db (see §7)│ ├── memory/MEMORY.md + USER.md@@ -202,7 +204,13 @@ Stored at `<uid>/cloud/chat_attachments/<cid>/<file>`, **zero pre-processing**;### Local execution tools-`bash / write_file / edit_file / markdown_to_pdf / html_to_pdf / generate_image` share the `localExec.granted` permission gate (grant/revoke from the settings page, re-read on every `execute()` so it takes effect mid-conversation); unauthorized → `isError=true`. `web_search` goes through `searchProfiles[0]` → paid API → fallback built-in. Outputs are collected via `ChatOptions.onFileWritten` (also fires for `edit_file` so in-place modifications surface as green chips); the renderer shows green chips → IPC `workspace.revealPath` (strictly validated to stay inside the workspace). See `model/core-agent/{local-tools, image-gen-tool, search-tools}.ts`.+`bash / write_file / edit_file / markdown_to_pdf / html_to_pdf / generate_image / create_artifact` share the `localExec.granted` permission gate (grant/revoke from the settings page, re-read on every `execute()` so it takes effect mid-conversation); unauthorized → `isError=true`. `web_search` goes through `searchProfiles[0]` → paid API → fallback built-in. Outputs are collected via `ChatOptions.onFileWritten` (also fires for `edit_file` so in-place modifications surface as green chips); the renderer shows green chips → IPC `workspace.revealPath` (strictly validated to stay inside the workspace). See `model/core-agent/{local-tools, image-gen-tool, search-tools}.ts`.++### Interactive web-app artifacts (`create_artifact` + `chat-app://`)++`create_artifact({title, files:[{path,content,encoding?}]})` writes a self-contained multi-file web app into `<uid>/cloud/chat_artifacts/<cid>/<artifactId>/` (the **only** place artifact files live; `features/chat_artifacts.ts` validates the set — must include a top-level `index.html`, ≤20 files / 256 KB·file / 1 MB total, served-extension allowlist, base64 for binary). The renderer embeds it as a sandboxed `<iframe>` (`sandbox="allow-scripts allow-same-origin allow-forms"`, cross-origin to the renderer so `parent.*` is blocked by SOP) at the bottom of the assistant bubble (`modules/chat-artifact.js`); the card header also has an "open in browser" button → `conversations.artifacts.openExternal` IPC → `shell.openPath(<artifactDir>/index.html)` (a `file://` view, so the `__orkas/bridge.js` virtual path and cross-origin sibling `fetch` don't work there — the iframe stays the primary surface; the path is still routed through `chatArtifacts.resolveArtifactFilePath`). It's served read-only by the privileged `chat-app://cid/<encCid>/<encArtifactId>/<relpath>` protocol handler in `index.ts` (every request → `chatArtifacts.resolveArtifactFilePath`, same traversal guards as `resolveAttachmentAbsPath`; reserved virtual path `__orkas/bridge.js` → in-memory `BRIDGE_JS`). The **only** artifact→app channel is `postMessage({__orkasArtifact:true, type:'submit'|'resize'|'open-external', ...}, '*')`, which the renderer validates by `event.source` identity (not origin string) before composing a `@`-routed user message (`<artifact-result artifact_id agent_id>` tag, stripped from display, opaque to bus). Never inject `window.orkas` or any privileged handle into the iframe. Flow: `create_artifact` fires `LocalToolsOpts.onArtifactCreated` → `bus.ts::runTurn` collects per-turn + attaches `GroupMessage.artifacts[{id,title,agent_id}]` on the end-of-turn enqueue (`agent_id` = the producing actor, the result-routing target); `chats.deleteConversation → chatArtifacts.purgeByCid`. `create_artifact` is only offered when the runner has both `cid` and an `onArtifactCreated` sink (group chat) — edit chats / ad-hoc runs don't get it. Orphaned artifact dirs (single-message edit/delete) are not GC'd yet.++The artifact card's header collapses into one `⋯` popover: **reload** / **open in browser** (`conversations.artifacts.openExternal` → `shell.openPath(<artifactDir>/index.html)`, a `file://` view, so the `chat-app://` bridge / cross-origin sibling `fetch` don't work there — the iframe stays the primary surface) / **save**. **Save** (`conversations.artifacts.save` → `features/saved_apps.ts::saveFromArtifact`) copies the bundle into a conversation-independent pool `<uid>/cloud/saved_apps/<appId>/` (cloud-synced, never auto-purged, not touched by `deleteConversation`), stamped with a provenance `__orkas-meta.json`. The "My Apps" sidebar tab (`#apps-btn` → view `apps` → `#panel-apps`, `modules/saved-apps.js`) lists them (`savedApps.list`); a card's primary click opens it in the system browser (`savedApps.openExternal` → `savedApps.resolveSavedAppIndex` — same appId-shape + `path.relative` traversal guard family as `resolveArtifactFilePath` — then `shell.openPath`); the card `⋯` has **edit** (`savedApps.openForEditing` → creates a fresh normal conversation, bundles the app's source into a single `app-source.md` and `chatAttachments.uploadAttachment`s it there, returns the conv so the renderer navigates + pre-fills a draft — on any failure the half-built conv is rolled back via `deleteConversation`) / rename (`savedApps.rename`) / delete (`savedApps.delete`). "Edit" is a fork-and-modify flow: the new conversation's `create_artifact` produces a *new* artifact, not an in-place update; the original saved app is untouched.**Write-file conflict avoidance** (`util/uniquify-path.ts`): `write_file / markdown_to_pdf / html_to_pdf / generate_image` write to the path the model gives by default; **on conflict, uniquify** (insert `-N` before the basename suffix) and pass it back explicitly via the `<file-renamed>` block in the tool result. "Mine vs not mine" is decided by the caller-injected `ChatOptions.hasProducedPath` (group_chat uses producedSet at turn granularity) — paths this turn already wrote are treated as refinement (overwrite); other pre-existing files are external conflicts. **`bash` is not in the protected scope** (shell redirection is a black box). **`edit_file` is also not in this scope** by design — its semantics is "modify an existing file in place" (not "create a new artefact"), so uniquify would be wrong; it instead enforces sandbox-membership (workspace + current attachment dir + extraRoots, same set as the file-tools read side) and rejects pdf/docx/image kinds, so the LLM can only mutate text files the conversation can already see. When `read_file` hits ENOENT, it scans sibling `<name>-N<ext>` files in the same directory; on a hit it appends a `<file-renamed-earlier>` hint as a second layer of defense.@@ -349,6 +357,14 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t- Reintroduce an aggregate `projects/_index.json`. Project existence is the set of `projects/<pid>/project.json` files on disk; listing scans the directory. **Why:** an aggregate index re-creates the multi-device sync conflict surface this round was designed to avoid (every membership change becomes a multi-file transactional write), and once a server-mediated collab story lands, server-side sync of project directories is a directory-level operation — clients only ever scan. See `features/projects.ts` header.- Apply the project agent/skill scope as a 5th `component_enabled` filter site. Project scope is an OUTER intersection plumbed through the existing render entry points (`buildAgentsIndexBlock` `allowedIds` / `getSystemPromptBlock` `allowlist`) — see §6.+**Artifacts (`chat-app://`)**:+- Serve artifact bytes from anywhere but `chat_artifacts/<cid>/<artifactId>/` via the `chat-app://` handler; let `create_artifact` write outside the current cid's artifact pool. Every request goes through `chatArtifacts.resolveArtifactFilePath` (safe-cid / safe-artifactId / safe-relpath + `path.relative` traversal guard + served-extension allowlist) — see §5.+- Expose `window.orkas` / IPC / any privileged handle into the artifact iframe. The only artifact→app channel is the validated `postMessage` contract; the iframe is sandboxed (`allow-scripts allow-same-origin allow-forms`, cross-origin to the renderer) and never gets a host handle.+- Widen the served-extension allowlist to executable / archive types, or combine `allow-scripts` with anything that re-grants embedder access (the current flags are safe only because the artifact origin `chat-app://cid` ≠ the renderer's `file://`).+- Route an artifact-result back via a parallel path — it's a plain `@<agent_id>`-prefixed user message through the normal send pipeline; the `<artifact-result>` tag is opaque to bus (stripped from display by `_stripArtifactResultTagForDisplay`).+- Open / serve a saved-app file from anywhere but `saved_apps/<appId>/`. `savedApps.resolveSavedAppIndex` is the sole resolver before `shell.openPath` (same appId-shape + `path.relative` traversal guard family as `resolveArtifactFilePath`). `saveFromArtifact` copies *out of* a `chat_artifacts/<cid>/<artifactId>/` dir resolved by `chatArtifacts.resolveArtifactDir` — never copy from an unvalidated path. `openForEditing` bundles the app's source into a single `.md` attachment (the `chat_attachments` whitelist deliberately excludes `.html`/`.js`/`.css`, and `buildAttachmentManifest` would skip them) — don't copy raw `.html`/`.js` into `chat_attachments/`, and don't widen that whitelist for this.+- Reuse `.agent-card` / `.agents-grid` class names for the "My Apps" panel (`#panel-apps` uses `.app-card` / `.apps-grid`): `agents.js` binds a global `document.querySelectorAll('.agent-card')` click handler, so sharing the name cross-wires the two panels. Layout-only shells (`.agents-grid-view` / `-header` / `-scroll` / `.agents-empty`) have no JS hook and are reused on purpose.+**Timeouts / locks**:- Add a "total wall-clock timeout" to LLM calls (`timeout: N` / `setTimeout→abort`). The single application-layer watchdog is `client.ts::streamChatWithModel`'s `idleTimeout=600s` (true idle); the SDK 1h limit is backstopped by `sdk-timeout-patch.ts`; group-chat infinite-loop protection is `bus.ts::MAX_WORKER_TURNS=100` (**turns, do not change to a timeout**).- Add a wait timeout to `sessionLock.acquire()` / `globalSlots.acquire()`. Long LLM tasks should queue indefinitely; adding a timeout = fake failures.diff --git a/src/main/features/chat_artifacts.ts b/src/main/features/chat_artifacts.tsnew file mode 100644index 00000000..ca7e13bf--- /dev/null+++ b/src/main/features/chat_artifacts.ts@@ -0,0 +1,425 @@+/**+ * Interactive web-app "artifacts" for the main chat.+ *+ * An artifact is a self-contained multi-file web app the LLM produces via the+ * `create_artifact` tool (HTML/CSS/JS, optional inline binary assets). It is+ * written to disk and served read-only through the `chat-app://` protocol (see+ * `src/main/index.ts`), then embedded in a sandboxed `<iframe>` inside the+ * assistant bubble (renderer `modules/chat-artifact.js`). User interaction+ * round-trips back to the creating agent via `postMessage` (see the renderer+ * widget) — there is no iframe→disk channel by design (the sandbox boundary).+ *+ * Layout: `<uid>/cloud/chat_artifacts/<cid>/<artifactId>/`+ * index.html required entry point+ * <other files...> siblings (css / js / json / svg / inline assets)+ * __orkas-meta.json { title, agentId, createdAt } — written by us;+ * `create_artifact` may not supply this name+ * Cloud-synced with the conversation; purged by cid on conversation delete.+ * A *separate* pool from `chat_attachments/` on purpose — attachments are user+ * uploads scanned by `buildAttachmentManifest` to feed the model; artifacts+ * are arbitrary directory trees that must not be scanned that way.+ *+ * Guard rails mirror `chat_attachments.resolveAttachmentAbsPath`:+ * - safeCid / safeArtifactId / safeRelPath reject path separators, traversal+ * names, NULs, empties; relpath segments are validated one by one+ * - the served extension allowlist blocks executables and anything not a web+ * asset; `create_artifact` additionally requires every file to declare a+ * known extension and (for utf8 content) to actually be valid UTF-8+ * - after `path.resolve` the final abs path MUST still live under+ * `<cid>/<artifactId>/` (belt-and-braces anti-traversal)+ * - file must exist and be a regular file+ *+ * If binary assets larger than the per-file cap are ever needed, the right+ * extension is base64-encoded content (already supported below) — never widen+ * the served allowlist to executable types.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import * as crypto from 'node:crypto';++import { artifactDir, chatArtifactCidDir } from '../paths';+import { createLogger } from '../logger';++const log = createLogger('chat_artifacts');++// ── Caps & extension allowlists ──────────────────────────────────────────++export const MAX_ARTIFACT_FILES = 20;+export const MAX_BYTES_PER_FILE = 256 * 1024; // 256 KB+export const MAX_BYTES_TOTAL = 1 * 1024 * 1024; // 1 MB+const MAX_RELPATH_LEN = 200;++// What the `chat-app://` handler is willing to serve. Web assets only — no+// executables, no archives.+const SERVED_EXTS: ReadonlySet<string> = new Set([+ '.html', '.htm', '.js', '.mjs', '.css', '.json', '.map', '.svg', '.xml', '.txt',+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.bmp',+ '.wasm', '.woff', '.woff2', '.ttf', '.otf', '.csv',+]);+// Extensions whose content is text (so `create_artifact` can validate UTF-8+// for utf8-encoded files, and which is the natural shape for hand-written app+// code). Anything else must be supplied as base64.+const TEXT_EXTS: ReadonlySet<string> = new Set([+ '.html', '.htm', '.js', '.mjs', '.css', '.json', '.map', '.svg', '.xml', '.txt', '.csv',+]);++const META_FILENAME = '__orkas-meta.json';+// Reserved virtual path prefix served by the protocol handler (the runtime+// bridge script), never read from disk; `create_artifact` rejects files under+// it so an artifact can't shadow the real bridge.+export const RESERVED_PREFIX = '__orkas/';+export const BRIDGE_RELPATH = '__orkas/bridge.js';++// ── Types ────────────────────────────────────────────────────────────────++export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string };++export interface ArtifactFileInput {+ path: string;+ content: string;+ encoding?: 'utf8' | 'base64';+}++export interface ArtifactMeta {+ title: string;+ agentId: string;+ createdAt: string; // ISO+}++interface ResolveOk { ok: true; absPath: string; mime: string }+interface ResolveErr { ok: false; code: 'bad_input' | 'forbidden' | 'not_found'; error: string }+export type ResolveResult = ResolveOk | ResolveErr;++// ── Safe-name helpers ────────────────────────────────────────────────────++function safeCid(cid: unknown): string {+ if (typeof cid !== 'string' || !cid) throw new Error('cid required');+ if (cid.includes('/') || cid.includes('\\') || cid.includes('\x00') || cid === '.' || cid === '..') {+ throw new Error('invalid cid');+ }+ return cid;+}++function safeArtifactId(id: unknown): string {+ if (typeof id !== 'string' || !id) throw new Error('artifactId required');+ // Generated ids are base64url (alphanumerics + `-` + `_`); be a touch+ // permissive for forward-compat but never allow separators / dots / NUL.+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new Error('invalid artifactId');+ return id;+}++/** Validate + normalise a forward-slash relative path. Returns the normalised+ * form (always `/`-joined, no leading slash). Throws on anything unsafe. */+function safeRelPath(rel: unknown): string {+ if (typeof rel !== 'string') throw new Error('relpath required');+ let s = rel.trim();+ if (s.startsWith('/')) s = s.slice(1);+ if (!s) throw new Error('empty relpath');+ if (s.length > MAX_RELPATH_LEN) throw new Error('relpath too long');+ if (s.includes('\x00') || s.includes('\\')) throw new Error('invalid relpath');+ const segs = s.split('/');+ for (const seg of segs) {+ if (!seg || seg === '.' || seg === '..') throw new Error('invalid relpath segment');+ if (seg.startsWith('.')) throw new Error('relpath segment must not start with "."');+ }+ return segs.join('/');+}++function extOf(name: string): string {+ return path.extname(name).toLowerCase();+}++/** MIME for the `chat-app://` handler. `.js` / `.mjs` resolve to+ * `text/javascript` so Chromium runs them as module scripts. */+export function mimeFor(name: string): string {+ switch (extOf(name)) {+ case '.html': case '.htm': return 'text/html; charset=utf-8';+ case '.js': case '.mjs': return 'text/javascript; charset=utf-8';+ case '.css': return 'text/css; charset=utf-8';+ case '.json': case '.map': return 'application/json; charset=utf-8';+ case '.svg': return 'image/svg+xml';+ case '.xml': return 'application/xml; charset=utf-8';+ case '.txt': case '.csv': return 'text/plain; charset=utf-8';+ case '.png': return 'image/png';+ case '.jpg': case '.jpeg': return 'image/jpeg';+ case '.gif': return 'image/gif';+ case '.webp': return 'image/webp';+ case '.bmp': return 'image/bmp';+ case '.ico': return 'image/x-icon';+ case '.wasm': return 'application/wasm';+ case '.woff': return 'font/woff';+ case '.woff2': return 'font/woff2';+ case '.ttf': return 'font/ttf';+ case '.otf': return 'font/otf';+ default: return 'application/octet-stream';+ }+}++// ── Runtime bridge (served at the reserved virtual path) ─────────────────+//+// Opt-in: an artifact that wants auto-sizing + a tidy send() helper does+// `<script src="__orkas/bridge.js"></script>`. Everything still works without+// it — the app may also `parent.postMessage({__orkasArtifact:true, ...}, '*')`+// directly.+export const BRIDGE_JS = `(function(){+ function post(type, extra){+ try { parent.postMessage(Object.assign({ __orkasArtifact: true, type: type }, extra || {}), '*'); }+ catch (e) {}+ }+ function reportHeight(){+ try {+ var h = Math.max(+ document.documentElement ? document.documentElement.scrollHeight : 0,+ document.body ? document.body.scrollHeight : 0+ );+ if (h > 0) post('resize', { height: h });+ } catch (e) {}+ }+ var api = {+ send: function(payload){ post('submit', { payload: payload }); },+ resize: function(px){ var n = Number(px); post('resize', { height: (isFinite(n) && n > 0) ? n : 0 }); },+ openExternal: function(url){ post('open-external', { url: String(url || '') }); }+ };+ try {+ if (document.readyState === 'loading') window.addEventListener('DOMContentLoaded', reportHeight);+ else setTimeout(reportHeight, 0);+ window.addEventListener('load', reportHeight);+ if (typeof ResizeObserver !== 'undefined') {+ try { new ResizeObserver(reportHeight).observe(document.documentElement); } catch (e) {}+ } else {+ setInterval(reportHeight, 1000);+ }+ } catch (e) {}+ window.orkasArtifact = api;+})();+`;++// ── Public API ───────────────────────────────────────────────────────────++/**+ * Write a new artifact bundle for (uid, cid, agentId). Validates the file set+ * (must include exactly one top-level `index.html`; per-file + total + count+ * caps; extension allowlist; UTF-8 for utf8-encoded text files; relpath+ * safety; no `__orkas/` or `__orkas-meta.json` clobber), writes atomically+ * (temp dir → rename), and stamps `__orkas-meta.json`.+ */+export function createArtifact(+ userId: string,+ cid: string,+ agentId: string,+ input: { title?: unknown; files?: unknown },+): Result<{ artifactId: string; title: string }> {+ let safeConvId: string;+ try { safeConvId = safeCid(cid); }+ catch (err) { return { ok: false, error: (err as Error).message }; }++ const title = (typeof input?.title === 'string' && input.title.trim())+ ? input.title.trim().slice(0, 120)+ : 'Interactive app';++ if (!Array.isArray(input?.files) || input.files.length === 0) {+ return { ok: false, error: 'files: required, must be a non-empty array of { path, content }' };+ }+ if (input.files.length > MAX_ARTIFACT_FILES) {+ return { ok: false, error: `too many files (max ${MAX_ARTIFACT_FILES})` };+ }++ // Validate + materialise every file in memory first; only touch disk once+ // the whole set checks out.+ const prepared: Array<{ rel: string; buf: Buffer }> = [];+ const seen = new Set<string>();+ let hasIndex = false;+ let totalBytes = 0;+ for (const raw of input.files) {+ if (!raw || typeof raw !== 'object') return { ok: false, error: 'each file must be an object { path, content }' };+ const f = raw as ArtifactFileInput;+ let rel: string;+ try { rel = safeRelPath(f.path); }+ catch (err) { return { ok: false, error: `file path ${JSON.stringify((raw as { path?: unknown }).path)}: ${(err as Error).message}` }; }+ if (rel === META_FILENAME || rel.startsWith(RESERVED_PREFIX)) {+ return { ok: false, error: `file path "${rel}" is reserved` };+ }+ const lc = rel.toLowerCase();+ if (seen.has(lc)) return { ok: false, error: `duplicate file path "${rel}"` };+ seen.add(lc);+ const ext = extOf(rel);+ if (!SERVED_EXTS.has(ext)) {+ return { ok: false, error: `file "${rel}": unsupported extension ${ext || '(none)'}` };+ }+ if (typeof f.content !== 'string') return { ok: false, error: `file "${rel}": content must be a string` };+ const encoding = f.encoding === 'base64' ? 'base64' : 'utf8';+ if (encoding === 'utf8' && !TEXT_EXTS.has(ext)) {+ return { ok: false, error: `file "${rel}": ${ext} content must be base64-encoded (set "encoding":"base64")` };+ }+ let buf: Buffer;+ if (encoding === 'base64') {+ if (!/^[A-Za-z0-9+/_\-=\s]*$/.test(f.content)) {+ return { ok: false, error: `file "${rel}": invalid base64 content` };+ }+ buf = Buffer.from(f.content, 'base64'); // tolerant of url-safe alphabet + whitespace+ } else {+ buf = Buffer.from(f.content, 'utf8');+ if (buf.toString('utf8') !== f.content) return { ok: false, error: `file "${rel}": content is not valid UTF-8` };+ }+ if (buf.length > MAX_BYTES_PER_FILE) {+ return { ok: false, error: `file "${rel}": exceeds ${Math.round(MAX_BYTES_PER_FILE / 1024)}KB per-file cap` };+ }+ totalBytes += buf.length;+ if (totalBytes > MAX_BYTES_TOTAL) {+ return { ok: false, error: `bundle exceeds ${Math.round(MAX_BYTES_TOTAL / 1024)}KB total cap` };+ }+ if (rel === 'index.html') hasIndex = true;+ prepared.push({ rel, buf });+ }+ if (!hasIndex) return { ok: false, error: 'files must include a top-level "index.html"' };++ const meta: ArtifactMeta = {+ title,+ agentId: typeof agentId === 'string' ? agentId : '',+ createdAt: new Date().toISOString(),+ };+ const metaBuf = Buffer.from(JSON.stringify(meta, null, 2), 'utf8');++ // Mint an id that isn't already taken (collisions are astronomically+ // unlikely with 9 random bytes, but a few retries cost nothing).+ let artifactId = '';+ let finalDir = '';+ for (let attempt = 0; attempt < 5; attempt++) {+ const candidate = crypto.randomBytes(9).toString('base64url'); // 12 url-safe chars+ const dir = artifactDir(userId, safeConvId, candidate);+ if (!fs.existsSync(dir)) { artifactId = candidate; finalDir = dir; break; }+ }+ if (!artifactId) return { ok: false, error: 'could not allocate an artifact id' };++ const tmpDir = `${finalDir}.tmp-${crypto.randomBytes(4).toString('hex')}`;+ try {+ for (const { rel, buf } of prepared) {+ const dst = path.join(tmpDir, rel);+ fs.mkdirSync(path.dirname(dst), { recursive: true });+ fs.writeFileSync(dst, buf);+ }+ fs.writeFileSync(path.join(tmpDir, META_FILENAME), metaBuf);+ fs.mkdirSync(path.dirname(finalDir), { recursive: true });+ fs.renameSync(tmpDir, finalDir);+ } catch (err) {+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ }+ try { fs.rmSync(finalDir, { recursive: true, force: true }); } catch { /* best-effort */ }+ log.warn(`createArtifact failed user=${userId} cid=${safeConvId}: ${(err as Error).message}`);+ return { ok: false, error: `failed to write artifact: ${(err as Error).message}` };+ }+ log.info(`createArtifact user=${userId} cid=${safeConvId} id=${artifactId} files=${prepared.length} bytes=${totalBytes} agent=${meta.agentId}`);+ return { ok: true, artifactId, title };+}++/** Resolve (uid, cid, artifactId) → the validated, existing artifact directory.+ * Used by `features/saved_apps.ts` to copy a bundle out of the chat pool —+ * it gets the same safe-cid / safe-artifactId guards without re-implementing+ * them. `code` maps to HTTP the same way `resolveArtifactFilePath`'s does. */+export function resolveArtifactDir(+ userId: string,+ cid: string,+ artifactId: string,+): { ok: true; dirPath: string } | { ok: false; code: 'bad_input' | 'not_found'; error: string } {+ let safeConvId: string;+ let safeId: string;+ try { safeConvId = safeCid(cid); safeId = safeArtifactId(artifactId); }+ catch (err) { return { ok: false, code: 'bad_input', error: (err as Error).message }; }+ const dir = artifactDir(userId, safeConvId, safeId);+ let st: fs.Stats;+ try { st = fs.statSync(dir); }+ catch { return { ok: false, code: 'not_found', error: 'artifact not found' }; }+ if (!st.isDirectory()) return { ok: false, code: 'not_found', error: 'artifact not found' };+ return { ok: true, dirPath: dir };+}++/** Read an artifact's metadata, if present. Best-effort (returns undefined on+ * any failure — callers fall back to a generic title). */+export function readArtifactMeta(userId: string, cid: string, artifactId: string): ArtifactMeta | undefined {+ let safeConvId: string;+ let safeId: string;+ try { safeConvId = safeCid(cid); safeId = safeArtifactId(artifactId); }+ catch { return undefined; }+ try {+ const raw = fs.readFileSync(path.join(artifactDir(userId, safeConvId, safeId), META_FILENAME), 'utf8');+ const obj = JSON.parse(raw) as Partial<ArtifactMeta>;+ if (obj && typeof obj === 'object') {+ return {+ title: typeof obj.title === 'string' ? obj.title : 'Interactive app',+ agentId: typeof obj.agentId === 'string' ? obj.agentId : '',+ createdAt: typeof obj.createdAt === 'string' ? obj.createdAt : '',+ };+ }+ } catch { /* missing / malformed */ }+ return undefined;+}++/**+ * Resolve (uid, cid, artifactId, relPath) → an on-disk file to stream, with+ * every guard rail the `chat-app://` protocol handler needs. Empty `relPath`+ * defaults to `index.html`. The reserved virtual path `__orkas/bridge.js` is+ * NOT a disk file — the handler must check for it before calling this and+ * serve `BRIDGE_JS` instead; this function rejects any `__orkas/...` request.+ *+ * Error codes map to HTTP: 'bad_input'→400, 'forbidden'→403, 'not_found'→404.+ */+export function resolveArtifactFilePath(+ userId: string,+ cid: string,+ artifactId: string,+ relPath: string,+): ResolveResult {+ let safeConvId: string;+ let safeId: string;+ try { safeConvId = safeCid(cid); safeId = safeArtifactId(artifactId); }+ catch (err) { return { ok: false, code: 'bad_input', error: (err as Error).message }; }++ let rel: string;+ const trimmed = typeof relPath === 'string' ? relPath.replace(/^\/+/, '').trim() : '';+ if (!trimmed) {+ rel = 'index.html';+ } else {+ try { rel = safeRelPath(trimmed); }+ catch (err) { return { ok: false, code: 'bad_input', error: (err as Error).message }; }+ }+ if (rel.startsWith(RESERVED_PREFIX)) {+ // Only `__orkas/bridge.js` exists, and the handler serves it before+ // reaching here; anything else under `__orkas/` is nothing.+ return { ok: false, code: 'not_found', error: 'not found' };+ }+ const ext = extOf(rel);+ if (!SERVED_EXTS.has(ext)) {+ return { ok: false, code: 'forbidden', error: `extension not served: ${ext || '(none)'}` };+ }++ const root = path.resolve(artifactDir(userId, safeConvId, safeId));+ const abs = path.resolve(root, rel);+ const relCheck = path.relative(root, abs);+ if (relCheck.startsWith('..') || path.isAbsolute(relCheck)) {+ return { ok: false, code: 'forbidden', error: 'path traversal blocked' };+ }+ let st: fs.Stats;+ try { st = fs.statSync(abs); }+ catch { return { ok: false, code: 'not_found', error: 'not found' }; }+ if (!st.isFile()) return { ok: false, code: 'not_found', error: 'not a file' };+ return { ok: true, absPath: abs, mime: mimeFor(rel) };+}++/** Remove every artifact for a conversation (`chat_artifacts/<cid>/`). Returns+ * the number of artifact directories removed. Called from+ * `chats.deleteConversation` next to `chat_attachments.purgeByCid`. */+export async function purgeByCid(userId: string, cid: string): Promise<number> {+ let safeConvId: string;+ try { safeConvId = safeCid(cid); }+ catch { return 0; }+ const dir = chatArtifactCidDir(userId, safeConvId);+ let count = 0;+ try {+ if (fs.existsSync(dir)) {+ try { count = fs.readdirSync(dir).filter((n) => !n.startsWith('.')).length; }+ catch { /* ignore */ }+ fs.rmSync(dir, { recursive: true, force: true });+ }+ } catch (err) { log.warn(`purgeByCid(${cid}): ${(err as Error).message}`); }+ return count;+}diff --git a/src/main/features/chats.ts b/src/main/features/chats.tsindex a3cfe9ab..683e6b7b 100644--- a/src/main/features/chats.ts+++ b/src/main/features/chats.ts@@ -246,6 +246,12 @@ export async function deleteConversation(userId: string, cid: string): Promise<bif (typeof att?.purgeByCid === 'function') await att.purgeByCid(userId, cid);} catch (err) { log.warn(`purge attachments user=${userId} cid=${cid}: ${(err as Error).message}`); }+ // Purge interactive web-app artifacts (chat_artifacts/<cid>/).+ try {+ const art = require('./chat_artifacts');+ if (typeof art?.purgeByCid === 'function') await art.purgeByCid(userId, cid);+ } catch (err) { log.warn(`purge artifacts user=${userId} cid=${cid}: ${(err as Error).message}`); }+// Drop CLI session bindings — the next time this cid is reused (or// a same-id collision, defensive), CLI agents start fresh. Their// own machine-local session files (~/.claude/...) are left alone;diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.tsindex bc7f806e..de91865c 100644--- a/src/main/features/group_chat/bus.ts+++ b/src/main/features/group_chat/bus.ts@@ -272,6 +272,10 @@ export interface EnqueueParams {form?: ChatFormPayload;created_agents?: Array<{ agent_id: string; name: string; kind?: 'created' | 'updated' }>;created_skills?: Array<{ skill_id: string; name: string; kind?: 'created' | 'updated' }>;+ /** Interactive web-app artifacts produced this turn (via `create_artifact`).+ * `agent_id` is the producing actor — the renderer routes a user→artifact+ * interaction result back to it. */+ artifacts?: Array<{ id: string; title: string; agent_id: string }>;plan_announcement?: boolean;/** Override resolved recipients (commander emitting plan announcement* uses this to force `to=[user]`). Otherwise router decides. */@@ -568,6 +572,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro...(params.form ? { form: params.form } : {}),...(params.created_agents && params.created_agents.length ? { created_agents: params.created_agents } : {}),...(params.created_skills && params.created_skills.length ? { created_skills: params.created_skills } : {}),+ ...(params.artifacts && params.artifacts.length ? { artifacts: params.artifacts } : {}),...(params.plan_announcement ? { plan_announcement: true } : {}),...(params.dispatch ? { dispatch: true } : {}),...(params.process && params.process.length ? { process: params.process } : {}),@@ -930,6 +935,12 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis// "ours" → overwrite in place. Files the user pre-created remain foreign// and still get `-2 / -3 / ...` suffixed via `util/uniquify-path`.const hasProducedPath = (absPath: string) => state.producedPaths.has(absPath);+ // Interactive web-app artifacts created via `create_artifact` this turn.+ // Attached to the actor's end-of-turn message so the renderer embeds each+ // one as a sandboxed `<iframe>` (`chat-app://`); `agent_id` = this actor,+ // the routing target for a user→artifact interaction result.+ const turnArtifacts: Array<{ id: string; title: string }> = [];+ const onArtifactCreated = (a: { id: string; title: string }) => { turnArtifacts.push(a); };let finalText = '';// Mirror of every text delta we forwarded to the renderer this turn.// Used as the salvage source when the user aborts mid-stream — the@@ -1071,6 +1082,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis...(turnProjectId ? { projectId: turnProjectId } : {}),onFileWritten,hasProducedPath,+ onArtifactCreated,cacheRetention: 'short',abortSignal: w.abortController.signal,readOnlyExtraRoots: [...skillRoots, ...agentRoots],@@ -1384,6 +1396,16 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis// user clearly saw it during streaming. Promoting to persist here lets// the enqueue carry `processItems` into the persisted message so reload// / history view still surfaces what the actor did before stopping.+ // A `create_artifact` call is a user-visible side effect the plan executor+ // doesn't know about (it never sees the artifact list). If the turn would+ // otherwise be silent — e.g. a commander turn that only produced an+ // artifact — promote it to persist so the embedded iframe surfaces. Same+ // rationale as the abort/process-trail promotion below; the artifact list+ // itself is attached at enqueue time, independent of the executor outcome.+ if (turnArtifacts.length > 0 && outcome.kind === 'silent') {+ outcome = { kind: 'persist', text: '' };+ }+if (aborted) {if (outcome.kind === 'silent' && processItems.length > 0) {outcome = { kind: 'persist', text: '' };@@ -1407,6 +1429,9 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis...(outcome.createdSkills && outcome.createdSkills.length? { created_skills: outcome.createdSkills.map((s) => ({ skill_id: s.skill_id, name: s.name })) }: {}),+ ...(turnArtifacts.length+ ? { artifacts: turnArtifacts.map((a) => ({ id: a.id, title: a.title, agent_id: actor.id })) }+ : {}),...(pendingPlan && actor.kind === 'commander'? { plan_announcement: true, forceTo: [USER_ID] } : {}),...(processItems.length ? { process: processItems } : {}),diff --git a/src/main/features/group_chat/visibility.ts b/src/main/features/group_chat/visibility.tsindex 9e3b7341..f9dcfebc 100644--- a/src/main/features/group_chat/visibility.ts+++ b/src/main/features/group_chat/visibility.ts@@ -57,6 +57,12 @@ export interface GroupMessage {/** Mirror of `created_agents` for skills — populated when the commander's* final text contained one or more `<skill>` containers. */created_skills?: Array<{ skill_id: string; name: string; kind?: 'created' | 'updated' }>;+ /** Interactive web-app artifacts produced this turn via `create_artifact`.+ * `id` keys `chat_artifacts/<cid>/<id>/`; `agent_id` is the producing actor+ * (`'commander'` or an agent id) — the renderer routes a user→artifact+ * interaction result back to it. Rendered as a sandboxed `<iframe>`+ * (`chat-app://`) at the bottom of the bubble. */+ artifacts?: Array<{ id: string; title: string; agent_id: string }>;/** Marks this message as a plan announcement (rendered with a folded* plan card in UI). Set by `plan_set` first-time emission. */plan_announcement?: boolean;diff --git a/src/main/features/saved_apps.ts b/src/main/features/saved_apps.tsnew file mode 100644index 00000000..bbb0f674--- /dev/null+++ b/src/main/features/saved_apps.ts@@ -0,0 +1,325 @@+/**+ * "My Apps" — user-kept copies of `create_artifact` interactive web apps.+ *+ * An artifact created in chat lives in `<uid>/cloud/chat_artifacts/<cid>/<id>/`+ * and is purged when the conversation is deleted. The artifact card's `⋯` →+ * "Save" copies the bundle into a new persistent pool here:+ * `<uid>/cloud/saved_apps/<appId>/{index.html, ...siblings, __orkas-meta.json}`+ * Cloud-synced; conversation-independent; never auto-purged (only the user's+ * explicit delete from the My Apps tab removes one). The files are served+ * read-only by being opened in the system browser via `shell.openPath` on+ * `index.html` (a `file://` view — same mechanism as the artifact card's+ * "open in browser"; the `chat-app://` protocol and `__orkas/bridge.js` are+ * NOT involved here).+ *+ * Guard rails: `safeAppId` rejects separators / traversal names; the source+ * dir is resolved through `chatArtifacts.resolveArtifactDir` (which reuses the+ * artifact pool's safe-cid / safe-artifactId checks); `resolveSavedAppIndex`+ * runs a `path.relative` traversal guard before handing a path to the IPC+ * layer for `shell.openPath`.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import * as crypto from 'node:crypto';++import { userSavedAppsDir, savedAppDir } from '../paths';+import * as chatArtifacts from './chat_artifacts';+import * as chats from './chats';+import * as chatAttachments from './chat_attachments';+import { t } from '../i18n';+import { createLogger } from '../logger';++const log = createLogger('saved_apps');++const META_FILENAME = '__orkas-meta.json';+const MAX_TITLE_LEN = 120;+const DEFAULT_TITLE = 'Interactive app';++// Source files that go into the editing bundle verbatim (everything in an+// artifact's served-extension set that is text). Anything else (png / woff /+// wasm / …) becomes a one-line `[binary asset …]` placeholder — it can't be+// represented in a text `.md` bundle, and changing it means re-supplying it+// via `create_artifact` with `"encoding":"base64"` anyway.+const TEXT_LIKE_EXTS: ReadonlySet<string> = new Set([+ '.html', '.htm', '.js', '.mjs', '.css', '.json', '.map', '.svg', '.xml', '.txt', '.csv',+]);+const SOURCE_BUNDLE_NAME = 'app-source.md';++export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string };++export interface SavedAppMeta {+ title: string;+ sourceCid: string;+ sourceArtifactId: string;+ savedAt: string; // ISO+}++export interface SavedAppListItem {+ id: string;+ title: string;+ savedAt: string;+ sourceCid: string;+}++// ── Helpers ──────────────────────────────────────────────────────────────++function safeAppId(id: unknown): string {+ if (typeof id !== 'string' || !id) throw new Error('appId required');+ // Generated ids are base64url (alphanumerics + `-` + `_`); never allow+ // separators / dots / NUL.+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new Error('invalid appId');+ return id;+}++function sanitiseTitle(t: unknown): string {+ if (typeof t === 'string') {+ const s = t.trim();+ if (s) return s.slice(0, MAX_TITLE_LEN);+ }+ return DEFAULT_TITLE;+}++function writeMeta(dir: string, meta: SavedAppMeta): void {+ fs.writeFileSync(path.join(dir, META_FILENAME), Buffer.from(JSON.stringify(meta, null, 2), 'utf8'));+}++// ── Public API ───────────────────────────────────────────────────────────++/** Copy a chat artifact bundle into a new `saved_apps/<appId>/`. */+export function saveFromArtifact(userId: string, cid: string, artifactId: string): Result<{ id: string; title: string }> {+ const resolved = chatArtifacts.resolveArtifactDir(userId, cid, artifactId);+ if (!resolved.ok) return { ok: false, error: (resolved as { error?: string }).error || 'artifact not found' };+ const srcDir = (resolved as { dirPath: string }).dirPath;++ const srcMeta = chatArtifacts.readArtifactMeta(userId, cid, artifactId);+ const title = sanitiseTitle(srcMeta?.title);++ // Mint a free appId (collisions are astronomically unlikely with 9 random+ // bytes; a few retries cost nothing).+ let appId = '';+ let destDir = '';+ for (let i = 0; i < 5; i++) {+ const candidate = crypto.randomBytes(9).toString('base64url'); // 12 url-safe chars+ const d = savedAppDir(userId, candidate);+ if (!fs.existsSync(d)) { appId = candidate; destDir = d; break; }+ }+ if (!appId) return { ok: false, error: 'could not allocate an app id' };++ const tmpDir = `${destDir}.tmp-${crypto.randomBytes(4).toString('hex')}`;+ try {+ // Copy everything except the source `__orkas-meta.json` (we write a fresh+ // one stamped with the source provenance).+ fs.cpSync(srcDir, tmpDir, {+ recursive: true,+ filter: (src) => path.basename(src) !== META_FILENAME,+ });+ if (!fs.existsSync(path.join(tmpDir, 'index.html'))) {+ throw new Error('source artifact is missing index.html');+ }+ const meta: SavedAppMeta = {+ title,+ sourceCid: typeof cid === 'string' ? cid : '',+ sourceArtifactId: typeof artifactId === 'string' ? artifactId : '',+ savedAt: new Date().toISOString(),+ };+ writeMeta(tmpDir, meta);+ fs.mkdirSync(path.dirname(destDir), { recursive: true });+ fs.renameSync(tmpDir, destDir);+ } catch (err) {+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ }+ try { fs.rmSync(destDir, { recursive: true, force: true }); } catch { /* best-effort */ }+ log.warn(`saveFromArtifact failed user=${userId} cid=${cid} artifact=${artifactId}: ${(err as Error).message}`);+ return { ok: false, error: `failed to save app: ${(err as Error).message}` };+ }+ log.info(`saveFromArtifact user=${userId} appId=${appId} <- cid=${cid} artifact=${artifactId}`);+ return { ok: true, id: appId, title };+}++/** List the user's saved apps, sorted A→Z by title (CLAUDE.md §8 inventory rule). */+export function listSavedApps(userId: string): SavedAppListItem[] {+ const root = userSavedAppsDir(userId);+ let names: string[];+ try { names = fs.readdirSync(root); }+ catch { return []; } // pool dir not created yet+ const items: SavedAppListItem[] = [];+ for (const name of names) {+ if (name.startsWith('.')) continue;+ let appId: string;+ try { appId = safeAppId(name); } catch { continue; }+ const dir = savedAppDir(userId, appId);+ try { if (!fs.statSync(dir).isDirectory()) continue; } catch { continue; }+ let meta: Partial<SavedAppMeta> = {};+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, META_FILENAME), 'utf8')) || {}; }+ catch (err) { log.warn(`listSavedApps: bad meta for ${appId}: ${(err as Error).message}`); }+ items.push({+ id: appId,+ title: typeof meta.title === 'string' && meta.title.trim() ? meta.title : DEFAULT_TITLE,+ savedAt: typeof meta.savedAt === 'string' ? meta.savedAt : '',+ sourceCid: typeof meta.sourceCid === 'string' ? meta.sourceCid : '',+ });+ }+ items.sort((a, b) =>+ (a.title || a.id).localeCompare(b.title || b.id, undefined, { sensitivity: 'base', numeric: true }));+ return items;+}++/** Resolve a saved app's `index.html` absolute path (for `shell.openPath`).+ * `code` maps to HTTP the same way the artifact resolvers' does. */+export function resolveSavedAppIndex(+ userId: string,+ appId: string,+): { ok: true; absPath: string } | { ok: false; code: 'bad_input' | 'not_found'; error: string } {+ let safeId: string;+ try { safeId = safeAppId(appId); }+ catch (err) { return { ok: false, code: 'bad_input', error: (err as Error).message }; }+ const root = path.resolve(savedAppDir(userId, safeId));+ const abs = path.resolve(root, 'index.html');+ const rel = path.relative(root, abs);+ if (rel.startsWith('..') || path.isAbsolute(rel)) {+ return { ok: false, code: 'bad_input', error: 'path traversal blocked' };+ }+ let st: fs.Stats;+ try { st = fs.statSync(abs); }+ catch { return { ok: false, code: 'not_found', error: 'app not found' }; }+ if (!st.isFile()) return { ok: false, code: 'not_found', error: 'app not found' };+ return { ok: true, absPath: abs };+}++/** Rename a saved app (rewrites `__orkas-meta.json`). */+export function renameSavedApp(userId: string, appId: string, title: unknown): Result<{ title: string }> {+ let safeId: string;+ try { safeId = safeAppId(appId); }+ catch (err) { return { ok: false, error: (err as Error).message }; }+ if (typeof title !== 'string' || !title.trim()) return { ok: false, error: 'title required' };+ const dir = savedAppDir(userId, safeId);+ let meta: SavedAppMeta;+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, META_FILENAME), 'utf8')); }+ catch (err) { return { ok: false, error: `app not found: ${(err as Error).message}` }; }+ meta.title = sanitiseTitle(title);+ try { writeMeta(dir, meta); }+ catch (err) { return { ok: false, error: `failed to rename: ${(err as Error).message}` }; }+ log.info(`renameSavedApp user=${userId} appId=${safeId} title=${JSON.stringify(meta.title)}`);+ return { ok: true, title: meta.title };+}++/** Delete a saved app (`rm -rf saved_apps/<appId>/`). */+export function deleteSavedApp(userId: string, appId: string): Result {+ let safeId: string;+ try { safeId = safeAppId(appId); }+ catch (err) { return { ok: false, error: (err as Error).message }; }+ const dir = savedAppDir(userId, safeId);+ try {+ if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });+ } catch (err) {+ log.warn(`deleteSavedApp(${safeId}): ${(err as Error).message}`);+ return { ok: false, error: `failed to delete: ${(err as Error).message}` };+ }+ log.info(`deleteSavedApp user=${userId} appId=${safeId}`);+ return { ok: true };+}++// ── "Edit in a new conversation" ─────────────────────────────────────────++/** Recursively list a saved app's file paths (relative to its dir), sorted. */+function listAppFilesRel(dir: string): string[] {+ const out: string[] = [];+ const walk = (rel: string): void => {+ let entries: fs.Dirent[];+ try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }); }+ catch { return; }+ for (const e of entries) {+ const childRel = rel ? `${rel}/${e.name}` : e.name;+ if (e.isDirectory()) walk(childRel);+ else if (e.isFile()) out.push(childRel);+ }+ };+ walk('');+ out.sort((a, b) => a.localeCompare(b));+ return out;+}++/** Build the single-`.md` source bundle handed to the editing conversation as+ * an attachment. Plain `FILE:` rules (not fenced code blocks) so the app's own+ * source — which may contain ``` — can't break the bundle. Binary assets are+ * represented as placeholder lines (a text bundle can't carry their bytes). */+function buildSourceBundle(dir: string, title: string): string {+ const files = listAppFilesRel(dir).filter((rel) => rel !== META_FILENAME);+ const lines: string[] = [+ `# Interactive app source — "${title}"`,+ '',+ 'This is the current source of a self-contained interactive web app (originally produced by the `create_artifact` tool). To modify it: read the files below, then call `create_artifact` again with the updated `files` array — it must still include a top-level `index.html`, the app runs offline (inline your CSS/JS or reference sibling files by relative URL), and the result is embedded in a sandboxed iframe.',+ '',+ ];+ for (const rel of files) {+ const abs = path.join(dir, rel);+ lines.push(`========== FILE: ${rel} ==========`);+ if (TEXT_LIKE_EXTS.has(path.extname(rel).toLowerCase())) {+ let content = '<could not read this file>';+ try { content = fs.readFileSync(abs, 'utf8'); } catch { /* keep placeholder */ }+ lines.push(content);+ } else {+ let kb = 1;+ try { kb = Math.max(1, Math.round(fs.statSync(abs).size / 1024)); } catch { /* ignore */ }+ lines.push(`[binary asset: ${rel} — ~${kb} KB; kept from the original app. To change it, re-supply it via create_artifact with "encoding":"base64".]`);+ }+ lines.push('');+ }+ lines.push('========== END ==========');+ lines.push('');+ return lines.join('\n');+}++/**+ * Open a saved app for editing: create a fresh normal conversation, drop the+ * app's source in as a single `app-source.md` attachment, and return the conv+ * so the renderer can navigate to it + pre-fill a draft. On any failure after+ * the conversation is created, the half-built conversation is deleted so no+ * orphan is left behind. "Edit" is a fork-and-modify flow — the conversation's+ * `create_artifact` produces a new artifact; the original saved app is+ * untouched.+ */+export async function openForEditing(+ userId: string,+ appId: string,+): Promise<Result<{ conversation: unknown; title: string; sourceFileName: string }>> {+ let safeId: string;+ try { safeId = safeAppId(appId); }+ catch (err) { return { ok: false, error: (err as Error).message }; }+ const dir = savedAppDir(userId, safeId);+ try { if (!fs.statSync(dir).isDirectory()) throw new Error('not a directory'); }+ catch { return { ok: false, error: 'app not found' }; }+ if (!fs.existsSync(path.join(dir, 'index.html'))) {+ return { ok: false, error: 'app is missing index.html' };+ }++ let title = DEFAULT_TITLE;+ try {+ const m = JSON.parse(fs.readFileSync(path.join(dir, META_FILENAME), 'utf8'));+ if (m && typeof m.title === 'string' && m.title.trim()) title = m.title;+ } catch { /* fallback */ }++ const bundle = buildSourceBundle(dir, title);++ let conv: Awaited<ReturnType<typeof chats.createConversation>>;+ try {+ conv = await chats.createConversation(userId, {+ kind: 'normal',+ title: t('apps.edit_conv_title', { name: title }),+ });+ } catch (err) {+ log.warn(`openForEditing: createConversation failed user=${userId} appId=${safeId}: ${(err as Error).message}`);+ return { ok: false, error: `failed to create a conversation: ${(err as Error).message}` };+ }++ const up = await chatAttachments.uploadAttachment(userId, conv.conversation_id, SOURCE_BUNDLE_NAME, Buffer.from(bundle, 'utf8'));+ if (!up.ok) {+ // Roll back the conversation we just created so no empty conv is orphaned.+ try { await chats.deleteConversation(userId, conv.conversation_id); }+ catch (err) { log.warn(`openForEditing: rollback deleteConversation failed: ${(err as Error).message}`); }+ return { ok: false, error: (up as { error?: string }).error || 'failed to attach the app source' };+ }+ const sourceFileName = ((up as { info?: { name?: string } }).info?.name) || SOURCE_BUNDLE_NAME;+ log.info(`openForEditing user=${userId} appId=${safeId} -> cid=${conv.conversation_id} source=${sourceFileName}`);+ return { ok: true, conversation: conv, title, sourceFileName };+}diff --git a/src/main/index.ts b/src/main/index.tsindex dd82d67d..0c6d1ac1 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -56,6 +56,19 @@ protocol.registerSchemesAsPrivileged([scheme: 'chat-media',privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true },},+ // `chat-app://cid/<encCid>/<encArtifactId>/<relpath>` — serves the files of+ // an LLM-generated interactive web-app artifact out of+ // `<uid>/cloud/chat_artifacts/<cid>/<artifactId>/`, embedded in a sandboxed+ // `<iframe>` in the chat bubble (renderer `modules/chat-artifact.js`).+ // `standard:true` gives the iframe a real origin (`chat-app://cid`) so it+ // can use `<script type="module">` / same-origin `fetch` of sibling files /+ // `localStorage`; `secure:true` lets the `file://` renderer frame it+ // without a mixed-content block (same as `kb-file://`). `stream:true` for+ // the Range-aware streamed body (see `serveFileRange`).+ {+ scheme: 'chat-app',+ privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true },+ },]);// WS_ROOT env injection (`~/.orkas/data` on mac/linux; Windows pinned@@ -108,6 +121,7 @@ import * as appConfig from './features/config';import * as reflectionTrigger from './features/reflection-trigger';import * as scheduledTasks from './features/scheduled_tasks';import * as chatAttachments from './features/chat_attachments';+import * as chatArtifacts from './features/chat_artifacts';function createWindow(): BrowserWindow {const dev = !app.isPackaged;@@ -532,6 +546,81 @@ function registerChatMediaProtocol(): void {});}+// `chat-app://cid/<encCid>/<encArtifactId>/<relpath...>` — streams the files+// of an LLM-generated interactive web-app artifact out of the active user's+// `<uid>/cloud/chat_artifacts/<cid>/<artifactId>/`. Read-only; every request+// is filtered through `chatArtifacts.resolveArtifactFilePath` (safe-cid /+// safe-artifactId / safe-relpath + `path.relative` traversal guard + served+// extension allowlist + regular-file check). The reserved virtual relpath+// `__orkas/bridge.js` is served from the in-memory `BRIDGE_JS` constant, not+// from disk. Fixed host (`cid`) sidesteps URL-parser divergence the same way+// `chat-media://cid/...` does. `Access-Control-Allow-Origin: *` is set+// defensively — `chat-app://` URLs are only issuable from inside this app.+function _withArtifactCors(resp: Response): Response {+ // Re-wrap so we can add the header without mutating the shared+ // `serveFileRange` helper (kb-file / chat-media must not change). The body+ // stream is passed through untouched — Chromium consumes it once.+ const headers = new Headers(resp.headers);+ headers.set('Access-Control-Allow-Origin', '*');+ return new Response(resp.body, { status: resp.status, statusText: resp.statusText, headers });+}++function registerChatAppProtocol(): void {+ protocol.handle('chat-app', async (request) => {+ const reqUrl = request.url;+ try {+ let u: URL;+ try { u = new URL(reqUrl); }+ catch {+ log.warn('chat-app: unparseable URL', { reqUrl });+ return new Response('bad request', { status: 400 });+ }+ if (u.host.toLowerCase() !== 'cid') {+ log.warn('chat-app: unknown host', { reqUrl, host: u.host });+ return new Response('bad request', { status: 400 });+ }+ // pathname is `/<encCid>/<encArtifactId>/<relpath...>` (always leading+ // slash, URL-encoded). Decode the whole thing then split — decoding+ // first then splitting on `/` is wrong if a relpath segment contained+ // an encoded slash, but artifact file paths never do (safeRelPath+ // rejects `\0` / `\`, and an encoded `/` would just be a path+ // separator anyway); decode per-segment to be precise.+ const rawSegs = (u.pathname || '').replace(/^\/+/, '').split('/');+ const cid = rawSegs[0] ? decodeURIComponent(rawSegs[0]) : '';+ const artifactId = rawSegs[1] ? decodeURIComponent(rawSegs[1]) : '';+ const relPath = rawSegs.slice(2).map((s) => (s ? decodeURIComponent(s) : '')).join('/');+ if (!cid || !artifactId) {+ log.warn('chat-app: bad URL (need cid + artifactId)', { reqUrl });+ return new Response('bad request', { status: 400 });+ }++ // Reserved virtual path: the runtime bridge script (not on disk).+ if (relPath === chatArtifacts.BRIDGE_RELPATH) {+ return _withArtifactCors(new Response(chatArtifacts.BRIDGE_JS, {+ headers: { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'private, max-age=60' },+ }));+ }++ const uid = users.getActiveUserId();+ const resolved = chatArtifacts.resolveArtifactFilePath(uid, cid, artifactId, relPath);+ if (!resolved.ok) {+ // Cast in the error branch — `strictNullChecks: false` keeps the+ // whole union here (same workaround as the chat-media handler above).+ const code = (resolved as { code?: string }).code;+ const errMsg = (resolved as { error?: string }).error;+ log.warn('chat-app: reject', { reqUrl, code, error: errMsg });+ return new Response(String(errMsg || code || 'error'), { status: _statusFor(code) });+ }+ const st = fs.statSync(resolved.absPath);+ log.info('chat-app: serving', { abs: resolved.absPath, mime: resolved.mime, bytes: st.size });+ return _withArtifactCors(serveFileRange(request, resolved.absPath, resolved.mime, st.size));+ } catch (err) {+ log.warn('chat-app serve failed', { reqUrl, error: (err as Error).message });+ return new Response('error', { status: 500 });+ }+ });+}+// Single-instance lock prevents double-launch from duplicating the backend.const gotLock = app.requestSingleInstanceLock();if (!gotLock) {@@ -571,6 +660,7 @@ if (!gotLock) {}registerKbFileProtocol();registerChatMediaProtocol();+ registerChatAppProtocol();registerIpc();createWindow();diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 4e23079c..f9041f6d 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -29,6 +29,8 @@ import * as contexts from '../features/contexts';import * as kbVector from '../features/kb_vector';import * as kbIndexer from '../features/kb_indexer';import * as chatAttachments from '../features/chat_attachments';+import * as chatArtifacts from '../features/chat_artifacts';+import * as savedApps from '../features/saved_apps';import * as search from '../features/search';import * as auth from '../features/auth';import * as imageAuth from '../features/image_auth';@@ -383,6 +385,64 @@ const invokeHandlers: Record<string, InvokeHandler> = {return chatAttachments.adoptDraftAttachments(ctx.userId, from_cid, to_cid);},+ // ── Chat artifacts (interactive web-app bundles, served via chat-app://) ──+ // Open the artifact's index.html in the OS default browser (a `file://`+ // URL via `shell.openPath`). Path is resolved through+ // `chatArtifacts.resolveArtifactFilePath` so caller-supplied cid /+ // artifactId can only ever reach a file inside that artifact's pool.+ 'conversations.artifacts.openExternal': async ({ cid, artifactId }, ctx) => {+ if (!safeId(cid)) throw new Error('invalid cid');+ const r = chatArtifacts.resolveArtifactFilePath(ctx.userId, String(cid), String(artifactId || ''), 'index.html');+ if (!r.ok) throw new Error((r as { error?: string }).error || 'artifact not found');+ const absPath = (r as { absPath: string }).absPath;+ const err = await shell.openPath(absPath);+ if (err) throw new Error(err);+ return { ok: true, path: absPath };+ },+ // Copy a chat artifact into the persistent "My Apps" pool+ // (`<uid>/cloud/saved_apps/<appId>/`). Surfaced as the artifact card's+ // `⋯` → "保存".+ 'conversations.artifacts.save': async ({ cid, artifactId }, ctx) => {+ if (!safeId(cid)) throw new Error('invalid cid');+ const r = savedApps.saveFromArtifact(ctx.userId, String(cid), String(artifactId || ''));+ if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to save app');+ return { ok: true, id: (r as { id: string }).id, title: (r as { title: string }).title };+ },++ // ── Saved apps ("My Apps" — user-kept copies of create_artifact bundles) ──+ 'savedApps.list': async (_payload, ctx) => ({ apps: savedApps.listSavedApps(ctx.userId) }),+ 'savedApps.openExternal': async ({ appId }, ctx) => {+ const r = savedApps.resolveSavedAppIndex(ctx.userId, String(appId || ''));+ if (!r.ok) throw new Error((r as { error?: string }).error || 'app not found');+ const absPath = (r as { absPath: string }).absPath;+ const err = await shell.openPath(absPath);+ if (err) throw new Error(err);+ return { ok: true, path: absPath };+ },+ // Open a saved app for editing — creates a fresh conversation with the+ // app's source bundled in as an `app-source.md` attachment. The renderer+ // navigates to it + pre-fills a draft.+ 'savedApps.openForEditing': async ({ appId }, ctx) => {+ const r = await savedApps.openForEditing(ctx.userId, String(appId || ''));+ if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to open the app for editing');+ return {+ ok: true,+ conversation: (r as { conversation: unknown }).conversation,+ title: (r as { title: string }).title,+ sourceFileName: (r as { sourceFileName: string }).sourceFileName,+ };+ },+ 'savedApps.rename': async ({ appId, title }, ctx) => {+ const r = savedApps.renameSavedApp(ctx.userId, String(appId || ''), title);+ if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to rename');+ return { ok: true, title: (r as { title: string }).title };+ },+ 'savedApps.delete': async ({ appId }, ctx) => {+ const r = savedApps.deleteSavedApp(ctx.userId, String(appId || ''));+ if (!r.ok) throw new Error((r as { error?: string }).error || 'failed to delete');+ return { ok: true };+ },+// ── Agents ──'agents.list': async () => ({ agents: await agents.listAgents() }),diff --git a/src/main/model/client.ts b/src/main/model/client.tsindex b52ca5e9..b7022d77 100644--- a/src/main/model/client.ts+++ b/src/main/model/client.ts@@ -119,6 +119,11 @@ export interface ChatOptions {* collision (rename to `-2 / -3 / ...`). When undefined, every* pre-existing path at the target is treated as a foreign collision. */hasProducedPath?: (absPath: string) => boolean;+ /** Fired after each successful `create_artifact` call with the new+ * artifact's id + title. `features/group_chat` collects these per turn+ * and attaches a `artifacts[]` list to the assistant message so the+ * renderer embeds each interactive web-app artifact in the bubble. */+ onArtifactCreated?: (a: { id: string; title: string }) => void;/** Prompt-cache TTL policy. Undefined lets pi-ai pick its default* (`"short"` = Anthropic 5m / OpenAI in-memory). `"long"` opts into* extended retention (Anthropic 1h with 2x write premium / OpenAI 24h).diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.tsindex 1525cb77..71b7499b 100644--- a/src/main/model/core-agent/client.ts+++ b/src/main/model/core-agent/client.ts@@ -91,6 +91,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<StprojectId,onFileWritten,hasProducedPath,+ onArtifactCreated,cacheRetention,thinkingLevel,} = opts;@@ -186,6 +187,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St...(readOnlyExtraRoots && readOnlyExtraRoots.length ? { readOnlyExtraRoots } : {}),...(onFileWritten ? { onFileWritten } : {}),...(hasProducedPath ? { hasProducedPath } : {}),+ ...(onArtifactCreated ? { onArtifactCreated } : {}),});const { runner, providerId, modelId } = built;diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.tsindex 88b112b4..f72ef67a 100644--- a/src/main/model/core-agent/local-tools.ts+++ b/src/main/model/core-agent/local-tools.ts@@ -52,6 +52,7 @@ import { isPathAllowed } from '../../util/path-sandbox';import { kindOf } from '../../features/file_indexer';import { getWorkspacePath } from '../../features/user_workspace';import { chatAttachmentDir } from '../../paths';+import * as chatArtifacts from '../../features/chat_artifacts';import { createLogger } from '../../logger';const log = createLogger('local-tools');@@ -64,8 +65,15 @@ export interface LocalToolsOpts {userId?: string;/** Current conversation id. Used by `edit_file` to add the current* conv's attachment dir to the sandbox. Without it, only the workspace- * (+ extraRoots) is editable. */+ * (+ extraRoots) is editable. Also the storage key for `create_artifact`+ * (artifacts live under `chat_artifacts/<cid>/`); the tool errors out+ * when it's missing. */cid?: string;+ /** The actor id producing this turn (an agent's id, or `''` for the+ * group-chat commander / edit chats). Stamped into `create_artifact`'s+ * metadata so the renderer knows which actor to route an interaction+ * result back to. */+ agentId?: string;/** Project id of the current conversation, when it belongs to one.* Threaded through from group_chat at runTurn so workspace resolution* picks up the project-scoped selection (per CLAUDE.md projects feature).@@ -79,6 +87,10 @@ export interface LocalToolsOpts {* edit_file, markdown_to_pdf, html_to_pdf). Lets chats.ts surface* produced files to the UI. */onFileWritten?: (absPath: string) => void;+ /** Fires after a successful `create_artifact` call. The caller (group_chat+ * bus) collects these per turn and attaches `message.artifacts` to the+ * assistant record so the renderer embeds each one in the bubble. */+ onArtifactCreated?: (a: { id: string; title: string }) => void;/** Predicate: returns true when the given absolute path was already* written by this caller in the current scope (typically: a Set* populated by `onFileWritten` this turn). When true, the wrapped@@ -467,15 +479,105 @@ function createHtmlToPdfTool(opts: LocalToolsOpts): AgentTool {};}+/** `create_artifact` — build an interactive multi-file web app shown live+ * inside the chat bubble (sandboxed `<iframe>` over the `chat-app://`+ * protocol). Permission-gated like the other write-style tools; writes only+ * into the current conversation's artifact pool (`chat_artifacts/<cid>/`),+ * never the workspace. On success fires `onArtifactCreated` so the caller+ * attaches it to the assistant message record. */+function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {+ return {+ name: 'create_artifact',+ description:+ 'Build a small interactive web app (self-contained HTML/CSS/JS) that is rendered LIVE and clickable inside this chat reply, embedded in a sandboxed iframe.\n' ++ '\n' ++ 'Use it for: dashboards, calculators, data visualizations, configurators, simulators, quizzes, mini-games — anything the user should interact with directly. Do NOT use it for static documents (use `html_to_pdf`) or images (use `generate_image`).\n' ++ '\n' ++ 'Input: `{ title?, files: [{ path, content, encoding? }, ...] }`\n' ++ ' - `files` MUST include a top-level `index.html` (the entry point). Up to 20 files, 256 KB per file, 1 MB total.\n' ++ ' - `path` is a forward-slash relative path (e.g. `index.html`, `assets/app.js`). No `..`, no leading `/`, no dotfiles, no `__orkas/...`.\n' ++ ' - Allowed extensions: text — `.html .htm .js .mjs .css .json .svg .xml .txt .csv`; binary (base64 only) — `.png .jpg .jpeg .gif .webp .ico .wasm .woff .woff2 .ttf .otf`.\n' ++ ' - `content` is UTF-8 text by default; for a binary extension set `"encoding":"base64"` and pass base64 bytes.\n' ++ '\n' ++ 'Constraints: the app runs OFFLINE — no network, no external CDN. Inline your CSS/JS or split into sibling files referenced by RELATIVE URL. The iframe is sandboxed (scripts + forms allowed; it cannot reach the host app).\n' ++ '\n' ++ 'To get what the user does back: the app sends a message to its parent —\n' ++ ' `parent.postMessage({ __orkasArtifact: true, type: "submit", payload: <json-serialisable value> }, "*")`\n' ++ 'and that arrives as the user\'s next message to you (a readable summary plus a machine tag). Optionally include `<script src="__orkas/bridge.js"></script>` to get `window.orkasArtifact.send(payload)` plus automatic iframe height — without the bridge the iframe is a fixed height (call `window.orkasArtifact.resize(px)` or post `{type:"resize",height:px}` to change it).\n' ++ '\n' ++ 'After calling this tool, do NOT also paste the artifact\'s HTML in your reply — it is already shown.\n' ++ '\n' ++ 'Permission: requires local execution permission (same gate as `write_file` / `html_to_pdf`).',+ inputSchema: {+ type: 'object',+ properties: {+ title: { type: 'string', description: 'Short title shown above the embedded app. Optional; defaults to "Interactive app".' },+ files: {+ type: 'array',+ description: 'The app files. Must include a top-level "index.html". Max 20 files, 256KB/file, 1MB total.',+ items: {+ type: 'object',+ properties: {+ path: { type: 'string', description: 'Forward-slash relative path, e.g. "index.html" or "assets/app.js". No "..", no leading "/", no dotfiles, no "__orkas/...".' },+ content: { type: 'string', description: 'File contents. UTF-8 text by default; for a binary extension set "encoding":"base64" and pass base64.' },+ encoding: { type: 'string', enum: ['utf8', 'base64'], description: 'Default "utf8". Use "base64" for image / font / wasm files.' },+ },+ required: ['path', 'content'],+ },+ },+ },+ required: ['files'],+ },+ async execute(input) {+ if (!getLocalExecGranted()) return deniedResult();+ const uid = opts.userId;+ const cid = opts.cid;+ if (!uid || !cid) {+ return { content: errText('E_NO_CONVERSATION', 'create_artifact is only available inside a conversation.'), isError: true };+ }+ const r = chatArtifacts.createArtifact(uid, cid, opts.agentId || '', {+ title: (input as { title?: unknown }).title,+ files: (input as { files?: unknown }).files,+ });+ if (!r.ok) {+ // Cast in the error branch — `strictNullChecks: false` keeps the+ // whole `Result<>` union here (codebase-wide workaround).+ const errMsg = (r as { error?: string }).error || 'invalid artifact';+ log.warn(`create_artifact reject user=${uid} cid=${cid}: ${errMsg}`);+ return { content: errText('E_BAD_ARTIFACT', errMsg), isError: true };+ }+ if (opts.onArtifactCreated) {+ try { opts.onArtifactCreated({ id: r.artifactId, title: r.title }); }+ catch (err) { log.warn(`onArtifactCreated callback failed: ${(err as Error).message}`); }+ }+ log.info(`create_artifact user=${uid} cid=${cid} id=${r.artifactId} agent=${opts.agentId || ''}`);+ return {+ content:+ `Artifact "${r.title}" created (id ${r.artifactId}) — it is now shown to the user inside this reply, so do NOT paste its HTML in your message. ` ++ `To receive what the user does in it, the app calls ` ++ `parent.postMessage({ __orkasArtifact: true, type: "submit", payload: <json-serialisable value> }, "*") ` ++ `(or, with <script src="__orkas/bridge.js"></script>, window.orkasArtifact.send(payload)); ` ++ `that becomes the user's next message to you.`,+ };+ },+ };+}+/** Build the array of local-machine tools for a single runner. */export function createLocalTools(opts: LocalToolsOpts = {}): AgentTool[] {- return [+ const tools: AgentTool[] = [createBashTool(),createWriteFileTool(opts),createEditFileTool(opts),createMarkdownToPdfTool(opts),createHtmlToPdfTool(opts),];+ // `create_artifact` only makes sense on a conversation surface that+ // renders the embedded result and routes interactions back — i.e. a `cid`+ // plus an `onArtifactCreated` sink (group chat). Edit chats / ad-hoc runs+ // don't pass the sink, so the tool isn't offered there.+ if (opts.cid && opts.onArtifactCreated) tools.push(createCreateArtifactTool(opts));+ return tools;}export { createFileTools } from './file-tools';diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.tsindex 2bfa12a8..76de0e69 100644--- a/src/main/model/core-agent/runner.ts+++ b/src/main/model/core-agent/runner.ts@@ -126,6 +126,9 @@ export interface BuildRunnerParams {/** Caller-supplied predicate consumed by write-style tools' uniquify* logic. See `model/client.ts` `ChatOptions.hasProducedPath`. */hasProducedPath?: (absPath: string) => boolean;+ /** Fires after each successful `create_artifact` call. See `model/client.ts`+ * `ChatOptions.onArtifactCreated`. */+ onArtifactCreated?: (a: { id: string; title: string }) => void;}/** Tool definition snapshot used to log "what tools did the LLM actually see@@ -229,10 +232,12 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{const localTools = createLocalTools({...(uid ? { userId: uid } : {}),...(params.cid ? { cid: params.cid } : {}),+ ...(agentId ? { agentId } : {}),...(params.projectId ? { projectId: params.projectId } : {}),...(params.extraRoots?.length ? { extraRoots: params.extraRoots } : {}),...(params.onFileWritten ? { onFileWritten: params.onFileWritten } : {}),...(params.hasProducedPath ? { hasProducedPath: params.hasProducedPath } : {}),+ ...(params.onArtifactCreated ? { onArtifactCreated: params.onArtifactCreated } : {}),});// File-scoped tools (read_file override + search_files + grep_files).diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.tsindex 7c9617e9..19619096 100644--- a/src/main/model/core-agent/tool-catalog.ts+++ b/src/main/model/core-agent/tool-catalog.ts@@ -59,6 +59,7 @@ export const TOOL_CATALOG: ToolCatalogEntry[] = [{ name: 'stat_file', group: 'fs', summary: 'Trigger PDF/DOCX extraction and return total_chars; call before read_file.' },{ name: 'search_files', group: 'fs', summary: 'Find files by name / glob across the workspace + attachment scope.' },{ name: 'grep_files', group: 'fs', summary: 'Grep text across the workspace + attachment scope (PDF/DOCX auto-extracted, then searched).' },+ { name: 'create_artifact', group: 'fs', permission: 'localExec', summary: 'Build an interactive multi-file web app (HTML/CSS/JS) rendered live & clickable inside the chat bubble; for dashboards / calculators / visualizations / mini-tools — not documents (html_to_pdf) or images (generate_image).' },// Shell{ name: 'bash', group: 'shell', permission: 'localExec', summary: 'Execute a shell command on the user\'s machine (cwd = $working_dir).' },diff --git a/src/main/paths.ts b/src/main/paths.tsindex 4c4d404b..e77099c6 100644--- a/src/main/paths.ts+++ b/src/main/paths.ts@@ -111,6 +111,26 @@ export const groupChatVisibilityFile = (uid: string, cid: string, actorId: strinexport const userChatAttachmentsDir = (uid: string) => path.join(userCloudRoot(uid), 'chat_attachments');export const chatAttachmentDir = (uid: string, cid: string) => path.join(userChatAttachmentsDir(uid), cid);+// LLM-generated interactive web-app bundles (artifacts). Layout:+// `<uid>/cloud/chat_artifacts/<cid>/<artifactId>/{index.html, ...assets, __orkas-meta.json}`.+// Served read-only via the `chat-app://` protocol (see index.ts). Cloud-synced+// with the conversation; purged by cid on conversation delete. Kept as a+// separate pool from chat_attachments/ on purpose — attachments are user+// uploads with an extension whitelist that `buildAttachmentManifest` scans to+// feed the model; artifacts are arbitrary directory trees that must not.+export const userChatArtifactsDir = (uid: string) => path.join(userCloudRoot(uid), 'chat_artifacts');+export const chatArtifactCidDir = (uid: string, cid: string) => path.join(userChatArtifactsDir(uid), cid);+export const artifactDir = (uid: string, cid: string, artifactId: string) =>+ path.join(chatArtifactCidDir(uid, cid), artifactId);++// User-kept copies of `create_artifact` apps ("My Apps"). Layout:+// `<uid>/cloud/saved_apps/<appId>/{index.html, ...siblings, __orkas-meta.json}`.+// Cloud-synced; never auto-purged (conversation-independent — only the user's+// explicit delete from the My Apps tab removes one). Opened via `shell.openPath`+// (a `file://` view). See `features/saved_apps.ts`.+export const userSavedAppsDir = (uid: string) => path.join(userCloudRoot(uid), 'saved_apps');+export const savedAppDir = (uid: string, appId: string) => path.join(userSavedAppsDir(uid), appId);+// core-agent session jsonl (LLM-view) — all session kinds land here:// conv (legacy) / gconv / gmember / skill / agent / extract-img.export const userSessionsDir = (uid: string) => path.join(userCloudRoot(uid), 'sessions');@@ -311,6 +331,8 @@ export function ensureUserLayout(uid: string): void {const dirs = [userChatsDir(uid),userChatAttachmentsDir(uid),+ userChatArtifactsDir(uid),+ userSavedAppsDir(uid),userSessionsDir(uid),userContextsDir(uid),userKbDir(uid),diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex 7ee46768..517945b0 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -26,6 +26,7 @@<button class="sidebar-btn" id="agents-btn" data-i18n="sidebar.agents">Agents</button><button class="sidebar-btn" id="skills-btn" data-i18n="sidebar.skills">Skills</button><button class="sidebar-btn" id="contexts-btn" data-i18n="sidebar.contexts">Knowledge</button>+ <button class="sidebar-btn" id="apps-btn" data-i18n="sidebar.apps">My Apps</button></div><div class="sidebar-section sidebar-projects-section"><div class="sidebar-section-title-row">@@ -411,6 +412,19 @@</div></section>+ <!-- My Apps — user-kept copies of create_artifact bundles (see modules/saved-apps.js) -->+ <section class="panel" id="panel-apps">+ <div class="agents-grid-view">+ <div class="agents-grid-header">+ <span data-i18n="apps.title">Apps you've created</span>+ </div>+ <div class="agents-grid-scroll">+ <div class="apps-grid" id="apps-grid"></div>+ <div class="agents-empty" id="apps-empty" data-i18n="apps.empty">No saved apps yet</div>+ </div>+ </div>+ </section>+<!-- Settings --><section class="panel" id="panel-settings"><div class="settings-container">@@ -825,6 +839,7 @@<script src="./modules/projects.js"></script><script src="./modules/project-detail.js"></script><script src="./modules/conversation.js"></script>+ <script src="./modules/chat-artifact.js"></script><script src="./modules/plan-rail.js"></script><script src="./modules/queue-draft.js"></script><script src="./modules/skills.js"></script>@@ -836,6 +851,7 @@<script src="./vendor/pinyin-firstletter/data.js"></script><script src="./modules/pinyin-firstletter.js"></script><script src="./modules/agents.js"></script>+ <script src="./modules/saved-apps.js"></script><script src="./modules/agent-schedule.js"></script><script src="./modules/utils.js"></script>diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 14fea2ea..0cfcc8a3 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -24,6 +24,7 @@"sidebar.new_chat": "Commander","sidebar.agents": "Agents","sidebar.skills": "Skills",+ "sidebar.apps": "My Apps","sidebar.contexts": "Knowledge","sidebar.conversations": "Conversations","sidebar.conv_empty": "No conversations yet",@@ -82,6 +83,31 @@"chat.from_agent_unknown": "Agent","chat.produced_reveal_title": "Reveal in folder","chat.process_info": "Process info",+ "artifact.title": "Interactive app",+ "artifact.reload": "Reload",+ "artifact.more": "More",+ "artifact.menu_save": "Save",+ "artifact.open_external": "Open in browser",+ "artifact.open_failed": "Could not open in browser",+ "artifact.result_prefix": "Result from",+ "apps.title": "Apps you've created",+ "apps.empty": "No saved apps yet — create an interactive app in a conversation, then use ⋯ → Save on its card.",+ "apps.open_hint": "Open in your default browser",+ "apps.open_failed": "Could not open in browser",+ "apps.edit": "Edit",+ "apps.edit_conv_title": "Edit \"{name}\"",+ "apps.edit_seed": "I want to modify the interactive app \"{name}\". Its full source is in the attached file \"{file}\". Please make these changes:\n\n",+ "apps.edit_failed": "Could not open an edit conversation",+ "apps.rename": "Rename",+ "apps.rename_prompt": "New name:",+ "apps.rename_failed": "Could not rename the app",+ "apps.delete": "Delete",+ "apps.delete_confirm": "Delete \"{name}\"? This cannot be undone.",+ "apps.delete_failed": "Could not delete the app",+ "apps.more": "More",+ "apps.source_hint": "From a conversation",+ "apps.saved_toast": "Saved to My Apps",+ "apps.save_failed": "Could not save the app","chat.archive_btn_title": "Save to knowledge base","chat.archive_btn": "Knowledge","chat.archive_done": "Archived ✓",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex 4585a5ab..cfafc01e 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -24,6 +24,7 @@"sidebar.new_chat": "指挥官","sidebar.agents": "智能体","sidebar.skills": "技能库",+ "sidebar.apps": "我的应用","sidebar.contexts": "知识库","sidebar.conversations": "对话记录","sidebar.conv_empty": "暂无对话",@@ -82,6 +83,31 @@"chat.from_agent_unknown": "智能体","chat.produced_reveal_title": "在文件夹中显示","chat.process_info": "过程信息",+ "artifact.title": "互动应用",+ "artifact.reload": "重新加载",+ "artifact.more": "更多操作",+ "artifact.menu_save": "保存",+ "artifact.open_external": "浏览器打开",+ "artifact.open_failed": "无法在浏览器中打开",+ "artifact.result_prefix": "来自",+ "apps.title": "用户创作的应用",+ "apps.empty": "还没有保存的应用 —— 在对话里生成一个互动应用后,点卡片上的 ⋯ → 保存。",+ "apps.open_hint": "在默认浏览器中打开",+ "apps.open_failed": "无法在浏览器中打开",+ "apps.edit": "编辑",+ "apps.edit_conv_title": "编辑「{name}」",+ "apps.edit_seed": "我想修改这个互动应用「{name}」。当前完整源码在对话附件「{file}」里。请帮我做以下改动:\n\n",+ "apps.edit_failed": "无法打开编辑会话",+ "apps.rename": "重命名",+ "apps.rename_prompt": "新名称:",+ "apps.rename_failed": "重命名失败",+ "apps.delete": "删除",+ "apps.delete_confirm": "删除「{name}」?删除后无法恢复。",+ "apps.delete_failed": "删除失败",+ "apps.more": "更多操作",+ "apps.source_hint": "来自对话",+ "apps.saved_toast": "已保存到「用户创作的应用」",+ "apps.save_failed": "保存失败","chat.archive_btn_title": "保存到知识库","chat.archive_btn": "知识库","chat.archive_done": "已存档 ✓",diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.jsindex 92ae4f41..e8bb4641 100644--- a/src/renderer/modules/boot.js+++ b/src/renderer/modules/boot.js@@ -144,6 +144,7 @@ function setView(view, cid, opts = {}) {: view === 'agents' ? 'panel-agents': view === 'skills' ? 'panel-skills': view === 'contexts' ? 'panel-contexts'+ : view === 'apps' ? 'panel-apps': view === 'settings' ? 'panel-settings': view === 'project' ? 'panel-project': 'panel-conversation';@@ -153,6 +154,7 @@ function setView(view, cid, opts = {}) {document.getElementById('agents-btn').classList.toggle('active', view === 'agents');document.getElementById('skills-btn').classList.toggle('active', view === 'skills');document.getElementById('contexts-btn')?.classList.toggle('active', view === 'contexts');+ document.getElementById('apps-btn')?.classList.toggle('active', view === 'apps');document.getElementById('settings-btn')?.classList.toggle('active', view === 'settings');document.querySelectorAll('.conv-item').forEach(it => {it.classList.toggle('active', view === 'conversation' && it.dataset.cid === cid);@@ -232,6 +234,13 @@ function setView(view, cid, opts = {}) {} else if (view === 'contexts') {currentCid = null;loadContexts();+ } else if (view === 'apps') {+ currentCid = null;+ // Force-refresh on every visit (same rationale as agents/skills): a+ // "保存" can land while the user is on another tab — the tab is the+ // recovery path, so it should always show ground truth. Cheap (one IPC+ // + dir scan).+ if (typeof loadSavedApps === 'function') loadSavedApps(true);} else if (view === 'settings') {currentCid = null;loadSettings();diff --git a/src/renderer/modules/chat-artifact.js b/src/renderer/modules/chat-artifact.jsnew file mode 100644index 00000000..9d048e65--- /dev/null+++ b/src/renderer/modules/chat-artifact.js@@ -0,0 +1,331 @@+// Chat-bubble interactive web-app artifact widget.+//+// Renders an `artifacts[]` entry from a GroupMessage as a card containing a+// sandboxed `<iframe>` whose `src` is the `chat-app://` protocol (served by+// the main process out of `<uid>/cloud/chat_artifacts/<cid>/<id>/`). The+// artifact is a self-contained web app the LLM produced via `create_artifact`.+//+// Round-trip: the artifact talks to the chat by posting to its parent —+// parent.postMessage({ __orkasArtifact: true, type: 'submit'|'resize'|'open-external', ... }, '*')+// A single global `message` listener (registered once) validates that+// `event.source` is one of our live artifact iframes (the iframe is+// cross-origin — `chat-app://cid` ≠ `file://` — so origin-string checks are+// brittle; identity of the contentWindow is the robust check) and that+// `event.data.__orkasArtifact === true`, then:+// - `submit` / `sendToChat` → compose a user message (readable summary ++// `<artifact-result>` machine tag, `@`-routed to the creating actor) and+// fire it through the normal send pipeline.+// - `resize` → set the iframe's height (cross-origin, so the parent can't+// measure the content itself; the artifact reports it, optionally via the+// `__orkas/bridge.js` helper).+// - `open-external` → open an http(s) URL in the system browser.+// We never expose `window.orkas` or any privileged handle into the iframe.+//+// Classic script — no import/export; globals `renderChatArtifact`,+// `encodeArtifactResult` are exposed via `window.*` (matching `chat-input-form.js`).+// Loaded after `conversation.js` in index.html so it can call+// `sendInCurrentConversation` / read `currentCid` directly.++(function () {+ const DEFAULT_FRAME_HEIGHT = 420; // px, until the artifact reports its own+ const MAX_FRAME_HEIGHT = 640; // px, clamp; the iframe scrolls past this+ const MIN_FRAME_HEIGHT = 80; // px+ const SANDBOX = 'allow-scripts allow-same-origin allow-forms';+ // `allow-same-origin` is safe: the artifact's origin (`chat-app://cid`) is+ // never the renderer's (`file://...`), so the same-origin policy already+ // blocks `parent.*` — the flag only lets the artifact keep a usable origin+ // for localStorage / same-origin sibling fetch. We deliberately omit+ // `allow-popups` / `allow-top-navigation`.++ function _t(key, fallback) {+ try { if (typeof t === 'function') { const v = t(key); if (v && v !== key) return v; } } catch (_) {}+ return fallback;+ }++ function _notifyFail(prefix, err) {+ const msg = (err && err.message) ? err.message : String(err || '');+ try {+ if (typeof uiAlert === 'function') uiAlert(msg ? `${prefix}: ${msg}` : prefix);+ else _convLog.warn(prefix, msg);+ } catch (_) {}+ }++ // Card-header "⋯" popover state. One shared menu element appended to <body>,+ // positioned to whichever ⋯ button opened it (same pattern as the agents /+ // contexts row menus); the acting context is stashed per-open.+ let _menuEl = null;+ let _menuCtx = null; // { frame, cid, artifactId, title } of the open menu+ let _menuAnchor = null; // the ⋯ button that opened it++ // chat-app://cid/<encCid>/<encArtifactId>/index.html+ function _artifactUrl(cid, artifactId, rel) {+ const parts = ['chat-app://cid', encodeURIComponent(String(cid)), encodeURIComponent(String(artifactId))];+ if (rel) parts.push(String(rel).split('/').map(encodeURIComponent).join('/'));+ else parts.push('index.html');+ return parts.join('/');+ }++ function _clampHeight(px) {+ const n = Number(px);+ if (!isFinite(n) || n <= 0) return DEFAULT_FRAME_HEIGHT;+ return Math.max(MIN_FRAME_HEIGHT, Math.min(MAX_FRAME_HEIGHT, Math.round(n)));+ }++ // ── result encoding (shared shape with the agent's parser; see the+ // `create_artifact` tool description for the contract) ───────────────+ // Renders a one-line readable summary + the `<artifact-result>` machine tag+ // routed `@`-style to the creating actor. The tag is stripped from the+ // user bubble's display by `_stripArtifactResultTagForDisplay` in+ // conversation.js; the agent reads the JSON from it.+ function encodeArtifactResult(artifactId, agentId, title, payload) {+ let json = '';+ try { json = JSON.stringify(payload); } catch (_) { json = '"<unserialisable>"'; }+ if (typeof json !== 'string') json = String(json);+ const aid = String(agentId || '').trim();+ // commander / unknown → no @-mention (a plain user message goes to the+ // commander by default); a real agent id gets `@<id>` so the bus routes+ // the result back to it (`buildMention` on the backend resolves the raw+ // id when the display name isn't known).+ const mention = (aid && aid !== 'commander') ? `@${aid} ` : '';+ const summary = `${_t('artifact.result_prefix', 'Result from')} "${String(title || _t('artifact.title', 'Interactive app'))}"`;+ const tag = `<artifact-result artifact_id="${String(artifactId || '')}" agent_id="${aid}">\n${json}\n</artifact-result>`;+ return `${mention}${summary}\n\n${tag}`;+ }++ // ── the single global message listener ──────────────────────────────────+ function _findArtifactFrame(sourceWin) {+ if (!sourceWin) return null;+ const frames = document.querySelectorAll('iframe.chat-artifact-frame');+ for (const f of frames) {+ try { if (f.contentWindow === sourceWin) return f; } catch (_) { /* cross-origin access can throw — skip */ }+ }+ return null;+ }++ let _listenerBound = false;+ function _bindGlobalListener() {+ if (_listenerBound) return;+ _listenerBound = true;+ window.addEventListener('message', (ev) => {+ const data = ev && ev.data;+ if (!data || typeof data !== 'object' || data.__orkasArtifact !== true) return;+ const frame = _findArtifactFrame(ev.source);+ if (!frame) return; // not one of ours (or a stale/removed iframe)+ const cid = frame.dataset.artifactCid || '';+ const artifactId = frame.dataset.artifactId || '';+ const agentId = frame.dataset.artifactAgent || '';+ const title = frame.dataset.artifactTitle || '';+ const type = String(data.type || '');+ if (type === 'resize') {+ frame.style.height = `${_clampHeight(data.height)}px`;+ return;+ }+ if (type === 'open-external') {+ const url = String(data.url || '').trim();+ if (/^https?:\/\//i.test(url)) { try { window.open(url, '_blank', 'noopener'); } catch (_) {} }+ return;+ }+ if (type === 'submit' || type === 'sendToChat') {+ // Only the currently-viewed conversation has live iframes in the DOM,+ // but guard anyway — a result for a non-current cid is a stale fire.+ if (!cid || cid !== currentCid) return;+ const text = encodeArtifactResult(artifactId, agentId, title, data.payload);+ try { sendInCurrentConversation(text); }+ catch (err) { try { _convLog.warn('artifact result send failed', err && err.message ? err.message : err); } catch (_) {} }+ return;+ }+ // Unknown type — ignore (forward-compat).+ });+ }++ // ── card-header "⋯" menu (reload / open in browser / save) ──────────────+ function _closeMenu() {+ if (_menuEl) _menuEl.style.display = 'none';+ if (_menuAnchor) _menuAnchor.classList.remove('is-menu-open');+ _menuCtx = null;+ _menuAnchor = null;+ }++ function _ensureMenuEl() {+ if (_menuEl) return _menuEl;+ const el = document.createElement('div');+ el.className = 'chat-artifact-menu';+ el.style.display = 'none';+ document.body.appendChild(el);+ document.addEventListener('click', (e) => {+ if (el.style.display === 'none') return;+ if (el.contains(e.target)) return;+ if (e.target && e.target.closest && e.target.closest('.chat-artifact-more')) return;+ _closeMenu();+ });+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && el.style.display !== 'none') _closeMenu(); });+ window.addEventListener('scroll', _closeMenu, true);+ window.addEventListener('resize', _closeMenu);+ window.addEventListener('i18n-change', _closeMenu);+ _menuEl = el;+ return el;+ }++ // Rebuilt on every open — items are fixed; doing it here keeps labels fresh+ // after an `i18n-change` without re-binding gymnastics.+ function _renderMenuItems(el) {+ el.innerHTML = '';+ const defs = [+ ['reload', _t('artifact.reload', 'Reload')],+ ['open', _t('artifact.open_external', 'Open in browser')],+ ['save', _t('artifact.menu_save', 'Save')],+ ];+ for (const [action, label] of defs) {+ const it = document.createElement('div');+ it.className = 'chat-artifact-menu-item';+ it.dataset.action = action;+ it.textContent = label;+ it.addEventListener('click', (e) => {+ e.stopPropagation();+ const ctx = _menuCtx;+ _closeMenu();+ if (!ctx) return;+ if (action === 'reload') _doReload(ctx);+ else if (action === 'open') _doOpenExternal(ctx);+ else if (action === 'save') _doSave(ctx);+ });+ el.appendChild(it);+ }+ }++ function _positionMenu(el, anchorEl) {+ el.style.display = 'block';+ el.style.left = '-9999px';+ el.style.top = '-9999px';+ const rect = anchorEl.getBoundingClientRect();+ const mr = el.getBoundingClientRect();+ const margin = 8;+ const gap = 4;+ let left = rect.right - mr.width;+ if (left < margin) left = margin;+ if (left + mr.width > window.innerWidth - margin) left = window.innerWidth - mr.width - margin;+ const below = rect.bottom + gap + mr.height <= window.innerHeight - margin;+ const top = below ? rect.bottom + gap : Math.max(margin, rect.top - mr.height - gap);+ el.style.left = left + 'px';+ el.style.top = top + 'px';+ }++ function _openMenu(anchorBtn, ctx) {+ const el = _ensureMenuEl();+ if (el.style.display !== 'none' && _menuAnchor === anchorBtn) { _closeMenu(); return; }+ _closeMenu();+ _menuCtx = ctx;+ _menuAnchor = anchorBtn;+ anchorBtn.classList.add('is-menu-open');+ _renderMenuItems(el);+ _positionMenu(el, anchorBtn);+ }++ function _doReload(ctx) {+ const f = ctx && ctx.frame;+ if (!f || !f.isConnected) return;+ // Reset height to default; the artifact re-reports on load. Reassigning+ // `src` forces a fresh load (the protocol handler sends `Cache-Control:+ // private` and dev reload ignores cache; this just re-runs the app).+ f.style.height = `${DEFAULT_FRAME_HEIGHT}px`;+ f.src = _artifactUrl(ctx.cid, ctx.artifactId);+ }++ async function _doOpenExternal(ctx) {+ try {+ const r = await window.orkas.invoke('conversations.artifacts.openExternal', {+ cid: String(ctx.cid), artifactId: String(ctx.artifactId),+ });+ if (!r || r.ok === false) throw new Error((r && r.error) || 'open failed');+ } catch (err) { _notifyFail(_t('artifact.open_failed', 'Could not open in browser'), err); }+ }++ async function _doSave(ctx) {+ try {+ const r = await window.orkas.invoke('conversations.artifacts.save', {+ cid: String(ctx.cid), artifactId: String(ctx.artifactId),+ });+ if (!r || r.ok === false) throw new Error((r && r.error) || 'save failed');+ try { if (typeof uiAlert === 'function') uiAlert(_t('apps.saved_toast', 'Saved to My Apps')); } catch (_) {}+ // Refresh the "My Apps" tab if its module is loaded.+ try { if (typeof loadSavedApps === 'function') loadSavedApps(true); } catch (_) {}+ } catch (err) { _notifyFail(_t('apps.save_failed', 'Could not save the app'), err); }+ }++ // ── render ──────────────────────────────────────────────────────────────+ // host: a container element appended inside the bubble.+ // ctx: { cid, artifactId, title, agentId }+ function renderChatArtifact(host, ctx) {+ if (!host || !ctx || !ctx.cid || !ctx.artifactId) return;+ _bindGlobalListener();+ const title = ctx.title || _t('artifact.title', 'Interactive app');++ const card = document.createElement('div');+ card.className = 'chat-artifact-card';++ const header = document.createElement('div');+ header.className = 'chat-artifact-header';+ const titleEl = document.createElement('span');+ titleEl.className = 'chat-artifact-title';+ titleEl.textContent = title;+ titleEl.title = title;+ const spacer = document.createElement('span');+ spacer.className = 'chat-artifact-spacer';+ // All header actions live behind a single "⋯" popover (reload / open in+ // browser / save) — keeps the bubble chrome quiet. See `_openMenu`.+ const moreBtn = document.createElement('button');+ moreBtn.className = 'btn btn-sm chat-artifact-more';+ moreBtn.type = 'button';+ moreBtn.textContent = '⋯';+ moreBtn.title = _t('artifact.more', 'More');+ moreBtn.setAttribute('aria-label', _t('artifact.more', 'More'));+ header.appendChild(titleEl);+ header.appendChild(spacer);+ header.appendChild(moreBtn);++ const frame = document.createElement('iframe');+ frame.className = 'chat-artifact-frame';+ frame.setAttribute('sandbox', SANDBOX);+ frame.setAttribute('referrerpolicy', 'no-referrer');+ frame.setAttribute('loading', 'lazy');+ frame.dataset.artifactCid = String(ctx.cid);+ frame.dataset.artifactId = String(ctx.artifactId);+ frame.dataset.artifactAgent = String(ctx.agentId || '');+ frame.dataset.artifactTitle = title;+ frame.style.height = `${DEFAULT_FRAME_HEIGHT}px`;+ frame.src = _artifactUrl(ctx.cid, ctx.artifactId);++ moreBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ _openMenu(moreBtn, { frame, cid: ctx.cid, artifactId: ctx.artifactId, title });+ });++ card.appendChild(header);+ card.appendChild(frame);+ host.appendChild(card);+ }++ // Render every artifact on a message into the given bubble. Idempotent —+ // skips ids already mounted in this bubble (the finalize / append paths+ // can both touch the same bubble).+ function mountMessageArtifacts(bubbleEl, artifacts, cid) {+ if (!bubbleEl || !Array.isArray(artifacts) || !artifacts.length) return;+ for (const a of artifacts) {+ if (!a || !a.id) continue;+ if (bubbleEl.querySelector(`iframe.chat-artifact-frame[data-artifact-id="${CSS.escape(String(a.id))}"]`)) continue;+ const host = document.createElement('div');+ host.className = 'chat-artifact-host';+ bubbleEl.appendChild(host);+ renderChatArtifact(host, {+ cid: cid,+ artifactId: a.id,+ title: a.title || '',+ agentId: a.agent_id || '',+ });+ }+ }++ window.renderChatArtifact = renderChatArtifact;+ window.mountMessageArtifacts = mountMessageArtifacts;+ window.encodeArtifactResult = encodeArtifactResult;+})();diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex aeea1d5d..f3ddbf7b 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -697,6 +697,7 @@ function _groupMsgToLegacy(gm) {...(gm.form ? { form: gm.form } : {}),...(_normalizeCreatedAgents(gm) ? { created_agents: _normalizeCreatedAgents(gm) } : {}),...(_normalizeCreatedSkills(gm) ? { created_skills: _normalizeCreatedSkills(gm) } : {}),+ ...(Array.isArray(gm.artifacts) && gm.artifacts.length ? { artifacts: gm.artifacts } : {}),...(gm.plan_announcement ? { _plan_announcement: true } : {}),...(Array.isArray(gm.process) && gm.process.length ? { process: gm.process } : {}),};@@ -1647,7 +1648,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {// `_stripSurvivingStructuralBlocks` in strip-structural-blocks.js).let displayContent = rawContent;if (!isHtmlSnippet) {- if (role === 'user') displayContent = _stripSubmissionTagForDisplay(rawContent);+ if (role === 'user') displayContent = _stripArtifactResultTagForDisplay(_stripSubmissionTagForDisplay(rawContent));else if (role === 'assistant') displayContent = _stripSurvivingStructuralBlocks(rawContent);}const contentHtml = isHtmlSnippet@@ -1728,6 +1729,14 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {_mountChatInputForm(formHost, msgDiv, message, opts);}}+ // Interactive web-app artifacts (assistant messages only) — sandboxed+ // `<iframe>` over the `chat-app://` protocol, appended after the form so it+ // reads as "reply text → embedded app". See chat-artifact.js.+ if (role === 'assistant' && Array.isArray(message.artifacts) && message.artifacts.length+ && typeof window.mountMessageArtifacts === 'function') {+ const bubble = msgDiv.querySelector('.chat-bubble');+ if (bubble) window.mountMessageArtifacts(bubble, message.artifacts, opts.cid || currentCid);+ }// Archive button is only for finalised assistant replies (raw markdown,// not an HTML placeholder / status stub).if (role === 'assistant' && !isHtmlSnippet && archive) {@@ -3414,6 +3423,13 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {_mountChatInputForm(host, ph, formMessage, { cid });}}++ // Interactive web-app artifacts (chat-app:// iframe). Idempotent — skips+ // ids already mounted in this bubble.+ if (Array.isArray(gm.artifacts) && gm.artifacts.length && typeof window.mountMessageArtifacts === 'function') {+ const bubble = ph.querySelector('.chat-bubble');+ if (bubble) window.mountMessageArtifacts(bubble, gm.artifacts, cid);+ }}// Group-chat bus event router. Each event is one of:@@ -3722,6 +3738,18 @@ function _stripSubmissionTagForDisplay(text) {return out.replace(/\n{3,}/g, '\n\n').trimEnd();}+// Hide the `<artifact-result artifact_id=... agent_id=...>{json}+// </artifact-result>` tag from a user message body at render time. The tag+// is the machine payload an interactive artifact posted back (the LLM parses+// it); the human reader only needs the one-line summary above it. Same+// atomic-container strip + prose/code guard as the submission tag.+function _stripArtifactResultTagForDisplay(text) {+ if (!text || text.indexOf('<artifact-result') < 0) return text;+ const out = _stripOuterTagBlocks(text, 'artifact-result');+ if (out === text) return text;+ return out.replace(/\n{3,}/g, '\n\n').trimEnd();+}+// `_splitMarkdownProseCode`, `_findOuterAgentRanges`, `_stripSurvivingAgentBlocks`,// `_replaceOuterAgentBlocks` are defined in `./strip-structural-blocks.js` (loaded earlier// in `index.html`). They live in their own file so vitest can pin the set-A /diff --git a/src/renderer/modules/saved-apps.js b/src/renderer/modules/saved-apps.jsnew file mode 100644index 00000000..96d573b8--- /dev/null+++ b/src/renderer/modules/saved-apps.js@@ -0,0 +1,275 @@+// "My Apps" — the panel listing user-kept copies of `create_artifact` bundles+// (`<uid>/cloud/saved_apps/<appId>/`, written by `features/saved_apps.ts`).+//+// Apps land here only via the chat-bubble artifact card's `⋯` → "Save" (which+// calls `loadSavedApps(true)` afterwards). Clicking a card opens its+// `index.html` in the system browser (`savedApps.openExternal` →+// `shell.openPath`, a `file://` view — same caveats as the artifact card's+// "open in browser": no chat round-trip, and the `__orkas/bridge.js` virtual+// path / cross-origin sibling `fetch` don't work there). The per-card `⋯` menu+// has: open in browser / rename / delete.+//+// Classic script — no import/export. Global `loadSavedApps` is exposed via+// `window.*`. Loaded after `agents.js` in index.html.++(function () {+ const _appsLog = (typeof createLogger === 'function') ? createLogger('saved-apps') : { warn: () => {}, error: () => {} };+ let _appsCache = null; // last fetched list (for the i18n-change re-render)++ function _t(key, fallback, vars) {+ try { if (typeof t === 'function') { const v = t(key, vars); if (v && v !== key) return v; } } catch (_) {}+ // Translation missing — interpolate the fallback ourselves so {vars} still resolve.+ if (vars && typeof fallback === 'string') {+ return fallback.replace(/\{(\w+)\}/g, (m, n) => (vars[n] != null ? String(vars[n]) : m));+ }+ return fallback;+ }++ function _fail(prefix, err) {+ const msg = (err && err.message) ? err.message : String(err || '');+ try {+ if (typeof uiAlert === 'function') uiAlert(msg ? `${prefix}: ${msg}` : prefix);+ else _appsLog.warn(prefix, msg);+ } catch (_) {}+ }++ // ── per-card "⋯" row menu (one shared element, like agents.js) ──────────+ let _rowMenuEl = null;+ let _rowMenuAppId = null;+ let _rowMenuAnchor = null;++ function _closeRowMenu() {+ if (_rowMenuEl) _rowMenuEl.style.display = 'none';+ for (const el of document.querySelectorAll('.app-card.is-menu-open')) el.classList.remove('is-menu-open');+ _rowMenuAppId = null;+ _rowMenuAnchor = null;+ }++ function _ensureRowMenuEl() {+ if (_rowMenuEl) return _rowMenuEl;+ const el = document.createElement('div');+ el.className = 'app-row-menu';+ el.style.display = 'none';+ document.body.appendChild(el);+ document.addEventListener('click', (e) => {+ if (el.style.display === 'none') return;+ if (el.contains(e.target)) return;+ if (e.target && e.target.closest && e.target.closest('[data-app-more]')) return;+ _closeRowMenu();+ });+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && el.style.display !== 'none') _closeRowMenu(); });+ window.addEventListener('scroll', _closeRowMenu, true);+ window.addEventListener('resize', _closeRowMenu);+ window.addEventListener('i18n-change', _closeRowMenu);+ _rowMenuEl = el;+ return el;+ }++ function _positionRowMenu(el, anchorEl) {+ el.style.display = 'block';+ el.style.left = '-9999px';+ el.style.top = '-9999px';+ const rect = anchorEl.getBoundingClientRect();+ const mr = el.getBoundingClientRect();+ const margin = 8;+ const gap = 4;+ let left = rect.right - mr.width;+ if (left < margin) left = margin;+ if (left + mr.width > window.innerWidth - margin) left = window.innerWidth - mr.width - margin;+ const below = rect.bottom + gap + mr.height <= window.innerHeight - margin;+ const top = below ? rect.bottom + gap : Math.max(margin, rect.top - mr.height - gap);+ el.style.left = left + 'px';+ el.style.top = top + 'px';+ }++ function _renderRowMenuItems(el) {+ el.innerHTML = '';+ const defs = [+ ['edit', _t('apps.edit', 'Edit'), false],+ ['rename', _t('apps.rename', 'Rename'), false],+ ['delete', _t('apps.delete', 'Delete'), true],+ ];+ for (const [action, label, danger] of defs) {+ const it = document.createElement('div');+ it.className = 'app-row-menu-item' + (danger ? ' is-danger' : '');+ it.dataset.action = action;+ it.textContent = label;+ it.addEventListener('click', (e) => {+ e.stopPropagation();+ const id = _rowMenuAppId;+ _closeRowMenu();+ if (!id) return;+ if (action === 'edit') _editApp(id);+ else if (action === 'rename') _renameApp(id);+ else if (action === 'delete') _deleteApp(id);+ });+ el.appendChild(it);+ }+ }++ function _toggleRowMenu(anchorBtn, appId) {+ const el = _ensureRowMenuEl();+ if (el.style.display !== 'none' && _rowMenuAppId === appId) { _closeRowMenu(); return; }+ _closeRowMenu();+ _rowMenuAppId = appId;+ _rowMenuAnchor = anchorBtn;+ const card = anchorBtn.closest && anchorBtn.closest('.app-card');+ if (card) card.classList.add('is-menu-open');+ _renderRowMenuItems(el);+ _positionRowMenu(el, anchorBtn);+ }++ // ── actions ─────────────────────────────────────────────────────────────+ async function _openApp(appId) {+ try {+ const r = await window.orkas.invoke('savedApps.openExternal', { appId: String(appId) });+ if (!r || r.ok === false) throw new Error((r && r.error) || 'open failed');+ } catch (err) { _fail(_t('apps.open_failed', 'Could not open in browser'), err); }+ }++ // "Edit" — backend creates a fresh conversation with the app's source bundled+ // in as an `app-source.md` attachment; we navigate to it and pre-fill a draft+ // (mirrors `agents.js::useAgent`'s create-conv-and-go pattern, but doesn't+ // auto-send — the user completes the request and hits Send).+ async function _editApp(appId) {+ let r;+ try {+ r = await window.orkas.invoke('savedApps.openForEditing', { appId: String(appId) });+ if (!r || r.ok === false) throw new Error((r && r.error) || 'open-for-editing failed');+ } catch (err) { _fail(_t('apps.edit_failed', 'Could not open an edit conversation'), err); return; }+ const conv = r.conversation;+ if (!conv || !conv.conversation_id) { _fail(_t('apps.edit_failed', 'Could not open an edit conversation')); return; }+ // Add to the sidebar list.+ try {+ if (typeof conversations !== 'undefined' && Array.isArray(conversations)) {+ conversations.unshift(conv);+ if (typeof renderConversationList === 'function') renderConversationList();+ }+ } catch (_) {}+ // Navigate (skipLoad — the conv is brand new, nothing to fetch).+ try { setView('conversation', conv.conversation_id, { skipLoad: true }); } catch (_) {}+ // Pre-fill a draft + refresh the attachment chips so `app-source.md` shows+ // (setView with skipLoad doesn't restore drafts or re-sync attachments).+ try {+ const file = r.sourceFileName || 'app-source.md';+ const name = r.title || _t('artifact.title', 'Interactive app');+ const input = document.getElementById('chat-input');+ if (input) {+ input.value = _t('apps.edit_seed',+ 'I want to modify the interactive app "{name}". Its full source is in the attached file "{file}". Please make these changes:\n\n',+ { name, file });+ if (typeof autoGrow === 'function') autoGrow(input, 200);+ if (typeof _saveDraft === 'function') _saveDraft(conv.conversation_id);+ setTimeout(() => { try { input.focus(); } catch (_) {} }, 60);+ }+ if (typeof _chatAttachRefreshFromServer === 'function') _chatAttachRefreshFromServer(conv.conversation_id);+ } catch (err) { _appsLog.warn('edit post-nav setup failed', err && err.message ? err.message : err); }+ }++ async function _renameApp(appId) {+ const cur = (_appsCache || []).find((a) => a.id === appId);+ let next = null;+ try {+ if (typeof uiPrompt === 'function') next = await uiPrompt(_t('apps.rename_prompt', 'New name:'), (cur && cur.title) || '');+ } catch (_) { next = null; }+ if (next == null) return; // cancelled+ next = String(next).trim();+ if (!next || (cur && next === cur.title)) return;+ try {+ const r = await window.orkas.invoke('savedApps.rename', { appId: String(appId), title: next });+ if (!r || r.ok === false) throw new Error((r && r.error) || 'rename failed');+ } catch (err) { _fail(_t('apps.rename_failed', 'Could not rename'), err); }+ loadSavedApps(true);+ }++ async function _deleteApp(appId) {+ const cur = (_appsCache || []).find((a) => a.id === appId);+ const name = (cur && cur.title) || _t('artifact.title', 'Interactive app');+ let ok = false;+ try {+ if (typeof uiConfirmDanger === 'function') {+ ok = await uiConfirmDanger({+ title: _t('apps.delete', 'Delete'),+ message: _t('apps.delete_confirm', 'Delete this app? This cannot be undone.', { name }),+ dangerLabel: _t('apps.delete', 'Delete'),+ });+ } else if (typeof uiConfirm === 'function') {+ ok = await uiConfirm(_t('apps.delete_confirm', 'Delete this app? This cannot be undone.', { name }));+ } else { ok = true; }+ } catch (_) { ok = false; }+ if (!ok) return;+ try {+ const r = await window.orkas.invoke('savedApps.delete', { appId: String(appId) });+ if (!r || r.ok === false) throw new Error((r && r.error) || 'delete failed');+ } catch (err) { _fail(_t('apps.delete_failed', 'Could not delete'), err); }+ loadSavedApps(true);+ }++ // ── render ──────────────────────────────────────────────────────────────+ function _renderApps(apps) {+ const grid = document.getElementById('apps-grid');+ const empty = document.getElementById('apps-empty');+ if (!grid) return;+ grid.innerHTML = '';+ const list = Array.isArray(apps) ? apps : [];+ if (empty) empty.style.display = list.length ? 'none' : '';+ for (const a of list) {+ if (!a || !a.id) continue;+ const card = document.createElement('div');+ card.className = 'app-card';+ card.dataset.appId = a.id;+ card.title = _t('apps.open_hint', 'Open in your default browser');++ const header = document.createElement('div');+ header.className = 'app-card-header';+ const name = document.createElement('span');+ name.className = 'app-card-name';+ name.textContent = a.title || _t('artifact.title', 'Interactive app');+ const more = document.createElement('button');+ more.type = 'button';+ more.className = 'app-card-more';+ more.dataset.appMore = '1';+ more.textContent = '⋯';+ more.title = _t('apps.more', 'More');+ more.setAttribute('aria-label', _t('apps.more', 'More'));+ header.appendChild(name);+ header.appendChild(more);++ const hint = document.createElement('div');+ hint.className = 'app-card-hint';+ hint.textContent = _t('apps.source_hint', 'From a conversation');++ card.appendChild(header);+ card.appendChild(hint);+ card.addEventListener('click', (e) => {+ if (e.target && e.target.closest && e.target.closest('[data-app-more]')) {+ e.stopPropagation();+ _toggleRowMenu(more, a.id);+ return;+ }+ _openApp(a.id);+ });+ grid.appendChild(card);+ }+ }++ async function loadSavedApps(_force) {+ // `_force` accepted for parity with loadAgents/loadSkills; this module+ // keeps no "loaded once" flag — the list is cheap, always re-fetch.+ try {+ const r = await window.orkas.invoke('savedApps.list');+ _appsCache = (r && Array.isArray(r.apps)) ? r.apps : [];+ } catch (err) {+ _appsLog.warn('savedApps.list failed', err && err.message ? err.message : err);+ _appsCache = _appsCache || [];+ }+ _renderApps(_appsCache);+ }++ window.addEventListener('i18n-change', () => {+ _closeRowMenu();+ if (_appsCache) _renderApps(_appsCache);+ });++ window.loadSavedApps = loadSavedApps;+})();diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.jsindex 998b337e..a86f0f6c 100644--- a/src/renderer/modules/state.js+++ b/src/renderer/modules/state.js@@ -154,6 +154,7 @@ function bindStaticHandlers() {document.getElementById('new-chat-btn').addEventListener('click', () => setView('new-chat'));document.getElementById('agents-btn').addEventListener('click', () => setView('agents'));document.getElementById('skills-btn').addEventListener('click', () => setView('skills'));+ document.getElementById('apps-btn')?.addEventListener('click', () => setView('apps'));document.getElementById('contexts-btn').addEventListener('click', () => setView('contexts'));document.getElementById('settings-btn')?.addEventListener('click', () => setView('settings'));diff --git a/src/renderer/modules/strip-structural-blocks.js b/src/renderer/modules/strip-structural-blocks.jsindex ce9b2a51..98bc7e94 100644--- a/src/renderer/modules/strip-structural-blocks.js+++ b/src/renderer/modules/strip-structural-blocks.js@@ -394,7 +394,10 @@ function _stripSkillCreateContainer(buf, fallbackPlaceholder) {function _stripSurvivingStructuralBlocks(text) {if (!text) return text;let out = text;- for (const tag of ['agent', 'agent-input-form', 'agent-input-submission', 'skill']) {+ // `artifact-result` is a user→artifact result tag (user-side render strips+ // it via `_stripArtifactResultTagForDisplay`); included here so it's also+ // removed if it ever leaks into assistant text (LLM quoting / hallucination).+ for (const tag of ['agent', 'agent-input-form', 'agent-input-submission', 'artifact-result', 'skill']) {out = _stripOuterTagBlocks(out, tag);}// `<<<skill-file>>>` blocks: backend `extractSkillFileBlocks` strips themdiff --git a/src/renderer/style.css b/src/renderer/style.cssindex edfafc05..3b96b84d 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -2821,6 +2821,149 @@ body.model-not-configured .main-content { flex-direction: column; }color: var(--muted);}+/* Interactive web-app artifact card — sandboxed `<iframe>` over the+ `chat-app://` protocol, embedded inside the assistant `.chat-bubble`.+ See modules/chat-artifact.js. Understated chrome (a title bar + reload)+ so it reads as an inline panel, not a separate window. */+.chat-artifact-host { margin-top: 10px; }+.chat-artifact-card {+ width: 40cqw;+ max-width: 100%;+ min-width: 280px;+ border: 1px solid var(--border);+ border-radius: 10px;+ overflow: hidden;+ background: var(--bg);+}+.chat-artifact-header {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 8px 6px 10px;+ background: rgba(127, 127, 127, 0.06);+ border-bottom: 1px solid var(--border);+ font-size: 12px;+}+.chat-artifact-title {+ font-weight: 600;+ color: var(--text);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ flex: 0 1 auto;+}+.chat-artifact-spacer { flex: 1 1 auto; }+.chat-artifact-header .btn-sm { flex: 0 0 auto; }+.chat-artifact-more {+ /* A compact `⋯` button — slimmer than the default `.btn-sm` padding so it+ reads as a quiet header affordance. */+ padding: 2px 8px;+ font-size: 15px;+ line-height: 1;+}+.chat-artifact-more.is-menu-open { background: rgba(15, 23, 42, 0.08); }+.chat-artifact-frame {+ display: block;+ width: 100%;+ border: 0;+ background: #fff;+}+/* Card-header `⋯` popover (reload / open in browser / save) + the My Apps+ panel's per-card `⋯` popover — both mirror `.agent-row-menu`'s look. */+.chat-artifact-menu,+.app-row-menu {+ position: fixed;+ z-index: 1000;+ min-width: 120px;+ background: #fff;+ border: 1px solid var(--border);+ border-radius: 6px;+ box-shadow: 0 6px 20px rgba(15, 23, 42, 0.12);+ padding: 4px 0;+}+.chat-artifact-menu-item,+.app-row-menu-item {+ padding: 6px 14px;+ font-size: 13px;+ color: var(--text);+ cursor: pointer;+ user-select: none;+}+.chat-artifact-menu-item:hover,+.app-row-menu-item:hover { background: #f1f5f9; }+.app-row-menu-item.is-danger { color: #dc2626; }+.app-row-menu-item.is-danger:hover { background: #fef2f2; }++/* ─── "My Apps" panel — user-kept create_artifact bundles (saved-apps.js) ───+ Reuses the agents-tab layout shells (`.agents-grid-view` / `-header` /+ `-scroll` / `.agents-empty`); only the card grid + card need their own+ classes (the agents tab binds a global `.agent-card` click handler). */+.apps-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ gap: 16px;+ padding: 8px 0 16px;+}+.app-card {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 14px 16px;+ background: #fff;+ border: 1px solid var(--border);+ border-radius: 10px;+ cursor: pointer;+ transition: border-color 0.12s, box-shadow 0.12s;+ min-height: 84px;+}+.app-card:hover {+ border-color: rgba(37, 99, 235, 0.45);+ box-shadow: 0 4px 16px rgba(15, 23, 42, 0.06);+}+.app-card.is-menu-open { border-color: rgba(37, 99, 235, 0.45); }+.app-card-header {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 22px;+}+.app-card-name {+ flex: 1;+ min-width: 0;+ font-size: 15px;+ font-weight: 600;+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.app-card-more {+ flex-shrink: 0;+ width: 22px;+ height: 22px;+ padding: 0;+ margin-right: -4px;+ border: none;+ background: transparent;+ color: var(--muted);+ font-size: 16px;+ line-height: 1;+ border-radius: 4px;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ visibility: hidden;+}+.app-card:hover .app-card-more,+.app-card.is-menu-open .app-card-more { visibility: visible; }+.app-card-more:hover { background: rgba(15, 23, 42, 0.08); color: #334155; }+.app-card-hint {+ font-size: 12px;+ color: #94a3b8;+}+.chat-queue-header {display: flex;align-items: center;diff --git a/test/main/features/chat_artifacts.test.ts b/test/main/features/chat_artifacts.test.tsnew file mode 100644index 00000000..cf4ea18d--- /dev/null+++ b/test/main/features/chat_artifacts.test.ts@@ -0,0 +1,281 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++const UID = 'u-artifact-001';+const CID = 'conv-art-1';+const AGENT = 'helper';++let tmpDir: string;+let prevWs: string | undefined;++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-chatart-'));+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ vi.resetModules();+ const users = await import('../../../src/main/features/users');+ users.activateUser(UID);+});++afterEach(() => {+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++async function loadMod() {+ return import('../../../src/main/features/chat_artifacts');+}++function cidDir(): string {+ return path.join(tmpDir, UID, 'cloud', 'chat_artifacts', CID);+}++const MIN_FILES = [{ path: 'index.html', content: '<!doctype html><h1>hi</h1>' }];++describe('chat_artifacts › createArtifact', () => {+ it('accepts a minimal one-file app, stamps meta, returns the id', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, { title: 'Tip calc', files: MIN_FILES });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.artifactId).toMatch(/^[A-Za-z0-9_-]{8,}$/);+ expect(r.title).toBe('Tip calc');+ const dir = path.join(cidDir(), r.artifactId);+ expect(fs.readFileSync(path.join(dir, 'index.html'), 'utf8')).toContain('<h1>hi</h1>');+ const meta = JSON.parse(fs.readFileSync(path.join(dir, '__orkas-meta.json'), 'utf8'));+ expect(meta.title).toBe('Tip calc');+ expect(meta.agentId).toBe(AGENT);+ expect(typeof meta.createdAt).toBe('string');+ // No leftover temp dir.+ expect(fs.readdirSync(cidDir()).some((n) => n.includes('.tmp-'))).toBe(false);+ });++ it('accepts a multi-file app with a nested asset', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, {+ title: 'Dash',+ files: [+ { path: 'index.html', content: '<!doctype html><script src="assets/app.js"></script>' },+ { path: 'assets/app.js', content: 'console.log(1)' },+ { path: 'style.css', content: 'body{margin:0}' },+ ],+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ const dir = path.join(cidDir(), r.artifactId);+ expect(fs.existsSync(path.join(dir, 'assets', 'app.js'))).toBe(true);+ expect(fs.existsSync(path.join(dir, 'style.css'))).toBe(true);+ });++ it('accepts base64-encoded binary content for an image asset', async () => {+ const m = await loadMod();+ const pngB64 = Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString('base64');+ const r = m.createArtifact(UID, CID, AGENT, {+ files: [+ { path: 'index.html', content: '<!doctype html><img src="logo.png">' },+ { path: 'logo.png', content: pngB64, encoding: 'base64' },+ ],+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ const buf = fs.readFileSync(path.join(cidDir(), r.artifactId, 'logo.png'));+ expect([...buf.subarray(0, 4)]).toEqual([0x89, 0x50, 0x4e, 0x47]);+ });++ it('rejects: no index.html', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, { files: [{ path: 'main.html', content: 'x' }] });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/index\.html/);+ });++ it('rejects: empty / non-array files', async () => {+ const m = await loadMod();+ expect((m.createArtifact(UID, CID, AGENT, { files: [] }) as { ok: boolean }).ok).toBe(false);+ expect((m.createArtifact(UID, CID, AGENT, { files: 'nope' as unknown as [] }) as { ok: boolean }).ok).toBe(false);+ });++ it('rejects: path traversal in a file path', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, {+ files: [{ path: 'index.html', content: 'x' }, { path: '../escape.js', content: 'x' }],+ });+ expect(r.ok).toBe(false);+ });++ it('rejects: absolute file path', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, {+ files: [{ path: 'index.html', content: 'x' }, { path: '/etc/passwd', content: 'x' }],+ });+ // leading slash is stripped → "etc/passwd" with no extension → unsupported ext+ expect(r.ok).toBe(false);+ });++ it('rejects: reserved __orkas-meta.json / __orkas/ paths', async () => {+ const m = await loadMod();+ expect((m.createArtifact(UID, CID, AGENT, { files: [{ path: 'index.html', content: 'x' }, { path: '__orkas-meta.json', content: '{}' }] }) as { ok: boolean }).ok).toBe(false);+ expect((m.createArtifact(UID, CID, AGENT, { files: [{ path: 'index.html', content: 'x' }, { path: '__orkas/bridge.js', content: 'x' }] }) as { ok: boolean }).ok).toBe(false);+ });++ it('rejects: disallowed extension', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, {+ files: [{ path: 'index.html', content: 'x' }, { path: 'evil.exe', content: 'AA==', encoding: 'base64' }],+ });+ expect(r.ok).toBe(false);+ });++ it('rejects: too many files', async () => {+ const m = await loadMod();+ const files = [{ path: 'index.html', content: 'x' }];+ for (let i = 0; i < 25; i++) files.push({ path: `f${i}.js`, content: 'x' });+ const r = m.createArtifact(UID, CID, AGENT, { files });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/too many files/);+ });++ it('rejects: a single file over the per-file cap', async () => {+ const m = await loadMod();+ const big = 'a'.repeat(300 * 1024);+ const r = m.createArtifact(UID, CID, AGENT, { files: [{ path: 'index.html', content: '<x>' }, { path: 'big.js', content: big }] });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/per-file cap/);+ });++ it('rejects: bundle over the total cap', async () => {+ const m = await loadMod();+ const chunk = 'a'.repeat(200 * 1024);+ const r = m.createArtifact(UID, CID, AGENT, {+ files: [+ { path: 'index.html', content: '<x>' },+ { path: 'a.js', content: chunk },+ { path: 'b.js', content: chunk },+ { path: 'c.js', content: chunk },+ { path: 'd.js', content: chunk },+ { path: 'e.js', content: chunk },+ { path: 'f.js', content: chunk },+ ],+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/total cap/);+ });++ it('rejects: utf8-encoded content for a binary extension', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, { files: [{ path: 'index.html', content: '<x>' }, { path: 'logo.png', content: 'not base64 binary' }] });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/base64/);+ });++ it('rejects: duplicate file paths (case-insensitive)', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, { files: [{ path: 'index.html', content: 'x' }, { path: 'Index.HTML', content: 'y' }] });+ expect(r.ok).toBe(false);+ });+});++describe('chat_artifacts › resolveArtifactFilePath', () => {+ async function seed() {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, {+ files: [+ { path: 'index.html', content: '<!doctype html><h1>hi</h1>' },+ { path: 'assets/app.js', content: 'console.log(2)' },+ ],+ });+ if (!r.ok) throw new Error('seed failed: ' + r.error);+ return { m, artifactId: r.artifactId };+ }++ it('resolves index.html (explicit and via empty relpath)', async () => {+ const { m, artifactId } = await seed();+ for (const rel of ['index.html', '', '/']) {+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, rel);+ expect(got.ok).toBe(true);+ if (!got.ok) continue;+ expect(got.absPath.endsWith(`${path.sep}index.html`)).toBe(true);+ expect(got.mime).toMatch(/text\/html/);+ }+ });++ it('resolves a nested asset with the right mime', async () => {+ const { m, artifactId } = await seed();+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, 'assets/app.js');+ expect(got.ok).toBe(true);+ if (!got.ok) return;+ expect(got.mime).toMatch(/javascript/);+ });++ it('rejects: path traversal (../)', async () => {+ const { m, artifactId } = await seed();+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, '../../etc/passwd');+ expect(got.ok).toBe(false);+ if (got.ok) return;+ expect(got.code).toBe('bad_input'); // safeRelPath rejects ".." segments before disk+ });++ it('rejects: absolute path', async () => {+ const { m, artifactId } = await seed();+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, '/etc/passwd');+ expect(got.ok).toBe(false);+ });++ it('rejects: missing file', async () => {+ const { m, artifactId } = await seed();+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, 'nope.js');+ expect(got.ok).toBe(false);+ if (got.ok) return;+ expect(got.code).toBe('not_found');+ });++ it('rejects: a bare directory name (no served extension)', async () => {+ const { m, artifactId } = await seed();+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, 'assets');+ expect(got.ok).toBe(false);+ if (got.ok) return;+ expect(got.code).toBe('forbidden'); // no served extension+ });++ it('rejects: disallowed extension on the request', async () => {+ const { m, artifactId } = await seed();+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, 'shell.exe');+ expect(got.ok).toBe(false);+ if (got.ok) return;+ expect(got.code).toBe('forbidden');+ });++ it('rejects: bad cid / bad artifactId', async () => {+ const { m, artifactId } = await seed();+ expect((m.resolveArtifactFilePath(UID, 'bad/cid', artifactId, 'index.html') as { ok: boolean }).ok).toBe(false);+ expect((m.resolveArtifactFilePath(UID, CID, 'bad/id', 'index.html') as { ok: boolean }).ok).toBe(false);+ expect((m.resolveArtifactFilePath(UID, CID, '..', 'index.html') as { ok: boolean }).ok).toBe(false);+ });++ it('rejects: anything under the reserved __orkas/ prefix', async () => {+ const { m, artifactId } = await seed();+ const got = m.resolveArtifactFilePath(UID, CID, artifactId, '__orkas/secrets.js');+ expect(got.ok).toBe(false);+ });+});++describe('chat_artifacts › purgeByCid', () => {+ it('removes the whole chat_artifacts/<cid>/ tree', async () => {+ const m = await loadMod();+ expect(m.createArtifact(UID, CID, AGENT, { files: MIN_FILES }).ok).toBe(true);+ expect(m.createArtifact(UID, CID, AGENT, { files: MIN_FILES }).ok).toBe(true);+ expect(fs.existsSync(cidDir())).toBe(true);+ const n = await m.purgeByCid(UID, CID);+ expect(n).toBe(2);+ expect(fs.existsSync(cidDir())).toBe(false);+ // Idempotent.+ expect(await m.purgeByCid(UID, CID)).toBe(0);+ });+});diff --git a/test/main/features/saved_apps.test.ts b/test/main/features/saved_apps.test.tsnew file mode 100644index 00000000..fe7cebe3--- /dev/null+++ b/test/main/features/saved_apps.test.ts@@ -0,0 +1,213 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++// `saved_apps.ts` → `chats.ts` → `group_chat` pulls in `model/client`; mock it+// so nothing tries a real LLM call (the openForEditing path doesn't dispatch a+// worker, but the mock keeps the import graph inert and matches chats.test.ts).+vi.mock('../../../src/main/model/client', () => ({+ async *streamChatWithModel(_opts: any) { yield { type: 'final', text: '' }; yield { type: 'done' }; },+ async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },+}));++const UID = 'u-savedapps-001';+const CID = 'conv-sa-1';++let tmpDir: string;+let prevWs: string | undefined;++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-savedapps-'));+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ vi.resetModules();+ const users = await import('../../../src/main/features/users');+ users.activateUser(UID);+});++afterEach(() => {+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++async function mods() {+ const savedApps = await import('../../../src/main/features/saved_apps');+ const chatArtifacts = await import('../../../src/main/features/chat_artifacts');+ return { savedApps, chatArtifacts };+}++const APPS_ROOT = () => path.join(tmpDir, UID, 'cloud', 'saved_apps');++/** Make a chat artifact and return its id. */+async function makeArtifact(title: string, extra: Array<{ path: string; content: string }> = []) {+ const { chatArtifacts } = await mods();+ const r = chatArtifacts.createArtifact(UID, CID, 'helper', {+ title,+ files: [{ path: 'index.html', content: `<!doctype html><h1>${title}</h1>` }, ...extra],+ });+ if (!r.ok) throw new Error(`createArtifact failed: ${(r as { error: string }).error}`);+ return r.artifactId;+}++describe('saved_apps › saveFromArtifact', () => {+ it('copies the bundle (sans source meta) + stamps a provenance meta', async () => {+ const aid = await makeArtifact('Tip calc', [{ path: 'assets/app.js', content: 'console.log(1)' }]);+ const { savedApps } = await mods();+ const r = savedApps.saveFromArtifact(UID, CID, aid);+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.id).toMatch(/^[A-Za-z0-9_-]{8,}$/);+ expect(r.title).toBe('Tip calc');+ const dir = path.join(APPS_ROOT(), r.id);+ expect(fs.readFileSync(path.join(dir, 'index.html'), 'utf8')).toContain('<h1>Tip calc</h1>');+ expect(fs.existsSync(path.join(dir, 'assets', 'app.js'))).toBe(true);+ const meta = JSON.parse(fs.readFileSync(path.join(dir, '__orkas-meta.json'), 'utf8'));+ expect(meta.title).toBe('Tip calc');+ expect(meta.sourceCid).toBe(CID);+ expect(meta.sourceArtifactId).toBe(aid);+ expect(typeof meta.savedAt).toBe('string');+ // The source artifact's own meta name must not have been carried over verbatim+ // (it is, but rewritten) — agentId from the artifact meta should be gone.+ expect('agentId' in meta).toBe(false);+ // No leftover temp dir.+ expect(fs.readdirSync(APPS_ROOT()).some((n) => n.includes('.tmp-'))).toBe(false);+ });++ it('rejects a bad cid, a bad artifactId, and a missing artifact', async () => {+ const { savedApps } = await mods();+ expect(savedApps.saveFromArtifact(UID, '../evil', 'whatever').ok).toBe(false);+ expect(savedApps.saveFromArtifact(UID, CID, 'has/slash').ok).toBe(false);+ expect(savedApps.saveFromArtifact(UID, CID, 'Zm9vYmFyAA').ok).toBe(false); // well-formed id, no such dir+ });+});++describe('saved_apps › resolveSavedAppIndex', () => {+ it('resolves a real app and rejects bad / missing ids', async () => {+ const aid = await makeArtifact('Game');+ const { savedApps } = await mods();+ const saved = savedApps.saveFromArtifact(UID, CID, aid);+ if (!saved.ok) throw new Error('save failed');++ const ok = savedApps.resolveSavedAppIndex(UID, saved.id);+ expect(ok.ok).toBe(true);+ if (ok.ok) expect(fs.readFileSync(ok.absPath, 'utf8')).toContain('<h1>Game</h1>');++ const bad = savedApps.resolveSavedAppIndex(UID, '../etc');+ expect(bad.ok).toBe(false);+ if (!bad.ok) expect(bad.code).toBe('bad_input');++ const missing = savedApps.resolveSavedAppIndex(UID, 'Zm9vYmFyAA');+ expect(missing.ok).toBe(false);+ if (!missing.ok) expect(missing.code).toBe('not_found');+ });+});++describe('saved_apps › rename / delete', () => {+ it('renameSavedApp rewrites the meta title; empty title is refused', async () => {+ const aid = await makeArtifact('Old');+ const { savedApps } = await mods();+ const saved = savedApps.saveFromArtifact(UID, CID, aid);+ if (!saved.ok) throw new Error('save failed');++ expect(savedApps.renameSavedApp(UID, saved.id, ' ').ok).toBe(false);+ const r = savedApps.renameSavedApp(UID, saved.id, 'New name');+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.title).toBe('New name');+ const meta = JSON.parse(fs.readFileSync(path.join(APPS_ROOT(), saved.id, '__orkas-meta.json'), 'utf8'));+ expect(meta.title).toBe('New name');+ });++ it('deleteSavedApp removes the directory', async () => {+ const aid = await makeArtifact('Doomed');+ const { savedApps } = await mods();+ const saved = savedApps.saveFromArtifact(UID, CID, aid);+ if (!saved.ok) throw new Error('save failed');+ const dir = path.join(APPS_ROOT(), saved.id);+ expect(fs.existsSync(dir)).toBe(true);+ expect(savedApps.deleteSavedApp(UID, saved.id).ok).toBe(true);+ expect(fs.existsSync(dir)).toBe(false);+ // Idempotent — deleting again is still ok.+ expect(savedApps.deleteSavedApp(UID, saved.id).ok).toBe(true);+ // Bad id is refused.+ expect(savedApps.deleteSavedApp(UID, '../boom').ok).toBe(false);+ });+});++describe('saved_apps › listSavedApps', () => {+ it('lists A→Z by title and tolerates a corrupt meta (fallback title, still listed)', async () => {+ const { savedApps } = await mods();+ const a1 = await makeArtifact('Zebra');+ const a2 = await makeArtifact('alpha');+ const s1 = savedApps.saveFromArtifact(UID, CID, a1);+ const s2 = savedApps.saveFromArtifact(UID, CID, a2);+ if (!s1.ok || !s2.ok) throw new Error('save failed');+ // Corrupt one app's meta.+ fs.writeFileSync(path.join(APPS_ROOT(), s1.id, '__orkas-meta.json'), '{ not json');+ // A non-conforming directory name must be ignored.+ fs.mkdirSync(path.join(APPS_ROOT(), 'has space'), { recursive: true });++ const list = savedApps.listSavedApps(UID);+ expect(list.map((x) => x.id).sort()).toEqual([s1.id, s2.id].sort());+ // s2 ("alpha") sorts before s1 (corrupt → "Interactive app").+ expect(list[0].id).toBe(s2.id);+ expect(list[0].title).toBe('alpha');+ const corrupt = list.find((x) => x.id === s1.id);+ expect(corrupt?.title).toBe('Interactive app');+ });++ it('returns [] when the pool dir does not exist', async () => {+ const { savedApps } = await mods();+ // No save has happened, but activateUser mkdir's the skeleton including+ // saved_apps/ — remove it to exercise the missing-dir branch.+ fs.rmSync(APPS_ROOT(), { recursive: true, force: true });+ expect(savedApps.listSavedApps(UID)).toEqual([]);+ });+});++describe('saved_apps › openForEditing', () => {+ function attachDir(cid: string): string {+ return path.join(tmpDir, UID, 'cloud', 'chat_attachments', cid);+ }++ it('creates a conversation and bundles every source file into app-source.md', async () => {+ const { savedApps, chatArtifacts } = await mods();+ const chats = await import('../../../src/main/features/chats');+ const aid = await makeArtifact('Snake', [+ { path: 'assets/app.js', content: 'const SPEED = 7; // tweak me' },+ { path: 'style.css', content: 'body { background: #000 }' },+ ]);+ const saved = savedApps.saveFromArtifact(UID, CID, aid);+ if (!saved.ok) throw new Error('save failed');++ const before = (await chats.listConversations(UID)).length;+ const r = await savedApps.openForEditing(UID, saved.id);+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ const conv = r.conversation as { conversation_id: string };+ expect(typeof conv.conversation_id).toBe('string');+ expect(r.sourceFileName).toBe('app-source.md');+ expect((await chats.listConversations(UID)).length).toBe(before + 1);++ const bundlePath = path.join(attachDir(conv.conversation_id), r.sourceFileName);+ const bundle = fs.readFileSync(bundlePath, 'utf8');+ expect(bundle).toContain('========== FILE: index.html ==========');+ expect(bundle).toContain('<h1>Snake</h1>');+ expect(bundle).toContain('========== FILE: assets/app.js ==========');+ expect(bundle).toContain('const SPEED = 7; // tweak me');+ expect(bundle).toContain('========== FILE: style.css ==========');+ expect(bundle).toContain('body { background: #000 }');+ // The source meta file must not be dumped into the bundle.+ expect(bundle).not.toContain('__orkas-meta.json');+ void chatArtifacts;+ });++ it('rejects a bad / missing appId and leaves no conversation behind', async () => {+ const { savedApps } = await mods();+ const chats = await import('../../../src/main/features/chats');+ const before = (await chats.listConversations(UID)).length;+ expect((await savedApps.openForEditing(UID, '../evil')).ok).toBe(false);+ expect((await savedApps.openForEditing(UID, 'Zm9vYmFyAA')).ok).toBe(false); // well-formed id, no such app+ expect((await chats.listConversations(UID)).length).toBe(before);+ });+});diff --git a/test/main/model/core-agent/local-tools.test.ts b/test/main/model/core-agent/local-tools.test.tsindex 5b352da3..42878925 100644--- a/test/main/model/core-agent/local-tools.test.ts+++ b/test/main/model/core-agent/local-tools.test.ts@@ -222,3 +222,70 @@ describe('local-tools › edit_file › onFileWritten', () => {expect(written).toEqual([]);});});++// ── create_artifact ──────────────────────────────────────────────────────+// Deep input validation lives in `chat_artifacts.test.ts`; here we pin the+// runner-side wiring: the gate, the cid+sink presence condition, the+// onArtifactCreated callback, and that backend rejections surface as isError.++async function buildCreateArtifactTool(opts: { cid?: string | null; onArtifactCreated?: (a: { id: string; title: string }) => void; agentId?: string } = {}) {+ const localTools = await import('../../../../src/main/model/core-agent/local-tools');+ const tools = localTools.createLocalTools({+ userId: UID,+ ...(opts.cid === undefined ? { cid: CID } : opts.cid ? { cid: opts.cid } : {}),+ ...(opts.agentId ? { agentId: opts.agentId } : {}),+ ...(opts.onArtifactCreated ? { onArtifactCreated: opts.onArtifactCreated } : {}),+ });+ return tools.find((t) => t.name === 'create_artifact') || null;+}++const MIN_FILES = [{ path: 'index.html', content: '<!doctype html><h1>hi</h1>' }];++describe('local-tools › create_artifact › availability', () => {+ it('is offered only when both cid and onArtifactCreated are present', async () => {+ expect(await buildCreateArtifactTool({ cid: CID, onArtifactCreated: () => {} })).toBeTruthy();+ // no sink → not offered (edit chats / ad-hoc runs)+ expect(await buildCreateArtifactTool({ cid: CID })).toBeNull();+ // no cid → not offered+ expect(await buildCreateArtifactTool({ cid: null, onArtifactCreated: () => {} })).toBeNull();+ });+});++describe('local-tools › create_artifact › permission gate', () => {+ it('rejects when localExec not granted', async () => {+ const tool = await buildCreateArtifactTool({ onArtifactCreated: () => {} });+ expect(tool).toBeTruthy();+ const r = await run(tool, { title: 'X', files: MIN_FILES });+ expect(r.isError).toBe(true);+ expect(r.content).toMatch(/Local execution is not authorised/i);+ });+});++describe('local-tools › create_artifact › success + callback', () => {+ it('writes the bundle, fires onArtifactCreated, and tells the model not to paste HTML', async () => {+ await grant();+ const created: Array<{ id: string; title: string }> = [];+ const tool = await buildCreateArtifactTool({ agentId: 'helper', onArtifactCreated: (a) => created.push(a) });+ const r = await run(tool, { title: 'Tip calc', files: MIN_FILES });+ expect(r.isError).toBeFalsy();+ expect(created.length).toBe(1);+ expect(created[0].title).toBe('Tip calc');+ expect(created[0].id).toMatch(/^[A-Za-z0-9_-]{8,}$/);+ expect(r.content).toMatch(/do NOT paste/i);+ const dir = path.join(tmpDir, UID, 'cloud', 'chat_artifacts', CID, created[0].id);+ expect(fs.readFileSync(path.join(dir, 'index.html'), 'utf8')).toContain('<h1>hi</h1>');+ expect(JSON.parse(fs.readFileSync(path.join(dir, '__orkas-meta.json'), 'utf8')).agentId).toBe('helper');+ });+});++describe('local-tools › create_artifact › backend rejection surfaces as isError', () => {+ it('missing index.html → isError, no callback', async () => {+ await grant();+ const created: unknown[] = [];+ const tool = await buildCreateArtifactTool({ onArtifactCreated: (a) => created.push(a) });+ const r = await run(tool, { files: [{ path: 'main.html', content: 'x' }] });+ expect(r.isError).toBe(true);+ expect(r.content).toMatch(/index\.html/);+ expect(created).toEqual([]);+ });+});diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.tsindex 3c52cad8..6f5545b7 100644--- a/test/main/model/core-agent/tool-catalog.test.ts+++ b/test/main/model/core-agent/tool-catalog.test.ts@@ -39,8 +39,10 @@ function enumerateAllInjectedToolNames(): Set<string> {}).name,);- // local + file + kb + image gen- for (const t of createLocalTools({})) names.add(t.name);+ // local + file + kb + image gen.+ // Pass cid + onArtifactCreated so `create_artifact` is included — runner.ts+ // wires both through for group-chat turns (see local-tools.createLocalTools).+ for (const t of createLocalTools({ userId: 'testuid', cid: 'testcid', onArtifactCreated: () => {} })) names.add(t.name);for (const t of createFileTools({ userId: 'testuid', cid: 'testcid' })) names.add(t.name);for (const t of createKbTools({ userId: 'testuid' })) names.add(t.name);names.add(createImageGenTool({ userId: 'testuid', cid: 'testcid' }).name);diff --git a/test/renderer/strip-structural-blocks.test.ts b/test/renderer/strip-structural-blocks.test.tsindex 861bd345..e3ff56c1 100644--- a/test/renderer/strip-structural-blocks.test.ts+++ b/test/renderer/strip-structural-blocks.test.ts@@ -294,6 +294,43 @@ describe('<agent-input-submission> — set B (literal mentions survive)', () =>});});+// `<artifact-result>` — the machine tag a renderer composes when an+// interactive artifact posts a result back; carried in a user message so+// the agent can parse it, stripped from the user bubble's display via+// `_stripArtifactResultTagForDisplay` (which delegates to `_stripOuterTagBlocks`).+// Same whack-a-mole class as the submission tag — pin set A + set B.+describe('<artifact-result> — set A (real result tags stripped from display)', () => {+ it('A1. result tag with attributes and a JSON payload body', () => {+ const buf = 'Result from "Tip calc"\n\n<artifact-result artifact_id="abc123" agent_id="helper">\n{"payload":{"tip":18,"total":118}}\n</artifact-result>';+ expect(_stripOuterTagBlocks(buf, 'artifact-result')).toBe('Result from "Tip calc"\n\n');+ });++ it('A2. payload JSON value contains backticks / angle brackets — still atomic', () => {+ const buf = 'Result from "Editor"\n\n<artifact-result artifact_id="x" agent_id="a">\n{"payload":{"code":"a `b` <c>"}}\n</artifact-result>\nthanks';+ const out = _stripOuterTagBlocks(buf, 'artifact-result');+ expect(out).not.toContain('artifact-result');+ expect(out).not.toContain('`b`');+ expect(out).toBe('Result from "Editor"\n\n\nthanks');+ });+});++describe('<artifact-result> — set B (literal mentions survive)', () => {+ it('B1. inside a fenced ```xml block (e.g. the tool description quoting the protocol)', () => {+ const buf = 'Format:\n```xml\n<artifact-result artifact_id="x" agent_id="y">\n{...}\n</artifact-result>\n```';+ expect(_stripOuterTagBlocks(buf, 'artifact-result')).toBe(buf);+ });++ it('B2. inside an inline backtick span', () => {+ const buf = 'The renderer posts a `<artifact-result ...>` tag back to you.';+ expect(_stripOuterTagBlocks(buf, 'artifact-result')).toBe(buf);+ });++ it('B3. UNCLOSED inline backtick', () => {+ const buf = 'see `<artifact-result';+ expect(_stripOuterTagBlocks(buf, 'artifact-result')).toBe(buf);+ });+});+// --- Boundary check: tagName lookup must not bleed across siblings -------describe('boundary check — `<agent>` lookup must not match `<agent-input-form>`', () => {@@ -344,6 +381,13 @@ describe('_stripSurvivingStructuralBlocks (final-time safety strip)', () => {expect(_stripSurvivingStructuralBlocks(buf)).toBe('lead\n\ntail');});+ it('strips a leaked <artifact-result> in assistant text but preserves a literal mention in code', () => {+ const real = 'lead\n<artifact-result artifact_id="x" agent_id="a">{"payload":1}</artifact-result>\ntail';+ expect(_stripSurvivingStructuralBlocks(real)).toBe('lead\n\ntail');+ const literal = 'Post back a `<artifact-result ...>` tag.';+ expect(_stripSurvivingStructuralBlocks(literal)).toBe(literal);+ });+it('strips all three tags coexisting in one buffer', () => {const buf = ['before',