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
Harden compacted artifact context handling
wyt4f1fcf914ec1
diff --git a/CLAUDE.md b/CLAUDE.mdindex 217622ce..aac27a12 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -125,6 +125,7 @@ Attachments:## Skills, Agents, And Marketplace- Skill sources are custom cloud skills plus platform local marketplace installs. Custom overrides platform by id.+- Platform builtin agents/skills are product content, not platform libraries. Runtime-facing platform code must not import/require files from `resources/builtin/...`, hard-code a builtin agent/skill id as a business dependency, or call a builtin skill script directly for shared logic. The only allowed direct reads of `resources/builtin` are seed/reconcile/build/eval flows that materialize or verify marketplace content. If platform code and a skill need the same logic, move that logic into a generic `src/main/features/*` or `src/main/util/*` module; skill scripts may call platform modules, but platform modules must not depend on a marketplace agent/skill. Runtime skill execution goes through `bin/run-skill.cjs` against the installed skill tier, not a packaged builtin path.- Agent/skill category belongs in the spec (`agent.json` or SKILL.md frontmatter); install freshness belongs in `_install.json` / install manifests.- Creator skills (`agent-creator`, `skill-creator`) are the canonical source for authoring semantics, validation details, and category candidates.- Creator skill paths under the PC data root: `<uid>/local/marketplace/skills/16e1bfcb3426/SKILL.md` (`agent-creator`) and `<uid>/local/marketplace/skills/efb0fe5d9664/SKILL.md` (`skill-creator`).diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.tsindex dd32a6c1..867699ef 100644--- a/src/core-agent/src/agent/runner.ts+++ b/src/core-agent/src/agent/runner.ts@@ -19,7 +19,7 @@ import { toToolDefinition } from "../tools/base.js";import { getBuiltinTools } from "../tools/builtin.js";import { SkillStore } from "../evolution/skill-store.js";import { createSkillManageTool } from "../evolution/skill-tools.js";-import { Session } from "./session.js";+import { COMPACTED_TOOL_USE_INPUT_KEY, Session } from "./session.js";import type { AgentRunParams, AgentRunResult, AgentRunMeta, AgentRunEvent } from "./types.js";const log = createLogger("agent-runner");@@ -917,7 +917,7 @@ export class AgentRunner {systemPrompt: string,cacheRetention?: "none" | "short" | "long",): Promise<string> {- const messages = this.session.getMessagesForModel();+ const messages = this.session.getMessagesForSummary();if (messages.length <= 4) return '';// Ask the LLM to summarize the conversation@@ -1162,6 +1162,18 @@ async function runToolWithWatchdog(opts: {};if (signal?.aborted) return abortResult();+ const compactedInputMarker = findCompactedToolInputMarker(call.input);+ if (compactedInputMarker) {+ const result = {+ content:+ `Rejected ${call.name}: tool input contains an Orkas compacted-history marker (${compactedInputMarker}). ` ++ "This is only a preview of an already executed old tool call, not valid tool input. " ++ "Inspect the paired tool_result, read the current file, or regenerate the full arguments before calling a tool.",+ isError: true,+ };+ emitToolEnd(result);+ return { result };+ }const toolAbort = createChildAbortController(signal);const toolIdle = createToolIdleWatchdog(toolIdleTimeoutMs);@@ -1235,6 +1247,45 @@ async function runToolWithWatchdog(opts: {}}+function findCompactedToolInputMarker(value: unknown): string | null {+ const visit = (entry: unknown): string | null => {+ if (typeof entry === "string") {+ if (entry.startsWith("[old tool input string compacted:")) {+ return "[old tool input string compacted]";+ }+ if (entry.startsWith("[old nested tool input ")) {+ return "[old nested tool input]";+ }+ if (/^Old .+ tool input compacted for repeated context;/.test(entry)) {+ return "old tool input context note";+ }+ return null;+ }+ if (Array.isArray(entry)) {+ for (const item of entry) {+ const found = visit(item);+ if (found) return found;+ }+ return null;+ }+ if (entry && typeof entry === "object") {+ const record = entry as Record<string, unknown>;+ if (Object.prototype.hasOwnProperty.call(record, "__orkas_context_note")) {+ return "__orkas_context_note";+ }+ if (Object.prototype.hasOwnProperty.call(record, COMPACTED_TOOL_USE_INPUT_KEY)) {+ return COMPACTED_TOOL_USE_INPUT_KEY;+ }+ for (const item of Object.values(record)) {+ const found = visit(item);+ if (found) return found;+ }+ }+ return null;+ };+ return visit(value);+}+async function executeReflectionTool(tool: AgentTool,input: Record<string, unknown>,diff --git a/src/core-agent/src/agent/session.ts b/src/core-agent/src/agent/session.tsindex fa8ee575..e0ca57d8 100644--- a/src/core-agent/src/agent/session.ts+++ b/src/core-agent/src/agent/session.ts@@ -63,6 +63,8 @@ const DEFAULT_TOOL_RESULT_COMPACTION: NormalizedToolResultCompactionOptions = {type ToolResultCompactionMode = "full-preview" | "aggregate-ref";type ToolUseInputCompactionMode = "full-preview" | "aggregate-ref";+export const COMPACTED_TOOL_USE_INPUT_KEY = "__orkas_compacted_tool_use";+/*** Session manages the conversation history for an agent run.*@@ -141,6 +143,22 @@ export class Session {* old image bytes. The image can still be reopened by calling read_file(path).*/getMessagesForModel(): Message[] {+ return this.buildMessagesForModel();+ }++ /**+ * Get the summarizer-facing view of the session.+ *+ * This is intentionally built from raw session messages, not by reusing a+ * previously materialized model view. Old tool inputs are represented as+ * inert metadata so compaction summaries cannot learn executable-looking+ * preview arguments from historical tool calls.+ */+ getMessagesForSummary(): Message[] {+ return this.buildMessagesForModel();+ }++ private buildMessagesForModel(): Message[] {let lastAssistantIndex = -1;for (let i = this.messages.length - 1; i >= 0; i--) {if (this.messages[i].role === "assistant") {@@ -430,18 +448,16 @@ export class Session {rawInputJson: string,mode: ToolUseInputCompactionMode,): Record<string, unknown> {- const opts = this.toolResultCompaction;- if (!opts) return input;-- const compacted = compactToolUseValue(input, opts, 0);- if (!isPlainObject(compacted)) return input;-- const note = (- `Old ${toolName} tool input compacted for repeated context; ` +- `mode=${mode}, original_json_chars=${rawInputJson.length}. ` +- "The tool call already executed; inspect the paired tool_result or current files if more detail is needed."- );- return { ...compacted, __orkas_context_note: note };+ return {+ [COMPACTED_TOOL_USE_INPUT_KEY]: {+ tool: toolName,+ mode,+ original_json_chars: rawInputJson.length,+ input_keys: Object.keys(input).slice(0, 20),+ note:+ "Historical tool input omitted from model context. This call already executed; inspect the paired tool_result or current files instead of reusing this object as tool input.",+ },+ };}private compactToolResultContent(@@ -562,64 +578,6 @@ function isImageOnlyMessage(msg: Message): boolean {return msg.role === "user" && msg.content.length > 0 && msg.content.every((c) => c.type === "image");}-const TOOL_USE_ARRAY_HEAD_ITEMS = 16;-const TOOL_USE_ARRAY_TAIL_ITEMS = 4;-const TOOL_USE_INPUT_MAX_DEPTH = 8;--function compactToolUseValue(- value: unknown,- opts: NormalizedToolResultCompactionOptions,- depth: number,-): unknown {- if (typeof value === "string") return compactToolUseString(value, opts);- if (Array.isArray(value)) {- if (depth >= TOOL_USE_INPUT_MAX_DEPTH) {- return `[old nested tool input array omitted: items=${value.length}]`;- }- const compactItem = (item: unknown) => compactToolUseValue(item, opts, depth + 1);- const keepCount = TOOL_USE_ARRAY_HEAD_ITEMS + TOOL_USE_ARRAY_TAIL_ITEMS;- if (value.length <= keepCount + 1) return value.map(compactItem);- return [- ...value.slice(0, TOOL_USE_ARRAY_HEAD_ITEMS).map(compactItem),- { __orkas_omitted_array_items: value.length - keepCount },- ...value.slice(-TOOL_USE_ARRAY_TAIL_ITEMS).map(compactItem),- ];- }- if (isPlainObject(value)) {- if (depth >= TOOL_USE_INPUT_MAX_DEPTH) {- return `[old nested tool input object omitted: keys=${Object.keys(value).length}]`;- }- const out: Record<string, unknown> = {};- for (const [key, entry] of Object.entries(value)) {- out[key] = compactToolUseValue(entry, opts, depth + 1);- }- return out;- }- return value;-}--function compactToolUseString(- value: string,- opts: NormalizedToolResultCompactionOptions,-): string {- if (value.length < opts.toolUseInputStringMinChars) return value;-- const previewChars = Math.max(32, opts.toolUseInputPreviewChars);- const headChars = Math.ceil(previewChars * 0.7);- const tailChars = Math.max(0, previewChars - headChars);- const head = value.slice(0, headChars);- const tail = tailChars > 0 && value.length > headChars + tailChars- ? value.slice(-tailChars)- : "";- const tailBlock = tail ? `\npreview_tail:\n${tail}` : "";- const compacted = (- `[old tool input string compacted: original_size=${value.length} chars]\n` +- `preview_head:\n${head}` +- tailBlock- );- return compacted.length < value.length ? compacted : value;-}-function stringifyToolInput(input: Record<string, unknown>): string {try {return JSON.stringify(input) ?? "";@@ -628,10 +586,6 @@ function stringifyToolInput(input: Record<string, unknown>): string {}}-function isPlainObject(value: unknown): value is Record<string, unknown> {- return !!value && typeof value === "object" && !Array.isArray(value);-}-function escapeAttr(value: string): string {return value.replace(/&/g, "&")diff --git a/src/core-agent/test/agent-runner.test.ts b/src/core-agent/test/agent-runner.test.tsindex 09f4a44c..fc373ca7 100644--- a/src/core-agent/test/agent-runner.test.ts+++ b/src/core-agent/test/agent-runner.test.ts@@ -158,6 +158,112 @@ describe("AgentRunner", () => {expect(result.meta.toolLoops).toBe(1);});+ it("rejects compacted historical tool input before executing the tool", async () => {+ const mockProvider = createMockProvider([+ {+ content: [+ {+ type: "tool_use",+ id: "call_compacted",+ name: "write_file",+ input: {+ path: "index.html",+ content:+ "[old tool input string compacted: original_size=13653 chars]\n" ++ "preview_head:\n<!doctype html>",+ __orkas_context_note:+ "Old write_file tool input compacted for repeated context; mode=full-preview, original_json_chars=14000.",+ },+ },+ {+ type: "tool_use",+ id: "call_new_compacted",+ name: "write_file",+ input: {+ __orkas_compacted_tool_use: {+ tool: "write_file",+ mode: "full-preview",+ original_json_chars: 14000,+ input_keys: ["path", "content"],+ },+ },+ },+ ],+ stopReason: "tool_use",+ usage: { inputTokens: 20, outputTokens: 10, totalTokens: 30 },+ model: "mock-model",+ },+ {+ content: [{ type: "text", text: "I will regenerate the file instead." }],+ stopReason: "end_turn",+ usage: { inputTokens: 30, outputTokens: 8, totalTokens: 38 },+ model: "mock-model",+ },+ ]);++ const registry = new ProviderRegistry();+ registry.registerFactory("mock", () => mockProvider);++ let executed = 0;+ const writeTool = defineTool({+ name: "write_file",+ description: "Write a file",+ inputSchema: { type: "object", properties: {} },+ async execute() {+ executed++;+ return { content: "wrote" };+ },+ });++ const config = createConfig({+ agent: { defaultProvider: "mock", defaultModel: "mock-model" },+ });++ const runner = new AgentRunner({ config, providers: registry, tools: [writeTool] });+ const collected: Array<{ type: string; [k: string]: unknown }> = [];+ for await (const ev of runner.runStream({ message: "go" })) {+ collected.push(ev as { type: string; [k: string]: unknown });+ }+ expect(executed).toBe(0);+ const toolEnd = collected.find((e) => e.type === "tool_end");+ expect(toolEnd).toMatchObject({+ type: "tool_end",+ id: "call_compacted",+ name: "write_file",+ isError: true,+ });+ expect(String(toolEnd?.result)).toContain("compacted-history marker");+ const newToolEnd = collected.find((e) => e.type === "tool_end" && e.id === "call_new_compacted");+ expect(newToolEnd).toMatchObject({+ type: "tool_end",+ id: "call_new_compacted",+ name: "write_file",+ isError: true,+ });+ expect(String(newToolEnd?.result)).toContain("__orkas_compacted_tool_use");++ const toolResults = runner.getSession().getMessages().flatMap((msg) =>+ msg.content.filter((content) => content.type === "tool_result"),+ );+ expect(toolResults).toHaveLength(2);+ expect(toolResults[0]).toMatchObject({+ type: "tool_result",+ toolUseId: "call_compacted",+ isError: true,+ });+ expect((toolResults[0] as { content: string }).content).toContain("not valid tool input");+ expect(toolResults[1]).toMatchObject({+ type: "tool_result",+ toolUseId: "call_new_compacted",+ isError: true,+ });++ const done = collected[collected.length - 1] as { type: string; result?: { text?: string; meta?: { permanentToolErrors?: number } } };+ expect(done.type).toBe("done");+ expect(done.result?.text).toBe("I will regenerate the file instead.");+ expect(done.result?.meta?.permanentToolErrors).toBe(2);+ });+it("endTurn terminal tool ends the run with NO follow-up inference", async () => {// Round 0: model narrates + calls the terminal tool. Round 1 (a synthesis)// must NEVER be consumed — that is the saved LLM call.diff --git a/src/core-agent/test/session.test.ts b/src/core-agent/test/session.test.tsindex ede50f29..ff742e4c 100644--- a/src/core-agent/test/session.test.ts+++ b/src/core-agent/test/session.test.ts@@ -241,7 +241,7 @@ describe("Session", () => {expect(persisted).toEqual(["call-1"]);});- it("compacts old tool_use inputs only in the model view", () => {+ it("compacts old tool_use inputs to inert metadata only in the model view", () => {const session = new Session({toolResultCompaction: {minChars: 999_999,@@ -270,13 +270,25 @@ describe("Session", () => {.filter((c) => c.type === "tool_use") as Array<{ input: Record<string, unknown> }>;expect(toolUses).toHaveLength(2);- expect(toolUses[0].input.path).toBe("/tmp/a.txt");- expect(toolUses[0].input.__orkas_context_note).toEqual(expect.stringContaining("original_json_chars"));- expect(toolUses[0].input.content).toEqual(expect.stringContaining("old tool input string compacted"));- expect(toolUses[0].input.content).toEqual(expect.stringContaining("START-"));- expect(toolUses[0].input.content).toEqual(expect.stringContaining("-END"));- expect(toolUses[0].input.content).not.toBe(fileContent);- expect(toolUses[1].input.command).toEqual(expect.stringContaining("old tool input string compacted"));+ expect(toolUses[0].input).not.toHaveProperty("path");+ expect(toolUses[0].input).not.toHaveProperty("content");+ expect(toolUses[0].input.__orkas_compacted_tool_use).toMatchObject({+ tool: "write_file",+ mode: "aggregate-ref",+ input_keys: ["path", "content"],+ });+ expect(toolUses[1].input).not.toHaveProperty("command");+ expect(toolUses[1].input.__orkas_compacted_tool_use).toMatchObject({+ tool: "bash",+ mode: "aggregate-ref",+ input_keys: ["command"],+ });+ const serialized = JSON.stringify(toolUses.map((u) => u.input));+ expect(serialized).not.toContain("old tool input string compacted");+ expect(serialized).not.toContain("START-");+ expect(serialized).not.toContain("-END");+ expect(serialized).not.toContain(fileContent);+ expect(serialized).not.toContain(command);const rawToolUse = session.getMessages()[0].content[0];expect(rawToolUse.type).toBe("tool_use");@@ -309,10 +321,35 @@ describe("Session", () => {const commands = session.getMessagesForModel().flatMap((m) => m.content).filter((c) => c.type === "tool_use")- .map((c) => (c as { input: Record<string, unknown> }).input.command);+ .map((c) => (c as { input: Record<string, unknown> }).input);++ expect(commands[0]).toHaveProperty("__orkas_compacted_tool_use");+ expect(commands[0]).not.toHaveProperty("command");+ expect(commands[1].command).toBe(freshCommand);+ });++ it("uses inert old tool_use metadata in the summary view", () => {+ const session = new Session({+ toolResultCompaction: {+ minChars: 999_999,+ aggregateMinChars: 999_999,+ toolUseInputMinChars: 100,+ keepRecentAssistantSteps: 0,+ keepRecentToolResults: 0,+ keepRecentToolUses: 0,+ },+ });+ const html = "<!doctype html>" + "x".repeat(1_000);++ session.addAssistantMessage([{ type: "tool_use", id: "call-html", name: "create_artifact", input: { files: [{ path: "index.html", content: html }] } }]);+ session.addToolResult("call-html", "Artifact created", undefined, false);+ session.addAssistantMessage([{ type: "text", text: "seen" }]);- expect(commands[0]).toEqual(expect.stringContaining("old tool input string compacted"));- expect(commands[1]).toBe(freshCommand);+ const serialized = JSON.stringify(session.getMessagesForSummary());+ expect(serialized).toContain("__orkas_compacted_tool_use");+ expect(serialized).not.toContain("old tool input string compacted");+ expect(serialized).not.toContain("<!doctype html>");+ expect(serialized).not.toContain(html);});it("estimateModelTokens uses the compacted provider view", () => {diff --git a/src/main/features/chat_artifacts.ts b/src/main/features/chat_artifacts.tsindex 5cd3894d..33b019e6 100644--- a/src/main/features/chat_artifacts.ts+++ b/src/main/features/chat_artifacts.ts@@ -71,6 +71,13 @@ const META_FILENAME = '__orkas-meta.json';export const RESERVED_PREFIX = '__orkas/';export const BRIDGE_RELPATH = '__orkas/bridge.js';+const COMPACTED_HISTORY_MARKERS = [+ '[old tool input string compacted:',+ '[old nested tool input ',+ '__orkas_context_note',+ '__orkas_compacted_tool_use',+];+// ── Types ────────────────────────────────────────────────────────────────export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string };@@ -90,6 +97,10 @@ export interface ArtifactMeta {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;+export type ArtifactInspection =+ | { ok: true; status: 'ok' }+ | { ok: true; status: 'unavailable'; reason: string; marker?: string }+ | { ok: false; error: string };// ── Safe-name helpers ────────────────────────────────────────────────────@@ -293,6 +304,13 @@ export function createArtifact(}buf = Buffer.from(f.content, 'base64'); // tolerant of url-safe alphabet + whitespace} else {+ const compactedMarker = findCompactedHistoryMarker(f.content);+ if (compactedMarker) {+ return {+ ok: false,+ error: `file "${rel}": contains compacted conversation-history marker ${compactedMarker}; regenerate the full artifact content before creating it`,+ };+ }buf = Buffer.from(f.content, 'utf8');if (buf.toString('utf8') !== f.content) return { ok: false, error: `file "${rel}": content is not valid UTF-8` };}@@ -347,6 +365,38 @@ export function createArtifact(return { ok: true, artifactId, title };}+function findCompactedHistoryMarker(content: string): string | null {+ for (const marker of COMPACTED_HISTORY_MARKERS) {+ if (content.includes(marker)) return marker;+ }+ if (/Old .+ tool input compacted for repeated context;/.test(content)) {+ return 'old tool input context note';+ }+ return null;+}++export function inspectArtifactIndex(userId: string, cid: string, artifactId: string): ArtifactInspection {+ const resolved = resolveArtifactFilePath(userId, cid, artifactId, 'index.html');+ if (!resolved.ok) {+ return { ok: true, status: 'unavailable', reason: (resolved as { error?: string }).error || 'artifact index is unavailable' };+ }+ try {+ const content = fs.readFileSync((resolved as { absPath: string }).absPath, 'utf8');+ const marker = findCompactedHistoryMarker(content);+ if (marker) {+ return {+ ok: true,+ status: 'unavailable',+ reason: 'artifact index contains compacted conversation-history content',+ marker,+ };+ }+ return { ok: true, status: 'ok' };+ } catch (err) {+ return { ok: false, error: (err as Error).message || 'failed to inspect artifact index' };+ }+}+/** 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-implementingdiff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex be39d879..e6125d41 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -1228,6 +1228,12 @@ const invokeHandlers: Record<string, InvokeHandler> = {if (err) throw new Error(err);return { ok: true, path: absPath };},+ // Read-only health check used by the renderer to avoid displaying a stale+ // compacted-history preview as if it were a real interactive app.+ 'conversations.artifacts.inspect': async ({ cid, artifactId }, ctx) => {+ if (!safeId(cid)) throw new Error('invalid cid');+ return chatArtifacts.inspectArtifactIndex(ctx.userId, String(cid), String(artifactId || ''));+ },// Copy a chat artifact into the persistent "My Apps" pool// (`<uid>/cloud/saved_apps/<appId>/`). Surfaced as the artifact card's// `⋯` → "保存".diff --git a/src/renderer/modules/chat-artifact.js b/src/renderer/modules/chat-artifact.jsindex 3d594691..6388e8ce 100644--- a/src/renderer/modules/chat-artifact.js+++ b/src/renderer/modules/chat-artifact.js@@ -303,6 +303,59 @@_positionMenu(el, anchorBtn);}+ function _clearArtifactUnavailable(frame) {+ if (!frame) return;+ const panel = frame._orkasUnavailablePanel;+ if (panel && panel.remove) panel.remove();+ frame._orkasUnavailablePanel = null;+ frame.style.display = 'block';+ }++ function _showArtifactUnavailable(frame, reason) {+ if (!frame || !frame.parentNode) return;+ let panel = frame._orkasUnavailablePanel;+ if (!panel) {+ panel = document.createElement('div');+ panel.className = 'chat-artifact-unavailable';+ frame._orkasUnavailablePanel = panel;+ frame.parentNode.insertBefore(panel, frame.nextSibling);+ }+ panel.innerHTML = '';+ const title = document.createElement('div');+ title.className = 'chat-artifact-unavailable-title';+ title.textContent = _t('artifact.unavailable_title', 'Preview unavailable');+ const detail = document.createElement('div');+ detail.className = 'chat-artifact-unavailable-detail';+ detail.textContent = _t('artifact.unavailable_detail', 'This app preview cannot be displayed from the saved history.');+ panel.appendChild(title);+ panel.appendChild(detail);+ if (reason) panel.title = String(reason);+ frame.removeAttribute('src');+ frame.style.display = 'none';+ }++ async function _checkArtifactAvailability(frame, ctx) {+ if (!frame || !ctx || !ctx.cid || !ctx.artifactId) return;+ if (!window.orkas || typeof window.orkas.invoke !== 'function') return;+ const expectedCid = String(ctx.cid);+ const expectedArtifactId = String(ctx.artifactId);+ try {+ const r = await window.orkas.invoke('conversations.artifacts.inspect', {+ cid: expectedCid,+ artifactId: expectedArtifactId,+ });+ if (!frame.isConnected) return;+ if (frame.dataset.artifactCid !== expectedCid || frame.dataset.artifactId !== expectedArtifactId) return;+ if (r && r.ok === true && r.status === 'unavailable') {+ _showArtifactUnavailable(frame, r.reason || '');+ } else if (r && r.ok === true && r.status === 'ok') {+ _clearArtifactUnavailable(frame);+ }+ } catch (err) {+ _trackError('artifact_inspect', { error_message: String(err && err.message || err) });+ }+ }+function _doReload(ctx) {const f = ctx && ctx.frame;if (!f || !f.isConnected) return;@@ -310,8 +363,10 @@// 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).+ _clearArtifactUnavailable(f);f.style.height = `${DEFAULT_FRAME_HEIGHT}px`;f.src = _artifactUrl(ctx.cid, ctx.artifactId);+ _checkArtifactAvailability(f, ctx);}function _doOpen(ctx) {@@ -390,6 +445,7 @@card.appendChild(header);card.appendChild(frame);host.appendChild(card);+ _checkArtifactAvailability(frame, ctx);}// Render every artifact on a message into the given bubble. Idempotent —diff --git a/src/renderer/style.css b/src/renderer/style.cssindex f7d2a246..404cb042 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -6328,6 +6328,25 @@ body.model-not-configured .main-content { flex-direction: column; }border: 0;background: #fff;}+.chat-artifact-unavailable {+ min-height: 180px;+ padding: 22px;+ display: flex;+ flex-direction: column;+ justify-content: center;+ gap: 6px;+ background: #fff;+ color: var(--muted);+}+.chat-artifact-unavailable-title {+ font-size: 14px;+ font-weight: 600;+ color: var(--text);+}+.chat-artifact-unavailable-detail {+ font-size: 13px;+ line-height: 1.4;+}/* Card-header `⋯` popover (reload / open / save) + the My Appspanel's per-card `⋯` popover — both mirror `.agent-row-menu`'s look. */.chat-artifact-menu,diff --git a/test/main/features/chat_artifacts.test.ts b/test/main/features/chat_artifacts.test.tsindex cf4ea18d..2215869b 100644--- a/test/main/features/chat_artifacts.test.ts+++ b/test/main/features/chat_artifacts.test.ts@@ -84,6 +84,44 @@ describe('chat_artifacts › createArtifact', () => {expect([...buf.subarray(0, 4)]).toEqual([0x89, 0x50, 0x4e, 0x47]);});+ it('rejects compacted history markers in artifact text files', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, {+ files: [+ {+ path: 'index.html',+ content:+ '[old tool input string compacted: original_size=13653 chars]\n' ++ 'preview_head:\n<!doctype html><h1>stale preview</h1>',+ },+ ],+ });++ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toContain('compacted conversation-history marker');+ expect(fs.existsSync(cidDir())).toBe(false);+ });++ it('reports compacted history artifacts as unavailable without rewriting them', async () => {+ const m = await loadMod();+ const r = m.createArtifact(UID, CID, AGENT, { title: 'Ok app', files: MIN_FILES });+ expect(r.ok).toBe(true);+ if (!r.ok) return;++ expect(m.inspectArtifactIndex(UID, CID, r.artifactId)).toEqual({ ok: true, status: 'ok' });++ const indexPath = path.join(cidDir(), r.artifactId, 'index.html');+ fs.writeFileSync(indexPath, '__orkas_compacted_tool_use', 'utf8');+ const inspected = m.inspectArtifactIndex(UID, CID, r.artifactId);+ expect(inspected).toMatchObject({+ ok: true,+ status: 'unavailable',+ marker: '__orkas_compacted_tool_use',+ });+ expect(fs.readFileSync(indexPath, 'utf8')).toBe('__orkas_compacted_tool_use');+ });+it('rejects: no index.html', async () => {const m = await loadMod();const r = m.createArtifact(UID, CID, AGENT, { files: [{ path: 'main.html', content: 'x' }] });