Skip to content

armgit / Orkas

Public Imported from GitHub
0

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

Preserve local apps and guide web app users to the commercial version

wyt8d577de148a1
diff --git a/docs/reference/web-app-sdk.json b/docs/reference/web-app-sdk.json
new file mode 100644
index 00000000..53be631c
--- /dev/null
+++ b/docs/reference/web-app-sdk.json
@@ -0,0 +1,1658 @@
+{
+ "sdkVersion": 1,
+ "manifest": {
+ "file": "orkas-app.json",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "sdkVersion": {
+ "type": "number",
+ "const": 1
+ },
+ "minimumClient": {
+ "type": "string",
+ "const": "1.9.0"
+ },
+ "capabilities": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": [
+ "storage",
+ "appFiles",
+ "files",
+ "ai",
+ "library",
+ "connectors",
+ "data"
+ ]
+ },
+ "maxItems": 7
+ },
+ "data": {
+ "type": "object",
+ "properties": {
+ "version": {
+ "type": "number",
+ "const": 1
+ },
+ "tables": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "name": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "fields": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "name": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "json",
+ "timestamp"
+ ]
+ },
+ "required": {
+ "type": "boolean"
+ },
+ "nullable": {
+ "type": "boolean"
+ },
+ "unique": {
+ "type": "boolean"
+ },
+ "default": {},
+ "references": {
+ "type": "object",
+ "properties": {
+ "table": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ }
+ },
+ "required": [
+ "table"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "type"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 128
+ },
+ "access": {
+ "type": "object",
+ "properties": {
+ "read": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "default": []
+ },
+ "insert": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "default": []
+ },
+ "count": {
+ "type": "boolean"
+ },
+ "maxCount": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000
+ },
+ "aggregate": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ }
+ },
+ "readFilters": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "field": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "op": {
+ "type": "string",
+ "enum": [
+ "eq",
+ "ne",
+ "lt",
+ "lte",
+ "gt",
+ "gte"
+ ]
+ },
+ "value": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "number",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "field",
+ "op",
+ "value"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 16
+ }
+ },
+ "additionalProperties": false
+ },
+ "indexes": {
+ "type": "array",
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "minItems": 1,
+ "maxItems": 4
+ },
+ "maxItems": 16
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "fields",
+ "access"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 32
+ }
+ },
+ "required": [
+ "version",
+ "tables"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "sdkVersion",
+ "capabilities"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "capabilities": {
+ "contains": {
+ "const": "data"
+ }
+ }
+ },
+ "required": [
+ "capabilities"
+ ]
+ },
+ "then": {
+ "required": [
+ "data"
+ ]
+ }
+ }
+ ]
+ },
+ "starter": {
+ "entry": "@skill/web-app-sdk/assets/starter/index.html",
+ "manifest": "@skill/web-app-sdk/assets/starter/orkas-app.json"
+ }
+ },
+ "dataDefinition": {
+ "type": "object",
+ "properties": {
+ "version": {
+ "type": "number",
+ "const": 1
+ },
+ "tables": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "name": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "fields": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "name": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "json",
+ "timestamp"
+ ]
+ },
+ "required": {
+ "type": "boolean"
+ },
+ "nullable": {
+ "type": "boolean"
+ },
+ "unique": {
+ "type": "boolean"
+ },
+ "default": {},
+ "references": {
+ "type": "object",
+ "properties": {
+ "table": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ }
+ },
+ "required": [
+ "table"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "type"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 128
+ },
+ "access": {
+ "type": "object",
+ "properties": {
+ "read": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "default": []
+ },
+ "insert": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "default": []
+ },
+ "count": {
+ "type": "boolean"
+ },
+ "maxCount": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000
+ },
+ "aggregate": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ }
+ },
+ "readFilters": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "field": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "op": {
+ "type": "string",
+ "enum": [
+ "eq",
+ "ne",
+ "lt",
+ "lte",
+ "gt",
+ "gte"
+ ]
+ },
+ "value": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "number",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "field",
+ "op",
+ "value"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 16
+ }
+ },
+ "additionalProperties": false
+ },
+ "indexes": {
+ "type": "array",
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "minItems": 1,
+ "maxItems": 4
+ },
+ "maxItems": 16
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "fields",
+ "access"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 32
+ }
+ },
+ "required": [
+ "version",
+ "tables"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "methods": [
+ {
+ "name": "data.query",
+ "capability": "data",
+ "description": "Read declared fields under readFilters; default limit 20, maximum 100, offset maximum 100000. Ordering adds id as a stable tie-breaker; include reads at most four declared one-hop relations.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "table": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "fields": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "maxItems": 130
+ },
+ "include": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "maxItems": 4
+ },
+ "filters": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "field": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "op": {
+ "type": "string",
+ "enum": [
+ "eq",
+ "ne",
+ "lt",
+ "lte",
+ "gt",
+ "gte"
+ ]
+ },
+ "value": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "number",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "field",
+ "op",
+ "value"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 16
+ },
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100
+ },
+ "offset": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 100000
+ },
+ "order": {
+ "type": "object",
+ "properties": {
+ "field": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "direction": {
+ "type": "string",
+ "enum": [
+ "asc",
+ "desc"
+ ]
+ }
+ },
+ "required": [
+ "field",
+ "direction"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "table"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{records:object[]}; include adds relations keyed by reference field.",
+ "example": {
+ "table": "messages",
+ "fields": [
+ "body"
+ ],
+ "limit": 20
+ }
+ },
+ {
+ "name": "data.count",
+ "capability": "data",
+ "description": "Count records under declared readFilters and caller filters; requires count permission.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "table": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "filters": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "field": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "op": {
+ "type": "string",
+ "enum": [
+ "eq",
+ "ne",
+ "lt",
+ "lte",
+ "gt",
+ "gte"
+ ]
+ },
+ "value": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "number",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "field",
+ "op",
+ "value"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 16
+ }
+ },
+ "required": [
+ "table"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{count:number}",
+ "example": {
+ "table": "messages"
+ }
+ },
+ {
+ "name": "data.insert",
+ "capability": "data",
+ "description": "Insert declared fields, apply defaults and meter canonical UTF-8 bytes atomically. requestId deduplicates the latest 2048 insert requests across reopening.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "table": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "values": {
+ "type": "object",
+ "additionalProperties": {}
+ },
+ "requestId": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
+ }
+ },
+ "required": [
+ "table",
+ "values"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{id:string}; generated record ID, never the private row.",
+ "example": {
+ "table": "messages",
+ "values": {
+ "body": "Hello"
+ },
+ "requestId": "message-1"
+ }
+ },
+ {
+ "name": "data.insertIf",
+ "capability": "data",
+ "description": "Atomically check whole-table count and insert. maxCount can only tighten the application declaration; full capacity returns E_CONDITION.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "table": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "values": {
+ "type": "object",
+ "additionalProperties": {}
+ },
+ "requestId": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
+ },
+ "maxCount": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000
+ }
+ },
+ "required": [
+ "table",
+ "values",
+ "maxCount"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{id:string}; no partial insertion on failure.",
+ "example": {
+ "table": "messages",
+ "values": {
+ "body": "Hello"
+ },
+ "maxCount": 100,
+ "requestId": "message-2"
+ }
+ },
+ {
+ "name": "data.aggregate",
+ "capability": "data",
+ "description": "Compute a declared aggregate under readFilters and caller filters; groupBy requires read permission. Up to 100 groups; larger results fail with E_LIMIT.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "table": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "field": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "op": {
+ "type": "string",
+ "enum": [
+ "count",
+ "sum",
+ "min",
+ "max",
+ "avg"
+ ]
+ },
+ "groupBy": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "filters": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "field": {
+ "type": "string",
+ "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
+ },
+ "op": {
+ "type": "string",
+ "enum": [
+ "eq",
+ "ne",
+ "lt",
+ "lte",
+ "gt",
+ "gte"
+ ]
+ },
+ "value": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "number",
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "field",
+ "op",
+ "value"
+ ],
+ "additionalProperties": false
+ },
+ "maxItems": 16
+ }
+ },
+ "required": [
+ "table",
+ "field",
+ "op"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{value:number|string|null} or {groups:[{key,value}]} when groupBy is supplied.",
+ "example": {
+ "table": "messages",
+ "field": "score",
+ "op": "sum"
+ }
+ },
+ {
+ "name": "capabilities.list",
+ "capability": null,
+ "description": "Discover supported methods, current availability and authorization requirements.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{sdkVersion, methods, unsupported}",
+ "example": {}
+ },
+ {
+ "name": "capabilities.describe",
+ "capability": null,
+ "description": "Read one method schema, result contract and example.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "method": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "required": [
+ "method"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "Method documentation.",
+ "example": {
+ "method": "data.query"
+ }
+ },
+ {
+ "name": "host.getContext",
+ "capability": null,
+ "description": "Read the current application language and SDK version.",
+ "appTypes": [
+ "local",
+ "web"
+ ],
+ "environments": [
+ "desktop",
+ "preview",
+ "online"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{language, sdkVersion}",
+ "example": {}
+ },
+ {
+ "name": "permissions.revoke",
+ "capability": null,
+ "description": "Revoke this instance grants and cancel pending work. Reopening starts fresh.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{revoked:true}",
+ "example": {}
+ },
+ {
+ "name": "storage.get",
+ "capability": "storage",
+ "description": "Read app-private JSON; scope defaults to local for compatibility. cloud participates in account sync.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string",
+ "minLength": 1
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "local"
+ }
+ },
+ "required": [
+ "key"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{value}; null when missing.",
+ "example": {
+ "key": "draft"
+ }
+ },
+ {
+ "name": "storage.set",
+ "capability": "storage",
+ "description": "Atomically save an app-private JSON value; total store limit 200 MiB.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string",
+ "minLength": 1
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "local"
+ },
+ "value": {}
+ },
+ "required": [
+ "key",
+ "value"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{saved:true}",
+ "example": {
+ "key": "draft",
+ "value": "Hello"
+ }
+ },
+ {
+ "name": "storage.remove",
+ "capability": "storage",
+ "description": "Remove one app-private value.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string",
+ "minLength": 1
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "local"
+ }
+ },
+ "required": [
+ "key"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{removed:true}",
+ "example": {
+ "key": "draft"
+ }
+ },
+ {
+ "name": "storage.keys",
+ "capability": "storage",
+ "description": "List keys in the selected app store.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "local"
+ }
+ },
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{keys:string[]}",
+ "example": {}
+ },
+ {
+ "name": "appFiles.list",
+ "capability": "appFiles",
+ "description": "List sandbox files recursively. cloud (default) syncs with the account; local is for caches.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "cloud"
+ }
+ },
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{files:[{path,size}]}",
+ "example": {
+ "scope": "cloud"
+ }
+ },
+ {
+ "name": "appFiles.readText",
+ "capability": "appFiles",
+ "description": "Read a sandbox UTF-8 file up to 200 MiB; missing files return null.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "cloud"
+ }
+ },
+ "required": [
+ "path"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{text} or null.",
+ "example": {
+ "path": "notes/today.txt"
+ }
+ },
+ {
+ "name": "appFiles.readBase64",
+ "capability": "appFiles",
+ "description": "Read a sandbox binary file up to 200 MiB; missing files return null.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "cloud"
+ }
+ },
+ "required": [
+ "path"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{base64} or null.",
+ "example": {
+ "path": "images/icon.png"
+ }
+ },
+ {
+ "name": "appFiles.writeText",
+ "capability": "appFiles",
+ "description": "Atomically replace an app-owned UTF-8 file (200 MiB). Creates parent directories. Saved means local persistence, not completed upload.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "cloud"
+ },
+ "text": {
+ "type": "string",
+ "maxLength": 209715200
+ }
+ },
+ "required": [
+ "path",
+ "text"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{saved:true}",
+ "example": {
+ "path": "notes/today.txt",
+ "text": "Hello"
+ }
+ },
+ {
+ "name": "appFiles.writeBase64",
+ "capability": "appFiles",
+ "description": "Atomically replace an app-owned binary file (200 MiB). Requires canonical base64.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "cloud"
+ },
+ "base64": {
+ "type": "string",
+ "maxLength": 279620268
+ }
+ },
+ "required": [
+ "path",
+ "base64"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{saved:true}",
+ "example": {
+ "path": "images/icon.bin",
+ "base64": "AAE="
+ }
+ },
+ {
+ "name": "appFiles.remove",
+ "capability": "appFiles",
+ "description": "Remove one sandbox file; missing files are a successful no-op. Directories are not recursively deleted.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
+ },
+ "scope": {
+ "type": "string",
+ "enum": [
+ "local",
+ "cloud"
+ ],
+ "default": "cloud"
+ }
+ },
+ "required": [
+ "path"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{removed:true}",
+ "example": {
+ "path": "notes/today.txt"
+ }
+ },
+ {
+ "name": "files.pick",
+ "capability": "files",
+ "description": "Choose a local file using the host dialog; grants read access only.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{handle,name,size} or null on cancellation.",
+ "example": {}
+ },
+ {
+ "name": "files.readText",
+ "capability": "files",
+ "description": "Read a selected UTF-8 file, at most 200 MiB.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "handle": {
+ "type": "string",
+ "pattern": "^[a-f0-9]{32}$"
+ }
+ },
+ "required": [
+ "handle"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{text}",
+ "example": {
+ "handle": "0123456789abcdef0123456789abcdef"
+ }
+ },
+ {
+ "name": "files.readBase64",
+ "capability": "files",
+ "description": "Read a selected file as base64, at most 200 MiB.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "handle": {
+ "type": "string",
+ "pattern": "^[a-f0-9]{32}$"
+ }
+ },
+ "required": [
+ "handle"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{base64}",
+ "example": {
+ "handle": "0123456789abcdef0123456789abcdef"
+ }
+ },
+ {
+ "name": "files.saveAs",
+ "capability": "files",
+ "description": "Export UTF-8 text using the host Save dialog. Create-only: choose a new destination; existing files are not overwritten.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^[^/\\\\\\x00-\\x1f]+$"
+ },
+ "text": {
+ "type": "string",
+ "maxLength": 209715200
+ }
+ },
+ "required": [
+ "name",
+ "text"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{saved:true,name} or null on cancellation.",
+ "example": {
+ "name": "summary.txt",
+ "text": "Summary"
+ }
+ },
+ {
+ "name": "files.release",
+ "capability": "files",
+ "description": "Release a file handle before closing the app.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "handle": {
+ "type": "string",
+ "pattern": "^[a-f0-9]{32}$"
+ }
+ },
+ "required": [
+ "handle"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{released:true}",
+ "example": {
+ "handle": "0123456789abcdef0123456789abcdef"
+ }
+ },
+ {
+ "name": "ai.generate",
+ "capability": "ai",
+ "description": "Generate text with the configured model without tools, skills or conversation history. Optional progress receives text deltas. Uses the configured model without an extra application permission dialog.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "prompt": {
+ "type": "string",
+ "minLength": 1
+ },
+ "maxTokens": {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "minimum": -9007199254740991,
+ "maximum": 9007199254740991
+ }
+ },
+ "required": [
+ "prompt"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{text,usage,stopReason}; token-limited output has stopReason=max_tokens. Cancel with AbortSignal.",
+ "example": {
+ "prompt": "Write a short greeting.",
+ "maxTokens": 128
+ }
+ },
+ {
+ "name": "tools.list",
+ "capability": null,
+ "description": "Discover eligible existing Orkas tools and their original schemas. Connector discovery supports BM25 query, bounded pages and full schemas for small catalogs through list_connector_tools. Does not grant execution.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{tools:[{name,capability,description,inputSchema}]}",
+ "example": {}
+ },
+ {
+ "name": "tools.call",
+ "capability": null,
+ "description": "Execute an eligible existing tool under its original operation permissions. Sensitive actions use host approval; Trusted mode skips confirmation. Unknown tools fail closed.",
+ "appTypes": [
+ "local"
+ ],
+ "environments": [
+ "desktop",
+ "preview"
+ ],
+ "status": "supported",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1
+ },
+ "arguments": {
+ "type": "object",
+ "additionalProperties": {}
+ }
+ },
+ "required": [
+ "name",
+ "arguments"
+ ],
+ "additionalProperties": false,
+ "$schema": "http://json-schema.org/draft-07/schema#"
+ },
+ "result": "{content,isError?}; inspect isError. Oversized results fail without replay.",
+ "example": {
+ "name": "library",
+ "arguments": {
+ "action": "list",
+ "scope": "global",
+ "limit": 10
+ }
+ }
+ }
+ ],
+ "unsupported": [
+ {
+ "capability": "account.renewalReminders",
+ "reason": "Host-only: account-wide reminder claims and billing navigation belong to the signed-in desktop account UI, not saved applications."
+ },
+ {
+ "capability": "browser",
+ "reason": "Host-only: task browser control, native file selection and site consent require a live conversation and its user-owned Chromium profile."
+ },
+ {
+ "capability": "files.writeInPlace",
+ "reason": "Deferred: needs shared revision/lock/indexer integration; export through files.saveAs."
+ },
+ {
+ "capability": "projects",
+ "reason": "Deferred: apps have no user-selected project binding; source conversation is not authority."
+ },
+ {
+ "capability": "memory",
+ "reason": "Deferred: needs a user-selected scope; Agent-private and global memories are not app state."
+ },
+ {
+ "capability": "history",
+ "reason": "Deferred: needs an explicit conversation grant and bounded history projection."
+ },
+ {
+ "capability": "agents.tasks",
+ "reason": "Deferred: needs a host-owned task lifetime, permissions and billing association."
+ },
+ {
+ "capability": "skills",
+ "reason": "Host-only: Skill script execution needs an explicitly scoped application sandbox and execution contract."
+ },
+ {
+ "capability": "shell",
+ "reason": "Host-only: arbitrary execution would escape the application capability boundary."
+ },
+ {
+ "capability": "media.generate",
+ "reason": "Deferred: owning studio plan, output and spending gates must be adapted first."
+ }
+ ]
+}
diff --git a/docs/test/my-apps-regression.md b/docs/test/my-apps-regression.md
new file mode 100644
index 00000000..d08968a6
--- /dev/null
+++ b/docs/test/my-apps-regression.md
@@ -0,0 +1,97 @@
+# Application regression
+
+Use temporary local user data and synthetic inputs. Confirm visible outcomes,
+retained file/database bytes and absence of refused side effects. A successful
+fixture does not establish model output quality or live third-party availability.
+
+## Automated entry points
+
+- `npm run test:js -- test/main/features/saved_apps.test.ts test/main/features/chat_artifacts.test.ts test/main/features/saved-app-type-recovery.test.ts test/main/features/web-app-commercial-entry.test.ts test/main/features/web_apps.test.ts test/renderer/saved-apps-journeys.test.ts test/renderer/commercial-entry.test.ts` covers feature, SDK and interaction contracts.
+- Run `npm run test:e2e:typecheck` before `npm run test:e2e -- test/e2e/saved_apps_e2e_lifecycle.spec.ts`.
+- Run `npm run test:apps:e2e` for the selected local application journeys.
+- Review the actual logs, warnings, fallback and cleanup failures. Intentional
+ damaged-metadata, interrupted-write and denied-capability cases are negative
+ controls; an unrelated warning remains a failure to investigate.
+
+## Commercial web application entry
+
+1. Activate the Web apps tab or the Web app creation option. The commercial
+ guidance appears before any conversation, model request, artifact, preview
+ or runtime instance is created. Cancel/Escape preserve the current local
+ view, draft and focus. Verify Chinese and English at normal and narrow sizes.
+2. Only an explicit Download action opens the official localized download URL.
+ An opener failure remains recoverable; cancel, page load and repeated model
+ failures never open the browser automatically.
+3. Direct IPC and tool requests for `web` or legacy `cloud` return the specific
+ `E_COMMERCIAL_REQUIRED` / `web_apps` receipt. Tool results are errors and keep
+ the receipt intact. A localized, nonblocking chat notice provides the download
+ action, once per turn, without relying on the model's wording.
+4. Retained web metadata, structured task bindings and edit snapshots remain
+ authoritative when a caller omits type or claims local. Save, update, edit,
+ preview, SDK and direct resource requests cannot execute that web source.
+ Compare all original files, metadata, databases and journals before/after,
+ including restart and background cleanup. They must remain unchanged.
+5. Corrupt/unreadable binding metadata cannot become local permission. Genuine
+ legacy local fallback remains available. Ordinary HTML, website authoring
+ and external resources in an authorized local application remain usable.
+
+## Local creation, list and save
+
+- Create from an idea or template once, preserving literal user text. A second
+ click does not duplicate the task. Sending failure keeps the recoverable draft.
+ Cancel/backdrop/Escape retain a session draft; a reset clears it.
+- The list uses local metadata, preserves cards after a failed/malformed refresh,
+ rejects a late stale listing after deletion, and confirms a genuine empty list.
+ Counts, type controls, menus and long titles remain stable at narrow widths.
+- Save an artifact and a complete file bundle, including a non-index entry,
+ CSS/module/JSON/font/audio assets, binary content and ordinary long paths.
+ Reject traversal, hidden/managed paths, symlinks, invalid encoding and oversized
+ input before changing the destination. A workspace-root entry requires its own
+ folder. Show one confirmation after an actual successful save.
+- Omitted or null type in an ordinary task retains local compatibility; conflicting
+ types in a bound edit fail before writes. Saving a valid independent local copy
+ must not overwrite its original or silently change identity.
+
+## Open, edit and recovery
+
+- Open a local card with mouse, Enter and Space. One action opens one preview;
+ rename preserves identity and icon. Refresh/restart retain the saved result.
+- Editing creates a source-attached task with the exact original identity and
+ fingerprint. Conflicting source changes require an explicit recovery choice;
+ repeated or interrupted commits do not lose the original or duplicate data.
+- Exercise each save-journal crash point and cleanup failure. Recovery retains a
+ usable source and only commits a complete replacement. Missing/damaged edit
+ context produces a recoverable failure rather than an invented local binding.
+- File/Artifacts views and chat cards navigate to the correct artifact and user.
+ Source attachments, generated files and current composer state remain isolated.
+
+## Shared local SDK and SQLite
+
+- Discover actual schemas, enforce manifest declarations and reject undeclared
+ capabilities before native, model or connector execution. Ordinary local calls
+ remain available without introducing additional paid routing or approvals.
+- Preserve record values, not just counts, through reopen. Preview records are
+ temporary and never overwrite formal data. App copies and local users remain
+ isolated. Concurrent startup, timeout and worker closure permit later recovery.
+- Run the independent common-data fixtures: field/type/size constraints, read
+ filters, stable pages, aggregation, relations, capacity and idempotent insert.
+ Reusing an operation ID with different data fails without corrupting records.
+- Cancellation, frame removal, account change, stream-consumer departure and
+ revocation terminate the owned request. Late results cannot write or publish
+ into a replacement frame; an explicit new request can succeed. Completed
+ external effects are not undone or replayed automatically.
+- Exercise partial reads, binary exports, create-only writes, storage aliases,
+ denied path access, deep paths, long keys and exhaustion/reopen boundaries.
+
+## Rename, delete, localization and privacy
+
+- Rename changes only the display name; original/source identity survives.
+ Delete confirmation names the app and irreversible local records/private files.
+ Cancel has initial focus and preserves data; success removes the card only
+ after backend confirmation. Failure keeps the card and permits retry.
+- Check card dates, exact edit draft, app-type tags and failure copy in every
+ registered language. No untranslated key, private path or backend text appears
+ in alerts. Long names and RTL layouts retain accessible buttons and local scroll.
+- Hosted publication, online data management and personal synchronization are
+ unavailable. Their execution/recovery journeys are outside this build; the
+ retained entry only explains how to obtain the commercial version.
diff --git a/playwright.apps.config.ts b/playwright.apps.config.ts
new file mode 100644
index 00000000..270badc9
--- /dev/null
+++ b/playwright.apps.config.ts
@@ -0,0 +1,14 @@
+import { defineConfig } from '@playwright/test';
+import base from './playwright.config';
+
+// Owning application journeys: detailed UI, runtime, recovery and authoring
+// oracle coverage stays here even when it is outside the release selection.
+export default defineConfig(base, {
+ testMatch: [
+ '**/saved_apps_e2e_lifecycle.spec.ts',
+ '**/web_app_sdk_e2e_lifecycle.spec.ts',
+ '**/web_app_sdk_e2e_runtime.spec.ts',
+ '**/web_app_permissions_e2e_usage.spec.ts',
+ '**/html_preview_e2e_generated_controls.spec.ts',
+ ],
+});
diff --git a/scripts/web-app-sdk-docs.ts b/scripts/web-app-sdk-docs.ts
index 3e8ccb09..dec97a68 100644
--- a/scripts/web-app-sdk-docs.ts
+++ b/scripts/web-app-sdk-docs.ts
@@ -4,11 +4,13 @@ import * as path from 'node:path';
import { catalogDocument } from '../src/main/features/web_apps/catalog';
const targets = [
+ 'docs/reference/web-app-sdk.json',
'resources/builtin/system/skills/web-app-sdk/references/api.json',
];
export function syncWebAppSdkDocs(root: string, check: boolean): void {
- const expected = JSON.stringify(catalogDocument(), null, 2) + '\n';
- for (const relative of targets) {
+ const web=JSON.stringify(catalogDocument('web'),null,2)+'\n';
+ const copies=[...targets.map(relative=>({relative,content:JSON.stringify(catalogDocument(),null,2)+'\n'})),{relative:'resources/builtin/system/skills/web-app-sdk/references/web-api.json',content:web}];
+ for (const {relative,content:expected} of copies) {
const target = path.resolve(root, relative);
if (check) {
if (!fs.existsSync(target) || fs.readFileSync(target, 'utf8') !== expected) {
diff --git a/src/main/features/chat_artifacts.ts b/src/main/features/chat_artifacts.ts
index c7ddb544..c2aa93b5 100644
--- a/src/main/features/chat_artifacts.ts
+++ b/src/main/features/chat_artifacts.ts
@@ -42,6 +42,9 @@ import {
chatArtifactCidDirForConversation,
chatArtifactRelPath,
} from '../util/project-layout';
+import { appTypeSchema, metadataAppType, type AppType } from './web_apps/data-contract';
+import { manifestSchema } from './web_apps/catalog';
+import type { ZodIssue } from 'zod';
import { createLogger } from '../logger';
import { logErrorSummary, maskId } from '../util/log-redact';
import { isPathAllowed } from '../util/path-sandbox';
@@ -100,7 +103,7 @@ export const ARTIFACT_FRAME = Object.freeze({
// ── Types ────────────────────────────────────────────────────────────────
-export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string };
+export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string; code?: string; feature?: string; message?: string };
export interface ArtifactFileInput {
path: string;
@@ -109,6 +112,8 @@ export interface ArtifactFileInput {
}
export interface ArtifactMeta {
+ browserStorage?: 'isolated-v1';
+ appType?: AppType;
title: string;
agentId: string;
createdAt: string; // ISO
@@ -118,7 +123,7 @@ 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: 'ok'; appType: AppType }
| { ok: true; status: 'unavailable'; reason: string }
| { ok: false; error: string };
@@ -293,6 +298,74 @@ export function ensureBridgeScript(html: string): string {
return `${html}\n${tag}`;
}
+// ── Declaration rejection detail ─────────────────────────────────────────
+
+// The author corrects and resubmits from this text, so it names the failing
+// member and the schema-side expectation. It never echoes rejected values;
+// unsupported keys appear only when they are identifier-shaped. Bounded so a
+// pathological manifest cannot flood the tool result or the reject log.
+const DECLARATION_ERROR_PREFIX = 'invalid application interface declaration in orkas-app.json: ';
+const DECLARATION_ISSUE_LIMIT = 3;
+const DECLARATION_ERROR_MAX = 600;
+const IDENTIFIER_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,39}$/;
+
+function declarationError(detail: string): string {
+ const text = DECLARATION_ERROR_PREFIX + detail;
+ return text.length <= DECLARATION_ERROR_MAX ? text : text.slice(0, DECLARATION_ERROR_MAX - 3) + '...';
+}
+
+function declarationPath(issuePath: ReadonlyArray<string | number>): string {
+ let out = '';
+ for (const part of issuePath) {
+ if (typeof part === 'number') out += `[${part}]`;
+ else out += (out ? '.' : '') + (IDENTIFIER_KEY.test(part) ? part : '<key>');
+ }
+ return out || 'root';
+}
+
+/** The schema-side reason for one issue, without its location. */
+function declarationReason(issue: ZodIssue): string {
+ switch (issue.code) {
+ case 'invalid_type':
+ return issue.received === 'undefined' ? 'is required' : `must be ${issue.expected}, received ${issue.received}`;
+ case 'invalid_literal':
+ return issue.received === undefined ? 'is required' : `must be ${JSON.stringify(issue.expected)}`;
+ case 'invalid_enum_value':
+ return `must be one of ${issue.options.join(', ')}`;
+ case 'unrecognized_keys': {
+ const named = issue.keys.filter(key => IDENTIFIER_KEY.test(key));
+ const unnamed = issue.keys.length - named.length;
+ const list = [...named.slice(0, 5), ...(named.length > 5 ? [`+${named.length - 5} more`] : []),
+ ...(unnamed ? [`${unnamed} other key(s)`] : [])];
+ return `has unsupported field(s) ${list.join(', ')}`;
+ }
+ case 'invalid_string':
+ return 'has an invalid format';
+ default:
+ // Remaining zod messages and data-contract refinements are schema-authored.
+ return `: ${issue.message}`;
+ }
+}
+
+/** Group identical reasons; unsupported fields first because an invented
+ * member (e.g. `interfaces`) usually explains the missing required ones. */
+function describeDeclarationIssues(issues: readonly ZodIssue[]): string {
+ const groups = new Map<string, string[]>();
+ const ordered = [...issues].sort((a, b) => Number(b.code === 'unrecognized_keys') - Number(a.code === 'unrecognized_keys'));
+ for (const issue of ordered) {
+ const reason = declarationReason(issue);
+ const paths = groups.get(reason) ?? [];
+ paths.push(declarationPath(issue.path));
+ groups.set(reason, paths);
+ }
+ const rendered = [...groups].map(([reason, paths]) => {
+ const where = paths.slice(0, DECLARATION_ISSUE_LIMIT).join(', ') + (paths.length > DECLARATION_ISSUE_LIMIT ? ` (+${paths.length - DECLARATION_ISSUE_LIMIT} more)` : '');
+ return reason.startsWith(':') ? where + reason : `${where} ${reason}`;
+ });
+ const shown = rendered.slice(0, DECLARATION_ISSUE_LIMIT).join('; ');
+ return rendered.length > DECLARATION_ISSUE_LIMIT ? `${shown} (+${rendered.length - DECLARATION_ISSUE_LIMIT} more)` : shown;
+}
+
// ── Public API ───────────────────────────────────────────────────────────
/**
@@ -305,12 +378,24 @@ export async function createArtifact(
userId: string,
cid: string,
agentId: string,
- input: { title?: unknown; files?: unknown },
+ input: { title?: unknown; files?: unknown; appType?: unknown },
): Promise<Result<{ artifactId: string; title: string }>> {
let safeConvId: string;
try { safeConvId = safeCid(cid); }
catch (err) { return { ok: false, error: (err as Error).message }; }
+ let boundType:AppType|undefined;
+ try{boundType=await (await import('./saved_apps')).boundAppType(userId,cid);}
+ catch(err){
+ log.warn('createArtifact app binding unavailable',{user_id:maskId(userId),conversation_id:maskId(safeConvId),error:logErrorSummary(err)});
+ return {ok:false,error:'app editing source unavailable; reopen editing from the app or save as a new app'};
+ }
+ const selectedType=appTypeSchema.safeParse((input.appType === 'cloud' ? 'web' : input.appType) ?? boundType ?? 'local');
+ if (boundType === 'web' || input?.appType === 'web' || input?.appType === 'cloud') {
+ return (await import('./web_apps/commercial-entry')).commercialWebAppFailure();
+ }
+ if(!selectedType.success || (boundType && selectedType.data!==boundType))return {ok:false,error:'app type must match the task or editing source'};
+ const appType=selectedType.data;
const title = (typeof input?.title === 'string' && input.title.trim())
? input.title.trim().slice(0, 120)
: 'Interactive app';
@@ -352,9 +437,31 @@ export async function createArtifact(
prepared.push({ rel, content: f.content, encoding });
if (prepared.length % 256 === 0) await yieldToHost();
}
+ const declared=prepared.find(f=>f.rel==='orkas-app.json');
+ let declaredText='';
+ if(declared){
+ const bytes=Buffer.from(declared.content,declared.encoding);declaredText=bytes.toString('utf8');
+ if(!Buffer.from(declaredText,'utf8').equals(bytes))return {ok:false,error:declarationError('content must be UTF-8 text')};
+ let parsedJson:unknown;
+ try{parsedJson=JSON.parse(declaredText);}catch{return {ok:false,error:declarationError('content must be valid JSON')};}
+ const parsed=manifestSchema.safeParse(parsedJson);
+ if(!parsed.success)return {ok:false,error:declarationError(describeDeclarationIssues(parsed.error.issues))};
+ const manifest=parsed.data;
+ const hostOnly=manifest.capabilities.filter(c=>c!=='data');
+ if(appType==='web'&&hostOnly.length)return {ok:false,error:`web applications cannot use host interfaces: declared local-only capabilities ${hostOnly.join(', ')}; web apps may declare only data`};
+ if(manifest.capabilities.includes('data')&&!manifest.data)return {ok:false,error:'data definition is required'};
+ }
+ // Older strict manifest readers reject this additive protocol marker before
+ // running a web bundle; they cannot silently treat it as a host app.
+ if(appType==='web'){
+ if(declared){declared.content=JSON.stringify({...JSON.parse(declaredText),minimumClient:'1.9.0'});declared.encoding='utf8';}
+ else prepared.push({rel:'orkas-app.json',encoding:'utf8',content:JSON.stringify({sdkVersion:1,minimumClient:'1.9.0',capabilities:[]})});
+ }
if (!hasIndex) return { ok: false, error: 'files must include a top-level "index.html"' };
const meta: ArtifactMeta = {
+ browserStorage: 'isolated-v1',
+ appType,
title,
agentId: typeof agentId === 'string' ? agentId : '',
createdAt: new Date().toISOString(),
@@ -378,7 +485,7 @@ export async function createArtifact(
let buf = Buffer.from(content, encoding);
if (encoding === 'utf8') {
if (buf.toString('utf8') !== content) throw new Error(`file "${rel}": content is not valid UTF-8`);
- if (rel === 'index.html') buf = Buffer.from(ensureBridgeScript(content), 'utf8');
+ if (rel === 'index.html' && appType === 'local') buf = Buffer.from(ensureBridgeScript(content), 'utf8');
}
const dst = path.join(tmpDir, rel);
await fsp.mkdir(path.dirname(dst), { recursive: true });
@@ -399,17 +506,22 @@ export async function createArtifact(
return { ok: true, artifactId, title };
}
-export function inspectArtifactIndex(userId: string, cid: string, artifactId: string): ArtifactInspection {
+export async function inspectArtifactIndex(userId: string, cid: string, artifactId: string): Promise<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 {
fs.accessSync((resolved as { absPath: string }).absPath, fs.constants.R_OK);
- return { ok: true, status: 'ok' };
} catch (err) {
return { ok: false, error: (err as Error).message || 'failed to inspect artifact index' };
}
+ // An unresolvable editing binding leaves the bubble unlabelled, never local.
+ try { return { ok: true, status: 'ok', appType: await (await import('./saved_apps')).resolveArtifactAppType(userId, cid, artifactId) }; }
+ catch (err) {
+ log.warn('inspectArtifactIndex app binding unavailable', { error: logErrorSummary(err) });
+ return { ok: false, error: 'app editing source unavailable' };
+ }
}
/** Resolve (uid, cid, artifactId) → the validated, existing artifact directory.
@@ -497,6 +609,8 @@ export function readArtifactMeta(userId: string, cid: string, artifactId: string
const obj = JSON.parse(raw) as Partial<ArtifactMeta>;
if (obj && typeof obj === 'object') {
return {
+ appType: metadataAppType(obj.appType),
+ ...(obj.browserStorage === 'isolated-v1' ? { browserStorage: obj.browserStorage } : {}),
title: typeof obj.title === 'string' ? obj.title : 'Interactive app',
agentId: typeof obj.agentId === 'string' ? obj.agentId : '',
createdAt: typeof obj.createdAt === 'string' ? obj.createdAt : '',
diff --git a/src/main/features/html_preview.ts b/src/main/features/html_preview.ts
index 8d290632..74e126e9 100644
--- a/src/main/features/html_preview.ts
+++ b/src/main/features/html_preview.ts
@@ -20,6 +20,13 @@ const HTML_PREVIEW_MAX_BLOCKED_RESOURCE_SAMPLES = 8;
const HTML_PREVIEW_MAX_DIAGNOSTICS = 12;
const HTML_PREVIEW_MAX_INTERACTION_SAMPLES = 10;
const HTML_PREVIEW_MAX_DIAGNOSTIC_CHARS = 400;
+const HTML_PREVIEW_DESIGN_MAX_ELEMENTS = 4_000;
+const HTML_PREVIEW_DESIGN_MAX_TEXT_BOXES = 600;
+const HTML_PREVIEW_DESIGN_MAX_RULES = 20_000;
+/** A product type scale has about this many roles (display, page title,
+ * section title, body, small body, caption, mono); more sizes on one screen
+ * is drift from one-off values, not hierarchy. */
+const HTML_PREVIEW_FONT_SIZE_LIMIT = 8;
export type HtmlPreviewViewportName = 'desktop' | 'mobile' | 'embed';
@@ -35,6 +42,46 @@ export interface HtmlPreviewLayoutIssue {
pixels: number;
}
+export interface HtmlPreviewTextOverlap {
+ selector: string;
+ /** The unrelated text element or control the text collides with. */
+ other: string;
+ width: number;
+ height: number;
+}
+
+export interface HtmlPreviewLowContrastText {
+ selector: string;
+ ratio: number;
+ /** WCAG AA: 4.5 for body text, 3 for large text. */
+ required: number;
+ color: string;
+ background: string;
+ fontSize: number;
+}
+
+/** Measurable design consistency of the rendered page. These numbers find
+ * drift and collisions; they do not judge taste, so they are warnings. */
+export interface HtmlPreviewDesignEvidence {
+ /** Distinct computed font sizes (px) of visible text, largest first. */
+ fontSizes: number[];
+ /** Distinct colors declared in color custom properties. */
+ colorTokenCount: number;
+ /** Used colors the author wrote as literals instead of tokens. Alpha is
+ * ignored, so a translucent variant of a token still counts as the token;
+ * browser-default colors of unstyled controls are not counted. */
+ nonTokenColorCount: number;
+ nonTokenColors: string[];
+ /** Text that collides with unrelated text or a control, after clipping. */
+ textOverlaps: HtmlPreviewTextOverlap[];
+ lowContrastCount: number;
+ lowContrastText: HtmlPreviewLowContrastText[];
+ /** Existing measurement limits reached; collected observations remain valid. */
+ incomplete?: string[];
+ /** Present when the measurement itself failed; the lists are then empty. */
+ error?: string;
+}
+
export interface HtmlPreviewViewportEvidence {
name: HtmlPreviewViewportName;
width: number;
@@ -56,6 +103,7 @@ export interface HtmlPreviewViewportEvidence {
failedImageCount: number;
layoutIssues: HtmlPreviewLayoutIssue[];
ineffectiveTransforms?: string[];
+ design?: HtmlPreviewDesignEvidence;
consoleErrors: string[];
}
@@ -139,6 +187,10 @@ export interface HtmlPreviewRenderOptions {
* `chat-media://local` with the viewer's sandbox (no storage, CORS-gated
* assets). Generated artifacts render in `chat-app://` and keep the default. */
fileViewer?: boolean;
+ /** Measure type sizes, token colors, text overlap, and contrast, and report
+ * findings as warnings. Defaults to true; the chat-artifact smoke judges
+ * operability only and turns it off. */
+ designAudit?: boolean;
}
type PageEvidence = Omit<
@@ -212,7 +264,407 @@ const INEFFECTIVE_TRANSFORMS_SCRIPT = `
};
`;
-const EVIDENCE_SCRIPT = `(() => {
+// Design audit, spliced into the evidence script after `visible` and
+// `selector`. It reads computed styles only. Colors are normalized through a
+// canvas so hex, rgb(), and named values compare equal; text boxes are Range
+// rects clipped by overflow ancestors, so a scrolled-away list item does not
+// "overlap" what sits below its scroller. Any failure is returned in
+// `design.error` rather than failing the preview.
+const DESIGN_EVIDENCE_SCRIPT = `
+ const designEvidence = () => {
+ const maxSamples = ${HTML_PREVIEW_MAX_DIAGNOSTICS};
+ const maxBoxes = ${HTML_PREVIEW_DESIGN_MAX_TEXT_BOXES};
+ const incomplete = new Set();
+ const colorCanvas = document.createElement('canvas');
+ colorCanvas.width = colorCanvas.height = 1;
+ const paint = colorCanvas.getContext('2d', { willReadFrequently: true });
+ const parsedColors = new Map();
+ const normalizeColor = (raw) => {
+ if (!raw || !paint || /^(none|currentcolor|inherit|initial|unset)$/i.test(raw)) return null;
+ paint.fillStyle = '#000001';
+ paint.fillStyle = raw;
+ const first = String(paint.fillStyle);
+ paint.fillStyle = '#000002';
+ paint.fillStyle = raw;
+ if (String(paint.fillStyle) !== first) return null;
+ if (first.charAt(0) === '#') {
+ const bits = parseInt(first.slice(1, 7), 16);
+ return [(bits >> 16) & 255, (bits >> 8) & 255, bits & 255, 1];
+ }
+ const match = first.match(/^rgba?\\(([^)]+)\\)$/);
+ if (!match) {
+ // CSS Color 4 values retain their syntax in fillStyle. Read the actual
+ // sRGB paint instead of treating a valid rendered color as unavailable.
+ paint.clearRect(0, 0, 1, 1);
+ paint.fillRect(0, 0, 1, 1);
+ const pixels = paint.getImageData(0, 0, 1, 1).data;
+ return [pixels[0], pixels[1], pixels[2], pixels[3] / 255];
+ }
+ const parts = match[1].split(',').map((part) => parseFloat(part));
+ if (parts.length < 3 || parts.some((part) => !Number.isFinite(part))) return null;
+ return [parts[0], parts[1], parts[2], parts.length > 3 ? parts[3] : 1];
+ };
+ const parseColor = (value) => {
+ const raw = String(value || '').trim();
+ if (!parsedColors.has(raw)) parsedColors.set(raw, normalizeColor(raw));
+ return parsedColors.get(raw);
+ };
+ const hex = (color) => '#' + color.slice(0, 3)
+ .map((channel) => Math.max(0, Math.min(255, Math.round(channel))).toString(16).padStart(2, '0'))
+ .join('');
+
+ // Tokens are color custom properties; "hard-coded" colors are color
+ // literals the author wrote anywhere else. A used color that is neither
+ // came from the browser's default styles, which is a different problem.
+ const tokenNames = new Set();
+ const tokenColors = [];
+ const literalColors = [];
+ const colorProperty = /color|^background|^border|^outline|^fill$|^stroke$|shadow|^column-rule|^text-decoration/;
+ const literalPattern = /#[0-9a-f]{3,8}\\b|\\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\\([^()]*\\)|\\b[a-z]{3,20}\\b/gi;
+ const collect = (value, into) => {
+ for (const literal of String(value || '').match(literalPattern) || []) {
+ const color = parseColor(literal);
+ if (color && color[3] > 0) into.push(color);
+ }
+ };
+ const scanDeclarations = (style) => {
+ for (let index = 0; index < style.length; index += 1) {
+ const name = String(style[index]);
+ if (name.startsWith('--')) collect(style.getPropertyValue(name), tokenColors);
+ else if (colorProperty.test(name)) collect(style.getPropertyValue(name), literalColors);
+ }
+ };
+ // Bounded so a full utility-class framework cannot stall the preview.
+ let rulesLeft = ${HTML_PREVIEW_DESIGN_MAX_RULES};
+ const scanRules = (rules) => {
+ for (let index = 0; index < (rules?.length || 0); index += 1) {
+ if (rulesLeft-- <= 0) { incomplete.add('stylesheet_rule_limit'); return; }
+ const rule = rules[index];
+ if (rule.style) {
+ scanDeclarations(rule.style);
+ if (/^\\s*(:root|html|body)\\b/i.test(String(rule.selectorText || ''))) {
+ for (let index = 0; index < rule.style.length; index += 1) {
+ if (String(rule.style[index]).startsWith('--')) tokenNames.add(rule.style[index]);
+ }
+ }
+ }
+ if (rule.cssRules) scanRules(rule.cssRules);
+ }
+ };
+ for (const sheet of Array.from(document.styleSheets || [])) {
+ let rules = [];
+ try { rules = sheet.cssRules || []; } catch (error) { continue; }
+ scanRules(rules);
+ }
+ for (const host of [document.documentElement, document.body]) {
+ if (!host) continue;
+ const style = getComputedStyle(host);
+ for (let index = 0; index < style.length; index += 1) {
+ if (String(style[index]).startsWith('--')) tokenNames.add(style[index]);
+ }
+ }
+ const rootStyle = getComputedStyle(document.documentElement);
+ const bodyStyle = document.body ? getComputedStyle(document.body) : rootStyle;
+ for (const name of tokenNames) {
+ collect(rootStyle.getPropertyValue(name) || bodyStyle.getPropertyValue(name), tokenColors);
+ }
+ const near = (list, color) => list.some((item) => Math.abs(item[0] - color[0]) <= 2
+ && Math.abs(item[1] - color[1]) <= 2 && Math.abs(item[2] - color[2]) <= 2);
+ const tokenCount = new Set(tokenColors.map((color) => hex(color))).size;
+
+ const used = new Map();
+ const record = (value, element) => {
+ const color = parseColor(value);
+ if (!color || color[3] <= 0) return;
+ const key = hex(color);
+ const entry = used.get(key);
+ if (entry) entry.count += 1;
+ else used.set(key, { color, count: 1, where: selector(element) });
+ };
+
+ const white = [255, 255, 255, 1];
+ const blend = (top, bottom) => [0, 1, 2]
+ .map((index) => top[index] * top[3] + bottom[index] * (1 - top[3]))
+ .concat(1);
+ const backgrounds = new Map();
+ // Composited background behind an element's text, or null when an image
+ // or gradient makes it unknowable from computed colors.
+ const backgroundOf = (element) => {
+ if (!element) return white;
+ if (backgrounds.has(element)) return backgrounds.get(element);
+ const style = getComputedStyle(element);
+ let result = null;
+ if (!style.backgroundImage || style.backgroundImage === 'none') {
+ const own = parseColor(style.backgroundColor);
+ if (own && own[3] >= 1) result = own;
+ else {
+ const below = backgroundOf(element.parentElement);
+ result = below && own && own[3] > 0 ? blend(own, below) : below;
+ }
+ }
+ backgrounds.set(element, result);
+ return result;
+ };
+ const channel = (value) => {
+ const unit = value / 255;
+ return unit <= 0.03928 ? unit / 12.92 : Math.pow((unit + 0.055) / 1.055, 2.4);
+ };
+ const luminance = (color) => 0.2126 * channel(color[0]) + 0.7152 * channel(color[1])
+ + 0.0722 * channel(color[2]);
+ const contrast = (left, right) => {
+ const a = luminance(left);
+ const b = luminance(right);
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
+ };
+
+ const clips = new Map();
+ const clipOf = (element) => {
+ if (clips.has(element)) return clips.get(element);
+ const style = getComputedStyle(element);
+ let clip = null;
+ if (!(element instanceof SVGElement) && !/^(inline|contents)$/.test(style.display)
+ && (style.overflowX !== 'visible' || style.overflowY !== 'visible')) {
+ const rect = element.getBoundingClientRect();
+ const left = rect.left + element.clientLeft;
+ const top = rect.top + element.clientTop;
+ clip = { left, top, right: left + element.clientWidth, bottom: top + element.clientHeight };
+ }
+ clips.set(element, clip);
+ return clip;
+ };
+ const clipped = (rect, from) => {
+ let box = { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom };
+ for (let node = from; node && node !== document.body && node !== document.documentElement;
+ node = node.parentElement) {
+ const clip = clipOf(node);
+ if (!clip) continue;
+ box = {
+ left: Math.max(box.left, clip.left),
+ top: Math.max(box.top, clip.top),
+ right: Math.min(box.right, clip.right),
+ bottom: Math.min(box.bottom, clip.bottom),
+ };
+ if (box.right - box.left < 1 || box.bottom - box.top < 1) return null;
+ }
+ return box;
+ };
+
+ const ownText = (element) => Array.from(element.childNodes)
+ .some((node) => node.nodeType === 3 && /\\S/.test(node.nodeValue || ''));
+ const textRects = (element) => {
+ const rects = [];
+ for (const node of Array.from(element.childNodes)) {
+ if (node.nodeType !== 3 || !/\\S/.test(node.nodeValue || '')) continue;
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ const list = range.getClientRects();
+ for (let index = 0; index < list.length; index += 1) {
+ const rect = list[index];
+ if (rect.width >= 1 && rect.height >= 1) {
+ if (rects.length >= 24) { incomplete.add('text_rectangle_limit'); return rects; }
+ rects.push(rect);
+ }
+ }
+ }
+ return rects;
+ };
+ const shown = (element) => (typeof element.checkVisibility === 'function'
+ ? element.checkVisibility({ opacityProperty: true, visibilityProperty: true })
+ : visible(element));
+ const sides = ['Top', 'Right', 'Bottom', 'Left'];
+ const controlSelector = 'button, input:not([type="hidden"]), select, textarea, a[href], [role="button"], [role="link"]';
+ const fieldSelector = 'input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"])'
+ + ':not([type="range"]):not([type="color"]):not([type="file"]), textarea, select';
+
+ const fontSizes = new Set();
+ const textBoxes = [];
+ const controls = [];
+ const lowContrast = [];
+ const nodes = document.body?.querySelectorAll('*') || [];
+ if (nodes.length > ${HTML_PREVIEW_DESIGN_MAX_ELEMENTS}) incomplete.add('element_limit');
+ const elements = Array.from({ length: Math.min(nodes.length, ${HTML_PREVIEW_DESIGN_MAX_ELEMENTS}) },
+ (_, index) => nodes[index]);
+ for (const element of elements) {
+ if (element.hasAttribute('style')) scanDeclarations(element.style);
+ if (element instanceof SVGElement) {
+ collect(element.getAttribute('fill'), literalColors);
+ collect(element.getAttribute('stroke'), literalColors);
+ }
+ if (!shown(element)) continue;
+ const style = getComputedStyle(element);
+ record(style.backgroundColor, element);
+ for (const side of sides) {
+ const borderStyle = style['border' + side + 'Style'];
+ if (parseFloat(style['border' + side + 'Width']) > 0 && borderStyle !== 'none' && borderStyle !== 'hidden') {
+ record(style['border' + side + 'Color'], element);
+ }
+ }
+ if (element instanceof SVGElement && !(element instanceof SVGSVGElement)) {
+ if (!/^(none|url)/.test(style.fill)) record(style.fill, element);
+ if (!/^(none|url)/.test(style.stroke)) record(style.stroke, element);
+ }
+ const box = element.getBoundingClientRect();
+ const hasText = ownText(element);
+ const field = element.matches(fieldSelector);
+ if (element.matches(controlSelector) && controls.length < maxBoxes) {
+ // A transparent, empty overlay link paints nothing text could collide with.
+ const paints = hasText || field || Boolean(element.querySelector('svg, img'))
+ || (parseColor(style.backgroundColor) || [0, 0, 0, 0])[3] > 0
+ || sides.some((side) => parseFloat(style['border' + side + 'Width']) > 0);
+ const area = paints ? clipped(box, element.parentElement) : null;
+ if (area) controls.push({ element, area });
+ } else if (element.matches(controlSelector) && controls.length >= maxBoxes) {
+ incomplete.add('control_box_limit');
+ }
+ // A 1-2px box is visually hidden (sr-only) text: no size, color, or collision.
+ if ((!hasText && !field) || box.width <= 2 || box.height <= 2) continue;
+ const rects = hasText ? textRects(element) : [box];
+ if (!rects.length) continue;
+ const size = Math.round(parseFloat(style.fontSize) * 2) / 2;
+ if (size > 0) fontSizes.add(size);
+ record(style.color, element);
+ if (!hasText) continue;
+ if (textBoxes.length < maxBoxes) {
+ const lines = rects.map((rect) => clipped(rect, element)).filter(Boolean);
+ if (lines.length) {
+ textBoxes.push({
+ element,
+ lines,
+ bounds: {
+ left: Math.min(...lines.map((line) => line.left)),
+ top: Math.min(...lines.map((line) => line.top)),
+ right: Math.max(...lines.map((line) => line.right)),
+ bottom: Math.max(...lines.map((line) => line.bottom)),
+ },
+ });
+ }
+ } else {
+ incomplete.add('text_box_limit');
+ }
+ if (element.closest(':disabled, [aria-disabled="true"]')) continue;
+ const ink = parseColor(style.color);
+ const ground = backgroundOf(element);
+ if (!ink || ink[3] <= 0 || !ground) continue;
+ const text = ink[3] < 1 ? blend(ink, ground) : ink;
+ const ratio = contrast(text, ground);
+ const px = parseFloat(style.fontSize) || 16;
+ const weight = parseFloat(style.fontWeight) || 400;
+ const required = px >= 24 || (px >= 18.66 && weight >= 700) ? 3 : 4.5;
+ if (ratio + 0.005 < required) {
+ lowContrast.push({
+ selector: selector(element),
+ ratio: Math.floor(ratio * 100) / 100,
+ required,
+ color: hex(text),
+ background: hex(ground),
+ fontSize: px,
+ });
+ }
+ }
+
+ const overlaps = [];
+ const reported = new Set();
+ const ids = new Map();
+ const idOf = (element) => {
+ if (!ids.has(element)) ids.set(element, ids.size);
+ return ids.get(element);
+ };
+ const overlap = (left, right) => {
+ const width = Math.min(left.right, right.right) - Math.max(left.left, right.left);
+ const height = Math.min(left.bottom, right.bottom) - Math.max(left.top, right.top);
+ return width > 2 && height > 2 ? { width, height } : null;
+ };
+ // Tight line-height lets neighbouring glyph boxes touch; only a quarter of
+ // a line or more counts as a collision.
+ const collides = (line, other) => {
+ const hit = overlap(line, other);
+ return hit && hit.height > Math.min(line.bottom - line.top, other.bottom - other.top) * 0.25 ? hit : null;
+ };
+ const labelFor = (element) => {
+ const label = element.closest('label');
+ return label ? label.control : null;
+ };
+ const related = (left, right) => left === right || left.contains(right) || right.contains(left)
+ || labelFor(left) === right || labelFor(right) === left;
+ // One entry per colliding pair: text-on-text and text-on-control can both
+ // fire for the same two elements.
+ const note = (element, other, hit) => {
+ const key = [idOf(element), idOf(other)].sort((left, right) => left - right).join('|');
+ if (reported.has(key) || overlaps.length >= maxSamples) return;
+ reported.add(key);
+ overlaps.push({
+ selector: selector(element),
+ other: selector(other),
+ width: Math.round(hit.width),
+ height: Math.round(hit.height),
+ });
+ };
+ for (let index = 0; index < textBoxes.length && overlaps.length < maxSamples; index += 1) {
+ const current = textBoxes[index];
+ for (let next = index + 1; next < textBoxes.length; next += 1) {
+ const candidate = textBoxes[next];
+ if (!overlap(current.bounds, candidate.bounds) || related(current.element, candidate.element)) continue;
+ let hit = null;
+ for (const line of current.lines) {
+ for (const other of candidate.lines) {
+ hit = collides(line, other);
+ if (hit) break;
+ }
+ if (hit) break;
+ }
+ if (hit) note(current.element, candidate.element, hit);
+ }
+ for (const control of controls) {
+ if (!overlap(current.bounds, control.area) || related(current.element, control.element)) continue;
+ let hit = null;
+ for (const line of current.lines) {
+ hit = collides(line, control.area);
+ if (hit) break;
+ }
+ if (hit) note(current.element, control.element, hit);
+ }
+ }
+
+ const nonToken = Array.from(used.entries())
+ .filter(([, entry]) => near(literalColors, entry.color) && !near(tokenColors, entry.color))
+ .sort((left, right) => right[1].count - left[1].count);
+ return {
+ fontSizes: Array.from(fontSizes).sort((left, right) => right - left),
+ colorTokenCount: tokenCount,
+ nonTokenColorCount: nonToken.length,
+ nonTokenColors: nonToken.slice(0, maxSamples).map(([key, entry]) => key + ' (' + entry.where + ')'),
+ textOverlaps: overlaps,
+ lowContrastCount: lowContrast.length,
+ // Repeated rows of one component share a sample.
+ lowContrastText: lowContrast
+ .sort((left, right) => left.ratio - right.ratio)
+ .filter((item, index, list) => list.findIndex((other) => other.selector === item.selector
+ && other.color === item.color && other.background === item.background
+ && other.fontSize === item.fontSize) === index)
+ .slice(0, maxSamples),
+ ...(incomplete.size ? { incomplete: Array.from(incomplete) } : {}),
+ };
+ };
+ const safeDesignEvidence = () => {
+ try {
+ return designEvidence();
+ } catch (error) {
+ return {
+ fontSizes: [],
+ colorTokenCount: 0,
+ nonTokenColorCount: 0,
+ nonTokenColors: [],
+ textOverlaps: [],
+ lowContrastCount: 0,
+ lowContrastText: [],
+ error: String((error && error.message) || error).slice(0, ${HTML_PREVIEW_MAX_DIAGNOSTIC_CHARS}),
+ };
+ }
+ };
+`;
+
+function evidenceScript(designAudit: boolean): string {
+ return `(() => {
${INEFFECTIVE_TRANSFORMS_SCRIPT}
const viewportWidth = Math.max(1, document.documentElement.clientWidth || window.innerWidth || 1);
const viewportHeight = Math.max(1, document.documentElement.clientHeight || window.innerHeight || 1);
@@ -227,6 +679,7 @@ const EVIDENCE_SCRIPT = `(() => {
const classes = Array.from(element.classList || []).slice(0, 2).map((value) => '.' + CSS.escape(value)).join('');
return String(element.tagName || 'element').toLowerCase() + classes;
};
+ ${designAudit ? DESIGN_EVIDENCE_SCRIPT : ''}
const issues = [];
for (const element of Array.from(document.body?.querySelectorAll('*') || [])) {
if (issues.length >= ${HTML_PREVIEW_MAX_DIAGNOSTICS} || !visible(element)) continue;
@@ -285,9 +738,14 @@ const EVIDENCE_SCRIPT = `(() => {
missingAltCount: images.filter((img) => !img.hasAttribute('alt')).length,
failedImageCount: images.filter((img) => img.complete && img.naturalWidth === 0).length,
layoutIssues: issues,
- ineffectiveTransforms: ineffectiveTransforms()
+ ineffectiveTransforms: ineffectiveTransforms()${designAudit ? `,
+ design: safeDesignEvidence()` : ''}
};
})()`;
+}
+
+const EVIDENCE_SCRIPT = evidenceScript(false);
+const DESIGN_AUDIT_EVIDENCE_SCRIPT = evidenceScript(true);
const INTERACTION_SCRIPT = `(async () => {
${INEFFECTIVE_TRANSFORMS_SCRIPT}
@@ -391,6 +849,54 @@ const INTERACTION_SCRIPT = `(async () => {
}
}
+ // Exercise each standalone field once before controls consume its value.
+ // Recheck after state changes for newly revealed fields, sharing one budget.
+ const exercisedFields = new WeakSet();
+ let fieldsExercised = 0;
+ const exerciseVisibleFields = async () => {
+ if (fieldsExercised >= maxGenericControls) return;
+ const fields = Array.from(document.querySelectorAll('input,textarea,select'))
+ .filter((field) => visible(field) && !field.disabled && !field.readOnly && !field.closest('form')
+ && !exercisedFields.has(field))
+ .slice(0, maxGenericControls - fieldsExercised);
+ for (const field of fields) {
+ exercisedFields.add(field);
+ fieldsExercised += 1;
+ try {
+ const before = visibleState();
+ if (field instanceof HTMLSelectElement) {
+ const alternatives = Array.from(field.options).filter((option) => !option.disabled);
+ const next = alternatives.find((option) => option.value !== field.value);
+ if (next) field.value = next.value;
+ } else if (field instanceof HTMLInputElement) {
+ const type = String(field.type || '').toLowerCase();
+ if (type === 'checkbox') field.checked = !field.checked;
+ else if (type === 'radio') field.checked = true;
+ else if (type === 'number' || type === 'range') {
+ const current = Number(field.value || 0);
+ const step = Math.max(1, Number(field.step || 1) || 1);
+ field.value = String(current + step);
+ } else if (!['button', 'submit', 'reset', 'file', 'hidden'].includes(type)) {
+ field.value = String(field.value || '') + ' preview';
+ }
+ } else if (field instanceof HTMLTextAreaElement) {
+ field.value = String(field.value || '') + ' preview';
+ }
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ field.dispatchEvent(new Event('change', { bubbles: true }));
+ controlsExercised += 1;
+ const after = await settleVisibleState(before, 500);
+ auditTransforms();
+ if (after !== before) stateChangesObserved += 1;
+ else warnings.push('standalone field produced no observable outcome: ' + label(field));
+ } catch (error) {
+ failures.push('control interaction failed for ' + label(field) + ': ' + String(error?.message || error));
+ }
+ }
+ };
+
+ await exerciseVisibleFields();
+
const explicitDownloads = Array.from(document.querySelectorAll('a[download]')).filter(visible);
const namedDownloadButtons = Array.from(document.querySelectorAll('button,[role="button"]'))
.filter((element) => visible(element) && /download|resume|cv|简历|下载/i.test(label(element)));
@@ -522,6 +1028,7 @@ const INTERACTION_SCRIPT = `(async () => {
enqueueVisibleStateControls();
await exerciseVisibleForms();
+ await exerciseVisibleFields();
enqueueVisibleStateControls();
for (let index = 0; index < stateControlQueue.length && index < maxStateControls; index += 1) {
const control = stateControlQueue[index];
@@ -548,47 +1055,14 @@ const INTERACTION_SCRIPT = `(async () => {
}
enqueueVisibleStateControls();
await exerciseVisibleForms();
+ await exerciseVisibleFields();
enqueueVisibleStateControls();
} catch (error) {
failures.push('control interaction failed for ' + label(control) + ': ' + String(error?.message || error));
}
}
- const fields = Array.from(document.querySelectorAll('input,textarea,select'))
- .filter((field) => visible(field) && !field.disabled && !field.readOnly && !field.closest('form'))
- .slice(0, maxGenericControls);
- for (const field of fields) {
- try {
- const before = visibleState();
- if (field instanceof HTMLSelectElement) {
- const alternatives = Array.from(field.options).filter((option) => !option.disabled);
- const next = alternatives.find((option) => option.value !== field.value);
- if (next) field.value = next.value;
- } else if (field instanceof HTMLInputElement) {
- const type = String(field.type || '').toLowerCase();
- if (type === 'checkbox') field.checked = !field.checked;
- else if (type === 'radio') field.checked = true;
- else if (type === 'number' || type === 'range') {
- const current = Number(field.value || 0);
- const step = Math.max(1, Number(field.step || 1) || 1);
- field.value = String(current + step);
- } else if (!['button', 'submit', 'reset', 'file', 'hidden'].includes(type)) {
- field.value = String(field.value || '') + ' preview';
- }
- } else if (field instanceof HTMLTextAreaElement) {
- field.value = String(field.value || '') + ' preview';
- }
- field.dispatchEvent(new Event('input', { bubbles: true }));
- field.dispatchEvent(new Event('change', { bubbles: true }));
- controlsExercised += 1;
- const after = await settleVisibleState(before, 500);
- auditTransforms();
- if (after !== before) stateChangesObserved += 1;
- else warnings.push('standalone field produced no observable outcome: ' + label(field));
- } catch (error) {
- failures.push('control interaction failed for ' + label(field) + ': ' + String(error?.message || error));
- }
- }
+ await exerciseVisibleFields();
await sleep(40);
return {
@@ -742,6 +1216,43 @@ function boundedDiagnostic(value: unknown): string {
return String(value || '').replace(/\s+/g, ' ').trim().slice(0, HTML_PREVIEW_MAX_DIAGNOSTIC_CHARS);
}
+/** Review prompts from one viewport's design audit. They name the element
+ * and the measured value; none of them blocks the preview or its screenshots. */
+function designWarnings(view: HtmlPreviewViewportEvidence): string[] {
+ const design = view.design;
+ if (!design) return [];
+ if (design.error) return [`${view.name}: design audit did not run: ${boundedDiagnostic(design.error)}`];
+ const warnings: string[] = [];
+ if (design.incomplete?.length) {
+ warnings.push(boundedDiagnostic(`${view.name}: design audit coverage is partial: ${design.incomplete.join(', ')}`));
+ }
+ if (design.fontSizes.length > HTML_PREVIEW_FONT_SIZE_LIMIT) {
+ warnings.push(boundedDiagnostic(
+ `${view.name}: ${design.fontSizes.length} distinct font sizes on visible text `
+ + `(${design.fontSizes.join(', ')}px); a type scale needs ${HTML_PREVIEW_FONT_SIZE_LIMIT} or fewer`,
+ ));
+ }
+ if (design.nonTokenColorCount) {
+ const samples = design.nonTokenColors.join(', ');
+ warnings.push(boundedDiagnostic(design.colorTokenCount
+ ? `${view.name}: ${design.nonTokenColorCount} hard-coded color(s) match no color variable: ${samples}`
+ : `${view.name}: no color variables; ${design.nonTokenColorCount} hard-coded color(s): ${samples}`));
+ }
+ if (design.textOverlaps.length) {
+ warnings.push(boundedDiagnostic(
+ `${view.name}: ${design.textOverlaps.length} text overlap(s): `
+ + design.textOverlaps.map((item) => `${item.selector} × ${item.other}`).join(', '),
+ ));
+ }
+ if (design.lowContrastCount) {
+ warnings.push(boundedDiagnostic(
+ `${view.name}: ${design.lowContrastCount} text element(s) below WCAG AA contrast: `
+ + design.lowContrastText.map((item) => `${item.selector} ${item.ratio}:1 < ${item.required}:1`).join(', '),
+ ));
+ }
+ return warnings;
+}
+
function blockedResourceLabel(raw: string): string {
try {
const url = new URL(raw);
@@ -907,6 +1418,7 @@ async function renderViewport(
viewport: HtmlPreviewViewport,
auditKeyboard: boolean,
exerciseInteractions: boolean,
+ designAudit: boolean,
bundle: Bundle | null,
sdkOrigin: { current?: string },
): Promise<{
@@ -946,11 +1458,19 @@ async function renderViewport(
);
const inspected = sdk ? await withTimeout(sdk.attach(), 'E_HTML_PREVIEW_SDK_TIMEOUT: SDK frame did not load') : webContents;
await withTimeout(
- inspected.executeJavaScript(READY_SCRIPT, true),
+ (async () => {
+ await inspected.executeJavaScript(READY_SCRIPT, true);
+ await sdk?.settle();
+ // Completed SDK calls can add fonts/images and change the layout.
+ if (sdk) await inspected.executeJavaScript(READY_SCRIPT, true);
+ })(),
`E_HTML_PREVIEW_READY_TIMEOUT: ${viewport.name} fonts or images did not settle`,
);
const page = await withTimeout(
- inspected.executeJavaScript(EVIDENCE_SCRIPT, true) as Promise<PageEvidence>,
+ inspected.executeJavaScript(
+ designAudit ? DESIGN_AUDIT_EVIDENCE_SCRIPT : EVIDENCE_SCRIPT,
+ true,
+ ) as Promise<PageEvidence>,
`E_HTML_PREVIEW_INSPECT_TIMEOUT: ${viewport.name} layout inspection timed out`,
);
const image = await withTimeout(
@@ -981,6 +1501,7 @@ async function renderViewport(
`E_HTML_PREVIEW_AUDIT_TIMEOUT: ${viewport.name} preview audit timed out`,
)
: undefined;
+ if (sdk) await withTimeout(sdk.settle(), 'E_HTML_PREVIEW_SDK_TIMEOUT: SDK requests did not settle');
const size = image.getSize();
return {
evidence: {
@@ -1068,6 +1589,7 @@ export async function renderResponsiveHtmlPreview(
interactions?: RenderInteractionEvidence;
}> = [];
const exerciseInteractions = options.interactions !== false;
+ const designAudit = options.designAudit !== false;
for (const [index, viewport] of viewports.entries()) {
rendered.push(await renderViewport(
BrowserWindow,
@@ -1076,6 +1598,7 @@ export async function renderResponsiveHtmlPreview(
viewport,
index === 0,
index === 0 && exerciseInteractions,
+ designAudit,
bundle,
sdkOrigin,
));
@@ -1107,6 +1630,7 @@ export async function renderResponsiveHtmlPreview(
if (!view.focusableCount) {
warnings.push(`${view.name}: no keyboard-focusable control was detected`);
}
+ warnings.push(...designWarnings(view));
}
if (blocked.count) {
blockers.push(`${blocked.count} external or out-of-directory resource request(s) were blocked`);
@@ -1255,7 +1779,7 @@ export async function renderInteractiveHtmlSmoke(
previewEntry,
ARTIFACT_SMOKE_VIEWPORTS,
deps,
- { interactions: true },
+ { interactions: true, designAudit: false },
);
} finally {
if (previewRoot) fs.rmSync(previewRoot, { recursive: true, force: true });
diff --git a/src/main/features/preview_windows.ts b/src/main/features/preview_windows.ts
index ab776672..18f5cc08 100644
--- a/src/main/features/preview_windows.ts
+++ b/src/main/features/preview_windows.ts
@@ -7,6 +7,7 @@ import { createLogger } from '../logger';
import { hardenedWebPreferences, installExternalNavigationGuard, installHtmlPreviewNavigationGuard } from '../util/window-security';
import { registerUserSwitchHook } from './user-switch-hooks';
import { subscribeBus } from './group_chat';
+import { commercialWebAppFailure, isCommercialWebAppFailure, requireLocalAppType, storedAppType } from './web_apps/commercial-entry';
// Host-only window chrome. Generated applications retain the existing iframe
// sandbox and acquire their SDK instance from their own trusted renderer.
@@ -85,6 +86,19 @@ export async function replacePreview(uid: string, sender: WebContents, accepted:
export async function openPreview(uid: string, owner: WebContents, payload: unknown) {
if ((JSON.stringify(payload)?.length || 0) > 8 * 1024 * 1024) throw new Error('Preview is too large.');
const source = sourceSchema.parse(payload);
+ try {
+ const saved = await import('./saved_apps');
+ if (source.kind === 'app') requireLocalAppType(await saved.resolveSavedAppType(uid, source.appId));
+ else if (source.kind === 'artifact') requireLocalAppType(await saved.resolveArtifactAppType(uid, source.cid, source.artifactId));
+ else if (source.kind === 'file') {
+ if (source.options.cid) requireLocalAppType(await saved.boundAppType(uid, source.options.cid));
+ const file = source.options.absPath || source.path;
+ if (path.isAbsolute(file)) {
+ requireLocalAppType(await saved.managedPathAppType(uid, file));
+ requireLocalAppType(storedAppType(path.dirname(file)));
+ }
+ }
+ } catch (error) { if (isCommercialWebAppFailure(error)) return commercialWebAppFailure(); throw error; }
if (records.has(owner.id)) throw new Error('Open previews from the main window.');
const existing = [...records.values()].find(r => r.uid === uid && r.owner === owner
&& (source.kind === 'app' ? sourceKey(r.source) === sourceKey(source) : r.source.kind !== 'app'));
diff --git a/src/main/features/saved_apps.ts b/src/main/features/saved_apps.ts
index 65d8396f..5f3fc8f7 100644
--- a/src/main/features/saved_apps.ts
+++ b/src/main/features/saved_apps.ts
@@ -5,7 +5,7 @@
* 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>/{entry.html, ...siblings, __orkas-meta.json}`
- * Cloud-synced; conversation-independent; never auto-purged (only the user's
+ * Device-local and conversation-independent; never auto-purged (only the user's
* explicit delete from the My Apps tab removes one). The files are served
* read-only inside the app via `chat-app://saved/<appId>/...`; the explicit
* external-open IPC still uses `shell.openPath` for callers that want the OS
@@ -23,14 +23,18 @@ import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
import * as crypto from 'node:crypto';
-import { userSavedAppsDir, savedAppDir } from '../paths';
+import { userSavedAppsDir, savedAppDir, userAppEditsDir,webAppSandboxRoot,userLocalRoot,userAppDeletesDir, userCloudRoot } from '../paths';
+import { metadataAppType, normalizeAppType, type AppType } from './web_apps/data-contract';
+import { commercialWebAppFailure, requireLocalAppType, storedAppType, isCommercialWebAppFailure } from './web_apps/commercial-entry';
import * as chatArtifacts from './chat_artifacts';
import * as chats from './chats';
+import { conversationLayout } from '../util/project-layout';
import * as chatAttachments from './chat_attachments';
import { t } from '../i18n';
import { createLogger } from '../logger';
-import { logErrorRef, logPathRef, maskId } from '../util/log-redact';
+import { logErrorSummary, logPathRef, maskId } from '../util/log-redact';
import { isPathAllowed } from '../util/path-sandbox';
+import { renameWithRetrySync, writeTextAtomicSync } from '../storage';
const log = createLogger('saved_apps');
@@ -57,10 +61,13 @@ const BUNDLE_EXCLUDED_DIRS: ReadonlySet<string> = new Set([
]);
const SOURCE_BUNDLE_NAME = 'app-source.md';
-export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string };
+export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string; code?: string; feature?: string; message?: string };
type ResolveCode = 'bad_input' | 'forbidden' | 'not_found';
export interface SavedAppMeta {
+ browserStorage?: 'isolated-v1';
+ appType?: AppType;
+ description?: string;
title: string;
sourceCid: string;
sourceArtifactId: string;
@@ -69,6 +76,8 @@ export interface SavedAppMeta {
}
export interface SavedAppListItem {
+ appType?: AppType;
+ description?: string;
id: string;
title: string;
savedAt: string;
@@ -111,7 +120,37 @@ function sanitiseTitle(t: unknown): string {
}
function writeMeta(dir: string, meta: SavedAppMeta): void {
- fs.writeFileSync(path.join(dir, META_FILENAME), Buffer.from(JSON.stringify(meta, null, 2), 'utf8'));
+ writeTextAtomicSync(path.join(dir, META_FILENAME), JSON.stringify(meta, null, 2));
+}
+
+// `<appId>.tmp-<8 hex>` staging folders (save copies and delete staging) are
+// never apps. Ones registered here belong to an operation in this process;
+// any other match is an interrupted leftover and is swept from the list path.
+const STAGING_DIR_RE = /^[A-Za-z0-9_-]{1,64}\.tmp-[a-f0-9]{8}$/;
+const activeStagingDirs = new Set<string>();
+function stagingDir(destDir: string): string {
+ const dir = `${destDir}.tmp-${crypto.randomBytes(4).toString('hex')}`;
+ activeStagingDirs.add(dir);
+ return dir;
+}
+function sweepStagingDirs(root: string, names: readonly string[], retained?: ReadonlySet<string>): void {
+ for (const name of names) {
+ if (!STAGING_DIR_RE.test(name)) continue;
+ const dir = path.join(root, name);
+ if (activeStagingDirs.has(dir) || retained?.has(dir)) continue;
+ try { const st = fs.lstatSync(dir); if (!st.isDirectory() || st.isSymbolicLink() || storedAppType(dir) === 'web') continue; }
+ catch { continue; }
+ activeStagingDirs.add(dir);
+ void fsp.rm(dir, { recursive: true, force: true })
+ .catch((error) => log.warn('saved app staging sweep deferred', { error: logErrorSummary(error) }))
+ .finally(() => activeStagingDirs.delete(dir));
+ }
+}
+/** Stable caller-visible failure: known `app_*` codes pass through, anything
+ * else (errno text, absolute paths) collapses to `fallback`. */
+function failureCode(err: unknown, fallback: string): string {
+ const message = (err as Error)?.message;
+ return typeof message === 'string' && /^app_[a-z_]+$/.test(message) ? message : fallback;
}
function isRealSavedAppDirectory(dir: string): boolean {
@@ -130,24 +169,19 @@ function readMeta(dir: string): Partial<SavedAppMeta> {
return JSON.parse(fs.readFileSync(metaPath, 'utf8')) || {};
}
-function savedAppRelPath(appId: string, rel = ''): string {
- return ['cloud/saved_apps', appId, rel].filter(Boolean).join('/');
-}
-
-function notifySavedAppDirty(appId: string, rel = ''): void {
+/** The absence of this additive marker preserves legacy browser storage. */
+export function hasIsolatedBrowserStorage(uid: string, appId: string): boolean {
try {
- // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
- const sync = null as { markDirty?: (domain: string, relPath: string) => void };
- sync?.markDirty?.('saved_apps', savedAppRelPath(appId, rel));
- } catch { /* features/sync stripped */ }
+ const dir = savedAppDir(uid, safeAppId(appId));
+ return isRealSavedAppDirectory(dir) && readMeta(dir).browserStorage === 'isolated-v1';
+ } catch { return false; }
}
-function notifySavedAppDeleted(appId: string, rel: string): void {
- try {
- // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
- const sync = null as { markDeleted?: (relPath: string) => Promise<void> | void };
- void sync?.markDeleted?.(savedAppRelPath(appId, rel));
- } catch { /* features/sync stripped */ }
+/** Persisted metadata owns type; legacy local apps have no type marker. */
+export async function resolveSavedAppType(uid: string, appId: string): Promise<AppType> {
+ const id = safeAppId(appId), dir = savedAppDir(uid, id);
+ if (!isRealSavedAppDirectory(dir)) throw new Error('app not found');
+ return storedAppType(dir) ?? 'local';
}
function isInsideAnyRoot(candidate: string, roots: string[]): boolean {
@@ -185,6 +219,38 @@ async function inferTitleFromHtml(entryPath: string, rootDir: string): Promise<s
return sanitiseTitle(path.basename(rootDir));
}
+function sanitiseDescription(value: unknown): string {
+ return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, 240) : '';
+}
+
+/** Read optional display copy once on save; gallery reads never scan app sources. */
+async function readHtmlDescription(entryPath: string): Promise<string> {
+ let file: fsp.FileHandle | undefined;
+ try {
+ file = await fsp.open(entryPath, 'r');
+ const buffer = Buffer.alloc(64 * 1024);
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ const html = buffer.toString('utf8', 0, bytesRead)
+ .replace(/<!--[\s\S]*?(?:-->|$)|<(script|style)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi, '');
+ for (const tag of html.matchAll(/<meta\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi)) {
+ const attrs: Record<string, string> = {};
+ for (const attr of tag[0].matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) {
+ attrs[attr[1].toLowerCase()] = attr[2] ?? attr[3] ?? attr[4];
+ }
+ if (attrs.name?.toLowerCase() !== 'description') continue;
+ const decoded = (attrs.content || '').replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (entity, key: string) => {
+ const named: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
+ if (key[0] !== '#') return named[key.toLowerCase()] ?? entity;
+ const point = key[1].toLowerCase() === 'x' ? parseInt(key.slice(2), 16) : Number(key.slice(1));
+ return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff) ? String.fromCodePoint(point) : entity;
+ });
+ return sanitiseDescription(decoded);
+ }
+ } catch { /* Optional metadata must not prevent saving an app. */ }
+ finally { await file?.close().catch(() => {}); }
+ return '';
+}
+
function isHtmlEntryName(name: string): boolean {
return HTML_ENTRY_EXTS.has(path.extname(name).toLowerCase());
}
@@ -334,6 +400,14 @@ async function inspectBundle(targetPath: string, opts: BundleInspectOptions): Pr
if (opts.fenceRoots?.length && !isInsideAnyRoot(rootDir, opts.fenceRoots)) {
return { ok: true, canSave: false, reason: 'bundle is outside allowed workspace' };
}
+ // A sandbox root can contain unrelated user files; it is never an implicit app bundle.
+ const realRoot = await fsp.realpath(rootDir);
+ for (const root of opts.fenceRoots || []) {
+ const realFence = await fsp.realpath(root).catch(() => path.resolve(root));
+ if (path.relative(realFence, realRoot) === '') {
+ return { ok: true, canSave: false, reason: 'app_bundle_root' };
+ }
+ }
const entry = found.entry;
const entryAbs = path.join(rootDir, entry);
let entryStat: fs.Stats;
@@ -386,26 +460,101 @@ function mintAppId(userId: string): { appId: string; destDir: string } {
// ── Public API ───────────────────────────────────────────────────────────
+function localDatabase(uid:string,appId:string){const key=crypto.createHash('sha256').update(JSON.stringify(['saved',appId])).digest('hex');return {key,file:path.join(webAppSandboxRoot(uid,key,'local'),'data.sqlite')};}
+async function appDefinition(dir:string){try{const {manifestSchema}=await import('./web_apps/catalog');const file=path.join(dir,'orkas-app.json');if((await fsp.stat(file)).size>65536)throw new Error('app_edit_data_migration');const definition=manifestSchema.parse(JSON.parse(await fsp.readFile(file,'utf8'))).data;if(!definition)throw new Error('app_edit_data_migration');return definition;}catch{throw new Error('app_edit_data_migration');}}
+/** Author-only recovery facts; records never enter model context. */
+export async function appDataImpact(uid:string,cid:string,artifactId:string):Promise<Result<{records:number;version:number;fingerprint:string;tables:Array<{name:string;fields:string[];count:number}>}>>{
+ try { requireLocalAppType(await boundAppType(uid, cid)); requireLocalAppType(await resolveArtifactAppType(uid, cid, artifactId)); }
+ catch (error) { return isCommercialWebAppFailure(error) ? commercialWebAppFailure() : { ok: false, error: 'app_edit_target_missing' }; }
+ const context=readEditContext(uid,cid),artifact=chatArtifacts.resolveArtifactDir(uid,cid,artifactId);if(!context||!artifact.ok)return {ok:false,error:'app_edit_target_missing'};
+ let release:(()=>void)|undefined;
+ try{const dir=savedAppDir(uid,context.appId);if(fingerprintApp(dir)!==context.fingerprint)throw new Error('app_edit_conflict');const {key,file}=localDatabase(uid,context.appId);const runtime=await import('./web_apps/runtime');release=runtime.holdAppData(uid,key);await runtime.closeAppData(uid,key);const {LocalAppData}=await import('./web_apps/data');const database=new LocalAppData(file,userLocalRoot(uid),await appDefinition(dir));try{const info:any=await database.call('internal.inspect',{});return {ok:true,records:info.records,version:info.version,fingerprint:context.fingerprint,tables:info.tables};}finally{await database.close();}}
+ catch{return {ok:false,error:'app_edit_conflict'};}finally{release?.();}
+}
+/** Consistent private SQLite export, create-only at the user-selected destination. */
+async function removeAppDataBackup(file: string): Promise<void> {
+ for (const suffix of ['', '-wal', '-shm']) {
+ try { await fsp.rm(file + suffix, { force: true }); }
+ catch (error) { log.warn('edited app data backup cleanup deferred', { error: logErrorSummary(error) }); }
+ }
+}
+
+export async function exportAppData(uid:string,cid:string,artifactId:string,destination:string):Promise<Result>{
+ try { requireLocalAppType(await boundAppType(uid, cid)); requireLocalAppType(await resolveArtifactAppType(uid, cid, artifactId)); }
+ catch (error) { return isCommercialWebAppFailure(error) ? commercialWebAppFailure() : { ok: false, error: 'app_edit_target_missing' }; }
+ const context=readEditContext(uid,cid);if(!context||!chatArtifacts.resolveArtifactDir(uid,cid,artifactId).ok)return {ok:false,error:'app_edit_target_missing'};
+ let release:(()=>void)|undefined,temporary='';
+ try{const {key,file}=localDatabase(uid,context.appId),runtime=await import('./web_apps/runtime');release=runtime.holdAppData(uid,key);await runtime.closeAppData(uid,key);temporary=file+'.backup-'+crypto.randomBytes(8).toString('hex');const {LocalAppData}=await import('./web_apps/data');const database=new LocalAppData(file,userLocalRoot(uid),await appDefinition(savedAppDir(uid,context.appId)));try{await database.call('internal.backup',{file:temporary});}finally{await database.close();}const users=await import('./users');if(users.getActiveUserId()!==uid)throw new Error('app_edit_conflict');await fsp.copyFile(temporary,destination,fs.constants.COPYFILE_EXCL);return {ok:true};}
+ catch{return {ok:false,error:'app_edit_data_export_failed'};}
+ finally {
+ try { if (temporary) await removeAppDataBackup(temporary); }
+ finally { release?.(); }
+ }
+}
+
/** Copy a chat artifact bundle into a new `saved_apps/<appId>/`. */
-export async function saveFromArtifact(userId: string, cid: string, artifactId: string): Promise<Result<{ id: string; title: string }>> {
+const activeEditSaves = new Map<string, number>();
+const deferredEditCleanup = new Set<string>();
+
+export async function saveFromArtifact(userId: string, cid: string, artifactId: string, mode: 'new' | 'update' = 'new', recovery?:{clearVersion:number;clearFingerprint:string}): Promise<Result<{ id: string; title: string }>> {
+ try {
+ requireLocalAppType(await boundAppType(userId, cid));
+ requireLocalAppType(await resolveArtifactAppType(userId, cid, artifactId));
+ } catch (error) {
+ return isCommercialWebAppFailure(error) ? commercialWebAppFailure() : { ok: false, error: 'app_edit_target_missing' };
+ }
+ const key = JSON.stringify([userId, cid]);
+ activeEditSaves.set(key, (activeEditSaves.get(key) || 0) + 1);
+ try { return await saveArtifact(userId, cid, artifactId, mode, recovery); }
+ finally {
+ const remaining = activeEditSaves.get(key)! - 1;
+ if (remaining) activeEditSaves.set(key, remaining);
+ else {
+ activeEditSaves.delete(key);
+ if (deferredEditCleanup.delete(key)) await cleanupEditSnapshots(userId);
+ }
+ }
+}
+
+async function saveArtifact(userId: string, cid: string, artifactId: string, mode: 'new' | 'update', recovery?:{clearVersion:number;clearFingerprint:string}): Promise<Result<{ id: string; title: string }>> {
+ recoverEditedSaves(userId);
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);
+ const context = readEditContext(userId, cid);
+ // Only an untyped artifact consults the task binding, which must resolve or
+ // fail. An update must also keep the original app's trusted type: the
+ // untyped case inherits it, so only a typed artifact needs the comparison.
+ let appType: AppType;
+ try {
+ appType = await resolveArtifactAppType(userId, cid, artifactId, srcMeta);
+ if (mode === 'update' && context && srcMeta?.appType) {
+ const original = (await getEditTarget(userId, cid))?.appType;
+ if (original && original !== appType) return { ok: false, error: 'app_type_mismatch' };
+ }
+ } catch (err) {
+ log.warn('saveFromArtifact edit binding unavailable', { error: logErrorSummary(err) });
+ return { ok: false, error: 'app_edit_target_missing' };
+ }
+ if (mode === 'update' && !context) return { ok: false, error: 'app_edit_target_missing' };
let appId = '';
let destDir = '';
try {
- const minted = mintAppId(userId);
+ const minted = mode === 'update' && context
+ ? { appId: context.appId, destDir: savedAppDir(userId, context.appId) }
+ : mintAppId(userId);
appId = minted.appId;
destDir = minted.destDir;
} catch (err) {
return { ok: false, error: (err as Error).message };
}
- const tmpDir = `${destDir}.tmp-${crypto.randomBytes(4).toString('hex')}`;
+ const tmpDir = stagingDir(destDir);
+ let release:(()=>void)|undefined,dataFile='',candidate='';
try {
// Copy everything except the source `__orkas-meta.json` (we write a fresh
// one stamped with the source provenance).
@@ -413,10 +562,28 @@ export async function saveFromArtifact(userId: string, cid: string, artifactId:
recursive: true,
filter: (src) => path.basename(src) !== META_FILENAME,
});
+ // Binary placeholders in the editing attachment are not replacement bytes.
+ // Omitted binary resources survive; explicit artifact files take precedence.
+ if (context) {
+ const snapshot = path.join(editContextDir(userId, cid), 'snapshot');
+ for (const rel of listAppFilesRel(snapshot)) {
+ if (rel === META_FILENAME || TEXT_LIKE_EXTS.has(path.extname(rel).toLowerCase())) continue;
+ const target = path.join(tmpDir, rel);
+ if (!fs.existsSync(target)) {
+ const source = path.join(snapshot, rel);
+ if (!isPathAllowed(source, [snapshot])) throw new Error('app_edit_snapshot_invalid');
+ await fsp.mkdir(path.dirname(target), { recursive: true });
+ await fsp.copyFile(source, target);
+ }
+ }
+ }
if (!fs.existsSync(path.join(tmpDir, 'index.html'))) {
throw new Error('source artifact is missing index.html');
}
const meta: SavedAppMeta = {
+ ...(mode === 'new' || hasIsolatedBrowserStorage(userId, appId) ? { browserStorage: 'isolated-v1' as const } : {}),
+ appType,
+ description: await readHtmlDescription(path.join(tmpDir, 'index.html')),
title,
sourceCid: typeof cid === 'string' ? cid : '',
sourceArtifactId: typeof artifactId === 'string' ? artifactId : '',
@@ -424,25 +591,70 @@ export async function saveFromArtifact(userId: string, cid: string, artifactId:
};
await fsp.writeFile(path.join(tmpDir, META_FILENAME), JSON.stringify(meta, null, 2));
await fsp.mkdir(path.dirname(destDir), { recursive: true });
- await fsp.rename(tmpDir, destDir);
+ if (mode === 'update' && context) {
+ const local=localDatabase(userId,appId);dataFile=local.file;
+ if(fs.existsSync(dataFile)){
+ const runtime=await import('./web_apps/runtime');release=runtime.holdAppData(userId,local.key);await runtime.closeAppData(userId,local.key);
+ const {LocalAppData}=await import('./web_apps/data');candidate=dataFile+'.backup-'+crypto.randomBytes(8).toString('hex');
+ const oldDefinition=await appDefinition(destDir),definition=await appDefinition(tmpDir);
+ const original=new LocalAppData(dataFile,userLocalRoot(userId),oldDefinition);
+ try{const info:any=await original.call('internal.inspect',{});if(recovery&&(recovery.clearVersion!==info.version||recovery.clearFingerprint!==context.fingerprint))throw new Error('app_edit_conflict');await original.call('internal.backup',{file:candidate});}finally{await original.close();}
+ if(recovery){const staged=new LocalAppData(candidate,userLocalRoot(userId),oldDefinition);try{await staged.call('internal.reset',{version:recovery.clearVersion});}finally{await staged.close();}}
+ const database=new LocalAppData(candidate,userLocalRoot(userId),definition,200*1024*1024,true);
+ try{await database.call('internal.check',{});}catch{throw new Error('app_edit_data_migration');}finally{await database.close();}
+ }
+ // No await between the comparison and swap: other main-process actions
+ // cannot silently overwrite a newer save, rename or deletion.
+ if((await import('./users')).getActiveUserId()!==userId)throw new Error('app_edit_conflict');
+ if (!isRealSavedAppDirectory(destDir)) throw new Error('app_edit_target_missing');
+ if (fingerprintApp(destDir) !== context.fingerprint) throw new Error('app_edit_conflict');
+ const backup = `${tmpDir}.previous`;
+ const journal = {version:1,appId,temporary:path.basename(tmpDir),before:context.fingerprint,after:fingerprintApp(tmpDir),...(candidate?{dataCandidate:path.basename(candidate)}:{})};
+ const journalPath=path.join(editContextDir(userId,cid),'save-journal.json');
+ const journalFd=fs.openSync(journalPath,'w',0o600);
+ try { fs.writeFileSync(journalFd,JSON.stringify(journal));fs.fsyncSync(journalFd); } finally {fs.closeSync(journalFd);}
+ fs.renameSync(destDir, backup);
+ try {
+ fs.renameSync(tmpDir, destDir);
+ if(candidate){fs.renameSync(dataFile,dataFile+'.previous');try{fs.renameSync(candidate,dataFile);}catch(error){fs.renameSync(dataFile+'.previous',dataFile);throw error;}}
+ } catch (err) { if(fs.existsSync(destDir))fs.rmSync(destDir,{recursive:true,force:true});fs.renameSync(backup, destDir);throw err; }
+ try {
+ refreshEditSnapshot(userId,cid,context,destDir);
+ fs.rmSync(backup, { recursive: true, force: true });
+ if(candidate)fs.rmSync(dataFile+'.previous',{force:true});
+ fs.rmSync(journalPath,{force:true});
+ if(candidate){const {key}=localDatabase(userId,appId);await (await import('./web_apps/runtime')).checkpointAppData(userId,key,dataFile,await appDefinition(destDir));}
+ } catch (err) {
+ // The save boundary already completed. Cleanup/presentation cannot
+ // turn it into a failed save or remove the newly written application.
+ log.warn('edited app post-save cleanup deferred', { error: logErrorSummary(err) });
+ }
+ } else await fsp.rename(tmpDir, destDir);
} catch (err) {
try { await fsp.rm(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ }
- try { await fsp.rm(destDir, { recursive: true, force: true }); } catch { /* best-effort */ }
+ if (mode !== 'update') {
+ try { await fsp.rm(destDir, { recursive: true, force: true }); } catch { /* best-effort */ }
+ }
log.warn('saveFromArtifact failed', {
user_id: maskId(userId),
conversation_id: maskId(cid),
artifact_id: maskId(artifactId),
- error: logErrorRef(err),
+ error: logErrorSummary(err),
});
- return { ok: false, error: `failed to save app: ${(err as Error).message}` };
+ return { ok: false, error: failureCode(err, 'app_save_failed') };
+ }
+ finally {
+ activeStagingDirs.delete(tmpDir);
+ try { if (candidate) await removeAppDataBackup(candidate); }
+ finally { release?.(); }
}
log.info('saveFromArtifact completed', {
user_id: maskId(userId),
app_id: maskId(appId),
conversation_id: maskId(cid),
artifact_id: maskId(artifactId),
+ save_mode: mode,
});
- notifySavedAppDirty(appId);
return { ok: true, id: appId, title };
}
@@ -452,11 +664,26 @@ export async function saveFromPath(
targetPath: string,
opts: BundleInspectOptions & { title?: unknown; sourceCid?: unknown } = {},
): Promise<Result<{ id: string; title: string; rootDir: string; entry: string; fileCount: number; totalBytes: number }>> {
+ try {
+ if (typeof opts.sourceCid === 'string' && opts.sourceCid) requireLocalAppType(await boundAppType(userId, opts.sourceCid));
+ requireLocalAppType(await managedPathAppType(userId, targetPath));
+ requireLocalAppType(storedAppType(path.dirname(targetPath)));
+ } catch (error) {
+ return isCommercialWebAppFailure(error) ? commercialWebAppFailure() : { ok: false, error: 'app_edit_target_missing' };
+ }
const inspected = await inspectBundle(targetPath, opts);
if (!inspected.ok) return { ok: false, error: (inspected as { ok: false; error: string }).error };
if (!inspected.canSave) return { ok: false, error: (inspected as { ok: true; canSave: false; reason: string }).reason };
+ try { requireLocalAppType(storedAppType(inspected.rootDir)); }
+ catch (error) { return isCommercialWebAppFailure(error) ? commercialWebAppFailure() : { ok: false, error: 'app_edit_target_missing' }; }
const title = sanitiseTitle(opts.title || inspected.title);
+ const sourceCid=typeof opts.sourceCid==='string'?opts.sourceCid:'';
+ const assistance=sourceCid?(await chats.getConversationMetadata(userId,sourceCid))?.assistance:undefined;
+ let editType:AppType|undefined;
+ try{editType=sourceCid?(await getEditTarget(userId,sourceCid))?.appType:undefined;}
+ catch(err){log.warn('saveFromPath edit binding unavailable',{error:logErrorSummary(err)});return {ok:false,error:'app_edit_target_missing'};}
+ const appType:AppType=editType??(assistance?.kind==='app_creation'?assistance.appType??'local':'local');
let appId = '';
let destDir = '';
try {
@@ -467,12 +694,21 @@ export async function saveFromPath(
return { ok: false, error: (err as Error).message };
}
- const tmpDir = `${destDir}.tmp-${crypto.randomBytes(4).toString('hex')}`;
+ const tmpDir = stagingDir(destDir);
try {
await fsp.mkdir(tmpDir, { recursive: true });
const copied = await copyBundleFiles(inspected.rootDir, tmpDir, inspected.files!);
if (!fs.existsSync(path.join(tmpDir, inspected.entry))) throw new Error('bundle is missing its HTML entry');
+ if(appType==='web'){
+ const {manifestSchema}=await import('./web_apps/catalog');const file=path.join(tmpDir,'orkas-app.json');
+ const manifest=manifestSchema.parse(fs.existsSync(file)?JSON.parse(await fsp.readFile(file,'utf8')):{sdkVersion:1,capabilities:[]});
+ if(manifest.capabilities.some(capability=>capability!=='data')||(manifest.capabilities.includes('data')&&!manifest.data))throw new Error('app_web_interfaces_required');
+ await fsp.writeFile(file,JSON.stringify({...manifest,minimumClient:'1.9.0'}));
+ }
const meta: SavedAppMeta = {
+ browserStorage: 'isolated-v1',
+ appType,
+ description: await readHtmlDescription(path.join(tmpDir, inspected.entry)),
title,
sourceCid: typeof opts.sourceCid === 'string' ? opts.sourceCid : '',
sourceArtifactId: '',
@@ -490,7 +726,6 @@ export async function saveFromPath(
file_count: copied.fileCount,
total_bytes: copied.totalBytes,
});
- notifySavedAppDirty(appId);
return { ok: true, id: appId, title, rootDir: inspected.rootDir, entry: inspected.entry, ...copied };
} catch (err) {
try { await fsp.rm(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ }
@@ -498,18 +733,23 @@ export async function saveFromPath(
log.warn('saveFromPath failed', {
user_id: maskId(userId),
target: logPathRef(targetPath),
- error: logErrorRef(err),
+ error: logErrorSummary(err),
});
- return { ok: false, error: `failed to save app: ${(err as Error).message}` };
+ return { ok: false, error: failureCode(err, 'app_save_failed') };
}
+ finally { activeStagingDirs.delete(tmpDir); }
}
/** List the user's saved apps, newest save first. */
export function listSavedApps(userId: string): SavedAppListItem[] {
+ const retained = recoverEditedSaves(userId);
+ void recoverInterruptedDeletes(userId);
+ void cleanupEditSnapshots(userId, true);
const root = userSavedAppsDir(userId);
let names: string[];
try { names = fs.readdirSync(root); }
catch { return []; } // pool dir not created yet
+ sweepStagingDirs(root, names, retained);
const items: SavedAppListItem[] = [];
for (const name of names) {
if (name.startsWith('.')) continue;
@@ -523,10 +763,12 @@ export function listSavedApps(userId: string): SavedAppListItem[] {
log.warn('listSavedApps bad meta skipped', {
user_id: maskId(userId),
app_id: maskId(appId),
- error: logErrorRef(err),
+ error: logErrorSummary(err),
});
}
items.push({
+ appType: metadataAppType(meta.appType),
+ description: sanitiseDescription(meta.description),
id: appId,
title: typeof meta.title === 'string' && meta.title.trim() ? meta.title : DEFAULT_TITLE,
savedAt: typeof meta.savedAt === 'string' ? meta.savedAt : '',
@@ -550,6 +792,16 @@ export function listSavedApps(userId: string): SavedAppListItem[] {
return items;
}
+/** Listing never contacts an account or publication service. */
+export async function listResolvedSavedApps(uid: string): Promise<SavedAppListItem[]> {
+ const items = listSavedApps(uid);
+ for (const item of items) {
+ try { item.appType = storedAppType(savedAppDir(uid, item.id)) ?? 'local'; }
+ catch { item.appType = undefined; }
+ }
+ return items;
+}
+
/** Resolve a saved app's entry HTML absolute path (for `shell.openPath`).
* `code` maps to HTTP the same way the artifact resolvers' does. */
export function resolveSavedAppIndex(
@@ -589,7 +841,7 @@ export function resolveSavedAppFilePath(
userId: string,
appId: string,
relPath: string,
-): { ok: true; absPath: string; mime: string; entry: string } | { ok: false; code: ResolveCode; error: string } {
+): { ok: true; absPath: string; mime: string; entry: string; appType: AppType } | { ok: false; code: ResolveCode; error: string } {
let safeId: string;
try { safeId = safeAppId(appId); }
catch (err) { return { ok: false, code: 'bad_input', error: (err as Error).message }; }
@@ -598,8 +850,10 @@ export function resolveSavedAppFilePath(
return { ok: false, code: 'not_found', error: 'not found' };
}
let entry = 'index.html';
+ let appType: AppType = 'local';
try {
const meta = readMeta(root);
+ appType = normalizeAppType(meta.appType);
entry = normaliseEntryRel(meta.entry);
} catch { /* old apps or corrupt meta fall back to index.html */ }
@@ -630,11 +884,12 @@ export function resolveSavedAppFilePath(
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: savedAppMimeFor(rel), entry };
+ return { ok: true, absPath: abs, mime: savedAppMimeFor(rel), entry, appType };
}
/** Rename a saved app (rewrites `__orkas-meta.json`). */
export function renameSavedApp(userId: string, appId: string, title: unknown): Result<{ title: string }> {
+ recoverEditedSaves(userId);
let safeId: string;
try { safeId = safeAppId(appId); }
catch (err) { return { ok: false, error: (err as Error).message }; }
@@ -643,20 +898,28 @@ export function renameSavedApp(userId: string, appId: string, title: unknown): R
if (!isRealSavedAppDirectory(dir)) return { ok: false, error: 'app not found' };
let meta: SavedAppMeta;
try { meta = readMeta(dir) as SavedAppMeta; }
- catch (err) { return { ok: false, error: `app not found: ${(err as Error).message}` }; }
+ catch { return { ok: false, error: 'app not found' }; }
meta.title = sanitiseTitle(title);
try { writeMeta(dir, meta); }
- catch (err) { return { ok: false, error: `failed to rename: ${(err as Error).message}` }; }
+ catch (err) {
+ log.warn('renameSavedApp failed', { user_id: maskId(userId), app_id: maskId(safeId), error: logErrorSummary(err) });
+ return { ok: false, error: 'app_rename_failed' };
+ }
log.info('renameSavedApp completed', { user_id: maskId(userId), app_id: maskId(safeId) });
- notifySavedAppDirty(safeId, META_FILENAME);
return { ok: true, title: meta.title };
}
/** Delete a saved app (`rm -rf saved_apps/<appId>/`). */
-export function deleteSavedApp(userId: string, appId: string): Result {
+export async function deleteSavedApp(userId: string, appId: string): Promise<Result> {
+ recoverEditedSaves(userId);
let safeId: string;
try { safeId = safeAppId(appId); }
catch (err) { return { ok: false, error: (err as Error).message }; }
+ await deleteRecoveries.get(userId);
+ return deleteLocalSavedApp(userId, safeId);
+}
+
+async function deleteLocalSavedApp(userId: string, safeId: string): Promise<Result> {
const dir = savedAppDir(userId, safeId);
let exists = false;
try {
@@ -665,15 +928,122 @@ export function deleteSavedApp(userId: string, appId: string): Result {
if (!st.isDirectory() || st.isSymbolicLink()) return { ok: false, error: 'app not found' };
} catch { /* idempotent missing delete */ }
const deleted = exists ? listAppFilesRel(dir) : [];
+ // The app folder moves aside atomically first and returns if its data cannot
+ // be removed, so a failed delete leaves the app listed and sync untouched.
+ // A durable intent recorded before anything moves lets a stopped delete finish.
+ const staged = exists ? stagingDir(dir) : '', intent = deleteIntentPath(userId, safeId);
+ activeDeleteIntents.add(intent);
try {
- if (exists) fs.rmSync(dir, { recursive: true, force: true });
- } catch (err) {
- log.warn('deleteSavedApp failed', { user_id: maskId(userId), app_id: maskId(safeId), error: logErrorRef(err) });
- return { ok: false, error: `failed to delete: ${(err as Error).message}` };
- }
- log.info('deleteSavedApp completed', { user_id: maskId(userId), app_id: maskId(safeId) });
- for (const rel of deleted) notifySavedAppDeleted(safeId, rel);
- return { ok: true };
+ let release:(()=>void)|undefined,key='',cloudFiles:string[]=[];
+ try {
+ key=appDataKey(safeId);
+ const runtime=await import('./web_apps/runtime');release=runtime.holdAppData(userId,key);
+ await runtime.closeAppData(userId,key);
+ cloudFiles=listAppDataCloudFiles(userId,key);
+ writeDeleteIntent(userId,{version:1,appId:safeId,files:deleted,cloudFiles});
+ if (exists) renameWithRetrySync(dir, staged);
+ try { await removeAppData(userId,key); }
+ catch (err) { if (exists) renameWithRetrySync(staged, dir); throw err; }
+ } catch (err) {
+ log.warn('deleteSavedApp failed', { user_id: maskId(userId), app_id: maskId(safeId), error: logErrorSummary(err) });
+ // A restored (or never moved) app voids the intent; a missing one keeps it for recovery.
+ if (!exists || isRealSavedAppDirectory(dir)) clearDeleteIntent(intent);
+ activeStagingDirs.delete(staged);
+ release?.();
+ return { ok: false, error: 'app_delete_failed' };
+ }
+ release?.();
+ // Committed: the app and its data are gone. Cleanup or sync notification
+ // failures cannot turn this into a failed delete; leftovers are swept later.
+ if (staged) {
+ try { await fsp.rm(staged, { recursive: true, force: true }); }
+ catch (err) { log.warn('deleteSavedApp staging cleanup deferred', { error: logErrorSummary(err) }); }
+ finally { activeStagingDirs.delete(staged); }
+ }
+ log.info('deleteSavedApp completed', { user_id: maskId(userId), app_id: maskId(safeId) });
+ clearDeleteIntent(intent);
+ return { ok: true };
+ } finally { activeDeleteIntents.delete(intent); }
+}
+
+const appDataKey = (appId: string) => crypto.createHash('sha256').update(JSON.stringify(['saved', appId])).digest('hex');
+function listAppDataCloudFiles(uid: string, key: string): string[] {
+ const local=webAppSandboxRoot(uid,key,'local'),cloud=webAppSandboxRoot(uid,key,'cloud');
+ for(const root of [local,cloud])if(fs.existsSync(root)&&fs.lstatSync(root).isSymbolicLink())throw new Error('app data unavailable');
+ return fs.existsSync(cloud)?listAppFilesRel(cloud):[];
+}
+async function removeAppData(uid: string, key: string): Promise<void> {
+ await fsp.rm(webAppSandboxRoot(uid,key,'local'),{recursive:true,force:true});
+ await fsp.rm(webAppSandboxRoot(uid,key,'cloud'),{recursive:true,force:true});
+}
+
+// ── Interrupted delete recovery ──────────────────────────────────────────
+// Only a recorded intent proves the user deleted an app. Data without a local
+// app folder may belong to an app still arriving through personal sync, so it
+// is never removed on its own. Intents live in the machine-private domain.
+interface DeleteIntent { version: 1; appId: string; files: string[]; cloudFiles: string[] }
+const activeDeleteIntents = new Set<string>();
+const deleteRecoveries = new Map<string, Promise<void>>();
+const DELETE_INTENT_RE = /^([A-Za-z0-9_-]{1,64})\.json$/;
+const deleteIntentPath = (uid: string, appId: string) => path.join(userAppDeletesDir(uid), `${appId}.json`);
+function writeDeleteIntent(uid: string, intent: DeleteIntent): void {
+ const file = deleteIntentPath(uid, intent.appId);
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
+ // A torn write is harmless: it can only precede the app-folder move, and a
+ // present app folder voids the intent without reading it.
+ const fd = fs.openSync(file, 'w', 0o600);
+ try { fs.writeFileSync(fd, JSON.stringify(intent)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+}
+function clearDeleteIntent(file: string): void {
+ try { fs.rmSync(file, { force: true }); }
+ catch (err) { log.warn('saved app delete intent cleanup deferred', { error: logErrorSummary(err) }); }
+}
+function isIntentRel(rel: unknown): rel is string {
+ return typeof rel === 'string' && rel.length > 0 && rel.length <= 1024 && !/[\\\0]/.test(rel)
+ && rel.split('/').every(seg => !!seg && seg !== '.' && seg !== '..');
+}
+function readDeleteIntent(file: string, appId: string): DeleteIntent {
+ if (!fs.lstatSync(file).isFile()) throw new Error('invalid delete intent');
+ const intent = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (intent?.version !== 1 || intent.appId !== appId || !Array.isArray(intent.files) || !Array.isArray(intent.cloudFiles)
+ || !intent.files.every(isIntentRel) || !intent.cloudFiles.every(isIntentRel)) throw new Error('invalid delete intent');
+ return intent;
+}
+function recoverInterruptedDeletes(uid: string): Promise<void> {
+ const running = deleteRecoveries.get(uid);
+ if (running) return running;
+ let appIds: string[];
+ try { appIds = fs.readdirSync(userAppDeletesDir(uid)).map(name => DELETE_INTENT_RE.exec(name)?.[1]).filter((id): id is string => !!id); }
+ catch { return Promise.resolve(); } // no intents recorded
+ if (!appIds.length) return Promise.resolve();
+ const work = (async () => { for (const appId of appIds) await recoverDelete(uid, appId); })()
+ .finally(() => deleteRecoveries.delete(uid));
+ deleteRecoveries.set(uid, work);
+ return work;
+}
+async function recoverDelete(uid: string, appId: string): Promise<void> {
+ const file = deleteIntentPath(uid, appId);
+ if (activeDeleteIntents.has(file)) return;
+ try {
+ // A present app folder means the delete never committed or was rolled back.
+ if (fs.existsSync(savedAppDir(uid, appId)) || isSymlink(savedAppDir(uid, appId))) {
+ clearDeleteIntent(file);
+ log.info('saved app delete intent voided', { app_id: maskId(appId) });
+ return;
+ }
+ // Tombstones go to the active account's personal sync; another account waits for its own session.
+ const users = await import('./users');
+ if (users.getActiveUserId() !== uid) return;
+ const intent = readDeleteIntent(file, appId), key = appDataKey(appId);
+ const runtime = await import('./web_apps/runtime'), release = runtime.holdAppData(uid, key);
+ try { await runtime.closeAppData(uid, key); listAppDataCloudFiles(uid, key); await removeAppData(uid, key); }
+ finally { release(); }
+ clearDeleteIntent(file);
+ log.info('saved app delete recovery completed', { app_id: maskId(appId), files: intent.files.length, data_files: intent.cloudFiles.length });
+ } catch (error) { log.warn('saved app delete recovery deferred', { app_id: maskId(appId), error: logErrorSummary(error) }); }
+}
+function isSymlink(target: string): boolean {
+ try { return fs.lstatSync(target).isSymbolicLink(); } catch { return false; }
}
// ── "Edit in a new conversation" ─────────────────────────────────────────
@@ -696,6 +1066,180 @@ function listAppFilesRel(dir: string): string[] {
return out;
}
+interface EditContext { appType?: AppType; version: 1; appId: string; title: string; fingerprint: string }
+
+function refreshEditSnapshot(uid: string,cid: string,context: EditContext,source: string) {
+ const root=editContextDir(uid,cid),snapshot=path.join(root,'snapshot'),next=path.join(root,'snapshot-next'),previous=path.join(root,'snapshot-previous');
+ fs.rmSync(next,{recursive:true,force:true});fs.cpSync(source,next,{recursive:true,dereference:false});
+ fs.rmSync(previous,{recursive:true,force:true});
+ if(fs.existsSync(snapshot))fs.renameSync(snapshot,previous);
+ try {fs.renameSync(next,snapshot);} catch(error) {if(fs.existsSync(previous))fs.renameSync(previous,snapshot);throw error;}
+ context.fingerprint=fingerprintApp(source);
+ fs.writeFileSync(path.join(root,'context.json'),JSON.stringify(context));
+ fs.rmSync(previous,{recursive:true,force:true});
+}
+
+function recoverEditedSaves(uid: string) {
+ const retained = new Set<string>();
+ const edits=userAppEditsDir(uid);
+ if(!fs.existsSync(edits))return retained;
+ for(const cid of fs.readdirSync(edits)) {
+ if(!/^[A-Za-z0-9_-]{1,128}$/.test(cid))continue;
+ const root=editContextDir(uid,cid),journalPath=path.join(root,'save-journal.json');
+ if(!fs.existsSync(journalPath)||fs.lstatSync(root).isSymbolicLink()||fs.lstatSync(journalPath).isSymbolicLink())continue;
+ try {
+ const journal=JSON.parse(fs.readFileSync(journalPath,'utf8'));
+ const appId=safeAppId(journal.appId);
+ if(journal.version!==1||!new RegExp('^'+appId+'\\.tmp-[a-f0-9]{8}$').test(journal.temporary)
+ || !/^[a-f0-9]{64}$/.test(journal.before)||!/^[a-f0-9]{64}$/.test(journal.after))throw new Error('invalid edit save journal');
+ const destination=savedAppDir(uid,appId),temporary=path.join(userSavedAppsDir(uid),journal.temporary),backup=temporary+'.previous';
+ const existingContext = readEditContext(uid, cid);
+ if (existingContext?.appType === 'web' || [destination, temporary, backup, path.join(root, 'snapshot')]
+ .some(dir => isRealSavedAppDirectory(dir) && storedAppType(dir) === 'web')) {
+ retained.add(temporary); retained.add(backup); continue;
+ }
+ if(journal.dataCandidate){
+ if(!/^data\.sqlite\.backup-[a-f0-9]{16}$/.test(journal.dataCandidate))throw new Error('invalid data save journal');
+ const {file}=localDatabase(uid,appId),candidate=path.join(path.dirname(file),journal.dataCandidate);
+ if(fs.existsSync(candidate)){
+ if(isRealSavedAppDirectory(backup)){if(fs.existsSync(destination))fs.rmSync(destination,{recursive:true,force:true});fs.renameSync(backup,destination);}
+ if(fs.existsSync(file+'.previous')){fs.rmSync(file,{force:true});fs.renameSync(file+'.previous',file);}
+ for(const suffix of ['', '-wal','-shm'])fs.rmSync(candidate+suffix,{force:true});
+ }else if(fs.existsSync(file+'.previous'))fs.rmSync(file+'.previous',{force:true});
+ }
+ if(!fs.existsSync(destination)&&isRealSavedAppDirectory(backup)&&fingerprintApp(backup)===journal.before)fs.renameSync(backup,destination);
+ if(isRealSavedAppDirectory(destination)&&fingerprintApp(destination)===journal.after){
+ const context=readEditContext(uid,cid);if(context&&context.appId===appId)refreshEditSnapshot(uid,cid,context,destination);
+ }
+ fs.rmSync(temporary,{recursive:true,force:true});fs.rmSync(backup,{recursive:true,force:true});fs.rmSync(journalPath,{force:true});
+ log.info('edited app save recovery completed');
+ } catch(error) {log.warn('edited app save recovery deferred',{error:logErrorSummary(error)});}
+ }
+ return retained;
+}
+const editCleanupRunning = new Map<string, Promise<void>>();
+const editCleanupLast = new Map<string, number>();
+
+/** Snapshot ownership follows the edit conversation, including recycle recovery. */
+export function cleanupEditSnapshots(uid: string, background = false, cid?: string): Promise<void> {
+ const running = editCleanupRunning.get(uid);
+ if (running) return background ? running : running.then(() => cleanupEditSnapshots(uid, false, cid));
+ if (background && Date.now() - (editCleanupLast.get(uid) || 0) < 60_000) return Promise.resolve();
+ editCleanupLast.set(uid, Date.now());
+ const run = (async () => {
+ const root = userAppEditsDir(uid);
+ try {
+ if ((await fsp.lstat(root)).isSymbolicLink()) throw new Error('unsafe edit root');
+ // Capture candidates before ownership so a concurrently created edit is never swept.
+ const candidates = (await fsp.readdir(root, { withFileTypes: true })).filter(entry => !cid || entry.name === cid);
+ if (!candidates.length) return;
+ const recycle = await import('./recycle_bin');
+ await recycle.withEditSnapshotRetention(uid, async () => {
+ const retained = await chats.retainedConversationIdsForEditCleanup(uid);
+ for (const cid of await recycle.retainedEditConversationIds(uid)) retained.add(cid);
+ for (const entry of candidates) {
+ if (!entry.isDirectory() || !/^[A-Za-z0-9_-]{1,128}$/.test(entry.name) || retained.has(entry.name)) continue;
+ const dir = editContextDir(uid, entry.name);
+ if (readEditContext(uid, entry.name)?.appType === 'web'
+ || storedAppType(path.join(dir, 'snapshot')) === 'web') continue;
+ const activeKey = JSON.stringify([uid, entry.name]);
+ if (activeEditSaves.has(activeKey)) { deferredEditCleanup.add(activeKey); continue; }
+ try { await fsp.lstat(path.join(dir, 'save-journal.json')); continue; }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ await fsp.rm(dir, { recursive: true, force: true });
+ }
+ });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') log.warn('edit snapshot cleanup deferred', { error: logErrorSummary(error) });
+ }
+ })().finally(() => { editCleanupRunning.delete(uid); });
+ editCleanupRunning.set(uid, run);
+ return run;
+}
+
+function editContextDir(userId: string, cid: string): string {
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(cid)) throw new Error('invalid cid');
+ return path.join(userAppEditsDir(userId), cid);
+}
+function fingerprintApp(dir: string): string {
+ const digest = crypto.createHash('sha256');
+ for (const rel of listAppFilesRel(dir)) {
+ const target = path.join(dir, rel);
+ if (!isPathAllowed(target, [dir])) throw new Error('app_edit_snapshot_invalid');
+ digest.update(JSON.stringify(rel)).update('\0').update(fs.readFileSync(target)).update('\0');
+ }
+ return digest.digest('hex');
+}
+function readEditContext(userId: string, cid: string): EditContext | null {
+ try {
+ const data = JSON.parse(fs.readFileSync(path.join(editContextDir(userId, cid), 'context.json'), 'utf8'));
+ if (data.version !== 1 || !/^[a-f0-9]{64}$/.test(data.fingerprint)) return null;
+ safeAppId(data.appId);
+ if (Object.hasOwn(data, 'appType') && !metadataAppType(data.appType)) return null;
+ return {...data, appType: metadataAppType(data.appType)};
+ } catch { return null; }
+}
+export async function getEditTarget(userId: string, cid: string): Promise<{ appId: string; title: string; appType: AppType } | null> {
+ const context = readEditContext(userId, cid);
+ if (!context && fs.existsSync(editContextDir(userId, cid))) throw Object.assign(new Error(t('web_apps.error_E_CLOSED')), { code: 'app_edit_context_unavailable' });
+ if (!context) return null;
+ const dir = savedAppDir(userId, context.appId);
+ const persisted = isRealSavedAppDirectory(dir) ? storedAppType(dir) : undefined;
+ const appType = context.appType === 'web' || persisted === 'web' ? 'web' : context.appType ?? persisted ?? 'local';
+ return { appId: context.appId, title: context.title, appType };
+}
+
+/** Read the structured task/edit binding without any publication lookup. */
+export async function boundAppType(userId: string, cid: string): Promise<AppType | undefined> {
+ const target = await getEditTarget(userId, cid); if (target) return target.appType;
+ const conversation = await chats.getConversationMetadata(userId, cid);
+ // The sidebar's normalizing reader is deliberately tolerant. Its recovery
+ // record cannot grant a local capability when that binding is unreadable.
+ const file = conversationLayout(userId, cid, conversation?.project_id).metaFile;
+ let stat: fs.Stats | undefined;
+ try { stat = fs.lstatSync(file); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ if (stat) {
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024) throw new Error('Application task binding unavailable');
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Application task binding unavailable');
+ if (raw.assistance?.kind === 'app_creation') {
+ const value = raw.assistance.appType;
+ const stored = metadataAppType(value);
+ if (value !== undefined && !stored) throw new Error('Application task binding unavailable');
+ if (stored === 'web') return 'web';
+ }
+ }
+ const assistance = conversation?.assistance;
+ return assistance?.kind === 'app_creation' ? assistance.appType ?? 'local' : undefined;
+}
+
+/** The one fallback order for an artifact on every surface (label, runtime,
+ * save, share): stored metadata, then the structured task binding, then
+ * local. A damaged binding throws so each caller can fail closed. */
+export async function resolveArtifactAppType(userId:string,cid:string,artifactId:string,meta=chatArtifacts.readArtifactMeta(userId,cid,artifactId)):Promise<AppType>{
+ const resolved = chatArtifacts.resolveArtifactDir(userId, cid, artifactId);
+ if (!resolved.ok) throw new Error('artifact not found');
+ const bound = await boundAppType(userId, cid);
+ if (bound === 'web') return bound;
+ return storedAppType(resolved.dirPath) ?? bound ?? 'local';
+}
+
+/** Resolve only canonical managed pools; HTML content and manifest capabilities
+ * never decide whether an app is commercial. No directory inventory is needed. */
+export async function managedPathAppType(userId: string, file: string): Promise<AppType | undefined> {
+ const relative = path.relative(userCloudRoot(userId), path.resolve(file));
+ if (path.isAbsolute(relative) || relative.split(path.sep).includes('..')) return undefined;
+ const segments = relative.split(path.sep);
+ if (segments[0] === 'saved_apps' && segments[1]) return resolveSavedAppType(userId, segments[1]);
+ const start = segments[0] === 'chat_artifacts' ? 1
+ : segments[0] === 'projects' && segments[2] === 'chat_artifacts' ? 3 : -1;
+ if (start < 0 || !segments[start] || !segments[start + 1]) return undefined;
+ const resolved = chatArtifacts.resolveArtifactDir(userId, segments[start], segments[start + 1]);
+ if (!resolved.ok || !isPathAllowed(file, [resolved.dirPath])) throw new Error('Invalid app source');
+ return resolveArtifactAppType(userId, segments[start], segments[start + 1]);
+}
+
/** 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
@@ -732,6 +1276,27 @@ function buildSourceBundle(dir: string, title: string): string {
return lines.join('\n');
}
+/** Best-effort removal of a half-built edit conversation; failures are logged
+ * redacted so the caller still reports the original edit failure. */
+async function rollbackEditConversation(
+ userId: string,
+ appId: string,
+ editingDir: string,
+ conv: { conversation_id: string; project_id?: string | null },
+): Promise<void> {
+ try { await fsp.rm(editingDir, { recursive: true, force: true }); }
+ catch (err) { log.warn('openForEditing rollback context cleanup failed', { error: logErrorSummary(err) }); }
+ try { await chats.deleteConversation(userId, conv.conversation_id, conv.project_id || null); }
+ catch (err) {
+ log.warn('openForEditing rollback deleteConversation failed', {
+ user_id: maskId(userId),
+ app_id: maskId(appId),
+ conversation_id: maskId(conv.conversation_id),
+ error: logErrorSummary(err),
+ });
+ }
+}
+
/**
* 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
@@ -751,14 +1316,21 @@ export async function openForEditing(
const dir = savedAppDir(userId, safeId);
if (!isRealSavedAppDirectory(dir)) return { ok: false, error: 'app not found' };
let title = DEFAULT_TITLE;
+ let appType: AppType = 'local';
try {
const m = readMeta(dir);
if (m && typeof m.title === 'string' && m.title.trim()) title = m.title;
} catch { /* fallback */ }
+ try { appType = await resolveSavedAppType(userId, safeId); }
+ catch (error) {
+ log.warn('saved app type recovery unavailable', { error: logErrorSummary(error) });
+ return { ok: false, error: t('web_apps.error_E_FAILED') };
+ }
+ if (appType === 'web') return commercialWebAppFailure();
const resolvedEntry = resolveSavedAppIndex(userId, safeId);
if (!resolvedEntry.ok) return { ok: false, error: 'app is missing its HTML entry' };
- const bundle = buildSourceBundle(dir, title);
+ const originalFingerprint = fingerprintApp(dir);
let conv: Awaited<ReturnType<typeof chats.createConversation>>;
try {
@@ -770,23 +1342,31 @@ export async function openForEditing(
log.warn('openForEditing createConversation failed', {
user_id: maskId(userId),
app_id: maskId(safeId),
- error: logErrorRef(err),
+ error: logErrorSummary(err),
});
- return { ok: false, error: `failed to create a conversation: ${(err as Error).message}` };
+ return { ok: false, error: 'app_edit_open_failed' };
}
+ const editingDir = editContextDir(userId, conv.conversation_id);
+ let bundle: string;
+ try {
+ const snapshot = path.join(editingDir, 'snapshot');
+ await fsp.cp(dir, snapshot, { recursive: true, dereference: false });
+ if (fingerprintApp(snapshot) !== originalFingerprint || fingerprintApp(dir) !== originalFingerprint) {
+ throw new Error('app_edit_conflict');
+ }
+ const context: EditContext = { version: 1, appId: safeId, title, appType, fingerprint: originalFingerprint };
+ await fsp.writeFile(path.join(editingDir, 'context.json'), JSON.stringify(context));
+ bundle = buildSourceBundle(snapshot, title);
+ } catch (err) {
+ log.warn('openForEditing snapshot failed', { error: logErrorSummary(err) });
+ await rollbackEditConversation(userId, safeId, editingDir, conv);
+ return { ok: false, error: 'app_edit_snapshot_failed' };
+ }
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, conv.project_id || null); }
- catch (err) {
- log.warn('openForEditing rollback deleteConversation failed', {
- user_id: maskId(userId),
- app_id: maskId(safeId),
- conversation_id: maskId(conv.conversation_id),
- error: logErrorRef(err),
- });
- }
+ await rollbackEditConversation(userId, safeId, editingDir, conv);
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;
diff --git a/src/main/features/web_apps/catalog.ts b/src/main/features/web_apps/catalog.ts
index 941fb69b..1cafecae 100644
--- a/src/main/features/web_apps/catalog.ts
+++ b/src/main/features/web_apps/catalog.ts
@@ -1,4 +1,5 @@
/** Web-only API contract. This is not a second model-visible Tool catalog. */
+import { DATA_INPUTS, dataDefinitionSchema, commonMethod, type AppType } from './data-contract';
import { isAtomicWriteTempPath } from '../../storage';
import { z } from 'zod';
import { MAX_TEXT_FILE_BYTES } from '../../util/file-size-limits';
@@ -20,8 +21,13 @@ const text = z.string().max(MAX_TEXT_FILE_BYTES);
const define = (capability: string | null, description: string, input: z.ZodTypeAny, result: string, example: object) =>
({ capability, description, input, result, example });
export const METHODS = {
+ 'data.query':define('data','Read declared fields under readFilters; default limit 20, maximum 100, offset maximum 100000. Ordering adds id as a stable tie-breaker; include reads at most four declared one-hop relations.',DATA_INPUTS['data.query'],'{records:object[]}; include adds relations keyed by reference field.',{table:'messages',fields:['body'],limit:20}),
+ 'data.count':define('data','Count records under declared readFilters and caller filters; requires count permission.',DATA_INPUTS['data.count'],'{count:number}',{table:'messages'}),
+ 'data.insert':define('data','Insert declared fields, apply defaults and meter canonical UTF-8 bytes atomically. requestId deduplicates the latest 2048 insert requests across reopening.',DATA_INPUTS['data.insert'],'{id:string}; generated record ID, never the private row.',{table:'messages',values:{body:'Hello'},requestId:'message-1'}),
+ 'data.insertIf':define('data','Atomically check whole-table count and insert. maxCount can only tighten the application declaration; full capacity returns E_CONDITION.',DATA_INPUTS['data.insertIf'],'{id:string}; no partial insertion on failure.',{table:'messages',values:{body:'Hello'},maxCount:100,requestId:'message-2'}),
+ 'data.aggregate':define('data','Compute a declared aggregate under readFilters and caller filters; groupBy requires read permission. Up to 100 groups; larger results fail with E_LIMIT.',DATA_INPUTS['data.aggregate'],'{value:number|string|null} or {groups:[{key,value}]} when groupBy is supplied.',{table:'messages',field:'score',op:'sum'}),
'capabilities.list': define(null, 'Discover supported methods, current availability and authorization requirements.', empty, '{sdkVersion, methods, unsupported}', {}),
- 'capabilities.describe': define(null, 'Read one method schema, result contract and example.', z.object({ method: key }).strict(), 'Method documentation.', { method: 'ai.generate' }),
+ 'capabilities.describe': define(null, 'Read one method schema, result contract and example.', z.object({ method: key }).strict(), 'Method documentation.', { method: 'data.query' }),
'host.getContext': define(null, 'Read the current application language and SDK version.', empty, '{language, sdkVersion}', {}),
'permissions.revoke': define(null, 'Revoke this instance grants and cancel pending work. Reopening starts fresh.', empty, '{revoked:true}', {}),
'storage.get': define('storage', 'Read app-private JSON; scope defaults to local for compatibility. cloud participates in account sync.', z.object({ key, scope }).strict(), '{value}; null when missing.', { key: 'draft' }),
@@ -44,10 +50,12 @@ export const METHODS = {
'tools.call': define(null, 'Execute an eligible existing tool under its original operation permissions. Sensitive actions use host approval; Trusted mode skips confirmation. Unknown tools fail closed.', z.object({ name: key, arguments: z.record(z.unknown()) }).strict(), '{content,isError?}; inspect isError. Oversized results fail without replay.', { name: 'library', arguments: { action: 'list', scope: 'global', limit: 10 } }),
} as const;
export type Method = keyof typeof METHODS;
-export const CAPABILITIES = ['storage', 'appFiles', 'files', 'ai', 'library', 'connectors'] as const;
-export const manifestSchema = z.object({ sdkVersion: z.literal(SDK_VERSION), capabilities: z.array(z.enum(CAPABILITIES)).max(CAPABILITIES.length) }).strict();
+export const CAPABILITIES = ['storage', 'appFiles', 'files', 'ai', 'library', 'connectors', 'data'] as const;
+export const manifestSchema = z.object({ sdkVersion: z.literal(SDK_VERSION), minimumClient:z.literal('1.9.0').optional(), capabilities: z.array(z.enum(CAPABILITIES)).max(CAPABILITIES.length), data: dataDefinitionSchema.optional() }).strict();
export type AppManifest = z.infer<typeof manifestSchema>;
export const UNSUPPORTED = [
+ { capability: 'account.renewalReminders', reason: 'Host-only: account-wide reminder claims and billing navigation belong to the signed-in desktop account UI, not saved applications.' },
+ { capability: 'browser', reason: 'Host-only: task browser control, native file selection and site consent require a live conversation and its user-owned Chromium profile.' },
{ capability: 'files.writeInPlace', reason: 'Deferred: needs shared revision/lock/indexer integration; export through files.saveAs.' },
{ capability: 'projects', reason: 'Deferred: apps have no user-selected project binding; source conversation is not authority.' },
{ capability: 'memory', reason: 'Deferred: needs a user-selected scope; Agent-private and global memories are not app state.' },
@@ -61,8 +69,23 @@ export function describeMethod(method: string) {
if (!Object.hasOwn(METHODS, method)) return null;
const def = METHODS[method as Method];
return { name: method, capability: def.capability, description: def.description,
+ appTypes:commonMethod(method)?['local','web']:['local'],environments:commonMethod(method)?['desktop','preview','online']:['desktop','preview'],status:'supported',
inputSchema: zodToJsonSchema(def.input, { $refStrategy: 'none' }), result: def.result, example: def.example };
}
-export function catalogDocument() {
- return { sdkVersion: SDK_VERSION, methods: Object.keys(METHODS).map(name => describeMethod(name)), unsupported: UNSUPPORTED };
+export function catalogDocument(appType:AppType='local') {
+ const starter = appType === 'web' ? 'web' : 'starter';
+ // Web creators and runtimes already reject host capabilities; retain the
+ // shared array bound while documenting their data-only declaration.
+ const schema = appType === 'web'
+ ? manifestSchema.extend({ capabilities: z.array(z.enum(['data'])).max(CAPABILITIES.length) })
+ : manifestSchema;
+ return { sdkVersion: SDK_VERSION,
+ manifest: { file: MANIFEST_FILE, schema: {
+ ...zodToJsonSchema(schema, { $refStrategy: 'none' }),
+ // Both creators and runtimes require a definition for declared data.
+ allOf: [{ if: { properties: { capabilities: { contains: { const: 'data' } } }, required: ['capabilities'] }, then: { required: ['data'] } }],
+ },
+ starter: { entry: `@skill/web-app-sdk/assets/${starter}/index.html`,
+ manifest: `@skill/web-app-sdk/assets/${starter}/${MANIFEST_FILE}` } },
+ dataDefinition:zodToJsonSchema(dataDefinitionSchema,{$refStrategy:'none'}), methods: Object.keys(METHODS).filter(name=>appType==='local'||commonMethod(name)).map(name => describeMethod(name)), unsupported: UNSUPPORTED };
}
diff --git a/src/main/features/web_apps/commercial-entry.ts b/src/main/features/web_apps/commercial-entry.ts
new file mode 100644
index 00000000..0d505be8
--- /dev/null
+++ b/src/main/features/web_apps/commercial-entry.ts
@@ -0,0 +1,29 @@
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { metadataAppType, type AppType } from './data-contract';
+
+const message = 'Web apps require the commercial version of Orkas.';
+export function commercialWebAppFailure() {
+ return { ok: false as const, code: 'E_COMMERCIAL_REQUIRED' as const, feature: 'web_apps' as const, message, error: message };
+}
+export function isCommercialWebAppFailure(value: unknown): boolean {
+ const receipt = value as { code?: unknown; feature?: unknown } | null;
+ return receipt?.code === 'E_COMMERCIAL_REQUIRED' && receipt?.feature === 'web_apps';
+}
+export function requireLocalAppType(value: unknown): void {
+ if (metadataAppType(value) === 'web') throw Object.assign(new Error(message), commercialWebAppFailure());
+}
+/** Missing metadata remains compatible with legacy local HTML. Damaged or
+ * explicitly invalid authority must never become a local capability grant. */
+export function storedAppType(dir: string): AppType | undefined {
+ const file = path.join(dir, '__orkas-meta.json');
+ let stat: fs.Stats;
+ try { stat = fs.lstatSync(file); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; throw error; }
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024) throw new Error('Invalid app metadata');
+ const metadata = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) throw new Error('Invalid app metadata');
+ const type = metadataAppType(metadata.appType);
+ if (Object.hasOwn(metadata, 'appType') && !type) throw new Error('Invalid app metadata');
+ return type;
+}
diff --git a/src/main/features/web_apps/data-contract.ts b/src/main/features/web_apps/data-contract.ts
new file mode 100644
index 00000000..b024078c
--- /dev/null
+++ b/src/main/features/web_apps/data-contract.ts
@@ -0,0 +1,48 @@
+/** Versioned common data contract, independent of host permissions. */
+import { z } from 'zod';
+export const appTypeSchema = z.enum(['local','web']);
+export type AppType = z.infer<typeof appTypeSchema>;
+/** Recognize a persisted type without mistaking missing authority for local. */
+export function metadataAppType(value: unknown): AppType | undefined {
+ return value === 'local' ? 'local' : value === 'web' || value === 'cloud' ? 'web' : undefined;
+}
+/** Legacy persisted bundles retain their restricted web capabilities on read. */
+export function normalizeAppType(value: unknown): AppType {
+ return value === 'web' || value === 'cloud' ? 'web' : 'local';
+}
+const name = z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,63}$/);
+const filter = z.object({field:name,op:z.enum(['eq','ne','lt','lte','gt','gte']),value:z.union([z.string(),z.number().finite().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER),z.boolean(),z.null()])}).strict();
+function jsonValue(v:unknown,depth=0):boolean{
+ if(depth>32)return false;if(v===null||typeof v==='boolean')return true;if(typeof v==='number')return Number.isFinite(v)&&Math.abs(v)<=Number.MAX_SAFE_INTEGER;if(typeof v==='string')return Buffer.from(v).toString('utf8')===v;
+ if(Array.isArray(v))return v.every(x=>jsonValue(x,depth+1));return !!v&&Object.getPrototypeOf(v)===Object.prototype&&Object.entries(v).every(([k,x])=>jsonValue(k,depth+1)&&jsonValue(x,depth+1));
+}
+function defaultValue(f:any):boolean{
+ const v=f.default;if(v===null)return !!f.nullable;
+ if(f.type==='timestamp'){if(typeof v!=='string'||v.startsWith('0000-')||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(v))return false;const d=new Date(v);return Number.isFinite(d.valueOf())&&d.toISOString()===(v.length===20?v.replace('Z','.000Z'):v);}
+ return ({string:typeof v==='string',number:typeof v==='number',integer:Number.isSafeInteger(v),boolean:typeof v==='boolean',json:!!v&&typeof v==='object'} as any)[f.type]&&jsonValue(v);
+}
+const field = z.object({id:name,name,type:z.enum(['string','number','integer','boolean','json','timestamp']),required:z.boolean().optional(),nullable:z.boolean().optional(),unique:z.boolean().optional(),default:z.unknown().optional(),references:z.object({table:name}).strict().optional()}).strict();
+export const dataDefinitionSchema = z.object({version:z.literal(1),tables:z.array(z.object({id:name,name,fields:z.array(field).max(128),access:z.object({read:z.array(name).default([]),insert:z.array(name).default([]),count:z.boolean().optional(),maxCount:z.number().int().min(1).max(1000000).optional(),aggregate:z.array(name).optional(),readFilters:z.array(filter).max(16).optional()}).strict(),indexes:z.array(z.array(name).min(1).max(4)).max(16).optional()}).strict()).max(32)}).strict().superRefine((value,ctx)=>{
+ if(!jsonValue(value)||Buffer.byteLength(JSON.stringify(value))>65536)ctx.addIssue({code:'custom',message:'Invalid or oversized definition'});
+ const ids=new Set<string>(),names=new Set<string>();
+ for(const t of value.tables){
+ if(ids.has(t.id)||names.has(t.name))ctx.addIssue({code:'custom',message:'Duplicate table identity'});
+ ids.add(t.id);names.add(t.name);
+ const fieldIds=new Set<string>(),fieldNames=new Set(['id','createdAt']);
+ for(const f of t.fields){if(Object.hasOwn(f,'default')&&!defaultValue(f))ctx.addIssue({code:'custom',message:'Default does not match field type'});if(fieldIds.has(f.id)||fieldNames.has(f.name)||f.name==='relations')ctx.addIssue({code:'custom',message:'Duplicate field identity'});fieldIds.add(f.id);fieldNames.add(f.name);}
+ for(const f of t.fields)if(f.references&&(f.type!=='string'||!value.tables.some(table=>table.id===f.references.table)))ctx.addIssue({code:'custom',message:'Invalid relation'});
+ for(const group of [t.access.read,t.access.insert,t.access.aggregate??[],...(t.indexes??[])])if(new Set(group).size!==group.length||group.some(f=>!fieldNames.has(f)))ctx.addIssue({code:'custom',message:'Unknown or duplicate access field'});
+ if(t.access.insert.some(f=>f==='id'||f==='createdAt')||(t.access.readFilters??[]).some(f=>!fieldNames.has(f.field)))ctx.addIssue({code:'custom',message:'Invalid access scope'});
+ }
+});
+export type DataDefinition=z.infer<typeof dataDefinitionSchema>;
+const query=z.object({table:name,fields:z.array(name).max(130).optional(),include:z.array(name).max(4).optional(),filters:z.array(filter).max(16).optional(),limit:z.number().int().min(1).max(100).optional(),offset:z.number().int().min(0).max(100000).optional(),order:z.object({field:name,direction:z.enum(['asc','desc'])}).strict().optional()}).strict();
+const insert=z.object({table:name,values:z.record(z.unknown()),requestId:z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional()}).strict();
+export const DATA_INPUTS={
+ 'data.query':query,
+ 'data.count':z.object({table:name,filters:z.array(filter).max(16).optional()}).strict(),
+ 'data.insert':insert,
+ 'data.insertIf':insert.extend({maxCount:z.number().int().min(1).max(1000000)}).strict(),
+ 'data.aggregate':z.object({table:name,field:name,op:z.enum(['count','sum','min','max','avg']),groupBy:name.optional(),filters:z.array(filter).max(16).optional()}).strict(),
+};
+export function commonMethod(method:string){return Object.hasOwn(DATA_INPUTS,method)||['capabilities.list','capabilities.describe','host.getContext'].includes(method);}
diff --git a/src/main/features/web_apps/data-worker.js b/src/main/features/web_apps/data-worker.js
new file mode 100644
index 00000000..66c671e8
--- /dev/null
+++ b/src/main/features/web_apps/data-worker.js
@@ -0,0 +1,161 @@
+/* SQLite executes only in this application-owned worker, never the UI thread. */
+'use strict';
+const {parentPort,workerData}=require('node:worker_threads');
+const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
+const Database=require('better-sqlite3');
+const fail=code=>{throw Object.assign(new Error(code),{code});};
+function canonical(v,depth=0){
+ if(depth>32)fail('E_LIMIT');
+ if(typeof v==='number'&&(!Number.isFinite(v)||Math.abs(v)>Number.MAX_SAFE_INTEGER))fail('E_INPUT');
+ if(typeof v==='string'&&Buffer.from(v).toString('utf8')!==v)fail('E_INPUT');
+ if(v===null||typeof v==='string'||typeof v==='boolean'||typeof v==='number')return JSON.stringify(v);
+ if(Array.isArray(v))return '['+v.map(x=>canonical(x,depth+1)).join(',')+']';
+ if(v&&Object.getPrototypeOf(v)===Object.prototype)return '{'+Object.keys(v).sort().map(k=>canonical(k,depth+1)+':'+canonical(v[k],depth+1)).join(',')+'}';
+ fail('E_INPUT');
+}
+const size=v=>Buffer.byteLength(canonical(v));
+const physical=(prefix,id)=>prefix+crypto.createHash('sha256').update(id).digest('hex').slice(0,24);
+const quote=n=>'"'+n+'"';
+const operations={eq:'=',ne:'!=',lt:'<',lte:'<=',gt:'>',gte:'>='};
+const definition=workerData.definition;
+let storedDefinition=definition;
+const tables=new Map(definition.tables.map(t=>[t.name,t]));
+const file=workerData.file;
+// A rejected path is reported through the startup message (E_FILE) instead of
+// crashing the worker; it fails closed before the database is opened.
+const pathError=(()=>{try{
+ for(let p=file;p!==workerData.boundary;p=path.dirname(p)){
+ if(p===path.dirname(p))fail('E_FILE');
+ if(fs.existsSync(p)&&fs.lstatSync(p).isSymbolicLink())fail('E_FILE');
+ }
+ if(fs.existsSync(file)&&fs.lstatSync(file).nlink!==1)fail('E_FILE');
+ return null;
+}catch(e){return e;}})();
+/** @type {import('better-sqlite3').Database} Opened unless the path was rejected; no message is served otherwise. */
+let db;
+if(!pathError){
+ fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
+ db=new Database(file,{timeout:2000});
+ db.pragma('foreign_keys=ON');db.pragma('journal_mode=WAL');db.pragma('max_page_count=32768');
+ fs.chmodSync(file,0o600);
+}
+function column(t,name){if(name==='id'||name==='createdAt')return quote(name);const f=t.fields.find(f=>f.name===name);if(!f)fail('E_INPUT');return quote(physical('c_',f.id));}
+function timestamp(v){if(typeof v!=='string'||v.startsWith('0000-')||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(v))return false;const d=new Date(v);return Number.isFinite(d.valueOf())&&d.toISOString()===(v.length===20?v.replace('Z','.000Z'):v);}
+function value(f,v){
+ if(v===null){if(!f.nullable)fail('E_INPUT');return null;}
+ const valid={string:typeof v==='string',timestamp:timestamp(v),number:typeof v==='number',integer:Number.isSafeInteger(v),boolean:typeof v==='boolean',json:v&&typeof v==='object'};
+ if(!valid[f.type])fail('E_INPUT');canonical(v);return f.type==='timestamp'?new Date(v).toISOString():v;
+}
+function record(t,r){const v={id:r.id,createdAt:r.createdAt};for(const f of t.fields){const x=r[physical('c_',f.id)];if(x!==null&&x!==undefined)v[f.name]=JSON.parse(x);}return v;}
+function usage(){return Number(db.prepare("SELECT value FROM _meta WHERE key='usage'").get().value);}
+const sameConstraint=(a,b,k)=>['required','nullable','unique'].includes(k)?!!a[k]===!!b[k]:JSON.stringify(a[k])===JSON.stringify(b[k]);
+// SQLite index names are database-wide. Encode each identity as a tuple so
+// locally scoped field ids and multi-digit ordinals cannot alias another table.
+function repairIndexes(actual){
+ if(db.prepare("SELECT value FROM _meta WHERE key='index_identity'").get()?.value==='2')return;
+ db.transaction(()=>{
+ for(const t of actual.tables){
+ const table=quote(physical('t_',t.id));
+ for(const f of t.fields)if(f.unique)db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS ${quote(physical('u_',canonical([t.id,f.id])))} ON ${table}(json_extract(${column(t,f.name)},'$'))`);
+ for(const [n,index] of (t.indexes||[]).entries())db.exec(`CREATE INDEX IF NOT EXISTS ${quote(physical('i_',canonical([t.id,n])))} ON ${table}(${index.map(k=>['id','createdAt'].includes(k)?column(t,k):`json_extract(${column(t,k)},'$')`).join(',')})`);
+ }
+ db.prepare("INSERT INTO _meta VALUES('index_identity','2') ON CONFLICT(key) DO UPDATE SET value='2'").run();
+ }).immediate();
+}
+function schema(){
+ // A failed static-file switch may leave an additive schema ahead of the page.
+ // Old pages read/write their declared fields; only explicit saves remove fields.
+ if(!workerData.strictMigration){
+ let previous;try{const saved=db.prepare("SELECT value FROM _meta WHERE key='definition'").get();previous=saved&&JSON.parse(saved.value);}catch(e){if(!String(e.message).includes('no such table'))throw e;}
+ if(previous&&canonical(previous)===canonical(definition)){repairIndexes(previous);return;}
+ if(previous&&canonical(previous)!==canonical(definition)){
+ const actual=new Map(previous.tables.map(t=>[t.id,t]));
+ const compatible=definition.tables.every(t=>{const stored=actual.get(t.id);return stored&&t.fields.every(f=>{const old=stored.fields.find(x=>x.id===f.id);return old&&!['type','required','nullable','unique','references'].some(k=>!sameConstraint(old,f,k));});});
+ const ahead=previous.tables.length>definition.tables.length||definition.tables.some(t=>{const old=actual.get(t.id);return old&&(old.name!==t.name||old.fields.length>t.fields.length||t.fields.some(f=>old.fields.find(x=>x.id===f.id)?.name!==f.name));});
+ if(compatible&&ahead){storedDefinition=previous;repairIndexes(previous);return;}
+ }
+ }
+ const run=db.transaction(()=>{
+ db.exec('CREATE TABLE IF NOT EXISTS _meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);CREATE TABLE IF NOT EXISTS _requests(id TEXT PRIMARY KEY,digest TEXT,response TEXT,created INTEGER)');
+ db.exec('CREATE INDEX IF NOT EXISTS _requests_created ON _requests(created)');
+ const saved=db.prepare("SELECT value FROM _meta WHERE key='definition'").get();const previous=saved?JSON.parse(saved.value):{tables:[]};const old=new Map(previous.tables.map(t=>[t.id,t]));
+ const reset=db.prepare("SELECT value FROM _meta WHERE key='reset_allowed'").get();
+ if(reset?.value==='1'){
+ if(previous.tables.some(t=>db.prepare(`SELECT 1 FROM ${quote(physical('t_',t.id))} LIMIT 1`).get()))fail('E_CONFLICT');
+ for(const t of previous.tables)db.exec(`DROP TABLE ${quote(physical('t_',t.id))}`);old.clear();previous.tables=[];db.prepare("UPDATE _meta SET value='0' WHERE key='reset_allowed'").run();
+ }
+ if(previous.tables.some(t=>!definition.tables.some(n=>n.id===t.id)))fail('E_MIGRATION');
+ for(const t of definition.tables){
+ const table=quote(physical('t_',t.id)),before=old.get(t.id),fields=new Map((before?.fields||[]).map(f=>[f.id,f]));
+ if(before?.fields.some(f=>!t.fields.some(n=>n.id===f.id)))fail('E_MIGRATION');
+ if(!before)db.exec(`CREATE TABLE ${table}(id TEXT PRIMARY KEY,createdAt TEXT NOT NULL,_bytes INTEGER NOT NULL)`);
+ for(const f of t.fields){const prev=fields.get(f.id),c=column(t,f.name);
+ if(prev&&['type','required','nullable','unique','references'].some(k=>!sameConstraint(prev,f,k)))fail('E_MIGRATION');
+ if(!prev){db.exec(`ALTER TABLE ${table} ADD COLUMN ${c} TEXT`);if(Object.hasOwn(f,'default')){const normalized=value(f,f.default);if(f.references&&normalized!==null&&before&&db.prepare(`SELECT 1 FROM ${table} LIMIT 1`).get()&&(!old.has(f.references.table)||!db.prepare(`SELECT 1 FROM ${quote(physical('t_',f.references.table))} WHERE id=?`).get(normalized)))fail('E_MIGRATION');db.prepare(`UPDATE ${table} SET ${c}=?`).run(canonical(normalized));}else if(before&&f.required)fail('E_MIGRATION');}
+ if(f.unique)db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS ${quote(physical('u_',canonical([t.id,f.id])))} ON ${table}(json_extract(${c},'$'))`);
+ }
+ for(const [n,index] of (t.indexes||[]).entries()){const name=quote(physical('i_',canonical([t.id,n])));db.exec(`DROP INDEX IF EXISTS ${name}`);db.exec(`CREATE INDEX ${name} ON ${table}(${index.map(k=>['id','createdAt'].includes(k)?column(t,k):`json_extract(${column(t,k)},'$')`).join(',')})`);}
+ }
+ db.prepare("INSERT OR IGNORE INTO _meta VALUES('usage','0')").run();
+ db.prepare("INSERT OR IGNORE INTO _meta VALUES('revision','0')").run();
+ if(saved&&canonical(previous)!==canonical(definition)){let total=0;for(const t of definition.tables){const table=quote(physical('t_',t.id));let cursor='';for(;;){const page=db.prepare(`SELECT * FROM ${table} WHERE id>? ORDER BY id LIMIT 16`).all(cursor);if(!page.length)break;for(const r of page){const bytes=size(record(t,r));if(bytes>1024*1024)fail('E_LIMIT');total+=bytes;db.prepare(`UPDATE ${table} SET _bytes=? WHERE id=?`).run(bytes,r.id);}cursor=page[page.length-1].id;}}if(total>workerData.limit)fail('E_LIMIT');db.prepare("UPDATE _meta SET value=? WHERE key='usage'").run(String(total));}
+ if(saved&&canonical(previous)!==canonical(definition))db.prepare("UPDATE _meta SET value=CAST(value AS INTEGER)+1 WHERE key='revision'").run();
+ db.prepare("INSERT INTO _meta VALUES('definition',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(canonical(definition));
+ db.prepare("INSERT INTO _meta VALUES('index_identity','2') ON CONFLICT(key) DO UPDATE SET value='2'").run();
+ });run.immediate();
+}
+function where(t,filters){
+ if(!Array.isArray(filters)||filters.length>32)fail('E_INPUT');const clauses=[],params=[];
+ for(const raw of filters){const q={...raw};const type=t.fields.find(f=>f.name===q.field);if(q.value!==null&&(type?.type==='timestamp'||q.field==='createdAt'))q.value=value(type||{type:'timestamp'},q.value);if(!q||Object.keys(q).sort().join(',')!=='field,op,value'||!operations[q.op])fail('E_INPUT');let c=column(t,q.field);if(!['id','createdAt'].includes(q.field))c=`json_extract(${c},'$')`;
+ if(q.value===null){if(!['eq','ne'].includes(q.op))fail('E_INPUT');clauses.push(c+' IS '+(q.op==='ne'?'NOT ':'')+'NULL');}
+ else{if(!['string','number','boolean'].includes(typeof q.value))fail('E_INPUT');canonical(q.value);clauses.push(c+' '+operations[q.op]+' ?');params.push(typeof q.value==='boolean'?Number(q.value):q.value);}
+ }return {sql:clauses.length?' WHERE '+clauses.join(' AND '):'',params};
+}
+function insert(t,table,args,w){
+ if(!args.values||typeof args.values!=='object'||Array.isArray(args.values)||!t.access.insert.length||Object.keys(args.values).some(k=>!t.access.insert.includes(k)))fail('E_PERMISSION');
+ const stored=storedDefinition.tables.find(table=>table.id===t.id),published=new Map(t.fields.map(f=>[f.id,f]));
+ const r={id:crypto.randomBytes(16).toString('hex'),createdAt:new Date().toISOString()};
+ for(const f of stored.fields){const requested=published.get(f.id),effective=requested||f;let v;if(requested&&Object.hasOwn(args.values,requested.name))v=args.values[requested.name];else if(Object.hasOwn(effective,'default'))v=effective.default;else if(f.required)fail('E_INPUT');else continue;r[f.name]=value(f,v);}
+ const bytes=size(r);if(bytes>1024*1024)fail('E_LIMIT');const digest=crypto.createHash('sha256').update(canonical(args)).digest('hex');
+ if(args.requestId!==undefined&&!/^[A-Za-z0-9_-]{1,64}$/.test(args.requestId))fail('E_INPUT');
+ return db.transaction(()=>{
+ if(args.requestId){const old=db.prepare('SELECT * FROM _requests WHERE id=?').get(args.requestId);if(old){if(old.digest!==digest)fail('E_CONFLICT');return JSON.parse(old.response);}}
+ const maximum=t.access.maxCount===undefined?args.maxCount:Math.min(args.maxCount??t.access.maxCount,t.access.maxCount);
+ if(maximum!==undefined&&db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get().n>=maximum)fail('E_CONDITION');
+ const used=usage();if(used+bytes>workerData.limit)fail('E_LIMIT');for(const f of stored.fields)if(f.references&&r[f.name]!=null&&!db.prepare(`SELECT 1 FROM ${quote(physical('t_',f.references.table))} WHERE id=?`).get(r[f.name]))fail('E_RELATION');const cols=['id','createdAt','_bytes'],vals=[r.id,r.createdAt,bytes];
+ for(const f of stored.fields)if(Object.hasOwn(r,f.name)){cols.push(physical('c_',f.id));vals.push(canonical(r[f.name]));}
+ db.prepare(`INSERT INTO ${table}(${cols.map(quote).join(',')}) VALUES(${vals.map(()=>'?').join(',')})`).run(...vals);db.prepare("UPDATE _meta SET value=? WHERE key='usage'").run(String(used+bytes));
+ db.prepare("UPDATE _meta SET value=CAST(value AS INTEGER)+1 WHERE key='revision'").run();
+ const result={id:r.id};if(args.requestId){db.prepare('INSERT INTO _requests VALUES(?,?,?,?)').run(args.requestId,digest,canonical(result),Date.now());db.exec('DELETE FROM _requests WHERE id IN (SELECT id FROM _requests ORDER BY created DESC,rowid DESC LIMIT -1 OFFSET 2048)');}return result;
+ }).immediate();
+}
+function call(method,args){
+ const t=tables.get(args.table);if(!t)fail('E_TABLE');const a=t.access,table=quote(physical('t_',t.id)),filters=args.filters||[];
+ if(filters.some(q=>!a.read.includes(q.field)))fail('E_PERMISSION');const w=where(t,[...(a.readFilters||[]),...filters]);
+ if(method==='data.insert'||method==='data.insertIf')return insert(t,table,args,w);
+ if(method==='data.count'){if(!a.count)fail('E_PERMISSION');return {count:db.prepare(`SELECT COUNT(*) AS n FROM ${table}`+w.sql).get(...w.params).n};}
+ if(method==='data.aggregate'){
+ if(!(a.aggregate||[]).includes(args.field)||(args.groupBy&&!a.read.includes(args.groupBy)))fail('E_PERMISSION');
+ const field=column(t,args.field),expression=['id','createdAt'].includes(args.field)?field:`json_extract(${field},'$')`;
+ const exp=args.op==='count'?'COUNT(*)':`${args.op}(${expression})`;
+ if(args.groupBy){const c=column(t,args.groupBy),groups=[];let bytes=0;for(const r of db.prepare(`SELECT ${c} AS key,${exp} AS value FROM ${table}`+w.sql+` GROUP BY ${c} LIMIT 101`).iterate(...w.params)){if(groups.length===100)fail('E_LIMIT');const item={key:['id','createdAt'].includes(args.groupBy)?r.key:r.key===null?null:JSON.parse(r.key),value:r.value};bytes+=size(item);if(bytes>2*1024*1024)fail('E_LIMIT');groups.push(item);}return {groups};}
+ return {value:db.prepare(`SELECT ${exp} AS value FROM ${table}`+w.sql).get(...w.params).value};
+ }
+ if(method!=='data.query')fail('E_METHOD');const fields=args.fields||a.read;if(!fields.length||fields.some(f=>!a.read.includes(f)))fail('E_PERMISSION');const order=args.order||{field:'id',direction:'asc'};if(order.field!=='id'&&!a.read.includes(order.field))fail('E_PERMISSION');let c=column(t,order.field);if(!['id','createdAt'].includes(order.field))c=`json_extract(${c},'$')`;
+ const rows=db.prepare(`SELECT * FROM ${table}`+w.sql+` ORDER BY ${c} ${order.direction},id LIMIT ? OFFSET ?`).iterate(...w.params,args.limit||20,args.offset||0);const output=[];let bytes=0;for(const r of rows){const projectedRow=((r)=>{const full=record(t,r),projected=Object.fromEntries(Object.entries(full).filter(([k])=>fields.includes(k)));if(args.include?.length){projected.relations={};for(const name of args.include){const f=t.fields.find(f=>f.name===name);if(!a.read.includes(name)||!f?.references)fail('E_PERMISSION');const target=definition.tables.find(t=>t.id===f.references.table),scope=where(target,[...(target.access.readFilters||[]),{field:'id',op:'eq',value:full[name]??null}]),found=db.prepare(`SELECT * FROM ${quote(physical('t_',target.id))}`+scope.sql).get(...scope.params);projected.relations[name]=found&&target.access.read.length?Object.fromEntries(Object.entries(record(target,found)).filter(([k])=>target.access.read.includes(k))):null;}}return projected;})(r);bytes+=size(projectedRow);if(bytes>2*1024*1024)fail('E_LIMIT');output.push(projectedRow);}return {records:output};
+}
+try{if(pathError)throw pathError;schema();parentPort.postMessage({ready:true});}catch(e){parentPort.postMessage({ready:false,code:e.code?.startsWith('E_')?e.code:e.code?.startsWith('SQLITE_CONSTRAINT')?'E_MIGRATION':e.code==='SQLITE_FULL'?'E_LIMIT':'E_DATA'});db?.close();}
+parentPort.on('message',async m=>{if(m.close){db?.close();parentPort.close();return;}try{
+ let result;
+ if(m.method==='internal.inspect'){
+ const counts=storedDefinition.tables.map(t=>({name:t.name,fields:t.fields.map(f=>f.name),count:db.prepare(`SELECT COUNT(*) AS n FROM ${quote(physical('t_',t.id))}`).get().n}));result={definition:storedDefinition,tables:counts,records:counts.reduce((n,t)=>n+t.count,0),version:Number(db.prepare("SELECT value FROM _meta WHERE key='revision'").get().value),bytes:usage()};
+ }else if(m.method==='internal.reset'){
+ result=db.transaction(()=>{if(Number(db.prepare("SELECT value FROM _meta WHERE key='revision'").get().value)!==m.args.version)fail('E_CONFLICT');for(const t of storedDefinition.tables)db.exec(`DELETE FROM ${quote(physical('t_',t.id))}`);db.exec('DELETE FROM _requests');db.prepare("UPDATE _meta SET value='0' WHERE key='usage'").run();db.prepare("UPDATE _meta SET value=CAST(value AS INTEGER)+1 WHERE key='revision'").run();db.prepare("INSERT INTO _meta VALUES('reset_allowed','1') ON CONFLICT(key) DO UPDATE SET value='1'").run();return {cleared:true};}).immediate();
+ }else if(m.method==='internal.check'){if(db.pragma('quick_check',{simple:true})!=='ok')fail('E_DATA');result={valid:true};}
+ else if(m.method==='internal.version'){result={revision:Number(db.prepare("SELECT value FROM _meta WHERE key='revision'").get().value)};}
+ else if(m.method==='internal.backup'){
+ if(path.dirname(m.args.file)!==path.dirname(file)||!m.args.file.startsWith(file+'.backup-'))fail('E_FILE');
+ const deadline=Date.now()+5000;await db.backup(m.args.file,{progress:()=>{if(Date.now()>deadline)fail('E_BUSY');return 64;}});const snapshot=new Database(m.args.file,{readonly:true});try{result={saved:true,revision:Number(snapshot.prepare("SELECT value FROM _meta WHERE key='revision'").get().value)};}finally{snapshot.close();}
+ }else result=call(m.method,m.args);
+ if(m.method.startsWith('data.')&&size(result)>2*1024*1024)fail('E_LIMIT');parentPort.postMessage({id:m.id,ok:true,value:result});
+}catch(e){parentPort.postMessage({id:m.id,ok:false,code:e.code?.startsWith('E_')?e.code:e.code==='SQLITE_BUSY'?'E_BUSY':e.code==='SQLITE_FULL'?'E_LIMIT':e.code?.startsWith('SQLITE_CONSTRAINT')?'E_CONFLICT':'E_DATA'});}});
diff --git a/src/main/features/web_apps/data.ts b/src/main/features/web_apps/data.ts
new file mode 100644
index 00000000..88b4cfb3
--- /dev/null
+++ b/src/main/features/web_apps/data.ts
@@ -0,0 +1,31 @@
+/** Bounded application-owned worker connection; never exposes path/SQL to pages. */
+import { Worker } from 'node:worker_threads';
+import * as path from 'node:path';
+import { SRC_ROOT } from '../../paths';
+import { dataDefinitionSchema, type DataDefinition } from './data-contract';
+const fail=(code:string)=>Object.assign(new Error(code),{code});
+export function dataWorkerPath(root=SRC_ROOT){return path.join(root,'main/features/web_apps/data-worker.js').replace(/([\\/])app\.asar([\\/])/g,'$1app.asar.unpacked$2');}
+export class LocalAppData {
+ private worker:Worker;
+ private sequence=0;
+ private closing=false;
+ private started=false;
+ private stopped=false;
+ private ready:Promise<void>;
+ private requests=new Map<number,{resolve:(v:any)=>void;reject:(e:Error)=>void;timer:ReturnType<typeof setTimeout>}>();
+ constructor(file:string,boundary:string,definition:DataDefinition,limit=200*1024*1024,strictMigration=false){
+ const checked=dataDefinitionSchema.parse(definition);
+ this.worker=new Worker(dataWorkerPath(),{workerData:{file,boundary,definition:checked,limit,strictMigration},resourceLimits:{maxOldGenerationSizeMb:64}});
+ this.ready=new Promise((resolve,reject)=>{
+ const startup=setTimeout(()=>{reject(fail('E_BUSY'));void this.worker.terminate();},5000);startup.unref();
+ this.worker.on('message',m=>{if(Object.hasOwn(m,'ready')){clearTimeout(startup);if(m.ready){this.started=true;resolve();}else{reject(fail(m.code));void this.worker.terminate();}return;}const request=this.requests.get(m.id);if(!request)return;this.requests.delete(m.id);clearTimeout(request.timer);if(m.ok)request.resolve(m.value);else request.reject(fail(m.code));});
+ this.worker.on('error',()=>{this.stopped=true;clearTimeout(startup);const e=fail('E_DATA');reject(e);for(const q of this.requests.values()){clearTimeout(q.timer);q.reject(e);}this.requests.clear();});
+ this.worker.on('exit',()=>{this.stopped=true;clearTimeout(startup);reject(fail('E_CLOSED'));for(const q of this.requests.values()){clearTimeout(q.timer);q.reject(fail('E_CLOSED'));}this.requests.clear();});
+ });
+ void this.ready.catch(()=>{});
+ }
+ /** The worker served calls and then stopped outside close() (timed-out call, crash, exit): holders must reopen. */
+ get dead(){return this.started&&this.stopped&&!this.closing;}
+ async call(method:string,args:unknown){if(this.closing)throw fail('E_CLOSED');if(this.requests.size>=16)throw fail('E_BUSY');await this.ready;if(this.closing||this.worker.threadId===-1)throw fail('E_CLOSED');if(this.requests.size>=16)throw fail('E_BUSY');const id=++this.sequence;return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.requests.delete(id);this.stopped=true;reject(fail('E_BUSY'));void this.worker.terminate();},method.startsWith('data.')?2000:10000);timer.unref();this.requests.set(id,{resolve,reject,timer});this.worker.postMessage({id,method,args});});}
+ async close(){if(this.closing)return;this.closing=true;await this.ready.catch(()=>{});if(this.worker.threadId===-1)return;await new Promise<void>(resolve=>{const deadline=setTimeout(()=>{void this.worker.terminate();resolve();},3000);deadline.unref();this.worker.once('exit',()=>{clearTimeout(deadline);resolve();});this.worker.postMessage({close:true});});}
+}
diff --git a/src/main/features/web_apps/host.ts b/src/main/features/web_apps/host.ts
index 813986d3..25af8f74 100644
--- a/src/main/features/web_apps/host.ts
+++ b/src/main/features/web_apps/host.ts
@@ -16,6 +16,7 @@ import type { AgentTool } from '#core-agent';
import { appResource as scopedAppResource } from './resources';
import { cancelForApp, type AppUsageScope } from '../connectors/action_confirm';
import { bundleRevision } from './bundle-revision';
+import { requireLocalAppType, isCommercialWebAppFailure, commercialWebAppFailure } from './commercial-entry';
let dialogBusy = false;
async function nativeDialog<T>(run: () => Promise<T>): Promise<T> {
@@ -72,6 +73,11 @@ export const runtime = new WebAppRuntime({
registerUserSwitchHook('web-apps', previousUid => runtime.closeUser(previousUid));
export type Source = { appId: string } | { cid: string; artifactId: string };
+/** Also used by the protocol handler to reject shared-origin aliases. */
+export function hasIsolatedBrowserStorage(uid: string, source: Source): boolean {
+ return 'appId' in source ? saved.hasIsolatedBrowserStorage(uid, source.appId)
+ : artifacts.readArtifactMeta(uid, source.cid, source.artifactId)?.browserStorage === 'isolated-v1';
+}
export async function resolveBundle(uid: string, source: Source): Promise<{ bundle: Bundle | null; url: string; entry: string }> {
const isSaved = 'appId' in source;
const resolve = (rel: string) => {
@@ -86,9 +92,23 @@ export async function resolveBundle(uid: string, source: Source): Promise<{ bund
: `chat-app://cid/${encodeURIComponent(source.cid)}/${encodeURIComponent(source.artifactId)}`;
const url = base + '/' + entry.split('/').map(encodeURIComponent).join('/');
const manifestFile = resolve(MANIFEST_FILE);
- if (!manifestFile) return { bundle: null, url, entry };
+ let appType: 'local'|'web'='local';
+ if (isSaved) appType = await saved.resolveSavedAppType(uid, source.appId);
+ else appType = await saved.resolveArtifactAppType(uid, source.cid, source.artifactId);
+ requireLocalAppType(appType);
+ if (!manifestFile && appType === 'local') {
+ if (!hasIsolatedBrowserStorage(uid, source)) return { bundle: null, url, entry };
+ const key = crypto.createHash('sha256').update(JSON.stringify(isSaved ? ['saved', source.appId] : ['artifact', source.cid, source.artifactId])).digest('hex');
+ // Ordinary pages reuse resource lifetime tracking, without receiving SDK authority.
+ return { url, entry, bundle: { browserOnly: true, kind: isSaved ? 'saved' : 'artifact',
+ key, title: t('artifact.title'), entry, appType, manifest: { sdkVersion: 1, capabilities: [] }, resolve } };
+ }
+ if(!manifestFile) {
+ const key=crypto.createHash('sha256').update(JSON.stringify(isSaved?['saved',source.appId]:['artifact',source.cid,source.artifactId])).digest('hex');
+ return {url,entry,bundle:{kind:isSaved?'saved' as const:'artifact' as const,key,title:'Interactive app',entry,appType,manifest:{sdkVersion:1,capabilities:[]},resolve}};
+ }
const stat = fs.statSync(manifestFile.absPath);
- if (stat.size > 16 * 1024) throw new AppError('E_MANIFEST');
+ if (stat.size > 64 * 1024) throw new AppError('E_MANIFEST');
let manifest: unknown;
try { manifest = JSON.parse(fs.readFileSync(manifestFile.absPath, 'utf8')); } catch { throw new AppError('E_MANIFEST'); }
const key = crypto.createHash('sha256').update(JSON.stringify(isSaved ? ['saved', source.appId] : ['artifact', source.cid, source.artifactId])).digest('hex');
@@ -102,7 +122,7 @@ export async function resolveBundle(uid: string, source: Source): Promise<{ bund
let revision: Awaited<ReturnType<typeof bundleRevision>>;
try { revision = await bundleRevision(path.dirname(manifestFile.absPath), [initial.absPath, manifestFile.absPath]); }
catch { throw new AppError('E_BUNDLE'); }
- return { url, entry, bundle: { kind: isSaved ? 'saved' : 'artifact', key, title, entry, manifest, valid: () => revision.valid(),
+ return { url, entry, bundle: { appType, kind: isSaved ? 'saved' : 'artifact', key, title, entry, manifest, valid: () => revision.valid(),
resolve: rel => { const file = resolve(rel); return file && revision.accept(file.absPath) ? file : null; } } };
}
export async function openApp(uid: string, owner: number, source: Source) {
@@ -112,6 +132,8 @@ export async function openApp(uid: string, owner: number, source: Source) {
export { sdkScript, APP_CSP } from './resources';
export function appResource(request: Request) { return scopedAppResource(request, runtime); }
export function safeFailure(err: unknown) {
+ if (isCommercialWebAppFailure(err)) return commercialWebAppFailure();
const code = err instanceof AppError ? err.code : (err as NodeJS.ErrnoException)?.code === 'EEXIST' ? 'E_EXISTS' : 'E_FAILED';
- return { code, message: t(`web_apps.error_${code}`) };
+ const key=`web_apps.error_${code}`, message=t(key);
+ return { code, message:message===key?t('web_apps.error_E_FAILED'):message };
}
diff --git a/src/main/features/web_apps/preview.ts b/src/main/features/web_apps/preview.ts
index 24278be1..fb092319 100644
--- a/src/main/features/web_apps/preview.ts
+++ b/src/main/features/web_apps/preview.ts
@@ -13,7 +13,10 @@ import { mimeFor } from '../chat_artifacts';
import { bundleRevision } from './bundle-revision';
import { MANIFEST_FILE, manifestSchema } from './catalog';
import { AppError, WebAppRuntime, type Bundle } from './runtime';
+import { normalizeAppType } from './data-contract';
import { appResource } from './resources';
+import { storedAppType, requireLocalAppType } from './commercial-entry';
+import { getActiveUserId, hasActiveUser } from '../users';
export const previewPreload = path.join(SRC_ROOT, 'main/features/web_apps/preview-preload.js');
export interface PreviewSdkEvidence {
@@ -26,18 +29,21 @@ export interface PreviewSdkEvidence {
/** Absence preserves legacy HTML; an invalid opt-in must never downgrade. */
export async function previewBundle(entry: string): Promise<Bundle | null> {
const root = path.dirname(entry);
+ if (hasActiveUser()) requireLocalAppType(await (await import('../saved_apps')).managedPathAppType(getActiveUserId(), entry));
+ const appType = storedAppType(root) ?? 'local';
+ requireLocalAppType(appType);
const manifestPath = path.join(root, MANIFEST_FILE);
let stat: fs.Stats;
try { stat = fs.lstatSync(manifestPath); }
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
- if (!stat.isFile() || stat.size > 16 * 1024) throw new AppError('E_MANIFEST');
+ if (!stat.isFile() || stat.size > 64 * 1024) throw new AppError('E_MANIFEST');
let manifest: unknown;
try { manifest = manifestSchema.parse(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))); }
catch { throw new AppError('E_MANIFEST'); }
let revision: Awaited<ReturnType<typeof bundleRevision>>;
try { revision = await bundleRevision(root, [entry, manifestPath]); }
catch { throw new AppError('E_BUNDLE'); }
- return { key: 'preview', title: 'HTML preview', entry: path.basename(entry), manifest,
+ return { appType, key: 'preview', title: 'HTML preview', entry: path.basename(entry), manifest,
valid: () => revision.valid(),
resolve(rel) {
if (!rel || rel.includes('\\') || rel.split('/').some(p => !p || p === '.' || p === '..' || p.startsWith('.'))) return null;
@@ -52,6 +58,7 @@ export async function previewBundle(entry: string): Promise<Bundle | null> {
}
export async function createPreviewSdk(ses: Session, contents: WebContents, bundle: Bundle) {
+ requireLocalAppType(bundle.appType);
const storageRoot = await fsp.mkdtemp(path.join(os.tmpdir(), 'orkas-preview-storage-'));
// This identity belongs only to this in-memory runtime; no account is created/read.
const uid = 'preview';
@@ -70,6 +77,7 @@ export async function createPreviewSdk(ses: Session, contents: WebContents, bund
runtime.closeOwner(contents.id);
if (listener) contents.removeListener('ipc-message', listener);
await Promise.allSettled([...pending]);
+ await runtime.drainData();
if (installed) { ses.protocol.unhandle('chat-app'); installed = false; }
await fsp.rm(storageRoot, { recursive: true, force: true });
}
@@ -139,6 +147,18 @@ export async function createPreviewSdk(ses: Session, contents: WebContents, bund
});
installed = true;
return { shellUrl, origin, evidence, dispose,
+ async settle() {
+ // Let replies reach the document and its promise continuations enqueue
+ // any follow-up calls. A quiet painted frame, not merely load, ends
+ // startup work. The renderer owns the existing preview timeout.
+ for (;;) {
+ const frame = contents.mainFrame.frames.find(frame => runtime.canNavigate(contents.id, open.url, frame.url));
+ if (!frame) throw new AppError('E_BUNDLE');
+ await frame.executeJavaScript('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
+ if (!pending.size) return;
+ await Promise.allSettled([...pending]);
+ }
+ },
async attach() {
await contents.executeJavaScript(`new Promise((resolve, reject) => {
const frame = document.querySelector('iframe');
diff --git a/src/main/features/web_apps/request-history.ts b/src/main/features/web_apps/request-history.ts
index 16cbfb66..97fe7444 100644
--- a/src/main/features/web_apps/request-history.ts
+++ b/src/main/features/web_apps/request-history.ts
@@ -1,8 +1,16 @@
/** Compact sequential SDK ids without expiring replay protection. Legacy/custom
* ids remain supported; out-of-order calls and cancel-before-call are remembered. */
+export const REQUEST_HISTORY_CAPACITY = 8192;
export class RequestHistory {
+ private units = 0;
+ private exhausted = false;
private documents = new Map<string, Array<[number, number]>>();
private other = new Set<string>();
+ private lowerBound(ranges:Array<[number,number]>, n:number):number {
+ let low=0, high=ranges.length;
+ while(low<high){const mid=(low+high)>>>1;if(ranges[mid][1]<n)low=mid+1;else high=mid;}
+ return low;
+ }
private sequence(id: string): { document: string; n: number } | null {
const match = /^((?:d[a-f0-9]{32})?q)([1-9][0-9]*)$/.exec(id);
if (!match) return null;
@@ -11,16 +19,23 @@ export class RequestHistory {
}
has(id: string): boolean {
const sequence = this.sequence(id);
- return sequence === null ? this.other.has(id) : (this.documents.get(sequence.document) ?? []).some(([start, end]) => start <= sequence.n && sequence.n <= end);
+ if(sequence===null)return this.other.has(id);
+ const ranges=this.documents.get(sequence.document)??[];
+ const range=ranges[this.lowerBound(ranges,sequence.n)];
+ return !!range&&range[0]<=sequence.n;
}
- add(id: string): void {
+ add(id: string): boolean {
+ // Accepted work must remain cancellable even after saturation.
+ if (this.has(id)) return true;
+ if (this.exhausted) return false;
const sequence = this.sequence(id);
- if (sequence === null) { this.other.add(id); return; }
+ if (sequence === null) {
+ if (!this.reserve(1)) return false;
+ this.other.add(id); return true;
+ }
const { document, n } = sequence;
- let ranges = this.documents.get(document);
- if (!ranges) { ranges = []; this.documents.set(document, ranges); }
- let i = 0;
- while (i < ranges.length && ranges[i][1] < n - 1) i++;
+ const ranges = this.documents.get(document)??[];
+ let i = this.lowerBound(ranges,n-1);
let start = n, end = n;
const first = i;
while (i < ranges.length && ranges[i][0] <= end + 1) {
@@ -28,7 +43,14 @@ export class RequestHistory {
end = Math.max(end, ranges[i][1]);
i++;
}
+ if (!this.reserve(1 - (i - first) + (this.documents.has(document) ? 0 : 1))) return false;
ranges.splice(first, i - first, [start, end]);
+ this.documents.set(document,ranges);
+ return true;
+ }
+ private reserve(delta: number): boolean {
+ if (this.units + delta > REQUEST_HISTORY_CAPACITY) { this.exhausted = true; return false; }
+ this.units += delta; return true;
}
- clear(): void { this.documents.clear(); this.other.clear(); }
+ clear(): void { this.documents.clear(); this.other.clear(); this.units = 0; this.exhausted = false; }
}
diff --git a/src/main/features/web_apps/resources.ts b/src/main/features/web_apps/resources.ts
index 1ae99cb1..94991b3f 100644
--- a/src/main/features/web_apps/resources.ts
+++ b/src/main/features/web_apps/resources.ts
@@ -3,29 +3,36 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import { SRC_ROOT } from '../../paths';
import * as artifacts from '../chat_artifacts';
+import { commonMethod } from './data-contract';
import { METHODS, SDK_PATH, catalogDocument } from './catalog';
import { webContentCsp } from '../../util/web-content-policy';
import type { WebAppRuntime } from './runtime';
-let sdk: string | null = null;
-export function sdkScript() {
- if (!sdk) sdk = fs.readFileSync(path.join(SRC_ROOT, 'main/features/web_apps/sdk.js'), 'utf8')
- .replace('/* HOST_METHOD_NAMES */ []', JSON.stringify(Object.keys(METHODS)));
- return sdk;
+const scripts = new Map<string,string>();
+export function sdkScript(appType: 'local'|'web'='local') {
+ if(!scripts.has(appType)){
+ const methods=Object.keys(METHODS).filter(method=>appType!=='web'||commonMethod(method));
+ const common=Object.keys(METHODS).filter(commonMethod);
+ scripts.set(appType,fs.readFileSync(path.join(SRC_ROOT,'main/features/web_apps/sdk.js'),'utf8')
+ .replace('/* HOST_METHOD_NAMES */ []',JSON.stringify(methods)).replaceAll('/* COMMON_METHOD_NAMES */ []',JSON.stringify(common)));
+ }
+ return scripts.get(appType)!;
}
export const APP_CSP = webContentCsp();
export function appResource(request: Request, runtime: WebAppRuntime) {
const url = new URL(request.url);
- if (!/^app-[a-f0-9]{32}$/.test(url.host)) return null;
+ if (!/^(?:app-[a-f0-9]{32}|a-[a-f0-9]{20})$/.test(url.host)) return null;
let rel: string;
try { rel = url.pathname.slice(1).split('/').map(decodeURIComponent).join('/'); } catch { return { status: 400 }; }
const scoped = runtime.resource(url.host, rel, request.headers.get('Origin'));
if (!scoped) return { status: 403 };
- const headers = { 'Content-Security-Policy': APP_CSP, 'Cache-Control': 'no-store',
+ const headers: Record<string, string> = { 'Cache-Control': 'no-store',
'Cross-Origin-Resource-Policy': 'same-origin', 'X-Content-Type-Options': 'nosniff' };
- if (rel === SDK_PATH) return { status: 200, body: sdkScript(), mime: 'text/javascript; charset=utf-8', headers };
- if (rel === artifacts.BRIDGE_RELPATH) return { status: 200, body: artifacts.BRIDGE_JS, mime: 'text/javascript; charset=utf-8', headers };
- if (rel === '__orkas/capabilities.json') return { status: 200, body: JSON.stringify(catalogDocument()), mime: 'application/json', headers };
+ if (!scoped.bundle.browserOnly) headers['Content-Security-Policy'] = APP_CSP;
+ if (scoped.bundle.browserOnly && (rel === SDK_PATH || rel === '__orkas/capabilities.json')) return { status: 403 };
+ if (rel === SDK_PATH) return { status: 200, body: sdkScript(scoped.bundle.appType), mime: 'text/javascript; charset=utf-8', headers };
+ if (rel === artifacts.BRIDGE_RELPATH) return scoped.bundle.appType==='web'?{status:403}:{ status: 200, body: artifacts.BRIDGE_JS, mime: 'text/javascript; charset=utf-8', headers };
+ if (rel === '__orkas/capabilities.json') return { status: 200, body: JSON.stringify(catalogDocument(scoped.bundle.appType)), mime: 'application/json', headers };
if (!scoped.resolved) return { status: 404 };
return { status: 200, file: scoped.resolved.absPath, mime: scoped.resolved.mime, headers,
source: scoped.bundle.kind === 'artifact' ? 'chat_app_artifact' as const : 'chat_app_saved' as const };
diff --git a/src/main/features/web_apps/runtime.ts b/src/main/features/web_apps/runtime.ts
index 9a59740d..52f8921b 100644
--- a/src/main/features/web_apps/runtime.ts
+++ b/src/main/features/web_apps/runtime.ts
@@ -5,17 +5,23 @@ import * as path from 'node:path';
import type { AppUsageScope } from '../connectors/action_confirm';
import { Mutex } from 'async-mutex';
import { METHODS, SDK_VERSION, UNSUPPORTED, describeMethod, manifestSchema, type AppManifest, type Method, MAX_PAYLOAD_BYTES } from './catalog';
-import { writeJson, writeBytesAtomic, isAtomicWriteTempPath } from '../../storage';
+import { writeBytesAtomic, isAtomicWriteTempPath } from '../../storage';
import { webAppDataFile, webAppSandboxRoot, userLocalRoot, userCloudRoot, userRoot, WS_ROOT } from '../../paths';
import { isPathAllowed } from '../../util/path-sandbox';
import { MAX_TEXT_FILE_BYTES } from '../../util/file-size-limits';
+import { LocalAppData } from './data';
+import {createLogger} from '../../logger';
+import { commonMethod, type AppType, type DataDefinition } from './data-contract';
import { RequestHistory } from './request-history';
+import { requireLocalAppType } from './commercial-entry';
export class AppError extends Error {
constructor(readonly code: string) { super(code); }
}
export interface Bundle {
+ browserOnly?: boolean;
kind?: 'saved' | 'artifact';
+ appType?: AppType;
key: string;
title: string;
entry: string;
@@ -30,7 +36,14 @@ export interface AppTool {
inputSchema: object;
execute(args: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;
}
+export interface AppDataOwner {
+ readonly closed?:boolean;
+ open():Promise<LocalAppData>;
+ call(method:string,args:unknown,signal?:AbortSignal):Promise<unknown>;
+ close():Promise<void>;
+}
export interface HostAdapters {
+ dataOwner?(uid:string,key:string,file:string,definition:DataDefinition):AppDataOwner;
storageChanged?(uid: string, relPath: string): void;
activeUser(): string;
language(): string;
@@ -56,7 +69,25 @@ interface Instance {
const id = () => crypto.randomBytes(16).toString('hex');
const MAX_FILE_BYTES = MAX_TEXT_FILE_BYTES;
const STORE_BYTES = MAX_TEXT_FILE_BYTES;
+/** Serialized bytes of parsed stores kept for open apps; larger stores are
+ * re-read per call. */
+const STORE_CACHE_BYTES = 32 * 1024 * 1024;
+interface ParsedStore { signature: string; owner: string; bytes: number; entries: Record<string, unknown> }
+/** Identity plus both change times: a synced copy arrives by rename (new
+ * inode) and an in-place rewrite always moves ctime, even when mtime is set. */
+const storeSignature = (st: { dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }) =>
+ `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`;
const error = (code: string): never => { throw new AppError(code); };
+const liveRuntimes=new Set<WeakRef<WebAppRuntime>>();
+const heldAppData=new Set<string>();
+export function holdAppData(uid:string,key:string){const identity=JSON.stringify([uid,key]);if(heldAppData.has(identity))throw new AppError('E_BUSY');heldAppData.add(identity);return ()=>heldAppData.delete(identity);}
+export async function closeAppData(uid:string,key:string){
+ for(const ref of [...liveRuntimes]){const runtime=ref.deref();if(!runtime){liveRuntimes.delete(ref);continue;}runtime.closeSource(uid,key);await runtime.drainData();}
+}
+/** A formal migration must be transferable even when its page stays closed. */
+export async function checkpointAppData(uid:string,key:string,file:string,definition:DataDefinition){
+ for(const ref of [...liveRuntimes]){const runtime=ref.deref();if(!runtime){liveRuntimes.delete(ref);continue;}if(await runtime.checkpointData(uid,key,file,definition))return;}
+}
async function readFileBytes(file: fs.FileHandle, check: () => void): Promise<Buffer> {
// Allocate for this file, not the admission ceiling; read in chunks so
// cancellation still interrupts large snapshots. Short reads are not EOF.
@@ -77,58 +108,161 @@ async function readFileBytes(file: fs.FileHandle, check: () => void): Promise<Bu
}
}
}
+/** Whether serialized JSON nests at most `max` objects/arrays deep. Strings
+ * are skipped whole (the input is JSON.stringify output, so quotes and escapes
+ * are well formed); scanning only structure keeps long text values cheap. */
+function jsonDepthWithin(json: string, max: number): boolean {
+ const structure = /["{}[\]]/g;
+ let depth = 0;
+ for (let m = structure.exec(json); m; m = structure.exec(json)) {
+ const c = m[0];
+ if (c === '"') {
+ // The closing quote is the next one not escaped by an odd backslash run.
+ let end = m.index;
+ for (;;) {
+ end = json.indexOf('"', end + 1);
+ if (end < 0) return true;
+ let slashes = 0;
+ while (json.charCodeAt(end - 1 - slashes) === 92) slashes++;
+ if (slashes % 2 === 0) break;
+ }
+ structure.lastIndex = end + 1;
+ } else if (c === '{' || c === '[') { if (++depth > max) return false; }
+ else depth--;
+ }
+ return true;
+}
export function boundedJson(value: unknown, max = MAX_PAYLOAD_BYTES): string {
let json: string;
try { json = JSON.stringify(value); } catch { return error('E_INPUT'); }
if (typeof json !== 'string' || Buffer.byteLength(json) > max) return error('E_LIMIT');
// Bound nested JSON work before Zod or service adapters traverse it.
- let depth = 0;
- let quoted = false;
- let escaped = false;
- for (let i = 0; i < json.length; i++) {
- const c = json[i];
- if (quoted) { if (escaped) escaped = false; else if (c === '\\') escaped = true; else if (c === '"') quoted = false; }
- else if (c === '"') quoted = true;
- else if (c === '{' || c === '[') { if (++depth > 32) return error('E_LIMIT'); }
- else if (c === '}' || c === ']') depth--;
- }
+ if (!jsonDepthWithin(json, 32)) return error('E_LIMIT');
return json;
}
/** Instances and grants are memory-only and bound to the trusted host renderer. */
export class WebAppRuntime {
+ private dataConnections=new Map<string,LocalAppData>();
+ private dataOwners=new Map<string,AppDataOwner>();
+ private dataOpening=new Map<string,Promise<LocalAppData>>();
+ private dataClosures=new Set<Promise<void>>();
+ async drainData(){await Promise.allSettled([...this.dataOpening.values()]);await Promise.allSettled([...this.dataClosures]);}
+ private dataFile(s:Instance){return this.preview ? path.join(this.preview.storageRoot,'data.sqlite') : path.join(webAppSandboxRoot(s.uid,s.bundle.key,'local'),'data.sqlite');}
+ private async dataCall(s:Instance,method:string,args:unknown,signal:AbortSignal){
+ if(heldAppData.has(JSON.stringify([s.uid,s.bundle.key])))return error('E_BUSY');
+ if(!s.manifest.data)return error('E_NOT_DECLARED');
+ const file=this.dataFile(s);let connection=this.dataConnections.get(file);
+ if(this.dataOwners.get(file)?.closed){this.releaseData(file);connection=undefined;}
+ // A worker stopped by a call timeout or crash never recovers; release it so this call reopens.
+ if(connection?.dead){createLogger('web-app-data').warn('data worker stopped, reopening');this.releaseData(file);connection=undefined;}
+ if(!connection){
+ if(!this.dataOpening.has(file)&&this.dataConnections.size+this.dataOpening.size>=4)return error('E_BUSY');
+ const boundary=this.preview?.storageRoot ?? userLocalRoot(s.uid);
+ if(!isPathAllowed(file,[boundary]))return error('E_FILE');
+ if(!this.dataOpening.has(file))this.dataOpening.set(file,(async()=>{
+ const owner=this.preview?null:this.host.dataOwner?.(s.uid,s.bundle.key,file,s.manifest.data);
+ const opened=owner?await owner.open():new LocalAppData(file,boundary,s.manifest.data);
+ const inUse = [...this.instances.values()].some(other => other.manifest.data
+ && this.dataFile(other) === file && !other.controller.signal.aborted
+ && other.uid === this.host.activeUser());
+ if(!inUse){await (owner?owner.close():opened.close());throw new AppError('E_CLOSED');}
+ this.dataConnections.set(file,opened);if(owner)this.dataOwners.set(file,owner);return opened;
+ })().finally(()=>this.dataOpening.delete(file)));
+ connection=await this.dataOpening.get(file);
+ }
+ if(s.controller.signal.aborted||s.uid!==this.host.activeUser())return error('E_CLOSED');
+ try{return await (this.dataOwners.get(file)?.call(method,args,signal)??connection.call(method,args));}catch(e){throw new AppError((e as any)?.code?.startsWith('E_')?(e as any).code:'E_DATA');}
+ }
+ /** Drop the cached connection for `file`; its close (and checkpoint) finishes in the background. */
+ private releaseData(file:string){
+ const connection=this.dataConnections.get(file);this.dataConnections.delete(file);
+ const owner=this.dataOwners.get(file);this.dataOwners.delete(file);
+ if(connection){const closing=(owner?owner.close():connection.close()).catch(e=>{createLogger('web-app-data').warn('data checkpoint unavailable',{error_code:(e as any).code||'E_DATA'});}).finally(()=>this.dataClosures.delete(closing));this.dataClosures.add(closing);}
+ }
+
private instances = new Map<string, Instance>();
private stores = new Map<string, { mutex: Mutex; users: number }>();
- constructor(private host: HostAdapters, private preview?: { storageRoot: string }) {}
+ /** Parsed storage files of open apps, least recently used first. */
+ private parsedStores = new Map<string, ParsedStore>();
+ private parsedBytes = 0;
+ constructor(private host: HostAdapters, private preview?: { storageRoot: string }) {liveRuntimes.add(new WeakRef(this));}
+ closeSource(uid:string,key:string){for(const s of [...this.instances.values()])if(s.uid===uid&&s.bundle.key===key)this.close(uid,s.owner,s.token);}
+
+ private static storeOwner(s: Instance): string { return `${s.uid}\0${s.bundle.key}`; }
+ private ownerOpen(owner: string): boolean {
+ for (const s of this.instances.values()) if (WebAppRuntime.storeOwner(s) === owner) return true;
+ return false;
+ }
+ private dropStore(file: string): void {
+ const old = this.parsedStores.get(file);
+ if (!old) return;
+ this.parsedStores.delete(file);
+ this.parsedBytes -= old.bytes;
+ }
+ private keepStore(file: string, store: ParsedStore): void {
+ this.dropStore(file);
+ if (store.bytes > STORE_CACHE_BYTES || !this.ownerOpen(store.owner)) return;
+ this.parsedStores.set(file, store);
+ this.parsedBytes += store.bytes;
+ for (const oldest of this.parsedStores.keys()) {
+ if (this.parsedBytes <= STORE_CACHE_BYTES) break;
+ this.dropStore(oldest);
+ }
+ }
private available(capability: string | null | undefined): boolean {
- if (this.preview && capability && capability !== 'storage' && capability !== 'appFiles') return false;
+ if (this.preview && capability && capability !== 'storage' && capability !== 'appFiles' && capability !== 'data') return false;
return capability !== 'ai' || this.host.modelAvailable();
}
+ async checkpointData(uid:string,key:string,file:string,definition:DataDefinition){
+ if(this.preview||!this.host.dataOwner)return false;
+ const owner=this.host.dataOwner(uid,key,file,definition);try{await owner.open();}finally{await owner.close();}return true;
+ }
open(uid: string, owner: number, bundle: Bundle) {
+ requireLocalAppType(bundle.appType);
if (uid !== this.host.activeUser()) return error('E_CLOSED');
+ if(heldAppData.has(JSON.stringify([uid,bundle.key])))return error('E_BUSY');
const parsed = manifestSchema.safeParse(bundle.manifest);
- if (!parsed.success) return error('E_MANIFEST');
+ if (!parsed.success || (bundle.appType === 'web' && parsed.data.capabilities.some(c=>c!=='data'))) return error('E_MANIFEST');
const token = id();
- const instance: Instance = { token, host: `app-${id()}`, uid, owner, bundle, manifest: parsed.data,
+ const host = bundle.browserOnly
+ ? 'a-' + crypto.createHash('sha256').update(JSON.stringify([uid, bundle.key])).digest('hex').slice(0, 20)
+ : `app-${id()}`;
+ if ([...this.instances.values()].some(s => s.host === host && (s.uid !== uid || s.bundle.key !== bundle.key))) return error('E_BUNDLE');
+ const instance: Instance = { token, host, uid, owner, bundle: {...bundle,appType:bundle.appType??'local'}, manifest: structuredClone(parsed.data),
controller: new AbortController(), handles: new Map(), requests: new Map(),
seen: new RequestHistory() };
this.instances.set(token, instance);
- return { token, entry: bundle.entry, url: `chat-app://${instance.host}/${bundle.entry.split('/').map(encodeURIComponent).join('/')}`, sdkVersion: SDK_VERSION };
+ return { token, entry: bundle.entry, url: `chat-app://${instance.host}/${bundle.entry.split('/').map(encodeURIComponent).join('/')}`, ...(bundle.browserOnly ? { browserOnly: true } : { sdkVersion: SDK_VERSION }) };
}
private current(uid: string, owner: number, token: string): Instance {
const s = this.instances.get(token);
if (!s || s.uid !== uid || s.owner !== owner || uid !== this.host.activeUser() || s.controller.signal.aborted) return error('E_CLOSED');
+ requireLocalAppType(s.bundle.appType);
if (s.bundle.valid?.() === false) {
this.close(uid, owner, token); return error('E_CLOSED');
}
return s;
}
+ /** The existing artifact bridge is available only in its local task context. */
+ canSubmitArtifact(uid: string, owner: number, token: string): boolean {
+ try {
+ const s = this.current(uid, owner, token);
+ return !this.preview && s.bundle.kind === 'artifact' && s.bundle.appType === 'local';
+ } catch { return false; }
+ }
close(uid: string, owner: number, token: string): void {
const s = this.instances.get(token);
if (!s || s.uid !== uid || s.owner !== owner) return;
this.instances.delete(token);
+ const dataFile=s.manifest.data?this.dataFile(s):null;
+ if(dataFile&&![...this.instances.values()].some(other=>other.manifest.data&&this.dataFile(other)===dataFile))this.releaseData(dataFile);
+ const app = WebAppRuntime.storeOwner(s);
+ if (!this.ownerOpen(app)) {
+ for (const [file, store] of this.parsedStores) if (store.owner === app) this.dropStore(file);
+ }
s.controller.abort();
for (const c of s.requests.values()) c.abort();
this.host.closed?.(s.uid, { id: s.token, owner: s.owner });
@@ -163,9 +297,10 @@ export class WebAppRuntime {
}
cancel(uid: string, owner: number, token: string, requestId: string) {
const s = this.current(uid, owner, token);
+ if (s.bundle.browserOnly) return error('E_UNAVAILABLE');
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(requestId)) return error('E_INPUT');
// Tombstones also stop a cancellation arriving before its invoke.
- s.seen.add(requestId);
+ if (!s.seen.add(requestId)) return error('E_LIMIT');
s.requests.get(requestId)?.abort();
}
resource(host: string, rel: string, origin: string | null) {
@@ -182,15 +317,17 @@ export class WebAppRuntime {
async call(uid: string, owner: number, token: string, requestId: string, method: string, raw: unknown,
progress: (event: unknown) => void = () => {}) {
const s = this.current(uid, owner, token);
+ if (s.bundle.browserOnly) return error('E_UNAVAILABLE');
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(requestId)) return error('E_INPUT');
if (s.seen.has(requestId)) return error('E_DUPLICATE');
if (!Object.hasOwn(METHODS, method)) return error('E_METHOD');
- boundedJson(raw);
+ if(s.bundle.appType==='web'&&!commonMethod(method))return error('E_UNAVAILABLE');
+ boundedJson(raw,method.startsWith('data.')?1024*1024:MAX_PAYLOAD_BYTES);
const def = METHODS[method as Method];
const parsed = def.input.safeParse(raw);
if (!parsed.success) return error('E_INPUT');
if (!this.available(def.capability) || (this.preview && method === 'tools.call')) return error('E_UNAVAILABLE');
- s.seen.add(requestId);
+ if (!s.seen.add(requestId)) return error('E_LIMIT');
const controller = new AbortController();
s.requests.set(requestId, controller);
const signal = controller.signal;
@@ -201,7 +338,7 @@ export class WebAppRuntime {
this.check(s, signal); boundedJson(event, 64 * 1024); progress(event);
});
if (method !== 'permissions.revoke') this.check(s, signal);
- boundedJson(value);
+ boundedJson(value,method.startsWith('data.')?2*1024*1024:MAX_PAYLOAD_BYTES);
return value;
} catch (cause) {
// Owning services may reject with Error/AbortError rather than AppError.
@@ -227,25 +364,48 @@ export class WebAppRuntime {
try { if ((await fs.lstat(segment)).isSymbolicLink()) return error('E_FILE'); }
catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
}
+ const owner = WebAppRuntime.storeOwner(s);
+ // Cached entries are shared with later calls: read them, never mutate.
let entries: Record<string, unknown> = Object.create(null);
try {
- if ((await fs.stat(file)).size > STORE_BYTES) return error('E_LIMIT');
- const data = await fs.readFile(file);
- if (data.length > STORE_BYTES) return error('E_LIMIT');
- const saved = JSON.parse(data.toString('utf8'));
- if (saved.version !== 1 || !saved.entries || Array.isArray(saved.entries) || typeof saved.entries !== 'object') return error('E_STORAGE');
- entries = Object.assign(Object.create(null), saved.entries);
- } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
+ const st = await fs.stat(file);
+ if (st.size > STORE_BYTES) return error('E_LIMIT');
+ const signature = storeSignature(st);
+ const cached = this.parsedStores.get(file);
+ if (cached?.signature === signature) {
+ entries = cached.entries;
+ this.keepStore(file, cached);
+ } else {
+ const data = await fs.readFile(file);
+ if (data.length > STORE_BYTES) return error('E_LIMIT');
+ const saved = JSON.parse(data.toString('utf8'));
+ if (saved.version !== 1 || !saved.entries || Array.isArray(saved.entries) || typeof saved.entries !== 'object') return error('E_STORAGE');
+ entries = Object.assign(Object.create(null), saved.entries);
+ this.keepStore(file, { signature, owner, bytes: data.length, entries });
+ }
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
+ this.dropStore(file);
+ }
this.check(s, signal);
if (action === 'storage.get') return { value: Object.hasOwn(entries, input.key) ? entries[input.key] : null };
if (action === 'storage.keys') return { keys: Object.keys(entries).sort() };
- if (action === 'storage.set') entries[input.key] = input.value;
- else delete entries[input.key];
- const saved = { version: 1, entries };
- boundedJson(saved, STORE_BYTES);
- if (Buffer.byteLength(JSON.stringify(saved, null, 2)) > STORE_BYTES) return error('E_LIMIT');
- await writeJson(file, saved, { shouldCommit: () => { this.check(s, signal); return true; } });
+ const next: Record<string, unknown> = Object.assign(Object.create(null), entries);
+ if (action === 'storage.set') next[input.key] = input.value;
+ else delete next[input.key];
+ // One serialization: the written bytes are what the size and depth
+ // limits check (the indented form is never smaller than the compact one).
+ let json: string;
+ try { json = JSON.stringify({ version: 1, entries: next }, null, 2); } catch { return error('E_INPUT'); }
+ const bytes = Buffer.from(json);
+ if (bytes.length > STORE_BYTES || !jsonDepthWithin(json, 32)) return error('E_LIMIT');
+ await writeBytesAtomic(file, bytes, { shouldCommit: () => { this.check(s, signal); return true; } });
this.check(s, signal);
+ // Only sync also writes cloud files, and it could land between this
+ // write and a stat; those are re-read on their next call instead.
+ const written = this.preview || input.scope !== 'cloud' ? await fs.stat(file).catch(() => null) : null;
+ if (written) this.keepStore(file, { signature: storeSignature(written), owner, bytes: bytes.length, entries: next });
+ else this.dropStore(file);
this.changed(s, input.scope, file);
return action === 'storage.set' ? { saved: true } : { removed: true };
}); } finally { if (--lock.users === 0) this.stores.delete(file); }
@@ -327,12 +487,13 @@ export class WebAppRuntime {
}); } finally { if (--lock.users === 0) this.stores.delete(root); }
}
private async execute(s: Instance, method: Method, a: any, signal: AbortSignal, progress: (event: unknown) => void): Promise<any> {
+ if (method.startsWith('data.')) return this.dataCall(s,method,a,signal);
if (method.startsWith('appFiles.')) return this.appFiles(s, method, a, signal);
if (method.startsWith('storage.')) return this.store(s, method, a, signal);
switch (method) {
case 'host.getContext': return { language: this.host.language(), sdkVersion: SDK_VERSION, ...(this.preview ? { mode: 'preview' } : {}) };
- case 'capabilities.describe': return describeMethod(a.method) || error('E_METHOD');
- case 'capabilities.list': return { sdkVersion: SDK_VERSION, methods: Object.keys(METHODS).map(name => {
+ case 'capabilities.describe': return (s.bundle.appType!=='web'||commonMethod(a.method)) && describeMethod(a.method) || error('E_METHOD');
+ case 'capabilities.list': return { sdkVersion: SDK_VERSION, methods: Object.keys(METHODS).filter(name=>s.bundle.appType!=='web'||commonMethod(name)).map(name => {
const def = METHODS[name as Method];
return { name, capability: def.capability, supported: true,
available: this.available(def.capability) && !(this.preview && name === 'tools.call'),
diff --git a/src/main/features/web_apps/sdk.js b/src/main/features/web_apps/sdk.js
index 370c441b..0fdb4b95 100644
--- a/src/main/features/web_apps/sdk.js
+++ b/src/main/features/web_apps/sdk.js
@@ -3,6 +3,7 @@
'use strict';
const pending = new Map();
let hostConnected = false;
+ let hostDiscovery = null;
const documentId = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
let nextId = 0;
function fail(code, message) { return Object.assign(new Error(message || code), { code }); }
@@ -10,6 +11,14 @@
const opts = options || {};
if (window.parent === window) return Promise.reject(fail('E_HOST_UNAVAILABLE'));
if (opts.signal && opts.signal.aborted) return Promise.reject(fail('E_CANCELLED'));
+ const discoverBeforeInference = method === 'ai.generate' && !hostConnected;
+ let wireArgs = args === undefined ? {} : args;
+ if (discoverBeforeInference) {
+ // Preserve postMessage's call-time input snapshot while discovery waits.
+ try { wireArgs = structuredClone(wireArgs); }
+ catch (_) { return Promise.reject(fail(opts.signal && opts.signal.aborted ? 'E_CANCELLED' : 'E_INPUT')); }
+ if (opts.signal && opts.signal.aborted) return Promise.reject(fail('E_CANCELLED'));
+ }
const id = 'd' + documentId + 'q' + (++nextId);
return new Promise((resolve, reject) => {
const cancel = () => {
@@ -19,17 +28,31 @@
const finish = (ok, value) => {
const p = pending.get(id); if (!p) return;
pending.delete(id); clearTimeout(p.timer);
+ wireArgs = undefined;
if (opts.signal) opts.signal.removeEventListener('abort', cancel);
if (ok) resolve(value); else reject(fail(value.code || 'E_FAILED', value.message));
};
- const timer = hostConnected ? undefined : setTimeout(() => {
+ const timer = hostConnected || discoverBeforeInference ? undefined : setTimeout(() => {
parent.postMessage({ __orkasApp: 1, type: 'cancel', id }, '*');
finish(false, { code: 'E_HOST_UNAVAILABLE' });
}, 10000);
pending.set(id, { finish, timer, progress: opts.onProgress });
if (opts.signal) opts.signal.addEventListener('abort', cancel, { once: true });
- try { parent.postMessage({ __orkasApp: 1, type: 'call', id, method, args: args === undefined ? {} : args }, '*'); }
- catch (_) { finish(false, { code: 'E_INPUT' }); }
+ const send = () => {
+ if (!pending.has(id)) return; // Cancelled/departed while discovering.
+ try {
+ parent.postMessage({ __orkasApp: 1, type: 'call', id, method, args: wireArgs }, '*');
+ wireArgs = undefined;
+ }
+ catch (_) { finish(false, { code: 'E_INPUT' }); }
+ };
+ if (discoverBeforeInference) {
+ // A cold inference import can block the host's browser message routing.
+ // Establish the existing read-only connection before starting that work;
+ // the inference itself remains one request with no automatic replay.
+ if (!hostDiscovery) hostDiscovery = call('host.getContext').finally(() => { hostDiscovery = null; });
+ hostDiscovery.then(send, error => finish(false, { code: error.code || 'E_FAILED', message: error.message }));
+ } else send();
});
}
window.addEventListener('message', event => {
diff --git a/src/main/ipc/web_apps.ts b/src/main/ipc/web_apps.ts
index 83df3e12..57b3135b 100644
--- a/src/main/ipc/web_apps.ts
+++ b/src/main/ipc/web_apps.ts
@@ -16,6 +16,23 @@ function bindOwner(sender: WebContents) {
owners.add(sender);
sender.once('destroyed', () => runtime.closeOwner(sender.id));
sender.on('render-process-gone', () => runtime.closeOwner(sender.id));
+ // FrameTreeNode identity survives a cross-process document replacement.
+ // Track committed app documents, never a URL merely proposed for download.
+ const documents = new Map<number, string>();
+ sender.on('did-frame-navigate', (_event, url, _code, _status, isMainFrame, processId, routingId) => {
+ if (isMainFrame) { documents.clear(); runtime.closeOwner(sender.id); return; }
+ const frames = sender.mainFrame.framesInSubtree;
+ const current = frames.find(frame => frame.processId === processId && frame.routingId === routingId);
+ const live = new Set(frames.map(frame => frame.frameTreeNodeId));
+ for (const [node, source] of documents) {
+ if (!live.has(node)) { documents.delete(node); runtime.closeOrigin(sender.id, source); }
+ }
+ if (!current) return;
+ const node = current.frameTreeNodeId, previous = documents.get(node);
+ if (previous && (new URL(previous).protocol !== new URL(url).protocol || new URL(previous).host !== new URL(url).host)) runtime.closeOrigin(sender.id, previous);
+ if (url.startsWith('chat-app://app-')) documents.set(node, url);
+ else documents.delete(node);
+ });
sender.on('will-frame-navigate', event => {
if (event.isMainFrame) runtime.closeOwner(sender.id);
else {
@@ -29,7 +46,7 @@ function bindOwner(sender: WebContents) {
// Rejected navigation leaves the current document usable. Only an
// actual departure to a website revokes this application's authority.
if (!safeExternalHttpUrl(event.url)) event.preventDefault();
- else runtime.closeOrigin(sender.id, source);
+ // Actual departure is handled by did-frame-navigate above.
}
}
});
@@ -38,7 +55,7 @@ function credential(payload: any): string {
if (!payload || typeof payload.token !== 'string' || !/^[a-f0-9]{32}$/.test(payload.token)) throw new AppError('E_INPUT');
return payload.token;
}
-function failure(err: unknown) { const value = safeFailure(err); return { ok: false, error: value.message, code: value.code }; }
+function failure(err: unknown) { const value = safeFailure(err); return { ...value, ok: false, error: value.message }; }
export const webAppInvokeHandlers = {
'webApps.catalog': async () => ({ catalog: catalogDocument() }),
'webApps.open': async (payload: any, ctx: Context) => {
@@ -54,6 +71,10 @@ export const webAppInvokeHandlers = {
return opened;
} catch (err) { return failure(err); }
},
+ 'webApps.canSubmitArtifact': async (payload: any, ctx: Context) => {
+ try { return { allowed: runtime.canSubmitArtifact(ctx.userId, ctx.sender.id, credential(payload)) }; }
+ catch { return { allowed: false }; }
+ },
'webApps.close': async (payload: any, ctx: Context) => {
try { runtime.close(ctx.userId, ctx.sender.id, credential(payload)); return {}; } catch (err) { return failure(err); }
},
diff --git a/src/renderer/modules/chat-artifact.js b/src/renderer/modules/chat-artifact.js
index a81af941..3901782d 100644
--- a/src/renderer/modules/chat-artifact.js
+++ b/src/renderer/modules/chat-artifact.js
@@ -8,9 +8,8 @@
// 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.source` is one of our live artifact iframes, its origin matches
+// the registered chat-app origin (even after iframe navigation), 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
@@ -43,15 +42,15 @@
// 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 (_) {}
+ function _t(key, fallback, vars) {
+ try { if (typeof t === 'function') { const v = t(key, vars); 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);
+ if (typeof uiAlert === 'function') uiAlert(msg ? _t('artifact.failure_detail', `${prefix}: ${msg}`, { action: prefix, detail: msg }) : prefix);
else _convLog.warn(prefix, msg);
} catch (_) {}
}
@@ -80,24 +79,6 @@
return { error_type: errorType, error_code: errorCode };
}
- function _artifactSaveSourceView(cid) {
- try {
- return (typeof _projectIdForConversation === 'function' && _projectIdForConversation(cid))
- ? 'project'
- : 'conversation';
- } catch (_) {
- return 'conversation';
- }
- }
-
- function _logArtifactSaveResult(startedAt, result, sourceView, failure = {}) {
- if (result === 'success') return;
- _logArtifactFailure('artifact_save', {
- source_view: sourceView,
- duration_ms: Math.max(0, Date.now() - startedAt),
- ...failure,
- });
- }
function _logArtifactSaveFailure(failure) {
_logArtifactFailure('artifact_save', failure);
@@ -123,6 +104,8 @@
let json = '';
try { json = JSON.stringify(payload); } catch (_) { json = '"<unserialisable>"'; }
if (typeof json !== 'string') json = String(json);
+ // JSON Unicode escapes preserve values while keeping payload text inside its tag.
+ json = json.replace(/</g, '\\u003c');
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
@@ -148,7 +131,12 @@
function _bindGlobalListener() {
if (_listenerBound) return;
_listenerBound = true;
- window.addEventListener('message', (ev) => {
+ window.addEventListener('i18n-change', () => {
+ for (const tag of document.querySelectorAll('.chat-artifact-header .chat-app-type-tag')) {
+ _updateAppTypeTag(tag, tag.dataset.appType);
+ }
+ });
+ window.addEventListener('message', async (ev) => {
const frame = _findArtifactFrame(ev.source);
if (!frame || !artifactSecurity.trustedArtifactMessage(ev, frame)) return;
const data = ev.data;
@@ -157,7 +145,7 @@
const agentId = frame.dataset.artifactAgent || '';
const title = frame.dataset.artifactTitle || '';
const type = String(data.type || '');
- if (window.OrkasWebAppHost.isManaged(frame) && type !== 'resize') return;
+ if (window.OrkasWebAppHost.isManaged(frame) && !['resize', 'submit', 'sendToChat'].includes(type)) return;
if (type === 'resize') {
if (frame.classList && frame.classList.contains('chat-artifact-viewer-frame')) return;
frame.style.height = `${_clampHeight(data.height)}px`;
@@ -172,8 +160,14 @@
// 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); }
+ try {
+ if (window.OrkasWebAppHost.isManaged(frame) && !await window.OrkasWebAppHost.canSubmitArtifact(frame)) return;
+ // An async lifetime check must not redirect a result after a task switch or reload.
+ if (!frame.isConnected || cid !== currentCid || frame.dataset.artifactCid !== cid
+ || frame.dataset.artifactId !== artifactId || !artifactSecurity.trustedArtifactMessage(ev, frame)) return;
+ const text = encodeArtifactResult(artifactId, agentId, title, data.payload);
+ await sendInCurrentConversation(text);
+ }
catch (err) { try { _convLog.warn('artifact result send failed', err && err.message ? err.message : err); } catch (_) {} }
return;
}
@@ -256,9 +250,14 @@
return el;
}
- function _openViewer(ctx) {
+ async function _openViewer(ctx) {
if (!ctx || !ctx.cid || !ctx.artifactId) return;
- if (window.OrkasPreviewWindows) return window.OrkasPreviewWindows.open({ kind: 'artifact', cid: ctx.cid, artifactId: ctx.artifactId, agentId: ctx.agentId || '', title: ctx.title || _t('artifact.title', 'Interactive app') });
+ if (ctx.frame?._orkasCommercial || ctx.frame?.dataset.appType === 'web') return window.OrkasCommercialEntry.show();
+ if (window.OrkasPreviewWindows) {
+ const result = await window.OrkasPreviewWindows.open({ kind: 'artifact', cid: ctx.cid, artifactId: ctx.artifactId, agentId: ctx.agentId || '', title: ctx.title || _t('artifact.title', 'Interactive app') });
+ if (window.OrkasCommercialEntry.isFailure(result)) return window.OrkasCommercialEntry.show();
+ return result;
+ }
_bindGlobalListener();
const el = _ensureViewer();
const title = ctx.title || _t('artifact.title', 'Interactive app');
@@ -268,12 +267,14 @@
_viewerFrame.dataset.artifactId = String(ctx.artifactId);
_viewerFrame.dataset.artifactAgent = String(ctx.agentId || '');
_viewerFrame.dataset.artifactTitle = title;
+ _viewerFrame.dataset.appType = '';
_viewerFrame.setAttribute('title', title);
window.OrkasWebAppHost.open(_viewerFrame, { cid: ctx.cid, artifactId: ctx.artifactId });
+ _checkArtifactAvailability(_viewerFrame, ctx);
}
el.classList.add('is-open');
if (!_viewerKeyHandler) {
- _viewerKeyHandler = (e) => { if (e.key === 'Escape' && !document.querySelector('.chat-share-overlay')) _closeViewer(); };
+ _viewerKeyHandler = (e) => { if (e.key === 'Escape') _closeViewer(); };
document.addEventListener('keydown', _viewerKeyHandler);
}
}
@@ -350,15 +351,29 @@
el.style.top = top + 'px';
}
- function _openMenu(anchorBtn, ctx) {
+ async 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');
+ await _checkArtifactAvailability(ctx.frame, ctx);
+ if (_menuCtx !== ctx || _menuAnchor !== anchorBtn) return;
_renderMenuItems(el);
_positionMenu(el, anchorBtn);
+ try {
+ const result = await window.orkas.invoke('conversations.artifacts.editTarget', { cid: String(ctx.cid) });
+ if (result?.target && _menuCtx === ctx && el.style.display !== 'none') {
+ const save = el.querySelector('[data-action="save"]');
+ if (save) save.textContent = _t('apps.save_new', 'Save new app');
+ const update = document.createElement('div');update.className='chat-artifact-menu-item';update.dataset.action='update';
+ update.textContent=_t('apps.update_original', 'Update original app');update.title=result.target.title;
+ update.onclick=event=>{event.stopPropagation();_closeMenu();_doSave({...ctx,saveMode:'update'});};
+ if (save) el.insertBefore(update,save);else el.appendChild(update);
+ }
+ } catch (_) { /* Older hosts preserve the existing Save action. */ }
+ if (_menuCtx === ctx && _menuAnchor === anchorBtn) _positionMenu(el, anchorBtn);
}
function _clearArtifactUnavailable(frame) {
@@ -369,7 +384,20 @@
frame.style.display = 'block';
}
- function _showArtifactUnavailable(frame, reason) {
+ function _showCommercialUnavailable(frame) {
+ frame._orkasCommercial = true;
+ frame.dataset.appType = 'web';
+ _updateAppTypeTag(frame.parentNode?.querySelector('.chat-app-type-tag'), 'web');
+ _clearArtifactUnavailable(frame);
+ const panel = document.createElement('div');
+ panel.className = 'chat-artifact-unavailable';
+ window.OrkasCommercialEntry.appendNotice(panel);
+ frame._orkasUnavailablePanel = panel;
+ frame.parentNode?.insertBefore(panel, frame.nextSibling);
+ frame.style.display = 'none';
+ }
+
+ function _showArtifactUnavailable(frame, reason, retry) {
if (!frame || !frame.parentNode) return;
let panel = frame._orkasUnavailablePanel;
if (!panel) {
@@ -381,20 +409,42 @@
panel.innerHTML = '';
const title = document.createElement('div');
title.className = 'chat-artifact-unavailable-title';
- title.textContent = _t('artifact.unavailable_title', 'App content incomplete');
+ title.textContent = retry ? _t('artifact.open_failed', 'Could not open') : _t('artifact.unavailable_title', 'App content incomplete');
const detail = document.createElement('div');
detail.className = 'chat-artifact-unavailable-detail';
detail.textContent = _t('artifact.unavailable_detail', 'This saved app only retains a summarized conversation record, not the complete app. Regenerate the app to preview it.');
panel.appendChild(title);
- panel.appendChild(detail);
+ if (!retry) panel.appendChild(detail);
+ if (retry) {
+ const button = document.createElement('button');
+ button.className = 'btn btn-sm';
+ button.type = 'button';
+ button.textContent = _t('artifact.reload', 'Reload');
+ button.addEventListener('click', retry);
+ const actions = document.createElement('div');
+ actions.className = 'header-actions';
+ actions.appendChild(button);
+ panel.appendChild(actions);
+ }
if (reason) panel.title = String(reason);
frame.removeAttribute('src');
frame.style.display = 'none';
}
+ function _updateAppTypeTag(tag, type) {
+ if (!tag) return;
+ if (type === 'cloud') type = 'web';
+ const known = type === 'local' || type === 'web';
+ tag.hidden = !known;
+ tag.dataset.appType = known ? type : '';
+ tag.textContent = known ? _t('apps.type_' + type, type === 'web' ? 'Web app' : 'Local app') : '';
+ }
+
async function _checkArtifactAvailability(frame, ctx) {
if (!frame || !ctx || !ctx.cid || !ctx.artifactId) return;
if (!window.orkas || typeof window.orkas.invoke !== 'function') return;
+ const inspection = {};
+ frame._orkasInspection = inspection;
const expectedCid = String(ctx.cid);
const expectedArtifactId = String(ctx.artifactId);
try {
@@ -402,12 +452,18 @@
cid: expectedCid,
artifactId: expectedArtifactId,
});
- if (!frame.isConnected) return;
+ if (!frame.isConnected || frame._orkasInspection !== inspection) return;
if (frame.dataset.artifactCid !== expectedCid || frame.dataset.artifactId !== expectedArtifactId) return;
+ if (frame._orkasLoadFailed) return;
if (r && r.ok === true && r.status === 'unavailable') {
+ frame.dataset.appType = '';
+ _updateAppTypeTag(frame.parentNode?.querySelector('.chat-app-type-tag'), '');
_showArtifactUnavailable(frame, r.reason || '');
} else if (r && r.ok === true && r.status === 'ok') {
+ frame.dataset.appType = r.appType || '';
+ if (r.appType === 'web' || r.appType === 'cloud') { _showCommercialUnavailable(frame); return; }
_clearArtifactUnavailable(frame);
+ _updateAppTypeTag(frame.parentNode?.querySelector('.chat-app-type-tag'), r.appType);
}
} catch (err) {
_logArtifactFailure('artifact_inspect', { error_message: String(err && err.message || err) });
@@ -416,47 +472,72 @@
function _doReload(ctx) {
const f = ctx && ctx.frame;
+ if (f?._orkasCommercial || f?.dataset.appType === 'web') return window.OrkasCommercialEntry.show();
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._orkasLoadFailed = false;
_clearArtifactUnavailable(f);
f.style.height = `${DEFAULT_FRAME_HEIGHT}px`;
window.OrkasWebAppHost.open(f, { cid: ctx.cid, artifactId: ctx.artifactId });
_checkArtifactAvailability(f, ctx);
}
- function _doOpen(ctx) {
- try { _openViewer(ctx); }
+ async function _doOpen(ctx) {
+ try { await _openViewer(ctx); }
catch (err) { _logArtifactFailure('artifact_open_viewer', { error_message: String(err && err.message || err) }); _notifyFail(_t('artifact.open_failed', 'Could not open'), err); }
}
async function _doSave(ctx) {
- const startedAt = Date.now();
- const sourceView = _artifactSaveSourceView(ctx?.cid);
+ if (ctx.frame?._orkasCommercial || ctx.frame?.dataset.appType === 'web') return window.OrkasCommercialEntry.show();
+
+
let r;
try {
r = await window.orkas.invoke('conversations.artifacts.save', {
cid: String(ctx.cid), artifactId: String(ctx.artifactId),
+ mode: ctx.saveMode || 'new',
});
+ if(r?.code==='app_edit_data_migration'&&ctx.saveMode==='update'){
+ const args={cid:String(ctx.cid),artifactId:String(ctx.artifactId)};
+ const impact=await window.orkas.invoke('conversations.artifacts.dataImpact',args);
+ if(window.OrkasCommercialEntry.isFailure(impact)) return window.OrkasCommercialEntry.show();
+ if(impact.ok){
+ const scope=impact.tables.map(table=>`${table.name}: ${table.count} (${table.fields.join(', ')})`).join('\n');
+ const exportFirst=await uiConfirm({message:_t('apps.migration_export')+'\n'+scope,okLabel:_t('apps.migration_export_action'),cancelLabel:_t('apps.migration_continue')});
+ if(exportFirst){const exported=await window.orkas.invoke('conversations.artifacts.exportData',args);if(window.OrkasCommercialEntry.isFailure(exported)) return window.OrkasCommercialEntry.show();if(!exported.ok||exported.canceled){if(!exported.canceled)_logArtifactSaveFailure(_artifactSaveFailure(exported,'operation'));return;}}
+ const confirmed=await uiConfirmDanger({message:_t('apps.migration_clear')+'\n'+scope,dangerLabel:_t('apps.migration_retry')});
+ if(!confirmed){return;}
+ r=await window.orkas.invoke('conversations.artifacts.save',{...args,mode:'update',recovery:{clearVersion:impact.version,clearFingerprint:impact.fingerprint}});
+ }
+ }
} catch (err) {
const failure = _artifactSaveFailure(err, 'ipc');
- _logArtifactSaveResult(startedAt, 'failure', sourceView, failure);
+
_logArtifactSaveFailure(failure);
_notifyFail(_t('apps.save_failed', 'Could not save the app'), err);
return;
}
if (!r || r.ok === false) {
+ if (window.OrkasCommercialEntry.isFailure(r)) return window.OrkasCommercialEntry.show();
const failure = _artifactSaveFailure(r, 'operation');
- _logArtifactSaveResult(startedAt, 'failure', sourceView, failure);
+
_logArtifactSaveFailure(failure);
- _notifyFail(_t('apps.save_failed', 'Could not save the app'), { message: (r && r.error) || 'save failed' });
+ const recovery = r?.code === 'app_type_mismatch'
+ ? _t('apps.save_type_mismatch', 'This version is a different app type from the original app, so it can’t replace it. Save it as a new app instead.')
+ : r?.code === 'app_edit_conflict' || r?.code === 'app_edit_target_missing'
+ ? _t('apps.edit_conflict', 'The original app changed or was deleted. Reopen it to edit, or save a new app.') : (r && r.error) || '';
+ _notifyFail(_t('apps.save_failed', 'Could not save the app'), { message: recovery });
return;
}
- _logArtifactSaveResult(startedAt, 'success', sourceView);
+
try {
- const message = _t('apps.saved_toast', 'Saved to Apps');
+ const name = r.title || ctx.title || _t('artifact.title', 'Interactive app');
+ const message = ctx.saveMode === 'update'
+ ? _t('apps.updated_toast', `Updated ${name}`, { name })
+ : _t('apps.saved_toast', 'Saved to Apps');
if (typeof uiToast === 'function') uiToast(message, { variant: 'success' });
else if (typeof uiAlert === 'function') uiAlert(message);
// Refresh the "My Apps" tab if its module is loaded.
@@ -487,6 +568,9 @@
titleEl.className = 'chat-artifact-title';
titleEl.textContent = title;
titleEl.title = title;
+ const typeTag = document.createElement('span');
+ typeTag.className = 'conv-status-badge chat-app-type-tag';
+ typeTag.hidden = true;
const spacer = document.createElement('span');
spacer.className = 'chat-artifact-spacer';
// All header actions live behind a single "⋯" popover (reload / open /
@@ -498,6 +582,7 @@
moreBtn.title = _t('artifact.more', 'More');
moreBtn.setAttribute('aria-label', _t('artifact.more', 'More'));
header.appendChild(titleEl);
+ header.appendChild(typeTag);
header.appendChild(spacer);
header.appendChild(moreBtn);
@@ -511,6 +596,12 @@
frame.dataset.artifactAgent = String(ctx.agentId || '');
frame.dataset.artifactTitle = title;
frame.style.height = `${DEFAULT_FRAME_HEIGHT}px`;
+ frame.addEventListener('orkas-app-error', event => {
+ event.preventDefault();
+ if (window.OrkasCommercialEntry.isFailure(event.detail)) { _showCommercialUnavailable(frame); return; }
+ frame._orkasLoadFailed = true;
+ _showArtifactUnavailable(frame, '', () => _doReload({ ...ctx, frame }));
+ });
window.OrkasWebAppHost.open(frame, { cid: ctx.cid, artifactId: ctx.artifactId });
moreBtn.addEventListener('click', (e) => {
diff --git a/src/renderer/modules/commercial-entry.js b/src/renderer/modules/commercial-entry.js
new file mode 100644
index 00000000..178aca21
--- /dev/null
+++ b/src/renderer/modules/commercial-entry.js
@@ -0,0 +1,78 @@
+(function () {
+ const seenTurns = new Map();
+ const seenMessages = new WeakSet();
+ let dialog = null;
+ const text = key => t(key);
+ const isFailure = value => value?.ok === false && value?.code === 'E_COMMERCIAL_REQUIRED' && value?.feature === 'web_apps';
+ function webLanguage() {
+ const language = typeof getLang === 'function' ? getLang() : 'en';
+ if (language === 'zh' || language === 'zh-tw') return 'zh';
+ if (language === 'pt-pt') return 'pt';
+ return ['en', 'ja', 'pt'].includes(language) ? language : 'en';
+ }
+ async function download() {
+ const url = new URL('https://orkas.ai/download/');
+ url.searchParams.set('lang', webLanguage());
+ try {
+ const result = await window.orkas.invoke('auth.openExternal', { url: url.href });
+ if (!result?.ok) throw new Error('open_failed');
+ } catch (_) { await uiAlert(text('apps.commercial_open_failed')); }
+ }
+ function show() {
+ if (dialog) return dialog;
+ const focus = document.activeElement;
+ dialog = (async () => {
+ if (await uiConfirm({ message: text('apps.commercial_required'),
+ okLabel: text('apps.commercial_download'), cancelLabel: text('common.cancel') })) await download();
+ })().finally(() => {
+ dialog = null;
+ if (focus?.isConnected) focus.focus({ preventScroll: true });
+ });
+ return dialog;
+ }
+ function receipt(value, depth = 0) {
+ if (depth > 3) return null;
+ if (isFailure(value)) return value;
+ if (typeof value === 'string' && value.length <= 65536) {
+ try { return receipt(JSON.parse(value), depth + 1); } catch (_) { return null; }
+ }
+ if (value && typeof value === 'object') {
+ if (typeof value.content === 'string') return receipt(value.content, depth + 1);
+ if (Array.isArray(value.content)) {
+ for (const part of value.content.slice(0, 8)) {
+ if (part?.type === 'text') { const found = receipt(part.text, depth + 1); if (found) return found; }
+ }
+ }
+ }
+ return null;
+ }
+ function appendNotice(host) {
+ const row = document.createElement('div');
+ row.className = 'chat-app-nav-row';
+ const label = document.createElement('span');
+ label.dataset.i18n = 'apps.commercial_required';
+ label.textContent = text('apps.commercial_required');
+ const button = document.createElement('button');
+ button.type = 'button'; button.className = 'chat-app-nav-btn';
+ button.dataset.i18n = 'apps.commercial_download';
+ button.textContent = text('apps.commercial_download');
+ button.addEventListener('click', download);
+ row.append(label, button); host.appendChild(row);
+ return row;
+ }
+ function observeToolResult(message, event) {
+ const data = event?.data;
+ if (event?.stream !== 'tool' || data?.phase !== 'end' || data.name !== 'create_artifact'
+ || data.isError !== true || !receipt(data.output) || !message) return;
+ const cid = message.dataset?.cid || (typeof currentCid === 'string' ? currentCid : '');
+ const turn = message.dataset?.turnId;
+ const key = turn ? JSON.stringify([cid, turn]) : null;
+ if (key ? seenTurns.has(key) : seenMessages.has(message)) return;
+ if (key) {
+ seenTurns.set(key, true);
+ if (seenTurns.size > 128) seenTurns.delete(seenTurns.keys().next().value);
+ } else seenMessages.add(message);
+ appendNotice(message.querySelector('.chat-bubble') || message);
+ }
+ window.OrkasCommercialEntry = { show, download, isFailure, appendNotice, observeToolResult };
+})();
diff --git a/src/renderer/modules/preview-windows.js b/src/renderer/modules/preview-windows.js
index 54989c63..141ccadd 100644
--- a/src/renderer/modules/preview-windows.js
+++ b/src/renderer/modules/preview-windows.js
@@ -5,6 +5,7 @@
async function open(source) {
try {
const result = await window.orkas.invoke('previewWindows.open', source);
+ if (window.OrkasCommercialEntry?.isFailure(result)) return result;
if (!result?.ok) throw new Error('preview_open_failed');
return result;
} catch (_) {
diff --git a/src/renderer/modules/saved-apps.js b/src/renderer/modules/saved-apps.js
index d3c4dc58..1c50ec5c 100644
--- a/src/renderer/modules/saved-apps.js
+++ b/src/renderer/modules/saved-apps.js
@@ -4,7 +4,7 @@
// Apps land here via the chat-bubble artifact card's `⋯` → "Save" or via
// "Save as app" on a generated HTML bundle. Clicking a card opens the saved
// bundle in an in-app floating iframe over `chat-app://saved/...`; the per-card
-// `⋯` menu has edit / rename / delete.
+// `⋯` menu has rename / edit / share or publication actions / delete.
//
// Classic script — no import/export. Global `loadSavedApps` is exposed via
// `window.*`. Loaded after `agents.js` in index.html.
@@ -14,6 +14,9 @@
if (!artifactSecurity) throw new Error('artifact-security.js must load before saved-apps.js');
const _appsLog = (typeof createLogger === 'function') ? createLogger('saved-apps') : { warn: () => {}, error: () => {} };
let _appsCache = null; // last fetched list (for the i18n-change re-render)
+ let _appsLoadGeneration = 0;
+ let _appsFilter = 'local';
+ const _appsFilters = [['local', 'apps.type_local'], ['web', 'apps.type_web']];
let _appViewerEl = null;
let _appViewerFrame = null;
let _appViewerTitle = null;
@@ -28,12 +31,10 @@
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 (_) {}
+ // Raw failures can carry local paths and internals; callers record only the
+ // stable failure code, and the user sees only the localized action copy.
+ function _fail(message) {
+ try { if (typeof uiAlert === 'function') uiAlert(message); } catch (_) {}
}
const _SAVED_APP_STABLE_ERROR_CODES = new Set([
@@ -78,30 +79,6 @@
_appsLog.warn('saved app operation failed', { action, ...(data || {}) });
}
- function _logManageResult(startedAt, action, result, failure = {}) {
- const payload = {
- result,
- action,
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result !== 'success') Object.assign(payload, failure);
- if (result === 'failure') {
- _appsLogFailure('saved_app_manage', {
- action,
- error_type: payload.error_type,
- error_code: payload.error_code,
- });
- }
- }
-
- function _logOpenResult(startedAt, result, failure = {}) {
- const payload = {
- result,
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result !== 'success') Object.assign(payload, failure);
- if (result === 'failure') _appsLogFailure('saved_app_open', failure);
- }
function _esc(s) {
return String(s == null ? '' : s)
@@ -187,18 +164,26 @@
let _rowMenuEl = null;
let _rowMenuAppId = null;
let _rowMenuAnchor = null;
+ // Items for a non-card owner (publication data actions) sharing this menu.
+ let _rowMenuCustom = null;
- function _closeRowMenu() {
+ function _closeRowMenu(restoreFocus = false) {
+ const anchor = _rowMenuAnchor;
if (_rowMenuEl) _rowMenuEl.style.display = 'none';
+ anchor?.setAttribute('aria-expanded', 'false');
for (const el of document.querySelectorAll('.app-card.is-menu-open')) el.classList.remove('is-menu-open');
_rowMenuAppId = null;
_rowMenuAnchor = null;
+ _rowMenuCustom = null;
+ if (restoreFocus === true && anchor?.isConnected) _uiRestoreDialogFocus(anchor, { preventScroll: true });
}
function _ensureRowMenuEl() {
if (_rowMenuEl) return _rowMenuEl;
const el = document.createElement('div');
el.className = 'app-row-menu';
+ el.setAttribute('role', 'menu');
+ el.tabIndex = -1;
el.style.display = 'none';
document.body.appendChild(el);
document.addEventListener('click', (e) => {
@@ -207,7 +192,24 @@
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(); });
+ document.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229 || el.style.display === 'none') return;
+ if (e.key === 'Escape') { e.preventDefault(); _closeRowMenu(true); }
+ });
+ el.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ const items = [...el.querySelectorAll('[role="menuitem"]:not(:disabled)')];
+ const current = items.indexOf(document.activeElement);
+ let next;
+ if (e.key === 'ArrowDown') next = (current + 1) % items.length;
+ else if (e.key === 'ArrowUp') next = (current - 1 + items.length) % items.length;
+ else if (e.key === 'Home') next = 0;
+ else if (e.key === 'End') next = items.length - 1;
+ else if (e.key === 'Tab') { _closeRowMenu(true); return; }
+ else return;
+ e.preventDefault();
+ items[next]?.focus({ preventScroll: true });
+ });
window.addEventListener('scroll', _closeRowMenu, true);
window.addEventListener('resize', _closeRowMenu);
window.addEventListener('i18n-change', _closeRowMenu);
@@ -232,63 +234,105 @@
el.style.top = top + 'px';
}
+ function _appendRowMenuItem(el, action, label, danger, disabled, onSelect) {
+ const it = document.createElement('button');
+ it.type = 'button';
+ it.setAttribute('role', 'menuitem');
+ it.tabIndex = -1;
+ it.className = 'app-row-menu-item' + (danger ? ' is-danger' : '');
+ it.dataset.action = action;
+ it.textContent = label;
+ it.disabled = !!disabled;
+ it.addEventListener('click', (e) => { e.stopPropagation(); onSelect(); });
+ el.appendChild(it);
+ }
+
function _renderRowMenuItems(el) {
el.innerHTML = '';
+ if (_rowMenuCustom) {
+ for (const item of _rowMenuCustom.items) {
+ _appendRowMenuItem(el, item.action, item.label, item.danger, item.disabled, () => {
+ if (item.disabled) return;
+ _closeRowMenu(true);
+ item.onSelect();
+ });
+ }
+ return;
+ }
+ const app = (_appsCache || []).find(row => row.id === _rowMenuAppId);
const defs = [
- ['edit', _t('apps.edit', 'Edit'), false],
['rename', _t('apps.rename', 'Rename'), false],
+ ['edit', _t('apps.edit', 'Edit'), false],
+ ['publish', _t('apps.publish_action', 'Publish'), 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();
+ _appendRowMenuItem(el, action, label, danger, false, () => {
const id = _rowMenuAppId;
- _closeRowMenu();
+ _closeRowMenu(true);
if (!id) return;
- if (action === 'edit') _editApp(id);
+ if (action === 'publish') void window.OrkasCommercialEntry?.show();
+ else 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; }
+ if (el.style.display !== 'none' && _rowMenuAppId === appId) { _closeRowMenu(true); return; }
_closeRowMenu();
_rowMenuAppId = appId;
_rowMenuAnchor = anchorBtn;
+ anchorBtn.setAttribute('aria-expanded', 'true');
const card = anchorBtn.closest && anchorBtn.closest('.app-card');
if (card) card.classList.add('is-menu-open');
_renderRowMenuItems(el);
_positionRowMenu(el, anchorBtn);
+ el.querySelector('[role="menuitem"]')?.focus({ preventScroll: true });
}
+ /** Shared three-dot menu for another owner: items are
+ * { action, label, danger?, disabled?, onSelect }. Keyboard, dismissal and
+ * focus restoration match the app-card menu. */
+ function _toggleActionMenu(anchorBtn, items) {
+ const el = _ensureRowMenuEl();
+ if (el.style.display !== 'none' && _rowMenuAnchor === anchorBtn) { _closeRowMenu(true); return; }
+ _closeRowMenu();
+ _rowMenuCustom = { items: Array.isArray(items) ? items : [] };
+ _rowMenuAnchor = anchorBtn;
+ anchorBtn.setAttribute('aria-expanded', 'true');
+ _renderRowMenuItems(el);
+ _positionRowMenu(el, anchorBtn);
+ (el.querySelector('[role="menuitem"]:not(:disabled)') || el).focus({ preventScroll: true });
+ }
+ window.AppActionMenu = { toggle: _toggleActionMenu, close: () => { if (_rowMenuCustom) _closeRowMenu(); } };
+
// ── actions ─────────────────────────────────────────────────────────────
async function _openApp(appId) {
- const startedAt = Date.now();
+ const selected = (_appsCache || []).find(row => row.id === appId);
+ if (selected && _appType(selected) === 'web') return window.OrkasCommercialEntry.show();
+
if (window.OrkasPreviewWindows) {
const app = (_appsCache || []).find(item => item.id === appId);
const result = await window.OrkasPreviewWindows.open({ kind: 'app', appId, title: app?.title || _t('artifact.title', 'Interactive app') });
- _logOpenResult(startedAt, result?.ok ? 'success' : 'failure', result?.ok ? {} : { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
+ if (window.OrkasCommercialEntry.isFailure(result)) return window.OrkasCommercialEntry.show();
+ if (!result?.ok) _appsLogFailure('saved_app_open', { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
return;
}
let r;
try {
r = await window.orkas.invoke('savedApps.openInApp', { appId: String(appId) });
} catch (err) {
- _logOpenResult(startedAt, 'failure', _savedAppFailure(err, 'saved_app_open_failed', 'ipc'));
+ _appsLogFailure('saved_app_open', _savedAppFailure(err, 'saved_app_open_failed', 'ipc'));
_fail(_t('apps.open_failed', 'Could not open the app'), err);
return;
}
if (!r || r.ok === false || !r.url) {
+ if (window.OrkasCommercialEntry.isFailure(r)) return window.OrkasCommercialEntry.show();
const failure = _savedAppFailure(r, r && r.ok === false ? 'saved_app_open_failed' : 'invalid_response');
- _logOpenResult(startedAt, 'failure', failure);
+ _appsLogFailure('saved_app_open', failure);
_fail(_t('apps.open_failed', 'Could not open the app'), { message: (r && r.error) || 'open failed' });
return;
}
@@ -299,7 +343,7 @@
_fail(_t('apps.open_failed', 'Could not open the app'), err);
return;
}
- _logOpenResult(startedAt, 'success');
+
}
// "Edit" — backend creates a fresh conversation with the app's source bundled
@@ -309,34 +353,37 @@
window.openSavedAppPreview = _openAppViewer;
async function _editApp(appId) {
- const startedAt = Date.now();
+ const selected = (_appsCache || []).find(row => row.id === appId);
+ if (selected && _appType(selected) === 'web') return window.OrkasCommercialEntry.show();
+
let r;
try {
r = await window.orkas.invoke('savedApps.openForEditing', { appId: String(appId) });
} catch (err) {
- _logManageResult(startedAt, 'edit', 'failure', _savedAppFailure(err, 'saved_app_edit_failed', 'ipc'));
+ _appsLogFailure('saved_app_manage', { action: 'edit', ..._savedAppFailure(err, 'saved_app_edit_failed', 'ipc') });
_fail(_t('apps.edit_failed', 'Could not open an edit conversation'), err);
return;
}
if (!r || r.ok === false) {
- _logManageResult(startedAt, 'edit', 'failure', _savedAppFailure(r, 'saved_app_edit_failed'));
+ if (window.OrkasCommercialEntry.isFailure(r)) return window.OrkasCommercialEntry.show();
+ _appsLogFailure('saved_app_manage', { action: 'edit', ..._savedAppFailure(r, 'saved_app_edit_failed') });
_fail(_t('apps.edit_failed', 'Could not open an edit conversation'), { message: (r && r.error) || 'open-for-editing failed' });
return;
}
const conv = r.conversation;
if (!conv || !conv.conversation_id) {
- _logManageResult(startedAt, 'edit', 'failure', _savedAppFailure(r, 'invalid_response'));
+ _appsLogFailure('saved_app_manage', { action: 'edit', ..._savedAppFailure(r, 'invalid_response') });
_fail(_t('apps.edit_failed', 'Could not open an edit conversation'));
return;
}
- _logManageResult(startedAt, 'edit', 'success');
+
// Add to the sidebar list. Set last_active_at explicitly — backend
// create response doesn't include the derived field, so timeBucket
// would otherwise put this brand-new row in the 'older' bucket.
try {
if (typeof conversations !== 'undefined' && Array.isArray(conversations)) {
conv.last_active_at = new Date().toISOString();
- conversations.unshift(conv);
+ _cacheCreatedConversation(conv);
if (typeof renderConversationList === 'function') renderConversationList();
}
} catch (_) {}
@@ -375,21 +422,21 @@
if (next == null) return; // cancelled
next = String(next).trim();
if (!next || (cur && next === cur.title)) return;
- const startedAt = Date.now();
+
let r;
try {
r = await window.orkas.invoke('savedApps.rename', { appId: String(appId), title: next });
} catch (err) {
- _logManageResult(startedAt, 'rename', 'failure', _savedAppFailure(err, 'saved_app_rename_failed', 'ipc'));
+ _appsLogFailure('saved_app_manage', { action: 'rename', ..._savedAppFailure(err, 'saved_app_rename_failed', 'ipc') });
_fail(_t('apps.rename_failed', 'Could not rename'), err);
return;
}
if (!r || r.ok === false) {
- _logManageResult(startedAt, 'rename', 'failure', _savedAppFailure(r, 'saved_app_rename_failed'));
+ _appsLogFailure('saved_app_manage', { action: 'rename', ..._savedAppFailure(r, 'saved_app_rename_failed') });
_fail(_t('apps.rename_failed', 'Could not rename'), { message: (r && r.error) || 'rename failed' });
return;
}
- _logManageResult(startedAt, 'rename', 'success');
+
try { loadSavedApps(true); } catch (_) {
_appsLogFailure('saved_app_refresh', { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
}
@@ -398,33 +445,34 @@
async function _deleteApp(appId) {
const cur = (_appsCache || []).find((a) => a.id === appId);
const name = (cur && cur.title) || _t('artifact.title', 'Interactive app');
+ const message=_t('apps.delete_data_confirm','Delete "{name}" and its local data? Data cannot be recovered.',{name});
let ok = false;
try {
if (typeof uiConfirmDanger === 'function') {
ok = await uiConfirmDanger({
- message: _t('apps.delete_confirm', 'Delete "{name}"?', { name }),
+ message,
dangerLabel: _t('apps.delete', 'Delete'),
});
} else if (typeof uiConfirm === 'function') {
- ok = await uiConfirm(_t('apps.delete_confirm', 'Delete "{name}"?', { name }));
+ ok = await uiConfirm(message);
} else { ok = true; }
} catch (_) { ok = false; }
if (!ok) return;
- const startedAt = Date.now();
+
let r;
try {
r = await window.orkas.invoke('savedApps.delete', { appId: String(appId) });
} catch (err) {
- _logManageResult(startedAt, 'delete', 'failure', _savedAppFailure(err, 'saved_app_delete_failed', 'ipc'));
+ _appsLogFailure('saved_app_manage', { action: 'delete', ..._savedAppFailure(err, 'saved_app_delete_failed', 'ipc') });
_fail(_t('apps.delete_failed', 'Could not delete'), err);
return;
}
if (!r || r.ok === false) {
- _logManageResult(startedAt, 'delete', 'failure', _savedAppFailure(r, 'saved_app_delete_failed'));
+ _appsLogFailure('saved_app_manage', { action: 'delete', ..._savedAppFailure(r, 'saved_app_delete_failed') });
_fail(_t('apps.delete_failed', 'Could not delete'), { message: (r && r.error) || 'delete failed' });
return;
}
- _logManageResult(startedAt, 'delete', 'success');
+
try { loadSavedApps(true); } catch (_) {
_appsLogFailure('saved_app_refresh', { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
}
@@ -443,13 +491,11 @@
}
}
- function _relativeTime(value, unit) {
+ function _relativeDays(value) {
try {
- return new Intl.RelativeTimeFormat(_currentLang(), { numeric: 'auto' }).format(value, unit);
+ return new Intl.RelativeTimeFormat(_currentLang(), { numeric: 'auto' }).format(value, 'day');
} catch (_) {
- if (unit === 'day') return `${Math.abs(value)} days ago`;
- if (unit === 'hour') return `${Math.abs(value)} hours ago`;
- return `${Math.abs(value)} minutes ago`;
+ return `${Math.abs(value)} days ago`;
}
}
@@ -460,10 +506,11 @@
const now = new Date();
const diffMs = now.getTime() - d.getTime();
if (diffMs < 60_000) return _t('common.just_now', 'just now');
- if (diffMs < 60 * 60_000) return _relativeTime(-Math.floor(diffMs / 60_000), 'minute');
- if (diffMs < 24 * 60 * 60_000) return _relativeTime(-Math.floor(diffMs / 3_600_000), 'hour');
+ if (d.toDateString() === now.toDateString()) {
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
+ }
const days = Math.floor(diffMs / 86_400_000);
- if (days < 7) return _relativeTime(-Math.max(1, days), 'day');
+ if (days < 7) return _relativeDays(-Math.max(1, days));
const yyyy = d.getFullYear();
const mo = String(d.getMonth() + 1).padStart(2, '0');
const da = String(d.getDate()).padStart(2, '0');
@@ -478,42 +525,28 @@
{ id: 'game', icon: 'play', tone: 'violet' },
];
let _createPanel = null;
+ let _createDraft = null; // Window-only; never persisted or shared between accounts.
function _createTemplateId(value) {
return _appTemplates.some(item => item.id === value) ? value : 'custom';
}
- function _logCreateAction(action, template = 'custom') {
- const payload = { action, template: _createTemplateId(template) };
- _appsLog.info?.('app creation action', payload);
- }
- async function _createAppTask(prompt, template, onReady) {
- const startedAt = Date.now();
+ async function _createAppTask(prompt, onReady, appType) {
+ if (appType === 'web' || appType === 'cloud') { await window.OrkasCommercialEntry.show(); return false; }
let stage = 'preflight';
- let reported = false;
let started = false;
- const report = (result) => {
- if (reported) return;
- reported = true;
- const payload = { result, template: _createTemplateId(template), stage,
- duration_ms: Math.max(0, Date.now() - startedAt) };
- if (result === 'failure') payload.error_code = stage === 'preflight'
- ? 'model_not_configured' : stage === 'conversation_create' ? 'conversation_create_failed' : 'send_not_started';
- if (result === 'failure') _appsLog.warn('app creation did not start', payload);
- else _appsLog.info?.('app creation started', payload);
- };
try {
- if (!ensureModelConfigured()) { report('failure'); return false; }
+ if (!ensureModelConfigured()) { _appsLog.warn('app creation did not start', { error_code: 'model_not_configured' }); return false; }
stage = 'conversation_create';
const result = await window.orkas.invoke('conversations.create', {
- title: _autoTitle(prompt), assistance: { kind: 'app_creation' },
+ title: _autoTitle(prompt), assistance: { kind: 'app_creation', appType },
});
const conversation = result && result.ok !== false && result.conversation;
const cid = conversation && conversation.conversation_id;
if (!cid) throw new Error('conversation_create_failed');
conversation.last_active_at = new Date().toISOString();
- conversations.unshift(conversation);
+ _cacheCreatedConversation(conversation);
renderConversationList();
onReady();
setView('conversation', cid, { skipLoad: true });
@@ -523,21 +556,22 @@
stage = 'send';
await sendInConversation(cid, prompt, { title_text: prompt }, {
source_view: 'conversation', restoreComposerOnFailure: true,
- onAccepted: () => { started = true; report('success'); },
+ onAccepted: () => { started = true; },
});
if (!started) throw new Error('send_not_started');
return true;
} catch (_) {
// Once accepted, the task owns its execution errors and retry controls.
if (!started) {
- report('failure');
+ _appsLog.warn('app creation did not start', { error_code: stage === 'preflight' ? 'model_not_configured' : stage === 'conversation_create' ? 'conversation_create_failed' : 'send_not_started' });
await uiAlert(_t('apps.create_failed', 'Could not start app creation. Please try again.'));
}
return started;
}
}
- function _openCreatePanel(draft = '', selectedTemplate = 'custom') {
+ function _openCreatePanel(draft = '', selectedTemplate = 'custom', selectedType = 'local') {
+ if (selectedType === 'web' || selectedType === 'cloud') { void window.OrkasCommercialEntry.show(); return; }
if (_createPanel) return;
_closeRowMenu();
const previousFocus = document.activeElement;
@@ -551,6 +585,9 @@
<h2 id="apps-create-title">${label('apps.create_title')}</h2>
</div>
</div>
+ <div class="header-actions apps-create-types" role="group">
+ ${['local','web'].map(type=>`<button type="button" class="btn btn-sm ${selectedType===type?'btn-primary':''}" data-app-type="${type}" aria-pressed="${selectedType===type}">${label('apps.type_'+type)}</button>`).join('')}
+ </div>
<div class="form-row apps-create-idea">
<label for="apps-create-idea">${label('apps.idea_label')}</label>
<textarea id="apps-create-idea" rows="4" placeholder="${label('apps.idea_placeholder')}"></textarea>
@@ -586,7 +623,9 @@
idea.addEventListener('input', updateSubmit);
updateSubmit();
const releaseFocusGuard = _uiKeepDialogFocus(overlay, idea);
- const close = () => {
+ const close = (retainDraft = true) => {
+ if (!overlay.isConnected) return;
+ _createDraft = retainDraft ? { idea: idea.value, template: selectedTemplate, type: selectedType } : null;
releaseFocusGuard();
document.removeEventListener('keydown', onKey, true);
overlay.remove();
@@ -598,41 +637,46 @@
if (_uiTrapDialogTab(overlay, event)) return;
if (event.key === 'Escape') {
event.preventDefault(); event.stopPropagation();
- if (!submitting) { _logCreateAction('cancel', selectedTemplate); close(); }
+ if (!submitting) { close(); }
}
};
document.addEventListener('keydown', onKey, true);
overlay.addEventListener('click', async (event) => {
if (submitting) return;
+ const typeButton=event.target.closest('[data-app-type]');
+ if(typeButton){
+ if (typeButton.dataset.appType === 'web') { await window.OrkasCommercialEntry.show(); return; }
+ selectedType=typeButton.dataset.appType;overlay.querySelectorAll('[data-app-type]').forEach(button=>(button.setAttribute('aria-pressed',String(button===typeButton)),button.classList.toggle('btn-primary',button===typeButton)));return;
+ }
if (event.target === overlay || event.target.closest('[data-create-cancel]')) {
- _logCreateAction('cancel', selectedTemplate); close(); return;
+ close(); return;
}
const template = event.target.closest('[data-app-template]');
if (template) {
selectedTemplate = _createTemplateId(template.dataset.appTemplate);
- _logCreateAction('template', selectedTemplate);
+
idea.value = _t(`apps.template_${template.dataset.appTemplate}_prompt`, '');
updateSubmit();
idea.focus();
return;
}
if (!event.target.closest('[data-create-submit]') || !idea.value.trim()) return;
- _logCreateAction('submit', selectedTemplate);
+
submitting = true;
updateSubmit();
cancelButton.disabled = true;
idea.disabled = true;
createButton.setAttribute('aria-busy', 'true');
- overlay.querySelectorAll('[data-app-template]').forEach(button => { button.disabled = true; });
- await _createAppTask(idea.value, selectedTemplate, close);
+ overlay.querySelectorAll('[data-app-template],[data-app-type]').forEach(button => { button.disabled = true; });
+ await _createAppTask(idea.value, () => close(false), selectedType);
submitting = false;
updateSubmit();
cancelButton.disabled = false;
idea.disabled = false;
createButton.removeAttribute('aria-busy');
- overlay.querySelectorAll('[data-app-template]').forEach(button => { button.disabled = false; });
+ overlay.querySelectorAll('[data-app-template],[data-app-type]').forEach(button => { button.disabled = false; });
});
- _createPanel = { close, getDraft: () => idea.value, getTemplate: () => selectedTemplate, isSubmitting: () => submitting };
+ _createPanel = { close, getDraft: () => idea.value, getTemplate: () => selectedTemplate, getType:()=>selectedType, isSubmitting: () => submitting };
idea.focus();
}
@@ -641,8 +685,19 @@
const empty = document.getElementById('apps-empty');
const countEl = document.getElementById('apps-page-header-count');
if (!grid) return;
+ const focused = document.activeElement;
+ const focusedCard = grid.contains(focused) ? focused.closest('.app-card') : null;
+ const focusedAppId = focusedCard?.dataset.appId;
+ const focusedMore = !!focusedCard && focused.matches('[data-app-more]');
+ const focusedDetails = !!focusedCard && focused.matches('[data-app-details]');
+ const focusedMenuAction = _rowMenuAppId && _rowMenuEl?.contains(focused) ? focused.dataset.action : null;
+ let replacementFocus = null;
+ let replacementAnchor = null;
grid.innerHTML = '';
- const list = Array.isArray(apps) ? apps : [];
+ const list = (Array.isArray(apps) ? apps : []).filter(app => {
+ if (!app || !app.id) return false;
+ return _appType(app) === _appsFilter;
+ });
if (empty) empty.style.display = list.length ? 'none' : '';
if (countEl) countEl.textContent = list.length ? String(list.length) : '';
@@ -658,7 +713,8 @@
card.dataset.appId = a.id;
card.setAttribute('role', 'button');
card.tabIndex = 0;
- card.setAttribute('aria-label', `${title} · ${_t('apps.open_hint', 'Open in Orkas')}`);
+ card.setAttribute('aria-label', `${title} · ${a.local === false
+ ? _t('apps.publish_visit', 'Visit online') : _t('apps.open_hint', 'Open in Orkas')}`);
// Identity-based decoration stays stable across renames and sorting.
const tones = ['violet', 'blue', 'green', 'amber', 'rose'];
@@ -667,7 +723,7 @@
const icon = document.createElement('span');
icon.className = `app-card-icon is-${tones[hash % tones.length]}`;
icon.setAttribute('aria-hidden', 'true');
- icon.innerHTML = uiIconHtml('layout-grid');
+ icon.innerHTML = uiIconHtml(_appType(a) === 'web' ? 'cloud' : 'layout-grid');
const header = document.createElement('div');
header.className = 'app-card-header';
header.appendChild(icon);
@@ -679,6 +735,7 @@
name.className = 'app-card-name';
name.textContent = title;
titleBlock.appendChild(name);
+ let details = null;
const more = document.createElement('button');
more.type = 'button';
@@ -687,9 +744,11 @@
more.innerHTML = moreSvg || '<span aria-hidden="true">...</span>';
more.title = _t('apps.more', 'More');
more.setAttribute('aria-label', _t('apps.more', 'More'));
+ more.setAttribute('aria-haspopup', 'menu');
+ more.setAttribute('aria-expanded', 'false');
- header.appendChild(titleBlock);
header.appendChild(more);
+ header.appendChild(titleBlock);
card.appendChild(header);
const meta = document.createElement('div');
@@ -712,7 +771,7 @@
_openApp(a.id);
});
card.addEventListener('keydown', (e) => {
- if (e.target && e.target.closest && e.target.closest('[data-app-more]')) return;
+ if (e.target && e.target.closest && e.target.closest('button')) return;
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
@@ -720,23 +779,103 @@
}
});
grid.appendChild(card);
+ if (a.id === focusedAppId) replacementFocus = focusedMore ? more : focusedDetails && details ? details : card;
+ if (a.id === _rowMenuAppId) replacementAnchor = more;
+ }
+ if (replacementFocus) _uiRestoreDialogFocus(replacementFocus, { preventScroll: true });
+ if (_rowMenuAppId) {
+ if (replacementAnchor) {
+ _rowMenuAnchor = replacementAnchor;
+ replacementAnchor.setAttribute('aria-expanded', 'true');
+ replacementAnchor.closest('.app-card').classList.add('is-menu-open');
+ _renderRowMenuItems(_rowMenuEl);
+ _positionRowMenu(_rowMenuEl, replacementAnchor);
+ if (focusedMenuAction) {
+ const replacement = [..._rowMenuEl.children].find(item => item.dataset.action === focusedMenuAction)
+ || _rowMenuEl.querySelector('[role="menuitem"]') || replacementAnchor;
+ replacement.focus({ preventScroll: true });
+ }
+ } else _closeRowMenu();
}
+ if ((focusedAppId && !replacementFocus) || (focusedMenuAction && !replacementAnchor)) {
+ document.getElementById('apps-create-btn')?.focus({ preventScroll: true });
+ }
+ }
+
+ function _appType(app) {
+ if (app.appType === 'local') return 'local';
+ return app.appType === 'web' || app.appType === 'cloud' ? 'web' : 'local';
}
- async function loadSavedApps(_force) {
+ function _renderFilters() {
+ const tools = document.getElementById('apps-type-tabs');
+ if (!tools) return;
+ const focusedType = tools.contains(document.activeElement) ? document.activeElement?.dataset?.appFilter : '';
+ const description = document.getElementById('apps-type-description');
+ if (description) {
+ description.textContent = _t('apps.type_' + _appsFilter + '_description', '');
+ description.title = description.textContent;
+ }
+ document.getElementById('apps-content')?.setAttribute('aria-labelledby', 'apps-tab-' + _appsFilter);
+ tools.replaceChildren();
+ for (const [value, key] of _appsFilters) {
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.id = 'apps-tab-' + value;
+ button.dataset.appFilter = value;
+ button.className = 'btn btn-sm';
+ button.textContent = _t(key, key);
+ button.setAttribute('role', 'tab');
+ button.setAttribute('aria-selected', String(_appsFilter === value));
+ if (_appsFilter === value) button.setAttribute('aria-describedby', 'apps-type-description');
+ button.setAttribute('aria-controls', 'apps-content');
+ button.tabIndex = _appsFilter === value ? 0 : -1;
+ button.onclick = () => {
+ if (value === 'web') { void window.OrkasCommercialEntry.show(); return; }
+ _closeRowMenu();
+ _appsFilter = value;
+ _renderFilters();
+ _renderApps(_appsCache);
+ tools.querySelector(`[data-app-filter="${value}"]`)?.focus();
+ };
+ button.onkeydown = (event) => {
+ if (event.isComposing || event.keyCode === 229) return;
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
+ event.preventDefault();
+ const next = event.key === 'Home' ? 'local' : event.key === 'End' ? 'web' : value === 'local' ? 'web' : 'local';
+ tools.querySelector(`[data-app-filter="${next}"]`)?.click();
+ };
+ tools.appendChild(button);
+ }
+ if (focusedType) tools.querySelector(`[data-app-filter="${focusedType}"]`)?.focus();
+ }
+
+ async function loadSavedApps(_force, options) {
+ const request=++_appsLoadGeneration;
+ if (options?.reset) {
+ _createPanel?.close(false);
+ _createDraft = null;
+ _appsCache = null;
+ _closeRowMenu();
+ _renderApps([]);
+ }
+ _renderFilters();
const createButton = document.getElementById('apps-create-btn');
if (createButton) createButton.onclick = () => {
if (_createPanel) return;
- _logCreateAction('open');
- _openCreatePanel();
+
+ _openCreatePanel(_createDraft?.idea ?? '', _createDraft?.template ?? 'custom', _createDraft?.type ?? _appsFilter);
};
- // `_force` accepted for parity with loadAgents/loadSkills; this module
- // keeps no "loaded once" flag — the list is cheap, always re-fetch.
+ // List from disk before online revalidation. Legacy type recovery can need
+ // the service; it must not hold every app card behind a network request.
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);
+ const r = await window.orkas.invoke('savedApps.list', { localOnly: true });
+ if(request!==_appsLoadGeneration)return;
+ if (!r || r.ok === false || !Array.isArray(r.apps)) throw new Error('saved_app_list_failed');
+ _appsCache = r.apps;
+ } catch (_) {
+ if(request!==_appsLoadGeneration)return;
+ _appsLog.warn('savedApps.list failed', { error_code: 'saved_app_list_failed' });
_appsCache = _appsCache || [];
}
_renderApps(_appsCache);
@@ -745,11 +884,12 @@
window.addEventListener('i18n-change', () => {
_closeRowMenu();
if (_appsCache) _renderApps(_appsCache);
+ _renderFilters();
if (_createPanel && !_createPanel.isSubmitting()) {
const selectedTemplate = _createPanel.getTemplate();
- const draft = _createPanel.getDraft();
+ const draft = _createPanel.getDraft(),selectedType=_createPanel.getType();
_createPanel.close();
- _openCreatePanel(draft, selectedTemplate);
+ _openCreatePanel(draft, selectedTemplate,selectedType);
}
});
diff --git a/src/renderer/modules/web-app-host.js b/src/renderer/modules/web-app-host.js
index 1a9476c5..f236c27e 100644
--- a/src/renderer/modules/web-app-host.js
+++ b/src/renderer/modules/web-app-host.js
@@ -12,13 +12,21 @@
}
function attach(frame, info) {
release(frame);
- frame._orkasUsesSdk = !!info.token;
+ frame._orkasUsesSdk = !!info.token && !info.browserOnly;
if (!info.token) { frame.src = info.url; return; }
const parsed = new URL(info.url);
- const b = { token: info.token, origin: parsed.protocol + '//' + parsed.host, streams: new Map() };
+ const b = { sdk: frame._orkasUsesSdk, token: info.token, origin: parsed.protocol + '//' + parsed.host, streams: new Map() };
bindings.set(frame, b);
frame.src = info.url;
}
+ async function canSubmitArtifact(frame) {
+ const b = bindings.get(frame);
+ if (!b || !b.sdk || !frame.isConnected) return false;
+ try {
+ const result = await window.orkas.invoke('webApps.canSubmitArtifact', { token: b.token });
+ return result?.ok === true && result.allowed === true && bindings.get(frame) === b && frame.isConnected;
+ } catch { return false; }
+ }
async function open(frame, source) {
release(frame);
const generation = {}; opening.set(frame, generation);
@@ -28,20 +36,21 @@
if (r.token) window.orkas.invoke('webApps.close', { token: r.token }).catch(() => {});
return;
}
- if (!r.ok) throw new Error(r.error || 'Application unavailable');
+ if (!r.ok) throw Object.assign(new Error(r.error || 'Application unavailable'), r);
attach(frame, r);
} catch (error) {
- if (opening.get(frame) !== generation) return;
+ if (opening.get(frame) !== generation || !frame.isConnected) return;
frame.removeAttribute('src');
- if (typeof uiAlert === 'function') uiAlert(error.message);
// Fail closed for an invalid SDK manifest, never downgrade to the old origin.
- frame.dispatchEvent(new CustomEvent('orkas-app-error', { detail: error.message }));
+ const commercial = window.OrkasCommercialEntry?.isFailure(error);
+ const unhandled = frame.dispatchEvent(new CustomEvent('orkas-app-error', { detail: commercial ? error : error.message, cancelable: true }));
+ if (unhandled && typeof uiAlert === 'function') uiAlert(error.message);
}
}
window.addEventListener('message', event => {
const d = event.data;
if (!d || d.__orkasApp !== 1 || typeof d.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(d.id)) return;
- const entry = [...bindings.entries()].find(([frame, b]) => frame.isConnected && frame.contentWindow === event.source && b.origin === event.origin);
+ const entry = [...bindings.entries()].find(([frame, b]) => b.sdk && frame.isConnected && frame.contentWindow === event.source && b.origin === event.origin);
if (!entry) return;
const [frame, b] = entry;
const reply = (type, extra) => {
@@ -74,5 +83,5 @@
for (const frame of bindings.keys()) if (!frame.isConnected || !frame.getAttribute('src')) release(frame);
}).observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['src'] });
window.addEventListener('pagehide', () => { for (const frame of bindings.keys()) release(frame); });
- window.OrkasWebAppHost = { open, attach, release, isManaged: frame => !!frame._orkasUsesSdk };
+ window.OrkasWebAppHost = { open, attach, release, canSubmitArtifact, isManaged: frame => !!frame._orkasUsesSdk };
})();
diff --git a/src/renderer/preview.css b/src/renderer/preview.css
index 2c8a766f..7da5baa7 100644
--- a/src/renderer/preview.css
+++ b/src/renderer/preview.css
@@ -25,7 +25,7 @@
.preview-window .chat-artifact-viewer-header { display: contents; }
.preview-window .chat-file-viewer-actions,
.preview-window .chat-lightbox-actions {
- position: absolute; top: 12px; right: 12px; z-index: 4;
+ position: absolute; top: 12px; right: 12px; --orkas-ui-layer: chrome; z-index: 4;
gap: 6px; padding: 6px; border: 1px solid rgba(148, 163, 184, 0.3);
border-radius: 12px; background: rgba(248, 250, 252, 0.94);
box-shadow: 0 4px 16px rgba(15, 23, 42, 0.12);
diff --git a/src/renderer/preview.html b/src/renderer/preview.html
index d229dc9f..46a3e2ee 100644
--- a/src/renderer/preview.html
+++ b/src/renderer/preview.html
@@ -28,6 +28,7 @@
<script src="./modules/connector-action-dialog.js"></script>
<script src="./modules/bash_permission.js"></script>
<script src="./modules/web-app-host.js"></script>
+ <script src="./modules/commercial-entry.js"></script>
<script src="./modules/artifact-security.js"></script>
<script src="./modules/saved-apps.js"></script>
<script src="./modules/chat-artifact.js"></script>
diff --git a/test/e2e/fixtures/app-template-journeys.ts b/test/e2e/fixtures/app-template-journeys.ts
index c98767c4..a68d623f 100644
--- a/test/e2e/fixtures/app-template-journeys.ts
+++ b/test/e2e/fixtures/app-template-journeys.ts
@@ -28,7 +28,11 @@ export async function exerciseProductInventory(frame: FrameLocator, reopen: () =
await submit.click();
await expect(row()).toContainText('21.43');
passed?.('edited');
- await expect(row().getByRole('cell').filter({ hasText: /^0$/ })).toBeVisible();
+ const stockColumn = await frame.getByRole('columnheader', { name: /库存/ }).evaluate(el =>
+ Array.from(el.parentElement!.children).indexOf(el));
+ const stockCell = row().getByRole('cell').nth(stockColumn);
+ await expect(stockCell).toBeVisible();
+ await expect.poll(async () => Number((await stockCell.innerText()).replace(/,/g, '').match(/[-+]?\d+(?:\.\d+)?/)?.[0])).toBe(0);
passed?.('zeroStock');
frame = await reopen();
await expect(row()).toContainText('21.43');
@@ -54,8 +58,12 @@ export async function exerciseConverter(frame: FrameLocator, passed?: Checkpoint
const from = frame.getByRole('combobox', { name: /输入单位|源单位|从/ });
const to = frame.getByRole('combobox', { name: /输出单位|目标单位|换算为/ });
const input = frame.getByRole('spinbutton').first();
- const result = frame.locator('output:visible');
- const value = async () => Number((await result.innerText()).replace(/,/g, '').match(/[-+]?\d+(?:\.\d+)?/)?.[0]);
+ const labeledResult = frame.getByRole('textbox', { name: /换算结果|输出数值/ });
+ const result = await labeledResult.count() ? labeledResult : frame.locator('output:visible');
+ const value = async () => {
+ const text = await result.evaluate(el => el instanceof HTMLInputElement ? el.value : el.textContent || '');
+ return Number(text.replace(/,/g, '').match(/[-+]?\d+(?:\.\d+)?/)?.[0]);
+ };
await selectOptionMatching(from, /^千米$|^公里$|^km$/i);
await selectOptionMatching(to, /^米$|^m$/i);
await input.fill('2.37');
@@ -91,18 +99,26 @@ export async function exerciseFlashcards(frame: FrameLocator, page: Page, eviden
const wordInput = frame.getByRole('textbox', { name: /^单词/ });
const addForm = frame.locator('form').filter({ has: wordInput });
for (let i = 0; i < 2; i++) {
+ if (!await wordInput.isVisible()) await frame.getByRole('button', { name: /添加(?:新)?单词|新增单词/ }).click();
await wordInput.fill(words[i]);
await frame.getByLabel(/^释义/).fill(meanings[i]);
await frame.getByLabel(/^例句/).fill(`This is ${words[i]}.`);
await addForm.locator('button[type="submit"], button:not([type]), input[type="submit"]').click();
}
- const flip = frame.getByRole('button', { name: /翻转.*卡|翻.*答案|收起答案|显示释义|显示单词|卡片正面|卡片背面/ });
+ const flip = frame.getByRole('button', { name: /翻转.*卡|翻.*答案|收起答案|显示释义|显示单词|卡片正面|卡片背面|单词卡片|答案已显示/ });
// A card may itself be a button or contain a separate flip button.
const article = frame.getByRole('article').filter({ has: flip });
const separateFlip = await article.count() === 1;
const card = separateFlip ? article : flip;
await expect(card).toContainText(words[1]);
passed?.('added');
+ // Some apps open the answer immediately after adding a word. CSS back faces
+ // can have a nonempty layout box while still facing away, so layout visibility
+ // alone cannot identify that starting state; use the flip control's state.
+ if (/答案已显示|收起答案|显示单词|卡片背面/.test(await flip.getAttribute('aria-label') || '')) {
+ await flip.click();
+ await expect(card.getByText(meanings[1], { exact: true })).not.toBeVisible();
+ }
const before = await card.screenshot({ path: evidencePath('flashcard-front.png') });
await flip.click();
await expect(card).toContainText(meanings[1]);
@@ -111,13 +127,22 @@ export async function exerciseFlashcards(frame: FrameLocator, page: Page, eviden
const after = await card.screenshot({ path: evidencePath('flashcard-back.png') });
expect(after.equals(before), 'Flip must visibly reveal the answer').toBe(false);
passed?.('flipped');
- await (separateFlip ? card : frame).getByRole('button', { name: /我已掌握|^已掌握$|标记.*掌握|^已经掌握$/ }).click();
+ await (separateFlip ? card : frame).getByRole('button', { name: /我已掌握|^(?:[✓✔]\s*)?已掌握$|标记.*掌握|^已经掌握$/ }).click();
await expect(card).toContainText(words[0]);
// The template promises mastery and priority, not a particular list layout.
// Verify the marked word through the app's list or its mastery filter.
const masteredRow = frame.getByRole('listitem').filter({ hasText: words[1] });
+ // The flashcard itself may be a non-native role=button with the same word.
+ // Deck navigation uses actual buttons, distinct from that flip surface.
+ const deckButton = frame.locator('button').filter({ hasText: words[1] });
+ const hasFilters = await frame.getByRole('combobox', { name: /筛选/ }).count()
+ || await frame.getByRole('group', { name: /筛选/ }).count();
if (await masteredRow.count()) {
await expect(masteredRow).toContainText('已掌握');
+ } else if (!hasFilters && await deckButton.count() === 1) {
+ await deckButton.click();
+ await expect(card).toContainText(words[1]);
+ await expect(card).toContainText('已掌握');
} else {
await filterCards('mastered');
await expect(card).toContainText(words[1]);
@@ -127,6 +152,18 @@ export async function exerciseFlashcards(frame: FrameLocator, page: Page, eviden
await expect(card).not.toContainText(words[1]);
}
passed?.('masteryMarked');
+ if (!await masteredRow.count() && !hasFilters && await deckButton.count() === 1) {
+ const again = frame.getByRole('button', { name: /^还不熟$|还不熟悉|未掌握|不认识/ });
+ if (!await again.isEnabled()) await flip.click();
+ await again.click();
+ const nextReview = await card.innerText();
+ await deckButton.click();
+ await expect(card, 'Returning a card to review must clear mastery').not.toContainText('已掌握');
+ expect(nextReview).toContain(words[0]);
+ expect(nextReview).not.toContain(words[1]);
+ passed?.('unmasteredPrioritized');
+ return { added: true, flipped: true, masteryMarked: true, unmasteredPrioritized: true };
+ }
const again = frame.getByRole('button', { name: /还不熟悉|未掌握|不认识/ });
if (await again.count()) {
await again.click();
@@ -166,11 +203,15 @@ export async function exerciseSnake(frame: FrameLocator, page: Page, passed?: Ch
const board = frame.locator('canvas');
const pixels = () => board.evaluate((el: HTMLCanvasElement) => el.toDataURL());
const difficulty = frame.getByRole('combobox', { name: /难度/ });
- const levels = await difficulty.locator('option').evaluateAll(options => options
+ const difficultyButtons = frame.getByRole('group', { name: /难度/ }).getByRole('button');
+ const selectDifficulty = await difficulty.count() > 0;
+ const levels = selectDifficulty ? await difficulty.locator('option').evaluateAll(options => options
.filter(option => !(option as HTMLOptionElement).disabled)
- .map(option => ({ value: (option as HTMLOptionElement).value, label: option.textContent || '' })));
- expect(levels.length, 'Difficulty must offer multiple levels').toBeGreaterThan(1);
- await difficulty.selectOption(levels[0].value);
+ .map(option => ({ value: (option as HTMLOptionElement).value, label: option.textContent || '' }))) : [];
+ const levelCount = selectDifficulty ? levels.length : await difficultyButtons.count();
+ expect(levelCount, 'Difficulty must offer multiple levels').toBeGreaterThan(1);
+ if (selectDifficulty) await difficulty.selectOption(levels[0].value);
+ else await difficultyButtons.first().click();
await frame.getByRole('button', { name: /重新开始/ }).click();
await expect(frame.getByText(/^最高分(?:\s*\d+)?$/)).toBeVisible();
for (const direction of ['上', '下', '左', '右']) {
@@ -195,10 +236,17 @@ export async function exerciseSnake(frame: FrameLocator, page: Page, passed?: Ch
await expect.poll(pixels, { timeout: 3000 }).not.toBe(turned);
passed?.('keyboard');
await frame.getByRole('button', { name: /重新开始/ }).click();
- await expect(frame.getByText(/^(?:当前分数|分数)(?:\s*\d+)?$/).first().locator('..')).toContainText('0');
+ const score = frame.getByText(/^(?:当前分数|当前得分|分数)(?:\s*\d+)?$/).first().locator('..');
+ await expect(score).toContainText('0');
passed?.('restart');
- await difficulty.selectOption(levels[levels.length - 1].value);
- await expect(difficulty.locator('option:checked')).toHaveText(levels[levels.length - 1].label);
+ if (selectDifficulty) {
+ await difficulty.selectOption(levels[levels.length - 1].value);
+ await expect(difficulty.locator('option:checked')).toHaveText(levels[levels.length - 1].label);
+ } else {
+ await difficultyButtons.last().click();
+ await expect(difficultyButtons.last()).toHaveAttribute('aria-pressed', 'true');
+ await expect(difficultyButtons.first()).toHaveAttribute('aria-pressed', 'false');
+ }
passed?.('difficulty');
return { movement: true, pause: true, resume: true, keyboard: true, restart: true, difficulty: true,
limits: 'Eating, collision, high-score persistence and visual design are not scored by this smoke journey.' };
diff --git a/test/e2e/fixtures/app-template-live-20261013/converter/index.html b/test/e2e/fixtures/app-template-live-20261013/converter/index.html
new file mode 100644
index 00000000..00d9d8be
--- /dev/null
+++ b/test/e2e/fixtures/app-template-live-20261013/converter/index.html
@@ -0,0 +1,24 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>单位换算器</title>
+<style>
+:root{font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#17211d;background:#f2f5f1;font-synthesis:none}*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;padding:32px}.app{width:min(100%,680px)}.top{display:flex;align-items:center;justify-content:space-between;margin-bottom:26px}.brand{display:flex;align-items:center;gap:12px}.mark{width:42px;height:42px;border-radius:14px;background:#185a43;color:white;display:grid;place-items:center;font-size:22px}.eyebrow{font-size:12px;color:#738078;letter-spacing:.12em;text-transform:uppercase}.top h1{font-size:22px;margin:3px 0 0}.badge{border:1px solid #dce4dd;border-radius:99px;padding:8px 12px;color:#65736a;font-size:12px;background:#fff}.card{background:white;border:1px solid #e4eae4;border-radius:24px;padding:28px;box-shadow:0 18px 50px #193b2610}.label{font-size:13px;font-weight:650;color:#56645b;margin:0 0 12px}.tabs{display:flex;gap:8px;margin-bottom:27px}.tab{border:0;background:#f3f6f3;color:#68756c;padding:10px 15px;border-radius:11px;font:600 13px inherit;cursor:pointer}.tab.active{background:#e4f1e9;color:#185a43}.field{border:1px solid #e1e8e1;border-radius:16px;padding:15px 17px}.field:focus-within{border-color:#4a9a70;box-shadow:0 0 0 3px #4a9a701c}.field-head{display:flex;justify-content:space-between;font-size:12px;color:#748078;margin-bottom:10px}.field-row{display:flex;align-items:center;gap:12px}.field input{min-width:0;flex:1;border:0;outline:0;font-size:27px;font-weight:650;color:#17211d;background:transparent}.field input::placeholder{color:#bcc6be}.select-wrap{position:relative}.field select{appearance:none;border:0;background:#f4f7f4;border-radius:10px;padding:10px 30px 10px 12px;font:600 13px inherit;color:#34473a;cursor:pointer;outline-offset:3px}.select-wrap:after{content:'⌄';position:absolute;right:11px;top:8px;color:#66756a;pointer-events:none}.middle{display:flex;align-items:center;gap:12px;margin:12px 0}.line{height:1px;background:#edf0ed;flex:1}.swap{width:39px;height:39px;border:1px solid #e1e8e1;background:#fff;border-radius:13px;font-size:18px;color:#185a43;cursor:pointer;transition:transform .2s}.swap:hover{transform:rotate(180deg);background:#f1f8f3}.result{background:#f4f8f4;border:0}.result input{color:#185a43}.precision{display:flex;justify-content:space-between;color:#7a877e;font-size:12px;margin-top:17px}.precision strong{color:#3b5142;font-weight:600}.foot{margin-top:17px;text-align:center;color:#89948d;font-size:12px}.foot a{color:#185a43;text-decoration:none}.tab:focus-visible,.swap:focus-visible,select:focus-visible{outline:3px solid #75b88d;outline-offset:2px}@media(max-width:520px){body{padding:20px}.card{padding:21px 17px;border-radius:20px}.top{margin-bottom:18px}.badge{display:none}.field{padding:13px}.field input{font-size:22px}.field select{max-width:138px;padding-left:9px;padding-right:25px;font-size:12px}.tabs{gap:5px}.tab{flex:1;padding:10px 7px;font-size:12px}}
+@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;scroll-behavior:auto!important}}
+</style>
+</head>
+<body><main class="app"><header class="top"><div class="brand"><div class="mark" aria-hidden="true">↔</div><div><div class="eyebrow">QUICK CONVERT</div><h1>单位换算器</h1></div></div><span class="badge">即时换算 · 无需联网</span></header>
+<section class="card" aria-label="单位换算"><p class="label">选择换算类别</p><div class="tabs" role="tablist" aria-label="换算类别"><button class="tab active" role="tab" aria-selected="true" data-kind="length">长度</button><button class="tab" role="tab" aria-selected="false" data-kind="weight">重量</button><button class="tab" role="tab" aria-selected="false" data-kind="temperature">温度</button></div>
+<div class="field"><div class="field-head"><label for="inputValue">输入数值</label><span>FROM</span></div><div class="field-row"><input id="inputValue" type="number" step="any" value="1" aria-label="输入数值"><div class="select-wrap"><select id="fromUnit" aria-label="输入单位"></select></div></div></div>
+<div class="middle"><div class="line"></div><button class="swap" id="swap" type="button" aria-label="交换输入和输出单位" title="交换单位">⇅</button><div class="line"></div></div>
+<div class="field result"><div class="field-head"><label for="outputValue">换算结果</label><span>TO</span></div><div class="field-row"><input id="outputValue" readonly aria-live="polite" aria-label="换算结果"><div class="select-wrap"><select id="toUnit" aria-label="输出单位"></select></div></div></div>
+<div class="precision"><span id="formula">1 米 = 100 厘米</span><strong>实时更新</strong></div></section><footer class="foot">结果按需四舍五入显示 · <a href="#" id="reset">重置为默认值</a></footer></main>
+<script>
+const units={length:[['m','米',1],['km','千米',1000],['cm','厘米',.01],['mm','毫米',.001],['mi','英里',1609.344],['ft','英尺',.3048],['in','英寸',.0254]],weight:[['kg','千克',1],['g','克',.001],['mg','毫克',1e-6],['lb','磅',.45359237],['oz','盎司',.028349523125],['t','公吨',1000]],temperature:[['c','摄氏度'],['f','华氏度'],['k','开尔文']]};let kind='length';const from=document.querySelector('#fromUnit'),to=document.querySelector('#toUnit'),input=document.querySelector('#inputValue'),output=document.querySelector('#outputValue'),formula=document.querySelector('#formula');
+function populate(keep=false){const prevA=from.value,prevB=to.value;from.innerHTML='';to.innerHTML='';units[kind].forEach(([id,name])=>{from.add(new Option(name,id));to.add(new Option(name,id))});if(keep&&units[kind].some(x=>x[0]===prevA))from.value=prevA;if(keep&&units[kind].some(x=>x[0]===prevB))to.value=prevB;else to.selectedIndex=Math.min(1,units[kind].length-1);convert()}
+function tempConvert(v,a,b){let c=a==='c'?v:a==='f'?(v-32)*5/9:v-273.15;return b==='c'?c:b==='f'?c*9/5+32:c+273.15}
+function fmt(x){if(!Number.isFinite(x))return '—';if(Math.abs(x)<1e-12&&x!==0)return '0';return Number(x.toPrecision(10)).toLocaleString('zh-CN',{maximumSignificantDigits:10})}
+function convert(){const v=Number(input.value),a=from.value,b=to.value;if(input.value===''||!Number.isFinite(v)){output.value='';formula.textContent='输入数值以查看换算结果';return}let result;if(kind==='temperature')result=tempConvert(v,a,b);else{const av=units[kind].find(x=>x[0]===a),bv=units[kind].find(x=>x[0]===b);result=v*av[2]/bv[2]}output.value=fmt(result);const an=from.selectedOptions[0]?.text,bn=to.selectedOptions[0]?.text;formula.textContent=`${fmt(v)} ${an} = ${fmt(result)} ${bn}`}
+document.querySelectorAll('.tab').forEach(btn=>btn.addEventListener('click',()=>{kind=btn.dataset.kind;document.querySelectorAll('.tab').forEach(x=>{const active=x===btn;x.classList.toggle('active',active);x.setAttribute('aria-selected',active)});populate()}));[input,from,to].forEach(el=>el.addEventListener('input',convert));[from,to].forEach(el=>el.addEventListener('change',convert));document.querySelector('#swap').addEventListener('click',()=>{const a=from.value;from.value=to.value;to.value=a;convert()});document.querySelector('#reset').addEventListener('click',e=>{e.preventDefault();kind='length';document.querySelectorAll('.tab').forEach((x,i)=>{x.classList.toggle('active',i===0);x.setAttribute('aria-selected',i===0)});input.value='1';populate()});populate();
+</script></body></html>
\ No newline at end of file
diff --git a/test/e2e/fixtures/app-template-live-20261013/flashcards/index.html b/test/e2e/fixtures/app-template-live-20261013/flashcards/index.html
new file mode 100644
index 00000000..8f33e80b
--- /dev/null
+++ b/test/e2e/fixtures/app-template-live-20261013/flashcards/index.html
@@ -0,0 +1,17 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f6f5f0">
+<title>词间 · 单词卡片</title>
+<style>
+:root{--ink:#20231f;--muted:#85887f;--paper:#f6f5f0;--card:#fffefa;--green:#315c48;--lime:#d9ee79;--line:#e8e7df;--orange:#e6a76b}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}button,input,textarea{font:inherit}button{cursor:pointer}.shell{max-width:1160px;margin:auto;padding:28px 42px 48px}.topbar{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:22px}.brand{display:flex;align-items:center;gap:12px;font-weight:750;font-size:19px;letter-spacing:-.5px}.brandmark{width:34px;height:34px;border-radius:11px;background:var(--green);color:var(--lime);display:grid;place-items:center;font-size:20px}.top-right{display:flex;align-items:center;gap:12px;color:var(--muted);font-size:13px}.avatar{width:34px;height:34px;border-radius:50%;background:#e8e5d9;display:grid;place-items:center;color:var(--green);font-weight:700}.hero{display:flex;justify-content:space-between;align-items:flex-end;padding:38px 0 28px}.eyebrow{text-transform:uppercase;letter-spacing:2px;font-size:11px;color:var(--green);font-weight:700}.hero h1{font-size:34px;letter-spacing:-1.5px;margin:9px 0 7px}.hero p{margin:0;color:var(--muted);font-size:14px}.primary{background:var(--green);color:white;border:0;padding:12px 18px;border-radius:12px;font-weight:650;box-shadow:0 4px 12px #315c4825}.primary:hover{background:#244b39}.layout{display:grid;grid-template-columns:minmax(0,1fr) 284px;gap:22px;align-items:start}.mainpanel,.sidepanel{background:var(--card);border:1px solid var(--line);border-radius:20px}.mainpanel{padding:22px}.panelhead{display:flex;align-items:center;justify-content:space-between;margin-bottom:19px}.panelhead h2{font-size:15px;margin:0}.progress-label{color:var(--muted);font-size:12px}.progress{height:5px;background:#eeeee7;border-radius:9px;margin:0 0 22px;overflow:hidden}.progress span{height:100%;display:block;background:#9dbb63;border-radius:9px;transition:width .3s}.flashcard{min-height:310px;border:1px solid #ebeae3;border-radius:17px;background:linear-gradient(145deg,#fffefa,#fbfaf5);display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:34px;position:relative;cursor:pointer;transition:transform .25s,box-shadow .2s;outline:none}.flashcard:hover{box-shadow:0 8px 24px #252b1a0c}.flashcard:focus-visible{box-shadow:0 0 0 3px #a9c47c}.card-top{position:absolute;top:20px;left:22px;right:22px;display:flex;justify-content:space-between;font-size:11px;color:#a1a197}.tag{background:#f0f2e7;color:#67754c;padding:5px 9px;border-radius:30px}.word{font-size:46px;font-weight:720;letter-spacing:-1.8px;margin:9px 0}.phonetic{font-size:15px;color:#93958c}.answer{display:none;margin-top:17px}.flashcard.revealed .answer{display:block;animation:fade .25s}.flashcard.revealed .hint{display:none}.meaning{font-size:22px;font-weight:650;margin-bottom:12px}.example{font-size:14px;line-height:1.6;color:#72766d;max-width:480px}.hint{font-size:12px;color:#999c91;margin-top:34px}.card-actions{display:flex;justify-content:center;align-items:center;gap:12px;margin:17px 0 5px}.iconbtn,.grade{border:1px solid var(--line);background:white;border-radius:11px;color:#62665d;height:42px;min-width:44px}.iconbtn:hover,.grade:hover{border-color:#aab99a;color:var(--green)}.grade{padding:0 17px;font-size:13px;font-weight:650}.grade.easy{background:#f0f5e8;color:#43644b;border-color:#e2e9d9}.grade.hard{background:#fff6ec;color:#a86731;border-color:#f2e8d9}.grade:disabled{opacity:.42;cursor:not-allowed}.studyfoot{display:flex;justify-content:space-between;align-items:center;color:var(--muted);font-size:12px;margin-top:10px}.kbd{border:1px solid var(--line);padding:3px 6px;border-radius:5px;background:#fff;color:#777}.sidepanel{padding:21px}.sidepanel h2{font-size:14px;margin:0 0 16px}.stat{padding:15px 0;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center}.stat:last-of-type{border:0}.statname{font-size:12px;color:var(--muted)}.statval{font-size:22px;font-weight:700;letter-spacing:-.5px}.statval small{font-size:11px;color:var(--muted);font-weight:500}.weakbox{background:#f6f5ef;border-radius:13px;padding:14px;margin-top:12px}.weakbox strong{font-size:12px}.weakbox p{font-size:12px;color:var(--muted);line-height:1.55;margin:7px 0 0}.decktitle{display:flex;justify-content:space-between;align-items:center;margin:28px 0 13px}.decktitle h2{font-size:14px;margin:0}.decktitle span{font-size:12px;color:var(--muted)}.deck{display:grid;gap:8px}.deckrow{display:flex;align-items:center;gap:11px;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:11px 13px;cursor:pointer;text-align:left;width:100%;color:inherit}.deckrow:hover{border-color:#c5cdb9}.deckrow.active{border-color:#9ab079;background:#fbfcf6}.dot{width:8px;height:8px;border-radius:50%;background:#d9a166;flex:none}.dot.mastered{background:#89a960}.rowword{font-size:13px;font-weight:650;flex:1}.rowmeaning{font-size:12px;color:var(--muted)}.empty{text-align:center;color:var(--muted);font-size:14px;padding:38px 18px}.empty strong{display:block;color:var(--ink);margin-bottom:8px}.modal-backdrop{position:fixed;inset:0;background:#17201976;display:none;align-items:center;justify-content:center;padding:20px;z-index:5}.modal-backdrop.open{display:flex}.modal{width:min(100%,480px);background:var(--card);border-radius:20px;padding:26px;box-shadow:0 20px 70px #121a1640}.modalhead{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}.modalhead h2{margin:0;font-size:19px}.close{border:0;background:transparent;color:#777;font-size:23px}.field{margin:14px 0}.field label{display:block;font-size:12px;font-weight:650;margin-bottom:7px}.field input,.field textarea{width:100%;border:1px solid var(--line);border-radius:10px;padding:11px 12px;background:#fffefa;outline:none}.field input:focus,.field textarea:focus{border-color:#839a6f;box-shadow:0 0 0 3px #839a6f22}.field textarea{min-height:78px;resize:vertical}.modalfoot{display:flex;justify-content:flex-end;gap:9px;margin-top:20px}.secondary{border:1px solid var(--line);background:white;border-radius:10px;padding:10px 15px;color:#62665d}.toast{position:fixed;bottom:24px;left:50%;transform:translate(-50%,15px);opacity:0;background:#253a2e;color:white;border-radius:10px;padding:11px 16px;font-size:13px;transition:.2s;pointer-events:none;z-index:8}.toast.show{transform:translate(-50%,0);opacity:1}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@keyframes fade{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:none}}@media(max-width:760px){.shell{padding:18px 16px 32px}.hero{padding:28px 0 20px;align-items:flex-start;gap:14px}.hero h1{font-size:29px}.hero p{font-size:12px}.hero .primary{white-space:nowrap;padding:10px 12px;font-size:12px}.layout{grid-template-columns:1fr}.sidepanel{order:2}.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}.stat{display:block;border:0;padding:7px 0}.statval{font-size:20px}.mainpanel{padding:15px}.flashcard{min-height:280px;padding:25px 18px}.word{font-size:39px}.rowmeaning{display:none}.topbar{padding-bottom:16px}}@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}
+</style></head>
+<body><div class="shell"><header class="topbar"><div class="brand"><span class="brandmark" aria-hidden="true">文</span>词间 <span style="font-size:11px;font-weight:500;color:#999">WORDSPACE</span></div><div class="top-right"><span>今天也进步一点</span><span class="avatar" aria-hidden="true">学</span></div></header>
+<section class="hero"><div><div class="eyebrow">YOUR DAILY PRACTICE</div><h1>让每个单词,都记得更久。</h1><p>翻开一张卡片,开启今天的记忆练习。</p></div><button class="primary" id="addOpen">+ 添加单词</button></section>
+<div class="layout"><main><section class="mainpanel" aria-label="单词复习"><div class="panelhead"><h2>今日复习</h2><span class="progress-label" id="progressLabel">准备开始</span></div><div class="progress" aria-label="复习进度"><span id="progressBar" style="width:0%"></span></div><div id="studyArea"></div></section>
+<div class="decktitle"><h2>我的词库</h2><span id="deckCount">0 个单词</span></div><div class="deck" id="deck"></div></main>
+<aside class="sidepanel"><h2>学习概览</h2><div class="stats"><div class="stat"><div class="statname">词库总量</div><div class="statval" id="totalStat">0</div></div><div class="stat"><div class="statname">尚未掌握</div><div class="statval" id="weakStat">0</div></div><div class="stat"><div class="statname">已掌握</div><div class="statval" id="masteredStat">0</div></div></div><div class="weakbox"><strong>🪴 复习小提示</strong><p>还不熟悉的单词会优先出现。多翻几次,让记忆慢慢扎根。</p></div></aside></div></div>
+<div class="modal-backdrop" id="modalBackdrop" role="presentation"><section class="modal" role="dialog" aria-modal="true" aria-labelledby="modalTitle"><div class="modalhead"><h2 id="modalTitle">添加新单词</h2><button class="close" id="closeModal" aria-label="关闭">×</button></div><form id="wordForm"><div class="field"><label for="wordInput">单词 *</label><input id="wordInput" name="word" required maxlength="80" placeholder="例如:serendipity" autocomplete="off"></div><div class="field"><label for="meaningInput">释义 *</label><input id="meaningInput" name="meaning" required maxlength="160" placeholder="例如:意外发现美好事物的能力"></div><div class="field"><label for="exampleInput">例句</label><textarea id="exampleInput" name="example" maxlength="300" placeholder="例如:Finding that little café was pure serendipity."></textarea></div><div class="modalfoot"><button type="button" class="secondary" id="cancelModal">取消</button><button class="primary" type="submit">保存单词</button></div></form></section></div><div class="toast" id="toast" role="status" aria-live="polite"></div>
+<script>
+(()=>{const KEY='wordspace.cards.v1';const samples=[{id:'s1',word:'serendipity',phonetic:'/ˌser.ənˈdɪp.ə.ti/',meaning:'意外发现美好事物的能力;机缘巧合',example:'Finding that little café was pure serendipity.',mastered:false},{id:'s2',word:'resilient',phonetic:'/rɪˈzɪl.jənt/',meaning:'有韧性的;能迅速恢复的',example:'Children are often remarkably resilient.',mastered:false},{id:'s3',word:'eloquent',phonetic:'/ˈel.ə.kwənt/',meaning:'雄辩的;表达流畅的',example:'She gave an eloquent speech about kindness.',mastered:true}];let cards=[];let currentId=null;let revealed=false;let toastTimer;const $=s=>document.querySelector(s);const escape=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));function load(){try{const raw=localStorage.getItem(KEY);cards=raw===null?samples.map(x=>({...x})):JSON.parse(raw);if(!Array.isArray(cards))throw Error();}catch{cards=samples.map(x=>({...x}));notify('本地数据读取失败,已载入示例词卡。');}if(!cards.length)currentId=null;else if(!cards.some(c=>c.id===currentId))currentId=nextCard()?.id??cards[0]?.id;render()}function save(){try{localStorage.setItem(KEY,JSON.stringify(cards));return true}catch{notify('保存失败:浏览器存储空间不可用。');return false}}function nextCard(){return cards.find(c=>!c.mastered)||cards[0]}function notify(msg){const el=$('#toast');el.textContent=msg;el.classList.add('show');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('show'),2400)}function render(){if(!currentId&&cards.length)currentId=nextCard().id;const card=cards.find(c=>c.id===currentId);const mastered=cards.filter(c=>c.mastered).length;$('#totalStat').textContent=cards.length;$('#weakStat').textContent=cards.length-mastered;$('#masteredStat').textContent=mastered;$('#deckCount').textContent=`${cards.length} 个单词`;const done=cards.length?mastered:0;$('#progressLabel').textContent=cards.length?`${done} / ${cards.length} 已掌握`:'准备开始';$('#progressBar').style.width=cards.length?`${done/cards.length*100}%`:'0%';const area=$('#studyArea');if(!card){area.innerHTML='<div class="empty"><strong>词库还是空的</strong>添加你的第一个单词,开始积累记忆。</div>';$('#deck').innerHTML='';return}area.innerHTML=`<div class="flashcard ${revealed?'revealed':''}" tabindex="0" role="button" aria-label="${revealed?'答案已显示,点击隐藏':'单词卡片,点击翻开查看答案'}" id="flashcard"><div class="card-top"><span>${cards.indexOf(card)+1} / ${cards.length}</span><span class="tag">${card.mastered?'已掌握':'待加强'}</span></div><div class="word">${escape(card.word)}</div><div class="phonetic">${escape(card.phonetic||'点击翻卡查看释义')}</div><div class="answer"><div class="meaning">${escape(card.meaning)}</div>${card.example?`<div class="example">“${escape(card.example)}”</div>`:''}</div><div class="hint">点击卡片翻开 · 或按空格键</div></div><div class="card-actions"><button class="iconbtn" id="prevBtn" aria-label="上一张">←</button><button class="grade hard" id="hardBtn" ${revealed?'':'disabled'}>还不熟</button><button class="grade easy" id="easyBtn" ${revealed?'':'disabled'}>✓ 已掌握</button><button class="iconbtn" id="nextBtn" aria-label="下一张">→</button></div><div class="studyfoot"><span>卡片可以用键盘操作</span><span><kbd class="kbd">←</kbd> <kbd class="kbd">→</kbd> 切换 <kbd class="kbd">空格</kbd> 翻卡</span></div>`;$('#flashcard').onclick=flip;$('#flashcard').onkeydown=e=>{if(e.key===' '||e.key==='Enter'){e.preventDefault();flip()}};$('#hardBtn').onclick=()=>grade(false);$('#easyBtn').onclick=()=>grade(true);$('#nextBtn').onclick=()=>move(1);$('#prevBtn').onclick=()=>move(-1);$('#deck').innerHTML=cards.map(c=>`<button class="deckrow ${c.id===currentId?'active':''}" data-id="${escape(c.id)}"><span class="dot ${c.mastered?'mastered':''}"></span><span class="rowword">${escape(c.word)}</span><span class="rowmeaning">${escape(c.meaning)}</span></button>`).join('');document.querySelectorAll('.deckrow').forEach(b=>b.onclick=()=>{currentId=b.dataset.id;revealed=false;render()})}function flip(){revealed=!revealed;render()}function move(dir){if(!cards.length)return;const i=cards.findIndex(c=>c.id===currentId);currentId=cards[(i+dir+cards.length)%cards.length].id;revealed=false;render()}function grade(isMastered){const card=cards.find(c=>c.id===currentId);if(!card)return;card.mastered=isMastered;if(!save())return;const remaining=cards.filter(c=>!c.mastered&&c.id!==currentId);currentId=remaining[0]?.id||cards.find(c=>c.id!==currentId)?.id||currentId;revealed=false;render();notify(isMastered?'标记为已掌握。':'已加入优先复习。')}const backdrop=$('#modalBackdrop');function openModal(){backdrop.classList.add('open');$('#wordInput').focus()}function closeModal(){backdrop.classList.remove('open');$('#wordForm').reset();$('#addOpen').focus()}$('#addOpen').onclick=openModal;$('#closeModal').onclick=closeModal;$('#cancelModal').onclick=closeModal;backdrop.onclick=e=>{if(e.target===backdrop)closeModal()};$('#wordForm').onsubmit=e=>{e.preventDefault();const data=new FormData(e.currentTarget);const word=String(data.get('word')).trim(),meaning=String(data.get('meaning')).trim(),example=String(data.get('example')).trim();if(!word||!meaning)return;const duplicate=cards.some(c=>c.word.toLocaleLowerCase()===word.toLocaleLowerCase());const card={id:crypto.randomUUID?crypto.randomUUID():String(Date.now()),word,meaning,example,phonetic:'',mastered:false};cards.unshift(card);if(!save()){cards.shift();return}currentId=card.id;revealed=true;closeModal();render();notify(duplicate?'已添加同名单词。':'单词已添加,来看看答案吧。')};document.addEventListener('keydown',e=>{if(backdrop.classList.contains('open')){if(e.key==='Escape')closeModal();return}if(e.target.matches('input,textarea,button'))return;if(e.key==='ArrowRight')move(1);if(e.key==='ArrowLeft')move(-1);if(e.code==='Space'){e.preventDefault();flip()}});load()})();
+</script></body></html>
\ No newline at end of file
diff --git a/test/e2e/fixtures/app-template-live-20261013/game/index.html b/test/e2e/fixtures/app-template-live-20261013/game/index.html
new file mode 100644
index 00000000..3b707448
--- /dev/null
+++ b/test/e2e/fixtures/app-template-live-20261013/game/index.html
@@ -0,0 +1,27 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#0b1020">
+<title>贪吃蛇 · Snake Arcade</title>
+<style>
+:root{color-scheme:dark;--bg:#0b1020;--panel:#121a2e;--line:#26334d;--muted:#8d9bb4;--lime:#b9f66a;--cyan:#5de4d1;--text:#f3f6fc}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:radial-gradient(ellipse at 50% 0%,#1a2940 0, var(--bg) 58%);color:var(--text);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;display:grid;place-items:center;padding:28px}.app{width:min(100%,940px)}header{display:flex;justify-content:space-between;align-items:center;margin-bottom:22px}.brand{display:flex;align-items:center;gap:12px}.mark{width:42px;height:42px;border-radius:14px;background:var(--lime);display:grid;place-items:center;color:#17200d;font-size:23px}.eyebrow{color:var(--cyan);font-size:11px;letter-spacing:.18em;text-transform:uppercase;font-weight:800}h1{font-size:23px;line-height:1;margin:3px 0 0;letter-spacing:-.04em}.status{font-size:12px;color:var(--muted);display:flex;align-items:center;gap:8px}.dot{width:7px;height:7px;border-radius:50%;background:var(--lime);box-shadow:0 0 10px var(--lime)}.layout{display:grid;grid-template-columns:minmax(0,1fr) 250px;gap:18px}.game,.side{background:linear-gradient(145deg,#151f35,#101729);border:1px solid var(--line);border-radius:20px;box-shadow:0 24px 70px #0005}.game{padding:18px}.scoreline{display:flex;align-items:center;justify-content:space-between;margin:0 2px 14px}.scorebox{display:flex;gap:26px}.label{color:var(--muted);font-size:11px;letter-spacing:.12em;text-transform:uppercase}.number{font-size:25px;font-weight:800;line-height:1.25;font-variant-numeric:tabular-nums}.best .number{color:var(--cyan)}.canvas-wrap{position:relative;overflow:hidden;border-radius:13px;border:1px solid #26324a;background:#0b1323}canvas{display:block;width:100%;height:auto;aspect-ratio:1}.overlay{position:absolute;inset:0;display:grid;place-items:center;background:#09101dcc;text-align:center;padding:24px}.overlay[hidden]{display:none}.overlay-card{max-width:280px}.overlay h2{margin:0 0 5px;font-size:26px;letter-spacing:-.04em}.overlay p{margin:0 0 18px;color:#aab6ca}.btn{border:1px solid #34415c;border-radius:10px;background:#202b42;color:var(--text);padding:10px 14px;font:inherit;font-weight:700;cursor:pointer;transition:transform .15s,border-color .15s,background .15s}.btn:hover{transform:translateY(-1px);border-color:#71819e}.btn:active{transform:translateY(0)}.btn.primary{background:var(--lime);border-color:var(--lime);color:#14200b}.btn:focus-visible,select:focus-visible{outline:3px solid var(--cyan);outline-offset:3px}.actions{display:flex;gap:8px;margin-top:14px}.actions .btn{flex:1}.side{padding:19px;display:flex;flex-direction:column;gap:19px}.side h2{font-size:13px;margin:0 0 9px;color:#dce5f3}.difficulty{display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px}.difficulty button{background:#1b263b;border:1px solid #2d3a53;color:#9eacc2;border-radius:8px;padding:8px 4px;font-size:12px;cursor:pointer}.difficulty button[aria-pressed="true"]{background:#273624;border-color:#759d49;color:var(--lime);font-weight:800}.tip{color:var(--muted);font-size:12px;margin:9px 0 0}.divider{height:1px;background:var(--line)}.key{display:inline-grid;place-items:center;min-width:25px;height:25px;padding:0 5px;border:1px solid #3a4861;border-bottom-width:2px;border-radius:6px;color:#dbe6f5;font-size:11px;font-weight:700}.keys{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;width:112px;margin:0 auto}.keys button{height:36px;padding:0;background:#1c2940;font-size:16px}.keys .empty{visibility:hidden}.controls{text-align:center}.controls .tip{margin-top:8px}.note{font-size:12px;color:var(--muted);line-height:1.65}.note strong{color:#dce5f3}.mobile-only{display:none}@media(max-width:700px){body{padding:18px 14px;align-items:start}.layout{grid-template-columns:1fr}.side{display:grid;grid-template-columns:1fr 1fr;gap:15px;padding:16px}.side .divider{display:none}.note{grid-column:1/-1}.mobile-only{display:block}header{margin-bottom:15px}.status{font-size:11px}.game{padding:13px}.actions{margin-top:11px}}@media(max-width:390px){.side{grid-template-columns:1fr}.note{grid-column:auto}.scorebox{gap:19px}.number{font-size:22px}}@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;transition:none!important}}
+</style>
+</head>
+<body><main class="app"><header><div class="brand"><div class="mark" aria-hidden="true">↗</div><div><div class="eyebrow">Arcade / 01</div><h1>贪吃蛇</h1></div></div><div class="status"><span class="dot" id="statusDot"></span><span id="statusText" aria-live="polite">准备就绪</span></div></header>
+<div class="layout"><section class="game" aria-label="贪吃蛇游戏区域"><div class="scoreline"><div class="scorebox"><div><div class="label">当前得分</div><div class="number" id="score">000</div></div><div class="best"><div class="label">最高分</div><div class="number" id="best">000</div></div></div><span class="eyebrow" id="levelTag">NORMAL</span></div><div class="canvas-wrap"><canvas id="board" width="480" height="480" role="img" aria-label="贪吃蛇游戏棋盘"></canvas><div class="overlay" id="overlay"><div class="overlay-card"><h2 id="overlayTitle">准备好了吗?</h2><p id="overlayText">吃掉闪亮的果实,挑战你的最高分。</p><button class="btn primary" id="overlayButton">开始游戏</button></div></div></div><div class="actions"><button class="btn primary" id="toggleBtn">开始游戏</button><button class="btn" id="restartBtn">重新开始</button></div></section>
+<aside class="side"><section><h2>难度</h2><div class="difficulty" role="group" aria-label="选择游戏难度"><button data-speed="180" aria-pressed="false">轻松</button><button data-speed="125" aria-pressed="true">标准</button><button data-speed="82" aria-pressed="false">疾速</button></div><p class="tip">难度可在游戏中随时调整</p></section><div class="divider"></div><section class="controls"><h2>方向控制</h2><div class="keys" aria-label="方向按钮"><span class="empty"></span><button class="btn" data-dir="up" aria-label="向上">↑</button><span class="empty"></span><button class="btn" data-dir="left" aria-label="向左">←</button><button class="btn" data-dir="down" aria-label="向下">↓</button><button class="btn" data-dir="right" aria-label="向右">→</button></div><p class="tip">方向键控制 <span class="mobile-only">· 也可点按</span></p></section><div class="divider"></div><section class="note"><strong>怎么玩</strong><br>收集果实,蛇身会逐渐变长。撞到墙壁或自己,游戏就会结束。按 <span class="key">Space</span> 暂停 / 继续。</section></aside></div></main>
+<script>
+(()=>{'use strict';const canvas=document.querySelector('#board'),ctx=canvas.getContext('2d'),scoreEl=document.querySelector('#score'),bestEl=document.querySelector('#best'),overlay=document.querySelector('#overlay'),overlayTitle=document.querySelector('#overlayTitle'),overlayText=document.querySelector('#overlayText'),overlayButton=document.querySelector('#overlayButton'),toggleBtn=document.querySelector('#toggleBtn'),statusText=document.querySelector('#statusText'),statusDot=document.querySelector('#statusDot'),levelTag=document.querySelector('#levelTag');const N=24,C=20;let snake,food,dir,nextDir,score,best=0,speed=125,timer=null,state='ready';try{best=Number(localStorage.getItem('snake-best'))||0}catch{}bestEl.textContent=String(best).padStart(3,'0');const levels={180:'EASY',125:'NORMAL',82:'FAST'};
+function newGame(){clearInterval(timer);snake=[{x:7,y:12},{x:6,y:12},{x:5,y:12}];dir={x:1,y:0};nextDir={...dir};score=0;scoreEl.textContent='000';placeFood();state='ready';render();showOverlay('准备好了吗?','吃掉闪亮的果实,挑战你的最高分。','开始游戏');updateStatus('准备就绪')}
+function placeFood(){do{food={x:Math.floor(Math.random()*N),y:Math.floor(Math.random()*N)}}while(snake?.some(p=>p.x===food.x&&p.y===food.y))}
+function render(){ctx.fillStyle='#0b1323';ctx.fillRect(0,0,480,480);ctx.strokeStyle='rgba(130,158,194,.055)';ctx.lineWidth=1;for(let i=1;i<N;i++){ctx.beginPath();ctx.moveTo(i*C,0);ctx.lineTo(i*C,480);ctx.stroke();ctx.beginPath();ctx.moveTo(0,i*C);ctx.lineTo(480,i*C);ctx.stroke()}ctx.fillStyle='#ff6b82';ctx.shadowColor='#ff5774';ctx.shadowBlur=16;ctx.beginPath();ctx.arc(food.x*C+10,food.y*C+10,6.7,0,Math.PI*2);ctx.fill();ctx.shadowBlur=0;snake.forEach((p,i)=>{const inset=i===0?2.4:3.2;ctx.fillStyle=i===0?'#c7ff78':`rgba(111,205,119,${Math.max(.55,1-i*.018)})`;ctx.beginPath();ctx.roundRect(p.x*C+inset,p.y*C+inset,C-inset*2,C-inset*2,i===0?6:5);ctx.fill()});const h=snake[0];ctx.fillStyle='#17200d';const eyeX=dir.x===1?14:dir.x===-1?6:dir.x===0?7:null;ctx.beginPath();if(dir.x!==0){ctx.arc(h.x*C+eyeX,h.y*C+7,1.2,0,7);ctx.arc(h.x*C+eyeX,h.y*C+13,1.2,0,7)}else{ctx.arc(h.x*C+7,h.y*C+(dir.y===1?14:6),1.2,0,7);ctx.arc(h.x*C+13,h.y*C+(dir.y===1?14:6),1.2,0,7)}ctx.fill()}
+function tick(){dir=nextDir;const head={x:snake[0].x+dir.x,y:snake[0].y+dir.y},eats=head.x===food.x&&head.y===food.y;if(head.x<0||head.y<0||head.x>=N||head.y>=N||snake.slice(0,eats?undefined:-1).some(p=>p.x===head.x&&p.y===head.y)){endGame();return}snake.unshift(head);if(eats){score+=10;scoreEl.textContent=String(score).padStart(3,'0');if(score>best){best=score;bestEl.textContent=String(best).padStart(3,'0');try{localStorage.setItem('snake-best',String(best))}catch{}}placeFood()}else snake.pop();render()}
+function start(){if(state==='running')return;overlay.hidden=true;state='running';clearInterval(timer);timer=setInterval(tick,speed);toggleBtn.textContent='暂停';updateStatus('游戏进行中')}
+function pause(){if(state!=='running')return;clearInterval(timer);timer=null;state='paused';showOverlay('游戏已暂停','稍作休息,准备好后继续。','继续游戏');toggleBtn.textContent='继续';updateStatus('已暂停')}
+function endGame(){clearInterval(timer);timer=null;state='over';showOverlay('游戏结束',`本局得分 ${score} · 再来一局?`,'重新开始');toggleBtn.textContent='重新开始';updateStatus('游戏结束')}
+function showOverlay(title,text,button){overlayTitle.textContent=title;overlayText.textContent=text;overlayButton.textContent=button;overlay.hidden=false}
+function updateStatus(s){statusText.textContent=s;statusDot.style.background=state==='running'?'var(--lime)':state==='over'?'#ff6b82':'#8d9bb4';statusDot.style.boxShadow=state==='running'?'0 0 10px var(--lime)':'none'}
+function setDirection(name){const d={up:{x:0,y:-1},down:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0}}[name];if(!d||d.x===-dir.x&&d.y===-dir.y)return;nextDir=d;if(state==='ready')start()}
+document.addEventListener('keydown',e=>{const map={ArrowUp:'up',ArrowDown:'down',ArrowLeft:'left',ArrowRight:'right',w:'up',s:'down',a:'left',d:'right'};if(map[e.key]){e.preventDefault();setDirection(map[e.key])}else if(e.code==='Space'){e.preventDefault();state==='running'?pause():state==='paused'?start():state==='ready'?start():newGame()}});document.querySelectorAll('[data-dir]').forEach(b=>b.addEventListener('click',()=>setDirection(b.dataset.dir)));document.querySelectorAll('[data-speed]').forEach(b=>b.addEventListener('click',()=>{speed=Number(b.dataset.speed);levelTag.textContent=levels[speed];document.querySelectorAll('[data-speed]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)));if(state==='running'){clearInterval(timer);timer=setInterval(tick,speed)}}));toggleBtn.addEventListener('click',()=>state==='running'?pause():state==='paused'||state==='ready'?start():newGame());overlayButton.addEventListener('click',()=>{if(state==='paused')start();else if(state==='over'){newGame();start()}else start()});document.querySelector('#restartBtn').addEventListener('click',()=>{newGame();start()});newGame();
+})();
+</script></body></html>
\ No newline at end of file
diff --git a/test/e2e/fixtures/app-template-live-20261013/products/index.html b/test/e2e/fixtures/app-template-live-20261013/products/index.html
new file mode 100644
index 00000000..ef87a1f7
--- /dev/null
+++ b/test/e2e/fixtures/app-template-live-20261013/products/index.html
@@ -0,0 +1,36 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f6f7f5">
+<title>库存台账 · 商品管理</title>
+<style>
+:root{color-scheme:light;--ink:#17221d;--muted:#626e67;--line:#e8ece8;--green:#176b4b;--pale:#e9f4ee;--bg:#f6f7f5;--white:#fff;--red:#b83d36;--shadow:0 10px 34px #15231b0a}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}button,input{font:inherit}button{cursor:pointer}.shell{max-width:1160px;margin:auto;padding:34px 36px 56px}.topbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:52px}.brand{display:flex;align-items:center;gap:11px;font-size:16px;font-weight:750;letter-spacing:-.3px}.brand-icon{width:36px;height:36px;border-radius:11px;background:var(--green);color:white;display:grid;place-items:center}.brand-icon svg{width:20px}.top-note{font-size:13px;color:var(--muted)}.intro{display:flex;justify-content:space-between;align-items:flex-end;margin-bottom:28px;gap:20px}.eyebrow{font-size:12px;letter-spacing:1.4px;text-transform:uppercase;color:var(--green);font-weight:750;margin:0 0 8px}.intro h1{font-size:34px;letter-spacing:-1.1px;line-height:1.15;margin:0}.subtitle{margin:10px 0 0;color:var(--muted)}.primary{border:0;border-radius:9px;background:var(--green);color:white;font-weight:650;padding:11px 16px;display:inline-flex;align-items:center;gap:8px;box-shadow:0 3px 8px #176b4b20}.primary:hover{background:#12593e}.primary:focus-visible,.secondary:focus-visible,.icon-btn:focus-visible,.search:focus-visible,input:focus-visible{outline:3px solid #69bb94;outline-offset:2px}.plus{font-size:21px;line-height:16px;font-weight:400}.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:15px;margin-bottom:24px}.stat{background:var(--white);border:1px solid var(--line);border-radius:12px;padding:19px 21px;box-shadow:var(--shadow)}.stat-label{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:13px}.dot{width:8px;height:8px;border-radius:50%;background:#92c7a8}.dot.amber{background:#e6ad54}.dot.blue{background:#82a8cc}.stat-value{font-size:27px;font-weight:720;letter-spacing:-.8px;margin-top:8px}.toolbar{display:flex;align-items:center;justify-content:space-between;margin:27px 0 13px;gap:16px}.section-title{font-size:16px;font-weight:700}.count{font-size:12px;color:var(--muted);font-weight:500;margin-left:7px}.search-wrap{position:relative;width:min(280px,45%)}.search-icon{position:absolute;left:12px;top:10px;width:17px;height:17px;color:#89938e}.search{width:100%;border:1px solid #e1e6e2;background:white;border-radius:8px;padding:9px 12px 9px 37px;color:var(--ink)}.search::placeholder{color:#a1aaa5}.table-wrap{background:white;border:1px solid var(--line);border-radius:12px;overflow:hidden;box-shadow:var(--shadow)}table{width:100%;border-collapse:collapse;text-align:left}thead{background:#fafbfa}th{height:45px;padding:0 21px;font-size:11px;color:#626e67;letter-spacing:.65px;font-weight:700;text-transform:uppercase}td{padding:15px 21px;border-top:1px solid #edf0ed;font-size:14px}tbody tr:hover{background:#fcfdfc}.product{font-weight:650}.price{font-variant-numeric:tabular-nums}.stock{font-variant-numeric:tabular-nums}.stock-pill{display:inline-flex;align-items:center;gap:7px}.stock-pill:before{content:"";width:7px;height:7px;border-radius:50%;background:#63a77f}.stock-pill.low:before{background:#e4a34a}.stock-pill.out:before{background:#d66d65}.stock-pill.low,.stock-pill.out{color:#a9632a}.stock-pill.out{color:#b34840}.actions{display:flex;justify-content:flex-end;gap:7px}.icon-btn{width:33px;height:33px;border:1px solid transparent;border-radius:7px;background:transparent;color:#7a8580;display:grid;place-items:center}.icon-btn:hover{background:#f1f5f2;color:var(--green)}.icon-btn.delete:hover{background:#fff1f0;color:var(--red)}.icon-btn svg{width:16px;height:16px}.empty{text-align:center;padding:58px 16px;color:var(--muted)}.empty strong{display:block;color:var(--ink);font-size:15px;margin-bottom:5px}.empty button{margin-top:15px}.status{min-height:22px;margin:12px 2px;color:var(--green);font-size:13px}.status.error{color:var(--red)}dialog{border:0;padding:0;width:min(440px,calc(100% - 32px));border-radius:15px;box-shadow:0 24px 80px #12201930;color:var(--ink)}dialog::backdrop{background:#10201970;backdrop-filter:blur(2px)}.modal{padding:25px}.modal-head{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:21px}.modal h2{font-size:20px;margin:0;letter-spacing:-.4px}.modal-desc{margin:5px 0 0;color:var(--muted);font-size:13px}.close{border:0;background:transparent;color:#78827c;font-size:23px;line-height:1;padding:0 3px}.field{display:block;margin:15px 0}.field span{display:block;font-size:13px;font-weight:600;margin-bottom:6px}.field input{width:100%;border:1px solid #dfe5e0;border-radius:8px;padding:10px 11px;background:white}.field input::placeholder{color:#a2aaa5}.field input[aria-invalid=true]{border-color:var(--red)}.hint{font-size:12px;color:var(--muted);margin-top:4px}.form-error{color:var(--red);min-height:20px;font-size:13px}.modal-actions{display:flex;justify-content:flex-end;gap:9px;margin-top:15px}.secondary{border:1px solid #dfe5e0;border-radius:8px;background:white;padding:10px 15px;color:#35413a;font-weight:600}.confirm-copy{color:var(--muted);margin:12px 0 22px}.danger{background:var(--red)}.danger:hover{background:#9e302b}footer{margin-top:21px;color:#626e67;font-size:12px;display:flex;justify-content:space-between;gap:10px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:680px){.shell{padding:22px 16px 36px}.topbar{margin-bottom:36px}.top-note{display:none}.intro{align-items:flex-start;flex-direction:column}.intro h1{font-size:29px}.stats{gap:8px}.stat{padding:14px 12px}.stat-label{font-size:11px;gap:5px}.stat-value{font-size:22px}.toolbar{align-items:flex-start}.search-wrap{width:52%}.table-wrap{overflow-x:auto}table{min-width:570px}th,td{padding-left:14px;padding-right:14px}footer{flex-direction:column}}@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}
+</style>
+</head>
+<body>
+<div class="shell">
+<header class="topbar"><div class="brand"><span class="brand-icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="m4 7 8-4 8 4v10l-8 4-8-4z"/><path d="m4 7 8 4 8-4M12 11v10M8 5l8 4"/></svg></span>库存台账</div><div class="top-note">轻松管理每一件商品</div></header>
+<main><section class="intro"><div><p class="eyebrow">Inventory overview</p><h1>商品库存</h1><p class="subtitle">清晰掌握商品与库存动态</p></div><button class="primary" id="addBtn"><span class="plus" aria-hidden="true">+</span>添加商品</button></section>
+<section class="stats" aria-label="库存统计"><article class="stat"><div class="stat-label"><i class="dot"></i>商品种类</div><div class="stat-value" id="kindStat">0</div></article><article class="stat"><div class="stat-label"><i class="dot blue"></i>库存总量</div><div class="stat-value" id="unitsStat">0</div></article><article class="stat"><div class="stat-label"><i class="dot amber"></i>库存金额</div><div class="stat-value" id="valueStat">¥0.00</div></article></section>
+<div class="toolbar"><div class="section-title">全部商品 <span class="count" id="countLabel">0 件</span></div><div class="search-wrap"><svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><circle cx="10.8" cy="10.8" r="6.8"/><path d="m16 16 4.5 4.5"/></svg><label class="sr-only" for="search">搜索商品名称</label><input id="search" class="search" type="search" placeholder="搜索商品…" autocomplete="off"></div></div>
+<div class="table-wrap"><table><thead><tr><th scope="col">商品名称</th><th scope="col">售价</th><th scope="col">库存数量</th><th scope="col" style="text-align:right">操作</th></tr></thead><tbody id="rows"></tbody></table><div id="empty" class="empty" hidden><strong id="emptyTitle">还没有商品</strong><span id="emptyCopy">添加第一件商品,开始管理库存。</span><br><button class="primary" id="emptyAdd"><span class="plus" aria-hidden="true">+</span>添加商品</button></div></div><p id="status" class="status" role="status" aria-live="polite"></p>
+</main><footer><span>数据保存在此浏览器中</span><span>商品售价与库存随时可更新</span></footer></div>
+<dialog id="productDialog" aria-labelledby="formTitle"><form class="modal" id="productForm"><div class="modal-head"><div><h2 id="formTitle">添加商品</h2><p class="modal-desc">填写商品信息,稍后也可以修改。</p></div><button class="close" type="button" data-close aria-label="关闭">×</button></div><label class="field"><span>商品名称</span><input id="name" name="name" maxlength="80" placeholder="例如:无线耳机" required autocomplete="off"><span class="hint">最多 80 个字符</span></label><label class="field"><span>售价(元)</span><input id="price" name="price" type="number" min="0" max="100000000" step="0.01" placeholder="0.00" required></label><label class="field"><span>库存数量</span><input id="quantity" name="quantity" type="number" min="0" max="100000000" step="1" placeholder="0" required></label><p class="form-error" id="formError" role="alert"></p><div class="modal-actions"><button class="secondary" type="button" data-close>取消</button><button class="primary" type="submit" id="saveBtn">保存商品</button></div></form></dialog>
+<dialog id="deleteDialog" aria-labelledby="deleteTitle"><div class="modal"><div class="modal-head"><div><h2 id="deleteTitle">删除商品?</h2><p class="modal-desc">此操作无法撤销</p></div><button class="close" type="button" data-close aria-label="关闭">×</button></div><p class="confirm-copy" id="deleteCopy"></p><div class="modal-actions"><button class="secondary" type="button" data-close>取消</button><button class="primary danger" type="button" id="confirmDelete">删除商品</button></div></div></dialog>
+<script>
+(()=>{'use strict';
+const KEY='inventory-ledger-products-v1', rows=document.querySelector('#rows'), empty=document.querySelector('#empty'), search=document.querySelector('#search'), status=document.querySelector('#status'), form=document.querySelector('#productForm'), productDialog=document.querySelector('#productDialog'), deleteDialog=document.querySelector('#deleteDialog');let products=[], editingId=null, deletingId=null;
+const escapeHTML=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));const money=n=>'¥'+Number(n).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2});
+function announce(message,error=false){status.textContent=message;status.classList.toggle('error',error)}
+function persist(){try{localStorage.setItem(KEY,JSON.stringify(products));return true}catch(e){announce('保存失败:浏览器存储不可用或空间不足,请检查浏览器设置后重试。',true);return false}}
+function load(){try{const raw=localStorage.getItem(KEY);if(raw===null)return;const parsed=JSON.parse(raw);if(Array.isArray(parsed))products=parsed.filter(p=>p&&typeof p.id==='string'&&typeof p.name==='string'&&Number.isFinite(p.price)&&Number.isInteger(p.quantity)&&p.price>=0&&p.quantity>=0)}catch(e){announce('无法读取已保存的数据;现有数据保持不变。',true)}}
+function render(){const query=search.value.trim().toLocaleLowerCase('zh-CN');const visible=products.filter(p=>p.name.toLocaleLowerCase('zh-CN').includes(query));document.querySelector('#kindStat').textContent=products.length.toLocaleString('zh-CN');document.querySelector('#unitsStat').textContent=products.reduce((sum,p)=>sum+p.quantity,0).toLocaleString('zh-CN');document.querySelector('#valueStat').textContent=money(products.reduce((sum,p)=>sum+p.price*p.quantity,0));document.querySelector('#countLabel').textContent=`${products.length} 件`;rows.innerHTML=visible.map(p=>{const stock=p.quantity===0?'out':p.quantity<=5?'low':'';return `<tr><td class="product">${escapeHTML(p.name)}</td><td class="price">${money(p.price)}</td><td class="stock"><span class="stock-pill ${stock}">${p.quantity.toLocaleString('zh-CN')} 件${p.quantity===0?' · 缺货':p.quantity<=5?' · 库存偏低':''}</span></td><td><div class="actions"><button class="icon-btn" data-action="edit" data-id="${escapeHTML(p.id)}" aria-label="编辑 ${escapeHTML(p.name)}" title="编辑"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="m14 5 5 5M4 20l4.5-.9L19 8.6a2.1 2.1 0 0 0-3-3L5.5 16.1 4 20Z"/></svg></button><button class="icon-btn delete" data-action="delete" data-id="${escapeHTML(p.id)}" aria-label="删除 ${escapeHTML(p.name)}" title="删除"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M4 7h16M10 11v6m4-6v6M5.5 7l1 13h11l1-13M9 7V4h6v3"/></svg></button></div></td></tr>`}).join('');empty.hidden=visible.length!==0;document.querySelector('#emptyTitle').textContent=products.length?'没有找到匹配的商品':'还没有商品';document.querySelector('#emptyCopy').textContent=products.length?'试试其他商品名称。':'添加第一件商品,开始管理库存。';document.querySelector('#emptyAdd').hidden=products.length>0}
+function openForm(product=null){editingId=product?.id||null;form.reset();document.querySelector('#formTitle').textContent=product?'编辑商品':'添加商品';document.querySelector('.modal-desc').textContent=product?'修改商品信息,保存后立即更新。':'填写商品信息,稍后也可以修改。';document.querySelector('#saveBtn').textContent=product?'保存修改':'保存商品';document.querySelector('#formError').textContent='';if(product){form.name.value=product.name;form.price.value=product.price;form.quantity.value=product.quantity}productDialog.showModal();form.name.focus()}
+document.querySelector('#addBtn').addEventListener('click',()=>openForm());document.querySelector('#emptyAdd').addEventListener('click',()=>openForm());document.querySelectorAll('[data-close]').forEach(b=>b.addEventListener('click',()=>b.closest('dialog').close()));search.addEventListener('input',render);
+rows.addEventListener('click',e=>{const btn=e.target.closest('button[data-action]');if(!btn)return;const item=products.find(p=>p.id===btn.dataset.id);if(!item)return;if(btn.dataset.action==='edit')openForm(item);else{deletingId=item.id;document.querySelector('#deleteCopy').textContent=`「${item.name}」將從庫存清單中移除。`;deleteDialog.showModal();document.querySelector('#confirmDelete').focus()}});
+form.addEventListener('submit',e=>{e.preventDefault();const name=form.name.value.trim(),price=Number(form.price.value),quantity=Number(form.quantity.value),error=document.querySelector('#formError');error.textContent='';if(!name){error.textContent='請輸入商品名稱。';form.name.focus();return}if(!Number.isFinite(price)||price<0||price>100000000){error.textContent='請輸入有效的非負售價。';form.price.focus();return}if(!Number.isSafeInteger(quantity)||quantity<0||quantity>100000000){error.textContent='庫存數量必須是有效的非負整數。';form.quantity.focus();return}const previous=products;if(editingId)products=products.map(p=>p.id===editingId?{...p,name,price,quantity}:p);else products=[...products,{id:crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,name,price,quantity}];if(!persist()){products=previous;return}productDialog.close();render();announce(editingId?'商品已更新。':'商品已添加。')});
+document.querySelector('#confirmDelete').addEventListener('click',()=>{const previous=products;products=products.filter(p=>p.id!==deletingId);if(!persist()){products=previous;return}deleteDialog.close();render();announce('商品已删除。');deletingId=null});
+productDialog.addEventListener('click',e=>{if(e.target===productDialog)productDialog.close()});deleteDialog.addEventListener('click',e=>{if(e.target===deleteDialog)deleteDialog.close()});load();render();
+})();
+</script>
+</body></html>
\ No newline at end of file
diff --git a/test/e2e/fixtures/web-app-author-main.ts b/test/e2e/fixtures/web-app-author-main.ts
new file mode 100644
index 00000000..007aefd4
--- /dev/null
+++ b/test/e2e/fixtures/web-app-author-main.ts
@@ -0,0 +1,21 @@
+/** Observe real host calls, never accept receipts written by generated code. */
+export async function observeWebAppCalls() {
+ const { WebAppRuntime } = await import('../../../src/main/features/web_apps/runtime');
+ const original = WebAppRuntime.prototype.call;
+ const calls: Array<{method:string;ok:boolean;code?:string}> = [];
+ WebAppRuntime.prototype.call = async function (...args: Parameters<typeof original>) {
+ try { const result = await original.apply(this,args); calls.push({method:args[4],ok:true}); return result; }
+ catch (error) { calls.push({method:args[4],ok:false,code:(error as any).code || 'E_FAILED'}); throw error; }
+ };
+ return { read:() => [...calls], restore:() => { WebAppRuntime.prototype.call = original; } };
+}
+
+/** Model availability is a simulated host prerequisite; the real runtime still
+ * owns capability checks, rejection, SDK delivery and explicit retry. */
+let restoreModelAvailability: (() => boolean) | undefined;
+export async function setWebAppModelAvailable(available: boolean) {
+ const { runtime } = await import('../../../src/main/features/web_apps/host');
+ const host = (runtime as any).host;
+ if (!restoreModelAvailability) restoreModelAvailability = host.modelAvailable;
+ host.modelAvailable = available ? restoreModelAvailability : () => false;
+}
diff --git a/test/e2e/html_preview_e2e_generated_controls.spec.ts b/test/e2e/html_preview_e2e_generated_controls.spec.ts
index 0bda8a7b..2c3a72f2 100644
--- a/test/e2e/html_preview_e2e_generated_controls.spec.ts
+++ b/test/e2e/html_preview_e2e_generated_controls.spec.ts
@@ -2,6 +2,107 @@ import { readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { test } from './fixtures/web-app-eval';
import { expect } from './fixtures/orkas';
+import type { HtmlPreviewDesignEvidence } from '../../src/main/features/html_preview';
+
+for (const broken of [false, true]) {
+ test(`fills an editor before download and retains empty-payload rejection (${broken ? 'broken' : 'working'})`, async ({ sdkOrkas: orkas }, info) => {
+ const entry = orkas.createWorkspaceFile('editor/index.html', `<!doctype html>
+ <style>button:focus-visible,textarea:focus-visible{outline:2px solid blue}</style>
+ <label>Draft<textarea id="draft"></textarea></label><button id="download">Download</button>
+ <script>
+ let edits=0;
+ const draft=document.getElementById('draft');
+ draft.addEventListener('input',()=>edits++);
+ document.getElementById('download').onclick=()=>{
+ const a=document.createElement('a');
+ a.download='draft-'+edits+'.txt';
+ a.href=URL.createObjectURL(new Blob([${broken ? "''" : 'draft.value'}],{type:'text/plain'}));
+ a.click();
+ };
+ </script>`);
+ for (const artifact of [false, true]) {
+ const evidence = await orkas.electronApp!.evaluate(async (_, args) => {
+ const preview = (process as any).mainModule.require(args.modulePath);
+ return (await (args.artifact ? preview.renderInteractiveHtmlSmoke(args.entry)
+ : preview.renderResponsiveHtmlPreview(args.entry, [{name:'desktop',width:1280,height:800}]))).evidence;
+ }, {entry,artifact,modulePath:path.resolve(__dirname,'../../src/main/features/html_preview.ts')});
+ writeFileSync(info.outputPath(`editor-${artifact}.json`), JSON.stringify({...evidence,entryPath:undefined},null,2));
+ expect(evidence.interactions.downloads).toHaveLength(1);
+ expect(evidence.interactions.downloads[0]).toMatchObject({filename:'draft-1.txt',mimeType:'text/plain'});
+ expect(evidence.interactions.downloads[0].totalBytes > 0).toBe(!broken);
+ expect(evidence.ok).toBe(!broken);
+ expect(evidence.blockers).toEqual(broken
+ ? ['1 observed download(s) lacked a filename, MIME type, or non-empty payload'] : []);
+ }
+ });
+}
+
+test('fills newly revealed fields before their action without editing earlier fields twice', async ({ sdkOrkas: orkas }, info) => {
+ const entry = orkas.createWorkspaceFile('revealed-editor/index.html', `<!doctype html>
+ <style>button:focus-visible,input:focus-visible{outline:2px solid blue}</style>
+ <input id="title" aria-label="Title"><button id="open">Open editor</button><div id="editor"></div>
+ <script>
+ let edits=0;
+ document.getElementById('title').addEventListener('input',()=>edits++);
+ document.getElementById('open').onclick=()=>{
+ document.getElementById('editor').innerHTML='<input id="body" aria-label="Body"><button id="save">Save</button>';
+ document.getElementById('save').onclick=()=>{
+ const a=document.createElement('a');
+ a.download='saved-'+edits+'.txt';
+ a.href=URL.createObjectURL(new Blob([document.getElementById('body').value],{type:'text/plain'}));
+ a.click();
+ };
+ };
+ </script>`);
+ const evidence = await orkas.electronApp!.evaluate(async (_, args) => {
+ const { renderResponsiveHtmlPreview } = (process as any).mainModule.require(args.modulePath);
+ return (await renderResponsiveHtmlPreview(args.entry,[{name:'desktop',width:1280,height:800}])).evidence;
+ }, {entry,modulePath:path.resolve(__dirname,'../../src/main/features/html_preview.ts')});
+ writeFileSync(info.outputPath('revealed-editor.json'),JSON.stringify({...evidence,entryPath:undefined},null,2));
+ expect(evidence.interactions.downloads).toHaveLength(1);
+ expect(evidence.interactions.downloads[0]).toMatchObject({filename:'saved-1.txt',mimeType:'text/plain'});
+ expect(evidence.interactions.downloads[0].totalBytes).toBeGreaterThan(0);
+ expect(evidence.interactions.stateControlsExercised).toBe(2);
+ expect(evidence.blockers).toEqual([]);
+ expect(evidence.ok).toBe(true);
+});
+
+test('reports low contrast for equivalent legacy and CSS Color 4 paints', async ({ sdkOrkas: orkas }) => {
+ const entry = orkas.createWorkspaceFile('color-audit/index.html', `<!doctype html>
+ <style>body{background:white;font:16px sans-serif}button{color:black}
+ #legacy{color:#ccc}#srgb{color:color(srgb 0.8 0.8 0.8)}#lch{color:oklch(0.9 0 0)}</style>
+ <button>Focusable</button><p id="legacy">Light text</p><p id="srgb">Equivalent light text</p>
+ <p id="lch">Light neutral text</p>`);
+ const evidence = await orkas.electronApp!.evaluate(async (_, args) => {
+ const { renderResponsiveHtmlPreview } = (process as any).mainModule.require(args.modulePath);
+ return (await renderResponsiveHtmlPreview(args.entry, [{ name: 'desktop', width: 1280, height: 800 }], {},
+ { interactions: false })).evidence;
+ }, { entry, modulePath: path.resolve(__dirname, '../../src/main/features/html_preview.ts') });
+ const design = evidence.viewports[0].design as HtmlPreviewDesignEvidence;
+ expect(design.lowContrastText.map(item => item.selector).sort()).toEqual(['#lch', '#legacy', '#srgb']);
+ const legacy = design.lowContrastText.find(item => item.selector === '#legacy');
+ const equivalent = design.lowContrastText.find(item => item.selector === '#srgb');
+ expect(equivalent).toMatchObject({ color: legacy!.color, background: legacy!.background, ratio: legacy!.ratio });
+ expect(design.lowContrastText.some(item => item.selector === 'button')).toBe(false);
+ expect(evidence.ok).toBe(true);
+});
+
+test('retains measured findings and marks a large document audit as partial', async ({ sdkOrkas: orkas }) => {
+ const entry = orkas.createWorkspaceFile('bounded-audit/index.html', `<!doctype html>
+ <style>body{background:white;font:16px sans-serif}p{color:#ccc}</style>
+ <button>Focusable</button><p id="early">Known light text</p>${'<i hidden></i>'.repeat(6000)}
+ <p id="late">Light text after the scan boundary</p>`);
+ const evidence = await orkas.electronApp!.evaluate(async (_, args) => {
+ const { renderResponsiveHtmlPreview } = (process as any).mainModule.require(args.modulePath);
+ return (await renderResponsiveHtmlPreview(args.entry, [{ name: 'desktop', width: 1280, height: 800 }], {},
+ { interactions: false })).evidence;
+ }, { entry, modulePath: path.resolve(__dirname, '../../src/main/features/html_preview.ts') });
+ const design = evidence.viewports[0].design as HtmlPreviewDesignEvidence & { incomplete?: string[] };
+ expect(design.lowContrastText.map(item => item.selector)).toContain('#early');
+ expect(design.incomplete).toContain('element_limit');
+ expect(design.error).toBeUndefined();
+ expect(evidence.ok).toBe(true);
+});
test('discovers post-submit controls and identifies an ineffective generated flip', async ({ sdkOrkas: orkas }, info) => {
const source = readFileSync(path.join(__dirname, 'fixtures/app-template-flashcards/list-inline-defect.html'), 'utf8');
diff --git a/test/e2e/preview_recovery_e2e_evidence.spec.ts b/test/e2e/preview_recovery_e2e_evidence.spec.ts
index 311fa411..4b9e70e0 100644
--- a/test/e2e/preview_recovery_e2e_evidence.spec.ts
+++ b/test/e2e/preview_recovery_e2e_evidence.spec.ts
@@ -1,7 +1,7 @@
import path from 'node:path';
import { writeFileSync } from 'node:fs';
import { test } from './fixtures/web-app-eval';
-import { expect } from './fixtures/orkas';
+import { openSidebarEntry, expect } from './fixtures/orkas';
import { recoveredPreviewWindows } from './fixtures/preview-recovery';
for (const errorKind of ['pageerror', 'console'] as const) {
@@ -48,7 +48,7 @@ for (const errorKind of ['pageerror', 'console'] as const) {
// Independent final UI behavior is still exercised, not inferred from the log.
const saved = await orkas.invoke<{ok:boolean;id:string}>('savedApps.saveFromPath', {path:entry,title:'Recovered app'});
expect(saved.ok).toBe(true);
- await orkas.page.locator('#apps-btn').click();
+ await openSidebarEntry(orkas.page, '#apps-btn');
const panel = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${saved.id}"]`).click());
const frame = panel.locator('.saved-app-viewer-frame').contentFrame();
await frame.getByRole('textbox', {name:'Name'}).fill('Independent test');
diff --git a/test/e2e/preview_windows_e2e_lifecycle.spec.ts b/test/e2e/preview_windows_e2e_lifecycle.spec.ts
index 0c9f5dd7..62f88634 100644
--- a/test/e2e/preview_windows_e2e_lifecycle.spec.ts
+++ b/test/e2e/preview_windows_e2e_lifecycle.spec.ts
@@ -265,15 +265,22 @@ test('presentation fills the native window and retains its slide content on resi
const file = path.join(orkas.userWorkspaceRoot, 'preview-deck.pptx');
await orkas.electronApp!.evaluate(async (_electron, args) => {
const engine = (process as any).mainModule.require(args.module);
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const verify = (stage: string, result: { code: number; stdout: string; stderr: string }) => {
+ const diagnostic = JSON.stringify({ stage, code: result.code,
+ stdoutChars: result.stdout.length, stderrChars: result.stderr.length });
+ req('node:assert/strict').equal(result.code, 0, diagnostic);
+ };
const options = { cwd: args.cwd };
try {
- await engine.runOfficeCli(['create', args.file, '--force', '--json'], options);
- await engine.runOfficeCli(['batch', args.file, '--stop-on-error', '--json'], {
+ verify('create', await engine.runOfficeCli(['create', args.file, '--force', '--json'], options));
+ verify('batch', await engine.runOfficeCli(['batch', args.file, '--stop-on-error', '--json'], {
...options, stdin: JSON.stringify([
{ command: 'add', parent: '/', type: 'slide', props: { title: 'Quarterly review', text: 'Progress and next steps' } },
{ command: 'add', parent: '/', type: 'slide', props: { title: 'Next steps', text: 'Review the proposed changes' } },
]),
- });
+ }));
+ req('node:assert/strict').equal(req('node:fs').existsSync(args.file), true, 'Office fixture must exist before native preview');
} finally { await engine.closeOfficeFile(args.file, args.cwd); }
}, { module: path.resolve(__dirname, '../../src/main/features/office/office_engine.ts'), file, cwd: orkas.userWorkspaceRoot });
const preview = await orkas.openPreview(() => orkas.page!.evaluate(file =>
diff --git a/test/e2e/saved_apps_e2e_lifecycle.spec.ts b/test/e2e/saved_apps_e2e_lifecycle.spec.ts
index f5d03031..daf403a0 100644
--- a/test/e2e/saved_apps_e2e_lifecycle.spec.ts
+++ b/test/e2e/saved_apps_e2e_lifecycle.spec.ts
@@ -1,5 +1,115 @@
+import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
import { expectComposerText } from './fixtures/composer';
-import { expect, test } from './fixtures/orkas';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+declare const currentCid: string;
+
+function historicalArtifact(root: string, cid: string, appType?: string, title = 'Historic app') {
+ const artifactId = 'historical-' + (appType || 'untyped');
+ const dir = path.join(root, 'account-e2e/cloud/chat_artifacts', cid, artifactId);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, 'index.html'), '<!doctype html><h1>Retained historical app</h1>');
+ writeFileSync(path.join(dir, '__orkas-meta.json'), JSON.stringify({ title, appType, entry: 'index.html', agentId: 'commander' }));
+ return { ok: true, artifactId, title };
+}
+
+
+
+
+test('root-level Save as app explains the separate-folder requirement and saves only the recovered bundle', async ({ orkas }, testInfo) => {
+ const page=orkas.page!;
+ const source=orkas.createWorkspaceFile('小工具.html','<!doctype html><html lang="zh"><meta charset="utf-8"><title>小工具</title><body><h1>小工具</h1><p>一个待保存的应用</p></body></html>');
+ const privateFile=orkas.createWorkspaceFile('客户名单.csv','private fixture');
+ expect(await orkas.invoke('savedApps.inspectBundleFromPath',{path:source})).toMatchObject({canSave:false,reason:'app_bundle_root'});
+ expect(await orkas.invoke('savedApps.saveFromPath',{path:source})).toMatchObject({ok:false,error:'app_bundle_root'});
+ const preview=await orkas.openPreview(()=>page.evaluate(file=>(window as any).openChatFileViewer(file,'小工具.html'),source));
+ for(const [language,width,height] of [['zh',1080,720],['en',560,600]] as const){
+ await preview.evaluate(language=>(window as any).setLang(language),language);
+ await preview.setViewportSize({width,height});
+ await preview.locator('.chat-file-viewer-save-app').click();
+ const dialog=preview.getByRole('alertdialog');
+ await expect(dialog).toContainText(language==='zh'?'独立文件夹':'separate folder');
+ await expect(dialog).toContainText(language==='zh'?'再保存为应用':'save as an app again');
+ expect(await dialog.evaluate(el=>el.scrollWidth<=el.clientWidth)).toBe(true);
+ await preview.screenshot({path:testInfo.outputPath(`root-save-${language}.png`)});
+ await dialog.getByRole('button').click();
+ await expect(dialog).toHaveCount(0);
+ }
+ expect((await orkas.invoke<any>('savedApps.list')).apps).toHaveLength(0);
+ expect(readFileSync(privateFile,'utf8')).toBe('private fixture');
+ await orkas.closePreview(preview);
+ const entry=orkas.createWorkspaceFile('tool/index.html',readFileSync(source,'utf8'));
+ const saved=await orkas.invoke<any>('savedApps.saveFromPath',{path:entry});expect(saved.ok).toBe(true);
+ expect(saved.fileCount).toBe(1);
+ const folder=path.join(orkas.workspaceRoot,'account-e2e/cloud/saved_apps',saved.id);
+ expect(readdirSync(folder).sort()).toEqual(['__orkas-meta.json','index.html']);
+ await openSidebarEntry(page,'#apps-btn');
+ await expect(page.locator(`.app-card[data-app-id="${saved.id}"]`)).toBeVisible();
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('operates app actions by keyboard and restores focus after cancelling rename', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ const entry = orkas.createWorkspaceFile('keyboard-app/index.html', '<h1>Keyboard app</h1>');
+ const saved = await orkas.invoke<any>('savedApps.saveFromPath', { path: entry, title: 'Keyboard app' });
+ await openSidebarEntry(page, '#apps-btn');
+ const card = page.locator(`.app-card[data-app-id="${saved.id}"]`);
+ const more = card.locator('[data-app-more]');
+ await card.focus();
+ await page.keyboard.press('Tab');
+ await expect(more).toBeFocused();
+ await page.keyboard.press('Enter');
+ const menu = page.locator('.app-row-menu');
+ await expect(menu).toBeVisible();
+ await expect(menu.getByRole('menuitem')).toHaveText(['Rename', 'Edit', 'Publish', 'Delete']);
+ await menu.screenshot({ path: testInfo.outputPath('local-menu-order.png') });
+ await expect(menu.locator('.app-row-menu-item').first()).toBeFocused();
+ await page.keyboard.press('End');
+ await expect(menu.getByRole('menuitem', { name: 'Delete', exact: true })).toBeFocused();
+ await page.keyboard.press('ArrowUp');
+ await expect(menu.getByRole('menuitem', { name: 'Publish', exact: true })).toBeFocused();
+ await page.keyboard.press('Home');
+ await expect(menu.getByRole('menuitem', { name: 'Rename', exact: true })).toBeFocused();
+ await page.keyboard.press('Enter');
+ const dialog = page.locator('.ui-dialog-overlay:visible');
+ await expect(dialog.locator('input')).toHaveValue('Keyboard app');
+ await page.keyboard.press('Escape');
+ await expect(dialog).toHaveCount(0);
+ await expect(more).toBeFocused();
+ await page.keyboard.press('Enter');
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ expect((await orkas.invoke<any>('savedApps.list')).apps).toEqual([expect.objectContaining({ id: saved.id, title: 'Keyboard app' })]);
+ expect((await orkas.invoke<any>('conversations.list')).conversations).toHaveLength(0);
+ expect(orkas.electronApp!.windows()).toHaveLength(1);
+});
+
+test('retains the focused app through refresh and dismisses a removed app menu', async ({ orkas }) => {
+ const page = orkas.page!;
+ const entry = orkas.createWorkspaceFile('refresh-app/index.html', '<h1>Refresh app</h1>');
+ const saved = await orkas.invoke<any>('savedApps.saveFromPath', { path: entry, title: 'Refresh app' });
+ await openSidebarEntry(page, '#apps-btn');
+ const card = page.locator(`.app-card[data-app-id="${saved.id}"]`);
+ const more = card.locator('[data-app-more]');
+ await card.focus();
+ await page.keyboard.press('Tab');
+ await expect(more).toBeFocused();
+ await page.evaluate(() => (window as any).loadSavedApps(true));
+ await expect(more).toBeFocused();
+ await more.click();
+ await expect(page.locator('.app-row-menu')).toBeVisible();
+ await page.keyboard.press('End');
+ await page.evaluate(() => (window as any).loadSavedApps(true));
+ await expect(page.getByRole('menuitem', { name: 'Delete', exact: true })).toBeFocused();
+ await expect(more).toHaveAttribute('aria-expanded', 'true');
+ await orkas.invoke('savedApps.delete', { appId: saved.id });
+ await page.evaluate(() => (window as any).loadSavedApps(true));
+ await expect(card).toHaveCount(0);
+ await expect(page.locator('.app-row-menu')).toBeHidden();
+ await expect(page.locator('#apps-empty')).toBeVisible();
+ await expect(page.locator('#apps-create-btn')).toBeFocused();
+});
function expectAppCreationContext(request: Record<string, unknown>) {
const messages = request.messages as Array<{ role: string; content: unknown }>;
@@ -17,6 +127,109 @@ function expectAppCreationContext(request: Record<string, unknown>) {
}
test.describe('My Apps', () => {
+ test('keeps a cancelled creation draft only for the current application session', async ({ orkas }, testInfo) => {
+ let page = orkas.page!;
+ await openSidebarEntry(page, '#apps-btn');
+ await page.locator('#apps-create-btn').click();
+ const panel = page.locator('.apps-create-panel');
+ const draft = '家庭菜单与购物清单\nKeep this idea <b>as text</b>';
+ await panel.locator('textarea').fill(draft);
+ for (const dismissal of ['cancel', 'escape', 'backdrop']) {
+ if (dismissal === 'cancel') await panel.locator('[data-create-cancel]').click();
+ else if (dismissal === 'escape') await page.keyboard.press('Escape');
+ else await page.locator('.apps-create-overlay').click({ position: { x: 5, y: 5 } });
+ await expect(panel).toHaveCount(0);
+ await expect(page.locator('#apps-create-btn')).toBeFocused();
+ await page.locator('#apps-create-btn').click();
+ await expect(panel.locator('textarea')).toHaveValue(draft);
+ await expect(panel.locator('[data-app-type="local"]')).toHaveAttribute('aria-pressed', 'true');
+ await expect(panel.locator('[data-create-submit]')).toBeEnabled();
+ }
+ await panel.screenshot({ path: testInfo.outputPath('retained-create-draft.png') });
+ await panel.locator('[data-create-cancel]').click();
+ expect(orkas.modelRequests).toHaveLength(0);
+ page = await orkas.relaunch();
+ await openSidebarEntry(page, '#apps-btn');
+ await page.locator('#apps-create-btn').click();
+ await expect(page.locator('.apps-create-panel textarea')).toHaveValue('');
+ await expect(page.locator('[data-create-submit]')).toBeDisabled();
+ });
+
+ test('keeps type buttons anchored when counts change or disappear', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ const entry = orkas.createWorkspaceFile('stable-header/index.html', '<h1>Local app</h1>');
+ for (let i = 0; i < 10; i++) await orkas.invoke('savedApps.saveFromPath', { path: entry, title: `App ${i}` });
+ await openSidebarEntry(page, '#apps-btn');
+ await page.evaluate(() => (window as any).setLang('zh'));
+ const tabs = page.locator('#apps-type-tabs');
+ const count = page.locator('#apps-page-header-count');
+ for (const width of [1133, 560]) {
+ await page.setViewportSize({ width, height: 720 });
+ await tabs.locator('[data-app-filter="local"]').click();
+ await expect(count).toHaveText('10');
+ await page.evaluate(() => (window as any).loadSavedApps(true));
+ await expect(tabs.locator('[data-app-filter="local"]')).toBeFocused();
+ const local = await tabs.boundingBox();
+ await tabs.locator('[data-app-filter="web"]').click();
+ await expect(page.locator('.ui-dialog-overlay.open').last()).toBeVisible();
+ await page.locator('.ui-dialog-overlay.open').last().locator('[data-act="cancel"]').click();
+ await expect(count).toHaveText('10');
+ const cloud = await tabs.boundingBox();
+ expect(Math.abs(cloud!.x - local!.x)).toBeLessThan(1);
+ expect(Math.abs(cloud!.y - local!.y)).toBeLessThan(1);
+ await tabs.locator('[data-app-filter="local"]').click();
+ await expect(page.locator('.app-card')).toHaveCount(10);
+ await expect(page.locator('#apps-type-description')).toHaveText('在 Orkas 桌面端运行,可使用 AI、文件、知识库和连接器等能力,不支持发布为网页。');
+ const description = page.locator('#apps-type-description');
+ const tabBox = (await tabs.boundingBox())!;
+ const descriptionBox = (await description.boundingBox())!;
+ expect(tabBox.height).toBe(32);
+ const createHeight = (await page.locator('#apps-create-btn').boundingBox())!.height;
+ expect(createHeight).toBe(28);
+ for (const tab of await tabs.getByRole('tab').all()) {
+ expect((await tab.boundingBox())!.height).toBe(createHeight);
+ }
+ expect(descriptionBox.x).toBeGreaterThanOrEqual(tabBox.x + tabBox.width);
+ expect(Math.abs(descriptionBox.y + descriptionBox.height / 2 - tabBox.y - tabBox.height / 2)).toBeLessThan(1);
+ if (width === 1133) expect((await page.locator('.apps-page-header').boundingBox())!.height).toBeLessThanOrEqual(60);
+ await page.locator('.apps-page-header').screenshot({ path: testInfo.outputPath(`stable-header-${width}.png`) });
+ }
+ });
+
+ test('keeps local cards and the creation draft when web guidance is cancelled across languages and sizes', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ const entry = orkas.createWorkspaceFile('described-app/index.html', '<head><meta name="description" content="Track orders &amp; stock"></head><h1>Inventory</h1>');
+ await orkas.invoke('savedApps.saveFromPath', { path: entry, title: 'Inventory' });
+ await openSidebarEntry(page, '#apps-btn');
+ await expect(page.locator('.app-card')).toHaveCount(1);
+ await expect(page.locator('.app-card-description')).toHaveCount(0);
+ for (const width of [1133, 560]) for (const language of ['en', 'zh']) {
+ await page.setViewportSize({ width, height: 720 });
+ await page.evaluate(language => (window as any).setLang(language), language);
+ const tab = page.locator('[data-app-filter="web"]'); await tab.click();
+ const dialog = page.locator('.ui-dialog-overlay.open').last();
+ await expect(dialog).toBeVisible();
+ await expect(dialog).toContainText(language === 'zh' ? '商业版' : 'commercial version');
+ await dialog.locator('[data-act="cancel"]').click();
+ await expect(page.locator('[data-app-filter="local"]')).toHaveAttribute('aria-selected', 'true');
+ await expect(page.locator('.app-card')).toHaveCount(1);
+ await page.locator('#apps-create-btn').click();
+ const panel = page.locator('.apps-create-panel');
+ await panel.locator('textarea').fill('Keep my draft');
+ await panel.locator('[data-app-type="web"]').click();
+ const guidance = page.locator('.ui-dialog-overlay.open').last();
+ await expect(guidance).toContainText(language === 'zh' ? '商业版' : 'commercial version');
+ await guidance.screenshot({ path: testInfo.outputPath(`web-guidance-${language}-${width}.png`) });
+ await page.keyboard.press('Escape');
+ await expect(panel.locator('textarea')).toHaveValue('Keep my draft');
+ await expect(panel.locator('[data-app-type="local"]')).toHaveAttribute('aria-pressed', 'true');
+ await panel.locator('[data-create-cancel]').click();
+ expect((await orkas.invoke<any>('conversations.list')).conversations).toHaveLength(0);
+ }
+ const refused = await orkas.invoke<any>('conversations.create', { title: 'Denied', assistance: { kind: 'app_creation', appType: 'web' } });
+ expect(refused).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ });
+
for (const existingTaskCount of [0, 2]) {
test(`creates a separate task once with ${existingTaskCount} existing tasks`, async ({ modelOrkas: orkas }) => {
const page = orkas.page!;
@@ -42,7 +255,7 @@ test.describe('My Apps', () => {
await idea.fill(' ');
await expect(submit).toBeDisabled();
await page.keyboard.press('Shift+Tab');
- await expect(cancel).toBeFocused();
+ await expect(panel.locator('[data-app-type=web]')).toBeFocused();
await idea.focus();
await idea.dispatchEvent('keydown', { key: 'Escape', isComposing: true });
await expect(panel).toBeVisible();
@@ -62,6 +275,8 @@ test.describe('My Apps', () => {
await cancel.click();
await expect(opener).toBeFocused();
await opener.click();
+ await expect(panel.locator('[data-app-type=local]')).toHaveAttribute('aria-pressed', 'true');
+ await expect(idea).toHaveValue(/snake game/i);
await idea.fill('Create an app to plan family meals');
await idea.press('Enter');
await idea.pressSequentially('Include a shopping list');
@@ -71,6 +286,7 @@ test.describe('My Apps', () => {
await submit.evaluate((el: HTMLButtonElement) => { el.click(); el.click(); });
await expect(panel).toHaveCount(0);
await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
+ await expect(page.locator('#chat-header .chat-app-type-tag')).toHaveCount(0);
await expect(page.locator('#chat-history .chat-message.user')).toHaveCount(1);
await expect(page.locator('#chat-history .chat-message.user')).toContainText(prompt);
await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', { hasText: 'APP_CREATE_ACK' })).toBeVisible({ timeout: 20_000 });
@@ -80,6 +296,7 @@ test.describe('My Apps', () => {
const listed = await orkas.invoke<{ conversations: unknown[] }>('conversations.list');
expect(listed.conversations).toHaveLength(existingTaskCount + 1);
expect(listed.conversations.filter((conversation: any) => conversation.assistance?.kind === 'app_creation')).toHaveLength(1);
+ expect((listed.conversations.find((conversation:any)=>conversation.assistance?.kind==='app_creation') as any).assistance.appType).toBe('local');
await expect(page.locator('#conversation-list .conv-item')).toHaveCount(existingTaskCount + 1);
await expect(page.locator('#conversation-list .conv-item').first()).toHaveClass(/\bactive\b/);
for (let i = 0; i < existingTaskCount; i += 1) {
@@ -94,7 +311,7 @@ test.describe('My Apps', () => {
test('keeps the description in the new task when sending is rejected and supports retry', async ({ modelOrkas: orkas }) => {
const page = orkas.page!;
orkas.setModelTextReplies(['APP_RETRY_ACK']);
- await page.locator('#apps-btn').click();
+ await openSidebarEntry(page, '#apps-btn');
await page.locator('#apps-create-btn').click();
const panel = page.locator('.apps-create-panel');
await panel.locator('[data-app-template="products"]').click();
@@ -140,7 +357,7 @@ test.describe('My Apps', () => {
for (const title of ['Orkas · SDK 能力体验馆', '像素贪吃蛇', '霓虹贪吃蛇', '指挥官 · 智能体详情', '计算器应用', 'ROI 计算器', '长标题应用 <img src=x onerror=alert(1)> '.repeat(5)]) {
await orkas.invoke('savedApps.saveFromPath', { path: entry, title });
}
- await page.locator('#apps-btn').click();
+ await openSidebarEntry(page, '#apps-btn');
await expect(page.locator('.app-card')).toHaveCount(7);
await expect(page.locator('.app-card img')).toHaveCount(0);
const scrollArea = page.locator('#panel-apps .agents-grid-scroll');
@@ -177,7 +394,7 @@ test.describe('My Apps', () => {
await panel.locator('[data-create-cancel]').click();
await expect(panel).toHaveCount(0);
expect(orkas.modelRequests.length).toBe(0);
- await page.locator('#apps-btn').click();
+ await openSidebarEntry(page, '#apps-btn');
const grid = page.locator('#apps-grid');
expect(await grid.evaluate(el => el.scrollWidth <= el.clientWidth)).toBe(true);
expect(await scrollArea.evaluate(el => el.scrollWidth <= el.clientWidth)).toBe(true);
@@ -201,7 +418,7 @@ test.describe('My Apps', () => {
});
expect(saved.ok).toBe(true);
- await page.locator('#apps-btn').click();
+ await openSidebarEntry(page, '#apps-btn');
await expect(page.locator('#panel-apps')).toHaveClass(/\bactive\b/);
let card = page.locator(`.app-card[data-app-id="${saved.id}"]`);
await expect(card).toContainText('E2E Saved App');
@@ -237,7 +454,7 @@ test.describe('My Apps', () => {
expect(await appFrame.contentFrame().locator('body').evaluate(() => typeof (window as any).orkas)).toBe('undefined');
await page.locator('#new-chat-btn').click();
await expect(appFrame.contentFrame().locator('#app-title')).toHaveText('E2E App Running');
- await page.locator('#apps-btn').click();
+ await openSidebarEntry(page, '#apps-btn');
await card.click();
expect(orkas.electronApp!.windows().filter(p => p.url().endsWith('/preview.html'))).toHaveLength(1);
await orkas.closePreview(preview);
@@ -265,6 +482,7 @@ test.describe('My Apps', () => {
});
await page.locator('.app-row-menu-item[data-action="edit"]').click();
await expect(page.locator('#panel-conversation')).toHaveClass(/\bactive\b/);
+ await expect(page.locator('#chat-header .chat-app-type-tag')).toHaveCount(0);
await expectComposerText(page.locator('#chat-input'), /E2E Renamed App/);
await expect(page.locator('#chat-attachments')).toContainText('app-source.md');
const editComposer = page.locator('.chat-rich-editor[data-rich-input-id="chat-input"]');
@@ -280,7 +498,7 @@ test.describe('My Apps', () => {
}
const relaunchedPage = await orkas.relaunch();
- await relaunchedPage.locator('#apps-btn').click();
+ await openSidebarEntry(relaunchedPage, '#apps-btn');
card = relaunchedPage.locator(`.app-card[data-app-id="${saved.id}"]`);
await expect(card).toContainText('E2E Renamed App');
await card.hover();
@@ -293,3 +511,319 @@ test.describe('My Apps', () => {
await expect(relaunchedPage.locator('#apps-page-header-count')).toHaveText('');
});
});
+
+
+test('labels each application artifact inside its bubble across languages and reopening', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ const created = await orkas.invoke<any>('conversations.create', { title: 'Application outputs' });
+ const cid = created.conversation.conversation_id;
+ const artifacts = [];
+ for (const appType of ['local', 'web']) {
+ const result = appType === 'web' ? historicalArtifact(orkas.workspaceRoot, cid, 'web', `${appType} application `.repeat(8)) : await orkas.electronApp!.evaluate(async (_electron, args) =>
+ (process as any).mainModule.require(args.module).createArtifact('account-e2e', args.cid, 'commander', {
+ appType: args.appType, title: args.title,
+ files: [{ path: 'index.html', content: '<!doctype html><h1>Application ready</h1>' }],
+ }), { module: path.resolve(__dirname, '../../src/main/features/chat_artifacts.ts'), cid, appType, title: `${appType} application `.repeat(8) });
+ expect(result.ok).toBe(true);
+ artifacts.push({ id: result.artifactId, title: result.title, agent_id: 'commander' });
+ }
+ appendFileSync(path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats', `${cid}.jsonl`), JSON.stringify({
+ id: 'm_app_outputs', ts: new Date().toISOString(), from: 'commander', to: ['user'],
+ text: 'Applications ready.', artifacts,
+ }) + '\n');
+ const reopen = async () => {
+ await page.evaluate(async id => {
+ await (window as any).loadConversations();
+ (window as any).setView('new-chat');
+ (window as any).setView('conversation', id);
+ }, cid);
+ };
+ await reopen();
+ const cards = page.locator('#chat-history .chat-bubble .chat-artifact-card');
+ const tags = cards.locator('.chat-app-type-tag');
+ await expect(cards).toHaveCount(2);
+ await expect(tags).toHaveText(['Local app', 'Web app']);
+ await expect(page.locator('#chat-header .chat-app-type-tag')).toHaveCount(0);
+ await page.evaluate(() => (window as any).setLang('zh'));
+ await expect(tags).toHaveText(['本地应用', '网页应用']);
+ for (const width of [1133, 560]) {
+ await page.setViewportSize({ width, height: 720 });
+ for (const card of await cards.all()) {
+ expect(await card.evaluate(el => {
+ const title = el.querySelector('.chat-artifact-title')!.getBoundingClientRect();
+ const tag = el.querySelector('.chat-app-type-tag')!.getBoundingClientRect();
+ const menu = el.querySelector('.chat-artifact-more')!.getBoundingClientRect();
+ const bounds = el.getBoundingClientRect();
+ const bubble = el.closest('.chat-bubble')!.getBoundingClientRect();
+ return title.right <= tag.left && tag.right <= menu.left && el.scrollWidth <= el.clientWidth
+ && bounds.left >= bubble.left && bounds.right <= bubble.right;
+ })).toBe(true);
+ }
+ for (let index = 0; index < await cards.count(); index++) {
+ const header = cards.nth(index).locator('.chat-artifact-header');
+ await header.scrollIntoViewIfNeeded();
+ await header.screenshot({ path: testInfo.outputPath(`artifact-tag-${width}-${index}.png`) });
+ }
+ }
+ await page.evaluate(() => (window as any).setLang('en'));
+ await reopen();
+ await expect(tags).toHaveText(['Local app', 'Web app']);
+ await expect(cards.locator('iframe[src]')).toHaveCount(1);
+ await expect(cards.nth(1)).toContainText('commercial version');
+});
+
+
+test('denies historical web resource URLs before and after restart while retaining their bytes', async ({ orkas }) => {
+ const created = await orkas.invoke<any>('conversations.create', { title: 'Historical web resources' });
+ const cid = created.conversation.conversation_id;
+ const urls: string[] = [];
+ const originals = new Map<string, Buffer>();
+ for (const appType of ['web', 'cloud']) {
+ const artifact = historicalArtifact(orkas.workspaceRoot, cid, appType);
+ const savedId = 'historic-' + appType;
+ const savedDir = path.join(orkas.workspaceRoot, 'account-e2e/cloud/saved_apps', savedId);
+ mkdirSync(savedDir, { recursive: true });
+ writeFileSync(path.join(savedDir, 'index.html'), '<h1>Preserve saved app bytes</h1>');
+ writeFileSync(path.join(savedDir, '__orkas-meta.json'), JSON.stringify({ title: 'Historic saved app', appType, entry: 'index.html' }));
+ for (const dir of [savedDir, path.join(orkas.workspaceRoot, 'account-e2e/cloud/chat_artifacts', cid, artifact.artifactId)]) {
+ for (const file of readdirSync(dir)) originals.set(path.join(dir, file), readFileSync(path.join(dir, file)));
+ }
+ urls.push(`chat-app://saved/${savedId}/index.html`, `chat-app://cid/${cid}/${artifact.artifactId}/index.html`);
+ }
+ for (const restart of [false, true]) {
+ if (restart) await orkas.relaunch();
+ const receipts = await orkas.electronApp!.evaluate(async ({ net }, urls) => Promise.all(urls.map(async url => {
+ const response = await net.fetch(url);
+ return { status: response.status, body: await response.json() };
+ })), urls);
+ for (const receipt of receipts) expect(receipt).toMatchObject({ status: 403, body: { ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' } });
+ for (const [file, bytes] of originals) expect(readFileSync(file).equals(bytes)).toBe(true);
+ expect(orkas.electronApp!.windows()).toHaveLength(1);
+ expect(orkas.modelRequests).toHaveLength(0);
+ }
+});
+
+
+test('labels an untyped artifact from its task: web in a web creation task, local in an ordinary conversation', async ({ orkas }) => {
+ const page = orkas.page!;
+ const tags: string[] = [];
+ for (const assistance of [{ kind: 'app_creation', appType: 'web' }, undefined]) {
+ const created = await orkas.electronApp!.evaluate(async (_electron, args) => ({ conversation: await (process as any).mainModule.require(args.module).createConversation('account-e2e', { title: 'Untyped output', assistance: args.assistance }) }), { module: path.resolve(__dirname, '../../src/main/features/chats.ts'), assistance });
+ const cid = created.conversation.conversation_id;
+ const result = historicalArtifact(orkas.workspaceRoot, cid);
+ expect(result.ok).toBe(true);
+ // Legacy/synced metadata without a type must not default to local in a web task.
+ writeFileSync(path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chat_artifacts', cid, result.artifactId, '__orkas-meta.json'), JSON.stringify({ title: 'Untyped app' }));
+ appendFileSync(path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats', `${cid}.jsonl`), JSON.stringify({
+ id: 'm_untyped', ts: new Date().toISOString(), from: 'commander', to: ['user'],
+ text: 'Application ready.', artifacts: [{ id: result.artifactId, title: result.title, agent_id: 'commander' }],
+ }) + '\n');
+ await page.evaluate(async id => {
+ await (window as any).loadConversations();
+ (window as any).setView('new-chat');
+ (window as any).setView('conversation', id);
+ }, cid);
+ await page.evaluate(() => (window as any).setLang('en'));
+ const tag = page.locator('#chat-history .chat-artifact-card .chat-app-type-tag');
+ await expect(tag).toBeVisible();
+ tags.push(await tag.innerText());
+ }
+ expect(tags).toEqual(['Web app', 'Local app']);
+});
+
+test('keeps the local application icon while the web entry only offers commercial guidance', async ({ orkas }) => {
+ const page = orkas.page!;
+ const local = orkas.createWorkspaceFile('icon-local/index.html', '<h1>Local</h1>');
+ await orkas.invoke('savedApps.saveFromPath', { path: local, title: 'Local example' });
+ await openSidebarEntry(page, '#apps-btn');
+ await expect(page.locator('.app-card-icon svg.is-layout-grid')).toHaveCount(1);
+ await page.locator('[data-app-filter="web"]').click();
+ await expect(page.locator('.ui-dialog-overlay.open').last()).toBeVisible();
+ await page.locator('.ui-dialog-overlay.open').last().locator('[data-act="cancel"]').click();
+ await expect(page.locator('.app-card-icon svg.is-layout-grid')).toHaveCount(1);
+});
+
+/** Mono 8-bit PCM WAV whose sample bytes vary, so a shifted or truncated byte
+ * range is distinguishable from the requested slice. */
+function wavFixture(seconds: number, rate = 8000): Buffer {
+ const samples = Math.round(seconds * rate);
+ const wav = Buffer.alloc(44 + samples);
+ wav.write('RIFF', 0); wav.writeUInt32LE(36 + samples, 4); wav.write('WAVE', 8); wav.write('fmt ', 12);
+ wav.writeUInt32LE(16, 16); wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22); wav.writeUInt32LE(rate, 24);
+ wav.writeUInt32LE(rate, 28); wav.writeUInt16LE(1, 32); wav.writeUInt16LE(8, 34); wav.write('data', 36); wav.writeUInt32LE(samples, 40);
+ for (let i = 0; i < samples; i++) wav[44 + i] = 96 + ((i * 7) % 61);
+ return wav;
+}
+
+test('opens a non-index saved entry with its stylesheet, font and seekable audio', async ({ orkas }) => {
+ const page = orkas.page!;
+ const font = readFileSync(path.resolve(__dirname, '../../src/renderer/vendor/mathjax/output/chtml/fonts/woff-v2/MathJax_Size3-Regular.woff'));
+ const audio = wavFixture(0.5);
+ const entry = orkas.createWorkspaceFile('cli-game/game.html', '<!doctype html><html><head><link rel="stylesheet" href="game.css"></head>'
+ + '<body><h1 id="game-title">Jump game</h1><audio id="jump" src="jump.wav" preload="auto"></audio></body></html>');
+ // A sibling page sorts before the entry: opening it instead is a wrong-entry regression.
+ orkas.createWorkspaceFile('cli-game/about.html', '<!doctype html><h1 id="game-title">About page</h1>');
+ orkas.createWorkspaceFile('cli-game/game.css', '@font-face { font-family: "E2E Game Font"; src: url("game-font.woff") format("woff"); }\n'
+ + 'body { color: rgb(12, 34, 56); }\nh1 { font-family: "E2E Game Font", monospace; }');
+ orkas.createWorkspaceFile('cli-game/game-font.woff', font);
+ orkas.createWorkspaceFile('cli-game/jump.wav', audio);
+ const saved = await orkas.invoke<any>('savedApps.saveFromPath', { path: entry, title: 'Jump game' });
+ expect(saved).toMatchObject({ ok: true, entry: 'game.html' });
+
+ await openSidebarEntry(page, '#apps-btn');
+ const preview = await orkas.openPreview(() => page.locator(`.app-card[data-app-id="${saved.id}"]`).click());
+ const viewer = preview.locator('.saved-app-viewer');
+ await expect(viewer.locator('.saved-app-viewer-title')).toHaveText('Jump game');
+ const appFrame = viewer.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(appFrame.locator('#game-title')).toHaveText('Jump game');
+ const body = appFrame.locator('body');
+ expect(await body.evaluate(() => new URL(location.href).pathname.split('/').at(-1))).toBe('game.html');
+ await expect(body).toHaveCSS('color', 'rgb(12, 34, 56)');
+ const fonts = await body.evaluate(async () => {
+ await document.fonts.load('16px "E2E Game Font"').catch(() => []);
+ await document.fonts.ready;
+ return [...document.fonts].filter(face => face.family.replace(/"/g, '') === 'E2E Game Font').map(face => face.status);
+ });
+ expect(fonts).toEqual(['loaded']);
+ const start = 100, end = 163;
+ const ranged = await body.evaluate(async (_body, { start, end }) => {
+ const response = await fetch('jump.wav', { headers: { Range: `bytes=${start}-${end}` } });
+ return { status: response.status, contentRange: response.headers.get('Content-Range'), bytes: [...new Uint8Array(await response.arrayBuffer())] };
+ }, { start, end });
+ expect(ranged.status).toBe(206);
+ expect(ranged.contentRange).toBe(`bytes ${start}-${end}/${audio.length}`);
+ expect(Buffer.from(ranged.bytes).equals(audio.subarray(start, end + 1))).toBe(true);
+ const duration = await body.evaluate(() => new Promise<number>((resolve, reject) => {
+ const element = document.getElementById('jump') as HTMLAudioElement;
+ if (element.readyState >= 1) { resolve(element.duration); return; }
+ element.addEventListener('loadedmetadata', () => resolve(element.duration), { once: true });
+ element.addEventListener('error', () => reject(new Error('audio failed to load')), { once: true });
+ }));
+ expect(duration).toBeCloseTo(0.5, 2);
+ await orkas.closePreview(preview);
+});
+
+test('Enter and Space each open one preview and the icon tone survives rename', async ({ orkas }) => {
+ const page = orkas.page!;
+ const entry = orkas.createWorkspaceFile('key-open/index.html', '<h1 id="key-title">Key open</h1>');
+ const saved = await orkas.invoke<any>('savedApps.saveFromPath', { path: entry, title: 'Key open' });
+ await openSidebarEntry(page, '#apps-btn');
+ const card = page.locator(`.app-card[data-app-id="${saved.id}"]`);
+ const toneBefore = await card.locator('.app-card-icon').getAttribute('class');
+ const previews = () => orkas.electronApp!.windows().filter(surface => surface.url().endsWith('/preview.html'));
+ for (const [index, key] of (['Enter', ' '] as const).entries()) {
+ await card.focus();
+ const preview = await orkas.openPreview(() => page.keyboard.press(key === ' ' ? 'Space' : key));
+ await expect(preview.locator('.saved-app-viewer-frame').contentFrame().locator('#key-title')).toHaveText('Key open');
+ expect(previews()).toHaveLength(1);
+ await orkas.closePreview(preview);
+ }
+
+ await card.hover();
+ await card.locator('[data-app-more]').click();
+ await page.locator('.app-row-menu-item[data-action="rename"]').click();
+ const prompt = page.locator('.ui-dialog-overlay:visible');
+ await prompt.locator('.ui-dialog-input').fill('Renamed key app');
+ await prompt.locator('[data-act="ok"]').click();
+ await expect(card.locator('.app-card-name')).toHaveText('Renamed key app');
+ await expect(card.locator('.app-card-icon')).toHaveAttribute('class', toneBefore!);
+ await page.evaluate(() => (window as any).loadSavedApps(true));
+ await expect(card.locator('.app-card-name')).toHaveText('Renamed key app');
+ await expect(card.locator('.app-card-icon')).toHaveAttribute('class', toneBefore!);
+ expect((await orkas.invoke<any>('savedApps.list')).apps).toEqual([expect.objectContaining({ id: saved.id, title: 'Renamed key app' })]);
+});
+
+test('saving an artifact shows exactly one confirmation toast and no dialog', async ({ orkas }) => {
+ const page = orkas.page!;
+ const created = await orkas.invoke<any>('conversations.create', { title: 'Artifact save' });
+ const cid = created.conversation.conversation_id;
+ const result = await orkas.electronApp!.evaluate(async (_electron, args) =>
+ (process as any).mainModule.require(args.module).createArtifact('account-e2e', args.cid, 'commander', {
+ title: 'Saved artifact', files: [{ path: 'index.html', content: '<!doctype html><h1>Saved artifact</h1>' }],
+ }), { module: path.resolve(__dirname, '../../src/main/features/chat_artifacts.ts'), cid });
+ expect(result.ok).toBe(true);
+ appendFileSync(path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats', `${cid}.jsonl`), JSON.stringify({
+ id: 'm_artifact_save', ts: new Date().toISOString(), from: 'commander', to: ['user'],
+ text: 'Artifact ready.', artifacts: [{ id: result.artifactId, title: result.title, agent_id: 'commander' }],
+ }) + '\n');
+ await page.evaluate(async id => {
+ await (window as any).loadConversations();
+ (window as any).setView('conversation', id);
+ }, cid);
+ const artifact = page.locator('#chat-history .chat-artifact-card');
+ await expect(artifact).toHaveCount(1);
+ await page.evaluate(() => {
+ const w = window as any;
+ // Count distinct surfaces, including any that appear and leave between checks.
+ const toasts = new Set<Element>(), dialogs = new Set<Element>();
+ w.__saveSurfaces = () => ({ toasts: toasts.size, dialogs: dialogs.size });
+ new MutationObserver(() => {
+ for (const node of document.querySelectorAll('.ui-toast')) toasts.add(node);
+ for (const node of document.querySelectorAll('.ui-dialog-overlay')) if ((node as HTMLElement).offsetParent !== null || getComputedStyle(node).display !== 'none') dialogs.add(node);
+ }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'style', 'hidden'] });
+ });
+ await artifact.locator('.chat-artifact-more').click();
+ await page.locator('.chat-artifact-menu [data-action="save"]').click();
+ await expect(page.locator('.ui-toast.is-success')).toHaveCount(1);
+ await expect.poll(async () => (await orkas.invoke<any>('savedApps.list')).apps.map((app: any) => app.title)).toEqual(['Saved artifact']);
+ await openSidebarEntry(page, '#apps-btn');
+ await expect(page.locator('.app-card').filter({ hasText: 'Saved artifact' })).toHaveCount(1);
+ await expect(page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
+ expect(await page.evaluate(() => (window as any).__saveSurfaces())).toEqual({ toasts: 1, dialogs: 0 });
+});
+
+// UI review captures (zh, default window unless named -390): saved time, local delete
+// confirmation without a publication, and the create dialog type choice.
+test('reads saved time, local delete confirmation and the create dialog in Chinese at default and narrow widths', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ const review = (name: string) => testInfo.outputPath('ui-review', name);
+ const entry = orkas.createWorkspaceFile('review-app/index.html', '<!doctype html><h1>Review</h1>');
+ const saved = await orkas.invoke<{ ok: boolean; id: string }>('savedApps.saveFromPath', { path: entry, title: '旅行清单' });
+ expect(saved.ok).toBe(true);
+ // An earlier save today (in the app's own time zone) reads as a clock time, not "just now".
+ const savedAt = new Date(await page.evaluate(() => { const today = new Date(); today.setHours(0, 0, 0, 0); return Math.max(Date.now() - 5 * 60_000, today.getTime()); }));
+ const meta = path.join(orkas.workspaceRoot, 'account-e2e/cloud/saved_apps', saved.id, '__orkas-meta.json');
+ writeFileSync(meta, JSON.stringify({ ...JSON.parse(readFileSync(meta, 'utf8')), savedAt: savedAt.toISOString() }));
+ await openSidebarEntry(page, '#apps-btn');
+ await page.evaluate(async () => { await (window as any).setLang('zh'); await (window as any).loadSavedApps(true); });
+ const card = page.locator(`.app-card[data-app-id="${saved.id}"]`);
+ const clock = await page.evaluate(ms => { const d = new Date(ms); return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; }, savedAt.getTime());
+ if (Date.now() - savedAt.getTime() >= 60_000) await expect(card).toContainText(`保存于 ${clock}`);
+ await card.screenshot({ path: review('09-card-saved-time.png') });
+
+ await card.hover(); await card.locator('[data-app-more]').click();
+ await page.locator('.app-row-menu-item[data-action="delete"]').click();
+ const confirm = page.locator('.ui-dialog-overlay:visible');
+ await expect(confirm).toContainText('删除「旅行清单」及其本地记录和私有文件?数据无法恢复。');
+ await expect(confirm).not.toContainText('已发布应用及线上数据将保留。');
+ await expect(confirm.locator('[data-act="cancel"]')).toBeFocused();
+ await confirm.locator('.ui-dialog').screenshot({ path: review('08-delete-confirm-local.png') });
+ await page.setViewportSize({ width: 390, height: 720 });
+ // Chromium can expose fractional visual CSS pixels while innerWidth is rounded.
+ const dialogBounds = await confirm.locator('.ui-dialog').evaluate(node => {
+ const rect = node.getBoundingClientRect();
+ const viewport = window.visualViewport;
+ const left = viewport?.offsetLeft ?? 0;
+ return { left: rect.left, right: rect.right, viewportLeft: left,
+ viewportRight: left + (viewport?.width ?? window.innerWidth) };
+ });
+ expect(dialogBounds.left, JSON.stringify(dialogBounds)).toBeGreaterThanOrEqual(dialogBounds.viewportLeft);
+ expect(dialogBounds.right, JSON.stringify(dialogBounds)).toBeLessThanOrEqual(dialogBounds.viewportRight);
+ await page.screenshot({ path: review('08-delete-confirm-local-390.png') });
+ await page.keyboard.press('Escape'); await expect(confirm).toHaveCount(0); await expect(card).toBeVisible();
+ await page.setViewportSize({ width: 1133, height: 800 });
+
+ await page.locator('#apps-create-btn').click();
+ const panel = page.locator('.apps-create-panel');
+ await expect(panel.getByRole('heading', { name: '创建应用', exact: true })).toBeVisible();
+ await expect(panel.locator('[data-app-type]')).toHaveText(['本地应用', '网页应用']);
+ await expect(panel.locator('[data-app-type="local"]')).toHaveAttribute('aria-pressed', 'true');
+ await panel.screenshot({ path: review('12-create-dialog.png') });
+ await page.setViewportSize({ width: 390, height: 720 });
+ expect(await panel.evaluate(node => node.scrollWidth <= node.clientWidth + 1)).toBe(true);
+ await page.screenshot({ path: review('12-create-dialog-390.png') });
+ await page.setViewportSize({ width: 1133, height: 800 });
+ await panel.locator('[data-create-cancel]').click(); await expect(panel).toHaveCount(0);
+ expect((await orkas.invoke<{ apps: unknown[] }>('savedApps.list')).apps).toHaveLength(1);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
diff --git a/test/e2e/web_app_permissions_e2e_usage.spec.ts b/test/e2e/web_app_permissions_e2e_usage.spec.ts
new file mode 100644
index 00000000..07ce9e25
--- /dev/null
+++ b/test/e2e/web_app_permissions_e2e_usage.spec.ts
@@ -0,0 +1,102 @@
+import { readFileSync } from 'node:fs';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+
+
+test('app approval uses Orkas UI, lasts for this use, isolates windows and honors Trusted', async ({ modelOrkas: orkas }, info) => {
+ const state = orkas.createFixtureFile('app-action-effects.json', '[]');
+ const server = orkas.createFixtureFile('app-action-server.cjs', String.raw`
+ const fs = require('node:fs');
+ require('node:readline').createInterface({ input: process.stdin }).on('line', line => {
+ const request = JSON.parse(line);
+ const reply = result => process.stdout.write(JSON.stringify({ jsonrpc:'2.0', id:request.id, result })+'\n');
+ if (request.method === 'initialize') reply({ protocolVersion:request.params.protocolVersion, capabilities:{tools:{}}, serverInfo:{name:'app-approval-fixture',version:'1'} });
+ else if (request.method === 'tools/list') reply({tools:[{name:'record', description:'Record a controlled effect.', inputSchema:{type:'object',properties:{value:{type:'string'}},required:['value']}}]});
+ else if (request.method === 'tools/call') {
+ const effects = JSON.parse(fs.readFileSync(process.env.APP_EFFECTS,'utf8'));
+ effects.push(request.params.arguments.value); fs.writeFileSync(process.env.APP_EFFECTS,JSON.stringify(effects));
+ reply({content:[{type:'text',text:'Recorded '+request.params.arguments.value}]});
+ } else if (request.method === 'ping') reply({});
+ });
+ `);
+ const connector: any = await orkas.invoke('connectors.add_custom', { display_name: 'App approval fixture',
+ transport: { kind: 'stdio', command: process.execPath, args: [server], env: { APP_EFFECTS: state } } });
+ expect(connector.ok).toBe(true);
+ expect(connector.instance.status.kind).toBe('connected');
+ const connectorId = connector.instance.id;
+ const effects = () => JSON.parse(readFileSync(state, 'utf8'));
+ await orkas.invoke('permissions.setLocalExecMode', { mode: 'all_files_approval' });
+ // Native confirmation would reproduce the original regression. File pickers
+ // retain their independent behavior; this journey records no remote effects.
+ await orkas.electronApp!.evaluate(({ dialog }) => {
+ (globalThis as any).__nativeAppConfirmations = 0;
+ (dialog as any).showMessageBox = async () => {
+ (globalThis as any).__nativeAppConfirmations++;
+ return { response: 0, checkboxChecked: false };
+ };
+ });
+ const entry = orkas.createWorkspaceFile('usage-app/index.html', `<!doctype html><html><head><script src="/__orkas/sdk.js"></script></head><body>
+ <h1>Approval notebook</h1><input aria-label="Value" value="first"><button id="run">Record</button><p role="status">Ready</p>
+ <script>document.querySelector('#run').onclick = async () => {
+ const status = document.querySelector('[role=status]'); status.textContent='Waiting';
+ try { const result = await orkasApp.tools.call({name:'call_connector_tool',arguments:{connector_id:${JSON.stringify(connectorId)},tool_name:'record',args:{value:document.querySelector('input').value}}});
+ status.textContent = result.isError ? 'Denied' : 'Recorded';
+ } catch (error) { status.textContent=error.code; }
+ };</script></body></html>`);
+ orkas.createWorkspaceFile('usage-app/orkas-app.json', JSON.stringify({sdkVersion:1,capabilities:['connectors']}));
+ const first: any = await orkas.invoke('savedApps.saveFromPath', {path:entry,title:'Usage one'});
+ const second: any = await orkas.invoke('savedApps.saveFromPath', {path:entry,title:'Usage two'});
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const open = (id: string) => orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${id}"]`).click());
+ let preview = await open(first.id);
+ let frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ const run = async (value: string) => { await frame.getByRole('textbox').fill(value); await frame.getByRole('button', { name:'Record', exact:true }).click(); };
+ await run('denied');
+ const approval = preview.locator('.bash-permission-dialog');
+ await expect(approval).toBeVisible();
+ await expect(approval.locator('.ui-dialog-context')).toHaveText('Application request');
+ await expect(approval.getByRole('button', { name:'Allow for this use', exact:true })).toBeVisible();
+ await expect(approval.getByRole('button', { name:'Allow for this task', exact:true })).toHaveCount(0);
+ await expect(orkas.page.locator('.bash-permission-dialog')).toHaveCount(0);
+ expect(effects()).toEqual([]);
+ await preview.screenshot({path:info.outputPath('app-sensitive-approval.png')});
+ await approval.locator('[data-act="cancel"]').click();
+ await expect(frame.getByRole('status')).toHaveText('Denied');
+ expect(effects()).toEqual([]);
+ await run('first');
+ await approval.getByRole('button', { name:'Allow for this use', exact:true }).click();
+ await expect(frame.getByRole('status')).toHaveText('Recorded');
+ await run('repeat'); await expect(frame.getByRole('status')).toHaveText('Recorded');
+ expect(effects()).toEqual(['first','repeat']);
+ await expect(approval).toHaveCount(0);
+
+ const other = await open(second.id);
+ const otherFrame = other.locator('.saved-app-viewer-frame').contentFrame();
+ await otherFrame.getByRole('button', {name:'Record',exact:true}).click();
+ await expect(other.locator('.bash-permission-dialog')).toBeVisible();
+ await expect(preview.locator('.bash-permission-dialog')).toHaveCount(0);
+ await orkas.closePreview(other);
+ expect(effects()).toEqual(['first','repeat']);
+ await orkas.closePreview(preview);
+ preview = await open(first.id); frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ await run('reopened');
+ await expect(preview.locator('.bash-permission-dialog')).toBeVisible();
+ expect(effects()).toEqual(['first','repeat']);
+ await preview.locator('.bash-permission-dialog [data-id="allow_once"]').click();
+ await expect(frame.getByRole('status')).toHaveText('Recorded');
+ await run('must-ask-again');
+ await expect(preview.locator('.bash-permission-dialog')).toBeVisible();
+ await preview.locator('.bash-permission-dialog [data-act="cancel"]').click();
+ await expect(frame.getByRole('status')).toHaveText('Denied');
+ await orkas.invoke('permissions.setLocalExecMode', {mode:'all_files_auto'});
+ await run('trusted'); await expect(frame.getByRole('status')).toHaveText('Recorded');
+ await expect(preview.locator('.bash-permission-dialog')).toHaveCount(0);
+ expect(effects()).toEqual(['first','repeat','reopened','trusted']);
+ expect(await orkas.electronApp!.evaluate(() => (globalThis as any).__nativeAppConfirmations)).toBe(0);
+ expect(orkas.modelRequests).toHaveLength(0);
+ expect(await frame.locator('body').evaluate(async () => {
+ try { await (window as any).orkasApp.appFiles.writeText({path:'escape.txt',text:'No'}); return 'unexpected'; }
+ catch (error) { return (error as any).code; }
+ })).toBe('E_NOT_DECLARED');
+ await orkas.closePreview(preview);
+ await orkas.invoke('connectors.remove', {id:connectorId});
+});
diff --git a/test/e2e/web_app_sdk_e2e_lifecycle.spec.ts b/test/e2e/web_app_sdk_e2e_lifecycle.spec.ts
new file mode 100644
index 00000000..1d15f758
--- /dev/null
+++ b/test/e2e/web_app_sdk_e2e_lifecycle.spec.ts
@@ -0,0 +1,255 @@
+import path from 'node:path';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+
+
+test('web and legacy cloud SDK authoring returns commercial-required without allocating apps', async ({ orkas }) => {
+ for (const appType of ['web', 'cloud']) {
+ const receipt = await orkas.electronApp!.evaluate(async (_electron, input) =>
+ (process as any).mainModule.require(input.module).createArtifact('account-e2e', 'refused-sdk', 'helper', {
+ appType: input.appType, files: [{ path: 'index.html', content: '<h1>Do not execute</h1>' }],
+ }), { module: path.resolve('src/main/features/chat_artifacts.ts'), appType });
+ expect(receipt).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ }
+ expect((await orkas.invoke<any>('savedApps.list')).apps).toEqual([]);
+ expect(orkas.electronApp!.windows()).toHaveLength(1);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('author can export, cancel, and explicitly clear incompatible local data before updating',async({orkas},testInfo)=>{
+ const state=await orkas.electronApp!.evaluate(async({dialog},input)=>{
+ const main=(process as any).mainModule,artifacts=main.require(input.artifacts),saved=main.require(input.saved),chats=main.require(input.chats),{LocalAppData}=main.require(input.data),paths=main.require(input.paths),crypto=main.require('node:crypto');
+ const uid='account-e2e',definition={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]};
+ const task=await chats.createConversation(uid,{title:'Local migration'});const make=(cid:string,text:string,data:any)=>artifacts.createArtifact(uid,cid,'helper',{files:[{path:'index.html',content:'<h1>'+text+'</h1>'},{path:'orkas-app.json',content:JSON.stringify({sdkVersion:1,capabilities:['data'],data})}]});
+ const original=await make(task.conversation_id,'Original',definition),app=await saved.saveFromArtifact(uid,task.conversation_id,original.artifactId);const key=crypto.createHash('sha256').update(JSON.stringify(['saved',app.id])).digest('hex'),file=paths.webAppSandboxRoot(uid,key,'local')+'/data.sqlite';
+ const db=new LocalAppData(file,paths.userLocalRoot(uid),definition);await db.call('data.insert',{table:'notes',values:{body:'KEEP'}});await db.close();const edit=await saved.openForEditing(uid,app.id),cid=edit.conversation.conversation_id;
+ const changed=await make(cid,'Updated',{version:1,tables:[]});(dialog as any).showSaveDialog=async()=>({canceled:false,filePath:input.exported});return {cid,artifactId:changed.artifactId,appId:app.id,file,definition};
+ },{artifacts:path.resolve('src/main/features/chat_artifacts.ts'),saved:path.resolve('src/main/features/saved_apps.ts'),chats:path.resolve('src/main/features/chats.ts'),data:path.resolve('src/main/features/web_apps/data.ts'),paths:path.resolve('src/main/paths.ts'),exported:path.join(orkas.workspaceRoot,'migration-export.sqlite')});
+ const page=orkas.page;await openSidebarEntry(page,'#apps-btn');await page.locator(`.app-card[data-app-id="${state.appId}"]`).hover();await page.locator(`.app-card[data-app-id="${state.appId}"] .app-card-more`).click();await page.locator('.app-row-menu-item[data-action="edit"]').click();
+ // Render the actual immutable edit result without paying a model provider.
+ await page.evaluate(state=>{const host=document.createElement('div');host.id='migration-result';document.querySelector('#panel-conversation')?.append(host);(window as any).renderChatArtifact(host,{cid:state.cid,artifactId:state.artifactId,title:'Updated'});},state);
+ const update=async()=>{await page.locator('#migration-result .chat-artifact-more').click();await expect(page.locator('.chat-artifact-menu [data-action="update"]')).toBeVisible();await page.locator('.chat-artifact-menu [data-action="update"]').click();};
+ await update();await expect(page.locator('.ui-dialog-overlay:visible')).toContainText('notes: 1');await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();await expect(page.locator('.ui-dialog-overlay:visible')).toContainText('Clear all local records');await page.locator('.ui-dialog-overlay:visible').screenshot({path:testInfo.outputPath('migration-confirmation.png')});await page.locator('.ui-dialog-overlay:visible [data-act="cancel"]').click();
+ const read=()=>orkas.electronApp!.evaluate(async(_electron,input)=>{const {LocalAppData}=(process as any).mainModule.require(input.module);const db=new LocalAppData(input.file,input.boundary,input.definition);try{return await db.call('internal.inspect',{});}finally{await db.close();}},{module:path.resolve('src/main/features/web_apps/data.ts'),file:state.file,boundary:path.join(orkas.workspaceRoot,'account-e2e/local'),definition:state.definition});expect((await read()).records).toBe(1);
+ await update();await page.locator('.ui-dialog-overlay:visible [data-act="cancel"]').click();await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();await expect(page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
+ await expect.poll(async()=>orkas.electronApp!.evaluate(({ },input)=>(process as any).mainModule.require('node:fs').readFileSync(input,'utf8'),path.join(orkas.workspaceRoot,'account-e2e/cloud/saved_apps',state.appId,'index.html'))).toContain('Updated');
+ const exported=await orkas.electronApp!.evaluate(async(_electron,input)=>{const {LocalAppData}=(process as any).mainModule.require(input.module);const db=new LocalAppData(input.file,input.boundary,input.definition);try{return await db.call('data.query',{table:'notes'});}finally{await db.close();}},{module:path.resolve('src/main/features/web_apps/data.ts'),file:path.join(orkas.workspaceRoot,'migration-export.sqlite'),boundary:orkas.workspaceRoot,definition:state.definition});expect(exported).toEqual({records:[{body:'KEEP'}]});expect(orkas.modelRequests).toHaveLength(0);
+});
+
+// The document starts real SDK inference while an unrelated image keeps its
+// first load pending. Load completion must not cancel that same document's work.
+test('SDK inference survives initial document load and a throwing progress consumer', async ({ modelOrkas: orkas }) => {
+ let releaseImage!: () => void;
+ const imageGate = new Promise<void>(resolve => { releaseImage = resolve; });
+ let requested = false;
+ await orkas.page.context().route('**/load-gate.svg', async route => {
+ requested = true;
+ await imageGate;
+ await route.continue();
+ });
+ const entry = orkas.createWorkspaceFile('load-race/index.html', `<!doctype html><html><head>
+ <script src="/__orkas/sdk.js"></script></head><body><h1>Loading notebook</h1>
+ <p role="status">Generating</p><img src="load-gate.svg" alt="">
+ <script>
+ window.finishedLoading = false; window.progressCalls = 0;
+ window.addEventListener('load', () => { window.finishedLoading = true; });
+ window.orkasApp.ai.generate({prompt:'Controlled stream',maxTokens:128}, {
+ onProgress: () => { window.progressCalls++; throw new Error('App progress renderer failed'); }
+ }).then(result => { document.querySelector('[role=status]').textContent = result.text; },
+ error => { document.querySelector('[role=status]').textContent = error.code; });
+ </script></body></html>`);
+ orkas.createWorkspaceFile('load-race/load-gate.svg', '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>');
+ orkas.createWorkspaceFile('load-race/orkas-app.json', JSON.stringify({ sdkVersion: 1, capabilities: ['ai'] }));
+ await orkas.electronApp!.evaluate(({ dialog }) => { (dialog as any).showMessageBox = async () => ({ response: 1, checkboxChecked: false }); });
+ orkas.setModelMode('controlled-slow');
+ const app: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, title: 'Loading notebook' });
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ const frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ try {
+ await expect.poll(() => requested).toBe(true);
+ await expect.poll(() => orkas.modelRequests.length).toBe(1);
+ expect(await frame.locator('body').evaluate(() => (window as any).finishedLoading)).toBe(false);
+ releaseImage();
+ await expect.poll(() => frame.locator('body').evaluate(() => (window as any).finishedLoading)).toBe(true);
+ await expect(frame.getByRole('status')).toHaveText('Generating');
+ orkas.releaseControlledModelChunk(); orkas.finishControlledModelStream();
+ await expect(frame.getByRole('status')).toHaveText('Hello from the local E2E model.');
+ expect(await frame.locator('body').evaluate(() => (window as any).progressCalls)).toBeGreaterThan(0);
+ expect(orkas.modelRequests).toHaveLength(1);
+ } finally { releaseImage(); }
+});
+
+// Same-app navigation cancels departing work without closing the application.
+test('same-app navigation cancels departing inference and the replacement document can use SDK', async ({ modelOrkas: orkas }, info) => {
+ await orkas.electronApp!.evaluate(async ({ dialog }, observer) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const Module = req('node:module');
+ const originalLoad = Module._load;
+ const profile = { startedAt: Date.now(), hostAlreadyLoaded: false, loads: [] as Array<{ name: string; ms: number; at: number }>, calls: [] as any[], restore: () => {} };
+ Module._load = function (id: string, ...args: any[]) {
+ const started = performance.now();
+ try { return originalLoad.call(this, id, ...args); }
+ finally {
+ const ms = performance.now() - started;
+ const normalized = String(id).replace(/\\/g, '/');
+ if (ms > 20 && /core-agent/.test(normalized) && profile.loads.length < 100) {
+ profile.loads.push({ name: normalized.split('/').slice(-2).join('/'), ms, at: Date.now() });
+ }
+ }
+ };
+ (globalThis as any).__webAppObserver = await req(observer).observeWebAppCalls();
+ // Inspect only an already loaded host; profiling must not prewarm setup.
+ const hostModule = Object.entries(Module._cache as Record<string, { exports: any }>)
+ .find(([id]) => id.replace(/\\/g, '/').endsWith('/features/web_apps/host.ts'))?.[1];
+ const host = hostModule?.exports.runtime?.host;
+ const generate = host?.generate;
+ if (typeof generate === 'function') {
+ profile.hostAlreadyLoaded = true;
+ host.generate = async function (...args: any[]) {
+ const call = { start: Date.now(), end: null as number | null };
+ profile.calls.push(call);
+ try { return await generate.apply(this, args); }
+ finally { call.end = Date.now(); }
+ };
+ }
+ profile.restore = () => { Module._load = originalLoad; if (generate) host.generate = generate; };
+ (globalThis as any).__webAppStartupProfile = profile;
+ (dialog as any).showMessageBox = async () => ({ response: 1, checkboxChecked: false });
+ }, path.resolve(__dirname, 'fixtures/web-app-author-main.ts'));
+ try {
+ const entry = orkas.createWorkspaceFile('navigation-cancel/index.html', `<!doctype html><html><head>
+ <script src="/__orkas/sdk.js"></script></head><body><h1>Navigation notebook</h1><p role="status">Ready</p></body></html>`);
+ orkas.createWorkspaceFile('navigation-cancel/orkas-app.json', JSON.stringify({ sdkVersion: 1, capabilities: ['ai','storage'] }));
+ const app: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, title: 'Navigation notebook' });
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ let preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ let frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(frame.getByRole('heading')).toHaveText('Navigation notebook');
+ orkas.setModelMode('controlled-slow');
+ await frame.locator('body').evaluate(() => {
+ (window as any).orkasApp.ai.generate({prompt:'Controlled stream',maxTokens:128}).then(
+ (result: any) => { document.querySelector('[role=status]')!.textContent = result.text; },
+ (error: any) => { document.querySelector('[role=status]')!.textContent = error.code; });
+ });
+ await expect.poll(() => orkas.modelRequests.length).toBe(1);
+ // The resource is an existing app document, not a network fixture that can
+ // accidentally bypass the owning will-frame-navigate guard.
+ await frame.locator('body').evaluate(() => { location.href = location.href + '?replacement'; });
+ await expect(frame.getByRole('status')).toHaveText('Ready');
+ // Cold inference first performs the existing read-only host handshake.
+ // Cancellation ownership is measured on inference, not that discovery call.
+ await expect.poll(() => orkas.electronApp!.evaluate(() => (globalThis as any).__webAppObserver.read().filter((call:any)=>call.method==='ai.generate'))).toEqual([
+ { method: 'ai.generate', ok: false, code: 'E_CANCELLED' },
+ ]);
+ expect(await frame.locator('body').evaluate(() => location.search)).toBe('?replacement');
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.keys())).toEqual({keys:[]});
+ orkas.releaseControlledModelChunk(); orkas.finishControlledModelStream();
+ await expect(frame.getByRole('status')).toHaveText('Ready');
+ expect(orkas.modelRequests).toHaveLength(1);
+ await orkas.closePreview(preview);
+ orkas.setModelMode('success');
+ preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(frame.getByRole('status')).toHaveText('Ready');
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.ai.generate({prompt:'Explicit recovery',maxTokens:128})))
+ .toMatchObject({text:'Hello from the local E2E model.',stopReason:'end_turn'});
+ expect(orkas.modelRequests).toHaveLength(2);
+ } finally {
+ const profile = await orkas.electronApp!.evaluate(() => {
+ const { restore, ...data } = (globalThis as any).__webAppStartupProfile;
+ restore();
+ return data;
+ }).catch(() => ({ unavailable: true }));
+ await info.attach('sdk-startup-profile.json', { body: JSON.stringify(profile), contentType: 'application/json' });
+ }
+});
+
+// Independent page scripts begin at request 1. They must not collide after navigation.
+test('local pages, reload and rejected navigation preserve the app SDK', async ({ modelOrkas: orkas }) => {
+ const code = `<script src="/__orkas/sdk.js"></script><script>
+ orkasApp.storage.get({key:'count'}).then(async ({value}) => {
+ await orkasApp.storage.set({key:'count',value:(value || 0)+1});
+ document.querySelector('output').textContent=String((value || 0)+1);
+ });</script>`;
+ const entry=orkas.createWorkspaceFile('multi/index.html','<!doctype html><h1>First</h1><output></output><a href="pages/second.html">Next</a>'+code);
+ orkas.createWorkspaceFile('multi/pages/second.html','<!doctype html><h1>Second</h1><output></output><button onclick="location.reload()">Reload</button><a href="chat-app://saved/foreign/index.html">Forbidden</a>'+code);
+ orkas.createWorkspaceFile('multi/orkas-app.json',JSON.stringify({sdkVersion:1,capabilities:['storage']}));
+ const app:any=await orkas.invoke('savedApps.saveFromPath',{path:entry,title:'Pages'});
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const preview=await orkas.openPreview(()=>orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ const frame=preview.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(frame.locator('output')).toHaveText('1');
+ await frame.getByRole('link',{name:'Next'}).click();
+ await expect(frame.getByRole('heading')).toHaveText('Second');
+ await expect(frame.locator('output')).toHaveText('2');
+ await frame.getByRole('button',{name:'Reload'}).click();
+ await expect(frame.locator('output')).toHaveText('3');
+ await frame.getByRole('link',{name:'Forbidden'}).click();
+ expect(await frame.locator('body').evaluate(()=>(window as any).orkasApp.storage.get({key:'count'}))).toEqual({value:3});
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('unavailable conversation apps show independent inline retries without modal stacks', async ({ orkas }, testInfo) => {
+ const fixture = await orkas.electronApp!.evaluate(async (_electron, input) => {
+ const main = (process as any).mainModule, fs = main.require('node:fs');
+ const artifacts = main.require(input.artifacts), chats = main.require(input.chats);
+ const task = await chats.createConversation('account-e2e', { title: 'App recovery' });
+ const items = [];
+ for (const title of ['Recovered form', 'Second form']) {
+ const app = await artifacts.createArtifact('account-e2e', task.conversation_id, 'helper', { files: [{ path: 'index.html', content: '<h1>' + title + '</h1>' }] });
+ const resolved = artifacts.resolveArtifactDir('account-e2e', task.conversation_id, app.artifactId);
+ fs.renameSync(resolved.dirPath, resolved.dirPath + '.held');
+ items.push({ cid: task.conversation_id, artifactId: app.artifactId, title, dir: resolved.dirPath });
+ }
+ return items;
+ }, { artifacts: path.resolve('src/main/features/chat_artifacts.ts'), chats: path.resolve('src/main/features/chats.ts') });
+ await orkas.page.evaluate(items => {
+ const host = document.createElement('div'); host.id = 'recovery-cards';
+ document.body.append(host); host.style.cssText = 'position:fixed;inset:60px 24px 24px;z-index:100;background:var(--bg);overflow:auto';
+ for (const item of items) (window as any).renderChatArtifact(host, item);
+ }, fixture);
+ const cards = orkas.page.locator('#recovery-cards .chat-artifact-card');
+ await expect(cards.locator('.chat-artifact-unavailable')).toHaveCount(2);
+ await expect(orkas.page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
+ await orkas.page.locator('#recovery-cards').screenshot({ path: testInfo.outputPath('inline-load-errors-en.png') });
+ await orkas.electronApp!.evaluate((_electron, dir) => {
+ const fs = (process as any).mainModule.require('node:fs'); fs.renameSync(dir + '.held', dir);
+ }, fixture[0].dir);
+ await cards.first().locator('.chat-artifact-unavailable button').click();
+ await expect(cards.first().locator('iframe').contentFrame().getByRole('heading')).toHaveText('Recovered form');
+ await expect(cards.first().locator('.chat-artifact-unavailable')).toHaveCount(0);
+ await expect(cards.nth(1).locator('.chat-artifact-unavailable')).toBeVisible();
+ await orkas.page.setViewportSize({ width: 820, height: 680 });
+ await orkas.page.evaluate(async item => {
+ await (window as any).setLang('zh');
+ const host = document.querySelector('#recovery-cards')!; host.innerHTML = '';
+ (window as any).renderChatArtifact(host, item);
+ }, fixture[1]);
+ await expect(cards.locator('.chat-artifact-unavailable button')).toHaveText('重新加载');
+ await orkas.page.locator('#recovery-cards').screenshot({ path: testInfo.outputPath('inline-load-error-zh-narrow.png') });
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('editing source survives recycle recovery and is reclaimed only after permanent task removal', async ({ orkas }) => {
+ const result = await orkas.electronApp!.evaluate(async (_electron, input) => {
+ const main = (process as any).mainModule, fs = main.require('node:fs');
+ const artifacts = main.require(input.artifacts), chats = main.require(input.chats);
+ const saved = main.require(input.saved), recycle = main.require(input.recycle), paths = main.require(input.paths);
+ const uid = 'account-e2e', task = await chats.createConversation(uid, { title: 'Edit retention' });
+ const original = await artifacts.createArtifact(uid, task.conversation_id, 'helper', { files: [{ path: 'index.html', content: '<h1>Retained source</h1>' }] });
+ const app = await saved.saveFromArtifact(uid, task.conversation_id, original.artifactId);
+ const edit = await saved.openForEditing(uid, app.id), cid = edit.conversation.conversation_id;
+ const snapshot = paths.userAppEditsDir(uid) + '/' + cid + '/snapshot/index.html';
+ const contents = fs.readFileSync(snapshot, 'utf8');
+ const batch = await recycle.createAppRecycleBatchForConversation(uid, cid);
+ await chats.deleteConversation(uid, cid);
+ const retained = fs.readFileSync(snapshot, 'utf8') === contents;
+ // Exercise real module instances and competing restore/purge operations.
+ const [restored] = await Promise.all([recycle.restoreRecycleBatch(uid, batch.id), recycle.deleteRecycleBatch(uid, batch.id)]);
+ const recovered = fs.readFileSync(snapshot, 'utf8') === contents;
+ await chats.deleteConversation(uid, cid);
+ return { retained, recovered, failures: restored.failed_paths.length, removed: !fs.existsSync(snapshot), originalIntact: fs.existsSync(paths.savedAppDir(uid, app.id) + '/index.html') };
+ }, { artifacts: path.resolve('src/main/features/chat_artifacts.ts'), chats: path.resolve('src/main/features/chats.ts'), saved: path.resolve('src/main/features/saved_apps.ts'), recycle: path.resolve('src/main/features/recycle_bin.ts'), paths: path.resolve('src/main/paths.ts') });
+ expect(result).toEqual({ retained: true, recovered: true, failures: 0, removed: true, originalIntact: true });
+ expect(orkas.modelRequests).toHaveLength(0);
+});
diff --git a/test/e2e/web_app_sdk_e2e_runtime.spec.ts b/test/e2e/web_app_sdk_e2e_runtime.spec.ts
new file mode 100644
index 00000000..c7d30bb9
--- /dev/null
+++ b/test/e2e/web_app_sdk_e2e_runtime.spec.ts
@@ -0,0 +1,870 @@
+import { appendFileSync, cpSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { createServer } from 'node:http';
+import { createHash } from 'node:crypto';
+import type { AddressInfo } from 'node:net';
+import { openSidebarEntry, expect, test } from './fixtures/orkas';
+
+
+test('ordinary artifact messages lose trust after the same iframe navigates to an external origin', async ({ modelOrkas: orkas }) => {
+ const external=createServer((_request,response)=>{response.setHeader('Content-Type','text/html');response.end('<script>parent.postMessage({__orkasArtifact:true,type:"probe"},"*")</script>');});
+ await new Promise<void>(resolve=>external.listen(0,'127.0.0.1',resolve));
+ try{
+ const entry=orkas.createWorkspaceFile('ordinary-origin/index.html','<script>parent.postMessage({__orkasArtifact:true,type:"probe"},"*")</script>');
+ const saved:any=await orkas.invoke('savedApps.saveFromPath',{path:entry,title:'Origin fixture'});expect(saved.ok).toBe(true);
+ const opened:any=await orkas.invoke('webApps.open',{source:{appId:saved.id}});
+ const ordinaryOrigin = 'chat-app://' + new URL(opened.url).host;
+ await orkas.page.evaluate(url=>{
+ const frame=document.createElement('iframe');frame.id='origin-probe';frame.src=url;
+ frame.setAttribute('sandbox',(window as any).OrkasArtifactSecurity.SANDBOX);
+ (window as any).originEvidence=[];
+ window.addEventListener('message',event=>{if(event.source===frame.contentWindow&&event.data?.type==='probe')
+ (window as any).originEvidence.push({trusted:(window as any).OrkasArtifactSecurity.trustedArtifactMessage(event,frame),origin:event.origin});});
+ document.body.append(frame);
+ },opened.url);
+ await expect.poll(()=>orkas.page.evaluate(()=>(window as any).originEvidence)).toEqual([{trusted:true,origin:ordinaryOrigin}]);
+ const url=`http://127.0.0.1:${(external.address() as AddressInfo).port}/`;
+ // Navigate inside the document: the host's src attribute and WindowProxy stay unchanged.
+ await orkas.page.locator('#origin-probe').contentFrame().locator('body').evaluate((_node,url)=>{location.href=url;},url);
+ await expect.poll(()=>orkas.page.evaluate(()=>(window as any).originEvidence)).toEqual([
+ {trusted:true,origin:ordinaryOrigin},{trusted:false,origin:new URL(url).origin},
+ ]);
+ expect(orkas.modelRequests).toHaveLength(0);
+ }finally{await new Promise<void>(resolve=>external.close(()=>resolve()));}
+});
+
+test('bundled SDK starter works through visible controls and uses ordinary model calls and recovers from existing export targets', async ({ modelOrkas: orkas }, info) => {
+ const source = path.resolve(__dirname, '../../resources/builtin/system/skills/web-app-sdk/assets/starter');
+ const entry = orkas.createWorkspaceFile('sdk-starter/index.html', readFileSync(path.join(source, 'index.html'), 'utf8'));
+ orkas.createWorkspaceFile('sdk-starter/orkas-app.json', readFileSync(path.join(source, 'orkas-app.json'), 'utf8'));
+ const app: any = await orkas.invoke('savedApps.saveFromPath', {path:entry,title:'SDK starter'});
+ expect(app.ok).toBe(true);
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ const frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(frame.locator('#status')).toContainText('Ready.');
+ await expect(frame.getByRole('note')).toContainText('Selected files are read-only');
+ const input = orkas.createWorkspaceFile('starter-source.txt', 'A useful note from a selected file.');
+ await orkas.selectFilesOnNextDialog([input]);
+ await preview.evaluate(() => {
+ (window as any).hostInputEvidence = [];
+ for (const type of ['pointerdown', 'pointerup', 'click']) document.addEventListener(type, event => {
+ const target = event.target as HTMLElement;
+ (window as any).hostInputEvidence.push({ type, tag: target.tagName, id: target.id, className: target.className });
+ }, true);
+ });
+ await frame.locator('body').evaluate(() => {
+ (window as any).inputEvidence = [];
+ for (const type of ['pointerdown', 'pointerup', 'click', 'focusin']) document.addEventListener(type, event => {
+ const target = event.target as HTMLElement;
+ (window as any).inputEvidence.push({ type, target: target.id, focused: document.hasFocus(), trusted: event.isTrusted });
+ }, true);
+ });
+ const nativeWindow = await orkas.electronApp!.evaluate(({ BrowserWindow }) => {
+ const win = BrowserWindow.getAllWindows().find(win => win.webContents.getURL().startsWith('file:'))!;
+ return { visible: win.isVisible(), focused: win.isFocused(), minimized: win.isMinimized(), webContentsFocused: win.webContents.isFocused() };
+ });
+ await frame.getByRole('button', {name:'Open text file'}).click();
+ try { await expect(frame.locator('#draft')).toHaveValue('A useful note from a selected file.'); }
+ finally {
+ const evidence = {
+ nativeWindow,
+ frame: await frame.locator('body').evaluate(() => ({ events: (window as any).inputEvidence,
+ status: document.querySelector('#status')?.textContent, buttonDisabled: (document.querySelector('#open') as HTMLButtonElement).disabled })),
+ host: await preview.evaluate(() => ({ events: (window as any).hostInputEvidence, focused: document.hasFocus() })),
+ };
+ writeFileSync(info.outputPath('starter-input-evidence.json'), JSON.stringify(evidence, null, 2));
+ await info.attach('starter-input-evidence', { contentType: 'application/json', path: info.outputPath('starter-input-evidence.json') });
+ }
+ await frame.getByRole('button', {name:'Save draft'}).click();
+ await expect(frame.locator('#status')).toHaveText('Draft saved.');
+ await frame.getByRole('button', {name:'Summarize',exact:true}).click();
+ await expect(frame.locator('#status')).toHaveText('Summary ready.');
+ await expect(frame.locator('#output')).toHaveText('Hello from the local E2E model.');
+ expect(orkas.modelRequests).toHaveLength(1);
+ await orkas.electronApp!.evaluate(({dialog}, file) => { (dialog as any).showSaveDialog = async () => ({canceled:false,filePath:file}); }, input);
+ await frame.getByRole('button', {name:'Export result'}).click();
+ await expect(frame.locator('#status')).toContainText('choose a new export filename');
+ expect(readFileSync(input, 'utf8')).toBe('A useful note from a selected file.');
+ const exported = path.join(orkas.userWorkspaceRoot, 'starter-export.txt');
+ await orkas.electronApp!.evaluate(({dialog}, file) => { (dialog as any).showSaveDialog = async () => ({canceled:false,filePath:file}); }, exported);
+ await frame.getByRole('button', {name:'Export result'}).click();
+ await expect(frame.locator('#status')).toHaveText('Export saved.');
+ expect(readFileSync(exported, 'utf8')).toBe('Hello from the local E2E model.');
+ await orkas.closePreview(preview);
+ const reopenedPage = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ const reopened = reopenedPage.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(reopened.locator('#draft')).toHaveValue('A useful note from a selected file.');
+ expect(orkas.modelRequests).toHaveLength(1);
+});
+
+const html='<!doctype html><html><head><script src="__orkas/sdk.js"></script></head><body><h1>SDK App</h1></body></html>';
+async function seed(orkas: any, folder: string, source = html) {
+ const entry=orkas.createWorkspaceFile(folder+'/index.html',source);
+ orkas.createWorkspaceFile(folder+'/orkas-app.json',JSON.stringify({sdkVersion:1,capabilities:['storage','appFiles','files','ai','library']}));
+ return orkas.invoke('savedApps.saveFromPath',{path:entry,title:folder});
+}
+async function mount(orkas: any, id: string) {
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${id}"]`).click());
+ const frame=preview.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(frame.locator('h1')).toHaveText('SDK App');
+ return frame;
+}
+test('SDK app loads external code and assets and calls an API without losing host isolation', async ({ modelOrkas: orkas }) => {
+ const requests: string[] = [];
+ const server = createServer((request, response) => {
+ requests.push(`${request.method} ${request.url}`);
+ response.setHeader('Access-Control-Allow-Origin', '*');
+ response.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-App-Test');
+ response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ if (request.method === 'OPTIONS') { response.writeHead(204); response.end(); return; }
+ if (request.url === '/app.js') {
+ response.setHeader('Content-Type', 'text/javascript');
+ response.end('window.externalCodeLoaded = true;');
+ } else if (request.url === '/app.css') {
+ response.setHeader('Content-Type', 'text/css');
+ response.end('#remote-style { color: rgb(1, 2, 3); }');
+ } else if (request.url === '/pixel.svg') {
+ response.setHeader('Content-Type', 'image/svg+xml');
+ response.end('<svg xmlns="http://www.w3.org/2000/svg" width="7" height="9"><rect width="7" height="9" fill="blue"/></svg>');
+ } else if (request.url === '/events') {
+ response.setHeader('Content-Type', 'text/event-stream');
+ response.end('data: live-event\n\n');
+ } else {
+ let body = '';
+ request.on('data', chunk => { body += chunk; });
+ request.on('end', () => {
+ response.setHeader('Content-Type', 'application/json');
+ response.end(JSON.stringify({ accepted: body === '{"message":"hello"}', header: request.headers['x-app-test'] }));
+ });
+ }
+ });
+ server.on('upgrade', (request, socket) => {
+ requests.push(`UPGRADE ${request.url}`);
+ const accept = createHash('sha1').update(String(request.headers['sec-websocket-key']) + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');
+ socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ' + accept + '\r\n\r\n');
+ socket.write(Buffer.from([0x81, 4, ...Buffer.from('live')]));
+ socket.on('data', () => socket.end(Buffer.from([0x88, 0])));
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const app: any = await seed(orkas, 'sdk-online', html.replace('</head>',
+ `<script src="${base}/app.js"></script><link rel="stylesheet" href="${base}/app.css"></head>`)
+ .replace('</body>', '<p id="remote-style">Remote style</p><img id="remote-image" src="' + base + '/pixel.svg"></body>'));
+ const frame = await mount(orkas, app.id);
+ await expect.poll(() => frame.locator('body').evaluate(() => (window as any).externalCodeLoaded)).toBe(true);
+ await expect(frame.locator('#remote-style')).toHaveCSS('color', 'rgb(1, 2, 3)');
+ await expect.poll(() => frame.locator('#remote-image').evaluate((image: HTMLImageElement) => image.naturalWidth)).toBe(7);
+ const result = await frame.locator('body').evaluate(async (_node, url) => {
+ const response = await fetch(url + '/api', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-App-Test': 'ordinary-browser-call' },
+ body: JSON.stringify({ message: 'hello' }), signal: AbortSignal.timeout(5000) });
+ const api = (window as any).orkasApp;
+ await api.storage.set({ key: 'network-result', value: await response.json() });
+ return { stored: await api.storage.get({ key: 'network-result' }), node: typeof (window as any).require, ipc: typeof (window as any).orkas };
+ }, base);
+ expect(result).toEqual({ stored: { value: { accepted: true, header: 'ordinary-browser-call' } }, node: 'undefined', ipc: 'undefined' });
+ const streams = await frame.locator('body').evaluate(async (_node, base) => {
+ const message = (source: WebSocket | EventSource) => new Promise<string>((resolve, reject) => {
+ const timeout = setTimeout(() => { source.close(); reject(new Error('Stream timed out')); }, 5000);
+ source.onmessage = event => { clearTimeout(timeout); source.close(); resolve(event.data); };
+ source.onerror = () => { clearTimeout(timeout); source.close(); reject(new Error('Stream failed')); };
+ });
+ return Promise.all([message(new WebSocket(base.replace('http:', 'ws:') + '/socket')), message(new EventSource(base + '/events'))]);
+ }, base);
+ expect(streams).toEqual(['live', 'live-event']);
+ expect(requests).toEqual(expect.arrayContaining(['GET /app.js', 'GET /app.css', 'GET /pixel.svg', 'OPTIONS /api', 'POST /api']));
+ const beforePreview = [...requests];
+ const preview = await orkas.electronApp!.evaluate(async (_electron, args) => {
+ const { renderResponsiveHtmlPreview } = (process as any).mainModule.require(args.module);
+ return (await renderResponsiveHtmlPreview(args.entry, [{ name: 'desktop', width: 800, height: 600 }], {}, { interactions: false })).evidence;
+ }, { module: path.resolve(__dirname, '../../src/main/features/html_preview.ts'), entry: path.join(orkas.userWorkspaceRoot, 'sdk-online/index.html') });
+ expect(preview.sdk).toMatchObject({ mode: 'preview', storage: 'temporary' });
+ expect(requests.slice(beforePreview.length)).toEqual(expect.arrayContaining(['GET /app.js', 'GET /app.css', 'GET /pixel.svg']));
+ expect(preview.blockedResourceCount).toBe(0);
+ expect(preview.viewports[0].consoleErrors).toEqual([]);
+ expect(orkas.modelRequests).toHaveLength(0);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ }
+});
+test('SDK app discovers, reads a selected file, generates, exports and keeps isolated state across reopening',async({modelOrkas:orkas})=>{
+ const app:any=await seed(orkas,'sdk-a'); expect(app.ok).toBe(true);
+ const frame=await mount(orkas,app.id);
+ expect(await frame.locator('body').evaluate(()=>typeof (window as any).orkas)).toBe('undefined');
+ const catalog:any=await frame.locator('body').evaluate(()=>(window as any).orkasApp.capabilities.list());
+ expect(catalog.methods.find((m:any)=>m.name==='ai.generate')).toMatchObject({supported:true,declared:true,authorized:true});
+ const source=orkas.createWorkspaceFile('source.txt','Text selected by the user.');
+ await orkas.selectFilesOnNextDialog([source]);
+ const selected:any=await frame.locator('body').evaluate(async()=>{
+ const api=(window as any).orkasApp;const file=await api.files.pick();return api.files.readText({handle:file.handle});
+ });expect(selected.text).toBe('Text selected by the user.');
+ await orkas.electronApp!.evaluate(({dialog})=>{const d=dialog as any;d.showMessageBox=async()=>({response:1,checkboxChecked:false});});
+ const generated:any=await frame.locator('body').evaluate(async()=>{
+ const api=(window as any).orkasApp;const result=await api.ai.generate({prompt:'Write a greeting.',maxTokens:128});await api.storage.set({key:'result',value:result.text});return result;
+ });expect(generated.text).toBe('Hello from the local E2E model.');expect(orkas.modelRequests).toHaveLength(1);
+ const exportPath=path.join(orkas.userWorkspaceRoot,'sdk-result.txt');
+ await orkas.electronApp!.evaluate(({dialog},file)=>{(dialog as any).showSaveDialog=async()=>({canceled:false,filePath:file});},exportPath);
+ await frame.locator('body').evaluate((_node,text)=>(window as any).orkasApp.files.saveAs({name:'sdk-result.txt',text}),generated.text);
+ expect(readFileSync(exportPath,'utf8')).toBe(generated.text);
+ await orkas.closePreview(frame.owner().page());
+ const second:any=await seed(orkas,'sdk-b');const other=await mount(orkas,second.id);
+ expect(await other.locator('body').evaluate(()=>(window as any).orkasApp.storage.get({key:'result'}))).toEqual({value:null});
+ await orkas.closePreview(other.owner().page());
+ await orkas.relaunch();const reopened=await mount(orkas,app.id);
+ expect(await reopened.locator('body').evaluate(()=>(window as any).orkasApp.storage.get({key:'result'}))).toEqual({value:generated.text});
+});
+
+test('a denied cross-origin write has no remote effect and an explicit retry keeps the app usable', async ({ modelOrkas: orkas }) => {
+ const requests: string[] = [];
+ const writes: string[] = [];
+ const server = createServer((request, response) => {
+ requests.push(`${request.method} ${request.url}`);
+ if (request.url === '/allowed') {
+ response.setHeader('Access-Control-Allow-Origin', '*');
+ response.setHeader('Access-Control-Allow-Headers', 'X-App-Test');
+ response.setHeader('Access-Control-Allow-Methods', 'POST');
+ }
+ if (request.method === 'OPTIONS') { response.writeHead(204); response.end(); return; }
+ let body = '';
+ request.on('data', chunk => { body += chunk; });
+ request.on('end', () => { writes.push(body); response.end('Saved remotely'); });
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const app: any = await seed(orkas, 'cors-recovery', html.replace('</body>', `
+ <button id="send">Send</button><button id="retry">Retry</button><output role="status">Ready</output>
+ <script>
+ async function send(route) {
+ try {
+ const response = await fetch('${base}' + route, { method: 'POST', headers: { 'X-App-Test': 'preflight' }, body: 'User approved content' });
+ const text = await response.text();
+ await orkasApp.storage.set({key:'result',value:text});
+ document.querySelector('output').textContent=text;
+ } catch (_) { document.querySelector('output').textContent='Request blocked; retry available'; }
+ }
+ document.querySelector('#send').onclick=()=>send('/denied');
+ document.querySelector('#retry').onclick=()=>send('/allowed');
+ </script></body>`));
+ const frame = await mount(orkas, app.id);
+ await frame.getByRole('button', { name: 'Send', exact: true }).click();
+ await expect(frame.getByRole('status')).toHaveText('Request blocked; retry available');
+ expect(requests).toEqual(['OPTIONS /denied']);
+ expect(writes).toEqual([]);
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'result' }))).toEqual({ value: null });
+ await frame.getByRole('button', { name: 'Retry', exact: true }).click();
+ await expect(frame.getByRole('status')).toHaveText('Saved remotely');
+ expect(writes).toEqual(['User approved content']);
+ expect(requests.filter(value => value === 'POST /allowed')).toHaveLength(1);
+ await orkas.closePreview(frame.owner().page());
+ const reopened = await mount(orkas, app.id);
+ expect(await reopened.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'result' }))).toEqual({ value: 'Saved remotely' });
+ expect(writes).toHaveLength(1);
+ expect(orkas.modelRequests).toHaveLength(0);
+ } finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); }
+});
+
+test('SDK metadata, JSON removal, binary snapshots and dialog cancellation cross the actual iframe bridge', async ({ modelOrkas: orkas }) => {
+ const app: any = await seed(orkas, 'sdk-remaining-methods');
+ const frame = await mount(orkas, app.id);
+ const metadata = await frame.locator('body').evaluate(async () => {
+ const api = (window as any).orkasApp;
+ const context = await api.host.getContext();
+ const schema = await api.capabilities.describe({ method: 'ai.generate' });
+ await api.storage.set({ key: 'nested', value: { text: '你好', values: [0, false, null] } });
+ const stored = await api.storage.get({ key: 'nested' });
+ const keys = await api.storage.keys();
+ await api.storage.remove({ key: 'nested' });
+ return { context, schema, stored, keys, removed: await api.storage.get({ key: 'nested' }) };
+ });
+ expect(metadata.context).toMatchObject({ sdkVersion: 1, language: expect.any(String) });
+ expect(metadata.schema.inputSchema.properties.maxTokens.default).toBeUndefined();
+ expect(metadata.stored).toEqual({ value: { text: '你好', values: [0, false, null] } });
+ expect(metadata.keys).toEqual({ keys: ['nested'] });
+ expect(metadata.removed).toEqual({ value: null });
+ const source = orkas.createWorkspaceFile('bytes.bin', '');
+ writeFileSync(source, Buffer.from([0, 255, 254, 128]));
+ await orkas.selectFilesOnNextDialog([source]);
+ const file = await frame.locator('body').evaluate(() => (window as any).orkasApp.files.pick());
+ expect(file).not.toHaveProperty('path');
+ writeFileSync(source, 'Changed after selection');
+ const result = await frame.locator('body').evaluate(async (_node, handle) => {
+ const api = (window as any).orkasApp;
+ const bytes = await api.files.readBase64({ handle });
+ const textError = await api.files.readText({ handle }).then(() => null, (error: any) => error.code);
+ await api.files.release({ handle });
+ const staleError = await api.files.readBase64({ handle }).then(() => null, (error: any) => error.code);
+ return { bytes, textError, staleError };
+ }, file.handle);
+ expect(result).toEqual({ bytes: { base64: 'AP/+gA==' }, textError: 'E_ENCODING', staleError: 'E_HANDLE' });
+ await orkas.electronApp!.evaluate(({ dialog }) => {
+ (dialog as any).showOpenDialog = async () => ({ canceled: true, filePaths: [] });
+ (dialog as any).showSaveDialog = async () => ({ canceled: true });
+ });
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.files.pick())).toBeNull();
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.files.saveAs({ name: 'cancel.txt', text: 'Not saved' }))).toBeNull();
+ expect(readFileSync(source, 'utf8')).toBe('Changed after selection');
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('SDK streams and cancels actual inference transport, then allows an explicit fresh request', async ({ modelOrkas: orkas }, info) => {
+ await orkas.electronApp!.evaluate(async (_electron, file) => {
+ (globalThis as any).__webAppObserver = await (process as any).mainModule.require(file).observeWebAppCalls();
+ }, path.resolve(__dirname, 'fixtures/web-app-author-main.ts'));
+ await orkas.page.evaluate(() => {
+ const events: any[] = (window as any).__streamLifecycle = [];
+ const record = (event: any) => { if (events.length < 64) events.push({ ...event, time: performance.now() }); };
+ window.addEventListener('pagehide', () => record({ kind: 'host-pagehide' }));
+ document.addEventListener('keydown', event => {
+ if (event.key === 'Escape') record({ kind: 'escape', trusted: event.isTrusted });
+ }, true);
+ document.addEventListener('click', event => {
+ if ((event.target as HTMLElement).closest('.saved-app-viewer-close')) record({ kind: 'close-click', trusted: event.isTrusted });
+ }, true);
+ window.addEventListener('message', event => {
+ if (event.data?.__orkasApp === 1) record({ kind: 'message', type: event.data.type, method: event.data.method });
+ });
+ const remove = HTMLIFrameElement.prototype.removeEventListener;
+ HTMLIFrameElement.prototype.removeEventListener = function (type: string, listener: any, options?: any) {
+ if (type === 'load') record({ kind: 'release', stack: new Error().stack });
+ return remove.call(this, type, listener, options);
+ };
+ document.addEventListener('load', event => {
+ const frame = event.target as HTMLIFrameElement;
+ if (frame.tagName === 'IFRAME') record({ kind: 'load', blank: frame.contentDocument?.URL === 'about:blank' });
+ }, true);
+ });
+ const app: any = await seed(orkas, 'sdk-stream-cancel');
+ const frame = await mount(orkas, app.id);
+ await orkas.electronApp!.evaluate(({ dialog }) => {
+ (dialog as any).showMessageBox = async () => ({ response: 1, checkboxChecked: false });
+ });
+ orkas.setModelMode('controlled-slow');
+ await frame.locator('body').evaluate(() => {
+ const state = (window as any).streamProbe = { controller: new AbortController(), deltas: [] as string[], outcome: null as any, started: performance.now(), transport: [] as any[] };
+ window.addEventListener('message', event => {
+ if (event.source === parent && event.data?.__orkasApp === 1 && state.transport.length < 64) state.transport.push({ type: event.data.type, id: event.data.id, elapsed: performance.now() - state.started });
+ });
+ const input = { prompt: 'Controlled stream', maxTokens: 128 };
+ (window as any).orkasApp.ai.generate(input, {
+ signal: state.controller.signal, onProgress: (event: any) => state.deltas.push(event.text),
+ }).then((result: any) => { state.outcome = result; }, (error: any) => { state.outcome = { code: error.code }; });
+ input.prompt = 'Changed after SDK call';
+ });
+ try {
+ await expect.poll(async () => ({ requests: orkas.modelRequests.length,
+ outcome: await frame.locator('body').evaluate(() => (window as any).streamProbe.outcome),
+ }), { timeout: 30_000 }).toEqual({ requests: 1, outcome: null });
+ expect(JSON.stringify(orkas.modelRequests[0])).toContain('Controlled stream');
+ expect(JSON.stringify(orkas.modelRequests[0])).not.toContain('Changed after SDK call');
+ orkas.releaseControlledModelChunk();
+ await expect.poll(() => frame.locator('body').evaluate(() => (window as any).streamProbe.deltas.join(''))).toBe('Hello from the local E2E model.');
+ expect(await frame.locator('body').evaluate(() => (window as any).streamProbe.outcome)).toBeNull();
+ await frame.locator('body').evaluate(() => (window as any).streamProbe.controller.abort());
+ await expect.poll(() => frame.locator('body').evaluate(() => (window as any).streamProbe.outcome)).toEqual({ code: 'E_CANCELLED' });
+ await expect.poll(() => orkas.electronApp!.evaluate(() =>
+ (globalThis as any).__webAppObserver.read().filter((call: any) => call.method === 'ai.generate')
+ )).toEqual([{ method: 'ai.generate', ok: false, code: 'E_CANCELLED' }]);
+ orkas.finishControlledModelStream();
+ orkas.setModelMode('success');
+ const recovered = await frame.locator('body').evaluate(() => (window as any).orkasApp.ai.generate({ prompt: 'Explicit retry', maxTokens: 128 }));
+ expect(recovered).toMatchObject({ text: 'Hello from the local E2E model.', stopReason: 'end_turn' });
+ expect(orkas.modelRequests).toHaveLength(2);
+ expect(await frame.locator('body').evaluate(() => (window as any).streamProbe.outcome)).toEqual({ code: 'E_CANCELLED' });
+ } finally {
+ const lifecycle = await orkas.page.evaluate(() => (window as any).__streamLifecycle);
+ const state = await frame.locator('body').evaluate(() => ({ ready: document.readyState, outcome: (window as any).streamProbe?.outcome,
+ aborted: (window as any).streamProbe?.controller.signal.aborted, transport: (window as any).streamProbe?.transport }), undefined, { timeout: 1000 }).catch(() => ({ unavailable: true }));
+ const calls = await orkas.electronApp!.evaluate(() => (globalThis as any).__webAppObserver.read());
+ const evidenceFile = info.outputPath('stream-lifecycle-evidence.json');
+ writeFileSync(evidenceFile, JSON.stringify({ lifecycle, state, calls, requests: orkas.modelRequests.length }, null, 2));
+ await info.attach('stream-lifecycle-evidence', { contentType: 'application/json', path: evidenceFile });
+ }
+});
+
+test('SDK tools discovery and execution read the real Library without redundant app consent', async ({ modelOrkas: orkas }) => {
+ await orkas.electronApp!.evaluate(async (_electron, modules) => {
+ const { getActiveUserId } = (process as any).mainModule.require(modules.users);
+ const { upsertFile } = (process as any).mainModule.require(modules.kb);
+ const embedding = Array(512).fill(0); embedding[0] = 1;
+ await upsertFile(getActiveUserId(), { relPath: 'sdk-note.md', kind: 'text', bytes: 23, mtime: 1, sha1: 'sdk-fixture',
+ chunks: [{ title: 'SDK note', content: 'Independent Library content', embedding }] });
+ }, { users: path.resolve(__dirname, '../../src/main/features/users.ts'), kb: path.resolve(__dirname, '../../src/main/features/kb_vector.ts') });
+ const app: any = await seed(orkas, 'sdk-library');
+ const frame = await mount(orkas, app.id);
+ const catalog = await frame.locator('body').evaluate(() => (window as any).orkasApp.tools.list());
+ expect(catalog.tools.map((tool: any) => tool.name)).toContain('library');
+ expect(catalog.tools.map((tool: any) => tool.name)).not.toContain('bash');
+ const result = await frame.locator('body').evaluate(() => (window as any).orkasApp.tools.call({ name: 'library', arguments: { action: 'read', scope: 'global', path: 'sdk-note.md' } }));
+ expect(result.content).toContain('Independent Library content');
+ expect(result.isError).not.toBe(true);
+ expect(result).not.toHaveProperty('observations');
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('HTML preview loads the real SDK through an isolated host and leaves the app container working', async ({ modelOrkas: orkas }, info) => {
+ const app: any = await seed(orkas, 'sdk-preview-boundary', html.replace('src="__orkas', 'src="/__orkas'));
+ const preview = await orkas.electronApp!.evaluate(async (_electron, args) => {
+ const { renderResponsiveHtmlPreview } = (process as any).mainModule.require(args.module);
+ return (await renderResponsiveHtmlPreview(args.entry, [{ name: 'desktop', width: 1280, height: 800 }], {}, { interactions: false })).evidence;
+ }, { module: path.resolve(__dirname, '../../src/main/features/html_preview.ts'), entry: path.join(orkas.userWorkspaceRoot, 'sdk-preview-boundary/index.html') });
+ await info.attach('standalone-preview-evidence', { contentType: 'application/json', body: JSON.stringify(preview) });
+ expect(preview.ok).toBe(true);
+ expect(preview.blockedResourceSamples).toEqual([]);
+ expect(preview.sdk).toMatchObject({ mode: 'preview', storage: 'temporary' });
+ expect(orkas.page.isClosed()).toBe(false);
+ const frame = await mount(orkas, app.id);
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.host.getContext())).toMatchObject({ sdkVersion: 1 });
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('authoring preview uses SDK storage and reports unavailable services without dialogs, model calls or persistent state', async ({ modelOrkas: orkas }, info) => {
+ const entry = orkas.createWorkspaceFile('sdk-preview-journey/index.html', `<!doctype html><html><head>
+ <script src="/__orkas/sdk.js"></script><style>button:focus-visible{outline:3px solid blue}</style></head><body>
+ <h1>Preview SDK</h1><button id="run">Check SDK</button><p id="result" role="status">Waiting</p><script>
+ document.getElementById('run').onclick = async () => {
+ const api = window.orkasApp, check = (value) => { if (!value) throw new Error('Preview SDK assertion failed'); };
+ try {
+ check(typeof window.orkas === 'undefined' && typeof require === 'undefined');
+ const context = await api.host.getContext();
+ check(context.mode === 'preview' && context.language === 'zh');
+ await api.appFiles.writeText({path:'note.txt',text:'预览'});
+ check((await api.appFiles.readText({path:'note.txt'})).text === '预览');
+ const catalog = await api.capabilities.list();
+ check(catalog.methods.find(m => m.name === 'ai.generate').available === false);
+ check((await api.capabilities.describe({method:'storage.set'})).name === 'storage.set');
+ check((await api.storage.get({key:'draft'})).value === null);
+ await api.storage.set({key:'draft',value:'Preview text'});
+ check((await api.storage.get({key:'draft'})).value === 'Preview text');
+ check((await api.storage.keys()).keys.includes('draft'));
+ await api.storage.remove({key:'draft'});
+ await Promise.all(Array.from({length:12}, (_,i) => api.storage.set({key:'batch-'+i,value:i})));
+ check((await api.storage.keys()).keys.length === 12);
+ check((await api.tools.list()).tools.length === 0);
+ for (const [method,args] of [['files.pick',{}],['files.saveAs',{name:'export.txt',text:'Denied'}],
+ ['ai.generate',{prompt:'Must not run'}],['tools.call',{name:'library',arguments:{}}]]) {
+ let code; try { await api.call(method,args); } catch (e) {code=e.code;} check(code === 'E_UNAVAILABLE');
+ }
+ document.getElementById('result').textContent = 'SDK verified';
+ } catch(e) { console.error(e.message); document.getElementById('result').textContent='Failed'; }
+ };
+ </script></body></html>`);
+ orkas.createWorkspaceFile('sdk-preview-journey/orkas-app.json', JSON.stringify({ sdkVersion: 1, capabilities: ['storage', 'appFiles', 'files', 'ai', 'library'] }));
+ const result = await orkas.electronApp!.evaluate(async ({ BrowserWindow, dialog }, args) => {
+ const fs = (process as any).mainModule.require('node:fs');
+ const os = (process as any).mainModule.require('node:os');
+ const { setLanguage } = (process as any).mainModule.require(args.config); setLanguage('zh');
+ const windowsBefore = BrowserWindow.getAllWindows().map(w => w.id);
+ const storesBefore = fs.readdirSync(os.tmpdir()).filter((name: string) => name.startsWith('orkas-preview-storage-')).sort();
+ const dialogs: string[] = [];
+ const original = { showOpenDialog: dialog.showOpenDialog, showSaveDialog: dialog.showSaveDialog, showMessageBox: dialog.showMessageBox };
+ for (const key of Object.keys(original)) (dialog as any)[key] = async () => { dialogs.push(key); throw new Error('Unexpected native adapter'); };
+ const { createLocalTools } = (process as any).mainModule.require(args.tools);
+ const { getActiveUserId } = (process as any).mainModule.require(args.users);
+ try {
+ const tool = createLocalTools({ userId: getActiveUserId(), cwd: args.root }).find((tool: any) => tool.name === 'html_preview');
+ const runs = [];
+ for (let index = 0; index < 2; index++) runs.push(await tool.execute({ path: args.entry, target: 'desktop' }, { signal: new AbortController().signal, state: {} }));
+ return { runs, dialogs, windowsBefore, windowsAfter: BrowserWindow.getAllWindows().map(w => w.id),
+ storesBefore, storesAfter: fs.readdirSync(os.tmpdir()).filter((name: string) => name.startsWith('orkas-preview-storage-')).sort() };
+ } finally { Object.assign(dialog, original); }
+ }, { config: path.resolve(__dirname, '../../src/main/features/config.ts'), tools: path.resolve(__dirname, '../../src/main/model/core-agent/local-tools.ts'), users: path.resolve(__dirname, '../../src/main/features/users.ts'), root: orkas.userWorkspaceRoot, entry });
+ await info.attach('preview-sdk-tool-journey', { contentType: 'application/json', body: JSON.stringify(result) });
+ for (const run of result.runs) {
+ expect(run.isError).not.toBe(true);
+ const evidence = JSON.parse(run.content);
+ expect(evidence.ok).toBe(true);
+ expect(evidence.sdk.calls).toEqual(expect.arrayContaining([
+ { method: 'host.getContext', code: 'OK' }, { method: 'storage.set', code: 'OK' },
+ { method: 'storage.remove', code: 'OK' }, { method: 'tools.list', code: 'OK' },
+ { method: 'files.pick', code: 'E_UNAVAILABLE' }, { method: 'files.saveAs', code: 'E_UNAVAILABLE' },
+ { method: 'ai.generate', code: 'E_UNAVAILABLE' }, { method: 'tools.call', code: 'E_UNAVAILABLE' },
+ ]));
+ }
+ expect(result.dialogs).toEqual([]);
+ expect(result.storesAfter).toEqual(result.storesBefore);
+ expect(result.windowsAfter).toEqual(result.windowsBefore);
+ expect(orkas.page.isClosed()).toBe(false);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('isolated origin denies forged messages, foreign data and revoked SDK calls',async({modelOrkas:orkas})=>{
+ const app:any=await seed(orkas,'sdk-security');const frame=await mount(orkas,app.id);
+ const before=orkas.modelRequests.length;
+ await frame.locator('body').evaluate(()=>parent.postMessage({__orkasArtifact:true,type:'submit',payload:'Unapproved task'},'*'));
+ const origin=await frame.locator('body').evaluate(()=>location.origin);
+ expect(origin).toMatch(/^chat-app:\/\/app-[a-f0-9]{32}$/);
+ expect(await frame.locator('body').evaluate(async()=>{try{await (window as any).orkasApp.call('auth.getConfig',{});return 'wrong';}catch(e){return (e as any).code;}})).toBe('E_METHOD');
+ const other:any=await seed(orkas,'sdk-foreign');
+ const remote:any=await orkas.invoke('savedApps.openInApp',{appId:other.id});
+ expect(await frame.locator('body').evaluate(async(_node,url)=>{try{return await (await fetch(url)).text();}catch{return 'blocked';}},remote.url)).toBe('blocked');
+ await frame.owner().page().evaluate(()=>{
+ const frame=document.querySelector('.saved-app-viewer-frame') as HTMLIFrameElement;
+ window.dispatchEvent(new MessageEvent('message',{source:frame.contentWindow,origin:'chat-app://forged',data:{__orkasApp:1,type:'call',id:'forged',method:'storage.set',args:{key:'attacked',value:true}}}));
+ });
+ expect(await frame.locator('body').evaluate(()=>(window as any).orkasApp.storage.get({key:'attacked'}))).toEqual({value:null});
+ expect(await frame.locator('body').evaluate(()=>(window as any).orkasApp.permissions.revoke())).toEqual({revoked:true});
+ expect(await frame.locator('body').evaluate(async()=>{try{await (window as any).orkasApp.storage.keys();return 'wrong';}catch(e){return (e as any).code;}})).toBe('E_CLOSED');
+ expect(orkas.modelRequests.length).toBe(before);
+});
+
+test('local SDK chat artifacts submit results but external destinations cannot submit or call the SDK', async ({ modelOrkas: orkas }) => {
+ const artifact: any = await orkas.electronApp!.evaluate(async (_electron, args) => {
+ const { createArtifact } = (process as any).mainModule.require(args.artifacts);
+ const { getActiveUserId } = (process as any).mainModule.require(args.users);
+ return (await createArtifact(getActiveUserId(), 'sdk-chat-test', 'commander', { title: 'SDK chat', files: [
+ { path: 'index.html', content: args.html },
+ { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }) }
+ ] }));
+ }, { artifacts: path.resolve(__dirname, '../../src/main/features/chat_artifacts.ts'),
+ users: path.resolve(__dirname, '../../src/main/features/users.ts'), html });
+ expect(artifact.ok).toBe(true);
+ await orkas.page!.evaluate(id => {
+ const host = document.createElement('div'); host.id = 'sdk-artifact-test'; document.body.append(host);
+ (window as any).eval('currentCid = "sdk-chat-test"');
+ (window as any).artifactSubmissions = 0;
+ (window as any).sendInCurrentConversation = () => { (window as any).artifactSubmissions++; };
+ (window as any).renderChatArtifact(host, { cid: 'sdk-chat-test', artifactId: id, title: 'SDK chat', agentId: 'commander' });
+ }, artifact.artifactId);
+ const frame = orkas.page!.locator('#sdk-artifact-test iframe').contentFrame();
+ await expect(frame.locator('h1')).toHaveText('SDK App');
+ await frame.locator('body').evaluate(async () => {
+ parent.postMessage({ __orkasArtifact: true, type: 'submit', payload: 'Submitted local result' }, '*');
+ await (window as any).orkasApp.storage.set({ key: 'working', value: true });
+ });
+ await expect.poll(() => orkas.page!.evaluate(() => (window as any).artifactSubmissions)).toBe(1);
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'working' }))).toEqual({ value: true });
+ expect(orkas.modelRequests).toHaveLength(0);
+ const requests: string[] = [];
+ const server = createServer((request, response) => {
+ requests.push(request.url || '/');
+ response.setHeader('Content-Type', 'text/html');
+ response.end(`<!doctype html><h1>Remote destination</h1><script>
+ parent.postMessage({__orkasApp:1,type:'call',id:'remote-write',method:'storage.set',args:{key:'working',value:false}},'*');
+ parent.postMessage({__orkasArtifact:true,type:'submit',payload:'Unapproved remote task'},'*');
+ </script>`);
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const address = server.address() as AddressInfo;
+ const expectedRequests: string[] = [];
+ for (const method of ['redirect', 'link']) {
+ const url = `http://127.0.0.1:${address.port}/${method}`;
+ if (method === 'redirect') {
+ // A real document request, without a route override that could bypass
+ // Electron's owning navigation guard.
+ await frame.locator('body').evaluate((_node, url) => { location.replace(url); }, url);
+ } else {
+ await frame.locator('body').evaluate((_node, url) => {
+ const link = document.createElement('a'); link.href = url;
+ link.textContent = 'Open website'; link.target = '_self'; document.body.append(link);
+ }, url);
+ await frame.getByRole('link', { name: 'Open website' }).click();
+ }
+ await expect(frame.locator('h1')).toHaveText('Remote destination');
+ expect(await frame.locator('body').evaluate(() => ({ sdk: typeof (window as any).orkasApp,
+ ipc: typeof (window as any).orkas, node: typeof (window as any).require })))
+ .toEqual({ sdk: 'undefined', ipc: 'undefined', node: 'undefined' });
+ expectedRequests.push('/' + method);
+ expect(requests).toEqual(expectedRequests);
+ await orkas.page.evaluate(id => {
+ const host = document.getElementById('sdk-artifact-test')!;
+ host.replaceChildren();
+ (window as any).renderChatArtifact(host, { cid: 'sdk-chat-test', artifactId: id, title: 'SDK chat', agentId: 'commander' });
+ }, artifact.artifactId);
+ await expect(frame.locator('h1')).toHaveText('SDK App');
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'working' }))).toEqual({ value: true });
+ expect(await orkas.page.evaluate(() => (window as any).artifactSubmissions)).toBe(1);
+ }
+ } finally { await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())); }
+});
+
+for (const locale of [
+ { language: 'zh', save: '保存草稿', label: '要总结的文本', empty: '请先输入文本。', saved: '草稿已保存。', summarize: '总结' },
+ { language: 'ja', save: '下書きを保存', label: '要約するテキスト', empty: '先にテキストを入力してください。', saved: '下書きを保存しました。', summarize: '要約' },
+ { language: 'pt', save: 'Salvar rascunho', label: 'Texto para resumir', empty: 'Digite algum texto primeiro.', saved: 'Rascunho salvo.', summarize: 'Resumir' },
+]) test(`starter uses ${locale.language} for visible controls, document language and recovery`, async ({ modelOrkas: orkas }, info) => {
+ await orkas.electronApp!.evaluate((_electron, args) => (process as any).mainModule.require(args.config).setLanguage(args.language),
+ { config: path.resolve(__dirname, '../../src/main/features/config.ts'), language: locale.language });
+ const source = path.resolve(__dirname, '../../resources/builtin/system/skills/web-app-sdk/assets/starter');
+ const entry = orkas.createWorkspaceFile('localized/index.html', readFileSync(path.join(source, 'index.html'), 'utf8'));
+ orkas.createWorkspaceFile('localized/orkas-app.json', readFileSync(path.join(source, 'orkas-app.json'), 'utf8'));
+ const app: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, title: 'Localized notebook' });
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const preview = await orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ const frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(frame.locator('html')).toHaveAttribute('lang', locale.language);
+ await expect(frame.getByRole('note')).toBeVisible();
+ await preview.bringToFront();
+ await frame.locator('body').evaluate(() => {
+ (window as any).__localeInput = [];
+ for (const type of ['pointerdown', 'pointerup', 'click']) document.addEventListener(type, event => {
+ (window as any).__localeInput.push({ type, target: (event.target as HTMLElement).id, trusted: event.isTrusted, focused: document.hasFocus() });
+ }, true);
+ });
+ await frame.getByRole('button', { name: locale.summarize, exact: true }).click();
+ try { await expect(frame.getByRole('status')).toHaveText(locale.empty); }
+ finally {
+ const evidence = await frame.locator('body').evaluate(() => ({ events: (window as any).__localeInput, focused: document.hasFocus() }));
+ await info.attach('localized-input-evidence', { contentType: 'application/json', body: JSON.stringify(evidence) });
+ }
+ await frame.getByRole('textbox', { name: locale.label }).fill('跨设备 notebook');
+ await frame.getByRole('button', { name: locale.save, exact: true }).click();
+ await expect(frame.getByRole('status')).toHaveText(locale.saved);
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'draft', scope: 'cloud' }))).toEqual({ value: '跨设备 notebook' });
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'draft' }))).toEqual({ value: null });
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('a large source bundle opens, persists multi-megabyte data and accepts concurrent SDK calls', async ({ modelOrkas: orkas }, info) => {
+ for (let i = 0; i < 320; i++) orkas.createWorkspaceFile(`sdk-growing/assets/data${i}.json`, JSON.stringify({ index: i }));
+ const app: any = await seed(orkas, 'sdk-growing');
+ expect(app).toMatchObject({ ok: true, fileCount: 322 });
+ const frame = await mount(orkas, app.id);
+ const source = orkas.createWorkspaceFile('large-selected.txt', 'selected:α\n'.repeat(200000));
+ await orkas.selectFilesOnNextDialog([source]);
+ const imported = await frame.locator('body').evaluate(async () => {
+ const api = (window as any).orkasApp;
+ const file = await api.files.pick();
+ const value = await api.files.readText({ handle: file.handle });
+ await api.files.release({ handle: file.handle });
+ return { size: file.size, valid: value.text === 'selected:α\n'.repeat(200000) };
+ });
+ expect(imported).toEqual({ size: Buffer.byteLength('selected:α\n'.repeat(200000)), valid: true });
+ const result = await frame.locator('body').evaluate(async () => {
+ const api = (window as any).orkasApp;
+ const start = performance.now();
+ const data = 'abcdefgh'.repeat(256 * 1024); // 2 MiB in each file.
+ await Promise.all(Array.from({ length: 12 }, (_, i) => api.appFiles.writeText({ path: `data/${i}.txt`, text: data })));
+ await api.storage.set({ key: 'large', value: data });
+ const values = await Promise.all(Array.from({ length: 12 }, (_, i) => api.appFiles.readText({ path: `data/${i}.txt` })));
+ const stored = await api.storage.get({ key: 'large' });
+ return { valid: values.every(value => value.text === data) && stored.value === data,
+ files: (await api.appFiles.list()).files.length, elapsedMs: Math.round(performance.now() - start) };
+ });
+ expect(result).toMatchObject({ valid: true, files: 12 });
+ writeFileSync(info.outputPath('quota-workload.json'), JSON.stringify({ bytesPerFile: 2 * 1024 * 1024,
+ totalFileBytes: 24 * 1024 * 1024, concurrentCalls: 12, elapsedMs: result.elapsedMs }));
+ await orkas.closePreview(frame.owner().page());
+ const reopened = await mount(orkas, app.id);
+ expect(await reopened.locator('body').evaluate(async () => {
+ const api = (window as any).orkasApp;
+ const data = 'abcdefgh'.repeat(256 * 1024);
+ return (await api.storage.get({ key: 'large' })).value === data &&
+ (await api.appFiles.readText({ path: 'data/11.txt' })).text === data;
+ })).toBe(true);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('embedded pages, forms, downloads, external links and workers keep the app usable', async ({modelOrkas:orkas}) => {
+ const submitted:string[]=[];
+ const server=createServer((req,res)=>{
+ if (req.url === '/redirect-download') { res.writeHead(302, { Location: '/attachment' }); res.end(); return; }
+ if (req.url === '/attachment') { res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename=server-report.txt' }); res.end('server report'); return; }
+ req.on('data',chunk=>submitted.push(String(chunk)));
+ res.setHeader('Content-Type','text/html');res.end('<h1>'+ (req.url==='/submit'?'Submitted':'Embedded') +'</h1>');
+ });
+ await new Promise<void>(resolve=>server.listen(0,'127.0.0.1',resolve));
+ try {
+ const base=`http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ await orkas.electronApp!.evaluate(({shell,session})=>{
+ (globalThis as any).__browserActions={links:[],downloads:[]};
+ shell.openExternal=async url=>{(globalThis as any).__browserActions.links.push(url);};
+ session.defaultSession.on('will-download',(event,item)=>{event.preventDefault();(globalThis as any).__browserActions.downloads.push(item.getFilename());});
+ });
+ const app:any=await seed(orkas,'browser-actions',html.replace('</body>',`
+ <iframe name="content" src="${base}/view"></iframe>
+ <form action="${base}/submit" method="post" target="content"><input name="value" value="accepted"><button>Submit form</button></form>
+ <a href="${base}/popup" target="_blank">Open external</a>
+ <button id="download" onclick="const a=document.createElement('a');a.href=window.URL.createObjectURL(new Blob(['report']));a.download='report.txt';a.click()">Download</button>
+ <a href="${base}/attachment">Server download</a><a href="${base}/redirect-download">Redirected download</a>
+ <output id="worker"></output><script>
+ const url=URL.createObjectURL(new Blob(['postMessage(42)'],{type:'text/javascript'}));
+ const worker=new Worker(url);worker.onmessage=e=>{document.querySelector('#worker').textContent=e.data;worker.terminate();URL.revokeObjectURL(url)};
+ </script></body>`));
+ const frame=await mount(orkas,app.id);
+ await expect(frame.locator('#worker')).toHaveText('42');
+ await expect(frame.locator('iframe').contentFrame().getByRole('heading')).toHaveText('Embedded');
+ expect(await frame.locator('body').evaluate(()=>(window as any).orkasApp.storage.keys())).toEqual({keys:[]});
+ await frame.getByRole('button',{name:'Submit form'}).click();
+ await expect(frame.locator('iframe').contentFrame().getByRole('heading')).toHaveText('Submitted');
+ expect(submitted.join('')).toBe('value=accepted');
+ await frame.getByRole('link',{name:'Open external'}).click();
+ await frame.getByRole('button',{name:'Download',exact:true}).click();
+ await expect.poll(()=>orkas.electronApp!.evaluate(()=>(globalThis as any).__browserActions)).toEqual({links:[base+'/popup'],downloads:['report.txt']});
+ expect(await frame.locator('body').evaluate(()=>(window as any).orkasApp.storage.keys())).toEqual({keys:[]});
+ for (const [index, name] of ['Server download', 'Redirected download'].entries()) {
+ await frame.getByRole('link', { name, exact: true }).click();
+ await expect.poll(() => orkas.electronApp!.evaluate(() => (globalThis as any).__browserActions.downloads.length)).toBe(index + 2);
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.keys())).toEqual({ keys: [] });
+ }
+ expect(orkas.modelRequests).toHaveLength(0);
+ }finally{server.closeAllConnections();await new Promise<void>(resolve=>server.close(()=>resolve()));}
+});
+
+test('new ordinary apps isolate browser data across objects and accounts while reopen and legacy data survive', async ({ modelOrkas: orkas }) => {
+ const entry = orkas.createWorkspaceFile('browser-data/index.html', '<!doctype html><h1>Browser data</h1><script src="__orkas/bridge.js"></script>');
+ const saved: any[] = [];
+ for (const title of ['First', 'Second', 'Legacy']) {
+ const app: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, title });
+ expect(app.ok).toBe(true); saved.push(app);
+ }
+ const oldMeta = path.join(orkas.workspaceRoot, 'account-e2e/cloud/saved_apps', saved[2].id, '__orkas-meta.json');
+ const metadata = JSON.parse(readFileSync(oldMeta, 'utf8')); delete metadata.browserStorage;
+ writeFileSync(oldMeta, JSON.stringify(metadata));
+ const open = async (source: any, id = 'browser-probe') => {
+ const result = await orkas.page.evaluate(async ({ source, id }) => {
+ document.getElementById(id)?.remove();
+ const frame = document.createElement('iframe'); frame.id = id;
+ frame.setAttribute('sandbox', (window as any).OrkasArtifactSecurity.SANDBOX);
+ document.body.append(frame);
+ await (window as any).OrkasWebAppHost.open(frame, source);
+ return { url: frame.src, sdk: (window as any).OrkasWebAppHost.isManaged(frame) };
+ }, { source, id });
+ expect(result.sdk).toBe(false);
+ const body = orkas.page.locator('#' + id).contentFrame().locator('body');
+ await expect(body).toContainText('Browser data');
+ return { ...result, body };
+ };
+ const data = (body: any, value?: string): Promise<{ local: string | null; indexed: string | null }> => body.evaluate(async (_node: unknown, value: string | undefined) => {
+ const db = await new Promise<IDBDatabase>((resolve, reject) => {
+ const request = indexedDB.open('drafts', 1);
+ request.onupgradeneeded = () => request.result.createObjectStore('values');
+ request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error);
+ });
+ try {
+ if (value !== undefined) {
+ localStorage.setItem('draft', value);
+ await new Promise<void>((resolve, reject) => {
+ const tx = db.transaction('values', 'readwrite'); tx.objectStore('values').put(value, 'draft');
+ tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error);
+ });
+ }
+ const indexed = await new Promise<string | null>((resolve, reject) => {
+ const request = db.transaction('values').objectStore('values').get('draft');
+ request.onsuccess = () => resolve(request.result ?? null); request.onerror = () => reject(request.error);
+ });
+ return { local: localStorage.getItem('draft'), indexed };
+ } finally { db.close(); }
+ }, value);
+ const first = await open({ appId: saved[0].id });
+ expect(first.url).toMatch(/^chat-app:\/\/a-[a-f0-9]{20}\/index.html$/);
+ expect(await data(first.body, 'First private draft')).toEqual({ local: 'First private draft', indexed: 'First private draft' });
+ const second = await open({ appId: saved[1].id }, 'browser-second');
+ expect(second.url).not.toBe(first.url);
+ expect(await data(second.body)).toEqual({ local: null, indexed: null });
+ expect(await second.body.evaluate(async (_node, url) => { try { await fetch(url); return true; } catch { return false; } }, first.url)).toBe(false);
+ // Ordinary bridge messages remain trusted, but no SDK adapter is installed.
+ await orkas.page.evaluate(() => {
+ (window as any).ordinaryBridgeEvidence = [];
+ window.addEventListener('message', event => {
+ const frame = document.getElementById('browser-probe');
+ if (event.data?.type === 'submit' && (window as any).OrkasArtifactSecurity.trustedArtifactMessage(event, frame))
+ (window as any).ordinaryBridgeEvidence.push(event.data.payload);
+ });
+ });
+ await first.body.evaluate(() => (window as any).orkasArtifact.send({ draft: 'Bridge retained' }));
+ await expect.poll(() => orkas.page.evaluate(() => (window as any).ordinaryBridgeEvidence)).toEqual([{ draft: 'Bridge retained' }]);
+ // Same-task artifacts must not share their storage or an old cid route.
+ const artifacts: any[] = [];
+ for (let i = 0; i < 2; i++) {
+ const artifact = await orkas.electronApp!.evaluate(async (_electron, modulePath) =>
+ (process as any).mainModule.require(modulePath).createArtifact('account-e2e', 'browser-task', 'commander', {
+ files: [{ path: 'index.html', content: '<!doctype html><h1>Browser data</h1>' }],
+ }), path.resolve(__dirname, '../../src/main/features/chat_artifacts.ts'));
+ expect(artifact.ok).toBe(true); artifacts.push(artifact);
+ }
+ const artifactOne = await open({ cid: 'browser-task', artifactId: artifacts[0].artifactId }, 'artifact-one');
+ await data(artifactOne.body, 'Artifact draft');
+ const artifactTwo = await open({ cid: 'browser-task', artifactId: artifacts[1].artifactId }, 'artifact-two');
+ expect(await data(artifactTwo.body)).toEqual({ local: null, indexed: null });
+ expect(await orkas.electronApp!.evaluate(async ({ net }, url) => (await net.fetch(url)).status,
+ `chat-app://cid/browser-task/${artifacts[0].artifactId}/index.html`)).toBe(403);
+ const alias = `chat-app://saved/${saved[0].id}/index.html`;
+ expect(await orkas.electronApp!.evaluate(async ({ net }, url) => (await net.fetch(url)).status, alias)).toBe(403);
+ const legacy = await open({ appId: saved[2].id }, 'browser-legacy');
+ expect(legacy.url).toBe(`chat-app://saved/${saved[2].id}/index.html`);
+ await data(legacy.body, 'Legacy retained');
+ const reopened = await open({ appId: saved[0].id });
+ expect(reopened.url).toBe(first.url);
+ expect(await data(reopened.body)).toEqual({ local: 'First private draft', indexed: 'First private draft' });
+
+ // Same source identifiers in another account must not reuse the first account's origin.
+ const otherRoot = path.join(orkas.workspaceRoot, 'browser-other/cloud/saved_apps');
+ mkdirSync(otherRoot, { recursive: true });
+ cpSync(path.join(orkas.workspaceRoot, 'account-e2e/cloud/saved_apps', saved[0].id), path.join(otherRoot, saved[0].id), { recursive: true });
+ await orkas.switchLocalUser('browser-other', { nickname: 'Other', email: '[email protected]' });
+ const other = await open({ appId: saved[0].id });
+ expect(other.url).not.toBe(first.url);
+ expect(await data(other.body)).toEqual({ local: null, indexed: null });
+ await orkas.switchLocalUser('account-e2e', { nickname: 'Original', email: '[email protected]' });
+ const restarted = await open({ appId: saved[0].id });
+ expect(restarted.url).toBe(first.url);
+ expect(await data(restarted.body)).toEqual({ local: 'First private draft', indexed: 'First private draft' });
+ expect(await data((await open({ appId: saved[2].id }, 'browser-legacy')).body)).toEqual({ local: 'Legacy retained', indexed: 'Legacy retained' });
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+
+test('local SDK form results reach their original conversation from the card and detached preview', async ({ modelOrkas: orkas }) => {
+ const created: any = await orkas.invoke('conversations.create', { title: 'SDK form task' });
+ const other: any = await orkas.invoke('conversations.create', { title: 'Unrelated task' });
+ const cid = created.conversation.conversation_id, otherCid = other.conversation.conversation_id;
+ const artifact = await orkas.electronApp!.evaluate(async (_electron, args) =>
+ (process as any).mainModule.require(args.module).createArtifact('account-e2e', args.cid, 'commander', {
+ title: 'Travel form', files: [
+ { path: 'index.html', content: '<!doctype html><script src="/__orkas/sdk.js"></script><h1>Travel form</h1><button id="submit">Send preferences</button><script>document.querySelector("button").onclick=async()=>{await orkasApp.storage.set({key:"city",value:"Kyoto"});orkasArtifact.send({city:"Kyoto",budget:1200});};</script>' },
+ { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }) },
+ ],
+ }), { module: path.resolve(__dirname, '../../src/main/features/chat_artifacts.ts'), cid });
+ expect(artifact.ok).toBe(true);
+ const transcript = path.join(orkas.workspaceRoot, 'account-e2e/cloud/chats', cid + '.jsonl');
+ const foreignTranscript = path.join(orkas.workspaceRoot, 'account-e2e/cloud/chats', otherCid + '.jsonl');
+ appendFileSync(transcript, JSON.stringify({ id: 'sdk-form-fixture', ts: new Date().toISOString(), from: 'commander', to: ['user'],
+ text: 'Fill in your preferences.', artifacts: [{ id: artifact.artifactId, title: 'Travel form', agent_id: 'commander' }] }) + '\n');
+ const results = (file: string) => readFileSync(file, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line))
+ .filter(message => message.from === 'user' && String(message.text).includes('<artifact-result'));
+ await orkas.page.evaluate(async cid => { await (window as any).loadConversations(); await (window as any).setView('conversation', cid); }, cid);
+ const card = orkas.page.locator('#chat-history .chat-artifact-card');
+ await card.locator('iframe').contentFrame().getByRole('button', { name: 'Send preferences' }).click();
+ await expect.poll(() => results(transcript).length).toBe(1);
+ expect(results(transcript)[0].text).toContain('"city":"Kyoto"');
+ await expect.poll(() => orkas.modelRequests.length).toBe(1);
+ await expect(orkas.page.locator('#chat-history')).toContainText('Hello from the local E2E model.');
+ await expect(orkas.page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);
+ const preview = await orkas.openPreview(() => orkas.page.evaluate(source =>
+ (window as any).OrkasPreviewWindows.open(source), { kind: 'artifact', cid, artifactId: artifact.artifactId, agentId: 'commander', title: 'Travel form' }));
+ await orkas.page.evaluate(cid => (window as any).setView('conversation', cid), otherCid);
+ await preview.locator('iframe.chat-artifact-frame').contentFrame().getByRole('button', { name: 'Send preferences' }).click();
+ await expect.poll(() => results(transcript).length).toBe(2);
+ expect(results(foreignTranscript)).toEqual([]);
+ await expect.poll(() => orkas.modelRequests.length).toBe(2);
+ expect(results(transcript)[1].text).toContain('"budget":1200');
+});
+
+
+test('historical web artifacts cannot submit conversation tasks with a forged local display type', async ({ modelOrkas: orkas }) => {
+ const task = await orkas.invoke<any>('conversations.create', { title: 'Historical web output' });
+ const cid = task.conversation.conversation_id, artifactId = 'web-submit-test';
+ const dir = path.join(orkas.workspaceRoot, 'account-e2e/cloud/chat_artifacts', cid, artifactId);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, 'index.html'), '<h1>Never execute historical web output</h1>');
+ writeFileSync(path.join(dir, '__orkas-meta.json'), JSON.stringify({ appType: 'web', title: 'Web output', entry: 'index.html' }));
+ await orkas.page.evaluate(({ cid, artifactId }) => {
+ const host = document.createElement('div'); host.id = 'web-submit-test'; document.body.append(host);
+ (window as any).unexpectedSubmissions = 0;
+ (window as any).sendInCurrentConversation = () => { (window as any).unexpectedSubmissions++; };
+ (window as any).renderChatArtifact(host, { cid, artifactId, agentId: 'commander' });
+ }, { cid, artifactId });
+ await expect(orkas.page.locator('#web-submit-test')).toContainText('commercial version');
+ const iframe = orkas.page.locator('#web-submit-test iframe');
+ await expect(iframe).not.toHaveAttribute('src');
+ await iframe.evaluate(node => { (node as HTMLElement).dataset.appType = 'local'; });
+ expect(await iframe.evaluate(node => (window as any).OrkasWebAppHost.canSubmitArtifact(node))).toBe(false);
+ expect(await orkas.invoke('webApps.open', { source: { cid, artifactId } })).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED' });
+ expect(await orkas.page.evaluate(() => (window as any).unexpectedSubmissions)).toBe(0);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
diff --git a/test/fixtures/app-data-v1.json b/test/fixtures/app-data-v1.json
new file mode 100644
index 00000000..c2436549
--- /dev/null
+++ b/test/fixtures/app-data-v1.json
@@ -0,0 +1,1459 @@
+{
+ "definition": {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ }
+ }
+ ]
+ },
+ "inserts": [
+ {
+ "title": "é",
+ "count": 2.0,
+ "enabled": true,
+ "object": {
+ "z": 1,
+ "a": "中"
+ },
+ "time": "2026-10-12T00:00:00.001Z"
+ },
+ {
+ "title": null
+ },
+ {
+ "title": "Z",
+ "count": 3
+ }
+ ],
+ "queries": [
+ {
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "title",
+ "direction": "asc"
+ }
+ },
+ "expected": {
+ "records": [
+ {
+ "title": null
+ },
+ {
+ "title": "Z"
+ },
+ {
+ "title": "é"
+ }
+ ]
+ }
+ },
+ {
+ "args": {
+ "table": "items",
+ "fields": [
+ "title",
+ "enabled"
+ ],
+ "filters": [
+ {
+ "field": "title",
+ "op": "eq",
+ "value": null
+ }
+ ]
+ },
+ "expected": {
+ "records": [
+ {
+ "title": null,
+ "enabled": false
+ }
+ ]
+ }
+ },
+ {
+ "args": {
+ "table": "items",
+ "fields": [
+ "time"
+ ],
+ "limit": 1,
+ "order": {
+ "field": "time",
+ "direction": "asc"
+ }
+ },
+ "expected": {
+ "records": [
+ {
+ "time": "2026-10-12T00:00:00.000Z"
+ }
+ ]
+ }
+ },
+ {
+ "args": {
+ "table": "items",
+ "fields": [
+ "time"
+ ],
+ "order": {
+ "field": "time",
+ "direction": "asc"
+ }
+ },
+ "expected": {
+ "records": [
+ {
+ "time": "2026-10-12T00:00:00.000Z"
+ },
+ {
+ "time": "2026-10-12T00:00:00.000Z"
+ },
+ {
+ "time": "2026-10-12T00:00:00.001Z"
+ }
+ ]
+ }
+ }
+ ],
+ "aggregates": [
+ {
+ "args": {
+ "table": "items",
+ "field": "count",
+ "op": "sum"
+ },
+ "expected": {
+ "value": 5
+ }
+ }
+ ],
+ "rejections": [
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "count": 2.5
+ }
+ }
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "private"
+ ]
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "enabled": 1
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "object": "{}"
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "title": "Z"
+ }
+ },
+ "code": "E_CONFLICT"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "time": "tomorrow"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "time": "2026-02-30T00:00:00Z"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "time": "2026-10-12T00:00:00+08:00"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "filters": [
+ {
+ "field": "count",
+ "op": "gt",
+ "value": 9007199254740992
+ }
+ ]
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "items",
+ "values": {
+ "time": "0000-01-01T00:00:00Z"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "createdAt",
+ "direction": "desc"
+ }
+ },
+ "code": "E_PERMISSION"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "private",
+ "direction": "desc"
+ }
+ },
+ "code": "E_PERMISSION"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": [
+ "title"
+ ],
+ "direction": "asc"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "title",
+ "direction": "sideways"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "title",
+ "direction": "asc",
+ "sql": "SELECT *"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "",
+ "direction": "asc"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "body; SELECT *",
+ "direction": "asc"
+ }
+ },
+ "code": "E_INPUT"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "items",
+ "fields": [
+ "title"
+ ],
+ "order": {
+ "field": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "direction": "asc"
+ }
+ },
+ "code": "E_INPUT"
+ }
+ ],
+ "invalidDefinitions": [
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": "wrong type"
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "relations",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "version": true,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": [],
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ],
+ "readFilters": [
+ {
+ "field": "title",
+ "op": {},
+ "value": "x"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ },
+ "indexes": [
+ [
+ []
+ ]
+ ]
+ }
+ ]
+ },
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true,
+ "references": {
+ "table": []
+ }
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "__proto__",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "2026-10-12T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "__proto__"
+ ],
+ "insert": [
+ "__proto__"
+ ],
+ "count": true
+ }
+ }
+ ]
+ },
+ {
+ "version": 1,
+ "tables": [
+ {
+ "id": "items",
+ "name": "items",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string",
+ "nullable": true,
+ "unique": true
+ },
+ {
+ "id": "count",
+ "name": "count",
+ "type": "integer",
+ "default": 0
+ },
+ {
+ "id": "enabled",
+ "name": "enabled",
+ "type": "boolean",
+ "default": false
+ },
+ {
+ "id": "object",
+ "name": "object",
+ "type": "json",
+ "default": {}
+ },
+ {
+ "id": "time",
+ "name": "time",
+ "type": "timestamp",
+ "default": "0000-01-01T00:00:00Z"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "insert": [
+ "title",
+ "count",
+ "enabled",
+ "object",
+ "time"
+ ],
+ "count": true,
+ "aggregate": [
+ "count"
+ ]
+ }
+ }
+ ]
+ }
+ ],
+ "scenarios": {
+ "definition": {
+ "version": 1,
+ "tables": [
+ {
+ "id": "authors",
+ "name": "authors",
+ "fields": [
+ {
+ "id": "name",
+ "name": "name",
+ "type": "string"
+ },
+ {
+ "id": "hidden",
+ "name": "hidden",
+ "type": "boolean",
+ "default": false
+ }
+ ],
+ "access": {
+ "read": [
+ "name"
+ ],
+ "insert": [
+ "name",
+ "hidden"
+ ],
+ "readFilters": [
+ {
+ "field": "hidden",
+ "op": "eq",
+ "value": false
+ }
+ ]
+ }
+ },
+ {
+ "id": "posts",
+ "name": "posts",
+ "fields": [
+ {
+ "id": "title",
+ "name": "title",
+ "type": "string"
+ },
+ {
+ "id": "rank",
+ "name": "rank",
+ "type": "integer"
+ },
+ {
+ "id": "author",
+ "name": "author",
+ "type": "string",
+ "nullable": true,
+ "references": {
+ "table": "authors"
+ }
+ },
+ {
+ "id": "state",
+ "name": "state",
+ "type": "string",
+ "default": "public"
+ }
+ ],
+ "access": {
+ "read": [
+ "title",
+ "rank",
+ "author"
+ ],
+ "insert": [
+ "title",
+ "rank",
+ "author",
+ "state"
+ ],
+ "count": true,
+ "readFilters": [
+ {
+ "field": "state",
+ "op": "eq",
+ "value": "public"
+ }
+ ]
+ }
+ },
+ {
+ "id": "seats",
+ "name": "seats",
+ "fields": [
+ {
+ "id": "name",
+ "name": "name",
+ "type": "string"
+ }
+ ],
+ "access": {
+ "read": [
+ "name"
+ ],
+ "insert": [
+ "name"
+ ],
+ "count": true,
+ "maxCount": 2
+ }
+ }
+ ]
+ },
+ "steps": [
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "authors",
+ "values": {
+ "name": "Ann"
+ }
+ },
+ "save": "ann"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "authors",
+ "values": {
+ "name": "Ghost",
+ "hidden": true
+ }
+ },
+ "save": "ghost"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "posts",
+ "values": {
+ "title": "A",
+ "rank": 1,
+ "author": {
+ "$ref": "ann"
+ }
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "posts",
+ "values": {
+ "title": "B",
+ "rank": 2,
+ "author": {
+ "$ref": "ghost"
+ }
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "posts",
+ "values": {
+ "title": "C",
+ "rank": 2,
+ "author": null
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "posts",
+ "values": {
+ "title": "D",
+ "rank": 2
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "posts",
+ "values": {
+ "title": "E",
+ "rank": 1,
+ "state": "draft"
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "posts",
+ "values": {
+ "title": "F",
+ "rank": 1
+ }
+ }
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "posts",
+ "values": {
+ "title": "G",
+ "rank": 1,
+ "author": "00000000000000000000000000000000"
+ }
+ },
+ "code": "E_RELATION"
+ },
+ {
+ "method": "data.count",
+ "args": {
+ "table": "posts"
+ },
+ "expected": {
+ "count": 5
+ }
+ },
+ {
+ "method": "data.count",
+ "args": {
+ "table": "posts",
+ "filters": [
+ {
+ "field": "rank",
+ "op": "eq",
+ "value": 1
+ }
+ ]
+ },
+ "expected": {
+ "count": 2
+ }
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "posts",
+ "fields": [
+ "title"
+ ],
+ "filters": [
+ {
+ "field": "title",
+ "op": "eq",
+ "value": "E"
+ }
+ ]
+ },
+ "expected": {
+ "records": []
+ }
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "posts",
+ "fields": [
+ "title"
+ ],
+ "include": [
+ "author"
+ ],
+ "order": {
+ "field": "title",
+ "direction": "asc"
+ }
+ },
+ "expected": {
+ "records": [
+ {
+ "title": "A",
+ "relations": {
+ "author": {
+ "name": "Ann"
+ }
+ }
+ },
+ {
+ "title": "B",
+ "relations": {
+ "author": null
+ }
+ },
+ {
+ "title": "C",
+ "relations": {
+ "author": null
+ }
+ },
+ {
+ "title": "D",
+ "relations": {
+ "author": null
+ }
+ },
+ {
+ "title": "F",
+ "relations": {
+ "author": null
+ }
+ }
+ ]
+ }
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "authors",
+ "fields": [
+ "name"
+ ]
+ },
+ "expected": {
+ "records": [
+ {
+ "name": "Ann"
+ }
+ ]
+ }
+ },
+ {
+ "paginate": {
+ "table": "posts",
+ "fields": [
+ "title",
+ "rank"
+ ],
+ "order": {
+ "field": "rank",
+ "direction": "asc"
+ }
+ },
+ "pageSize": 2,
+ "expectedRanks": [
+ 1,
+ 1,
+ 2,
+ 2,
+ 2
+ ],
+ "expectedTitles": [
+ "A",
+ "B",
+ "C",
+ "D",
+ "F"
+ ]
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "x"
+ },
+ "requestId": "seat-1"
+ },
+ "save": "seat"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "x"
+ },
+ "requestId": "seat-1"
+ },
+ "sameIdAs": "seat"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "changed"
+ },
+ "requestId": "seat-1"
+ },
+ "code": "E_CONFLICT"
+ },
+ {
+ "method": "data.count",
+ "args": {
+ "table": "seats"
+ },
+ "expected": {
+ "count": 1
+ }
+ },
+ {
+ "reopen": true
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "x"
+ },
+ "requestId": "seat-1"
+ },
+ "sameIdAs": "seat"
+ },
+ {
+ "method": "data.insertIf",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "tight"
+ },
+ "maxCount": 1
+ },
+ "code": "E_CONDITION"
+ },
+ {
+ "method": "data.insertIf",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "z"
+ },
+ "maxCount": 5,
+ "requestId": "seat-2"
+ },
+ "save": "last"
+ },
+ {
+ "method": "data.insertIf",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "w"
+ },
+ "maxCount": 5
+ },
+ "code": "E_CONDITION"
+ },
+ {
+ "method": "data.insert",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "w"
+ }
+ },
+ "code": "E_CONDITION"
+ },
+ {
+ "method": "data.insertIf",
+ "args": {
+ "table": "seats",
+ "values": {
+ "name": "z"
+ },
+ "maxCount": 5,
+ "requestId": "seat-2"
+ },
+ "sameIdAs": "last"
+ },
+ {
+ "method": "data.query",
+ "args": {
+ "table": "seats",
+ "order": {
+ "field": "name",
+ "direction": "asc"
+ }
+ },
+ "expected": {
+ "records": [
+ {
+ "name": "x"
+ },
+ {
+ "name": "z"
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/test/main/features/app-data-local.test.ts b/test/main/features/app-data-local.test.ts
new file mode 100644
index 00000000..e0d4982b
--- /dev/null
+++ b/test/main/features/app-data-local.test.ts
@@ -0,0 +1,119 @@
+/** Shared local data migration and packaged-worker compatibility. */
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import {afterEach,beforeEach,it,expect,vi} from 'vitest';
+let root:string,previous:string|undefined;
+beforeEach(()=>{root=fs.mkdtempSync(path.join(os.tmpdir(),'orkas-data-snapshot-'));previous=process.env.ORKAS_WORKSPACE_ROOT;process.env.ORKAS_WORKSPACE_ROOT=root;vi.resetModules();});
+afterEach(()=>{if(previous===undefined)delete process.env.ORKAS_WORKSPACE_ROOT;else process.env.ORKAS_WORKSPACE_ROOT=previous;fs.rmSync(root,{recursive:true,force:true});});
+const definition:any={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body'],count:true}}]};
+
+it.each(['id','createdAt'])('aggregates declared plain-text %s values without parsing them as JSON',async field=>{
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');
+ const schema=structuredClone(definition);
+ schema.tables[0].access.read=['body','id','createdAt'];
+ schema.tables[0].access.aggregate=[field];
+ const db=new LocalAppData(path.join(root,'system-fields.sqlite'),root,schema);
+ try{
+ for(const body of ['A','B','A'])await db.call('data.insert',{table:'notes',values:{body}});
+ const {records}:any=await db.call('data.query',{table:'notes'});
+ expect(records).toHaveLength(3);
+ for(const op of ['min','max']){
+ const pick=(rows:any[])=>rows.map(row=>row[field]).sort()[op==='min'?0:rows.length-1];
+ expect(await db.call('data.aggregate',{table:'notes',field,op})).toEqual({value:pick(records)});
+ expect(await db.call('data.aggregate',{table:'notes',field,op,groupBy:'body'})).toEqual({groups:
+ ['A','B'].map(key=>({key,value:pick(records.filter((row:any)=>row.body===key))}))});
+ }
+ expect(await db.call('data.aggregate',{table:'notes',field,op:'min',filters:[{field:'body',op:'eq',value:'missing'}]})).toEqual({value:null});
+ await expect(db.call('data.aggregate',{table:'notes',field:'body',op:'min'})).rejects.toMatchObject({code:'E_PERMISSION'});
+ expect(await db.call('data.count',{table:'notes'})).toEqual({count:3});
+ }finally{await db.close();}
+});
+
+it('resolves unpacked worker code on both packaged desktop layouts without rewriting ordinary directories',async()=>{
+ const {dataWorkerPath}=await import('../../../src/main/features/web_apps/data');
+ expect(dataWorkerPath('/Applications/Orkas.app/Contents/Resources/app.asar/src').replaceAll('\\','/')).toBe('/Applications/Orkas.app/Contents/Resources/app.asar.unpacked/src/main/features/web_apps/data-worker.js');
+ expect(dataWorkerPath('C:\\Orkas\\resources\\app.asar\\src').replaceAll('\\','/')).toBe('C:/Orkas/resources/app.asar.unpacked/src/main/features/web_apps/data-worker.js');
+ expect(dataWorkerPath('/tmp/app.asar-source/src').replaceAll('\\','/')).toBe('/tmp/app.asar-source/src/main/features/web_apps/data-worker.js');
+ const pkg=JSON.parse(fs.readFileSync(path.resolve('package.json'),'utf8'));expect(pkg.build.asarUnpack).toContain('src/main/features/web_apps/data-worker.js');
+});
+it('keeps the previous app usable after a compatible migration when the frontend swap fails',async()=>{
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');const file=path.join(root,'u/local/rollback/data.sqlite');
+ const original=new LocalAppData(file,root,definition);await original.call('data.insert',{table:'notes',values:{body:'retained'}});await original.close();
+ const updated=structuredClone(definition);Object.assign(updated.tables[0].fields[0],{required:false,nullable:false,unique:false});updated.tables[0].fields.push({id:'tag',name:'tag',type:'string',default:'new'});
+ const migration=new LocalAppData(file,root,updated);await migration.call('internal.check',{});await migration.close();
+ const previous=new LocalAppData(file,root,definition);try{expect(await previous.call('data.query',{table:'notes'})).toEqual({records:[{body:'retained'}]});await previous.call('data.insert',{table:'notes',values:{body:'after failure'}});}finally{await previous.close();}
+ updated.tables[0].access.read.push('tag');const retry=new LocalAppData(file,root,updated);try{expect(await retry.call('data.query',{table:'notes'})).toMatchObject({records:expect.arrayContaining([{body:'retained',tag:'new'},{body:'after failure',tag:'new'}])});}finally{await retry.close();}
+});
+it('rejects a destructive explicit migration even when an older app can still read the data',async()=>{
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');const file=path.join(root,'u/local/strict/data.sqlite');const db=new LocalAppData(file,root,definition);await db.call('data.insert',{table:'notes',values:{body:'protected'}});await db.close();
+ const incompatible=new LocalAppData(file,root,{version:1,tables:[]},200*1024*1024,true);try{await expect(incompatible.call('internal.check',{})).rejects.toMatchObject({code:'E_MIGRATION'});}finally{await incompatible.close();}
+});
+
+it('rejects an added reference default that would orphan existing records',async()=>{
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');const file=path.join(root,'u/local/references/data.sqlite'),original=new LocalAppData(file,root,definition);await original.call('data.insert',{table:'notes',values:{body:'KEEP'}});await original.close();const next=structuredClone(definition);next.tables[0].fields.push({id:'parent',name:'parent',type:'string',default:'missing',references:{table:'parents'}});next.tables.push({id:'parents',name:'parents',fields:[{id:'label',name:'label',type:'string'}],access:{read:['label'],insert:['label']}});const migration=new LocalAppData(file,root,next,200*1024*1024,true);try{await expect(migration.call('internal.check',{})).rejects.toMatchObject({code:'E_MIGRATION'});}finally{await migration.close();}const old=new LocalAppData(file,root,definition);try{await old.call('data.insert',{table:'notes',values:{body:'old writer works'}});expect(await old.call('data.count',{table:'notes'})).toEqual({count:2});}finally{await old.close();}
+});
+
+const collidingDefinition:any={version:1,tables:[['ab','c'],['a','bc']].map(([id,field],n)=>({id,name:'table'+n,fields:[{id:field,name:'value',type:'string',unique:true}],access:{read:['value'],insert:['value'],count:true}}))};
+
+it('enforces unique values separately for table and field identities with the same concatenation',async()=>{
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');
+ const database=new LocalAppData(path.join(root,'fresh.sqlite'),root,collidingDefinition);
+ try{for(const table of collidingDefinition.tables){await database.call('data.insert',{table:table.name,values:{value:'one'}});await expect(database.call('data.insert',{table:table.name,values:{value:'one'}})).rejects.toMatchObject({code:'E_CONFLICT'});expect(await database.call('data.count',{table:table.name})).toEqual({count:1});}}finally{await database.close();}
+});
+
+async function legacyDatabase(file:string,duplicate=false){
+ const {createHash}=await import('node:crypto');const Database=(await import('better-sqlite3')).default;
+ const physical=(prefix:string,id:string)=>prefix+createHash('sha256').update(id).digest('hex').slice(0,24);
+ const db=new Database(file);db.exec('CREATE TABLE _meta(key TEXT PRIMARY KEY,value TEXT NOT NULL); CREATE TABLE _requests(id TEXT PRIMARY KEY,digest TEXT,response TEXT,created INTEGER)');
+ for(const [key,val] of [['definition',JSON.stringify(collidingDefinition)],['usage','2'],['revision','7']])db.prepare('INSERT INTO _meta VALUES(?,?)').run(key,val);
+ for(const [n,t] of collidingDefinition.tables.entries()){
+ const table=physical('t_',t.id),column=physical('c_',t.fields[0].id);
+ db.exec(`CREATE TABLE "${table}"(id TEXT PRIMARY KEY,createdAt TEXT NOT NULL,_bytes INTEGER NOT NULL,"${column}" TEXT); CREATE UNIQUE INDEX IF NOT EXISTS "${physical('u_',t.id+t.fields[0].id)}" ON "${table}"(json_extract("${column}",'$'))`);
+ db.prepare(`INSERT INTO "${table}" VALUES(?,?,?,?)`).run('original','2026-10-01T00:00:00.000Z',1,JSON.stringify('one'));
+ if(duplicate&&n===1)db.prepare(`INSERT INTO "${table}" VALUES(?,?,?,?)`).run('duplicate','2026-10-01T00:00:00.000Z',1,JSON.stringify('one'));
+ }db.close();return physical;
+}
+it('repairs legacy index collisions on an unchanged definition without changing records or revision',async()=>{
+ const file=path.join(root,'legacy.sqlite');await legacyDatabase(file);
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');const database=new LocalAppData(file,root,collidingDefinition);
+ try{for(const table of collidingDefinition.tables){expect(await database.call('data.query',{table:table.name})).toEqual({records:[{value:'one'}]});await expect(database.call('data.insert',{table:table.name,values:{value:'one'}})).rejects.toMatchObject({code:'E_CONFLICT'});}expect(await database.call('internal.version',{})).toEqual({revision:7});}finally{await database.close();}
+});
+it('refuses legacy duplicate repair atomically while retaining every record and schema',async()=>{
+ const file=path.join(root,'duplicates.sqlite'),physical=await legacyDatabase(file,true);
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');const database=new LocalAppData(file,root,collidingDefinition);
+ try{await expect(database.call('internal.check',{})).rejects.toMatchObject({code:'E_MIGRATION'});}finally{await database.close();}
+ const Database=(await import('better-sqlite3')).default,db=new Database(file);
+ try{expect(db.prepare(`SELECT COUNT(*) AS n FROM "${physical('t_','a')}"`).get()).toEqual({n:2});expect(JSON.parse(db.prepare("SELECT value FROM _meta WHERE key='definition'").get().value)).toEqual(collidingDefinition);}finally{db.close();}
+});
+
+it('refuses writes and migrations beyond the application byte limit without changing records, revision or schema',async()=>{
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');const file=path.join(root,'u/local/limited/data.sqlite');
+ // One record is about 100 canonical bytes ({id,createdAt,body}); 150 admits exactly one.
+ const db=new LocalAppData(file,root,definition,150);
+ try{
+ await db.call('data.insert',{table:'notes',values:{body:'0123456789'}});const before:any=await db.call('internal.version',{});
+ await expect(db.call('data.insert',{table:'notes',values:{body:'0123456789'}})).rejects.toMatchObject({code:'E_LIMIT'});
+ await expect(db.call('data.insertIf',{table:'notes',values:{body:'x'},maxCount:10})).rejects.toMatchObject({code:'E_LIMIT'});
+ expect(await db.call('data.count',{table:'notes'})).toEqual({count:1});expect(await db.call('internal.version',{})).toEqual(before);
+ }finally{await db.close();}
+ const grown=structuredClone(definition);grown.tables[0].fields.push({id:'tag',name:'tag',type:'string',default:'y'.repeat(60)});grown.tables[0].access.read.push('tag');
+ const migration=new LocalAppData(file,root,grown,150,true);
+ try{await expect(migration.call('internal.check',{})).rejects.toMatchObject({code:'E_LIMIT'});}finally{await migration.close();}
+ const Database=(await import('better-sqlite3')).default,raw=new Database(file,{readonly:true});
+ try{expect(JSON.parse(raw.prepare("SELECT value FROM _meta WHERE key='definition'").get().value)).toEqual(definition);}finally{raw.close();}
+ const reopened=new LocalAppData(file,root,definition,150);
+ try{expect(await reopened.call('data.query',{table:'notes'})).toEqual({records:[{body:'0123456789'}]});expect(await reopened.call('internal.version',{})).toEqual({revision:1});}finally{await reopened.close();}
+});
+
+it.each(['directory','database','hardlink'] as const)('rejects a %s link escaping the app data boundary as a file error without touching the target',async kind=>{
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');
+ const outside=path.join(root,'outside'),boundary=path.join(root,'app');fs.mkdirSync(outside);fs.mkdirSync(boundary);
+ const target=path.join(outside,'data.sqlite');fs.writeFileSync(target,'not a database');
+ let file=path.join(boundary,'data.sqlite');
+ if(kind==='directory'){fs.symlinkSync(outside,path.join(boundary,'linked'),'dir');file=path.join(boundary,'linked','data.sqlite');}
+ else if(kind==='database')fs.symlinkSync(target,file);else fs.linkSync(target,file);
+ const db=new LocalAppData(file,boundary,definition);
+ try{await expect(db.call('internal.check',{})).rejects.toMatchObject({code:'E_FILE'});}finally{await db.close();}
+ expect(fs.readFileSync(target,'utf8')).toBe('not a database');expect(fs.readdirSync(outside)).toEqual(['data.sqlite']);
+});
diff --git a/test/main/features/app-data-packaged.test.ts b/test/main/features/app-data-packaged.test.ts
new file mode 100644
index 00000000..87266dc0
--- /dev/null
+++ b/test/main/features/app-data-packaged.test.ts
@@ -0,0 +1,26 @@
+/** The unpacked application worker must retain its actual native dependency chain. */
+import {it,expect} from 'vitest';
+import {createRequire} from 'node:module';
+import {finished} from 'node:stream/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {spawnSync} from 'node:child_process';
+import {createPackageFromStreams} from '@electron/asar';
+import {dataWorkerPath} from '../../../src/main/features/web_apps/data';
+const requireNative=createRequire(path.resolve('test/package-probe.cjs')),disk=requireNative('original-fs'),fs=disk.promises,glob=requireNative('minimatch'),match=typeof glob==='function'?glob:glob.minimatch;
+it('opens and writes SQLite from the declared unpacked archive without source-tree dependencies',async()=>{
+ const directory=await fs.mkdtemp(path.join(os.tmpdir(),'orkas-app-data-package-')),root=await fs.realpath(directory),stage=path.join(root,'stage'),archive=path.join(root,'app.asar');
+ try{
+ const relative='src/main/features/web_apps/data-worker.js';await fs.mkdir(path.dirname(path.join(stage,relative)),{recursive:true});await fs.copyFile(path.resolve(relative),path.join(stage,relative));
+ for(const name of ['better-sqlite3','bindings','file-uri-to-path'])await fs.cp(path.resolve('node_modules',name),path.join(stage,'node_modules',name),{recursive:true});
+ const config=JSON.parse(await fs.readFile(path.resolve('package.json'),'utf8')),streams:any[]=[];
+ const walk=async(relative:string)=>{for(const entry of await fs.readdir(path.join(stage,relative),{withFileTypes:true})){const name=path.posix.join(relative,entry.name),absolute=path.join(stage,name);if(entry.isDirectory()){streams.push({type:'directory',path:name,unpacked:false});await walk(name);}else if(entry.isFile())streams.push({type:'file',path:name,stat:await fs.stat(absolute),unpacked:config.build.asarUnpack.some((pattern:string)=>match(name,pattern)),streamGenerator:()=>disk.createReadStream(absolute)});}};
+ await walk('');await finished(await createPackageFromStreams(archive,streams));
+ const source=dataWorkerPath(path.join(archive,'src')),file=path.join(root,'private/data.sqlite');
+ const program=`const {Worker}=require('node:worker_threads');const [source,file,boundary]=process.argv.slice(1);const worker=new Worker(source,{workerData:{file,boundary,limit:200*1024*1024,definition:{version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]}}});worker.on('error',e=>{process.stdout.write(JSON.stringify({error:e.code}));process.exitCode=1;});worker.on('message',m=>{if(m.ready===true)worker.postMessage({id:1,method:'data.insert',args:{table:'notes',values:{body:'Packed'}}});else if(m.id===1&&m.ok)worker.postMessage({id:2,method:'data.query',args:{table:'notes'}});else if(m.id===2&&m.ok){process.stdout.write(JSON.stringify(m.value));worker.postMessage({close:true});}else{process.stdout.write(JSON.stringify({error:m.code}));worker.terminate();process.exitCode=1;}});`;
+ const env={...process.env,ELECTRON_RUN_AS_NODE:'1'};delete env.NODE_PATH;delete env.NODE_OPTIONS;
+ const probe=()=>spawnSync(process.execPath,['-e',program,source,file,root],{env,cwd:root,timeout:15000,encoding:'utf8'});
+ const result=probe();expect(result.status,JSON.stringify({status:result.status,stderrBytes:result.stderr.length})).toBe(0);expect(result.stderr).toBe('');expect(JSON.parse(result.stdout)).toEqual({records:[{body:'Packed'}]});
+ await fs.rename(path.join(archive+'.unpacked','node_modules/bindings'),path.join(archive+'.unpacked','node_modules/bindings.disabled'));const missing=probe();expect(missing.status).not.toBe(0);expect(JSON.parse(missing.stdout)).toMatchObject({error:'MODULE_NOT_FOUND'});expect(missing.stderr).toBe('');
+ }finally{await fs.rm(root,{recursive:true,force:true});}
+},30000);
diff --git a/test/main/features/app-data-worker.test.ts b/test/main/features/app-data-worker.test.ts
new file mode 100644
index 00000000..9dc50df3
--- /dev/null
+++ b/test/main/features/app-data-worker.test.ts
@@ -0,0 +1,36 @@
+/** A failed application worker must release callers rather than leave an app loading forever. */
+import {EventEmitter} from 'node:events';
+import {afterEach,expect,it,vi} from 'vitest';
+const state=vi.hoisted(()=>({workers:[] as any[]}));
+vi.mock('node:worker_threads',()=>({Worker:class extends EventEmitter{
+ threadId=1;postMessage=vi.fn();terminate=vi.fn(async()=>{this.threadId=-1;this.emit('exit',1);return 1;});
+ constructor(){super();state.workers.push(this);}
+}}));
+import {LocalAppData} from '../../../src/main/features/web_apps/data';
+afterEach(()=>{vi.useRealTimers();state.workers.length=0;});
+it('fails stuck startup within its deadline and terminates only the owned worker',async()=>{
+ vi.useFakeTimers();const data=new LocalAppData('/tmp/app/data.sqlite','/tmp/app',{version:1,tables:[]});const failure=expect(data.call('internal.check',{})).rejects.toMatchObject({code:'E_BUSY'});await vi.advanceTimersByTimeAsync(5000);await failure;expect(state.workers[0].terminate).toHaveBeenCalledOnce();await data.close();expect(vi.getTimerCount()).toBe(0);
+});
+it('releases a caller when a worker exits before reporting readiness',async()=>{
+ vi.useFakeTimers();const data=new LocalAppData('/tmp/app/data.sqlite','/tmp/app',{version:1,tables:[]});const failure=expect(data.call('internal.check',{})).rejects.toMatchObject({code:'E_CLOSED'});state.workers[0].threadId=-1;state.workers[0].emit('exit',1);await failure;await data.close();expect(vi.getTimerCount()).toBe(0);
+});
+it('terminates a rejected startup so repeated opens cannot leak failed application workers',async()=>{
+ vi.useFakeTimers();const data=new LocalAppData('/tmp/app/data.sqlite','/tmp/app',{version:1,tables:[]});const failure=expect(data.call('internal.check',{})).rejects.toMatchObject({code:'E_MIGRATION'});state.workers[0].emit('message',{ready:false,code:'E_MIGRATION'});await failure;expect(state.workers[0].terminate).toHaveBeenCalledOnce();await data.close();expect(vi.getTimerCount()).toBe(0);
+});
+
+it('releases its shutdown deadline when the owned worker exits normally',async()=>{
+ vi.useFakeTimers();const data=new LocalAppData('/tmp/app/data.sqlite','/tmp/app',{version:1,tables:[]});const worker=state.workers[0];worker.emit('message',{ready:true});worker.postMessage.mockImplementation(()=>{worker.threadId=-1;worker.emit('exit',0);});await data.close();expect(vi.getTimerCount()).toBe(0);expect(worker.terminate).not.toHaveBeenCalled();
+});
+// The worker holds every reply, so the 16-request in-flight cap is reached without timing races.
+it('refuses a seventeenth in-flight request as busy without posting it and accepts again once a reply drains',async()=>{
+ vi.useFakeTimers();const data=new LocalAppData('/tmp/app/data.sqlite','/tmp/app',{version:1,tables:[]});const worker=state.workers[0];worker.emit('message',{ready:true});
+ const held=Array.from({length:16},(_,i)=>data.call('data.query',{table:'notes',i}));
+ await expect(data.call('data.query',{table:'notes',i:16})).rejects.toMatchObject({code:'E_BUSY'});
+ const posted=()=>worker.postMessage.mock.calls.map(([message]:any)=>message).filter((message:any)=>message.id);
+ expect(posted()).toHaveLength(16);expect(posted().some((message:any)=>message.args.i===16)).toBe(false);
+ worker.emit('message',{id:posted()[0].id,ok:true,value:{records:[]}});await expect(held[0]).resolves.toEqual({records:[]});
+ const next=data.call('data.query',{table:'notes',i:17});await vi.advanceTimersByTimeAsync(0);expect(posted()).toHaveLength(17);
+ for(const message of posted().slice(1))worker.emit('message',{id:message.id,ok:true,value:{records:[]}});
+ await expect(Promise.all([...held.slice(1),next])).resolves.toHaveLength(16);
+ worker.postMessage.mockImplementation((message:any)=>{if(message.close){worker.threadId=-1;worker.emit('exit',0);}});await data.close();expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/test/main/features/chat_artifacts.test.ts b/test/main/features/chat_artifacts.test.ts
index 12807070..60cc7233 100644
--- a/test/main/features/chat_artifacts.test.ts
+++ b/test/main/features/chat_artifacts.test.ts
@@ -37,6 +37,78 @@ function cidDir(): string {
}
const MIN_FILES = [{ path: 'index.html', content: '<!doctype html><h1>hi</h1>' }];
+it.each(['local','web'] as const)('accepts a valid base64 manifest for a %s artifact while preserving the host permission boundary',async appType=>{
+ const m=await loadMod(),manifest={sdkVersion:1,capabilities:['data'],data:{version:1,tables:[]}};
+ const result=await m.createArtifact(UID,CID,AGENT,{appType,files:[...MIN_FILES,{path:'orkas-app.json',content:Buffer.from(JSON.stringify(manifest)).toString('base64'),encoding:'base64'}]});
+ if (appType === 'web') { expect(result).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' }); expect(fs.existsSync(cidDir())).toBe(false); return; }
+ expect(result.ok).toBe(true);if(!result.ok)throw new Error(result.error);
+ const saved=JSON.parse(fs.readFileSync(path.join(cidDir(),result.artifactId,'orkas-app.json'),'utf8'));
+ expect(saved).toMatchObject(manifest);expect(m.readArtifactMeta(UID,CID,result.artifactId)?.appType).toBe(appType);
+ const denied=await m.createArtifact(UID,CID,AGENT,{appType:'web',files:[...MIN_FILES,{path:'orkas-app.json',content:Buffer.from(JSON.stringify({sdkVersion:1,capabilities:['ai']})).toString('base64'),encoding:'base64'}]});
+ expect(denied).toMatchObject({ok:false,code:'E_COMMERCIAL_REQUIRED',feature:'web_apps'});
+ const missing=await m.createArtifact(UID,CID,AGENT,{appType,files:[...MIN_FILES,{path:'orkas-app.json',content:JSON.stringify({sdkVersion:1,capabilities:['data']})}]});
+ expect(missing).toMatchObject({ok:false,error:'data definition is required'});
+});
+
+// 2026-10-15 live regression: an opaque manifest rejection made authors drop
+// the declaration instead of correcting it. Each rejection names its cause,
+// stays bounded, and creates nothing.
+const PREFIX = 'invalid application interface declaration in orkas-app.json: ';
+const TABLE = (fields: unknown, access: unknown = { read: ['body'], insert: ['body'] }) =>
+ ({ sdkVersion: 1, capabilities: ['data'], data: { version: 1, tables: [{ id: 'notes', name: 'notes', fields, access }] } });
+const BODY = [{ id: 'body', name: 'body', type: 'string' }];
+it.each([
+ ['non-UTF-8 bytes', { content: Buffer.from([0x7b, 0xff, 0xfe, 0x7d]).toString('base64'), encoding: 'base64' }, 'must be UTF-8 text'],
+ ['malformed JSON', { content: '{"sdkVersion":1,' }, 'must be valid JSON'],
+ ['a non-object root', { content: '[]' }, 'root must be object, received array'],
+ ['a missing sdkVersion', { content: JSON.stringify({ capabilities: [] }) }, 'sdkVersion is required'],
+ ['an unsupported sdkVersion', { content: JSON.stringify({ sdkVersion: 2, capabilities: [] }) }, 'sdkVersion must be 1'],
+ ['an unknown capability', { content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage', 'shell'] }) },
+ 'capabilities[1] must be one of storage, appFiles, files, ai, library, connectors, data'],
+ ['capabilities as an object', { content: JSON.stringify({ sdkVersion: 1, capabilities: { data: true } }) }, 'capabilities must be array, received object'],
+ ['invented top-level fields', { content: JSON.stringify({ sdkVersion: 1, capabilities: [], name: 'Notes', version: '1' }) },
+ 'root has unsupported field(s) name, version'],
+ ['an unknown field type', { content: JSON.stringify(TABLE([{ id: 'body', name: 'body', type: 'text' }])) },
+ 'data.tables[0].fields[0].type must be one of string, number, integer, boolean, json, timestamp'],
+ ['an access list naming an undeclared field', { content: JSON.stringify(TABLE(BODY, { read: ['body', 'createdBy'], insert: ['body'] })) },
+ 'data: Unknown or duplicate access field'],
+] as const)('names the cause of a manifest with %s and creates no artifact', async (_label, file, cause) => {
+ const m = await loadMod();
+ for (const appType of ['local', 'web'] as const) {
+ const result = await m.createArtifact(UID, CID, AGENT, { appType, files: [...MIN_FILES, { path: 'orkas-app.json', ...file }] });
+ if (appType === 'web') { expect(result).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' }); continue; }
+ expect(result.ok).toBe(false); if (result.ok) return;
+ expect(result.error.startsWith(PREFIX)).toBe(true);
+ expect(result.error).toContain(cause);
+ }
+ expect(fs.existsSync(cidDir()) ? fs.readdirSync(cidDir()) : []).toEqual([]);
+});
+
+it('bounds a rejection with many issues and never echoes non-identifier keys or rejected values', async () => {
+ const m = await loadMod();
+ const secret = '/Users/test/private notes ' + 'x'.repeat(400);
+ const manifest = { sdkVersion: 2, capabilities: ['shell-' + secret, 'a', 'b', 'c'], data: 'tables', [secret]: 1, extra_field: true };
+ const result = await m.createArtifact(UID, CID, AGENT, { files: [...MIN_FILES, { path: 'orkas-app.json', content: JSON.stringify(manifest) }] });
+ expect(result.ok).toBe(false); if (result.ok) return;
+ expect(result.error.startsWith(PREFIX)).toBe(true);
+ // Invented members come first; repeated reasons share one entry.
+ expect(result.error).toContain('root has unsupported field(s) extra_field, 1 other key(s)');
+ expect(result.error).toContain('capabilities[0], capabilities[1], capabilities[2] (+1 more) must be one of');
+ expect(result.error).toMatch(/\(\+1 more\)$/);
+ expect(result.error).not.toContain('someone');
+ expect(result.error).not.toContain('shell-');
+ expect(result.error.length).toBeLessThanOrEqual(600);
+ expect(fs.existsSync(cidDir()) ? fs.readdirSync(cidDir()) : []).toEqual([]);
+});
+
+it('names the local-only capabilities a web manifest declared', async () => {
+ const m = await loadMod();
+ const result = await m.createArtifact(UID, CID, AGENT, { appType: 'web', files: [...MIN_FILES,
+ { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['data', 'storage', 'ai'], data: { version: 1, tables: [] } }) }] });
+ expect(result).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ expect(fs.existsSync(cidDir()) ? fs.readdirSync(cidDir()) : []).toEqual([]);
+});
+
/**
* 2026-08-26: the host cannot measure a cross-origin iframe, so an artifact
@@ -416,3 +488,64 @@ it('creates and serves the same media/model/font resources accepted by saved app
if(result.ok)expect(fs.readFileSync(result.absPath)).toEqual(Buffer.from([0,1]));
}
});
+
+
+describe('chat_artifacts › application type for bubble labels', () => {
+ it.each(['local', 'web'] as const)('returns the actual %s bundle type during preview inspection', async appType => {
+ const m = await loadMod();
+ let created: any;
+ if (appType === 'web') {
+ const dir = path.join(cidDir(), 'legacy-web'); fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'index.html'), MIN_FILES[0].content);
+ fs.writeFileSync(path.join(dir, '__orkas-meta.json'), JSON.stringify({ title: 'Legacy web app', appType: 'web' }));
+ created = { ok: true, artifactId: 'legacy-web' };
+ } else created = await m.createArtifact(UID, CID, AGENT, { appType, files: MIN_FILES });
+ if (!created.ok) throw new Error(created.error);
+ expect(await m.inspectArtifactIndex(UID, CID, created.artifactId)).toEqual({ ok: true, status: 'ok', appType });
+ });
+
+ it('identifies a legacy bundle as local and does not label a missing preview', async () => {
+ const m = await loadMod();
+ const created = await m.createArtifact(UID, CID, AGENT, { files: MIN_FILES });
+ if (!created.ok) throw new Error(created.error);
+ const dir = path.join(cidDir(), created.artifactId);
+ fs.writeFileSync(path.join(dir, '__orkas-meta.json'), JSON.stringify({ title: 'Legacy app' }));
+ expect(await m.inspectArtifactIndex(UID, CID, created.artifactId)).toEqual({ ok: true, status: 'ok', appType: 'local' });
+ fs.rmSync(path.join(dir, 'index.html'));
+ const missing = await m.inspectArtifactIndex(UID, CID, created.artifactId);
+ expect(missing).toMatchObject({ ok: true, status: 'unavailable' });
+ expect(missing).not.toHaveProperty('appType');
+ });
+});
+
+describe('chat_artifacts › application type input', () => {
+ // Sync notification is loaded through CommonJS require and cannot be
+ // intercepted here; it is sent only after the staged directory is renamed,
+ // so an absent directory is the observable no-publication oracle.
+ it('denies authoring through the legacy cloud alias without allocating a bundle', async () => {
+ const m = await loadMod();
+ const created = await m.createArtifact(UID, CID, AGENT, { appType: 'cloud', files: MIN_FILES });
+ expect(created).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ expect(fs.existsSync(cidDir())).toBe(false);
+ });
+
+ it.each([['desktop'], ['Web'], [1], [{ type: 'web' }]])('rejects unknown type %j without creating an artifact', async appType => {
+ const m = await loadMod();
+ const result = await m.createArtifact(UID, CID, AGENT, { appType, files: MIN_FILES });
+ expect(result).toEqual({ ok: false, error: 'app type must match the task or editing source' });
+ expect(fs.existsSync(cidDir()) ? fs.readdirSync(cidDir()) : []).toEqual([]);
+ expect(m.listArtifacts(UID, CID)).toEqual([]);
+ });
+
+ it('denies an undeclared web app and retains local auto-sizing authoring', async () => {
+ const m = await loadMod();
+ const html = '<!doctype html><html><head><title>Web</title></head><body><p>Plain</p></body></html>';
+ const created = await m.createArtifact(UID, CID, AGENT, { appType: 'web', files: [{ path: 'index.html', content: html }] });
+ expect(created).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ expect(fs.existsSync(cidDir())).toBe(false);
+ const local = await m.createArtifact(UID, CID, AGENT, { files: [{ path: 'index.html', content: html }] });
+ expect(local.ok).toBe(true); if (!local.ok) return;
+ expect(fs.readFileSync(path.join(cidDir(), local.artifactId, 'index.html'), 'utf8')).toContain(m.BRIDGE_RELPATH);
+ expect(fs.existsSync(path.join(cidDir(), local.artifactId, 'orkas-app.json'))).toBe(false);
+ });
+});
diff --git a/test/main/features/html_preview.test.ts b/test/main/features/html_preview.test.ts
index dc6bffec..24d824a5 100644
--- a/test/main/features/html_preview.test.ts
+++ b/test/main/features/html_preview.test.ts
@@ -69,8 +69,11 @@ function fakeRuntime(options: {
interactionWarnings?: string[];
loadFailure?: boolean;
extraRequests?: string[];
+ /** Returned only when the evidence script carries the design audit. */
+ design?: Record<string, unknown>;
} = {}): {
deps: HtmlPreviewRuntimeDeps;
+ evidenceScripts: string[];
windows: Array<{ options: Record<string, any>; destroyed: boolean }>;
requestDecisions: Array<{ url: string; cancel: boolean }>;
permissionDecisions: {
@@ -98,6 +101,7 @@ function fakeRuntime(options: {
const loadedEntryUrls: string[] = [];
const bridgeAvailableAtLoad: boolean[] = [];
const interactionExecutions: string[] = [];
+ const evidenceScripts: string[] = [];
const protocolHandlers = new Map<string, (request: Request) => Response | Promise<Response>>();
const registeredProtocolHandlers: Array<(request: Request) => Response | Promise<Response>> = [];
let requestHandler: ((details: { url: string }, callback: (decision: { cancel: boolean }) => void) => void) | undefined;
@@ -169,14 +173,15 @@ function fakeRuntime(options: {
const width = Number(windowOptions.width);
const isEmbed = width === ARTIFACT_FRAME.smokeWidth
&& Number(windowOptions.height) === ARTIFACT_FRAME.maxHeight;
- return script.startsWith('(async')
- ? true
- : { ...pageEvidence(
+ if (script.startsWith('(async')) return true;
+ evidenceScripts.push(script);
+ return { ...pageEvidence(
width,
width <= 480 ? options.mobileOverflow ?? 0 : 0,
isEmbed ? options.embedUnreachablePx ?? 0 : 0,
isEmbed ? options.embedScrollHeight ?? 900 : 900,
- ), ...(options.ineffectiveTransforms ? { ineffectiveTransforms: options.ineffectiveTransforms } : {}) };
+ ), ...(options.ineffectiveTransforms ? { ineffectiveTransforms: options.ineffectiveTransforms } : {}),
+ ...(options.design && script.includes('designEvidence') ? { design: options.design } : {}) };
}
},
capturePage: async () => ({
@@ -262,6 +267,7 @@ function fakeRuntime(options: {
};
return {
deps,
+ evidenceScripts,
windows,
requestDecisions,
permissionDecisions,
@@ -712,6 +718,97 @@ describe('responsive HTML preview renderer', () => {
});
});
+describe('design audit', () => {
+ const desktop = [{ name: 'desktop' as const, width: 1440, height: 900 }];
+ const clean = {
+ fontSizes: [32, 16, 14, 13, 12, 11, 10.5, 10],
+ colorTokenCount: 8,
+ nonTokenColorCount: 0,
+ nonTokenColors: [],
+ textOverlaps: [],
+ lowContrastCount: 0,
+ lowContrastText: [],
+ };
+ // The shape a UIDesigner revision drifted into: one-off sizes, colors typed
+ // in place of tokens, copy laid over copy, and muted text too faint to read.
+ const drifted = {
+ fontSizes: [32, 25, 20, 17, 16, 14, 13, 12, 11],
+ colorTokenCount: 8,
+ nonTokenColorCount: 2,
+ nonTokenColors: ['#4945c0 (a.e-tag)', '#fff8e1 (#notice)'],
+ textOverlaps: [{ selector: 'h2#goal-title', other: 'p.micro', width: 40, height: 12 }],
+ lowContrastCount: 3,
+ lowContrastText: [{
+ selector: 'span.muted', ratio: 3.69, required: 4.5, color: '#7e8597', background: '#ffffff', fontSize: 11,
+ }],
+ };
+
+ it('measures every viewport by default and reports drift as warnings, not blockers', async () => {
+ const runtime = fakeRuntime({ design: drifted });
+ const result = await renderResponsiveHtmlPreview(
+ path.join(root, 'index.html'),
+ desktop,
+ runtime.deps,
+ { interactions: false },
+ );
+
+ expect(runtime.evidenceScripts).toHaveLength(1);
+ expect(runtime.evidenceScripts[0]).toContain('designEvidence');
+ expect(result.evidence.ok).toBe(true);
+ expect(result.evidence.blockers).toEqual([]);
+ expect(result.evidence.viewports[0].design).toEqual(drifted);
+ expect(result.evidence.warnings).toEqual([
+ 'desktop: 9 distinct font sizes on visible text (32, 25, 20, 17, 16, 14, 13, 12, 11px); a type scale needs 8 or fewer',
+ 'desktop: 2 hard-coded color(s) match no color variable: #4945c0 (a.e-tag), #fff8e1 (#notice)',
+ 'desktop: 1 text overlap(s): h2#goal-title × p.micro',
+ 'desktop: 3 text element(s) below WCAG AA contrast: span.muted 3.69:1 < 4.5:1',
+ ]);
+ });
+
+ it('stays quiet within the scale, names untokened pages, and survives a failed measurement', async () => {
+ const quiet = await renderResponsiveHtmlPreview(
+ path.join(root, 'index.html'), desktop, fakeRuntime({ design: clean }).deps, { interactions: false },
+ );
+ expect(quiet.evidence.warnings).toEqual([]);
+
+ const untokened = await renderResponsiveHtmlPreview(
+ path.join(root, 'index.html'),
+ desktop,
+ fakeRuntime({
+ design: { ...clean, colorTokenCount: 0, nonTokenColorCount: 1, nonTokenColors: ['#123456 (p.rogue)'] },
+ }).deps,
+ { interactions: false },
+ );
+ expect(untokened.evidence.warnings).toEqual([
+ 'desktop: no color variables; 1 hard-coded color(s): #123456 (p.rogue)',
+ ]);
+
+ const failed = await renderResponsiveHtmlPreview(
+ path.join(root, 'index.html'),
+ desktop,
+ fakeRuntime({ design: { ...clean, fontSizes: [], error: 'canvas unavailable' } }).deps,
+ { interactions: false },
+ );
+ expect(failed.evidence.ok).toBe(true);
+ expect(failed.evidence.warnings).toEqual(['desktop: design audit did not run: canvas unavailable']);
+ });
+
+ it('leaves design out of the chat-artifact smoke, which judges operability only', async () => {
+ const runtime = fakeRuntime({
+ controlsExercised: 1,
+ stateChangesObserved: 1,
+ embedScrollHeight: ARTIFACT_FRAME.maxHeight - 40,
+ design: drifted,
+ });
+ const result = await renderInteractiveHtmlSmoke(path.join(root, 'index.html'), runtime.deps);
+
+ expect(runtime.evidenceScripts).toHaveLength(3);
+ expect(runtime.evidenceScripts.some((script) => script.includes('designEvidence'))).toBe(false);
+ expect(result.evidence.viewports.every((view) => view.design === undefined)).toBe(true);
+ expect(result.evidence.warnings).toEqual([]);
+ });
+});
+
describe('file viewer check', () => {
const desktop = [{ name: 'desktop' as const, width: 1440, height: 900 }];
const png1x1 = Buffer.from(
diff --git a/test/main/features/preview-windows.test.ts b/test/main/features/preview-windows.test.ts
index 67ba321b..cfca19f4 100644
--- a/test/main/features/preview-windows.test.ts
+++ b/test/main/features/preview-windows.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import * as path from 'node:path';
-const runtime = vi.hoisted(() => ({ windows: [] as any[], hook: null as any, nextId: 0, unsubscribe: vi.fn() }));
+const runtime = vi.hoisted(() => ({ windows: [] as any[], hook: null as any, nextId: 0, appType: 'local', unsubscribe: vi.fn() }));
vi.mock('electron', async () => {
const { EventEmitter } = await import('node:events');
class Contents extends EventEmitter {
@@ -26,6 +26,12 @@ vi.mock('electron', async () => {
}
return { BrowserWindow: Window, shell: { openExternal: vi.fn() }, screen: { getDisplayMatching: () => ({ workArea: { x: 0, y: 0, width: 1440, height: 900 } }) } };
});
+vi.mock('../../../src/main/features/saved_apps', () => ({
+ resolveSavedAppType: async () => runtime.appType,
+ resolveArtifactAppType: async () => runtime.appType,
+ boundAppType: async () => undefined,
+ managedPathAppType: async () => undefined,
+}));
vi.mock('../../../src/main/features/user-switch-hooks', () => ({ registerUserSwitchHook: (_name: string, fn: any) => { runtime.hook = fn; } }));
vi.mock('../../../src/main/features/group_chat', () => ({ subscribeBus: () => runtime.unsubscribe }));
vi.mock('../../../src/main/logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
@@ -36,10 +42,24 @@ import { openPreview, initializePreview, closePreview, setPreviewDirty, requestP
beforeEach(() => {
for (const win of runtime.windows) win.destroy();
runtime.windows.length = 0;
+ runtime.appType = 'local';
runtime.unsubscribe.mockClear();
});
describe('independent preview ownership and lifecycle', () => {
+ it.each(['web', 'cloud'])('refuses a %s preview before allocating, focusing or reusing a window', async appType => {
+ const main = new BrowserWindow({});
+ const local = { kind: 'app', appId: 'a', title: 'App' };
+ await openPreview('user-a', main.webContents, local);
+ const previous = runtime.windows[1]; previous.focus.mockClear(); previous.show.mockClear();
+ runtime.appType = appType;
+ for (const source of [local, { kind: 'artifact', cid: 'task', artifactId: 'result', title: 'Result' }]) {
+ expect(await openPreview('user-a', main.webContents, source)).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ expect(runtime.windows).toHaveLength(2);
+ expect(previous.focus).not.toHaveBeenCalled(); expect(previous.show).not.toHaveBeenCalled();
+ }
+ });
+
it.each([false, true])('inherits owner focusability across every preview kind, including reopening minimized windows: %s', async (focusable) => {
const sources = [
{ kind: 'app', appId: 'a', title: 'App' },
diff --git a/test/main/features/saved-app-type-recovery.test.ts b/test/main/features/saved-app-type-recovery.test.ts
new file mode 100644
index 00000000..3ddcb7b2
--- /dev/null
+++ b/test/main/features/saved-app-type-recovery.test.ts
@@ -0,0 +1,121 @@
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import { captureMainLogWorkers } from '../../helpers/capture-main-log-workers';
+import { drainMainRuntimeForTest } from '../../helpers/drain-main-runtime';
+
+const wire = { uid: 'type-owner' };
+vi.mock('electron', () => ({ app: { isPackaged: false }, dialog: {} }));
+vi.mock('../../../src/main/model/client', () => ({
+ async *streamChatWithModel() { yield { type: 'done' }; },
+ async chatWithModel() { return { ok: true, text: '' }; },
+}));
+
+let root: string, previous: string | undefined, closeLogs: () => Promise<void>;
+beforeEach(async () => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-type-recovery-'));
+ previous = process.env.ORKAS_WORKSPACE_ROOT; process.env.ORKAS_WORKSPACE_ROOT = root;
+ vi.resetModules(); wire.uid = 'type-owner';
+ closeLogs = await captureMainLogWorkers();
+ (await import('../../../src/main/features/users')).activateUser(wire.uid);
+});
+afterEach(async () => {
+ await drainMainRuntimeForTest(); await closeLogs();
+ if (previous === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previous;
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+async function fixture() {
+ const saved = await import('../../../src/main/features/saved_apps');
+ const artifacts = await import('../../../src/main/features/chat_artifacts');
+ const created = await artifacts.createArtifact(wire.uid, 'type-conversation', 'helper', {
+ appType: 'local', files: [{ path: 'index.html', content: '<h1>Keep this source</h1>' }],
+ });
+ if (!created.ok) throw new Error(created.error);
+ const kept = await saved.saveFromArtifact(wire.uid, 'type-conversation', created.artifactId);
+ if (!kept.ok) throw new Error(kept.error);
+ const metadata = path.join(root, wire.uid, 'cloud/saved_apps', kept.id, '__orkas-meta.json');
+ return { saved, artifacts, kept, metadata };
+}
+
+it('uses valid local metadata and preserves its edit binding without any hosted service', async () => {
+ const f = await fixture();
+ const edited = await f.saved.openForEditing(wire.uid, f.kept.id);
+ expect(edited.ok).toBe(true); if (!edited.ok) throw new Error(edited.error);
+ expect(await f.saved.getEditTarget(wire.uid, (edited.conversation as any).conversation_id)).toMatchObject({ appType: 'local' });
+});
+
+it('preserves legacy local editing when metadata is absent without creating metadata', async () => {
+ const f = await fixture(); fs.unlinkSync(f.metadata);
+ const edited = await f.saved.openForEditing(wire.uid, f.kept.id);
+ expect(edited.ok).toBe(true); if (!edited.ok) throw new Error(edited.error);
+ expect(await f.saved.getEditTarget(wire.uid, (edited.conversation as any).conversation_id)).toMatchObject({ appType: 'local' });
+ expect(fs.existsSync(f.metadata)).toBe(false);
+});
+
+it.each(['{ damaged', '{"appType":"unexpected"}', '[]'])('refuses damaged authoritative metadata %s without rewriting source bytes', async damaged => {
+ const f = await fixture(); fs.writeFileSync(f.metadata, damaged);
+ expect((await f.saved.openForEditing(wire.uid, f.kept.id)).ok).toBe(false);
+ expect(fs.readFileSync(f.metadata, 'utf8')).toBe(damaged);
+});
+
+it('resolves a mixed local listing using explicit metadata and the legacy fallback', async () => {
+ const f = await fixture(); const dir = path.dirname(path.dirname(f.metadata));
+ for (const [id, meta] of [['legacy', '{}'], ['historic-web', '{"appType":"web"}'], ['invalid', '{ damaged']]) {
+ fs.mkdirSync(path.join(dir, id)); fs.writeFileSync(path.join(dir, id, '__orkas-meta.json'), meta);
+ fs.writeFileSync(path.join(dir, id, 'index.html'), '<h1>Keep</h1>');
+ }
+ const list = await f.saved.listResolvedSavedApps(wire.uid);
+ expect(Object.fromEntries(list.map(app => [app.id, app.appType]))).toEqual({
+ [f.kept.id]: 'local', legacy: 'local', 'historic-web': 'web', invalid: undefined,
+ });
+});
+
+it('rechecks the original app when an edit context loses its type and refuses damaged contexts', async () => {
+ const f = await fixture(); const edited = await f.saved.openForEditing(wire.uid, f.kept.id);
+ if (!edited.ok) throw new Error(edited.error);
+ const cid = (edited.conversation as any).conversation_id;
+ const contextFile = path.join(root, wire.uid, 'local/app-edits', cid, 'context.json');
+ const context = JSON.parse(fs.readFileSync(contextFile, 'utf8')); delete context.appType;
+ fs.writeFileSync(contextFile, JSON.stringify(context));
+ expect(await f.saved.boundAppType(wire.uid, cid)).toBe('local');
+ fs.writeFileSync(f.metadata, JSON.stringify({ ...JSON.parse(fs.readFileSync(f.metadata, 'utf8')), appType: 'web' }));
+ expect(await f.saved.boundAppType(wire.uid, cid)).toBe('web');
+ expect(await f.artifacts.createArtifact(wire.uid, cid, 'helper', { appType: 'local', files: [] }))
+ .toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ fs.writeFileSync(contextFile, '{ damaged');
+ await expect(f.saved.boundAppType(wire.uid, cid)).rejects.toMatchObject({ code: 'app_edit_context_unavailable' });
+});
+
+it('keeps a local edit on its original type and writes nothing for a conflicting web request', async () => {
+ const f = await fixture(); const edited = await f.saved.openForEditing(wire.uid, f.kept.id);
+ if (!edited.ok) throw new Error(edited.error);
+ const cid = (edited.conversation as any).conversation_id;
+ const denied = await f.artifacts.createArtifact(wire.uid, cid, 'helper', { appType: 'web', files: [{ path: 'index.html', content: '<h1>Other type</h1>' }] });
+ expect(denied).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ expect(fs.existsSync(path.join(root, wire.uid, 'cloud/chat_artifacts', cid))).toBe(false);
+ const inherited = await f.artifacts.createArtifact(wire.uid, cid, 'helper', { files: [{ path: 'index.html', content: '<h1>Same type</h1>' }] });
+ if (!inherited.ok) throw new Error(inherited.error);
+ expect(f.artifacts.readArtifactMeta(wire.uid, cid, inherited.artifactId)?.appType).toBe('local');
+});
+
+it.each([undefined, null])('keeps omitted/null application types compatible in an ordinary conversation (%s)', async appType => {
+ const f = await fixture();
+ const created = await f.artifacts.createArtifact(wire.uid, 'ordinary', 'helper', { appType, files: [{ path: 'index.html', content: '<h1>Local</h1>' }] });
+ if (!created.ok) throw new Error(created.error);
+ expect(f.artifacts.readArtifactMeta(wire.uid, 'ordinary', created.artifactId)?.appType).toBe('local');
+});
+
+it('does not label an untyped artifact whose editing binding is damaged', async () => {
+ const f = await fixture(); const edited = await f.saved.openForEditing(wire.uid, f.kept.id);
+ if (!edited.ok) throw new Error(edited.error);
+ const cid = (edited.conversation as any).conversation_id;
+ const created = await f.artifacts.createArtifact(wire.uid, cid, 'helper', { files: [{ path: 'index.html', content: '<h1>Untyped</h1>' }] });
+ if (!created.ok) throw new Error(created.error);
+ fs.writeFileSync(path.join(root, wire.uid, 'cloud/chat_artifacts', cid, created.artifactId, '__orkas-meta.json'), '{}');
+ fs.writeFileSync(path.join(root, wire.uid, 'local/app-edits', cid, 'context.json'), '{ damaged');
+ const inspection = await f.artifacts.inspectArtifactIndex(wire.uid, cid, created.artifactId);
+ expect(inspection.ok).toBe(false); expect(inspection).not.toHaveProperty('appType');
+});
diff --git a/test/main/features/saved_apps.test.ts b/test/main/features/saved_apps.test.ts
index e5bc3930..6093a7fd 100644
--- a/test/main/features/saved_apps.test.ts
+++ b/test/main/features/saved_apps.test.ts
@@ -3,6 +3,7 @@ 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';
+import * as crypto from 'node:crypto';
import { drainMainRuntimeForTest } from '../../helpers/drain-main-runtime';
// `saved_apps.ts` → `chats.ts` → `group_chat` pulls in `model/client`; mock it
@@ -13,6 +14,12 @@ vi.mock('../../../src/main/model/client', () => ({
async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },
}));
+const cleanupWarnings = vi.hoisted(() => vi.fn());
+vi.mock('node:fs/promises', async importOriginal => {
+ const actual = await importOriginal<typeof import('node:fs/promises')>();
+ return { ...actual, rm: vi.fn(actual.rm), rename: vi.fn(actual.rename), cp: vi.fn(actual.cp), copyFile: vi.fn(actual.copyFile) };
+});
+
const UID = 'u-savedapps-001';
const CID = 'conv-sa-1';
@@ -25,6 +32,7 @@ beforeEach(async () => {
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
vi.resetModules();
+ cleanupWarnings.mockClear();
closeLogWorkers = await captureMainLogWorkers();
const users = await import('../../../src/main/features/users');
users.activateUser(UID);
@@ -59,6 +67,193 @@ async function makeArtifact(title: string, extra: Array<{ path: string; content:
}
describe('saved_apps › saveFromArtifact', () => {
+ it.each(['update', 'export'] as const)('preserves committed %s results and releases the data lease when backup cleanup fails', async mode => {
+ const logging = await import('../../../src/main/logger');
+ const createLogger = logging.createLogger;
+ const loggerSpy = vi.spyOn(logging, 'createLogger').mockImplementation(module => {
+ const logger = createLogger(module);
+ if (module !== 'saved_apps') return logger;
+ return { ...logger, warn: (message: string, ...args: unknown[]) => {
+ if (message === 'edited app data backup cleanup deferred') cleanupWarnings(message, ...args);
+ logger.warn(message, ...args);
+ } };
+ });
+ try {
+ const { chatArtifacts, savedApps } = await mods();
+ const definition = { version: 1, tables: [{ id: 'notes', name: 'notes', fields: [{ id: 'body', name: 'body', type: 'string' }], access: { read: ['body'], insert: ['body'] } }] };
+ const declaration = { sdkVersion: 1, capabilities: ['data'], data: definition };
+ const original = await chatArtifacts.createArtifact(UID, CID, 'helper', { files: [
+ { path: 'index.html', content: '<h1>Original</h1>' }, { path: 'orkas-app.json', content: JSON.stringify(declaration) },
+ ] });
+ if (!original.ok) throw new Error(original.error);
+ const saved = await savedApps.saveFromArtifact(UID, CID, original.artifactId);
+ if (!saved.ok) throw new Error(saved.error);
+ const key = crypto.createHash('sha256').update(JSON.stringify(['saved', saved.id])).digest('hex');
+ const file = path.join(tmpDir, UID, 'local/web_apps', key, 'data.sqlite');
+ const { LocalAppData } = await import('../../../src/main/features/web_apps/data');
+ const database = new LocalAppData(file, path.join(tmpDir, UID, 'local'), definition);
+ try { await database.call('data.insert', { table: 'notes', values: { body: 'KEEP' } }); }
+ finally { await database.close(); }
+ const edit = await savedApps.openForEditing(UID, saved.id);
+ if (!edit.ok) throw new Error(edit.error);
+ const cid = (edit.conversation as any).conversation_id;
+ const revised = await chatArtifacts.createArtifact(UID, cid, 'helper', { files: [
+ { path: 'index.html', content: '<h1>Revised</h1>' }, { path: 'orkas-app.json', content: JSON.stringify(declaration) },
+ ] });
+ if (!revised.ok) throw new Error(revised.error);
+ const fsp = await import('node:fs/promises');
+ const { rm } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ let cleanupAttempts = 0;
+ const fault = vi.spyOn(fsp, 'rm').mockImplementation(async (target, options) => {
+ if (String(target).startsWith(file + '.backup-')) { cleanupAttempts += 1; throw Object.assign(new Error('PRIVATE cleanup path'), { code: 'EACCES' }); }
+ return rm(target, options);
+ });
+ const runtime = await import('../../../src/main/features/web_apps/runtime');
+ const destination = path.join(tmpDir, 'records.sqlite');
+ try {
+ const result = mode === 'update'
+ ? await savedApps.saveFromArtifact(UID, cid, revised.artifactId, 'update')
+ : await savedApps.exportAppData(UID, cid, revised.artifactId, destination);
+ expect(cleanupAttempts).toBe(3);
+ expect(cleanupWarnings).toHaveBeenCalledTimes(3);
+ expect(JSON.stringify(cleanupWarnings.mock.calls)).not.toContain('PRIVATE cleanup path');
+ expect(cleanupWarnings.mock.calls[0][1].error).toMatchObject({ code: 'EACCES', message_chars: 20 });
+ expect(result.ok).toBe(true);
+ const release = runtime.holdAppData(UID, key);
+ release();
+ if (mode === 'update') expect(fs.readFileSync(path.join(APPS_ROOT(), saved.id, 'index.html'), 'utf8')).toContain('Revised');
+ const retained = new LocalAppData(mode === 'export' ? destination : file, tmpDir, definition);
+ try { expect(await retained.call('data.query', { table: 'notes' })).toEqual({ records: [{ body: 'KEEP' }] }); }
+ finally { await retained.close(); }
+ } finally { fault.mockRestore(); }
+ } finally { loggerSpy.mockRestore(); }
+ });
+
+ it('rejects destructive local schema replacement before changing the original code or records',async()=>{
+ const {chatArtifacts,savedApps}=await mods();const definition:any={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]};
+ const original=await chatArtifacts.createArtifact(UID,CID,'helper',{files:[{path:'index.html',content:'<h1>Original schema</h1>'},{path:'orkas-app.json',content:JSON.stringify({sdkVersion:1,capabilities:['data'],data:definition})}]});if(!original.ok)throw new Error(original.error);
+ const saved=await savedApps.saveFromArtifact(UID,CID,original.artifactId);if(!saved.ok)throw new Error(saved.error);
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');const key=crypto.createHash('sha256').update(JSON.stringify(['saved',saved.id])).digest('hex'),file=path.join(tmpDir,UID,'local/web_apps',key,'data.sqlite');
+ const db=new LocalAppData(file,path.join(tmpDir,UID,'local'),definition);await db.call('data.insert',{table:'notes',values:{body:'KEEP'}});await db.close();
+ const edit=await savedApps.openForEditing(UID,saved.id);if(!edit.ok)throw new Error(edit.error);const cid=(edit.conversation as any).conversation_id;
+ const destructive={version:1,tables:[{id:'notes',name:'notes',fields:[],access:{read:[],insert:[]}}]};
+ const changed=await chatArtifacts.createArtifact(UID,cid,'helper',{files:[{path:'index.html',content:'<h1>Destructive</h1>'},{path:'orkas-app.json',content:JSON.stringify({sdkVersion:1,capabilities:['data'],data:destructive})}]});if(!changed.ok)throw new Error(changed.error);
+ expect((await savedApps.saveFromArtifact(UID,cid,changed.artifactId,'update')).ok).toBe(false);
+ expect(fs.readFileSync(path.join(APPS_ROOT(),saved.id,'index.html'),'utf8')).toContain('Original schema');
+ const reopened=new LocalAppData(file,path.join(tmpDir,UID,'local'),definition);try{expect(await reopened.call('data.query',{table:'notes'})).toEqual({records:[{body:'KEEP'}]});}finally{await reopened.close();}
+ const impact=await savedApps.appDataImpact(UID,cid,changed.artifactId);if(!impact.ok)throw new Error(impact.error);expect(impact.records).toBe(1);
+ const exported=path.join(tmpDir,'records.sqlite');expect((await savedApps.exportAppData(UID,cid,changed.artifactId,exported)).ok).toBe(true);expect((await savedApps.exportAppData(UID,cid,changed.artifactId,exported)).ok).toBe(false);
+ const exportDb=new LocalAppData(exported,tmpDir,definition);try{expect(await exportDb.call('data.query',{table:'notes'})).toEqual({records:[{body:'KEEP'}]});}finally{await exportDb.close();}
+ expect((await savedApps.saveFromArtifact(UID,cid,changed.artifactId,'update',{clearVersion:impact.version+1,clearFingerprint:impact.fingerprint})).ok).toBe(false);
+ const updated=await savedApps.saveFromArtifact(UID,cid,changed.artifactId,'update',{clearVersion:impact.version,clearFingerprint:impact.fingerprint});expect(updated.ok).toBe(true);expect(fs.readFileSync(path.join(APPS_ROOT(),saved.id,'index.html'),'utf8')).toContain('Destructive');
+ const cleared=new LocalAppData(file,path.join(tmpDir,UID,'local'),destructive);try{expect(await cleared.call('internal.inspect',{})).toMatchObject({records:0});}finally{await cleared.close();}
+ });
+ it('preserves a cloud creation selection when saving a CLI-produced bundle without accepting bundle metadata as authority',async()=>{
+ const {savedApps}=await mods();const chats=await import('../../../src/main/features/chats');const creation=await chats.createConversation(UID,{title:'Cloud',assistance:{kind:'app_creation',appType:'web'}});const cid=creation.conversation_id;
+ const source=path.join(tmpDir,'cli-cloud');fs.mkdirSync(source);fs.writeFileSync(path.join(source,'index.html'),'<h1>Cloud CLI</h1>');fs.writeFileSync(path.join(source,'__orkas-meta.json'),JSON.stringify({appType:'local'}));
+ const saved=await savedApps.saveFromPath(UID,path.join(source,'index.html'),{sourceCid:cid,fenceRoots:[tmpDir]});expect(saved).toMatchObject({ok:false,code:'E_COMMERCIAL_REQUIRED',feature:'web_apps'});expect(savedApps.listSavedApps(UID)).toEqual([]);
+ fs.writeFileSync(path.join(source,'orkas-app.json'),JSON.stringify({sdkVersion:1,capabilities:['ai']}));expect((await savedApps.saveFromPath(UID,path.join(source,'index.html'),{sourceCid:cid,fenceRoots:[tmpDir]})).ok).toBe(false);
+ });
+ it('locks a new app to the structured creation selection without inspecting prompt words',async()=>{
+ const {chatArtifacts}=await mods();const chats=await import('../../../src/main/features/chats');
+ const assistance=chats.normalizeConversationAssistance({kind:'app_creation',appType:'cloud'});
+ expect(assistance).toEqual({kind:'app_creation',appType:'web'});
+ const conversation=await chats.createConversation(UID,{title:'Create',assistance});
+ const cid=conversation.conversation_id;
+ const created=await chatArtifacts.createArtifact(UID,cid,'helper',{files:[{path:'index.html',content:'Local words do not select the type'}]});
+ expect(created).toMatchObject({ok:false,code:'E_COMMERCIAL_REQUIRED',feature:'web_apps'});
+ expect(fs.existsSync(path.join(tmpDir,UID,'cloud/chat_artifacts',cid))).toBe(false);
+ expect((await chatArtifacts.createArtifact(UID,cid,'helper',{appType:'local',files:[{path:'index.html',content:'Blocked'}]})).ok).toBe(false);
+ });
+ it.each(['web','cloud'])('preserves stored %s type as web across save and editing while refusing host declarations',async storedType=>{
+ const {chatArtifacts,savedApps}=await mods();
+ const created=await chatArtifacts.createArtifact(UID,CID,'helper',{appType:'local',files:[{path:'index.html',content:'<h1>Retained</h1>'}]});
+ if(!created.ok)throw new Error(created.error);
+ const artifactDir=path.join(tmpDir,UID,'cloud/chat_artifacts',CID,created.artifactId);
+ const metadata=path.join(artifactDir,'__orkas-meta.json');
+ fs.writeFileSync(metadata,JSON.stringify({...JSON.parse(fs.readFileSync(metadata,'utf8')),appType:storedType}));
+ const before=fs.readFileSync(metadata);
+ expect(chatArtifacts.readArtifactMeta(UID,CID,created.artifactId)?.appType).toBe('web');
+ expect(await savedApps.saveFromArtifact(UID,CID,created.artifactId)).toMatchObject({ok:false,code:'E_COMMERCIAL_REQUIRED',feature:'web_apps'});
+ const id='historic-'+storedType,dir=path.join(APPS_ROOT(),id);fs.mkdirSync(dir,{recursive:true});
+ fs.writeFileSync(path.join(dir,'index.html'),'<h1>Retained</h1>');
+ const savedMeta=path.join(dir,'__orkas-meta.json');
+ fs.writeFileSync(savedMeta,JSON.stringify({title:'Retained',appType:storedType,sourceCid:CID,sourceArtifactId:created.artifactId,savedAt:'2026-10-01T00:00:00Z'}));
+ const savedBefore=fs.readFileSync(savedMeta);
+ expect(savedApps.listSavedApps(UID).find(app=>app.id===id)?.appType).toBe('web');
+ expect(await savedApps.openForEditing(UID,id)).toMatchObject({ok:false,code:'E_COMMERCIAL_REQUIRED',feature:'web_apps'});
+ expect(fs.readFileSync(metadata)).toEqual(before);expect(fs.readFileSync(savedMeta)).toEqual(savedBefore);
+ });
+ it('recovers an interrupted local replacement to the original and preserves revised binary bytes on later saves',async()=>{
+ const {savedApps,chatArtifacts}=await mods();
+ const original=await savedApps.saveFromArtifact(UID,CID,await makeArtifact('Original'));
+ if(!original.ok)throw new Error(original.error);
+ const edit=await savedApps.openForEditing(UID,original.id);if(!edit.ok)throw new Error(edit.error);
+ const cid=(edit.conversation as any).conversation_id;
+ const edits=path.join(tmpDir,UID,'local','app-edits',cid);
+ const context=JSON.parse(fs.readFileSync(path.join(edits,'context.json'),'utf8'));
+ const temporary=original.id+'.tmp-12345678';
+ fs.writeFileSync(path.join(edits,'save-journal.json'),JSON.stringify({version:1,appId:original.id,temporary,before:context.fingerprint,after:'a'.repeat(64)}));
+ fs.renameSync(path.join(APPS_ROOT(),original.id),path.join(APPS_ROOT(),temporary+'.previous'));
+ expect(savedApps.listSavedApps(UID).map(app=>app.id)).toContain(original.id);
+ expect(fs.existsSync(path.join(edits,'save-journal.json'))).toBe(false);
+ const revised=await chatArtifacts.createArtifact(UID,cid,'helper',{files:[{path:'index.html',content:'<img src="image.png">'},
+ {path:'image.png',encoding:'base64',content:Buffer.from([5,4,3,2]).toString('base64')}]});
+ if(!revised.ok)throw new Error(revised.error);
+ expect((await savedApps.saveFromArtifact(UID,cid,revised.artifactId,'update')).ok).toBe(true);
+ const later=await chatArtifacts.createArtifact(UID,cid,'helper',{files:[{path:'index.html',content:'<h1>Later</h1><img src="image.png">'}]});
+ if(!later.ok)throw new Error(later.error);
+ expect((await savedApps.saveFromArtifact(UID,cid,later.artifactId,'update')).ok).toBe(true);
+ expect(fs.readFileSync(path.join(APPS_ROOT(),original.id,'image.png'))).toEqual(Buffer.from([5,4,3,2]));
+ });
+ it('updates an edited original with its stable ID and retained binary bytes, while save-new stays independent', async () => {
+ const { savedApps, chatArtifacts } = await mods();
+ const artifact = await chatArtifacts.createArtifact(UID,CID,'helper',{title:'Original',files:[
+ {path:'index.html',content:'<img src="assets/icon.png"><h1>Original</h1>'},
+ {path:'assets/icon.png',content:Buffer.from([0,1,2,255]).toString('base64'),encoding:'base64'},
+ {path:'obsolete.css',content:'body{color:red}'},
+ ]});
+ if (!artifact.ok) throw new Error(artifact.error);
+ const original = await savedApps.saveFromArtifact(UID,CID,artifact.artifactId);
+ if (!original.ok) throw new Error(original.error);
+ const edit = await savedApps.openForEditing(UID,original.id);
+ if (!edit.ok) throw new Error(edit.error);
+ const cid=(edit.conversation as any).conversation_id;
+ const revised=await chatArtifacts.createArtifact(UID,cid,'helper',{title:'Revised',files:[{path:'index.html',content:'<img src="assets/icon.png"><h1>Revised</h1>'}]});
+ if (!revised.ok) throw new Error(revised.error);
+ expect(await savedApps.getEditTarget(UID,cid)).toEqual({appId:original.id,title:'Original',appType:'local'});
+ const copy=await savedApps.saveFromArtifact(UID,cid,revised.artifactId,'new');
+ if (!copy.ok) throw new Error(copy.error);
+ expect(copy.id).not.toBe(original.id);
+ expect(fs.readFileSync(path.join(APPS_ROOT(),original.id,'index.html'),'utf8')).toContain('Original');
+ expect(fs.readFileSync(path.join(APPS_ROOT(),copy.id,'assets/icon.png'))).toEqual(Buffer.from([0,1,2,255]));
+ vi.resetModules();
+ (await import('../../../src/main/features/users')).activateUser(UID);
+ const reloaded=await import('../../../src/main/features/saved_apps');
+ const updated=await reloaded.saveFromArtifact(UID,cid,revised.artifactId,'update');
+ expect(updated).toMatchObject({ok:true,id:original.id,title:'Revised'});
+ expect(fs.readFileSync(path.join(APPS_ROOT(),original.id,'index.html'),'utf8')).toContain('Revised');
+ expect(fs.readFileSync(path.join(APPS_ROOT(),original.id,'assets/icon.png'))).toEqual(Buffer.from([0,1,2,255]));
+ expect(fs.existsSync(path.join(APPS_ROOT(),original.id,'obsolete.css'))).toBe(false);
+ expect(await reloaded.getEditTarget('another-account',cid)).toBeNull();
+ });
+ it('refuses stale edit and deleted targets without destroying the newer saved application', async () => {
+ const {savedApps,chatArtifacts}=await mods();
+ const original=await savedApps.saveFromArtifact(UID,CID,await makeArtifact('Original'));
+ if(!original.ok)throw new Error(original.error);
+ const edit=await savedApps.openForEditing(UID,original.id);
+ if(!edit.ok)throw new Error(edit.error);
+ const cid=(edit.conversation as any).conversation_id;
+ const revised=await chatArtifacts.createArtifact(UID,cid,'helper',{files:[{path:'index.html',content:'Changed'}]});
+ if(!revised.ok)throw new Error(revised.error);
+ savedApps.renameSavedApp(UID,original.id,'Newer name');
+ expect(await savedApps.saveFromArtifact(UID,cid,revised.artifactId,'update')).toEqual({ok:false,error:'app_edit_conflict'});
+ expect(fs.readFileSync(path.join(APPS_ROOT(),original.id,'index.html'),'utf8')).toContain('Original');
+ expect(savedApps.listSavedApps(UID)[0].title).toBe('Newer name');
+ await savedApps.deleteSavedApp(UID,original.id);
+ expect(await savedApps.saveFromArtifact(UID,cid,revised.artifactId,'update')).toEqual({ok:false,error:'app_edit_target_missing'});
+ expect(fs.readdirSync(APPS_ROOT())).toEqual([]);
+ });
it('finds a deeply nested source inside its workspace without crossing the workspace fence', async () => {
const workspace = path.join(tmpDir, 'workspace', 'deep-app');
const entry = path.join(workspace, 'index.html');
@@ -67,7 +262,7 @@ describe('saved_apps › saveFromArtifact', () => {
fs.writeFileSync(entry, '<!doctype html><h1>Deep app</h1>');
fs.writeFileSync(script, 'window.deepApp = true;');
const { savedApps } = await mods();
- const saved = await savedApps.saveFromPath(UID, script, { fenceRoots: [workspace] });
+ const saved = await savedApps.saveFromPath(UID, script, { fenceRoots: [path.dirname(workspace)] });
if (!saved.ok) throw new Error(saved.error);
const resource = savedApps.resolveSavedAppFilePath(UID, saved.id, path.relative(workspace, script).split(path.sep).join('/'));
if (!resource.ok) throw new Error(resource.error);
@@ -134,7 +329,138 @@ describe('saved_apps › saveFromArtifact', () => {
});
});
+describe('saved_apps › interrupted code and data replacement', () => {
+ const notes: any = { version: 1, tables: [{ id: 'notes', name: 'notes', fields: [{ id: 'body', name: 'body', type: 'string' }], access: { read: ['body'], insert: ['body'] } }] };
+ const grown: any = structuredClone(notes);
+ grown.tables[0].fields.push({ id: 'tag', name: 'tag', type: 'string', default: 'new' }); grown.tables[0].access.read.push('tag');
+ const declaration = (data: any, title: string) => [{ path: 'index.html', content: `<h1>${title}</h1>` }, { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['data'], data }) }];
+
+ // Renames 1-4 are: original code -> backup, new code -> original, records ->
+ // .previous, migrated candidate -> records. A crash leaves later steps undone.
+ it.each([1, 2, 3, 4])('recovers a consistent code and records pair after the process stops at swap rename %i', async crashAt => {
+ const { chatArtifacts, savedApps } = await mods();
+ const original = await chatArtifacts.createArtifact(UID, CID, 'helper', { files: declaration(notes, 'Original') });
+ if (!original.ok) throw new Error(original.error);
+ const kept = await savedApps.saveFromArtifact(UID, CID, original.artifactId);
+ if (!kept.ok) throw new Error(kept.error);
+ const key = crypto.createHash('sha256').update(JSON.stringify(['saved', kept.id])).digest('hex');
+ const userRoot = path.join(tmpDir, UID), dataDir = path.join(userRoot, 'local/web_apps', key), file = path.join(dataDir, 'data.sqlite');
+ const { LocalAppData } = await import('../../../src/main/features/web_apps/data');
+ const seed = new LocalAppData(file, path.join(userRoot, 'local'), notes);
+ try { await seed.call('data.insert', { table: 'notes', values: { body: 'KEEP' } }); } finally { await seed.close(); }
+ const edit = await savedApps.openForEditing(UID, kept.id);
+ if (!edit.ok) throw new Error(edit.error);
+ const cid = (edit.conversation as any).conversation_id;
+ const journal = path.join(userRoot, 'local/app-edits', cid, 'save-journal.json');
+ const revised = await chatArtifacts.createArtifact(UID, cid, 'helper', { files: declaration(grown, 'Revised') });
+ if (!revised.ok) throw new Error(revised.error);
+
+ const nodeFs = (await import('node:fs')).default, { syncBuiltinESMExports } = await import('node:module');
+ const fsp = await import('node:fs/promises');
+ const real = { renameSync: nodeFs.renameSync, rmSync: nodeFs.rmSync, existsSync: nodeFs.existsSync };
+ const { rm } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ let renames = 0, stopped = false;
+ const owned = (target: unknown) => String(target).startsWith(userRoot + path.sep);
+ const halt = () => Object.assign(new Error('process stopped'), { code: 'EIO' });
+ // After the crash point nothing else in this process may touch the user's files.
+ const spies = [
+ vi.spyOn(nodeFs, 'renameSync').mockImplementation((from: any, to: any) => {
+ if (stopped && owned(from)) throw halt();
+ real.renameSync(from, to);
+ if (owned(from) && real.existsSync(journal) && ++renames === crashAt) { stopped = true; throw halt(); }
+ }),
+ vi.spyOn(nodeFs, 'rmSync').mockImplementation((target: any, options?: any) => { if (stopped && owned(target)) throw halt(); return real.rmSync(target, options); }),
+ vi.spyOn(nodeFs, 'existsSync').mockImplementation((target: any) => { if (stopped && owned(target)) throw halt(); return real.existsSync(target); }),
+ vi.spyOn(fsp, 'rm').mockImplementation(async (target: any, options?: any) => { if (stopped && owned(target)) throw halt(); return rm(target, options); }),
+ ];
+ syncBuiltinESMExports();
+ try { expect((await savedApps.saveFromArtifact(UID, cid, revised.artifactId, 'update')).ok).toBe(false); }
+ finally { for (const spy of spies) spy.mockRestore(); syncBuiltinESMExports(); }
+ expect(stopped).toBe(true);
+ // The interruption left a pending journal and a mixed on-disk state.
+ expect(fs.existsSync(journal)).toBe(true);
+ const entry = path.join(APPS_ROOT(), kept.id, 'index.html');
+ expect(fs.existsSync(entry) ? fs.readFileSync(entry, 'utf8') : '').not.toContain('Original');
+
+ // Restart: a fresh module graph runs journal recovery on the next listing.
+ vi.resetModules(); (await import('../../../src/main/features/users')).activateUser(UID);
+ const restarted = await mods();
+ expect(restarted.savedApps.listSavedApps(UID).map(app => app.id)).toContain(kept.id);
+ const committed = crashAt === 4;
+ expect(fs.readFileSync(path.join(APPS_ROOT(), kept.id, 'index.html'), 'utf8')).toContain(committed ? 'Revised' : 'Original');
+ const Database = (await import('better-sqlite3')).default, raw = new Database(file, { readonly: true });
+ try { expect(JSON.parse(raw.prepare("SELECT value FROM _meta WHERE key='definition'").get().value)).toEqual(committed ? grown : notes); }
+ finally { raw.close(); }
+ const reader = new LocalAppData(file, path.join(userRoot, 'local'), committed ? grown : notes);
+ try { expect(await reader.call('data.query', { table: 'notes' })).toEqual({ records: [committed ? { body: 'KEEP', tag: 'new' } : { body: 'KEEP' }] }); }
+ finally { await reader.close(); }
+ expect(fs.readdirSync(APPS_ROOT()).filter(name => name !== kept.id)).toEqual([]);
+ expect(fs.readdirSync(dataDir).filter(name => name.includes('.previous') || name.includes('.backup-'))).toEqual([]);
+ expect(fs.existsSync(journal)).toBe(false);
+ if (!committed) {
+ // The user's retry completes the interrupted update.
+ expect((await restarted.savedApps.saveFromArtifact(UID, cid, revised.artifactId, 'update')).ok).toBe(true);
+ expect(fs.readFileSync(path.join(APPS_ROOT(), kept.id, 'index.html'), 'utf8')).toContain('Revised');
+ }
+ });
+});
+
describe('saved_apps › saveFromPath', () => {
+ it('refuses the workspace bundle before copying unrelated files and recovers after moving the app into its own folder', async () => {
+ const { savedApps } = await mods();
+ const root=path.join(tmpDir,'workspace');fs.mkdirSync(root);
+ fs.writeFileSync(path.join(root,'index.html'),'<h1>Tool</h1>');
+ fs.writeFileSync(path.join(root,'style.css'),'body { color: blue; }');
+ fs.writeFileSync(path.join(root,'customers.csv'),'private customer data');
+ fs.mkdirSync(path.join(root,'assets'));fs.writeFileSync(path.join(root,'assets','app.js'),'window.tool=true;');
+ const opts={fenceRoots:[root]};
+ for(const target of [root,path.join(root,'index.html'),path.join(root,'assets','app.js')]){
+ expect(await savedApps.inspectBundleFromPath(target,opts)).toMatchObject({ok:true,canSave:false,reason:'app_bundle_root'});
+ expect(await savedApps.saveFromPath(UID,target,opts)).toEqual({ok:false,error:'app_bundle_root'});
+ }
+ const alias=path.join(root,'alias');fs.symlinkSync(root,alias,'dir');
+ expect(await savedApps.saveFromPath(UID,path.join(alias,'index.html'),opts)).toEqual({ok:false,error:'app_bundle_root'});
+ expect(savedApps.listSavedApps(UID)).toEqual([]);
+ expect(fs.existsSync(APPS_ROOT())?fs.readdirSync(APPS_ROOT()):[]).toEqual([]);
+ expect(fs.readFileSync(path.join(root,'customers.csv'),'utf8')).toBe('private customer data');
+ const app=path.join(root,'tool');fs.mkdirSync(app);
+ for(const name of ['index.html','style.css','assets'])fs.renameSync(path.join(root,name),path.join(app,name));
+ const saved=await savedApps.saveFromPath(UID,path.join(app,'index.html'),opts);
+ if(!saved.ok)throw new Error(saved.error);
+ expect(saved.fileCount).toBe(3);
+ expect(fs.readdirSync(path.join(APPS_ROOT(),saved.id)).sort()).toEqual(['__orkas-meta.json','assets','index.html','style.css']);
+ expect(savedApps.resolveSavedAppIndex(UID,saved.id).ok).toBe(true);
+ });
+
+ it('keeps the HTML description across saving, renaming and listing without requiring it on legacy apps', async () => {
+ const root = path.join(tmpDir, 'described-app');
+ fs.mkdirSync(root);
+ const entry = path.join(root, 'index.html');
+ fs.writeFileSync(entry, '<head><meta content="Track orders &amp; stock" name="description"><title>Inventory</title></head>');
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromPath(UID, entry, { fenceRoots: [path.dirname(root)] });
+ if (!saved.ok) throw new Error(saved.error);
+ expect(savedApps.listSavedApps(UID).find(app => app.id === saved.id)).toMatchObject({ description: 'Track orders & stock' });
+ expect(savedApps.renameSavedApp(UID, saved.id, 'Orders').ok).toBe(true);
+ expect(savedApps.listSavedApps(UID).find(app => app.id === saved.id)).toMatchObject({ title: 'Orders', description: 'Track orders & stock' });
+ const legacy = await makeArtifact('Legacy app');
+ const kept = await savedApps.saveFromArtifact(UID, CID, legacy);
+ if (!kept.ok) throw new Error(kept.error);
+ expect(savedApps.listSavedApps(UID).find(app => app.id === kept.id)?.description).toBe('');
+ });
+
+ it('uses real HTML metadata rather than commented or scripted look-alikes for artifact descriptions', async () => {
+ const { savedApps, chatArtifacts } = await mods();
+ const artifact = await chatArtifacts.createArtifact(UID, CID, 'helper', { files: [{ path: 'index.html', content:
+ '<head><!-- <meta name="description" content="Wrong comment"> --><script>const sample = `<meta name="description" content="Wrong script">`;</script>'
+ + '<META NAME=description CONTENT="Review &#x41; &lt;img src=x onerror=alert(1)&gt;"></head><h1>Review</h1>',
+ }] });
+ if (!artifact.ok) throw new Error(artifact.error);
+ const saved = await savedApps.saveFromArtifact(UID, CID, artifact.artifactId);
+ if (!saved.ok) throw new Error(saved.error);
+ expect(savedApps.listSavedApps(UID).find(app => app.id === saved.id)?.description).toBe('Review A <img src=x onerror=alert(1)>');
+ });
+
it('saves the whole app bundle when given a nested resource file', async () => {
const root = path.join(tmpDir, 'workspace', 'snake');
fs.mkdirSync(path.join(root, 'assets'), { recursive: true });
@@ -345,7 +671,7 @@ describe('saved_apps › saveFromPath', () => {
const { savedApps } = await mods();
let ticks = 0;
const timer = setInterval(() => { ticks++; }, 0);
- const r = await savedApps.saveFromPath(UID, root, { fenceRoots: [root] });
+ const r = await savedApps.saveFromPath(UID, root, { fenceRoots: [path.dirname(root)] });
clearInterval(timer);
expect(r.ok).toBe(true);
if (!r.ok) throw new Error(r.error);
@@ -398,7 +724,9 @@ describe('saved_apps › resolveSavedAppIndex', () => {
expect(resolved.ok).toBe(true);
if (resolved.ok) expect(resolved.absPath).toBe(path.join(dir, 'index.html'));
const edit = await savedApps.openForEditing(UID, saved.id);
- expect(edit.ok).toBe(true);
+ expect(edit.ok).toBe(false);
+ fs.unlinkSync(path.join(dir, '__orkas-meta.json'));
+ expect(await savedApps.openForEditing(UID, saved.id)).toMatchObject({ ok: true });
});
});
@@ -481,6 +809,23 @@ describe('saved_apps › rename / delete', () => {
expect(meta.title).toBe('New name');
});
+ it('deleting an open saved app closes its database and removes private data without deleting another app',async()=>{
+ const {savedApps}=await mods();const artifact=await makeArtifact('Delete data');const saved=await savedApps.saveFromArtifact(UID,CID,artifact);if(!saved.ok)throw new Error(saved.error);
+ const key=crypto.createHash('sha256').update(JSON.stringify(['saved',saved.id])).digest('hex'),definition:any={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]};
+ const {WebAppRuntime}=await import('../../../src/main/features/web_apps/runtime');const runtime=new WebAppRuntime({activeUser:()=>UID,language:()=> 'en',modelAvailable:()=>false} as any);
+ const app=runtime.open(UID,123,{key,title:'Delete data',entry:'index.html',appType:'local',manifest:{sdkVersion:1,capabilities:['data'],data:definition},resolve:()=>null});
+ await runtime.call(UID,123,app.token,'insert','data.insert',{table:'notes',values:{body:'private'}});
+ const local=path.join(tmpDir,UID,'local/web_apps',key),cloud=path.join(tmpDir,UID,'cloud/web_apps',key);fs.mkdirSync(cloud,{recursive:true});fs.writeFileSync(path.join(cloud,'private.txt'),'private');
+ const other=path.join(tmpDir,UID,'local/web_apps','d'.repeat(64));fs.mkdirSync(other,{recursive:true});fs.writeFileSync(path.join(other,'keep'),'keep');
+ let entered!:()=>void,release!:()=>void;const draining=new Promise<void>(resolve=>entered=resolve),resume=new Promise<void>(resolve=>release=resolve);
+ const realDrain=runtime.drainData.bind(runtime);vi.spyOn(runtime,'drainData').mockImplementationOnce(async()=>{entered();await resume;await realDrain();});
+ const deleting=savedApps.deleteSavedApp(UID,saved.id);let result;
+ try{await draining;expect(()=>runtime.open(UID,124,{key,title:'Concurrent opening',entry:'index.html',appType:'local',manifest:{sdkVersion:1,capabilities:['data'],data:definition},resolve:()=>null})).toThrowError('E_BUSY');
+ const unrelated=runtime.open(UID,125,{key:'d'.repeat(64),title:'Other app',entry:'index.html',appType:'local',manifest:{sdkVersion:1,capabilities:[]},resolve:()=>null});expect(unrelated.token).toBeTruthy();runtime.close(UID,125,unrelated.token);
+ }finally{release();result=await deleting;}
+ expect(result.ok).toBe(true);await runtime.drainData();expect(fs.existsSync(local)).toBe(false);expect(fs.existsSync(cloud)).toBe(false);expect(fs.readFileSync(path.join(other,'keep'),'utf8')).toBe('keep');
+ await expect(runtime.call(UID,123,app.token,'query','data.query',{table:'notes'})).rejects.toBeInstanceOf(Error);
+ });
it('deleteSavedApp removes the directory', async () => {
const aid = await makeArtifact('Doomed');
const { savedApps } = await mods();
@@ -488,12 +833,12 @@ describe('saved_apps › rename / delete', () => {
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((await 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);
+ expect((await savedApps.deleteSavedApp(UID, saved.id)).ok).toBe(true);
// Bad id is refused.
- expect(savedApps.deleteSavedApp(UID, '../boom').ok).toBe(false);
+ expect((await savedApps.deleteSavedApp(UID, '../boom')).ok).toBe(false);
});
it('does not rename metadata through a symlinked saved-app directory', async () => {
@@ -521,6 +866,37 @@ describe('saved_apps › rename / delete', () => {
});
describe('saved_apps › listSavedApps', () => {
+ it('keeps private malformed metadata excerpts out of diagnostics and retains the recoverable app', async () => {
+ const logging = await import('../../../src/main/logger');
+ const createLogger = logging.createLogger;
+ const warnings: unknown[][] = [];
+ const loggerSpy = vi.spyOn(logging, 'createLogger').mockImplementation(module => {
+ const logger = createLogger(module);
+ if (module !== 'saved_apps') return logger;
+ return { ...logger, warn: (message: string, ...args: unknown[]) => {
+ warnings.push([message, ...args]);
+ logger.warn(message, ...args);
+ } };
+ });
+ try {
+ const { savedApps, chatArtifacts } = await mods();
+ const artifact = await chatArtifacts.createArtifact(UID, CID, 'helper', { appType: 'local',
+ files: [{ path: 'index.html', content: '<h1>Recoverable local app</h1>' }] });
+ if (!artifact.ok) throw new Error(artifact.error);
+ const saved = await savedApps.saveFromArtifact(UID, CID, artifact.artifactId);
+ if (!saved.ok) throw new Error(saved.error);
+ expect(savedApps.listSavedApps(UID)[0].appType).toBe('local');
+ fs.writeFileSync(path.join(APPS_ROOT(), saved.id, '__orkas-meta.json'), 'PRIVATE123 customer metadata');
+ const recovered = savedApps.listSavedApps(UID);
+ expect(recovered).toEqual([expect.objectContaining({ id: saved.id, title: 'Interactive app' })]);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0][0]).toBe('listSavedApps bad meta skipped');
+ expect(JSON.stringify(warnings)).not.toContain('PRIVATE');
+ expect((warnings[0][1] as any).error).toMatchObject({ name: 'SyntaxError', message_hash: expect.any(String) });
+ expect(fs.readFileSync(path.join(APPS_ROOT(), saved.id, '__orkas-meta.json'), 'utf8')).toBe('PRIVATE123 customer metadata');
+ } finally { loggerSpy.mockRestore(); }
+ });
+
it('lists newest saves first, uses a stable tie-break, and puts missing times last', async () => {
const { savedApps } = await mods();
const saves = await Promise.all(['Older alpha', 'Newest Zebra', 'Tie gamma', 'Tie beta', 'Corrupt'].map(async (title) => {
@@ -692,3 +1068,346 @@ describe('saved_apps › openForEditing', () => {
expect((await chats.listConversations(UID)).length).toBe(before);
});
});
+
+describe('saved_apps › failure consistency and redacted errors', () => {
+ const PRIVATE = '/Users/test/secret-folder';
+ const fault = (code: string) => Object.assign(new Error(`${code}: operation failed, '${PRIVATE}/x'`), { code });
+
+ it('reports a failed save with a stable code and no private path, leaving no card or staging folder', async () => {
+ const { savedApps } = await mods();
+ const aid = await makeArtifact('Disk full');
+ const fsp = await import('node:fs/promises');
+ const { rename } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ const spy = vi.spyOn(fsp, 'rename').mockImplementation(async (from, to) => {
+ if (String(from).includes('.tmp-')) throw fault('ENOSPC');
+ return rename(from, to);
+ });
+ try {
+ const result = await savedApps.saveFromArtifact(UID, CID, aid);
+ expect(result).toEqual({ ok: false, error: 'app_save_failed' });
+ } finally { spy.mockRestore(); }
+ expect(savedApps.listSavedApps(UID)).toEqual([]);
+ expect(fs.existsSync(APPS_ROOT()) ? fs.readdirSync(APPS_ROOT()) : []).toEqual([]);
+ });
+
+ it('keeps metadata intact when a rename write fails midway', async () => {
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Stable title'));
+ if (!saved.ok) throw new Error(saved.error);
+ const dir = path.join(APPS_ROOT(), saved.id), metaFile = path.join(dir, '__orkas-meta.json'), before = fs.readFileSync(metaFile, 'utf8');
+ const nodeFs = (await import('node:fs')).default, { syncBuiltinESMExports } = await import('node:module');
+ const writeFileSync = nodeFs.writeFileSync;
+ const spy = vi.spyOn(nodeFs, 'writeFileSync').mockImplementation(((file: any, data: any, options?: any) => {
+ // A full disk truncates the destination, writes a prefix, then fails.
+ if (String(file).startsWith(path.join(dir, '__orkas-meta.json'))) { writeFileSync(file, String(data).slice(0, 5), options); throw fault('ENOSPC'); }
+ return writeFileSync(file, data, options);
+ }) as any);
+ syncBuiltinESMExports();
+ let result: any;
+ try { result = savedApps.renameSavedApp(UID, saved.id, 'Renamed'); } finally { spy.mockRestore(); syncBuiltinESMExports(); }
+ expect(result).toEqual({ ok: false, error: 'app_rename_failed' });
+ expect(fs.readFileSync(metaFile, 'utf8')).toBe(before);
+ expect(fs.readdirSync(dir).sort()).toEqual(['__orkas-meta.json', 'index.html']);
+ expect(savedApps.listSavedApps(UID).find(app => app.id === saved.id)?.title).toBe('Stable title');
+ });
+
+ it('sweeps interrupted staging folders without following links or touching a save in progress', async () => {
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Kept'));
+ if (!saved.ok) throw new Error(saved.error);
+ const leftover = path.join(APPS_ROOT(), `${saved.id}.tmp-deadbeef`), outside = path.join(tmpDir, 'outside-staging');
+ fs.mkdirSync(leftover); fs.writeFileSync(path.join(leftover, 'index.html'), '<h1>partial</h1>');
+ fs.mkdirSync(outside); fs.writeFileSync(path.join(outside, 'keep.txt'), 'keep');
+ const linked = path.join(APPS_ROOT(), 'Linked.tmp-cafebabe'); fs.symlinkSync(outside, linked, 'dir');
+ const unrelated = path.join(APPS_ROOT(), 'notes.tmp-backup'); fs.mkdirSync(unrelated);
+ const fsp = await import('node:fs/promises');
+ const { cp } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ let entered!: (target: string) => void, release!: () => void;
+ const copying = new Promise<string>(resolve => { entered = resolve; }), resume = new Promise<void>(resolve => { release = resolve; });
+ const spy = vi.spyOn(fsp, 'cp').mockImplementation(async (from: any, to: any, options?: any) => {
+ await cp(from, to, options);
+ if (String(to).includes('.tmp-')) { entered(String(to)); await resume; }
+ });
+ const pending = savedApps.saveFromArtifact(UID, CID, await makeArtifact('In progress'));
+ const inProgress = await copying;
+ try {
+ expect(savedApps.listSavedApps(UID).map(app => app.id)).toEqual([saved.id]);
+ await vi.waitFor(() => expect(fs.existsSync(leftover)).toBe(false));
+ expect(fs.existsSync(inProgress)).toBe(true);
+ } finally { release(); spy.mockRestore(); }
+ const second = await pending;
+ if (!second.ok) throw new Error(second.error);
+ expect(savedApps.listSavedApps(UID).map(app => app.id).sort()).toEqual([saved.id, second.id].sort());
+ expect(fs.lstatSync(linked).isSymbolicLink()).toBe(true);
+ expect(fs.readFileSync(path.join(outside, 'keep.txt'), 'utf8')).toBe('keep');
+ expect(fs.existsSync(unrelated)).toBe(true);
+ });
+
+ it('leaves the app intact when its data cannot be removed, then completes the delete on retry', async () => {
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Delete later'));
+ if (!saved.ok) throw new Error(saved.error);
+ const key = crypto.createHash('sha256').update(JSON.stringify(['saved', saved.id])).digest('hex');
+ const local = path.join(tmpDir, UID, 'local/web_apps', key);
+ fs.mkdirSync(local, { recursive: true }); fs.writeFileSync(path.join(local, 'data.sqlite'), 'records');
+ const fsp = await import('node:fs/promises');
+ const { rm } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ const spy = vi.spyOn(fsp, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === local) throw fault('EBUSY');
+ return rm(target, options);
+ });
+ let failed: any;
+ try { failed = await savedApps.deleteSavedApp(UID, saved.id); } finally { spy.mockRestore(); }
+ expect(failed).toEqual({ ok: false, error: 'app_delete_failed' });
+ expect(savedApps.listSavedApps(UID).map(app => app.id)).toEqual([saved.id]);
+ expect(fs.readFileSync(path.join(APPS_ROOT(), saved.id, 'index.html'), 'utf8')).toContain('Delete later');
+ expect(fs.readdirSync(APPS_ROOT())).toEqual([saved.id]);
+ expect(await savedApps.deleteSavedApp(UID, saved.id)).toEqual({ ok: true });
+ expect(fs.existsSync(path.join(APPS_ROOT(), saved.id))).toBe(false);
+ expect(fs.existsSync(local)).toBe(false);
+ expect(fs.readdirSync(APPS_ROOT())).toEqual([]);
+ });
+
+ // Regression doc 数据边界 4 / 联动 5: an interrupted workspace copy leaves no card, staging folder or
+ // source change, and a completed save is an independent copy that survives source removal.
+ const tree = (root: string) => Object.fromEntries(fs.readdirSync(root, { recursive: true }).map(String).sort()
+ .filter(rel => fs.statSync(path.join(root, rel)).isFile())
+ .map(rel => [rel, crypto.createHash('sha256').update(fs.readFileSync(path.join(root, rel))).digest('hex')]));
+ const workspaceApp = (name: string) => {
+ const root = path.join(tmpDir, 'workspace', name);
+ fs.mkdirSync(path.join(root, 'assets'), { recursive: true });
+ fs.writeFileSync(path.join(root, 'game.html'), '<!doctype html><title>Copy game</title><link rel="stylesheet" href="style.css"><script src="assets/app.js"></script>');
+ fs.writeFileSync(path.join(root, 'style.css'), 'body { color: teal; }');
+ fs.writeFileSync(path.join(root, 'assets', 'app.js'), 'window.copyGame = 1;');
+ fs.writeFileSync(path.join(root, 'assets', 'logo.png'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 255]));
+ return root;
+ };
+
+ it('fails a workspace save cleanly when copying the second file fails', async () => {
+ const { savedApps } = await mods();
+ const existing = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Existing app'));
+ if (!existing.ok) throw new Error(existing.error);
+ const before = savedApps.listSavedApps(UID);
+ const root = workspaceApp('copy-fault'), sourceBefore = tree(root);
+ const fsp = await import('node:fs/promises');
+ const { copyFile } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ let copies = 0;
+ const spy = vi.spyOn(fsp, 'copyFile').mockImplementation(async (from, to, mode) => {
+ if (++copies === 2) throw fault('ENOSPC');
+ return copyFile(from, to, mode);
+ });
+ let result: any;
+ try { result = await savedApps.saveFromPath(UID, path.join(root, 'game.html'), { fenceRoots: [path.join(tmpDir, 'workspace')] }); }
+ finally { spy.mockRestore(); }
+ expect(copies).toBe(2);
+ expect(result).toEqual({ ok: false, error: 'app_save_failed' });
+ expect(JSON.stringify(result)).not.toContain(PRIVATE);
+ expect(fs.readdirSync(APPS_ROOT())).toEqual([existing.id]);
+ expect(savedApps.listSavedApps(UID)).toEqual(before);
+ expect(tree(root)).toEqual(sourceBefore);
+ });
+
+ it('keeps a workspace-saved app openable with its assets after the source folder is deleted', async () => {
+ const { savedApps } = await mods();
+ const root = workspaceApp('removed-source'), source = Object.fromEntries(
+ ['game.html', 'style.css', 'assets/app.js', 'assets/logo.png'].map(rel => [rel, fs.readFileSync(path.join(root, rel))]));
+ const saved = await savedApps.saveFromPath(UID, path.join(root, 'style.css'), { fenceRoots: [path.join(tmpDir, 'workspace')] });
+ if (!saved.ok) throw new Error(saved.error);
+ fs.rmSync(root, { recursive: true, force: true });
+ expect(savedApps.listSavedApps(UID).map(app => [app.id, app.title])).toEqual([[saved.id, 'Copy game']]);
+ const entry = savedApps.resolveSavedAppIndex(UID, saved.id);
+ if (!entry.ok) throw new Error(entry.error);
+ expect(fs.readFileSync(entry.absPath)).toEqual(source['game.html']);
+ for (const [rel, bytes] of Object.entries(source)) {
+ const resolved = savedApps.resolveSavedAppFilePath(UID, saved.id, rel);
+ if (!resolved.ok) throw new Error(resolved.error);
+ expect(resolved.absPath.startsWith(path.join(APPS_ROOT(), saved.id) + path.sep)).toBe(true);
+ expect(fs.readFileSync(resolved.absPath)).toEqual(bytes);
+ }
+ });
+
+ it('returns a redacted edit failure when rollback of the new conversation also fails', async () => {
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Rollback'));
+ if (!saved.ok) throw new Error(saved.error);
+ const chats = await import('../../../src/main/features/chats');
+ const fsp = await import('node:fs/promises');
+ const copy = vi.spyOn(fsp, 'cp').mockRejectedValue(fault('ENOSPC'));
+ const removal = vi.spyOn(chats, 'deleteConversation').mockRejectedValue(fault('EACCES'));
+ try {
+ expect(await savedApps.openForEditing(UID, saved.id)).toEqual({ ok: false, error: 'app_edit_snapshot_failed' });
+ expect(removal).toHaveBeenCalledOnce();
+ } finally { copy.mockRestore(); removal.mockRestore(); }
+ });
+});
+
+// A crash while deleting a saved app must not strand its private data forever,
+// and recovery must never delete data that merely lacks a local app folder
+// (an app still arriving through personal sync, or data of another device).
+describe('saved_apps › delete interrupted by a process stop', () => {
+ const dataKey = (appId: string) => crypto.createHash('sha256').update(JSON.stringify(['saved', appId])).digest('hex');
+ const dataRoots = (key: string) => ({ local: path.join(tmpDir, UID, 'local/web_apps', key), cloud: path.join(tmpDir, UID, 'cloud/web_apps', key) });
+ const seed = (key: string) => {
+ const roots = dataRoots(key);
+ fs.mkdirSync(roots.local, { recursive: true }); fs.writeFileSync(path.join(roots.local, 'data.sqlite'), 'records');
+ fs.mkdirSync(path.join(roots.cloud, 'files'), { recursive: true }); fs.writeFileSync(path.join(roots.cloud, 'state.json'), '{}');
+ fs.writeFileSync(path.join(roots.cloud, 'files', 'note.txt'), 'note');
+ return roots;
+ };
+ async function restart() {
+ vi.resetModules();
+ (await import('../../../src/main/features/users')).activateUser(UID);
+ return (await import('../../../src/main/features/saved_apps'));
+ }
+
+ it.each(['after moving the app folder aside', 'after removing part of its data'] as const)(
+ 'completes a delete that stopped %s on the next listing, keeping unrelated data', async stage => {
+
+
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Interrupted delete'));
+ const kept = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Kept app'));
+ if (!saved.ok || !kept.ok) throw new Error('save failed');
+ const doomed = seed(dataKey(saved.id)), keptData = seed(dataKey(kept.id));
+ // Data with no local app folder and no recorded delete: possibly an app still syncing in.
+ const orphanKey = dataKey('ArrivingFromSync'), orphan = seed(orphanKey);
+ const fsp = await import('node:fs/promises');
+ const { rm } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ const stopAt = stage === 'after moving the app folder aside' ? doomed.local : doomed.cloud;
+ let stopped!: () => void; const reached = new Promise<void>(resolve => { stopped = resolve; });
+ const halt = vi.spyOn(fsp, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === stopAt) { stopped(); return new Promise<void>(() => {}); } // the process stops here
+ return rm(target, options);
+ });
+ void savedApps.deleteSavedApp(UID, saved.id);
+ await reached; halt.mockRestore();
+ expect(fs.existsSync(path.join(APPS_ROOT(), saved.id))).toBe(false);
+ expect(fs.existsSync(doomed.cloud)).toBe(true);
+
+ const next = await restart();
+ expect(next.listSavedApps(UID).map(app => app.id)).toEqual([kept.id]);
+ await vi.waitFor(() => { expect(fs.existsSync(doomed.local)).toBe(false); expect(fs.existsSync(doomed.cloud)).toBe(false); });
+ for (const root of [keptData.local, keptData.cloud, orphan.local, orphan.cloud]) expect(fs.readdirSync(root).length).toBeGreaterThan(0);
+ expect(fs.readdirSync(APPS_ROOT()).sort()).toEqual([kept.id]);
+
+ // The recorded intent is cleared: another start repeats no deletion or tombstone.
+ const later = await restart();
+ expect(later.listSavedApps(UID).map(app => app.id)).toEqual([kept.id]);
+ await new Promise(resolve => setTimeout(resolve, 50));
+ for (const root of [keptData.local, keptData.cloud, orphan.local, orphan.cloud]) expect(fs.existsSync(root)).toBe(true);
+
+ });
+
+ it('leaves no delete intent after a completed or a failed delete', async () => {
+
+
+ const { savedApps } = await mods();
+ const done = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Deleted normally'));
+ const failed = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Delete fails'));
+ if (!done.ok || !failed.ok) throw new Error('save failed');
+ seed(dataKey(done.id)); const failedData = seed(dataKey(failed.id));
+ expect(await savedApps.deleteSavedApp(UID, done.id)).toEqual({ ok: true });
+ const fsp = await import('node:fs/promises');
+ const { rm } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ const spy = vi.spyOn(fsp, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === failedData.cloud) throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' });
+ return rm(target, options);
+ });
+ try { expect(await savedApps.deleteSavedApp(UID, failed.id)).toEqual({ ok: false, error: 'app_delete_failed' }); }
+ finally { spy.mockRestore(); }
+ // A later start neither re-deletes the completed app nor finishes the refused one.
+ const next = await restart();
+ expect(next.listSavedApps(UID).map(app => app.id)).toEqual([failed.id]);
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(fs.readFileSync(path.join(failedData.cloud, 'state.json'), 'utf8')).toBe('{}');
+ expect(fs.readFileSync(path.join(APPS_ROOT(), failed.id, 'index.html'), 'utf8')).toContain('Delete fails');
+
+ });
+});
+
+
+it.each([false, true])('keeps browser isolation identity on update and gives save-as-new its own identity (legacy=%s)', async legacy => {
+ const { savedApps, chatArtifacts } = await mods();
+ const artifactId = await makeArtifact('Original');
+ const saved = await savedApps.saveFromArtifact(UID, CID, artifactId);
+ if (!saved.ok) throw new Error(saved.error);
+ const metaFile = path.join(APPS_ROOT(), saved.id, '__orkas-meta.json');
+ expect(JSON.parse(fs.readFileSync(metaFile, 'utf8')).browserStorage).toBe('isolated-v1');
+ if (legacy) {
+ const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8')); delete meta.browserStorage;
+ fs.writeFileSync(metaFile, JSON.stringify(meta));
+ }
+ const edit = await savedApps.openForEditing(UID, saved.id);
+ if (!edit.ok) throw new Error(edit.error);
+ const cid = (edit.conversation as any).conversation_id;
+ const changed = await chatArtifacts.createArtifact(UID, cid, 'agent', { files: [{ path: 'index.html', content: '<h1>Updated</h1>' }] });
+ if (!changed.ok) throw new Error(changed.error);
+ expect(chatArtifacts.readArtifactMeta(UID, cid, changed.artifactId)).toMatchObject({ browserStorage: 'isolated-v1' });
+ expect(await savedApps.saveFromArtifact(UID, cid, changed.artifactId, 'update')).toMatchObject({ ok: true, id: saved.id });
+ expect(JSON.parse(fs.readFileSync(metaFile, 'utf8')).browserStorage).toBe(legacy ? undefined : 'isolated-v1');
+ const another = await savedApps.saveFromArtifact(UID, cid, changed.artifactId, 'new');
+ if (!another.ok) throw new Error(another.error);
+ expect(another.id).not.toBe(saved.id);
+ expect(JSON.parse(fs.readFileSync(path.join(APPS_ROOT(), another.id, '__orkas-meta.json'), 'utf8')).browserStorage).toBe('isolated-v1');
+});
+
+describe('editing snapshot retention', () => {
+ it('keeps a restorable edit, keeps a restored live edit, and purges only after the final archive is deleted', async () => {
+ const { savedApps } = await mods();
+ const chats = await import('../../../src/main/features/chats');
+ const recycle = await import('../../../src/main/features/recycle_bin');
+ const id = await makeArtifact('Retained edit');
+ const saved = await savedApps.saveFromArtifact(UID, CID, id);
+ if (!saved.ok) throw new Error(saved.error);
+ const edit = await savedApps.openForEditing(UID, saved.id);
+ if (!edit.ok) throw new Error(edit.error);
+ const cid = (edit.conversation as any).conversation_id;
+ const snapshot = path.join(tmpDir, UID, 'local/app-edits', cid, 'snapshot/index.html');
+ const contents = fs.readFileSync(snapshot, 'utf8');
+ expect((await savedApps.deleteSavedApp(UID, saved.id)).ok).toBe(true);
+ await savedApps.cleanupEditSnapshots(UID);
+ expect(fs.readFileSync(snapshot, 'utf8')).toBe(contents);
+ const first = await recycle.createAppRecycleBatchForConversation(UID, cid);
+ const second = await recycle.createAppRecycleBatchForConversation(UID, cid);
+ expect(first).toBeTruthy(); expect(second).toBeTruthy();
+ await chats.deleteConversation(UID, cid);
+ expect(fs.readFileSync(snapshot, 'utf8')).toBe(contents);
+ await recycle.deleteRecycleBatch(UID, first!.id);
+ expect(fs.existsSync(snapshot)).toBe(true);
+ await recycle.restoreRecycleBatch(UID, second!.id);
+ await recycle.deleteRecycleBatch(UID, second!.id);
+ expect(fs.readFileSync(snapshot, 'utf8')).toBe(contents);
+ await chats.deleteConversation(UID, cid);
+ expect(fs.existsSync(path.dirname(snapshot))).toBe(false);
+ expect(fs.existsSync(path.join(APPS_ROOT(), saved.id, 'index.html'))).toBe(false);
+ });
+
+ it('sweeps historical orphans only after readable ownership evidence, retaining journals and other accounts', async () => {
+ const { savedApps } = await mods();
+ const paths = await import('../../../src/main/paths');
+ const orphan = path.join(paths.userAppEditsDir(UID), 'orphan');
+ const journal = path.join(paths.userAppEditsDir(UID), 'unfinished');
+ const other = path.join(paths.userAppEditsDir('other-user'), 'orphan');
+ for (const dir of [orphan, journal, other]) fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(journal, 'save-journal.json'), '{}');
+ const recycleDir = paths.userRecycleDir(UID);
+ fs.mkdirSync(path.join(recycleDir, 'incomplete'), { recursive: true });
+ await savedApps.cleanupEditSnapshots(UID);
+ expect(fs.existsSync(orphan)).toBe(true);
+ fs.rmSync(path.join(recycleDir, 'incomplete'), { recursive: true });
+ const index = path.join(paths.userChatsDir(UID), '_index.json');
+ fs.mkdirSync(path.dirname(index), { recursive: true });
+ fs.writeFileSync(index, '{');
+ await savedApps.cleanupEditSnapshots(UID);
+ expect(fs.existsSync(orphan)).toBe(true);
+ fs.writeFileSync(index, '[]');
+ const fsp = await import('node:fs/promises');
+ vi.mocked(fsp.rm).mockRejectedValueOnce(Object.assign(new Error('Injected cleanup failure'), { code: 'EACCES' }));
+ await savedApps.cleanupEditSnapshots(UID);
+ expect(fs.existsSync(orphan)).toBe(true);
+ await savedApps.cleanupEditSnapshots(UID);
+ expect(fs.existsSync(orphan)).toBe(false);
+ expect(fs.existsSync(journal)).toBe(true);
+ expect(fs.existsSync(other)).toBe(true);
+ });
+});
diff --git a/test/main/features/web-app-commercial-entry.test.ts b/test/main/features/web-app-commercial-entry.test.ts
new file mode 100644
index 00000000..72f1abd5
--- /dev/null
+++ b/test/main/features/web-app-commercial-entry.test.ts
@@ -0,0 +1,176 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { captureMainLogWorkers } from '../../helpers/capture-main-log-workers';
+
+vi.mock('electron', () => ({ app: { isPackaged: false }, dialog: {} }));
+const uid = 'commercial-boundary';
+const receipt = { ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' };
+let root: string, previous: string | undefined, closeLogs: () => Promise<void>;
+beforeEach(async () => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-commercial-entry-'));
+ previous = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = root;
+ vi.resetModules();
+ closeLogs = await captureMainLogWorkers();
+ (await import('../../../src/main/features/users')).activateUser(uid);
+});
+afterEach(async () => {
+ await closeLogs();
+ if (previous === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previous;
+ fs.rmSync(root, { recursive: true, force: true });
+});
+function seed(dir: string, appType: string | undefined, manifest = true) {
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'index.html'), '<!doctype html><h1>Retained app</h1>');
+ fs.writeFileSync(path.join(dir, '__orkas-meta.json'), JSON.stringify({
+ title: 'Retained app', appType, entry: 'index.html', savedAt: '2026-10-01T00:00:00Z',
+ sourceCid: 'historic', sourceArtifactId: 'historic',
+ }));
+ if (manifest) fs.writeFileSync(path.join(dir, 'orkas-app.json'), JSON.stringify({ sdkVersion: 1, capabilities: [] }));
+}
+function snapshot(dir: string): unknown {
+ if (!fs.existsSync(dir)) return null;
+ return fs.readdirSync(dir).sort().map(name => {
+ const file = path.join(dir, name);
+ return [name, fs.statSync(file).isDirectory() ? snapshot(file) : fs.readFileSync(file).toString('base64')];
+ });
+}
+describe('commercial web application boundary', () => {
+ it('inherits a web task binding even when a caller claims local or stored type is absent', async () => {
+ const chats = await import('../../../src/main/features/chats');
+ const conversation = await chats.createConversation(uid, { assistance: { kind: 'app_creation', appType: 'web' } });
+ const cid = conversation.conversation_id;
+ const paths = await import('../../../src/main/paths');
+ const dir = path.join(paths.chatArtifactCidDir(uid, cid), 'historic');
+ seed(dir, undefined);
+ const before = snapshot(paths.userChatArtifactsDir(uid));
+ const artifacts = await import('../../../src/main/features/chat_artifacts');
+ expect(await artifacts.createArtifact(uid, cid, 'commander', { appType: 'local', files: [] })).toMatchObject(receipt);
+ const saved = await import('../../../src/main/features/saved_apps');
+ expect(await saved.saveFromArtifact(uid, cid, 'historic')).toMatchObject(receipt);
+ expect(await saved.saveFromPath(uid, path.join(dir, 'index.html'))).toMatchObject(receipt);
+ const { previewBundle } = await import('../../../src/main/features/web_apps/preview');
+ await expect(previewBundle(path.join(dir, 'index.html'))).rejects.toMatchObject(receipt);
+ expect(snapshot(paths.userChatArtifactsDir(uid))).toEqual(before);
+ });
+
+ it.each(['{ damaged', '[]', '{"assistance":{"kind":"app_creation","appType":"unexpected"}}'])
+ ('does not turn an unreadable task binding into local permission (%s)', async content => {
+ const chats = await import('../../../src/main/features/chats');
+ const { conversationLayout } = await import('../../../src/main/util/project-layout');
+ const conversation = await chats.createConversation(uid, { assistance: { kind: 'app_creation', appType: 'web' } });
+ const cid = conversation.conversation_id;
+ fs.writeFileSync(conversationLayout(uid, cid).metaFile, content);
+ vi.spyOn(chats, 'getConversationMetadata').mockResolvedValue(null);
+ try {
+ const artifacts = await import('../../../src/main/features/chat_artifacts');
+ const paths = await import('../../../src/main/paths');
+ const before = snapshot(paths.userChatArtifactsDir(uid));
+ expect(await artifacts.createArtifact(uid, cid, 'commander', { appType: 'local', files: [{ path: 'index.html', content: '<h1>No grant</h1>' }] }))
+ .toMatchObject({ ok: false });
+ expect(snapshot(paths.userChatArtifactsDir(uid))).toEqual(before);
+ expect(fs.readFileSync(conversationLayout(uid, cid).metaFile, 'utf8')).toBe(content);
+ } finally { vi.restoreAllMocks(); }
+ });
+
+ it.each(['web', 'cloud'])('refuses direct %s SDK and preview acquisition', async appType => {
+ const { WebAppRuntime } = await import('../../../src/main/features/web_apps/runtime');
+ const called = vi.fn();
+ const runtime = new WebAppRuntime({ activeUser: () => uid, language: () => 'en', modelAvailable: () => true,
+ pick: called, save: called, generate: called, tools: called });
+ const bundle = { key: 'direct', appType, entry: 'index.html', title: 'Retained',
+ manifest: { sdkVersion: 1, capabilities: [] }, resolve: called } as any;
+ expect(() => runtime.open(uid, 1, bundle)).toThrowError(expect.objectContaining(receipt));
+ const { createPreviewSdk } = await import('../../../src/main/features/web_apps/preview');
+ await expect(createPreviewSdk({} as any, {} as any, bundle)).rejects.toMatchObject(receipt);
+ expect(called).not.toHaveBeenCalled();
+ });
+ it.each(['web', 'cloud'])('refuses explicit %s authoring before allocating artifact files', async appType => {
+ const artifacts = await import('../../../src/main/features/chat_artifacts');
+ const paths = await import('../../../src/main/paths');
+ const pool = paths.userChatArtifactsDir(uid), before = snapshot(pool);
+ for (const files of [[], [{ path: 'index.html', content: '<h1>Must not be created</h1>' }]]) {
+ expect(await artifacts.createArtifact(uid, 'new-task', 'commander', { appType, files })).toMatchObject(receipt);
+ expect(snapshot(pool)).toEqual(before);
+ }
+ });
+
+ it.each(['web', 'cloud'])('keeps the specific %s tool failure and never finalizes, smoke-tests or announces an artifact', async appType => {
+ const { createLocalTools } = await import('../../../src/main/model/core-agent/local-tools');
+ const paths = await import('../../../src/main/paths');
+ const callback = vi.fn(), smoke = vi.fn();
+ const tool = createLocalTools({ userId: uid, cid: 'tool-task', onArtifactCreated: callback, artifactInteractionSmoke: smoke })
+ .find(tool => tool.name === 'create_artifact')!;
+ const before = snapshot(paths.userChatArtifactsDir(uid));
+ const result = await tool.execute({ appType, files: [{ path: 'index.html', content: '<h1>Refused</h1>' }] }, { workingDir: root, state: new Map() } as any);
+ expect(result.isError).toBe(true);
+ expect(JSON.parse(String(result.content))).toMatchObject(receipt);
+ expect(callback).not.toHaveBeenCalled(); expect(smoke).not.toHaveBeenCalled();
+ expect(snapshot(paths.userChatArtifactsDir(uid))).toEqual(before);
+ });
+
+ it('preserves web edit journals and snapshots during local listing and background cleanup', async () => {
+ const paths = await import('../../../src/main/paths');
+ const edit = path.join(paths.userAppEditsDir(uid), 'historic-edit');
+ seed(path.join(edit, 'snapshot'), 'web');
+ seed(paths.savedAppDir(uid, 'historic-app'), 'web');
+ seed(paths.savedAppDir(uid, 'historic-app.tmp-01234567'), 'web');
+ fs.writeFileSync(path.join(edit, 'context.json'), JSON.stringify({ version: 1, appId: 'historic-app',
+ appType: 'web', title: 'Retained app', fingerprint: '0'.repeat(64) }));
+ fs.writeFileSync(path.join(edit, 'save-journal.json'), JSON.stringify({ version: 1, appId: 'historic-app',
+ temporary: 'historic-app.tmp-01234567', before: '0'.repeat(64), after: '1'.repeat(64) }));
+ const beforeEdits = snapshot(paths.userAppEditsDir(uid));
+ const beforeApps = snapshot(paths.userSavedAppsDir(uid));
+ const saved = await import('../../../src/main/features/saved_apps');
+ saved.listSavedApps(uid);
+ await saved.cleanupEditSnapshots(uid);
+ expect(snapshot(paths.userAppEditsDir(uid))).toEqual(beforeEdits);
+ expect(snapshot(paths.userSavedAppsDir(uid))).toEqual(beforeApps);
+ });
+
+ it.each(['web', 'cloud'])('preserves existing %s bundles when save, edit, open and preview are refused', async appType => {
+ const paths = await import('../../../src/main/paths');
+ const savedDir = paths.savedAppDir(uid, 'historic-app');
+ const artifactDir = path.join(paths.chatArtifactCidDir(uid, 'historic'), 'historic');
+ seed(savedDir, appType); seed(artifactDir, appType);
+ const saved = await import('../../../src/main/features/saved_apps');
+ const beforeSaved = snapshot(paths.userSavedAppsDir(uid));
+ const beforeArtifact = snapshot(paths.userChatArtifactsDir(uid));
+ const beforeEdits = snapshot(paths.userAppEditsDir(uid));
+ expect(await saved.saveFromArtifact(uid, 'historic', 'historic')).toMatchObject(receipt);
+ expect(await saved.saveFromArtifact(uid, 'historic', 'historic', 'update')).toMatchObject(receipt);
+ expect(await saved.saveFromPath(uid, path.join(artifactDir, 'index.html'))).toMatchObject(receipt);
+ expect(await saved.openForEditing(uid, 'historic-app')).toMatchObject(receipt);
+ expect(await saved.appDataImpact(uid, 'historic', 'historic')).toMatchObject(receipt);
+ const destination = path.join(root, 'export-refused');
+ expect(await saved.exportAppData(uid, 'historic', 'historic', destination)).toMatchObject(receipt);
+ expect(fs.existsSync(destination)).toBe(false);
+ const { openApp } = await import('../../../src/main/features/web_apps/host');
+ await expect(openApp(uid, 4, { appId: 'historic-app' })).rejects.toMatchObject(receipt);
+ await expect(openApp(uid, 4, { cid: 'historic', artifactId: 'historic' })).rejects.toMatchObject(receipt);
+ const { previewBundle } = await import('../../../src/main/features/web_apps/preview');
+ await expect(previewBundle(path.join(artifactDir, 'index.html'))).rejects.toMatchObject(receipt);
+ fs.unlinkSync(path.join(artifactDir, 'orkas-app.json'));
+ await expect(previewBundle(path.join(artifactDir, 'index.html'))).rejects.toMatchObject(receipt);
+ fs.writeFileSync(path.join(artifactDir, 'orkas-app.json'), JSON.stringify({ sdkVersion: 1, capabilities: [] }));
+ expect(snapshot(paths.userSavedAppsDir(uid))).toEqual(beforeSaved);
+ expect(snapshot(paths.userChatArtifactsDir(uid))).toEqual(beforeArtifact);
+ expect(snapshot(paths.userAppEditsDir(uid))).toEqual(beforeEdits);
+ });
+
+ it('allows ordinary local authoring, saving and editing with the same SDK declaration', async () => {
+ const artifacts = await import('../../../src/main/features/chat_artifacts');
+ const saved = await import('../../../src/main/features/saved_apps');
+ const created = await artifacts.createArtifact(uid, 'local-task', 'commander', { appType: 'local', files: [
+ { path: 'index.html', content: '<h1>Local app</h1>' },
+ { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }) },
+ ] });
+ expect(created.ok).toBe(true); if (!created.ok) throw new Error(created.error);
+ const stored = await saved.saveFromArtifact(uid, 'local-task', created.artifactId);
+ expect(stored.ok).toBe(true); if (!stored.ok) throw new Error(stored.error);
+ expect(await saved.openForEditing(uid, stored.id)).toMatchObject({ ok: true });
+ });
+});
diff --git a/test/main/features/web-app-host.test.ts b/test/main/features/web-app-host.test.ts
index d8a1588d..0300c8ef 100644
--- a/test/main/features/web-app-host.test.ts
+++ b/test/main/features/web-app-host.test.ts
@@ -6,6 +6,16 @@ import * as path from 'node:path';
import { EventEmitter } from 'node:events';
const connector = vi.hoisted(() => ({ instances: [] as any[], call: vi.fn(async () => ({ content: [{ type: 'text', text: 'Verified remote result' }] })), approve: vi.fn(async () => false) }));
+
+it('keeps structured data errors while returning readable localized recovery instead of raw keys', async () => {
+ const {safeFailure}=await import('../../../src/main/features/web_apps/host');
+ const {AppError}=await import('../../../src/main/features/web_apps/runtime');
+ const {t}=await import('../../../src/main/i18n');
+ for(const code of ['E_DATA','E_SCHEMA','E_CONFLICT','E_PERMISSION','E_MIGRATION','E_RELATION','E_TABLE','E_CONDITION']){
+ const result=safeFailure(new AppError(code));expect(result.code).toBe(code);
+ expect(result.message).not.toMatch(/^web_apps\./);expect(result.message).toBe(t('web_apps.error_E_FAILED'));
+ }
+});
vi.mock('electron', () => ({ dialog: {}, app: { isPackaged: false } }));
vi.mock('../../../src/main/features/connectors/manager', () => ({
listInstances: () => connector.instances, restoreComposioConnectionsFromServer: async () => 0,
@@ -100,7 +110,8 @@ describe('Web host reuses owning services', () => {
{ path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }) },
] });
if (!created.ok) throw new Error(created.error);
- const sender = Object.assign(new EventEmitter(), { id: 10, isDestroyed: () => false });
+ const liveFrames: any[] = [];
+ const sender = Object.assign(new EventEmitter(), { id: 10, isDestroyed: () => false, mainFrame: { framesInSubtree: liveFrames } });
const open = () => webAppInvokeHandlers['webApps.open'](
{ source: { cid: 'navigation-test', artifactId: created.artifactId } }, { userId: uid, sender: sender as any },
) as Promise<any>;
@@ -114,11 +125,19 @@ describe('Web host reuses owning services', () => {
for (const frameAvailable of [true, false]) {
const app = await open();
await runtime.call(uid, sender.id, app.token, 'before', 'host.getContext', {});
+ const frame = { url: app.url, frameTreeNodeId: liveFrames.length + 1, processId: 20, routingId: liveFrames.length + 1 };
+ liveFrames.push(frame);
+ sender.emit('did-frame-navigate', {}, app.url, 200, 'OK', false, frame.processId, frame.routingId);
const event = { url, isMainFrame: false, preventDefault: vi.fn(),
- ...(frameAvailable ? { frame: { url: app.url } } : { initiator: { url: app.url } }) };
+ ...(frameAvailable ? { frame } : { initiator: frame }) };
sender.emit('will-frame-navigate', event);
expect(event.preventDefault.mock.calls.length, url).toBe(allowed ? 0 : 1);
if (allowed) {
+ // A navigation attempt may become a download or be aborted.
+ expect(await runtime.call(uid, sender.id, app.token, 'download-still-open', 'storage.keys', {})).toEqual({ keys: [] });
+ // A committed document can have new process/routing IDs.
+ frame.url = url; frame.processId = 30; frame.routingId += 1000;
+ sender.emit('did-frame-navigate', {}, url, 200, 'OK', false, frame.processId, frame.routingId);
await expect(runtime.call(uid, sender.id, app.token, 'after', 'storage.keys', {})).rejects.toMatchObject({ code: 'E_CLOSED' });
expect(appResource(new Request(app.url))).toEqual({ status: 403 });
} else {
@@ -184,8 +203,16 @@ describe('Web host reuses owning services', () => {
const files = [{ path: 'index.html', content: '<h1>Original</h1>' }];
const old: any = (await artifact.createArtifact(uid, 'cid-test', 'agent', { title: 'Legacy', files }));
expect(old.ok).toBe(true);
+ const oldFile: any = artifact.resolveArtifactFilePath(uid, 'cid-test', old.artifactId, 'index.html');
+ const oldMeta = path.join(path.dirname(oldFile.absPath), '__orkas-meta.json');
+ const metadata = JSON.parse(fs.readFileSync(oldMeta, 'utf8')); delete metadata.browserStorage;
+ fs.writeFileSync(oldMeta, JSON.stringify(metadata));
const legacy = (await openApp(uid, 1, { cid: 'cid-test', artifactId: old.artifactId }));
expect(legacy).not.toHaveProperty('token'); expect(legacy).toMatchObject({ entry: 'index.html' });
+ expect(legacy.url).toBe(`chat-app://cid/cid-test/${old.artifactId}/index.html`);
+ const copied = await (await import('../../../src/main/features/saved_apps')).saveFromArtifact(uid, 'cid-test', old.artifactId);
+ if (!copied.ok) throw new Error(copied.error);
+ expect(await openApp(uid, 1, { appId: copied.id })).toMatchObject({ browserOnly: true, url: expect.stringMatching(/^chat-app:\/\/a-/) });
const created: any = (await artifact.createArtifact(uid, 'cid-test', 'agent', { title: 'SDK', files: [...files,
{ path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }) }] }));
const app: any = (await openApp(uid, 1, { cid: 'cid-test', artifactId: created.artifactId }));
@@ -199,3 +226,54 @@ describe('Web host reuses owning services', () => {
expect(appResource(new Request(app.url))).toEqual({ status: 403 });
});
});
+
+
+it('isolates new ordinary objects and accounts with short stable origins and no SDK authority', async () => {
+ const artifacts = await import('../../../src/main/features/chat_artifacts');
+ const saved = await import('../../../src/main/features/saved_apps');
+ const { openApp, appResource, runtime } = await import('../../../src/main/features/web_apps/host');
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const sources: any[] = [];
+ for (const cid of ['same-task', 'same-task', 'other-task']) {
+ const a = await artifacts.createArtifact(uid, cid, 'agent', { files: [{ path: 'index.html', content: '<h1>Ordinary</h1>' }] });
+ if (!a.ok) throw new Error(a.error);
+ sources.push({ cid, artifactId: a.artifactId });
+ }
+ const copy = await saved.saveFromArtifact(uid, sources[0].cid, sources[0].artifactId);
+ if (!copy.ok) throw new Error(copy.error);
+ sources.push({ appId: copy.id });
+ const apps: any[] = [];
+ for (const source of sources) {
+ const app: any = await openApp(uid, 1, source); apps.push(app);
+ expect(new URL(app.url).host).toMatch(/^a-[a-f0-9]{20}$/);
+ expect(app.url.length).toBeLessThan(50);
+ expect(app).toMatchObject({ browserOnly: true });
+ expect(app).not.toHaveProperty('sdkVersion');
+ expect(appResource(new Request(app.url))).toMatchObject({ status: 200 });
+ expect(appResource(new Request(new URL('__orkas/bridge.js', app.url)))).toMatchObject({ status: 200, body: artifacts.BRIDGE_JS });
+ for (const rel of ['__orkas/sdk.js', '__orkas/capabilities.json'])
+ expect(appResource(new Request(new URL(rel, app.url)))).toMatchObject({ status: 403 });
+ expect(appResource(new Request(app.url, { headers: { Origin: 'chat-app://cid' } }))).toMatchObject({ status: 403 });
+ await expect(runtime.call(uid, 1, app.token, 'probe', 'host.getContext', {})).rejects.toMatchObject({ code: 'E_UNAVAILABLE' });
+ expect(() => runtime.cancel(uid, 1, app.token, 'probe')).toThrow('E_UNAVAILABLE');
+ const second: any = await openApp(uid, 2, source);
+ runtime.close(uid, 1, app.token);
+ expect(second.url).toBe(app.url);
+ expect(appResource(new Request(second.url))).toMatchObject({ status: 200 });
+ runtime.close(uid, 2, second.token);
+ expect(appResource(new Request(second.url))).toMatchObject({ status: 403 });
+ expect((await openApp(uid, 1, source)).url).toBe(app.url);
+ }
+ expect(new Set(apps.map(a => new URL(a.url).host)).size).toBe(4);
+ const other = 'other-browser-account';
+ fs.mkdirSync(path.dirname(paths.savedAppDir(other, copy.id)), { recursive: true });
+ fs.cpSync(paths.savedAppDir(uid, copy.id), paths.savedAppDir(other, copy.id), { recursive: true });
+ users.activateUser(other);
+ expect(appResource(new Request(apps[3].url))).toMatchObject({ status: 403 });
+ const foreign: any = await openApp(other, 1, { appId: copy.id });
+ expect(foreign.url).not.toBe(apps[3].url);
+ users.activateUser(uid);
+ expect(appResource(new Request(foreign.url))).toMatchObject({ status: 403 });
+ expect((await openApp(uid, 1, { appId: copy.id })).url).toBe(apps[3].url);
+});
diff --git a/test/main/features/web-app-ipc.test.ts b/test/main/features/web-app-ipc.test.ts
index 5179610a..3154da0b 100644
--- a/test/main/features/web-app-ipc.test.ts
+++ b/test/main/features/web-app-ipc.test.ts
@@ -1,12 +1,32 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import type { WebAppRuntime } from '../../../src/main/features/web_apps/runtime';
+import type { HostAdapters, WebAppRuntime } from '../../../src/main/features/web_apps/runtime';
let runtime: WebAppRuntime;
beforeEach(() => vi.resetModules());
afterEach(() => { runtime?.closeOwner(1); vi.doUnmock('../../../src/main/features/web_apps/host'); });
-it('cancels a producer that outruns the progress consumer without replay and keeps the next request usable', async () => {
+async function setup(generate: HostAdapters['generate'], activeUser = () => 'user') {
const { WebAppRuntime, AppError } = await import('../../../src/main/features/web_apps/runtime');
+ runtime = new WebAppRuntime({ activeUser, language: () => 'en', modelAvailable: () => true,
+ pick: async () => null, save: async () => null, tools: async () => [], generate });
+ vi.doMock('../../../src/main/features/web_apps/host', () => ({ runtime,
+ openApp: vi.fn(), safeFailure: (error: unknown) => ({ code: error instanceof AppError ? error.code : 'E_FAILED' }) }));
+ const { webAppCall } = await import('../../../src/main/ipc/web_apps');
+ const open = () => runtime.open(activeUser(), 1, { key: 'stream-test', title: 'Stream', entry: 'index.html',
+ manifest: { sdkVersion: 1, capabilities: ['ai'] }, resolve: () => null });
+ const ctx = () => ({ userId: activeUser(), sender: { id: 1 } as any });
+ const call = (token: string, requestId: string, signal = new AbortController().signal) =>
+ webAppCall({ token, requestId, method: 'ai.generate', args: { prompt: 'Report' } }, ctx(), signal);
+ return { open, call, webAppCall, ctx };
+}
+
+async function collect(stream: AsyncIterable<unknown>) {
+ const events = [];
+ for await (const event of stream) events.push(event);
+ return events;
+}
+
+it('cancels a producer that outruns the progress consumer without replay and keeps the next request usable', async () => {
let resume!: () => void;
let observedSignal!: AbortSignal;
const generate = vi.fn(async (_uid, _args, signal, progress) => {
@@ -16,15 +36,9 @@ it('cancels a producer that outruns the progress consumer without replay and kee
for (let i = 0; i < 129; i++) progress({ text: String(i) });
return { text: 'Must not complete after overflow' };
});
- runtime = new WebAppRuntime({ activeUser: () => 'user', language: () => 'en', modelAvailable: () => true,
- pick: async () => null, save: async () => null, tools: async () => [], generate });
- vi.doMock('../../../src/main/features/web_apps/host', () => ({ runtime,
- openApp: vi.fn(), safeFailure: (error: unknown) => ({ code: error instanceof AppError ? error.code : 'E_FAILED' }) }));
- const { webAppCall } = await import('../../../src/main/ipc/web_apps');
- const app = runtime.open('user', 1, { key: 'stream-test', title: 'Stream', entry: 'index.html',
- manifest: { sdkVersion: 1, capabilities: ['ai'] }, resolve: () => null });
- const ctx = { userId: 'user', sender: { id: 1 } as any };
- const stream = webAppCall({ token: app.token, requestId: 'burst', method: 'ai.generate', args: { prompt: 'Report' } }, ctx, new AbortController().signal);
+ const { open, call, webAppCall, ctx } = await setup(generate);
+ const app = open();
+ const stream = call(app.token, 'burst');
expect((await stream.next()).value).toEqual({ type: 'progress', value: { text: 'First' } });
resume();
await new Promise(resolve => setImmediate(resolve));
@@ -35,6 +49,109 @@ it('cancels a producer that outruns the progress consumer without replay and kee
expect(observedSignal.aborted).toBe(true);
expect(generate).toHaveBeenCalledOnce();
const recovered = [];
- for await (const event of webAppCall({ token: app.token, requestId: 'recovered', method: 'host.getContext', args: {} }, ctx, new AbortController().signal)) recovered.push(event);
+ for await (const event of webAppCall({ token: app.token, requestId: 'recovered', method: 'host.getContext', args: {} }, ctx(), new AbortController().signal)) recovered.push(event);
expect(recovered).toEqual([{ type: 'result', ok: true, value: { language: 'en', sdkVersion: 1 } }]);
});
+
+it('admits submission only from a live local artifact owned by the active account and window', async () => {
+ const { WebAppRuntime } = await import('../../../src/main/features/web_apps/runtime');
+ let active = 'user';
+ let valid = true;
+ runtime = new WebAppRuntime({ activeUser: () => active, language: () => 'en', modelAvailable: () => true,
+ pick: async () => null, save: async () => null, tools: async () => [], generate: vi.fn() });
+ vi.doMock('../../../src/main/features/web_apps/host', () => ({ runtime, openApp: vi.fn(), safeFailure: () => ({ code: 'E_FAILED' }) }));
+ const { webAppInvokeHandlers } = await import('../../../src/main/ipc/web_apps');
+ const check = (token: string, userId = 'user', owner = 1) => webAppInvokeHandlers['webApps.canSubmitArtifact'](
+ { token }, { userId, sender: { id: owner } as any });
+ const bundle = { key: 'artifact', title: 'Form', entry: 'index.html', kind: 'artifact' as const, appType: 'local' as const,
+ manifest: { sdkVersion: 1, capabilities: [] }, valid: () => valid, resolve: () => null };
+ const local = runtime.open('user', 1, bundle);
+ expect(await check(local.token)).toEqual({ allowed: true });
+ expect(await check(local.token, 'foreign')).toEqual({ allowed: false });
+ expect(await check(local.token, 'user', 99)).toEqual({ allowed: false });
+ const saved = runtime.open('user', 1, { ...bundle, kind: 'saved' });
+ expect(await check(saved.token)).toEqual({ allowed: false });
+ expect(() => runtime.open('user', 1, { ...bundle, appType: 'web' })).toThrowError(expect.objectContaining({ code: 'E_COMMERCIAL_REQUIRED' }));
+ active = 'foreign'; expect(await check(local.token)).toEqual({ allowed: false });
+ active = 'user'; expect(await check(local.token)).toEqual({ allowed: true });
+ valid = false; expect(await check(local.token)).toEqual({ allowed: false });
+ valid = true; expect(await check(local.token)).toEqual({ allowed: false });
+ const reopened = runtime.open('user', 1, bundle);
+ expect(await check(reopened.token)).toEqual({ allowed: true });
+ await runtime.call('user', 1, reopened.token, 'revoke', 'permissions.revoke', {});
+ expect(await check(reopened.token)).toEqual({ allowed: false });
+});
+
+it.each(['cancel', 'close', 'account-switch'] as const)('emits one cancellation terminal and discards a late result after %s', async action => {
+ let uid = 'user';
+ let resume!: () => void;
+ let observedSignal!: AbortSignal;
+ const generate = vi.fn<HostAdapters['generate']>(async (_uid, _args, signal, progress) => {
+ observedSignal = signal;
+ progress({ text: 'Accepted progress' });
+ await new Promise<void>(resolve => { resume = resolve; });
+ // Simulate a dependency that completes despite cancellation.
+ return { text: 'Late private result' };
+ });
+ const { open, call, webAppCall, ctx } = await setup(generate, () => uid);
+ const app = open();
+ const controller = new AbortController();
+ const stream = call(app.token, 'departing', controller.signal);
+ expect((await stream.next()).value).toEqual({ type: 'progress', value: { text: 'Accepted progress' } });
+ if (action === 'cancel') controller.abort();
+ else if (action === 'close') runtime.close('user', 1, app.token);
+ else { uid = 'other'; runtime.closeUser('user'); }
+ expect(observedSignal.aborted).toBe(true);
+ resume();
+ expect(await collect(stream)).toEqual([{ type: 'result', ok: false, value: { code: 'E_CANCELLED' } }]);
+ expect(generate).toHaveBeenCalledOnce();
+ const recovered = action === 'cancel' ? app : open();
+ expect(await collect(webAppCall({ token: recovered.token, requestId: 'recovered', method: 'host.getContext', args: {} },
+ ctx(), new AbortController().signal))).toEqual([{ type: 'result', ok: true, value: { language: 'en', sdkVersion: 1 } }]);
+});
+
+it('aborts the producer when the IPC consumer leaves and does not replay its request', async () => {
+ let observedSignal!: AbortSignal;
+ const generate = vi.fn<HostAdapters['generate']>(async (_uid, _args, signal, progress) => {
+ observedSignal = signal;
+ progress({ text: 'Started' });
+ await new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }));
+ return { text: 'Discarded' };
+ });
+ const { open, call } = await setup(generate);
+ const app = open();
+ const stream = call(app.token, 'abandoned');
+ await stream.next();
+ expect(await stream.return(undefined)).toEqual({ done: true, value: undefined });
+ expect(observedSignal.aborted).toBe(true);
+ expect(await collect(call(app.token, 'abandoned'))).toEqual([{ type: 'result', ok: false, value: { code: 'E_DUPLICATE' } }]);
+ expect(generate).toHaveBeenCalledOnce();
+});
+
+it.each(['signal', 'tombstone', 'credential', 'owner'] as const)('rejects %s before invoking a side-effecting adapter and keeps an independent request usable', async rejection => {
+ const generate = vi.fn(async () => ({ text: 'Explicit new request' }));
+ const { open, call, webAppCall, ctx } = await setup(generate);
+ const app = open();
+ const controller = new AbortController();
+ if (rejection === 'signal') controller.abort();
+ if (rejection === 'tombstone') runtime.cancel('user', 1, app.token, 'blocked');
+ const events = await collect(webAppCall({ token: rejection === 'credential' ? 'invalid' : app.token,
+ requestId: 'blocked', method: 'ai.generate', args: { prompt: 'Report' } },
+ rejection === 'owner' ? { userId: 'user', sender: { id: 2 } as any } : ctx(), controller.signal));
+ const codes = { signal: 'E_CANCELLED', tombstone: 'E_DUPLICATE', credential: 'E_INPUT', owner: 'E_CLOSED' };
+ expect(events).toEqual([{ type: 'result', ok: false, value: { code: codes[rejection] } }]);
+ expect(generate).not.toHaveBeenCalled();
+ expect(await collect(call(app.token, 'fresh'))).toEqual([{ type: 'result', ok: true, value: { text: 'Explicit new request' } }]);
+ expect(generate).toHaveBeenCalledOnce();
+});
+
+it('scopes cancellation and duplicate IDs to the originating app instance', async () => {
+ const generate = vi.fn(async () => ({ text: 'Sibling result' }));
+ const { open, call } = await setup(generate);
+ const first = open(), sibling = open();
+ runtime.cancel('user', 1, first.token, 'same-id');
+ expect(await collect(call(first.token, 'same-id'))).toEqual([{ type: 'result', ok: false, value: { code: 'E_DUPLICATE' } }]);
+ expect(await collect(call(sibling.token, 'same-id'))).toEqual([{ type: 'result', ok: true, value: { text: 'Sibling result' } }]);
+ expect(await collect(call(sibling.token, 'same-id'))).toEqual([{ type: 'result', ok: false, value: { code: 'E_DUPLICATE' } }]);
+ expect(generate).toHaveBeenCalledOnce();
+});
diff --git a/test/main/features/web-app-preview.test.ts b/test/main/features/web-app-preview.test.ts
index c4383ce8..52a93ecc 100644
--- a/test/main/features/web-app-preview.test.ts
+++ b/test/main/features/web-app-preview.test.ts
@@ -83,3 +83,69 @@ it('accepts only its own trusted frame, token and narrow operations, then revoke
expect(resource).toBeUndefined(); expect(contents.listenerCount('ipc-message')).toBe(0);
expect(fs.readdirSync(os.tmpdir()).filter(name => name.startsWith('orkas-preview-storage-')).sort()).toEqual(before);
});
+
+it('settles the current bundle document after local navigation and rejects foreign or revoked frames', async () => {
+ const { EventEmitter } = await import('node:events');
+ const { createPreviewSdk } = await import('../../../src/main/features/web_apps/preview');
+ manifest();
+ fs.writeFileSync(path.join(path.dirname(entry), 'second.html'), '<h1>Second page</h1>');
+ const contents: any = new EventEmitter();
+ Object.assign(contents, { id: 20, mainFrame: { frames: [] }, isDestroyed: () => false });
+ const ses: any = { protocol: { handle() {}, unhandle() {} } };
+ const preview = await createPreviewSdk(ses, contents, (await previewBundle(entry))!);
+ let painted = 0;
+ const foreign = { url: 'https://example.invalid/second.html', executeJavaScript() { throw new Error('Foreign frame executed'); } };
+ const current = { url: preview.origin + '/second.html', async executeJavaScript() { painted++; } };
+ try {
+ contents.mainFrame.frames = [foreign];
+ await expect(preview.settle()).rejects.toThrow('E_BUNDLE');
+ contents.mainFrame.frames.push(current);
+ await preview.settle();
+ expect(painted).toBe(1);
+ } finally { await preview.dispose(); }
+ await expect(preview.settle()).rejects.toThrow('E_BUNDLE');
+});
+
+it('keeps preview data in disposable storage: writes are readable during the session and leave no files afterwards', async () => {
+ const { EventEmitter } = await import('node:events');
+ const { createPreviewSdk } = await import('../../../src/main/features/web_apps/preview');
+ const data = { version: 1, tables: [{ id: 'notes', name: 'notes', fields: [{ id: 'body', name: 'body', type: 'string' }], access: { read: ['body'], insert: ['body'], count: true } }] };
+ manifest(JSON.stringify({ sdkVersion: 1, capabilities: ['data'], data }));
+ const workspace = process.env.ORKAS_WORKSPACE_ROOT!;
+ const inventory = (dir: string) => fs.existsSync(dir) ? fs.readdirSync(dir, { recursive: true }).map(String).sort() : [];
+ const temporary = () => fs.readdirSync(os.tmpdir()).filter(name => name.startsWith('orkas-preview-storage-')).sort();
+ const workspaceBefore = inventory(workspace), sourceBefore = inventory(path.dirname(entry)), tempBefore = temporary();
+ const session = async () => {
+ const contents: any = new EventEmitter(), replies: any[] = [];
+ const frame: any = { detached: false, frames: [], send: (_channel: string, value: any) => replies.push(value) };
+ let token = '';
+ Object.assign(contents, { id: 31, mainFrame: frame, isDestroyed: () => false,
+ // attach() hands the trusted shell its instance; capture it like the shell would.
+ executeJavaScript: async (script: string) => { const opened = JSON.parse(/attach\(frame, (\{.*?\})\);/s.exec(script)![1]); token = opened.token; frame.frames = [{ url: opened.url }]; } });
+ const preview = await createPreviewSdk({ protocol: { handle() {}, unhandle() {} } } as any, contents, (await previewBundle(entry))!);
+ contents.getURL = () => preview.shellUrl; await preview.attach();
+ let sequence = 0;
+ const invoke = async (method: string, args: unknown) => {
+ const id = String(++sequence);
+ contents.emit('ipc-message', { senderFrame: frame }, 'orkas.web-app-preview', { id, operation: 'webApps.call', payload: { token, requestId: 'r' + id, method, args } });
+ for (let tries = 0; tries < 500 && !replies.some(reply => reply.id === id); tries++) await new Promise(resolve => setTimeout(resolve, 5));
+ return replies.find(reply => reply.id === id)?.event;
+ };
+ return { preview, invoke };
+ };
+ const first = await session();
+ let created: string[] = [];
+ try {
+ expect(await first.invoke('data.insert', { table: 'notes', values: { body: 'preview only' } })).toMatchObject({ type: 'result', ok: true });
+ expect(await first.invoke('data.query', { table: 'notes' })).toEqual({ type: 'result', ok: true, value: { records: [{ body: 'preview only' }] } });
+ created = temporary().filter(name => !tempBefore.includes(name));
+ expect(created.length).toBeGreaterThan(0);
+ } finally { await first.preview.dispose(); }
+ // Compare only this session's directories so concurrent suites cannot interfere.
+ expect(temporary().filter(name => created.includes(name))).toEqual([]);
+ expect(inventory(workspace)).toEqual(workspaceBefore);
+ expect(inventory(path.dirname(entry))).toEqual(sourceBefore);
+ const second = await session();
+ try { expect(await second.invoke('data.count', { table: 'notes' })).toEqual({ type: 'result', ok: true, value: { count: 0 } }); }
+ finally { await second.preview.dispose(); }
+});
diff --git a/test/main/features/web_apps.test.ts b/test/main/features/web_apps.test.ts
index bc3a8252..2d54cb7a 100644
--- a/test/main/features/web_apps.test.ts
+++ b/test/main/features/web_apps.test.ts
@@ -30,10 +30,158 @@ beforeEach(async () => {
});
afterEach(async () => {
runtime.closeOwner(1); runtime.closeOwner(2);
+ await runtime.drainData?.();
if (prev === undefined) delete process.env.ORKAS_WORKSPACE_ROOT; else process.env.ORKAS_WORKSPACE_ROOT = prev;
await fs.rm(root, { recursive: true, force: true });
});
describe('Web app capability journeys', () => {
+ it('keeps another application instance usable when the first requester closes during shared SQLite startup', async () => {
+ let enter!: () => void, release!: () => void;
+ const entered = new Promise<void>(resolve => { enter = resolve; });
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let database: import('../../../src/main/features/web_apps/data').LocalAppData;
+ const close = vi.fn(async () => { await database?.close(); });
+ host.dataOwner = (owner, _key, file, definition) => ({
+ async open() {
+ enter(); await gate;
+ const { LocalAppData } = await import('../../../src/main/features/web_apps/data');
+ const { userLocalRoot } = await import('../../../src/main/paths');
+ database = new LocalAppData(file, userLocalRoot(owner), definition);
+ await database.call('data.insert', { table: 'notes', values: { body: 'KEEP' } });
+ return database;
+ },
+ call: (method, args) => database.call(method, args), close,
+ });
+ const definition = { version: 1, tables: [{ id: 'notes', name: 'notes',
+ fields: [{ id: 'body', name: 'body', type: 'string' }],
+ access: { read: ['body'], insert: ['body'], count: true } }] };
+ const b = { ...bundle('shared-startup', ['data']), manifest: { sdkVersion: 1, capabilities: ['data'], data: definition } };
+ const first = runtime.open(uid, 1, b), second = runtime.open(uid, 2, b);
+ const firstResult = call(first.token, 'data.query', { table: 'notes' }).then(value => ({ value }), error => ({ error }));
+ await entered;
+ const secondResult = runtime.call(uid, 2, second.token, 'second-query', 'data.query', { table: 'notes' }).then(value => ({ value }), error => ({ error }));
+ runtime.close(uid, 1, first.token); release();
+ expect(await firstResult).toMatchObject({ error: { code: 'E_CANCELLED' } });
+ expect(await secondResult).toEqual({ value: { records: [{ body: 'KEEP' }] } });
+ expect(close).not.toHaveBeenCalled();
+ expect(await runtime.call(uid, 2, second.token, 'second-count', 'data.count', { table: 'notes' })).toEqual({ count: 1 });
+ runtime.close(uid, 2, second.token); await runtime.drainData();
+ expect(close).toHaveBeenCalledOnce();
+ expect(host.generate).not.toHaveBeenCalled(); expect(host.tools).not.toHaveBeenCalled();
+ });
+
+ it('closes a late SQLite owner once when its last requester departs before startup completes', async () => {
+ let enter!: () => void, release!: () => void;
+ const entered = new Promise<void>(resolve => { enter = resolve; });
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let database: import('../../../src/main/features/web_apps/data').LocalAppData;
+ const close = vi.fn(async () => { await database?.close(); });
+ host.dataOwner = (owner, _key, file, definition) => ({
+ async open() {
+ enter(); await gate;
+ const { LocalAppData } = await import('../../../src/main/features/web_apps/data');
+ const { userLocalRoot } = await import('../../../src/main/paths');
+ database = new LocalAppData(file, userLocalRoot(owner), definition);
+ await database.call('internal.check', {}); return database;
+ },
+ call: (method, args) => database.call(method, args), close,
+ });
+ const app = runtime.open(uid, 1, { ...bundle('departing-startup', ['data']),
+ manifest: { sdkVersion: 1, capabilities: ['data'], data: { version: 1, tables: [] } } });
+ const pending = call(app.token, 'data.query', { table: 'notes' }).then(value => ({ value }), error => ({ error }));
+ await entered; runtime.close(uid, 1, app.token); release();
+ expect(await pending).toMatchObject({ error: { code: 'E_CANCELLED' } });
+ await runtime.drainData(); expect(close).toHaveBeenCalledOnce();
+ await expect(database.call('internal.check', {})).rejects.toMatchObject({ code: 'E_CLOSED' });
+ expect(host.generate).not.toHaveBeenCalled(); expect(host.tools).not.toHaveBeenCalled();
+ });
+
+ it.each(['direct'] as const)('reopens the application database after a timed-out query stops its worker (%s owner)', async mode => {
+ const { Worker } = await import('node:worker_threads');
+ const definition = { version: 1, tables: [{ id: 'notes', name: 'notes',
+ fields: [{ id: 'body', name: 'body', type: 'string' }],
+ access: { read: ['body'], insert: ['body'], count: true } }] };
+ const b = { ...bundle('stalled-query', ['data']), appType: 'local' as const, manifest: { sdkVersion: 1, capabilities: ['data'], data: definition } };
+ const workers = new Set<unknown>();
+ let stall = false;
+ const post = Worker.prototype.postMessage;
+ const spy = vi.spyOn(Worker.prototype, 'postMessage').mockImplementation(function (this: InstanceType<typeof Worker>, message: any, transfer?: any) {
+ workers.add(this);
+ // A query slower than the data.* budget never answers; the timeout stops this worker.
+ if (stall && message?.method === 'data.count') { stall = false; return; }
+ return post.call(this, message, transfer);
+ });
+ try {
+ const a = runtime.open(uid, 1, b);
+ await call(a.token, 'data.insert', { table: 'notes', values: { body: 'KEEP' } });
+ stall = true;
+ await expect(call(a.token, 'data.count', { table: 'notes' })).rejects.toMatchObject({ code: 'E_BUSY' });
+ // The saved row must stay reachable from the open page and from a later instance.
+ expect(await call(a.token, 'data.count', { table: 'notes' })).toEqual({ count: 1 });
+ const second = runtime.open(uid, 2, b);
+ expect(await runtime.call(uid, 2, second.token, 'second-query', 'data.query', { table: 'notes' })).toEqual({ records: [{ body: 'KEEP' }] });
+ expect(workers.size).toBe(2);
+ } finally { spy.mockRestore(); }
+ });
+
+ it('lets a local app describe the method shown in its supplied discovery example', async () => {
+ const { appResource } = await import('../../../src/main/features/web_apps/resources');
+ const app = runtime.open(uid, 1, { ...bundle('cloud-discovery-example', []), appType: 'local' });
+ const supplied = appResource(new Request(new URL('/__orkas/capabilities.json', app.url)), runtime);
+ const document = JSON.parse(supplied!.body!);
+ const example = document.methods.find((method: any) => method.name === 'capabilities.describe').example;
+ expect(await call(app.token, 'capabilities.describe', example)).toMatchObject({ name: example.method });
+ expect(host.generate).not.toHaveBeenCalled();
+ expect(host.tools).not.toHaveBeenCalled();
+ });
+
+ it.each(['local'] as const)('serves the matching %s authoring contract and invalidates it on closure', async appType => {
+ const { appResource } = await import('../../../src/main/features/web_apps/resources');
+ const b = { ...bundle('catalog-' + appType, []), appType };
+ const app = runtime.open(uid, 1, b);
+ const request = new Request(new URL('/__orkas/capabilities.json', app.url));
+ const result = appResource(request, runtime);
+ expect(result?.status).toBe(200);
+ const document = JSON.parse(result!.body!);
+ expect(document.manifest.starter.manifest).toBe(`@skill/web-app-sdk/assets/${appType === 'web' ? 'web' : 'starter'}/orkas-app.json`);
+ expect(document.methods.some((method: any) => method.name === 'ai.generate')).toBe(appType === 'local');
+ runtime.closeOwner(1);
+ expect(appResource(request, runtime)?.status).toBe(403);
+ });
+ it('preserves ordinary SQLite data without requiring a personal sync adapter',async()=>{
+ const definition:any={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]};const b=bundle('offline-data',['data']);b.appType='local';b.manifest={sdkVersion:1,capabilities:['data'],data:definition};const app=runtime.open(uid,1,b);await call(app.token,'data.insert',{table:'notes',values:{body:'local only'}});runtime.closeOwner(1);await runtime.drainData();
+ const {webAppSandboxRoot}=await import('../../../src/main/paths');expect(nativeFs.existsSync(path.join(webAppSandboxRoot(uid,b.key,'local'),'data.sqlite'))).toBe(true);expect(nativeFs.existsSync(path.join(webAppSandboxRoot(uid,b.key,'cloud'),'database.snapshot'))).toBe(false);const reopened=runtime.open(uid,1,b);expect(await call(reopened.token,'data.query',{table:'notes'})).toEqual({records:[{body:'local only'}]});
+ });
+ it('runs real common SQLite calls with the same visitor rules and preserves formal records across reopen',async()=>{
+ const definition={version:1,tables:[{id:'messages',name:'messages',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body'],count:true}}]};
+ const b={...bundle('common',['data']),appType:'local' as const,manifest:{sdkVersion:1,capabilities:['data'],data:definition}};
+ const first=runtime.open(uid,1,b);
+ await call(first.token,'data.insert',{table:'messages',values:{body:'KEEP'}});
+ expect(await call(first.token,'data.query',{table:'messages',fields:['body']})).toEqual({records:[{body:'KEEP'}]});
+ await expect(call(first.token,'data.query',{table:'messages',fields:['private']})).rejects.toMatchObject({code:'E_PERMISSION'});
+ // A generated app may sort by a reserved timestamp without declaring read
+ // authority. Denial must leave the saved row available to a valid query.
+ await expect(call(first.token,'data.query',{table:'messages',fields:['body'],order:{field:'createdAt',direction:'desc'}})).rejects.toMatchObject({code:'E_PERMISSION'});
+ expect(await call(first.token,'data.query',{table:'messages',fields:['body']})).toEqual({records:[{body:'KEEP'}]});
+ runtime.closeOwner(1);await runtime.drainData();runtime=new mod.WebAppRuntime(host);
+ const reopened=runtime.open(uid,1,b);
+ expect(await call(reopened.token,'data.count',{table:'messages'})).toEqual({count:1});
+ const previewRoot=path.join(root,'preview-common');await fs.mkdir(previewRoot);
+ const preview=new mod.WebAppRuntime(host,{storageRoot:previewRoot});const test=preview.open(uid,2,b);
+ expect(await preview.call(uid,2,test.token,'preview-q','data.count',{table:'messages'})).toEqual({count:0});
+ await preview.call(uid,2,test.token,'preview-w','data.insert',{table:'messages',values:{body:'TEST'}});
+ preview.closeOwner(2);await preview.drainData();
+ expect(await call(reopened.token,'data.count',{table:'messages'})).toEqual({count:1});
+ });
+ it('refuses a known web bundle before granting a runtime instance, including after manifest mutation', () => {
+ const b = { ...bundle('cloud', []), appType: 'web' as const };
+ for (const capabilities of [[], ['ai', 'storage']]) {
+ (b.manifest as any).capabilities = capabilities;
+ expect(() => runtime.open(uid, 1, b)).toThrowError(expect.objectContaining({ code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' }));
+ }
+ expect(host.generate).not.toHaveBeenCalled(); expect(host.tools).not.toHaveBeenCalled();
+ });
+
it('reads complete picked and sandbox files when the filesystem returns short chunks', async () => {
const source = path.join(root, 'chunked.txt');
const text = '完整内容 αβ — complete payload';
@@ -430,6 +578,82 @@ it.each(['switch', 'revoke', 'cancel'])('does not publish sandbox bytes after %s
} finally { spy.mockRestore(); syncBuiltinESMExports(); }
});
+// Storage calls run on the main process, so an unchanged store must not be
+// re-read and re-parsed for every call; any external replacement (a synced
+// copy, an in-place rewrite) must still be seen, and a failed write must not
+// leave a value that never reached the disk.
+describe('app storage reuse', () => {
+ const storeReads = () => {
+ const realRead = nativeFs.promises.readFile.bind(nativeFs.promises);
+ const reads: string[] = [];
+ const spy = vi.spyOn(nativeFs.promises, 'readFile').mockImplementation(async (...args: any[]) => {
+ if (String(args[0]).endsWith('.json')) reads.push(String(args[0]));
+ return (realRead as any)(...args);
+ });
+ syncBuiltinESMExports();
+ return { reads, restore: () => { spy.mockRestore(); syncBuiltinESMExports(); } };
+ };
+
+ it('reads an unchanged store once while the app stays open and writes the same bytes', async () => {
+ const paths = await import('../../../src/main/paths');
+ const key = bundle('reuse').key;
+ const file = paths.webAppDataFile(uid, key);
+ const a = open('reuse', ['storage']);
+ await call(a.token, 'storage.set', { key: 'draft', value: { text: 'first' } });
+ const probe = storeReads();
+ try {
+ for (let i = 0; i < 5; i++) {
+ expect(await call(a.token, 'storage.get', { key: 'draft' })).toEqual({ value: { text: 'first' } });
+ }
+ expect(await call(a.token, 'storage.keys')).toEqual({ keys: ['draft'] });
+ await call(a.token, 'storage.set', { key: 'count', value: 2 });
+ expect(await call(a.token, 'storage.get', { key: 'count' })).toEqual({ value: 2 });
+ expect(probe.reads).toEqual([]);
+ expect(nativeFs.readFileSync(file, 'utf8'))
+ .toBe(JSON.stringify({ version: 1, entries: { draft: { text: 'first' }, count: 2 } }, null, 2));
+
+ // Closing the last instance releases the parsed store.
+ runtime.close(uid, 1, a.token);
+ const again = open('reuse', ['storage']);
+ expect(await call(again.token, 'storage.get', { key: 'count' })).toEqual({ value: 2 });
+ expect(probe.reads).toEqual([file]);
+ } finally { probe.restore(); }
+ });
+
+ it('sees replaced and rewritten stores and keeps the stored value when a write fails', async () => {
+ const paths = await import('../../../src/main/paths');
+ const key = bundle('external').key;
+ const a = open('external', ['storage']);
+ for (const scope of ['local', 'cloud'] as const) {
+ const file = paths.webAppDataFile(uid, key, scope);
+ await call(a.token, 'storage.set', { key: 'draft', value: 'v1', scope });
+ expect(await call(a.token, 'storage.get', { key: 'draft', scope })).toEqual({ value: 'v1' });
+
+ // A synced copy replaces the file through a temp file and rename.
+ const tmp = file + '.sync.tmp';
+ await fs.writeFile(tmp, JSON.stringify({ version: 1, entries: { draft: 'v2' } }));
+ await fs.rename(tmp, file);
+ expect(await call(a.token, 'storage.get', { key: 'draft', scope })).toEqual({ value: 'v2' });
+
+ // An in-place rewrite of the same size is still a different store.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ await fs.writeFile(file, JSON.stringify({ version: 1, entries: { draft: 'v3' } }));
+ expect(await call(a.token, 'storage.get', { key: 'draft', scope })).toEqual({ value: 'v3' });
+
+ // Guarded atomic writes publish with renameSync.
+ const rename = vi.spyOn(nativeFs, 'renameSync').mockImplementationOnce(() => {
+ throw Object.assign(new Error('disk full'), { code: 'ENOSPC' });
+ });
+ syncBuiltinESMExports();
+ try {
+ await expect(call(a.token, 'storage.set', { key: 'draft', value: 'lost', scope })).rejects.toMatchObject({ code: 'ENOSPC' });
+ } finally { rename.mockRestore(); syncBuiltinESMExports(); }
+ expect(await call(a.token, 'storage.get', { key: 'draft', scope })).toEqual({ value: 'v3' });
+ expect(await call(a.token, 'storage.keys', { scope })).toEqual({ keys: ['draft'] });
+ }
+ });
+});
+
// A working notebook must grow beyond the old demo quotas and stay usable.
it('persists larger files and JSON, many entries and long-lived request sequences', async () => {
const app = open('growing-notebook', ['storage', 'appFiles']);
@@ -449,7 +673,7 @@ it('persists larger files and JSON, many entries and long-lived request sequence
const reopened = open('growing-notebook', ['storage', 'appFiles']);
expect(await call(reopened.token, 'appFiles.readText', { path: 'large.txt' })).toEqual({ text });
expect(await call(reopened.token, 'storage.get', { key: 'new' })).toEqual({ value: 'retained' });
- for (let i = 0; i < 4200; i++) await call(reopened.token, 'host.getContext');
+ for (let i = 0; i < 20000; i++) await call(reopened.token, 'host.getContext');
expect(await call(reopened.token, 'storage.get', { key: 'new' })).toEqual({ value: 'retained' });
await expect(runtime.call(uid, 1, reopened.token, 'q' + seq, 'storage.remove', { key: 'new' }))
.rejects.toMatchObject({ code: 'E_DUPLICATE' });
@@ -467,6 +691,35 @@ it('remembers cancelled and completed SDK ids out of order without rejecting int
expect(await runtime.call(uid, 1, a.token, 'q6', 'storage.keys', {})).toEqual({ keys: ['q1', 'q2', 'q3', 'q5'] });
});
+it.each(['custom', 'sparse', 'documents'])('bounds an identity flood, preserves replay protection, and recovers by reopening (%s)', async shape => {
+ const a = open();
+ let limited = 0;
+ for (let n = 0; n < 100000; n++) {
+ const id = shape === 'custom' ? 'custom_' + n : shape === 'sparse' ? 'q' + (2 * n + 1) : 'd' + n.toString(16).padStart(32, '0') + 'q1';
+ try { runtime.cancel(uid, 1, a.token, id); }
+ catch (error) { expect(error).toMatchObject({ code: 'E_LIMIT' }); limited++; }
+ }
+ expect(limited).toBeGreaterThan(90000);
+ const first = shape === 'custom' ? 'custom_0' : shape === 'sparse' ? 'q1' : 'd' + '0'.repeat(32) + 'q1';
+ await expect(runtime.call(uid, 1, a.token, first, 'storage.set', { key: 'replayed', value: true })).rejects.toMatchObject({ code: 'E_DUPLICATE' });
+ await expect(runtime.call(uid, 1, a.token, 'fresh', 'storage.set', { key: 'replayed', value: true })).rejects.toMatchObject({ code: 'E_LIMIT' });
+ const other = open(); expect(await runtime.call(uid, 1, other.token, 'q1', 'storage.get', { key: 'replayed' })).toEqual({ value: null });
+ runtime.close(uid, 1, a.token);
+ const reopened = open(); expect(await runtime.call(uid, 1, reopened.token, first, 'host.getContext', {})).toMatchObject({ sdkVersion: 1 });
+});
+
+it('still cancels accepted work after the replay history is exhausted', async () => {
+ const a = open(); let started!: () => void;
+ const gate = new Promise<void>(resolve => { started = resolve; });
+ host.generate = async (_uid, _args, signal) => { started(); await new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true })); return { text: 'discarded' }; };
+ const work = runtime.call(uid, 1, a.token, 'running', 'ai.generate', { prompt: 'Controlled operation' });
+ const outcome = expect(work).rejects.toMatchObject({ code: 'E_CANCELLED' }); await gate;
+ let saturated = false;
+ for (let i = 0; i < 9000; i++) { try { runtime.cancel(uid, 1, a.token, 'cancel_' + i); } catch { saturated = true; break; } }
+ expect(saturated).toBe(true);
+ runtime.cancel(uid, 1, a.token, 'running'); await outcome;
+});
+
it('lets the owning service complete long work without an additional SDK deadline', async () => {
vi.useFakeTimers();
let finish!: (value: unknown) => void;
@@ -524,6 +777,104 @@ it('keeps acknowledged browser calls alive until result or explicit cancellation
} finally { vi.useRealTimers(); }
});
+async function browserSdkHarness() {
+ const { runInNewContext } = await import('node:vm');
+ const source = await fs.readFile(path.resolve('src/main/features/web_apps/sdk.js'), 'utf8');
+ const listeners: Record<string, (event?: any) => void> = {};
+ const messages: any[] = [];
+ const parent = { postMessage: vi.fn(message => { messages.push(structuredClone(message)); }) };
+ const window: any = { parent, addEventListener: (type: string, fn: any) => { listeners[type] = fn; } };
+ runInNewContext(source, { window, parent, setTimeout, clearTimeout, structuredClone, crypto: (await import('node:crypto')).webcrypto });
+ return { call: window.orkasApp.call, listeners,
+ calls: () => messages.filter(message => message.type === 'call'),
+ result: (id: string, value: unknown) => listeners.message({ source: parent,
+ data: { __orkasApp: 1, id, type: 'result', ok: true, value } }),
+ };
+}
+
+it('discovers the host before first inference so a cold service cannot expire host discovery', async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = await browserSdkHarness();
+ const input = { prompt: 'Cold inference', maxTokens: 128 };
+ const work = sdk.call('ai.generate', input);
+ input.prompt = 'Changed after the call';
+ let status = 'pending';
+ void work.then(() => { status = 'resolved'; }, () => { status = 'rejected'; });
+ expect(sdk.calls().map(call => call.method)).toEqual(['host.getContext']);
+ sdk.result(sdk.calls()[0].id, { sdkVersion: 1 });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sdk.calls().map(call => call.method)).toEqual(['host.getContext', 'ai.generate']);
+ expect(sdk.calls()[1].args).toEqual({ prompt: 'Cold inference', maxTokens: 128 });
+ await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
+ expect(status).toBe('pending');
+ expect(sdk.calls()).toHaveLength(2);
+ sdk.result(sdk.calls()[1].id, { text: 'One completed inference' });
+ expect(await work).toEqual({ text: 'One completed inference' });
+ } finally { vi.useRealTimers(); }
+});
+
+it('shares inference discovery and never dispatches an operation cancelled while waiting', async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = await browserSdkHarness();
+ const controller = new AbortController();
+ const cancelled = sdk.call('ai.generate', { prompt: 'Cancelled operation' }, { signal: controller.signal });
+ const outcome = expect(cancelled).rejects.toMatchObject({ code: 'E_CANCELLED' });
+ const kept = sdk.call('ai.generate', { prompt: 'Kept operation' });
+ expect(sdk.calls().map(call => call.method)).toEqual(['host.getContext']);
+ controller.abort();
+ await outcome;
+ sdk.result(sdk.calls()[0].id, { sdkVersion: 1 });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sdk.calls().map(call => call.method)).toEqual(['host.getContext', 'ai.generate']);
+ expect(sdk.calls()[1].args).toEqual({ prompt: 'Kept operation' });
+ sdk.result(sdk.calls()[1].id, { text: 'Completed' });
+ expect(await kept).toEqual({ text: 'Completed' });
+ } finally { vi.useRealTimers(); }
+});
+
+it('does not start late inference when the document departs just after discovery resolves', async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = await browserSdkHarness();
+ const work = sdk.call('ai.generate', { prompt: 'Departing document' });
+ const outcome = expect(work).rejects.toMatchObject({ code: 'E_CLOSED' });
+ expect(sdk.calls().map(call => call.method)).toEqual(['host.getContext']);
+ sdk.result(sdk.calls()[0].id, { sdkVersion: 1 });
+ sdk.listeners.pagehide();
+ await outcome;
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sdk.calls().map(call => call.method)).toEqual(['host.getContext']);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally { vi.useRealTimers(); }
+});
+
+it('keeps missing-host discovery bounded without dispatching inference or retrying it', async () => {
+ vi.useFakeTimers();
+ try {
+ const sdk = await browserSdkHarness();
+ const work = sdk.call('ai.generate', { prompt: 'Unavailable host' });
+ const outcome = expect(work).rejects.toMatchObject({ code: 'E_HOST_UNAVAILABLE' });
+ await vi.advanceTimersByTimeAsync(10_000);
+ await outcome;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(sdk.calls().map(call => call.method)).toEqual(['host.getContext']);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally { vi.useRealTimers(); }
+});
+
+it('retains serialization failure and cancellation during input snapshot without contacting the host', async () => {
+ const sdk = await browserSdkHarness();
+ await expect(sdk.call('ai.generate', { prompt: 'Invalid', unsupported: () => {} }))
+ .rejects.toMatchObject({ code: 'E_INPUT' });
+ const controller = new AbortController();
+ const input = { get prompt() { controller.abort(); return 'Must not dispatch'; } };
+ await expect(sdk.call('ai.generate', input, { signal: controller.signal }))
+ .rejects.toMatchObject({ code: 'E_CANCELLED' });
+ expect(sdk.calls()).toEqual([]);
+});
+
it('can select more than sixteen files and release snapshots independently', async () => {
const source = path.join(root, 'selected.txt');
await fs.writeFile(source, 'Selected content');
@@ -632,3 +983,102 @@ it('shares initial host discovery across concurrent requests and cancels all wor
expect(vi.getTimerCount()).toBe(0);
} finally { vi.useRealTimers(); }
});
+
+it('matches the shared independent data contract fixtures through the real browser runtime',async()=>{
+ const fixture=JSON.parse(await fs.readFile(path.resolve(__dirname,'../../fixtures/app-data-v1.json'),'utf8'));
+ const b=bundle('conformance',['data']);b.appType='local';b.manifest={sdkVersion:1,capabilities:['data'],data:fixture.definition};const app=runtime.open(uid,1,b);
+ for(const values of fixture.inserts)await call(app.token,'data.insert',{table:'items',values});
+ for(const [method,key] of [['data.query','queries'],['data.aggregate','aggregates']])for(const test of fixture[key])expect(await call(app.token,method,test.args)).toEqual(test.expected);
+ for(const test of fixture.rejections){const result=call(app.token,test.method,test.args);if(test.code)await expect(result).rejects.toMatchObject({code:test.code});else await expect(result).rejects.toBeInstanceOf(Error);}
+ expect(await call(app.token,'data.count',{table:'items'})).toEqual({count:3});
+ expect(await call(app.token,'data.query',fixture.queries[0].args)).toEqual(fixture.queries[0].expected);
+});
+
+it('fails grouped analytics explicitly when more than one hundred groups match',async()=>{
+ const definition={version:1,tables:[{id:'items',name:'items',fields:[{id:'category',name:'category',type:'string'},{id:'n',name:'n',type:'integer'}],access:{read:['category','n'],insert:['category','n'],aggregate:['n']}}]};
+ const b=bundle('group-boundary',['data']);b.appType='local';b.manifest={sdkVersion:1,capabilities:['data'],data:definition};const app=runtime.open(uid,1,b);
+ for(let n=0;n<101;n++)await call(app.token,'data.insert',{table:'items',values:{category:String(n),n}});
+ await expect(call(app.token,'data.aggregate',{table:'items',field:'n',op:'sum',groupBy:'category'})).rejects.toMatchObject({code:'E_LIMIT'});
+});
+
+// Web type contract. The expected common surface is the published v1 product
+// contract (Common/docs/plans/app-publishing.md), not a copy of commonMethod().
+const WEB_COMMON_V1 = ['capabilities.describe', 'capabilities.list', 'data.aggregate', 'data.count', 'data.insert', 'data.insertIf', 'data.query', 'host.getContext'];
+const webBundle = (name: string, data?: any): Bundle => ({ ...bundle(name, data ? ['data'] : []), appType: 'local',
+ manifest: data ? { sdkVersion: 1, capabilities: ['data'], data } : { sdkVersion: 1, capabilities: [] } });
+const notesDefinition = { version: 1, tables: [{ id: 'notes', name: 'notes', fields: [{ id: 'body', name: 'body', type: 'string' }], access: { read: ['body'], insert: ['body'], count: true } }] };
+
+it('refuses web SDK resource acquisition before exposing any runtime URL or token', () => {
+ const b = { ...webBundle('web-resources'), appType: 'web' as const };
+ expect(() => runtime.open(uid, 1, b)).toThrowError(expect.objectContaining({ code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' }));
+ for (const adapter of [host.pick, host.save, host.generate, host.tools]) expect(adapter).not.toHaveBeenCalled();
+});
+
+it('matches the shared stateful data scenarios: retries, relations, read filters, capacity and stable pages', async () => {
+ // Same fixture steps are replayed against the Server SQLite runtime; expected
+ // values come from the published data contract, never from either runtime.
+ const { scenarios } = JSON.parse(await fs.readFile(path.resolve(__dirname, '../../fixtures/app-data-v1.json'), 'utf8'));
+ const b = webBundle('shared-scenarios', scenarios.definition);
+ let app = runtime.open(uid, 1, b);
+ const saved: Record<string, string> = {};
+ const resolve = (value: any): any => Array.isArray(value) ? value.map(resolve)
+ : value && typeof value === 'object' ? (Object.keys(value).join() === '$ref' ? saved[value.$ref] : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolve(v)]))) : value;
+ for (const [index, step] of scenarios.steps.entries()) {
+ const label = `step ${index}`;
+ if (step.reopen) { runtime.closeOwner(1); await runtime.drainData(); runtime = new mod.WebAppRuntime(host); app = runtime.open(uid, 1, b); continue; }
+ if (step.paginate) {
+ const pages: any[] = [];
+ for (let offset = 0; ; offset += step.pageSize) {
+ const { records } = await call(app.token, 'data.query', { ...step.paginate, limit: step.pageSize, offset });
+ if (!records.length) break; pages.push(...records);
+ }
+ const { records: whole } = await call(app.token, 'data.query', { ...step.paginate, limit: 100 });
+ expect(pages, label).toEqual(whole);
+ expect(pages.map(r => r.rank), label).toEqual(step.expectedRanks);
+ expect(pages.map(r => r.title).sort(), label).toEqual(step.expectedTitles);
+ continue;
+ }
+ const result = call(app.token, step.method, resolve(step.args));
+ if (step.code) { await expect(result, label).rejects.toMatchObject({ code: step.code }); continue; }
+ const value = await result;
+ if (step.expected) expect(value, label).toEqual(step.expected);
+ if (step.sameIdAs) expect(value, label).toEqual({ id: saved[step.sameIdAs] });
+ if (step.save) saved[step.save] = value.id;
+ }
+});
+
+it('isolates formal data by application and account and closes the previous account immediately', async () => {
+ const first = webBundle('isolated-a', notesDefinition), second = webBundle('isolated-b', notesDefinition);
+ const a = runtime.open(uid, 1, first), b = runtime.open(uid, 1, second);
+ await call(a.token, 'data.insert', { table: 'notes', values: { body: 'A private' } });
+ expect(await call(b.token, 'data.query', { table: 'notes' })).toEqual({ records: [] });
+ uid = 'account-b';
+ await expect(runtime.call('account-a', 1, a.token, 'after-switch', 'data.query', { table: 'notes' })).rejects.toMatchObject({ code: 'E_CLOSED' });
+ await expect(runtime.call('account-a', 1, a.token, 'after-switch-write', 'data.insert', { table: 'notes', values: { body: 'late' } })).rejects.toMatchObject({ code: 'E_CLOSED' });
+ runtime.closeUser('account-a'); await runtime.drainData();
+ const other = runtime.open(uid, 1, first);
+ expect(await call(other.token, 'data.count', { table: 'notes' })).toEqual({ count: 0 });
+ await call(other.token, 'data.insert', { table: 'notes', values: { body: 'B private' } });
+ runtime.closeUser(uid); await runtime.drainData();
+ uid = 'account-a';
+ const back = runtime.open(uid, 1, first);
+ expect(await call(back.token, 'data.query', { table: 'notes' })).toEqual({ records: [{ body: 'A private' }] });
+});
+
+it.each(['local'] as const)('rejects record update and delete from a %s app without changing records', async appType => {
+ const b = { ...webBundle('no-mutation-' + appType, notesDefinition), appType };
+ const app = runtime.open(uid, 1, b);
+ const { id } = await call(app.token, 'data.insert', { table: 'notes', values: { body: 'KEEP' } });
+ for (const [method, args] of [['data.update', { table: 'notes', id, values: { body: 'changed' } }], ['data.delete', { table: 'notes', id }], ['data.deleteMany', { table: 'notes' }]] as const)
+ await expect(call(app.token, method, args), method).rejects.toMatchObject({ code: 'E_METHOD' });
+ expect(await call(app.token, 'data.query', { table: 'notes' })).toEqual({ records: [{ body: 'KEEP' }] });
+});
+
+it('bounds concurrently open application databases and recovers once one closes', async () => {
+ const apps = Array.from({ length: 5 }, (_, n) => { const b = webBundle('bounded-' + n, notesDefinition); return { b, app: runtime.open(uid, 1, b) }; });
+ for (const { app } of apps.slice(0, 4)) expect(await call(app.token, 'data.count', { table: 'notes' })).toEqual({ count: 0 });
+ await expect(call(apps[4].app.token, 'data.insert', { table: 'notes', values: { body: 'refused' } })).rejects.toMatchObject({ code: 'E_BUSY' });
+ runtime.close(uid, 1, apps[0].app.token); await runtime.drainData();
+ await call(apps[4].app.token, 'data.insert', { table: 'notes', values: { body: 'accepted' } });
+ expect(await call(apps[4].app.token, 'data.query', { table: 'notes' })).toEqual({ records: [{ body: 'accepted' }] });
+});
diff --git a/test/main/model/core-agent/html-preview-tool.test.ts b/test/main/model/core-agent/html-preview-tool.test.ts
index ebad52c4..4d234f25 100644
--- a/test/main/model/core-agent/html-preview-tool.test.ts
+++ b/test/main/model/core-agent/html-preview-tool.test.ts
@@ -560,7 +560,7 @@ describe('html_preview tool', () => {
const invalidViewport = await tool.execute({
path: 'index.html',
target: 'responsive',
- mobile: { width: 768, height: 844 },
+ mobile: { width: 360.5, height: 844 },
}, context);
const missing = await tool.execute({ path: 'missing.html' }, context);
const outOfScope = await tool.execute({ path: outside }, context);
@@ -573,4 +573,20 @@ describe('html_preview tool', () => {
expect(outOfScope.content).toContain('E_PATH_OUT_OF_SCOPE');
expect(render).not.toHaveBeenCalled();
});
+
+ it('renders with default out-of-range viewport dimensions and preserves valid dimensions', async () => {
+ const { render, tool, workspace, context } = await buildTool();
+ fs.writeFileSync(path.join(workspace, 'index.html'), '<!doctype html><main>OK</main>');
+ const result = await tool.execute({ path: 'index.html', target: 'responsive',
+ desktop: { width: 100, height: 720 }, mobile: { width: 768, height: 10000 } }, context);
+ expect(result.isError).toBeFalsy();
+ expect(render).toHaveBeenCalledOnce();
+ expect(render.mock.calls[0][1]).toEqual([
+ { name: 'desktop', width: 1440, height: 720 }, { name: 'mobile', width: 390, height: 844 },
+ ]);
+ for (const width of [null, 'wide', '100000', 360.5]) {
+ expect((await tool.execute({ path: 'index.html', target: 'mobile', mobile: { width } }, context)).isError).toBe(true);
+ }
+ expect(render).toHaveBeenCalledOnce();
+ });
});
diff --git a/test/main/quality/web-app-sdk-builtin.test.ts b/test/main/quality/web-app-sdk-builtin.test.ts
index 51dd235f..902c16cc 100644
--- a/test/main/quality/web-app-sdk-builtin.test.ts
+++ b/test/main/quality/web-app-sdk-builtin.test.ts
@@ -1,15 +1,77 @@
+import * as vm from 'node:vm';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { validateSkillDir } from '../../../src/main/quality';
-import { catalogDocument, manifestSchema } from '../../../src/main/features/web_apps/catalog';
+import { catalogDocument, manifestSchema, METHODS } from '../../../src/main/features/web_apps/catalog';
import { syncWebAppSdkDocs } from '../../../scripts/web-app-sdk-docs';
const root = path.resolve(__dirname, '../../..');
const relative = 'resources/builtin/system/skills/web-app-sdk';
const skill = path.join(root, relative);
describe('Web app authoring package', () => {
+ it.each(['local', 'web'] as const)('requires a data definition in the documented %s manifest only when data is declared', appType => {
+ const { AjvJsonSchemaValidator } = require('@modelcontextprotocol/sdk/validation/ajv');
+ const validate = new AjvJsonSchemaValidator().getValidator(catalogDocument(appType).manifest.schema);
+ expect(validate({sdkVersion: 1, capabilities: ['data']}).valid).toBe(false);
+ expect(validate({sdkVersion: 1, capabilities: []}).valid).toBe(true);
+ expect(validate({sdkVersion: 1, capabilities: ['data'], data: {version: 1, tables: []}}).valid).toBe(true);
+ });
+
+ it.each(['storage', 'appFiles', 'files', 'ai', 'library', 'connectors', 'data'])('describes the actual web manifest capability boundary for %s while retaining local support', capability => {
+ const { AjvJsonSchemaValidator } = require('@modelcontextprotocol/sdk/validation/ajv');
+ const validator = new AjvJsonSchemaValidator();
+ const manifest = {sdkVersion: 1, capabilities: [capability], data: {version: 1, tables: []}};
+ expect(validator.getValidator(catalogDocument('local').manifest.schema)(manifest).valid).toBe(true);
+ expect(validator.getValidator(catalogDocument('web').manifest.schema)(manifest).valid).toBe(capability === 'data');
+ });
+
+ it.each(['local', 'web'] as const)('exposes the complete %s bundle contract and paired starter before authoring', appType => {
+ const catalog = catalogDocument(appType) as any;
+ expect(catalog.manifest?.file).toBe('orkas-app.json');
+ const { AjvJsonSchemaValidator } = require('@modelcontextprotocol/sdk/validation/ajv');
+ const validate = new AjvJsonSchemaValidator().getValidator(catalog.manifest.schema);
+ const starter = catalog.manifest.starter;
+ const resolve = (logical: string) => path.join(skill, logical.replace('@skill/web-app-sdk/', ''));
+ expect(fs.readFileSync(resolve(starter.entry), 'utf8')).toContain('/__orkas/sdk.js');
+ const example = JSON.parse(fs.readFileSync(resolve(starter.manifest), 'utf8'));
+ expect(validate(example).valid).toBe(true);
+ expect(manifestSchema.safeParse(example).success).toBe(true);
+ // Historical generated shapes must fail independently in the published
+ // JSON schema and the host validator, rather than only in a text rubric.
+ for (const invalid of [
+ { capabilities: ['data'] }, { sdkVersion: 2, capabilities: [] },
+ { sdkVersion: 1, capabilities: { data: true } },
+ { sdkVersion: 1, capabilities: ['shell'] },
+ { ...example, appType }, { ...example, name: 'Notes', version: '1' },
+ { sdkVersion: 1, interfaces: { data: {} } },
+ ]) {
+ expect(validate(invalid).valid).toBe(false);
+ expect(manifestSchema.safeParse(invalid).success).toBe(false);
+ }
+ });
+ it('retries an uncertain starter submission without duplicating its committed record',async()=>{
+ const source=fs.readFileSync(path.join(skill,'assets/web/index.html'),'utf8').split('<script>')[1].split('</script>')[0];let failed=false,ids=0;const status={textContent:''};const committed=new Map<string,string>();const requests:any[]=[];const form:any={body:{value:'First'},querySelector:()=>({disabled:false}),reset(){this.body.value='';}};
+ const api={data:{query:async()=>{if(failed&&requests.length>1)throw new Error('E_BUSY');return {records:[]};},insert:async(args:any)=>{requests.push(structuredClone(args));committed.set(args.requestId,args.values.body);if(!failed){failed=true;throw new Error('E_BUSY');}return {id:args.requestId};}}};
+ vm.runInNewContext(source,{window:{orkasApp:api},document:{querySelector:(q:string)=>q==='form'?form:q==='ul'?{replaceChildren(){},append(){}}:status},crypto:{randomUUID:()=>String(++ids)}});
+ await form.onsubmit({preventDefault(){}});form.body.value='Changed after timeout';await form.onsubmit({preventDefault(){}});
+ expect(committed.size).toBe(1);expect(requests[1]).toEqual(requests[0]);expect([...committed.values()]).toEqual(['First']);expect(status.textContent).toContain('Saved');
+ });
+ it('rejects malformed common definitions before an author can create or publish them',()=>{
+ const fixture=JSON.parse(fs.readFileSync(path.resolve(root,'test/fixtures/app-data-v1.json'),'utf8'));for(const data of fixture.invalidDefinitions)expect(manifestSchema.safeParse({sdkVersion:1,capabilities:['data'],data}).success).toBe(false);
+ });
+ it('generates the standalone SDK package without creating a sibling Server directory',()=>{
+ const temporary=fs.mkdtempSync(path.join(os.tmpdir(),'orkas-sdk-standalone-'));const standalone=path.join(temporary,'Orkas');fs.mkdirSync(standalone);
+ try{syncWebAppSdkDocs(standalone,false);expect(fs.existsSync(path.join(temporary,'Server'))).toBe(false);expect(()=>syncWebAppSdkDocs(standalone,true)).not.toThrow();}finally{fs.rmSync(temporary,{recursive:true,force:true});}
+ });
+ it('provides runnable examples and explicit result contracts for every common data operation',()=>{
+ for(const [name,method] of Object.entries(METHODS))if(name.startsWith('data.')){expect(method.input.safeParse(method.example).success,name).toBe(true);expect(method.result,name).not.toBe('Structured data result.');}
+ });
+ it('does not expose native account renewal reminders through the app SDK', () => {
+ const catalog = catalogDocument();
+ expect(catalog.unsupported).toContainEqual(expect.objectContaining({capability:'account.renewalReminders'}));
+ });
it('ships a valid self-contained Skill, starter and exact current API reference', () => {
const report = validateSkillDir(skill);
expect(report.ok, JSON.stringify(report.violations)).toBe(true);
@@ -25,10 +87,25 @@ describe('Web app authoring package', () => {
expect(() => syncWebAppSdkDocs(root, true)).not.toThrow();
expect(fs.existsSync(path.join(skill, '_meta.json'))).toBe(false);
});
+ // 2026-10-15 live regression: authors omitted orkas-app.json. The entry owns
+ // the same-call declaration rule once; the web reference no longer mirrors it.
+ it('states the same-call declaration rule once, in the entry every app type reads',()=>{
+ const body=fs.readFileSync(path.join(skill,'SKILL.md'),'utf8').replace(/\s+/g,' ');
+ expect(body).toContain('Include `orkas-app.json` in that same call, declaring every SDK capability the app uses');
+ for(const reference of ['common.md','local.md','web.md'])
+ expect(fs.readFileSync(path.join(skill,'references',reference),'utf8').replace(/\s+/g,' ')).not.toMatch(/in orkas-app\.json when using data|orkas-app\.json[^.]*same call/);
+ });
+ it('cloud guidance and generated contract contain only actually common interfaces',()=>{
+ const cloud=JSON.parse(fs.readFileSync(path.join(skill,'references/web-api.json'),'utf8'));
+ expect(cloud.methods.map((method:any)=>method.name)).toContain('data.insert');
+ expect(cloud.methods.map((method:any)=>method.name)).not.toContain('ai.generate');
+ expect(cloud.methods.map((method:any)=>method.name)).not.toContain('tools.call');
+ expect(fs.readFileSync(path.join(skill,'SKILL.md'),'utf8')).toContain('references/web.md');
+ });
- it('rejects a stale public Skill API reference and restores it from the executable registry', () => {
- const target = `${relative}/references/api.json`;
- const isolated = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-sdk-docs-'));
+ it.each(['docs/reference/web-app-sdk.json', `${relative}/references/api.json`])('rejects stale %s and restores it from the executable registry', target => {
+ const temporary=fs.mkdtempSync(path.join(os.tmpdir(),'orkas-sdk-docs-'));
+ const isolated=path.join(temporary,'Orkas');fs.mkdirSync(isolated);
try {
syncWebAppSdkDocs(isolated, false);
fs.writeFileSync(path.join(isolated, target), '{"sdkVersion":999}');
@@ -36,6 +113,6 @@ describe('Web app authoring package', () => {
syncWebAppSdkDocs(isolated, false);
expect(() => syncWebAppSdkDocs(isolated, true)).not.toThrow();
expect(JSON.parse(fs.readFileSync(path.join(isolated, target), 'utf8'))).toEqual(catalogDocument());
- } finally { fs.rmSync(isolated, {recursive:true, force:true}); }
+ } finally { fs.rmSync(temporary, {recursive:true, force:true}); }
});
});
diff --git a/test/renderer/artifact-submit.test.ts b/test/renderer/artifact-submit.test.ts
new file mode 100644
index 00000000..f25015b8
--- /dev/null
+++ b/test/renderer/artifact-submit.test.ts
@@ -0,0 +1,97 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+import { expect, it, vi } from 'vitest';
+
+function setup(failOpen = false) {
+ const listeners = new Map<string, Function[]>();
+ const frames: any[] = [];
+ function element(tag = 'div'): any {
+ const events = new Map<string, Function[]>();
+ const e: any = { tagName: tag, dataset: {}, style: {}, children: [], isConnected: true,
+ classList: { contains: () => false }, addEventListener(t: string, fn: Function) { events.set(t, [...(events.get(t) || []), fn]); },
+ dispatchEvent(ev: any) { for (const fn of events.get(ev.type) || []) fn(ev); return !ev.defaultPrevented; },
+ removeAttribute(k: string) { delete this[k]; },
+ remove() { this.parentNode.children = this.parentNode.children.filter((c: any) => c !== this); },
+ insertBefore(child: any) { this.appendChild(child); }, querySelector: () => null,
+ setAttribute(k: string, v: string) { this[k] = v; }, getAttribute(k: string) { return this[k]; },
+ appendChild(child: any) { this.children.push(child); child.parentNode = this; } };
+ if (tag === 'iframe') { e.contentWindow = {}; frames.push(e); }
+ return e;
+ }
+ const invoke = vi.fn(async channel => channel === 'webApps.open'
+ ? failOpen ? { ok: false, error: 'Could not open' } : { ok: true, token: 'a'.repeat(32), url: 'chat-app://app-fixture/index.html', sdkVersion: 1 }
+ : channel === 'webApps.canSubmitArtifact' ? { ok: true, allowed: true } : {});
+ const send = vi.fn(async () => ({}));
+ const alert = vi.fn();
+ const context: any = { URL, uiAlert: alert, CustomEvent: class { type: string; detail: any; defaultPrevented = false; cancelable: boolean; constructor(type: string, options: any = {}) { this.type = type; this.detail = options.detail; this.cancelable = options.cancelable; } preventDefault() { if (this.cancelable) this.defaultPrevented = true; } }, currentCid: 'source-chat', sendInCurrentConversation: send,
+ document: { createElement: element, querySelectorAll: () => frames, documentElement: {} },
+ MutationObserver: class { observe() {} },
+ window: { orkas: { invoke }, addEventListener(type: string, fn: Function) {
+ listeners.set(type, [...(listeners.get(type) || []), fn]);
+ } } };
+ context.globalThis = context.window;
+ vm.createContext(context);
+ for (const name of ['artifact-security', 'commercial-entry', 'web-app-host', 'chat-artifact'])
+ vm.runInContext(readFileSync(path.resolve(__dirname, `../../src/renderer/modules/${name}.js`), 'utf8'), context);
+ context.window.renderChatArtifact(element(), { cid: 'source-chat', artifactId: 'artifact', agentId: 'commander', title: 'Form' });
+ const frame = frames[0];
+ const event = (payload: unknown = { answer: 'ready' }) => ({ source: frame.contentWindow, origin: 'chat-app://app-fixture',
+ data: { __orkasArtifact: true, type: 'submit', payload, cid: 'attacker-chat', agentId: 'attacker' } });
+ const dispatch = async (ev = event()) => { for (const fn of listeners.get('message') || []) await fn(ev); };
+ return { context, frame, invoke, send, event, dispatch, alert, element, frames };
+}
+
+it('submits a local SDK result through the owning chat and ignores caller-supplied routing', async () => {
+ const h = setup(); await vi.waitFor(() => expect(h.frame.src).toBe('chat-app://app-fixture/index.html'));
+ await h.dispatch();
+ expect(h.send).toHaveBeenCalledOnce();
+ expect(h.send.mock.calls[0][0]).toContain('"answer":"ready"');
+ expect(h.send.mock.calls[0][0]).not.toContain('attacker');
+ h.invoke.mockResolvedValueOnce({ ok: true, allowed: false });
+ await h.dispatch(); expect(h.send).toHaveBeenCalledOnce();
+ await h.dispatch({ ...h.event(), origin: 'https://external.invalid' });
+ expect(h.send).toHaveBeenCalledOnce();
+});
+
+it.each(['chat-switch', 'frame-replaced', 'frame-removed', 'artifact-rebound'])(
+ 'discards an in-flight SDK submission after %s without sending to the new target', async change => {
+ const h = setup(); await vi.waitFor(() => expect(h.frame.src).toBe('chat-app://app-fixture/index.html'));
+ let release!: (value: any) => void;
+ h.invoke.mockImplementationOnce(async () => new Promise(resolve => { release = resolve; }));
+ const pending = h.dispatch(); await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ if (change === 'chat-switch') h.context.currentCid = 'another-chat';
+ if (change === 'frame-removed') h.frame.isConnected = false;
+ if (change === 'artifact-rebound') h.frame.dataset.artifactId = 'another-artifact';
+ if (change === 'frame-replaced') h.context.window.OrkasWebAppHost.attach(h.frame,
+ { token: 'b'.repeat(32), url: 'chat-app://app-new/index.html', sdkVersion: 1 });
+ expect(release).toBeTypeOf('function'); release({ ok: true, allowed: true });
+ await pending; expect(h.send).not.toHaveBeenCalled();
+ });
+
+
+it('keeps automatic failures in each card and retries only the selected card', async () => {
+ const h = setup(true);
+ h.context.window.renderChatArtifact(h.element(), { cid: 'source-chat', artifactId: 'second' });
+ await vi.waitFor(() => expect(h.frames.every(f => f._orkasUnavailablePanel)).toBe(true));
+ expect(h.alert).not.toHaveBeenCalled();
+ const retry = h.frame._orkasUnavailablePanel.children.flatMap((c: any) => c.children).find((c: any) => c.tagName === 'button');
+ expect(retry).toBeDefined();
+ h.invoke.mockImplementation(async channel => channel === 'webApps.open'
+ ? { ok: true, token: 'a'.repeat(32), url: 'chat-app://app-fixture/index.html' } : {});
+ retry.dispatchEvent({ type: 'click' });
+ await vi.waitFor(() => expect(h.frame.src).toBe('chat-app://app-fixture/index.html'));
+ expect(h.frame._orkasUnavailablePanel).toBeNull();
+ expect(h.frames[1]._orkasUnavailablePanel).toBeTruthy();
+});
+
+it('keeps explicit viewer feedback and ignores removed frames', async () => {
+ const h = setup(); await vi.waitFor(() => expect(h.frame.src).toBeTruthy());
+ h.invoke.mockResolvedValue({ ok: false, error: 'Could not open' });
+ const viewer = h.element('iframe');
+ await h.context.window.OrkasWebAppHost.open(viewer, {});
+ expect(h.alert).toHaveBeenCalledTimes(1);
+ viewer.isConnected = false;
+ await h.context.window.OrkasWebAppHost.open(viewer, {});
+ expect(h.alert).toHaveBeenCalledTimes(1);
+});
diff --git a/test/renderer/commercial-entry.test.ts b/test/renderer/commercial-entry.test.ts
new file mode 100644
index 00000000..36453572
--- /dev/null
+++ b/test/renderer/commercial-entry.test.ts
@@ -0,0 +1,100 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+
+const source = fs.readFileSync(path.resolve('src/renderer/modules/commercial-entry.js'), 'utf8');
+class Element {
+ children: Element[] = [];
+ dataset: Record<string, string> = {};
+ isConnected = true;
+ textContent = '';
+ className = '';
+ type = '';
+ focus = vi.fn();
+ events = new Map<string, () => unknown>();
+ append(...children: Element[]) { this.children.push(...children); }
+ appendChild(child: Element) { this.children.push(child); return child; }
+ querySelector() { return null; }
+ addEventListener(name: string, handler: () => unknown) { this.events.set(name, handler); }
+ async click() { await this.events.get('click')?.(); }
+}
+function harness(language = 'en') {
+ const focus = new Element();
+ const invoke = vi.fn(async () => ({ ok: true }));
+ const confirm = vi.fn(async () => false);
+ const alert = vi.fn(async () => {});
+ const table = JSON.parse(fs.readFileSync(path.resolve(`src/renderer/locales/${language}.json`), 'utf8'));
+ const context = { window: { orkas: { invoke } } as any, currentCid: 'task', URL,
+ document: { activeElement: focus, createElement: () => new Element() },
+ getLang: () => language, t: (key: string) => table[key] || key, uiConfirm: confirm, uiAlert: alert };
+ vm.runInNewContext(source, context);
+ return { api: context.window.OrkasCommercialEntry, invoke, confirm, alert, focus, table };
+}
+describe('commercial entry actions', () => {
+ it('cancels without opening a link and restores the invoking control', async () => {
+ const h = harness();
+ await h.api.show();
+ expect(h.confirm).toHaveBeenCalledWith({ message: h.table['apps.commercial_required'],
+ okLabel: h.table['apps.commercial_download'], cancelLabel: h.table['common.cancel'] });
+ expect(h.invoke).not.toHaveBeenCalled();
+ expect(h.focus.focus).toHaveBeenCalledExactlyOnceWith({ preventScroll: true });
+ });
+ it.each(['zh', 'zh-tw', 'en', 'fr', 'de', 'hi', 'id', 'it', 'ja', 'ko', 'pt', 'pt-pt', 'ru', 'es', 'es-419', 'th', 'tr', 'vi', 'ar'])('opens the official download page only after confirmation (%s)', async language => {
+ const h = harness(language);
+ h.confirm.mockResolvedValue(true);
+ expect(h.invoke).not.toHaveBeenCalled();
+ await h.api.show();
+ const webLanguage = language.startsWith('zh') ? 'zh' : language.startsWith('pt') ? 'pt' : language === 'ja' ? 'ja' : 'en';
+ expect(h.invoke).toHaveBeenCalledExactlyOnceWith('auth.openExternal', { url: `https://orkas.ai/download/?lang=${webLanguage}` });
+ for (const key of ['apps.commercial_required', 'apps.commercial_download', 'apps.commercial_open_failed']) {
+ expect(typeof h.table[key]).toBe('string'); expect(h.table[key].trim()).not.toBe('');
+ }
+ });
+ it.each(['rejection', 'exception'])('keeps a failed opener recoverable without app operations: %s', async mode => {
+ const h = harness(); h.confirm.mockResolvedValue(true);
+ if (mode === 'exception') h.invoke.mockRejectedValueOnce(new Error('Fixture opener failure'));
+ else h.invoke.mockResolvedValueOnce({ ok: false });
+ await h.api.show();
+ expect(h.alert).toHaveBeenCalledExactlyOnceWith(h.table['apps.commercial_open_failed']);
+ await h.api.show();
+ expect(h.invoke.mock.calls.map(call => call[0])).toEqual(['auth.openExternal', 'auth.openExternal']);
+ });
+ it('coalesces simultaneous entry actions into one standard dialog', async () => {
+ const h = harness(); let finish!: (accepted: boolean) => void;
+ h.confirm.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
+ const a = h.api.show(), b = h.api.show();
+ expect(a).toBe(b); expect(h.confirm).toHaveBeenCalledOnce();
+ finish(false); await a; expect(h.invoke).not.toHaveBeenCalled();
+ });
+ it('shows one independent notice per turn for the structured rejected tool receipt', async () => {
+ const h = harness();
+ const receipt = { ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps', message: 'Model may omit this message' };
+ const event = { stream: 'tool', data: { phase: 'end', name: 'create_artifact', isError: true, output: JSON.stringify(receipt) } };
+ const first = new Element(), second = new Element();
+ first.dataset.turnId = second.dataset.turnId = 'same-turn';
+ h.api.observeToolResult(first, event); h.api.observeToolResult(first, event); h.api.observeToolResult(second, event);
+ expect(first.children).toHaveLength(1); expect(second.children).toHaveLength(0);
+ const row = first.children[0];
+ expect(row.className).toBe('chat-app-nav-row');
+ expect(row.children[0].textContent).toBe(h.table['apps.commercial_required']);
+ expect(h.confirm).not.toHaveBeenCalled(); expect(h.invoke).not.toHaveBeenCalled();
+ await row.children[1].click();
+ expect(h.invoke).toHaveBeenCalledOnce();
+ const next = new Element(); next.dataset.turnId = 'next-turn'; h.api.observeToolResult(next, event);
+ expect(next.children).toHaveLength(1);
+ });
+ it('does not interpret model text, ordinary errors, successful tools or foreign features as authority', () => {
+ const h = harness(); const message = new Element();
+ for (const output of ['Web apps require commercial Orkas', '{bad JSON', JSON.stringify({ code: 'E_FAILED' }),
+ JSON.stringify({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'other' }),
+ JSON.stringify({ ok: true, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' }),
+ JSON.stringify({ code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' })]) {
+ h.api.observeToolResult(message, { stream: 'tool', data: { phase: 'end', name: 'create_artifact', isError: true, output } });
+ }
+ const output = JSON.stringify({ code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ h.api.observeToolResult(message, { stream: 'tool', data: { phase: 'end', name: 'read_files', isError: true, output } });
+ h.api.observeToolResult(message, { stream: 'tool', data: { phase: 'end', name: 'create_artifact', isError: false, output } });
+ expect(message.children).toHaveLength(0); expect(h.invoke).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/renderer/helpers/apps-renderer.ts b/test/renderer/helpers/apps-renderer.ts
new file mode 100644
index 00000000..35f112fa
--- /dev/null
+++ b/test/renderer/helpers/apps-renderer.ts
@@ -0,0 +1,124 @@
+// My Apps renderer journey harness: runs the shipped Apps panel markup from
+// index.html with the real dialogs.js, i18n lookup, escapeHtml, composer and
+// conversation-cache boundaries, then saved-apps.js, inside one `node:vm`
+// context over the shared mini DOM. IPC is the only injected dependency, so
+// cases observe user-visible copy, dialogs and cards instead of private calls.
+// Optional extra modules (for example the commercial publication module) are
+// loaded by the caller in index.html order before saved-apps.js.
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+import ts from 'typescript';
+import { vi } from 'vitest';
+import { composerAccessorSource } from '../composer-test-source';
+import { conversationCacheSource } from '../conversation-cache-test-source';
+import { MiniDocument, MiniElement, MiniEvent, visibleText } from './mini-dom';
+
+const rendererDir = path.join(__dirname, '../../../src/renderer');
+const read = (relative: string) => readFileSync(path.join(rendererDir, relative), 'utf8');
+export const rendererModuleSource = (name: string) => read(`modules/${name}`);
+
+function functionsFrom(file: string, names: string[]): string {
+ const source = read(file);
+ const parsed = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+ const found = parsed.statements.filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text || ''));
+ if (found.length !== names.length) throw new Error(`missing renderer functions in ${file}`);
+ return found.map(node => node.getText(parsed)).join('\n');
+}
+
+const locales = {
+ zh: JSON.parse(read('locales/zh.json')),
+ en: JSON.parse(read('locales/en.json')),
+};
+const appsPanelMarkup = (() => {
+ const html = read('index.html');
+ const start = html.indexOf('<section class="panel" id="panel-apps">');
+ const end = html.indexOf('</section>', start);
+ if (start < 0 || end < 0) throw new Error('Apps panel markup not found');
+ return html.slice(start, end + '</section>'.length);
+})();
+const i18nSource = 'var _tables = __tables; var _currentLang = __lang; function fallbackChain(lang) { return [lang, "en"]; }\n'
+ + functionsFrom('modules/i18n.js', ['_lookup', 't', 'getLang']);
+
+export type Invoke = (channel: string, payload?: any) => any;
+
+export function loadAppsRenderer(options: { invoke: Invoke; lang?: 'zh' | 'en'; before?: Array<{ source: string; filename: string }>;
+ orkas?: Record<string, any>; }) {
+ const document = new MiniDocument();
+ const warnings: any[] = [];
+ const pendingTimers: Array<() => void> = [];
+ const invoke = vi.fn(options.invoke);
+ const window: any = {
+ OrkasArtifactSecurity: { SANDBOX: 'allow-scripts', trustedArtifactMessage: () => false, safeExternalHttpUrl: () => '' },
+ addEventListener: vi.fn(), removeEventListener: vi.fn(), open: vi.fn(), innerWidth: 1280, innerHeight: 800,
+ orkas: { invoke, onPushEvent: () => () => {}, ...options.orkas },
+ };
+ const context: any = {
+ console, Date, Math, Set, Map, Intl, Promise, Object, Array, JSON, Number, String, Error, URL,
+ __tables: locales, __lang: options.lang || 'zh',
+ window, document, navigator: { language: options.lang || 'zh' },
+ MutationObserver: class { observe() {} disconnect() {} },
+ requestAnimationFrame: (callback: () => void) => callback(),
+ setTimeout: (callback: () => void, delay = 0) => { if (!delay) callback(); else pendingTimers.push(callback); return pendingTimers.length; },
+ clearTimeout: () => {},
+ createLogger: () => ({ warn: (...args: any[]) => warnings.push(args), error: (...args: any[]) => warnings.push(args), info: () => {} }),
+ uiIconHtml: () => '',
+ _aiSelectMount: (node: MiniElement, config: { value: string }) => {
+ const trigger = document.createElement('button'); trigger.type = 'button'; node.append(trigger);
+ return { getValue: () => config.value, close: () => {} };
+ },
+ };
+ window.uiIconHtml = context.uiIconHtml;
+ vm.createContext(context);
+ document.body.innerHTML = appsPanelMarkup;
+ document.body.append(Object.assign(document.createElement('textarea'), { id: 'chat-input' }));
+ for (const [source, filename] of [
+ [i18nSource, 'i18n.js'],
+ [functionsFrom('modules/connectors.js', ['escapeHtml']), 'connectors.js'],
+ [read('modules/dialogs.js'), 'dialogs.js'],
+ [composerAccessorSource, 'composer-input.js'],
+ [conversationCacheSource, 'conversation.js'],
+ ] as const) vm.runInContext(source, context, { filename });
+ for (const extra of options.before || []) vm.runInContext(extra.source, context, { filename: extra.filename });
+ vm.runInContext(rendererModuleSource('commercial-entry.js'), context, { filename: 'commercial-entry.js' });
+ vm.runInContext(rendererModuleSource('saved-apps.js'), context, { filename: 'saved-apps.js' });
+
+ const $ = (selector: string) => document.querySelector(selector);
+ const helpers = {
+ context, window, document, invoke, warnings,
+ $, $$: (selector: string) => document.querySelectorAll(selector),
+ cards: () => document.querySelectorAll('#apps-grid .app-card').map(card => card.dataset.appId),
+ card: (id: string) => document.querySelectorAll('#apps-grid .app-card').find(card => card.dataset.appId === id) || null,
+ channels: () => invoke.mock.calls.map(call => call[0]),
+ /** Open the card's "..." menu and choose the action, the way a user does. */
+ async chooseMenuAction(appId: string, action: string) {
+ const card = helpers.card(appId);
+ if (!card) throw new Error(`card ${appId} is not rendered`);
+ card.querySelector('[data-app-more]')!.click();
+ const item = document.querySelector(`.app-row-menu [data-action="${action}"]`);
+ if (!item) throw new Error(`menu action ${action} is not offered`);
+ item.click();
+ await flush();
+ },
+ async showTab(type: 'local' | 'web') {
+ document.querySelector(`[data-app-filter="${type}"]`)!.click();
+ await flush();
+ },
+ openDialogs: () => document.querySelectorAll('.ui-dialog-overlay.open'),
+ dialogText: (overlay: MiniElement) => visibleText(overlay.querySelector('.ui-dialog-message')!),
+ press: (key: string) => document.press(key),
+ input: (element: MiniElement, value: string) => { element.value = value; element.dispatchEvent(new MiniEvent('input')); },
+ };
+ return helpers;
+}
+
+/** Drain promise continuations queued by awaited IPC mocks. */
+export async function flush(rounds = 20) {
+ for (let i = 0; i < rounds; i += 1) await new Promise(resolve => setImmediate(resolve));
+}
+
+export function deferred<T = any>() {
+ let resolve!: (value: T) => void; let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((ok, fail) => { resolve = ok; reject = fail; });
+ return { promise, resolve, reject };
+}
diff --git a/test/renderer/preview-host.test.ts b/test/renderer/preview-host.test.ts
index 4c8e6ffd..6e8ba74e 100644
--- a/test/renderer/preview-host.test.ts
+++ b/test/renderer/preview-host.test.ts
@@ -58,3 +58,14 @@ describe('non-conversation image previews', () => {
})]);
});
});
+
+
+it('preserves a structured commercial refusal for the invoking viewer to present', async () => {
+ const receipt = { ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' };
+ const alert = vi.fn(), invoke = vi.fn(async () => receipt);
+ const context: any = { uiAlert: alert, window: { orkas: { invoke, onPushEvent: vi.fn() } } };
+ vm.runInNewContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/commercial-entry.js'), 'utf8'), context);
+ vm.runInNewContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/preview-windows.js'), 'utf8'), context);
+ await expect(context.window.OrkasPreviewWindows.open({ kind: 'file', path: '/fixture/app.html' })).resolves.toBe(receipt);
+ expect(alert).not.toHaveBeenCalled(); expect(invoke).toHaveBeenCalledOnce();
+});
diff --git a/test/renderer/save-as-app-entry-visibility.test.ts b/test/renderer/save-as-app-entry-visibility.test.ts
new file mode 100644
index 00000000..0dd3b074
--- /dev/null
+++ b/test/renderer/save-as-app-entry-visibility.test.ts
@@ -0,0 +1,173 @@
+// "Save as app" is offered from the file preview button and the conversation
+// file menu. Oracle: docs/test/my-apps-regression.md 保存入口 2/3 — only
+// HTML/HTM, CSS and JS/MJS application sources and directories containing an
+// HTML entry offer it; images, JSON, audio/video, manifests, fonts, WASM,
+// models, PDF, ZIP and plain directories never do, even beside an HTML entry.
+// The inspection IPC is forwarded to the real main-process inspector over real
+// files, so neither surface's result is decided by the fixture.
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+import { drainMainRuntimeForTest } from '../helpers/drain-main-runtime';
+
+vi.mock('../../src/main/model/client', () => ({
+ async *streamChatWithModel() { yield { type: 'done' }; },
+ async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },
+}));
+
+const modulesDir = path.resolve(__dirname, '../../src/renderer/modules');
+const viewerSource = fs.readFileSync(path.join(modulesDir, 'chat-file-viewer.js'), 'utf8');
+const policySource = fs.readFileSync(path.join(modulesDir, 'file-operation-policy.js'), 'utf8');
+const infoSource = fs.readFileSync(path.join(modulesDir, 'conversation-info.js'), 'utf8');
+
+function extractFunction(source: string, name: string): string {
+ const marker = source.indexOf(`async function ${name}(`) >= 0 ? `async function ${name}(` : `function ${name}(`;
+ const start = source.indexOf(marker);
+ if (start < 0) throw new Error(`missing ${name}`);
+ const braceStart = source.indexOf('{', source.indexOf(')', start));
+ for (let i = braceStart, depth = 0; i < source.length; i += 1) {
+ if (source[i] === '{') depth += 1;
+ else if (source[i] === '}' && --depth === 0) return source.slice(start, i + 1);
+ }
+ throw new Error(`unterminated ${name}`);
+}
+
+let tmpDir = '', workspace = '', previousRoot: string | undefined;
+let inspect: (target: string, opts: { fenceRoots: string[] }) => Promise<any>;
+const saveable: string[] = ['app/index.html', 'app/page.htm', 'app/style.css', 'app/app.js', 'app/module.mjs', 'app'];
+const notSaveable: string[] = ['app/logo.png', 'app/photo.jpg', 'app/icon.svg', 'app/data.json', 'app/site.webmanifest',
+ 'app/sound.mp3', 'app/clip.mp4', 'app/font.woff2', 'app/module.wasm', 'app/model.glb', 'app/report.pdf', 'app/bundle.zip',
+ 'app/assets', 'docs'];
+
+beforeAll(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-save-entry-'));
+ previousRoot = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ workspace = path.join(tmpDir, 'workspace');
+ fs.mkdirSync(path.join(workspace, 'app', 'assets'), { recursive: true });
+ fs.mkdirSync(path.join(workspace, 'docs'), { recursive: true });
+ fs.writeFileSync(path.join(workspace, 'app', 'index.html'), '<!doctype html><title>Arcade</title>');
+ for (const rel of [...saveable, ...notSaveable]) {
+ const abs = path.join(workspace, rel);
+ if (rel === 'app' || rel === 'app/assets' || rel === 'docs' || fs.existsSync(abs)) continue;
+ fs.writeFileSync(abs, `fixture ${rel}`);
+ }
+ fs.writeFileSync(path.join(workspace, 'app', 'assets', 'sprite.png'), 'fixture sprite');
+ fs.writeFileSync(path.join(workspace, 'docs', 'notes.md'), '# notes');
+ const savedApps = await import('../../src/main/features/saved_apps');
+ inspect = savedApps.inspectBundleFromPath;
+});
+
+afterAll(async () => {
+ await drainMainRuntimeForTest();
+ if (previousRoot === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previousRoot;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+// The renderer sends only its payload; main applies the workspace fence.
+const inspectionIpc = vi.fn(async (channel: string, payload: { path: string }) => {
+ if (channel !== 'savedApps.inspectBundleFromPath') throw new Error(`unexpected channel: ${channel}`);
+ return inspect(payload.path, { fenceRoots: [workspace] });
+});
+
+function fileViewer(invoke: (channel: string, payload: any) => Promise<any>) {
+ const warnings: unknown[] = [];
+ const context: any = { window: { orkas: { invoke } }, warnings };
+ vm.createContext(context);
+ vm.runInContext(`
+ var _viewerSaveAppBtn = { hidden: true, disabled: true };
+ var _viewerCurrentPath = null, _viewerCurrentCid = 'conversation-1', _viewerCurrentProjectId = null;
+ var _viewerLog = { warn: (...args) => warnings.push(args) };
+ function _isViewerOpen() { return true; }
+ ${extractFunction(viewerSource, '_viewerFileActionPayload')}
+ ${extractFunction(viewerSource, '_setSaveAppVisible')}
+ ${extractFunction(viewerSource, '_refreshSaveAppButton')}
+ async function previewSaveAppVisible(target) {
+ _viewerCurrentPath = target;
+ await _refreshSaveAppButton(target);
+ return !_viewerSaveAppBtn.hidden && !_viewerSaveAppBtn.disabled;
+ }`, context, { filename: 'chat-file-viewer.js' });
+ return { visible: (target: string) => context.previewSaveAppVisible(target) as Promise<boolean>, warnings };
+}
+
+class MenuNode {
+ id = ''; className = '';
+ readonly classList = { add() {}, remove() {}, toggle() {} };
+ readonly dataset: Record<string, string> = {};
+ readonly style: Record<string, string> = {};
+ readonly children: MenuNode[] = [];
+ set innerHTML(value: string) {
+ this.children.length = 0;
+ for (const match of value.matchAll(/data-action="([^"]+)"/g)) {
+ const child = new MenuNode(); child.dataset.action = match[1]; this.children.push(child);
+ }
+ }
+ appendChild(child: MenuNode) { this.children.push(child); return child; }
+ addEventListener() {} removeEventListener() {} setAttribute() {}
+ querySelectorAll(selector: string) { return selector === '.ctx-row-menu-item' ? this.children : []; }
+ closest() { return null; }
+ contains() { return false; }
+ getBoundingClientRect() { return { left: 20, right: 220, top: 20, bottom: 52, width: 200, height: 180 }; }
+}
+
+function conversationFileMenu(invoke: (channel: string, payload: any) => Promise<any>) {
+ const elements = new Map<string, MenuNode>();
+ const body = new MenuNode();
+ body.appendChild = (child: MenuNode) => { if (child.id) elements.set(child.id, child); return child; };
+ const context: any = {
+ console, setTimeout, clearTimeout, encodeURIComponent, Date, Map, Set, Array, String, Number, RegExp,
+ currentView: 'conversation', conversations: [{ conversation_id: 'conversation-1', project_id: '' }],
+ createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ escapeHtml: (value: unknown) => String(value ?? ''),
+ t: (key: string) => key,
+ document: {
+ readyState: 'complete', body, getElementById: (id: string) => elements.get(id) || null,
+ createElement: () => new MenuNode(), querySelectorAll: () => [], addEventListener() {}, removeEventListener() {},
+ },
+ window: { innerWidth: 1200, innerHeight: 800, addEventListener() {}, removeEventListener() {}, orkas: { invoke } },
+ };
+ context.window.window = context.window;
+ vm.createContext(context);
+ vm.runInContext(policySource, context, { filename: 'file-operation-policy.js' });
+ vm.runInContext(infoSource, context, { filename: 'conversation-info.js' });
+ return async (target: string) => {
+ await context.window.ConversationInfo.openFileMenu(new MenuNode(), target, path.basename(target), { cid: 'conversation-1' });
+ const actions = elements.get('conversation-info-file-menu')!.children.map(item => item.dataset.action);
+ await context.window.ConversationInfo.openFileMenu(new MenuNode(), target, path.basename(target), { cid: 'conversation-1' });
+ return actions.includes('save-as-app');
+ };
+}
+
+describe('Save as app entry visibility by file type', () => {
+ const table = [...saveable.map(rel => [rel, true] as const), ...notSaveable.map(rel => [rel, false] as const)];
+
+ it.each(table)('file preview offers Save as app for %s: %s', async (rel, expected) => {
+ const viewer = fileViewer(inspectionIpc);
+ expect(await viewer.visible(path.join(workspace, rel))).toBe(expected);
+ expect(viewer.warnings).toEqual([]);
+ });
+
+ it.each(table)('conversation file menu offers Save as app for %s: %s', async (rel, expected) => {
+ const menu = conversationFileMenu(inspectionIpc);
+ expect(await menu(path.join(workspace, rel))).toBe(expected);
+ });
+
+ it('keeps both root-level entries discoverable so the user can receive recovery guidance', async () => {
+ const invoke=async()=>({ok:true,canSave:false,reason:'app_bundle_root'});
+ expect(await fileViewer(invoke).visible(path.join(workspace,'index.html'))).toBe(true);
+ expect(await conversationFileMenu(invoke)(path.join(workspace,'index.html'))).toBe(true);
+ });
+
+ it('keeps both entries hidden when inspection fails or reports a refusal', async () => {
+ const target = path.join(workspace, 'app', 'index.html');
+ for (const invoke of [async () => { throw new Error('path is outside the user workspace'); },
+ async () => ({ ok: false, error: 'path required' }), async () => ({ canSave: false })]) {
+ const viewer = fileViewer(invoke);
+ expect(await viewer.visible(target)).toBe(false);
+ expect(await conversationFileMenu(invoke)(target)).toBe(false);
+ }
+ });
+});
diff --git a/test/renderer/saved-apps-journeys.test.ts b/test/renderer/saved-apps-journeys.test.ts
new file mode 100644
index 00000000..f4c234f7
--- /dev/null
+++ b/test/renderer/saved-apps-journeys.test.ts
@@ -0,0 +1,260 @@
+// My Apps card journeys through the shipped panel markup, real shared dialogs
+// and saved-apps.js. Each case starts from what the user sees (cards, menu,
+// dialogs, composer) and asserts the visible result plus the IPC side effects
+// that must or must not happen. Locale strings are the product copy contract.
+import { describe, expect, it, vi } from 'vitest';
+import { deferred, flush, loadAppsRenderer, type Invoke } from './helpers/apps-renderer';
+
+const savedAt = '2026-05-01T08:00:00.000Z';
+const budget = { id: 'app-budget', title: 'Budget', appType: 'local', savedAt };
+
+function apps(list: any[], extra: Invoke = () => { throw new Error('unexpected IPC'); }): Invoke {
+ return (channel, payload) => (channel === 'savedApps.list' ? { apps: list } : extra(channel, payload));
+}
+
+async function openPanel(invoke: Invoke, lang: 'zh' | 'en' = 'zh') {
+ const h = loadAppsRenderer({ invoke, lang });
+ await h.window.loadSavedApps(true);
+ return h;
+}
+
+describe('My Apps list refresh', () => {
+ it.each(['rejected', 'refused', 'malformed'] as const)('keeps visible apps on a %s refresh and accepts a later confirmed empty list', async failure => {
+ let result: any = { apps: [budget] };
+ const h = await openPanel(() => {
+ if (result instanceof Error) throw result;
+ return result;
+ });
+ result = failure === 'rejected' ? new Error('/private/app-state')
+ : failure === 'refused' ? { ok: false, error: '/private/app-state' } : {};
+ await h.window.loadSavedApps(true);
+ expect(h.cards()).toEqual(['app-budget']);
+ expect(h.warnings).toHaveLength(1);
+ expect(JSON.stringify(h.warnings)).not.toContain('/private/app-state');
+ result = { apps: [] };
+ await h.window.loadSavedApps(true);
+ expect(h.cards()).toEqual([]);
+ });
+
+ it('ignores an older listing that completes after a newer deletion refresh', async () => {
+ const old = deferred();
+ let result: any = { apps: [budget] };
+ const h = await openPanel(() => result);
+ result = old.promise;
+ const loading = h.window.loadSavedApps(true);
+ result = { apps: [] };
+ await h.window.loadSavedApps(true);
+ old.resolve({ apps: [budget] });
+ await loading;
+ expect(h.cards()).toEqual([]);
+ });
+});
+
+describe('My Apps commercial entry', () => {
+ it('keeps the local view, focus and cards when a web-tab request is cancelled', async () => {
+ const h = await openPanel(apps([budget, { id: 'historic-web', appType: 'web', title: 'Historic', savedAt }]));
+ const tab = h.$('[data-app-filter="web"]')!; tab.focus();
+ await h.showTab('web');
+ const [dialog] = h.openDialogs();
+ expect(h.dialogText(dialog)).toBe('网页应用需要 Orkas 商业版。下载商业版即可继续。');
+ expect(h.$('[data-app-filter="local"]')!.getAttribute('aria-selected')).toBe('true');
+ expect(h.cards()).toEqual(['app-budget']);
+ dialog.querySelector('[data-act="cancel"]')!.click(); await flush();
+ expect(h.openDialogs()).toHaveLength(0);
+ expect(h.document.activeElement).toBe(tab);
+ expect(h.channels()).toEqual(['savedApps.list']);
+ });
+});
+
+describe('My Apps deletion', () => {
+ it.each([
+ ['zh', '删除「Budget」及其本地记录和私有文件?数据无法恢复。', '删除', '取消'],
+ ['en', 'Delete "Budget" and its local records and private files? Data cannot be recovered.', 'Delete', 'Cancel'],
+ ] as const)('names the app and its unrecoverable local data in %s, and Escape keeps the app', async (lang, message, danger, cancel) => {
+ const h = await openPanel(apps([budget]), lang);
+ await h.chooseMenuAction('app-budget', 'delete');
+
+ const [dialog] = h.openDialogs();
+ expect(h.dialogText(dialog)).toBe(message);
+ expect(dialog.querySelector('[data-act="ok"]')!.textContent).toBe(danger);
+ expect(h.document.activeElement).toBe(dialog.querySelector('[data-act="cancel"]'));
+ expect(h.document.activeElement!.textContent).toBe(cancel);
+
+ h.press('Escape');
+ await flush();
+ expect(h.openDialogs()).toHaveLength(0);
+ expect(h.channels()).toEqual(['savedApps.list']);
+ expect(h.cards()).toEqual(['app-budget']);
+ expect(h.warnings).toEqual([]);
+ });
+
+ it('removes the card only after the deletion is confirmed and succeeds', async () => {
+ let stored = [budget];
+ const h = await openPanel(channel => {
+ if (channel === 'savedApps.list') return { apps: stored };
+ if (channel === 'savedApps.delete') { stored = []; return { ok: true }; }
+ throw new Error('unexpected IPC');
+ });
+ await h.chooseMenuAction('app-budget', 'delete');
+ h.openDialogs()[0].querySelector('[data-act="ok"]')!.click();
+ await flush();
+
+ expect(h.invoke).toHaveBeenCalledWith('savedApps.delete', { appId: 'app-budget' });
+ expect(h.cards()).toEqual([]);
+ expect(h.openDialogs()).toHaveLength(0);
+ });
+
+ it('keeps the card and tells the user deletion failed when the deletion request is rejected', async () => {
+ const h = await openPanel(apps([budget], channel => {
+ if (channel === 'savedApps.delete') return Promise.reject(new Error('delete interrupted'));
+ throw new Error('unexpected IPC');
+ }));
+ await h.chooseMenuAction('app-budget', 'delete');
+ h.openDialogs()[0].querySelector('[data-act="ok"]')!.click();
+ await flush();
+
+ expect(h.channels()).toEqual(['savedApps.list', 'savedApps.delete']);
+ expect(h.cards()).toEqual(['app-budget']);
+ const dialogs = h.openDialogs();
+ expect(dialogs).toHaveLength(1);
+ expect(h.dialogText(dialogs[0]).startsWith('删除失败')).toBe(true);
+ expect(JSON.stringify(h.warnings)).not.toContain('delete interrupted');
+ });
+});
+
+describe('My Apps edit', () => {
+ it('opens the new edit task with the exact source-attachment prompt and saves it as the draft', async () => {
+ const drafts: Array<[string, string]> = [];
+ const h = await openPanel(apps([budget], channel => {
+ if (channel !== 'savedApps.openForEditing') throw new Error('unexpected IPC');
+ return { ok: true, title: 'X', sourceFileName: 'app-source.md',
+ conversation: { conversation_id: 'edit-task', title: 'X', created_at: savedAt, updated_at: savedAt } };
+ }));
+ const input = h.document.getElementById('chat-input')!;
+ Object.assign(h.context, {
+ conversations: [], renderConversationList: vi.fn(), setView: vi.fn(),
+ _saveDraft: (cid: string) => drafts.push([cid, input.value]),
+ });
+ await h.chooseMenuAction('app-budget', 'edit');
+
+ expect(h.invoke).toHaveBeenCalledWith('savedApps.openForEditing', { appId: 'app-budget' });
+ expect(h.context.setView).toHaveBeenCalledWith('conversation', 'edit-task', { skipLoad: true });
+ expect(input.value).toBe('请修改交互应用「X」,源码见附件「app-source.md」:');
+ expect(drafts).toEqual([['edit-task', '请修改交互应用「X」,源码见附件「app-source.md」:']]);
+ expect(h.warnings).toEqual([]);
+ });
+});
+
+describe('My Apps creation type', () => {
+ it.each(['cancel', 'escape', 'backdrop'])('retains the idea and selected type after %s without creating a task', async dismissal => {
+ const h = await openPanel(apps([]));
+ h.$('#apps-create-btn')!.click();
+ const panel = h.$('.apps-create-overlay')!;
+ panel.querySelector('[data-app-type="web"]')!.click();
+ await flush();
+ expect(h.openDialogs().filter(dialog => dialog.querySelector('.ui-dialog-message'))).toHaveLength(1);
+ h.openDialogs().find(dialog => dialog.querySelector('.ui-dialog-message'))!.querySelector('[data-act="cancel"]')!.click(); await flush();
+ h.input(panel.querySelector('textarea')!, ' Family meals\n购物清单 <b>raw</b> ');
+ if (dismissal === 'cancel') panel.querySelector('[data-create-cancel]')!.click();
+ else if (dismissal === 'escape') h.press('Escape');
+ else panel.click();
+ expect(h.$('.apps-create-overlay')).toBeNull();
+ h.$('#apps-create-btn')!.click();
+ expect(h.$('.apps-create-overlay textarea')!.value).toBe(' Family meals\n购物清单 <b>raw</b> ');
+ expect(h.$('[data-app-type="local"]')!.getAttribute('aria-pressed')).toBe('true');
+ expect(h.$('[data-create-submit]')!.disabled).toBe(false);
+ expect(h.channels()).toEqual(['savedApps.list']);
+ });
+
+ it.each([true, false])('account reset discards the draft with the dialog open=%s', async open => {
+ const h = await openPanel(apps([]));
+ h.$('#apps-create-btn')!.click();
+ h.input(h.$('.apps-create-overlay textarea')!, 'Private account idea');
+ if (!open) h.$('[data-create-cancel]')!.click();
+ await h.window.loadSavedApps(true, { reset: true });
+ expect(h.$('.apps-create-overlay')).toBeNull();
+ h.$('#apps-create-btn')!.click();
+ expect(h.$('.apps-create-overlay textarea')!.value).toBe('');
+ expect(h.$('[data-create-submit]')!.disabled).toBe(true);
+ });
+
+ it.each([
+ ['local', null, 'local'],
+ ['local', 'local', 'local'],
+ ] as const)('opened on the %s tab with %s chosen creates a %s app task', async (tab, chosen, expected) => {
+ const accepted = deferred();
+ const h = await openPanel(apps([], channel => {
+ if (channel !== 'conversations.create') throw new Error('unexpected IPC');
+ return { ok: true, conversation: { conversation_id: 'create-task', title: 'Habit tracker', created_at: savedAt, updated_at: savedAt } };
+ }));
+ Object.assign(h.context, {
+ ensureModelConfigured: () => true, _autoTitle: (text: string) => text, conversations: [],
+ renderConversationList: vi.fn(), setView: vi.fn(), _restoreDraft: vi.fn(), setChatRecipient: vi.fn(),
+ _rememberSentComposerSnapshot: vi.fn(),
+ sendInConversation: vi.fn(async (_cid: string, _text: string, _extra: unknown, options: any) => { options.onAccepted(); accepted.resolve(null); }),
+ });
+ if (tab === 'web') await h.showTab('web');
+ h.$('#apps-create-btn')!.click();
+ const overlay = h.$('.apps-create-overlay')!;
+ expect(overlay.querySelector(`[data-app-type="${tab}"]`)!.getAttribute('aria-pressed')).toBe('true');
+ if (chosen) overlay.querySelector(`[data-app-type="${chosen}"]`)!.click();
+ h.input(overlay.querySelector('#apps-create-idea')!, 'Habit tracker');
+ overlay.querySelector('[data-create-submit]')!.click();
+ await accepted.promise; await flush();
+
+ expect(h.invoke.mock.calls.filter(call => call[0] === 'conversations.create')).toEqual([
+ ['conversations.create', { title: 'Habit tracker', assistance: { kind: 'app_creation', appType: expected } }],
+ ]);
+ expect(h.context.sendInConversation).toHaveBeenCalledOnce();
+ expect(h.$('.apps-create-overlay')).toBeNull();
+ h.$('#apps-create-btn')!.click();
+ expect(h.$('.apps-create-overlay textarea')!.value).toBe('');
+ expect(h.$(`[data-app-type="${tab}"]`)!.getAttribute('aria-pressed')).toBe('true');
+ });
+});
+
+describe('My Apps saved time', () => {
+ // Product copy (docs/test/my-apps-regression.md): just now / same-day HH:mm / an older calendar date.
+ it.each([
+ ['zh', ['保存于 刚刚', '保存于 08:05', '保存于 13:21', '保存于 2026-06-01']],
+ ['en', ['Saved just now', 'Saved 08:05', 'Saved 13:21', 'Saved 2026-06-01']],
+ ] as const)('shows %s card times as just now, a same-day clock time, or the saved date', async (lang, expected) => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ vi.setSystemTime(new Date(2026, 5, 10, 15, 30, 0));
+ const at = (...parts: number[]) => new Date(...(parts as [number, number, number, number, number])).toISOString();
+ const list = [
+ { id: 'a-now', title: 'Now', appType: 'local', savedAt: at(2026, 5, 10, 15, 29, 40) },
+ { id: 'b-morning', title: 'Morning', appType: 'local', savedAt: at(2026, 5, 10, 8, 5) },
+ { id: 'c-noon', title: 'Noon', appType: 'local', savedAt: at(2026, 5, 10, 13, 21) },
+ { id: 'd-old', title: 'Old', appType: 'local', savedAt: at(2026, 5, 1, 9, 0) },
+ ];
+ const h = await openPanel(apps(list), lang);
+ expect(h.cards()).toEqual(['a-now', 'b-morning', 'c-noon', 'd-old']);
+ expect(list.map(app => h.card(app.id)!.querySelector('.app-card-time')!.textContent)).toEqual(expected);
+ } finally { vi.useRealTimers(); }
+ });
+});
+
+describe('My Apps failure alerts', () => {
+ const privateDetail = '/Users/test/Library/Application Support/Orkas/data/u1/cloud/saved_apps/app-budget/index.html: ENOENT';
+ it.each([
+ ['zh', 'rejected', '无法打开应用'],
+ ['zh', 'refused', '无法打开应用'],
+ ['en', 'rejected', 'Could not open the app'],
+ ['en', 'refused', 'Could not open the app'],
+ ] as const)('%s open failure (%s) shows only the localized action copy, never the private error text', async (lang, mode, copy) => {
+ const h = await openPanel(apps([budget], channel => {
+ if (channel !== 'savedApps.openInApp') throw new Error('unexpected IPC');
+ return mode === 'rejected' ? Promise.reject(new Error(privateDetail)) : { ok: false, error: privateDetail };
+ }), lang);
+ h.card('app-budget')!.click();
+ await flush();
+
+ const dialogs = h.openDialogs();
+ expect(dialogs).toHaveLength(1);
+ expect(h.dialogText(dialogs[0])).toBe(copy);
+ expect(JSON.stringify(h.warnings)).not.toContain('/Users/');
+ expect(h.cards()).toEqual(['app-budget']);
+ });
+});