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.

Unify local app lifecycle with publication-only commercial guidance

wyt1641c490daa8
diff --git a/docs/reference/web-app-sdk.json b/docs/reference/web-app-sdk.json
index 53be631c..b5cc14c8 100644
--- a/docs/reference/web-app-sdk.json
+++ b/docs/reference/web-app-sdk.json
@@ -3,6 +3,7 @@
"manifest": {
"file": "orkas-app.json",
"schema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"sdkVersion": {
@@ -14,6 +15,7 @@
"const": "1.9.0"
},
"capabilities": {
+ "maxItems": 7,
"type": "array",
"items": {
"type": "string",
@@ -26,8 +28,7 @@
"connectors",
"data"
]
- },
- "maxItems": 7
+ }
},
"data": {
"type": "object",
@@ -37,6 +38,7 @@
"const": 1
},
"tables": {
+ "maxItems": 32,
"type": "array",
"items": {
"type": "object",
@@ -50,6 +52,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 128,
"type": "array",
"items": {
"type": "object",
@@ -103,27 +106,26 @@
"type"
],
"additionalProperties": false
- },
- "maxItems": 128
+ }
},
"access": {
"type": "object",
"properties": {
"read": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"insert": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"count": {
"type": "boolean"
@@ -141,6 +143,7 @@
}
},
"readFilters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -185,24 +188,23 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"additionalProperties": false
},
"indexes": {
+ "maxItems": 16,
"type": "array",
"items": {
+ "minItems": 1,
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "minItems": 1,
- "maxItems": 4
- },
- "maxItems": 16
+ }
+ }
}
},
"required": [
@@ -212,8 +214,7 @@
"access"
],
"additionalProperties": false
- },
- "maxItems": 32
+ }
}
},
"required": [
@@ -228,7 +229,6 @@
"capabilities"
],
"additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#",
"allOf": [
{
"if": {
@@ -257,6 +257,7 @@
}
},
"dataDefinition": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"version": {
@@ -264,6 +265,7 @@
"const": 1
},
"tables": {
+ "maxItems": 32,
"type": "array",
"items": {
"type": "object",
@@ -277,6 +279,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 128,
"type": "array",
"items": {
"type": "object",
@@ -330,27 +333,26 @@
"type"
],
"additionalProperties": false
- },
- "maxItems": 128
+ }
},
"access": {
"type": "object",
"properties": {
"read": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"insert": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"count": {
"type": "boolean"
@@ -368,6 +370,7 @@
}
},
"readFilters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -412,24 +415,23 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"additionalProperties": false
},
"indexes": {
+ "maxItems": 16,
"type": "array",
"items": {
+ "minItems": 1,
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "minItems": 1,
- "maxItems": 4
- },
- "maxItems": 16
+ }
+ }
}
},
"required": [
@@ -439,16 +441,14 @@
"access"
],
"additionalProperties": false
- },
- "maxItems": 32
+ }
}
},
"required": [
"version",
"tables"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"methods": [
{
@@ -466,6 +466,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -473,22 +474,23 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 130,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "maxItems": 130
+ }
},
"include": {
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "maxItems": 4
+ }
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -533,8 +535,7 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
},
"limit": {
"type": "integer",
@@ -571,8 +572,7 @@
"required": [
"table"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{records:object[]}; include adds relations keyed by reference field.",
"example": {
@@ -598,6 +598,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -605,6 +606,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -649,15 +651,13 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"required": [
"table"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{count:number}",
"example": {
@@ -679,6 +679,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -687,6 +688,9 @@
},
"values": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
},
"requestId": {
@@ -698,8 +702,7 @@
"table",
"values"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{id:string}; generated record ID, never the private row.",
"example": {
@@ -725,6 +728,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -733,6 +737,9 @@
},
"values": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
},
"requestId": {
@@ -750,8 +757,7 @@
"values",
"maxCount"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{id:string}; no partial insertion on failure.",
"example": {
@@ -778,6 +784,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -803,6 +810,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -847,8 +855,7 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"required": [
@@ -856,8 +863,7 @@
"field",
"op"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{value:number|string|null} or {groups:[{key,value}]} when groupBy is supplied.",
"example": {
@@ -881,10 +887,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{sdkVersion, methods, unsupported}",
"example": {}
@@ -904,6 +910,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"method": {
@@ -914,8 +921,7 @@
"required": [
"method"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "Method documentation.",
"example": {
@@ -937,10 +943,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{language, sdkVersion}",
"example": {}
@@ -958,10 +964,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{revoked:true}",
"example": {}
@@ -979,6 +985,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"key": {
@@ -986,19 +993,18 @@
"minLength": 1
},
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
}
},
"required": [
"key"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{value}; null when missing.",
"example": {
@@ -1018,6 +1024,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"key": {
@@ -1025,12 +1032,12 @@
"minLength": 1
},
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
},
"value": {}
},
@@ -1038,8 +1045,7 @@
"key",
"value"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true}",
"example": {
@@ -1060,6 +1066,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"key": {
@@ -1067,19 +1074,18 @@
"minLength": 1
},
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
}
},
"required": [
"key"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{removed:true}",
"example": {
@@ -1099,19 +1105,19 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
}
},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{keys:string[]}",
"example": {}
@@ -1129,19 +1135,19 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{files:[{path,size}]}",
"example": {
@@ -1161,6 +1167,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1169,19 +1176,18 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
"required": [
"path"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{text} or null.",
"example": {
@@ -1201,6 +1207,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1209,19 +1216,18 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
"required": [
"path"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{base64} or null.",
"example": {
@@ -1241,6 +1247,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1249,12 +1256,12 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
},
"text": {
"type": "string",
@@ -1265,8 +1272,7 @@
"path",
"text"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true}",
"example": {
@@ -1287,6 +1293,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1295,12 +1302,12 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
},
"base64": {
"type": "string",
@@ -1311,8 +1318,7 @@
"path",
"base64"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true}",
"example": {
@@ -1333,6 +1339,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1341,19 +1348,18 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
"required": [
"path"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{removed:true}",
"example": {
@@ -1373,10 +1379,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{handle,name,size} or null on cancellation.",
"example": {}
@@ -1394,6 +1400,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"handle": {
@@ -1404,8 +1411,7 @@
"required": [
"handle"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{text}",
"example": {
@@ -1425,6 +1431,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"handle": {
@@ -1435,8 +1442,7 @@
"required": [
"handle"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{base64}",
"example": {
@@ -1456,6 +1462,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
@@ -1472,8 +1479,7 @@
"name",
"text"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true,name} or null on cancellation.",
"example": {
@@ -1494,6 +1500,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"handle": {
@@ -1504,8 +1511,7 @@
"required": [
"handle"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{released:true}",
"example": {
@@ -1525,6 +1531,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"prompt": {
@@ -1534,15 +1541,13 @@
"maxTokens": {
"type": "integer",
"exclusiveMinimum": 0,
- "minimum": -9007199254740991,
"maximum": 9007199254740991
}
},
"required": [
"prompt"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{text,usage,stopReason}; token-limited output has stopReason=max_tokens. Cancel with AbortSignal.",
"example": {
@@ -1563,10 +1568,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{tools:[{name,capability,description,inputSchema}]}",
"example": {}
@@ -1584,6 +1589,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
@@ -1592,6 +1598,9 @@
},
"arguments": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
}
},
@@ -1599,8 +1608,7 @@
"name",
"arguments"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{content,isError?}; inspect isError. Oversized results fail without replay.",
"example": {
diff --git a/docs/test/my-apps-regression.md b/docs/test/my-apps-regression.md
index d08968a6..0eff754c 100644
--- a/docs/test/my-apps-regression.md
+++ b/docs/test/my-apps-regression.md
@@ -13,27 +13,26 @@ fixture does not establish model output quality or live third-party availability
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.
+## Unified apps and publication guidance
+
+1. Local, web and legacy cloud apps share one Apps list and creation dialog.
+ Create, save, update, edit, open, preview and local execution remain available
+ without a commercial-version dialog. Legacy metadata preserves its capability
+ identity; a web app still cannot invoke host-only SDK methods.
+2. Publish remains in every app menu. Invoking it opens the standard localized
+ Cancel / Download commercial version dialog. Cancellation preserves the app,
+ draft and invoking focus. Check English and Chinese at normal and narrow sizes.
+3. Only an explicit Download action opens the official download page with the
+ current supported Web language. An opener failure presents localized recovery
+ and preserves the app. Page load, creation and ordinary app errors never open
+ the browser or start publication.
+4. Direct existing publication IPC returns the explicit
+ `E_COMMERCIAL_REQUIRED` / `web_apps` failure before preparing a snapshot,
+ uploading or changing local state. Ordinary artifact tools remain usable;
+ no new model-visible publication tool is introduced.
+5. Corrupt or unreadable metadata cannot become local SDK permission. Reject
+ conflicting types on a bound editing source before writes. Genuine legacy
+ local fallback and ordinary local HTML remain compatible.
## Local creation, list and save
@@ -42,23 +41,24 @@ fixture does not establish model output quality or live third-party availability
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.
+ Counts, one creation entry, 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.
+ folder. Show one toast 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;
+- Open a card of any retained app type 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.
+ capability identity. Updating retains its ID and compatible records. Saving a new
+ app binds this source to an independent copy; a deleted destination creates a
+ new ID. 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.
@@ -89,9 +89,38 @@ fixture does not establish model output quality or live third-party availability
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
+- Check card dates, exact edit draft, unified icons 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.
+
+## Revision and save-destination continuity
+
+- Correcting an artifact retains its ID, saved destination, type and records.
+ Streamed and restored history refresh one existing card. Failed preparation
+ keeps the previous bundle; independent creations remain independent. An open
+ native preview follows only a newer revision of that same artifact.
+- After saving an artifact or workspace bundle, each source exposes Update
+ original app / Save new app. Reopening and sibling JS/CSS/directory discovery
+ recover the same destination. An explicit Save new changes only that source's
+ destination; a deleted destination never falls back to an unrelated original.
+- Simultaneous automatic saves and symlink aliases create one destination.
+ Canonical directory identity owns the save queue and binding. Conflicting old
+ lexical bindings require an explicit new copy; do not guess between old copies.
+- Saving a non-index HTML and later updating from sibling JS/CSS retains its
+ selected entry and title. A missing selected entry fails without replacing the
+ saved version. Explicit HTML selection may change the entry.
+- Both artifact and file save entries use the same record migration recovery.
+ Export failure/cancellation, clear cancellation, user change, stale data/code
+ and changed destination never clear records or replace code. Confirmed recovery
+ updates the same app and an exported SQLite file retains the original values.
+- Application shutdown closes data owners and waits for their SQLite checkpoints.
+ A compatible update and complete application restart retain formal records.
+ Preview records stay temporary.
+
+Owning evidence: `chat-artifact-revisions.test.ts`, `saved_apps.test.ts`,
+`web_apps.test.ts`, `preview-windows.test.ts`, `app-save-recovery.test.ts`,
+`artifact-revisions.test.ts`, `artifact_revisions_e2e_lifecycle.spec.ts`,
+`saved_apps_e2e_lifecycle.spec.ts` and `web_app_sdk_e2e_lifecycle.spec.ts`.
diff --git a/resources/builtin/system/skills/web-app-sdk/references/api.json b/resources/builtin/system/skills/web-app-sdk/references/api.json
index 53be631c..b5cc14c8 100644
--- a/resources/builtin/system/skills/web-app-sdk/references/api.json
+++ b/resources/builtin/system/skills/web-app-sdk/references/api.json
@@ -3,6 +3,7 @@
"manifest": {
"file": "orkas-app.json",
"schema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"sdkVersion": {
@@ -14,6 +15,7 @@
"const": "1.9.0"
},
"capabilities": {
+ "maxItems": 7,
"type": "array",
"items": {
"type": "string",
@@ -26,8 +28,7 @@
"connectors",
"data"
]
- },
- "maxItems": 7
+ }
},
"data": {
"type": "object",
@@ -37,6 +38,7 @@
"const": 1
},
"tables": {
+ "maxItems": 32,
"type": "array",
"items": {
"type": "object",
@@ -50,6 +52,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 128,
"type": "array",
"items": {
"type": "object",
@@ -103,27 +106,26 @@
"type"
],
"additionalProperties": false
- },
- "maxItems": 128
+ }
},
"access": {
"type": "object",
"properties": {
"read": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"insert": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"count": {
"type": "boolean"
@@ -141,6 +143,7 @@
}
},
"readFilters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -185,24 +188,23 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"additionalProperties": false
},
"indexes": {
+ "maxItems": 16,
"type": "array",
"items": {
+ "minItems": 1,
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "minItems": 1,
- "maxItems": 4
- },
- "maxItems": 16
+ }
+ }
}
},
"required": [
@@ -212,8 +214,7 @@
"access"
],
"additionalProperties": false
- },
- "maxItems": 32
+ }
}
},
"required": [
@@ -228,7 +229,6 @@
"capabilities"
],
"additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#",
"allOf": [
{
"if": {
@@ -257,6 +257,7 @@
}
},
"dataDefinition": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"version": {
@@ -264,6 +265,7 @@
"const": 1
},
"tables": {
+ "maxItems": 32,
"type": "array",
"items": {
"type": "object",
@@ -277,6 +279,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 128,
"type": "array",
"items": {
"type": "object",
@@ -330,27 +333,26 @@
"type"
],
"additionalProperties": false
- },
- "maxItems": 128
+ }
},
"access": {
"type": "object",
"properties": {
"read": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"insert": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"count": {
"type": "boolean"
@@ -368,6 +370,7 @@
}
},
"readFilters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -412,24 +415,23 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"additionalProperties": false
},
"indexes": {
+ "maxItems": 16,
"type": "array",
"items": {
+ "minItems": 1,
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "minItems": 1,
- "maxItems": 4
- },
- "maxItems": 16
+ }
+ }
}
},
"required": [
@@ -439,16 +441,14 @@
"access"
],
"additionalProperties": false
- },
- "maxItems": 32
+ }
}
},
"required": [
"version",
"tables"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"methods": [
{
@@ -466,6 +466,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -473,22 +474,23 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 130,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "maxItems": 130
+ }
},
"include": {
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "maxItems": 4
+ }
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -533,8 +535,7 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
},
"limit": {
"type": "integer",
@@ -571,8 +572,7 @@
"required": [
"table"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{records:object[]}; include adds relations keyed by reference field.",
"example": {
@@ -598,6 +598,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -605,6 +606,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -649,15 +651,13 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"required": [
"table"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{count:number}",
"example": {
@@ -679,6 +679,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -687,6 +688,9 @@
},
"values": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
},
"requestId": {
@@ -698,8 +702,7 @@
"table",
"values"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{id:string}; generated record ID, never the private row.",
"example": {
@@ -725,6 +728,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -733,6 +737,9 @@
},
"values": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
},
"requestId": {
@@ -750,8 +757,7 @@
"values",
"maxCount"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{id:string}; no partial insertion on failure.",
"example": {
@@ -778,6 +784,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -803,6 +810,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -847,8 +855,7 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"required": [
@@ -856,8 +863,7 @@
"field",
"op"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{value:number|string|null} or {groups:[{key,value}]} when groupBy is supplied.",
"example": {
@@ -881,10 +887,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{sdkVersion, methods, unsupported}",
"example": {}
@@ -904,6 +910,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"method": {
@@ -914,8 +921,7 @@
"required": [
"method"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "Method documentation.",
"example": {
@@ -937,10 +943,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{language, sdkVersion}",
"example": {}
@@ -958,10 +964,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{revoked:true}",
"example": {}
@@ -979,6 +985,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"key": {
@@ -986,19 +993,18 @@
"minLength": 1
},
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
}
},
"required": [
"key"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{value}; null when missing.",
"example": {
@@ -1018,6 +1024,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"key": {
@@ -1025,12 +1032,12 @@
"minLength": 1
},
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
},
"value": {}
},
@@ -1038,8 +1045,7 @@
"key",
"value"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true}",
"example": {
@@ -1060,6 +1066,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"key": {
@@ -1067,19 +1074,18 @@
"minLength": 1
},
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
}
},
"required": [
"key"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{removed:true}",
"example": {
@@ -1099,19 +1105,19 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"scope": {
+ "default": "local",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "local"
+ ]
}
},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{keys:string[]}",
"example": {}
@@ -1129,19 +1135,19 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{files:[{path,size}]}",
"example": {
@@ -1161,6 +1167,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1169,19 +1176,18 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
"required": [
"path"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{text} or null.",
"example": {
@@ -1201,6 +1207,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1209,19 +1216,18 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
"required": [
"path"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{base64} or null.",
"example": {
@@ -1241,6 +1247,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1249,12 +1256,12 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
},
"text": {
"type": "string",
@@ -1265,8 +1272,7 @@
"path",
"text"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true}",
"example": {
@@ -1287,6 +1293,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1295,12 +1302,12 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
},
"base64": {
"type": "string",
@@ -1311,8 +1318,7 @@
"path",
"base64"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true}",
"example": {
@@ -1333,6 +1339,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"path": {
@@ -1341,19 +1348,18 @@
"description": "Relative path. No atomic temporary filenames, hidden/traversal segments, backslashes, Windows reserved names, trailing dots/spaces, visibility, Thumbs.db or desktop.ini."
},
"scope": {
+ "default": "cloud",
"type": "string",
"enum": [
"local",
"cloud"
- ],
- "default": "cloud"
+ ]
}
},
"required": [
"path"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{removed:true}",
"example": {
@@ -1373,10 +1379,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{handle,name,size} or null on cancellation.",
"example": {}
@@ -1394,6 +1400,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"handle": {
@@ -1404,8 +1411,7 @@
"required": [
"handle"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{text}",
"example": {
@@ -1425,6 +1431,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"handle": {
@@ -1435,8 +1442,7 @@
"required": [
"handle"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{base64}",
"example": {
@@ -1456,6 +1462,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
@@ -1472,8 +1479,7 @@
"name",
"text"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{saved:true,name} or null on cancellation.",
"example": {
@@ -1494,6 +1500,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"handle": {
@@ -1504,8 +1511,7 @@
"required": [
"handle"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{released:true}",
"example": {
@@ -1525,6 +1531,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"prompt": {
@@ -1534,15 +1541,13 @@
"maxTokens": {
"type": "integer",
"exclusiveMinimum": 0,
- "minimum": -9007199254740991,
"maximum": 9007199254740991
}
},
"required": [
"prompt"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{text,usage,stopReason}; token-limited output has stopReason=max_tokens. Cancel with AbortSignal.",
"example": {
@@ -1563,10 +1568,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{tools:[{name,capability,description,inputSchema}]}",
"example": {}
@@ -1584,6 +1589,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
@@ -1592,6 +1598,9 @@
},
"arguments": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
}
},
@@ -1599,8 +1608,7 @@
"name",
"arguments"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{content,isError?}; inspect isError. Oversized results fail without replay.",
"example": {
diff --git a/resources/builtin/system/skills/web-app-sdk/references/common.md b/resources/builtin/system/skills/web-app-sdk/references/common.md
index e48de7ea..251971f9 100644
--- a/resources/builtin/system/skills/web-app-sdk/references/common.md
+++ b/resources/builtin/system/skills/web-app-sdk/references/common.md
@@ -4,7 +4,8 @@ The generated API reference includes the exact version-1 data definition schema.
Use stable table/field IDs. Renaming a display name preserves data; removal,
constraint/type changes and incompatible references fail migration.
-Records have a platform-generated id and UTC createdAt. Values are finite safe
+Records have a platform-generated id and UTC createdAt; do not redeclare these
+names in table fields. Values are finite safe
numbers, booleans, UTF-8 strings, JSON objects/arrays or null on nullable fields.
Timestamp fields use UTC ISO strings, normalized to millisecond precision.
Omitted fields use explicit defaults or remain absent. Query comparisons use
@@ -13,6 +14,21 @@ UTF-8 record bytes meter the online 20 MiB limit, including id/createdAt. JSON
null and absent fields both match a null filter. User-provided SQL is rejected.
Queries, counts and aggregates apply the declared read fields and readFilters.
+A query's selected fields, filters and non-id ordering require access.read;
+createdAt ordering requires it too. Explicit query fields determine the returned
+projection: granting read access alone does not add a field to that projection.
+For example, reading message text and creation time in newest-first order:
+
+```json
+{
+ "access": { "read": ["body", "createdAt"], "insert": ["body"] },
+ "query": {
+ "table": "messages", "fields": ["body", "createdAt"],
+ "order": { "field": "createdAt", "direction": "desc" }
+ }
+}
+```
+
Declared references target stable table IDs; include performs one-hop reads under
the target's read permissions. References must identify an existing record;
author deletion refuses references instead of silently cascading.
diff --git a/resources/builtin/system/skills/web-app-sdk/references/web-api.json b/resources/builtin/system/skills/web-app-sdk/references/web-api.json
index 6b86a368..01b24fc1 100644
--- a/resources/builtin/system/skills/web-app-sdk/references/web-api.json
+++ b/resources/builtin/system/skills/web-app-sdk/references/web-api.json
@@ -3,6 +3,7 @@
"manifest": {
"file": "orkas-app.json",
"schema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"sdkVersion": {
@@ -14,14 +15,14 @@
"const": "1.9.0"
},
"capabilities": {
+ "maxItems": 7,
"type": "array",
"items": {
"type": "string",
"enum": [
"data"
]
- },
- "maxItems": 7
+ }
},
"data": {
"type": "object",
@@ -31,6 +32,7 @@
"const": 1
},
"tables": {
+ "maxItems": 32,
"type": "array",
"items": {
"type": "object",
@@ -44,6 +46,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 128,
"type": "array",
"items": {
"type": "object",
@@ -97,27 +100,26 @@
"type"
],
"additionalProperties": false
- },
- "maxItems": 128
+ }
},
"access": {
"type": "object",
"properties": {
"read": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"insert": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"count": {
"type": "boolean"
@@ -135,6 +137,7 @@
}
},
"readFilters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -179,24 +182,23 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"additionalProperties": false
},
"indexes": {
+ "maxItems": 16,
"type": "array",
"items": {
+ "minItems": 1,
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "minItems": 1,
- "maxItems": 4
- },
- "maxItems": 16
+ }
+ }
}
},
"required": [
@@ -206,8 +208,7 @@
"access"
],
"additionalProperties": false
- },
- "maxItems": 32
+ }
}
},
"required": [
@@ -222,7 +223,6 @@
"capabilities"
],
"additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#",
"allOf": [
{
"if": {
@@ -251,6 +251,7 @@
}
},
"dataDefinition": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"version": {
@@ -258,6 +259,7 @@
"const": 1
},
"tables": {
+ "maxItems": 32,
"type": "array",
"items": {
"type": "object",
@@ -271,6 +273,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 128,
"type": "array",
"items": {
"type": "object",
@@ -324,27 +327,26 @@
"type"
],
"additionalProperties": false
- },
- "maxItems": 128
+ }
},
"access": {
"type": "object",
"properties": {
"read": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"insert": {
+ "default": [],
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "default": []
+ }
},
"count": {
"type": "boolean"
@@ -362,6 +364,7 @@
}
},
"readFilters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -406,24 +409,23 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"additionalProperties": false
},
"indexes": {
+ "maxItems": 16,
"type": "array",
"items": {
+ "minItems": 1,
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "minItems": 1,
- "maxItems": 4
- },
- "maxItems": 16
+ }
+ }
}
},
"required": [
@@ -433,16 +435,14 @@
"access"
],
"additionalProperties": false
- },
- "maxItems": 32
+ }
}
},
"required": [
"version",
"tables"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"methods": [
{
@@ -460,6 +460,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -467,22 +468,23 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"fields": {
+ "maxItems": 130,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "maxItems": 130
+ }
},
"include": {
+ "maxItems": 4,
"type": "array",
"items": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
- },
- "maxItems": 4
+ }
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -527,8 +529,7 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
},
"limit": {
"type": "integer",
@@ -565,8 +566,7 @@
"required": [
"table"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{records:object[]}; include adds relations keyed by reference field.",
"example": {
@@ -592,6 +592,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -599,6 +600,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -643,15 +645,13 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"required": [
"table"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{count:number}",
"example": {
@@ -673,6 +673,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -681,6 +682,9 @@
},
"values": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
},
"requestId": {
@@ -692,8 +696,7 @@
"table",
"values"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{id:string}; generated record ID, never the private row.",
"example": {
@@ -719,6 +722,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -727,6 +731,9 @@
},
"values": {
"type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
"additionalProperties": {}
},
"requestId": {
@@ -744,8 +751,7 @@
"values",
"maxCount"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{id:string}; no partial insertion on failure.",
"example": {
@@ -772,6 +778,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"table": {
@@ -797,6 +804,7 @@
"pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"
},
"filters": {
+ "maxItems": 16,
"type": "array",
"items": {
"type": "object",
@@ -841,8 +849,7 @@
"value"
],
"additionalProperties": false
- },
- "maxItems": 16
+ }
}
},
"required": [
@@ -850,8 +857,7 @@
"field",
"op"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{value:number|string|null} or {groups:[{key,value}]} when groupBy is supplied.",
"example": {
@@ -875,10 +881,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{sdkVersion, methods, unsupported}",
"example": {}
@@ -898,6 +904,7 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"method": {
@@ -908,8 +915,7 @@
"required": [
"method"
],
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "Method documentation.",
"example": {
@@ -931,10 +937,10 @@
],
"status": "supported",
"inputSchema": {
+ "$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {},
- "additionalProperties": false,
- "$schema": "http://json-schema.org/draft-07/schema#"
+ "additionalProperties": false
},
"result": "{language, sdkVersion}",
"example": {}
diff --git a/src/main/features/chat_artifacts.ts b/src/main/features/chat_artifacts.ts
index c2aa93b5..102ec18f 100644
--- a/src/main/features/chat_artifacts.ts
+++ b/src/main/features/chat_artifacts.ts
@@ -48,6 +48,9 @@ import type { ZodIssue } from 'zod';
import { createLogger } from '../logger';
import { logErrorSummary, maskId } from '../util/log-redact';
import { isPathAllowed } from '../util/path-sandbox';
+import { writeTextAtomicSync } from '../storage';
+import { replaceDirectoryAtomically } from '../util/atomic-directory-replace';
+import { fileEditLock } from '../util/locks';
const log = createLogger('chat_artifacts');
@@ -112,6 +115,8 @@ export interface ArtifactFileInput {
}
export interface ArtifactMeta {
+ revision?: number;
+ savedAppId?: string;
browserStorage?: 'isolated-v1';
appType?: AppType;
title: string;
@@ -314,11 +319,11 @@ function declarationError(detail: string): string {
return text.length <= DECLARATION_ERROR_MAX ? text : text.slice(0, DECLARATION_ERROR_MAX - 3) + '...';
}
-function declarationPath(issuePath: ReadonlyArray<string | number>): string {
+function declarationPath(issuePath: ReadonlyArray<PropertyKey>): string {
let out = '';
for (const part of issuePath) {
if (typeof part === 'number') out += `[${part}]`;
- else out += (out ? '.' : '') + (IDENTIFIER_KEY.test(part) ? part : '<key>');
+ else out += (out ? '.' : '') + (typeof part === 'string' && IDENTIFIER_KEY.test(part) ? part : '<key>');
}
return out || 'root';
}
@@ -326,12 +331,14 @@ function declarationPath(issuePath: ReadonlyArray<string | number>): string {
/** 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 'invalid_type': {
+ const received = issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input;
+ return received === 'undefined' ? 'is required' : `must be ${issue.expected}, received ${received}`;
+ }
+ case 'invalid_value':
+ return issue.values.length === 1
+ ? issue.input === undefined ? 'is required' : `must be ${JSON.stringify(issue.values[0])}`
+ : `must be one of ${issue.values.join(', ')}`;
case 'unrecognized_keys': {
const named = issue.keys.filter(key => IDENTIFIER_KEY.test(key));
const unnamed = issue.keys.length - named.length;
@@ -339,7 +346,7 @@ function declarationReason(issue: ZodIssue): string {
...(unnamed ? [`${unnamed} other key(s)`] : [])];
return `has unsupported field(s) ${list.join(', ')}`;
}
- case 'invalid_string':
+ case 'invalid_format':
return 'has an invalid format';
default:
// Remaining zod messages and data-contract refinements are schema-authored.
@@ -369,7 +376,7 @@ function describeDeclarationIssues(issues: readonly ZodIssue[]): string {
// ── Public API ───────────────────────────────────────────────────────────
/**
- * Write a new artifact bundle for (uid, cid, agentId). Validates the file set
+ * Create or explicitly revise an artifact bundle for (uid, cid, agentId). Validates the file set
* (must include exactly one top-level `index.html`; extension allowlist; UTF-8 for utf8-encoded text files; relpath
* safety; no `__orkas/` or `__orkas-meta.json` clobber), writes atomically
* (temp dir → rename), and stamps `__orkas-meta.json`.
@@ -378,27 +385,45 @@ export async function createArtifact(
userId: string,
cid: string,
agentId: string,
- input: { title?: unknown; files?: unknown; appType?: unknown },
-): Promise<Result<{ artifactId: string; title: string }>> {
+ input: { title?: unknown; files?: unknown; appType?: unknown; artifactId?: unknown },
+ finalize?: (stagedDir: string, artifactId: string) => Promise<void>,
+): Promise<Result<{ artifactId: string; title: string; revision: number }>> {
let safeConvId: string;
try { safeConvId = safeCid(cid); }
catch (err) { return { ok: false, error: (err as Error).message }; }
+ let targetId: string | undefined;
+ let previousMeta: ArtifactMeta | undefined;
+ let previousRaw: string | undefined;
+ let previousFiles: string[] = [];
+ if (input.artifactId !== undefined) {
+ try {
+ targetId = safeArtifactId(input.artifactId);
+ const resolved = resolveArtifactDir(userId, safeConvId, targetId);
+ if (!resolved.ok) return { ok: false, error: 'application to revise was not found in this conversation' };
+ previousMeta = readArtifactMeta(userId, safeConvId, targetId, { strictSaveBinding: true });
+ if (!previousMeta || previousMeta.agentId !== agentId || !previousMeta.appType) {
+ return { ok: false, error: 'application revision requires an existing app from this creator' };
+ }
+ previousRaw = fs.readFileSync(path.join(resolved.dirPath, META_FILENAME), 'utf8');
+ previousFiles = listArtifactFilesRel(resolved.dirPath);
+ } catch {
+ return { ok: false, error: 'application revision target is invalid or unavailable' };
+ }
+ }
+
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 selectedType=appTypeSchema.safeParse((input.appType === 'cloud' ? 'web' : input.appType) ?? previousMeta?.appType ?? boundType ?? 'local');
+ if(!selectedType.success || (boundType && selectedType.data!==boundType) || (previousMeta && selectedType.data!==previousMeta.appType))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';
+ : previousMeta?.title ?? 'Interactive app';
if (!Array.isArray(input?.files) || input.files.length === 0) {
return { ok: false, error: 'files: required, must be a non-empty array of { path, content }' };
@@ -444,7 +469,9 @@ export async function createArtifact(
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);
+ // Input is retained only for the type/required distinction below; rejected
+ // values never enter the bounded declaration error or logs.
+ const parsed=manifestSchema.safeParse(parsedJson,{reportInput:true});
if(!parsed.success)return {ok:false,error:declarationError(describeDeclarationIssues(parsed.error.issues))};
const manifest=parsed.data;
const hostOnly=manifest.capabilities.filter(c=>c!=='data');
@@ -460,50 +487,65 @@ export async function createArtifact(
if (!hasIndex) return { ok: false, error: 'files must include a top-level "index.html"' };
const meta: ArtifactMeta = {
- browserStorage: 'isolated-v1',
+ ...(previousRaw ? JSON.parse(previousRaw) : { browserStorage: 'isolated-v1' }),
appType,
title,
agentId: typeof agentId === 'string' ? agentId : '',
- createdAt: new Date().toISOString(),
+ createdAt: previousMeta?.createdAt ?? new Date().toISOString(),
+ revision: (previousMeta?.revision ?? (previousMeta ? 1 : 0)) + 1,
};
const metaBuf = Buffer.from(JSON.stringify(meta, null, 2), 'utf8');
// Mint an id that isn't already taken (collisions are astronomically
// unlikely with 9 random bytes, but a few retries cost nothing).
- let artifactId = '';
- let finalDir = '';
- for (let attempt = 0; attempt < 5; attempt++) {
+ let artifactId = targetId ?? '';
+ let finalDir = targetId ? artifactDirForConversation(userId, safeConvId, targetId) : '';
+ for (let attempt = 0; !artifactId && attempt < 5; attempt++) {
const candidate = crypto.randomBytes(9).toString('base64url'); // 12 url-safe chars
const dir = artifactDirForConversation(userId, safeConvId, candidate);
if (!fs.existsSync(dir)) { artifactId = candidate; finalDir = dir; break; }
}
if (!artifactId) return { ok: false, error: 'could not allocate an artifact id' };
- const tmpDir = `${finalDir}.tmp-${crypto.randomBytes(4).toString('hex')}`;
try {
- for (const { rel, content, encoding } of prepared) {
- 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' && appType === 'local') buf = Buffer.from(ensureBridgeScript(content), 'utf8');
+ await replaceDirectoryAtomically(finalDir, async tmpDir => {
+ for (const { rel, content, encoding } of prepared) {
+ 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' && appType === 'local') buf = Buffer.from(ensureBridgeScript(content), 'utf8');
+ }
+ const dst = path.join(tmpDir, rel);
+ await fsp.mkdir(path.dirname(dst), { recursive: true });
+ await fsp.writeFile(dst, buf);
+ totalBytes += buf.length;
}
- const dst = path.join(tmpDir, rel);
- await fsp.mkdir(path.dirname(dst), { recursive: true });
- await fsp.writeFile(dst, buf);
- totalBytes += buf.length;
- }
- await fsp.writeFile(path.join(tmpDir, META_FILENAME), metaBuf);
- await fsp.mkdir(path.dirname(finalDir), { recursive: true });
- await fsp.rename(tmpDir, finalDir);
+ await fsp.writeFile(path.join(tmpDir, META_FILENAME), metaBuf);
+ await finalize?.(tmpDir, artifactId);
+ }, undefined, {
+ activationGuard: activate => fileEditLock(finalDir).runExclusive(async () => {
+ if (targetId) {
+ const current = resolveArtifactDir(userId, safeConvId, targetId);
+ if (!current.ok || await fsp.readFile(path.join(finalDir, META_FILENAME), 'utf8') !== previousRaw) {
+ throw new Error('application changed while preparing the revision');
+ }
+ } else if (fs.existsSync(finalDir)) throw new Error('application identity already exists');
+ return activate();
+ }),
+ onCleanupError: err => log.warn('artifact replacement cleanup deferred', { error: logErrorSummary(err) }),
+ });
} catch (err) {
- try { await fsp.rm(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ }
- try { await fsp.rm(finalDir, { recursive: true, force: true }); } catch { /* best-effort */ }
- log.warn(`createArtifact failed user=${userId} cid=${safeConvId}: ${(err as Error).message}`);
- return { ok: false, error: `failed to write artifact: ${(err as Error).message}` };
+ log.warn('artifact preparation failed', { error: logErrorSummary(err) });
+ return { ok: false, error: targetId ? 'could not update the application; the previous version is retained' : 'could not prepare the application' };
}
- log.info(`createArtifact user=${userId} cid=${safeConvId} id=${artifactId} files=${prepared.length} bytes=${totalBytes} agent=${meta.agentId}`);
+ log.info('artifact committed', { user_id: maskId(userId), conversation_id: maskId(safeConvId),
+ artifact_id: maskId(artifactId), file_count: prepared.length, bytes: totalBytes, revision: meta.revision });
notifyArtifactDirty(userId, safeConvId, artifactId);
- return { ok: true, artifactId, title };
+ if (previousFiles.length) {
+ const retained = new Set(listArtifactFilesRel(finalDir));
+ for (const rel of previousFiles) if (!retained.has(rel)) notifyArtifactDeleted(userId, safeConvId, artifactId, rel);
+ }
+ return { ok: true, artifactId, title, revision: meta.revision! };
}
export async function inspectArtifactIndex(userId: string, cid: string, artifactId: string): Promise<ArtifactInspection> {
@@ -598,8 +640,9 @@ export function discardArtifact(
}
/** Read an artifact's metadata, if present. Best-effort (returns undefined on
- * any failure — callers fall back to a generic title). */
-export function readArtifactMeta(userId: string, cid: string, artifactId: string): ArtifactMeta | undefined {
+ * any failure — callers fall back to a generic title). Save-target resolution
+ * opts into strict association reads so damaged state never redirects a write. */
+export function readArtifactMeta(userId: string, cid: string, artifactId: string, opts: { strictSaveBinding?: boolean } = {}): ArtifactMeta | undefined {
let safeConvId: string;
let safeId: string;
try { safeConvId = safeCid(cid); safeId = safeArtifactId(artifactId); }
@@ -607,8 +650,13 @@ export function readArtifactMeta(userId: string, cid: string, artifactId: string
try {
const raw = fs.readFileSync(path.join(artifactDirForConversation(userId, safeConvId, safeId), META_FILENAME), 'utf8');
const obj = JSON.parse(raw) as Partial<ArtifactMeta>;
+ const validSavedAppId = typeof obj?.savedAppId === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(obj.savedAppId);
+ if (opts.strictSaveBinding && (!obj || typeof obj !== 'object' || Array.isArray(obj)
+ || (Object.hasOwn(obj, 'savedAppId') && !validSavedAppId))) throw new Error('invalid save binding');
if (obj && typeof obj === 'object') {
return {
+ ...(Number.isSafeInteger(obj.revision) && obj.revision! > 0 ? { revision: obj.revision } : {}),
+ ...(validSavedAppId ? { savedAppId: obj.savedAppId } : {}),
appType: metadataAppType(obj.appType),
...(obj.browserStorage === 'isolated-v1' ? { browserStorage: obj.browserStorage } : {}),
title: typeof obj.title === 'string' ? obj.title : 'Interactive app',
@@ -616,10 +664,32 @@ export function readArtifactMeta(userId: string, cid: string, artifactId: string
createdAt: typeof obj.createdAt === 'string' ? obj.createdAt : '',
};
}
- } catch { /* missing / malformed */ }
+ } catch (error) {
+ if (opts.strictSaveBinding && (error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ throw new Error('app_save_binding_unavailable');
+ }
+ }
return undefined;
}
+/** Host-owned save association; never accepted from application source files. */
+export function bindSavedApp(userId: string, cid: string, artifactId: string, appId: string): void {
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(appId)) throw new Error('invalid app id');
+ const source = resolveArtifactDir(userId, cid, artifactId);
+ if (!source.ok) throw new Error('artifact unavailable');
+ const file = path.join(source.dirPath, META_FILENAME);
+ if (!isPathAllowed(file, [source.dirPath])) throw new Error('artifact unavailable');
+ let meta = {};
+ try {
+ if (!fs.lstatSync(file).isFile()) throw new Error('artifact unavailable');
+ meta = JSON.parse(fs.readFileSync(file, 'utf8'));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ writeTextAtomicSync(file, JSON.stringify({ ...meta, savedAppId: appId }, null, 2));
+ notifyArtifactDirty(userId, cid, artifactId);
+}
+
export interface ArtifactSummary {
artifactId: string;
title: string;
diff --git a/src/main/features/saved_apps.ts b/src/main/features/saved_apps.ts
index 5f3fc8f7..c5adbe59 100644
--- a/src/main/features/saved_apps.ts
+++ b/src/main/features/saved_apps.ts
@@ -25,7 +25,7 @@ import * as crypto from 'node:crypto';
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 { storedAppType } from './web_apps/commercial-entry';
import * as chatArtifacts from './chat_artifacts';
import * as chats from './chats';
import { conversationLayout } from '../util/project-layout';
@@ -65,6 +65,7 @@ export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string; co
type ResolveCode = 'bad_input' | 'forbidden' | 'not_found';
export interface SavedAppMeta {
+ sourcePathKey?: string;
browserStorage?: 'isolated-v1';
appType?: AppType;
description?: string;
@@ -138,7 +139,7 @@ function sweepStagingDirs(root: string, names: readonly string[], retained?: Rea
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; }
+ try { const st = fs.lstatSync(dir); if (!st.isDirectory() || st.isSymbolicLink()) continue; }
catch { continue; }
activeStagingDirs.add(dir);
void fsp.rm(dir, { recursive: true, force: true })
@@ -177,7 +178,12 @@ export function hasIsolatedBrowserStorage(uid: string, appId: string): boolean {
} catch { return false; }
}
-/** Persisted metadata owns type; legacy local apps have no type marker. */
+/** Read only bounded local metadata, including legacy app types. */
+export function declaredSavedAppType(uid: string, appId: string): AppType | undefined {
+ const dir = savedAppDir(uid, safeAppId(appId));
+ if (!isRealSavedAppDirectory(dir)) throw new Error('app not found');
+ return storedAppType(dir);
+}
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');
@@ -392,7 +398,7 @@ async function findBundleRoot(target: string, opts: BundleInspectOptions = {}):
return { ok: false, reason: 'no HTML entry found for this file' };
}
-async function inspectBundle(targetPath: string, opts: BundleInspectOptions): Promise<BundleInspection & { files?: string[] }> {
+async function inspectBundle(targetPath: string, opts: BundleInspectOptions): Promise<BundleInspection & { files?: string[]; realRoot?:string }> {
if (typeof targetPath !== 'string' || !targetPath.trim()) return { ok: false, error: 'path required' };
const found = await findBundleRoot(targetPath, opts);
if (!found.ok) return { ok: true, canSave: false, reason: (found as { ok: false; reason: string }).reason };
@@ -422,6 +428,7 @@ async function inspectBundle(targetPath: string, opts: BundleInspectOptions): Pr
ok: true,
canSave: true,
rootDir,
+ realRoot,
entry,
title: await inferTitleFromHtml(entryAbs, rootDir),
files: scanned.files,
@@ -431,7 +438,7 @@ async function inspectBundle(targetPath: string, opts: BundleInspectOptions): Pr
}
export async function inspectBundleFromPath(targetPath: string, opts: BundleInspectOptions = {}): Promise<BundleInspection> {
- const { files: _files, ...inspection } = await inspectBundle(targetPath, opts);
+ const { files: _files, realRoot: _realRoot, ...inspection } = await inspectBundle(targetPath, opts);
return inspection;
}
@@ -462,13 +469,17 @@ function mintAppId(userId: string): { appId: string; destDir: string } {
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');}}
+type DataSource = string | {rootDir:string};
+export type SaveRecovery = {appId?:string;clearVersion:number;clearFingerprint:string};
+async function dataTarget(uid:string,cid:string,source:DataSource) {
+ if(typeof source==='string'&&!chatArtifacts.resolveArtifactDir(uid,cid,source).ok)return null;
+ return getSaveTarget(uid,cid,typeof source==='string'?{artifactId:source}:source);
+}
/** 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'};
+export async function appDataImpact(uid:string,cid:string,source:DataSource):Promise<Result<{appId:string;records:number;version:number;fingerprint:string;tables:Array<{name:string;fields:string[];count:number}>}>>{
+ const context=await dataTarget(uid,cid,source);if(!context)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();}}
+ try{const dir=savedAppDir(uid,context.appId);const fingerprint=fingerprintApp(dir);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,appId:context.appId,records:info.records,version:info.version,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. */
@@ -479,10 +490,9 @@ async function removeAppDataBackup(file: string): Promise<void> {
}
}
-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'};
+export async function exportAppData(uid:string,cid:string,source:DataSource,destination:string,expectedAppId?:string):Promise<Result>{
+ const context=await dataTarget(uid,cid,source);if(!context)return {ok:false,error:'app_edit_target_missing'};
+ if(expectedAppId!==undefined&&context.appId!==expectedAppId)return {ok:false,error:'app_edit_conflict'};
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'};}
@@ -495,18 +505,78 @@ export async function exportAppData(uid:string,cid:string,artifactId:string,dest
/** Copy a chat artifact bundle into a new `saved_apps/<appId>/`. */
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 }>> {
+type SaveMode = 'new' | 'update' | 'auto';
+type PathSource = { rootDir: string; bindingRoot: string; entry: string; explicitEntry: boolean; explicitTitle: boolean; title: string; files: string[]; appType: AppType; sourceCid: string };
+const saveQueues = new Map<string, Promise<unknown>>();
+const legacyPathSourceKey = (root: string) => crypto.createHash('sha256').update(path.resolve(root)).digest('hex');
+const pathSourceKey = (root: string) => legacyPathSourceKey(fs.realpathSync(root));
+const pathBindingFile = (uid: string, key: string) => path.join(userAppEditsDir(uid), `source-${key}.json`);
+function readPathBinding(uid:string,key:string):{version:1|2;appId:string}|null {
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 binding=JSON.parse(fs.readFileSync(pathBindingFile(uid,key),'utf8'));
+ if(!binding||![1,2].includes(binding.version))throw new Error('invalid save binding');
+ return {version:binding.version,appId:safeAppId(binding.appId)};
+ } catch(error) {
+ if((error as NodeJS.ErrnoException).code==='ENOENT')return null;
+ throw new Error('app_save_binding_unavailable');
+ }
+}
+
+/** A source owns its current save destination; conversation-wide edit bindings are only a fallback. */
+export async function getSaveTarget(uid: string, cid: string, source: {artifactId?: string; rootDir?: string; legacyRoot?: string}) {
+ let id: string | undefined;
+ if (source.artifactId) id = chatArtifacts.readArtifactMeta(uid, cid, source.artifactId, { strictSaveBinding: true })?.savedAppId;
+ else if (source.rootDir) {
+ const canonicalKey=pathSourceKey(source.rootDir),legacyKey=legacyPathSourceKey(source.legacyRoot??source.rootDir);
+ const canonical=readPathBinding(uid,canonicalKey);
+ // Version 2 explicitly owns every spelling, including a later Save as new.
+ // Version 1 aliases are migrated lazily; ambiguous old copies need a choice.
+ if(canonical?.version===2)id=canonical.appId;
+ else {
+ const legacy=legacyKey===canonicalKey?canonical:readPathBinding(uid,legacyKey);
+ if(canonical&&legacy&&canonical.appId!==legacy.appId)throw new Error('app_save_binding_unavailable');
+ id=canonical?.appId??legacy?.appId;
+ }
}
+ // A deleted explicit destination must not fall back to an unrelated original.
+ if (id) {
+ const dir = savedAppDir(uid, safeAppId(id));
+ if (!isRealSavedAppDirectory(dir)) return null;
+ const meta = readMeta(dir);
+ return { appId: id, title: sanitiseTitle(meta.title), appType: metadataAppType(meta.appType) ?? await resolveSavedAppType(uid, id) };
+ }
+ const edit = cid ? await getEditTarget(uid, cid) : null;
+ if (edit) return isRealSavedAppDirectory(savedAppDir(uid, edit.appId)) ? edit : null;
+ // Recover only unique historical provenance; duplicate copies are not a choice.
+ const sourceKeys=source.rootDir?[pathSourceKey(source.rootDir),legacyPathSourceKey(source.legacyRoot??source.rootDir)]:[];
+ const candidates = listSavedApps(uid).filter(app => {
+ let meta: Partial<SavedAppMeta>;
+ try { meta = readMeta(savedAppDir(uid, app.id)); } catch { return false; }
+ return source.artifactId ? meta.sourceCid === cid && meta.sourceArtifactId === source.artifactId
+ : sourceKeys.includes(meta.sourcePathKey!);
+ });
+ return candidates.length === 1 ? { appId: candidates[0].id, title: candidates[0].title,
+ appType: candidates[0].appType ?? await resolveSavedAppType(uid, candidates[0].id) } : null;
+}
+
+function bindSave(uid: string, cid: string, artifactId: string, appId: string, source?: PathSource) {
+ if (!source) return chatArtifacts.bindSavedApp(uid, cid, artifactId, appId);
+ fs.mkdirSync(userAppEditsDir(uid), {recursive:true});
+ writeTextAtomicSync(pathBindingFile(uid, pathSourceKey(source.rootDir)), JSON.stringify({version:2,appId}));
+}
+
+export async function saveFromArtifact(userId: string, cid: string, artifactId: string, mode: SaveMode = 'new', recovery?:SaveRecovery, source?: PathSource): Promise<Result<{ id: string; title: string; entry?:string }>> {
const key = JSON.stringify([userId, cid]);
activeEditSaves.set(key, (activeEditSaves.get(key) || 0) + 1);
- try { return await saveArtifact(userId, cid, artifactId, mode, recovery); }
+ // Keep each conversation's recovery journal exclusive, and share the source
+ // queue when different conversations save the same workspace bundle.
+ const queueKeys = source ? [key, JSON.stringify([userId, 'source', pathSourceKey(source.rootDir)])] : [key];
+ const previous = queueKeys.map(queueKey => saveQueues.get(queueKey)?.catch(() => {}));
+ const saving = Promise.all(previous).then(() => saveArtifact(userId, cid, artifactId, mode, recovery, source));
+ for (const queueKey of queueKeys) saveQueues.set(queueKey, saving);
+ try { return await saving; }
finally {
+ for (const queueKey of queueKeys) if (saveQueues.get(queueKey) === saving) saveQueues.delete(queueKey);
const remaining = activeEditSaves.get(key)! - 1;
if (remaining) activeEditSaves.set(key, remaining);
else {
@@ -516,30 +586,40 @@ export async function saveFromArtifact(userId: string, cid: string, artifactId:
}
}
-async function saveArtifact(userId: string, cid: string, artifactId: string, mode: 'new' | 'update', recovery?:{clearVersion:number;clearFingerprint:string}): Promise<Result<{ id: string; title: string }>> {
+async function saveArtifact(userId: string, cid: string, artifactId: string, mode: SaveMode, recovery?:SaveRecovery, source?: PathSource): Promise<Result<{ id: string; title: string; entry?:string }>> {
recoverEditedSaves(userId);
- const resolved = chatArtifacts.resolveArtifactDir(userId, cid, artifactId);
+ const resolved = source ? {ok:true as const,dirPath:source.rootDir} : 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 title = sanitiseTitle(source?.title ?? srcMeta?.title);
+ const editContext = readEditContext(userId, cid);
+ let context: EditContext | null = null;
+ // Legacy type metadata remains readable; saving never changes application identity based on type.
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' };
+ appType = source?.appType ?? await resolveArtifactAppType(userId, cid, artifactId, srcMeta);
+ if (mode !== 'new') {
+ const target = await getSaveTarget(userId, cid, source ? {rootDir:source.rootDir,legacyRoot:source.bindingRoot} : {artifactId});
+ if (target) {
+ // Updating a durable destination preserves its capability identity;
+ // another task's creation defaults belong only to new applications.
+ appType = target.appType;
+ context = {version:1,...target,fingerprint:fingerprintApp(savedAppDir(userId,target.appId))};
+ }
}
} 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' };
+ if(recovery&&(!context||(source&&!recovery.appId)||(recovery.appId!==undefined&&recovery.appId!==context.appId)
+ ||!Number.isInteger(recovery.clearVersion)||typeof recovery.clearFingerprint!=='string'
+ ||recovery.clearFingerprint!==context.fingerprint))return {ok:false,error:'app_edit_conflict'};
+ mode = context ? 'update' : 'new';
+ const entry = source && context && !source.explicitEntry
+ ? normaliseEntryRel(readMeta(savedAppDir(userId,context.appId)).entry) : source?.entry ?? 'index.html';
+ if(source&&context&&!source.explicitEntry&&!source.explicitTitle)title=context.title;
let appId = '';
let destDir = '';
@@ -558,14 +638,21 @@ async function saveArtifact(userId: string, cid: string, artifactId: string, mod
try {
// Copy everything except the source `__orkas-meta.json` (we write a fresh
// one stamped with the source provenance).
- await fsp.cp(srcDir, tmpDir, {
+ if (source) {
+ await fsp.mkdir(tmpDir,{recursive:true});
+ await copyBundleFiles(srcDir,tmpDir,source.files);
+ } else await fsp.cp(srcDir, tmpDir, {
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');
+ if (editContext && !source) {
+ // Updates retain assets from their remembered destination, which can be
+ // an independently edited copy rather than the task's original snapshot.
+ const snapshot = mode === 'update' && context
+ ? savedAppDir(userId, context.appId)
+ : 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);
@@ -577,15 +664,23 @@ async function saveArtifact(userId: string, cid: string, artifactId: string, mod
}
}
}
- if (!fs.existsSync(path.join(tmpDir, 'index.html'))) {
+ if (!fs.existsSync(path.join(tmpDir, entry))) {
throw new Error('source artifact is missing index.html');
}
+ if (source && 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 = {
...(mode === 'new' || hasIsolatedBrowserStorage(userId, appId) ? { browserStorage: 'isolated-v1' as const } : {}),
appType,
- description: await readHtmlDescription(path.join(tmpDir, 'index.html')),
+ ...(source ? {sourcePathKey:pathSourceKey(source.rootDir),entry} : {}),
+ description: await readHtmlDescription(path.join(tmpDir, entry)),
title,
- sourceCid: typeof cid === 'string' ? cid : '',
+ sourceCid: source ? source.sourceCid : cid,
sourceArtifactId: typeof artifactId === 'string' ? artifactId : '',
savedAt: new Date().toISOString(),
};
@@ -611,6 +706,7 @@ async function saveArtifact(userId: string, cid: string, artifactId: string, mod
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');
+ fs.mkdirSync(path.dirname(journalPath),{recursive:true});
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);
@@ -619,7 +715,7 @@ async function saveArtifact(userId: string, cid: string, artifactId: string, mod
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);
+ if (editContext?.appId === appId) 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});
@@ -629,7 +725,11 @@ async function saveArtifact(userId: string, cid: string, artifactId: string, mod
// 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);
+ } else {
+ await fsp.rename(tmpDir, destDir);
+ // Do not report a successful copy if its source association could not be persisted.
+ bindSave(userId,cid,artifactId,appId,source);
+ }
} catch (err) {
try { await fsp.rm(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ }
if (mode !== 'update') {
@@ -648,6 +748,10 @@ async function saveArtifact(userId: string, cid: string, artifactId: string, mod
try { if (candidate) await removeAppDataBackup(candidate); }
finally { release?.(); }
}
+ if (mode === 'update') {
+ try { bindSave(userId,cid,artifactId,appId,source); }
+ catch (error) { log.warn('saved app association recovery deferred',{error:logErrorSummary(error)}); }
+ }
log.info('saveFromArtifact completed', {
user_id: maskId(userId),
app_id: maskId(appId),
@@ -655,27 +759,20 @@ async function saveArtifact(userId: string, cid: string, artifactId: string, mod
artifact_id: maskId(artifactId),
save_mode: mode,
});
- return { ok: true, id: appId, title };
+ return { ok: true, id: appId, title, ...(source?{entry}:{}) };
}
/** Copy a workspace/file-tab-discovered HTML app bundle into saved_apps. */
export async function saveFromPath(
userId: string,
targetPath: string,
- opts: BundleInspectOptions & { title?: unknown; sourceCid?: unknown } = {},
+ opts: BundleInspectOptions & { title?: unknown; sourceCid?: unknown; mode?: SaveMode; recovery?:SaveRecovery } = {},
): 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' }; }
+ try { storedAppType(inspected.rootDir); }
+ catch { return { ok: false, error: 'app_edit_target_missing' }; }
const title = sanitiseTitle(opts.title || inspected.title);
const sourceCid=typeof opts.sourceCid==='string'?opts.sourceCid:'';
@@ -683,61 +780,16 @@ export async function saveFromPath(
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 {
- const minted = mintAppId(userId);
- appId = minted.appId;
- destDir = minted.destDir;
- } catch (err) {
- return { ok: false, error: (err as Error).message };
- }
-
- 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: '',
- entry: inspected.entry,
- savedAt: new Date().toISOString(),
- };
- 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);
- log.info('saveFromPath completed', {
- user_id: maskId(userId),
- app_id: maskId(appId),
- root: logPathRef(inspected.rootDir),
- entry: logPathRef(inspected.entry),
- file_count: copied.fileCount,
- total_bytes: copied.totalBytes,
- });
- 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 */ }
- try { await fsp.rm(destDir, { recursive: true, force: true }); } catch { /* best-effort */ }
- log.warn('saveFromPath failed', {
- user_id: maskId(userId),
- target: logPathRef(targetPath),
- error: logErrorSummary(err),
- });
- return { ok: false, error: failureCode(err, 'app_save_failed') };
- }
- finally { activeStagingDirs.delete(tmpDir); }
+ const appType:AppType=editType??(assistance?.kind==='app_creation'?assistance.appType??'local':storedAppType(inspected.rootDir)??'local');
+ const realRoot=inspected.realRoot!;
+ const operationCid = sourceCid || `file-${pathSourceKey(realRoot)}`;
+ const result = await saveFromArtifact(userId,operationCid,'',opts.mode ?? 'new',opts.recovery,{
+ rootDir:realRoot,bindingRoot:inspected.rootDir,entry:inspected.entry,
+ explicitEntry:/\.html?$/i.test(targetPath)&&fs.statSync(targetPath).isFile(),
+ explicitTitle:!!opts.title,title,files:inspected.files!.map(file=>path.join(realRoot,path.relative(inspected.rootDir,file))),appType,sourceCid,
+ });
+ if (result.ok === false) return result;
+ return {...result,rootDir:inspected.rootDir,entry:result.entry!,fileCount:inspected.fileCount,totalBytes:inspected.totalBytes};
}
/** List the user's saved apps, newest save first. */
@@ -927,7 +979,12 @@ async function deleteLocalSavedApp(userId: string, safeId: string): Promise<Resu
exists = true;
if (!st.isDirectory() || st.isSymbolicLink()) return { ok: false, error: 'app not found' };
} catch { /* idempotent missing delete */ }
- const deleted = exists ? listAppFilesRel(dir) : [];
+ let deleted: string[];
+ try { deleted = exists ? listAppFilesRel(dir) : []; }
+ catch (err) {
+ log.warn('deleteSavedApp inventory unavailable', { user_id: maskId(userId), app_id: maskId(safeId), error: logErrorSummary(err) });
+ return { ok: false, error: 'app_delete_failed' };
+ }
// 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.
@@ -1048,13 +1105,12 @@ function isSymlink(target: string): boolean {
// ── "Edit in a new conversation" ─────────────────────────────────────────
-/** Recursively list a saved app's file paths (relative to its dir), sorted. */
+/** Integrity and deletion inventories must never turn unreadable data into
+ * an empty subtree. Callers own rollback or post-commit recovery. */
function listAppFilesRel(dir: string): string[] {
const out: string[] = [];
const walk = (rel: string): void => {
- let entries: fs.Dirent[];
- try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }); }
- catch { return; }
+ const entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true });
for (const e of entries) {
const childRel = rel ? `${rel}/${e.name}` : e.name;
if (e.isDirectory()) walk(childRel);
@@ -1093,11 +1149,10 @@ function recoverEditedSaves(uid: string) {
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;
- }
+ retained.add(temporary); retained.add(backup);
+ const current = isRealSavedAppDirectory(destination) ? fingerprintApp(destination) : null;
+ const rollback = isRealSavedAppDirectory(backup) ? fingerprintApp(backup) : null;
+ if (current !== journal.before && current !== journal.after && (current !== null || rollback !== journal.before)) throw new Error('app_edit_conflict');
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);
@@ -1112,6 +1167,7 @@ function recoverEditedSaves(uid: string) {
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});
+ retained.delete(temporary); retained.delete(backup);
log.info('edited app save recovery completed');
} catch(error) {log.warn('edited app save recovery deferred',{error:logErrorSummary(error)});}
}
@@ -1140,8 +1196,6 @@ export function cleanupEditSnapshots(uid: string, background = false, cid?: stri
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; }
@@ -1170,6 +1224,19 @@ function fingerprintApp(dir: string): string {
}
return digest.digest('hex');
}
+/** Same fingerprint spelling as save/recovery, without reading large source
+ * files synchronously while a user is opening the editor. */
+async function fingerprintAppAsync(dir: string): Promise<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');
+ for await (const chunk of fs.createReadStream(target)) digest.update(chunk as Buffer);
+ digest.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'));
@@ -1181,7 +1248,7 @@ function readEditContext(userId: string, cid: string): EditContext | 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 && (fs.existsSync(path.join(editContextDir(userId, cid),'context.json')) || fs.existsSync(path.join(editContextDir(userId, cid),'snapshot')))) 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;
@@ -1240,11 +1307,22 @@ export async function managedPathAppType(userId: string, file: string): Promise<
return resolveArtifactAppType(userId, segments[start], segments[start + 1]);
}
+/** Opening needs only local identity. An unresolved/damaged edit binding
+ * can render, but must not inherit the ordinary new-artifact local authority. */
+export async function declaredArtifactAppType(userId:string,cid:string,artifactId:string):Promise<AppType|undefined>{
+ const meta=chatArtifacts.readArtifactMeta(userId,cid,artifactId);
+ if(meta?.appType)return meta.appType;
+ const context=readEditContext(userId,cid);
+ if(context)return context.appType??storedAppType(savedAppDir(userId,context.appId))??'local';
+ if(fs.existsSync(path.join(editContextDir(userId,cid),'context.json')) || fs.existsSync(path.join(editContextDir(userId,cid),'snapshot')))return undefined;
+ return await boundAppType(userId,cid)??'local';
+}
+
/** Build the single-`.md` source bundle handed to the editing conversation as
* an attachment. Plain `FILE:` rules (not fenced code blocks) so the app's own
* source — which may contain ``` — can't break the bundle. Binary assets are
* represented as placeholder lines (a text bundle can't carry their bytes). */
-function buildSourceBundle(dir: string, title: string): string {
+async function buildSourceBundle(dir: string, title: string): Promise<string> {
const files = listAppFilesRel(dir).filter((rel) => rel !== META_FILENAME);
let entry = 'index.html';
try {
@@ -1261,12 +1339,10 @@ function buildSourceBundle(dir: string, title: string): string {
const abs = path.join(dir, rel);
lines.push(`========== FILE: ${rel} ==========`);
if (TEXT_LIKE_EXTS.has(path.extname(rel).toLowerCase())) {
- let content = '<could not read this file>';
- try { content = fs.readFileSync(abs, 'utf8'); } catch { /* keep placeholder */ }
- lines.push(content);
+ lines.push(await fsp.readFile(abs, 'utf8'));
} else {
let kb = 1;
- try { kb = Math.max(1, Math.round(fs.statSync(abs).size / 1024)); } catch { /* ignore */ }
+ try { kb = Math.max(1, Math.round((await fsp.stat(abs)).size / 1024)); } catch { /* ignore */ }
lines.push(`[binary asset: ${rel} — ~${kb} KB; kept from the original app. To change it, re-supply it via create_artifact with "encoding":"base64".]`);
}
lines.push('');
@@ -1326,11 +1402,15 @@ export async function openForEditing(
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 originalFingerprint = fingerprintApp(dir);
+ let originalFingerprint: string;
+ try { originalFingerprint = await fingerprintAppAsync(dir); }
+ catch (err) {
+ log.warn('openForEditing snapshot failed', { error: logErrorSummary(err) });
+ return { ok: false, error: 'app_edit_snapshot_failed' };
+ }
let conv: Awaited<ReturnType<typeof chats.createConversation>>;
try {
@@ -1349,21 +1429,22 @@ export async function openForEditing(
const editingDir = editContextDir(userId, conv.conversation_id);
let bundle: string;
+ let up: Awaited<ReturnType<typeof chatAttachments.uploadAttachment>>;
try {
const snapshot = path.join(editingDir, 'snapshot');
await fsp.cp(dir, snapshot, { recursive: true, dereference: false });
- if (fingerprintApp(snapshot) !== originalFingerprint || fingerprintApp(dir) !== originalFingerprint) {
+ if (await fingerprintAppAsync(snapshot) !== originalFingerprint || await fingerprintAppAsync(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);
+ bundle = await buildSourceBundle(snapshot, title);
+ up = await chatAttachments.uploadAttachment(userId, conv.conversation_id, SOURCE_BUNDLE_NAME, Buffer.from(bundle, 'utf8'));
} 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.
await rollbackEditConversation(userId, safeId, editingDir, conv);
diff --git a/src/main/features/web_apps/bundle-revision.ts b/src/main/features/web_apps/bundle-revision.ts
index 423c43f9..ab495c02 100644
--- a/src/main/features/web_apps/bundle-revision.ts
+++ b/src/main/features/web_apps/bundle-revision.ts
@@ -1,21 +1,51 @@
+import * as crypto from 'node:crypto';
import * as fs from 'node:fs';
import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
-/** Freeze the file inventory at launch. Only files from this revision can be
- * served; already loaded resources are rechecked before privileged operations.
- * Immutable saved/artifact source remains owned by its existing resolver. */
-export async function bundleRevision(root: string, required: string[]) {
- const stamps = new Map<string, string>();
+const signature = (s: fs.BigIntStats) => [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(':');
+const stamp = (file: string) => {
+ const s = fs.lstatSync(file, { bigint: true });
+ return s.isFile() ? signature(s) : '';
+};
+
+/** Read a fixed length from the verified handle. Growth cannot keep a check
+ * reading forever, and source bodies are never buffered whole in main memory. */
+async function digest(file: string, expected: string, signal?: AbortSignal): Promise<string> {
+ if (signal?.aborted) throw new Error('bundle check cancelled');
+ if (signature(await fsp.lstat(file, { bigint: true })) !== expected) throw new Error('bundle source changed');
+ const handle = await fsp.open(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW);
+ try {
+ const before = await handle.stat({ bigint: true });
+ if (!before.isFile() || signature(before) !== expected) throw new Error('bundle source changed');
+ const length = Number(before.size);
+ if (!Number.isSafeInteger(length)) throw new Error('unsupported bundle entry');
+ const hash = crypto.createHash('sha256');
+ const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, length));
+ for (let offset = 0; offset < length;) {
+ if (signal?.aborted) throw new Error('bundle check cancelled');
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, length - offset), offset);
+ if (!bytesRead) throw new Error('bundle source changed');
+ hash.update(buffer.subarray(0, bytesRead));
+ offset += bytesRead;
+ }
+ if (signature(await handle.stat({ bigint: true })) !== expected || stamp(file) !== expected) throw new Error('bundle source changed');
+ return hash.digest('hex');
+ } finally { await handle.close(); }
+}
+
+/** Freeze inventory and content identities at launch. Metadata can reject a
+ * revision cheaply, but cannot prove unchanged bytes. Privileged consumers
+ * await valid(); synchronous cancellation/navigation guards use current(). */
+export async function bundleRevision(root: string, required: string[], requiredContents: ReadonlyMap<string, Buffer> = new Map()) {
+ const files = new Map<string, { stamp: string; digest: string }>();
const loaded = new Set(required.map(p => path.resolve(p)));
let invalid = false;
- const stamp = (file: string) => {
- const s = fs.lstatSync(file);
- return s.isFile() ? [s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs].join(':') : '';
- };
// Manifest authority and the entry were resolved before the asynchronous
// inventory. They must not change while that inventory yields to the host.
const requiredStamps = new Map([...loaded].map(file => [file, stamp(file)]));
+ const requiredDigests = new Map([...requiredContents].map(([file, bytes]) =>
+ [path.resolve(file), crypto.createHash('sha256').update(bytes).digest('hex')]));
const pending = [path.resolve(root)];
while (pending.length) {
const dir = pending.pop()!;
@@ -26,23 +56,49 @@ export async function bundleRevision(root: string, required: string[]) {
const file = path.join(dir, item.name);
if (item.isDirectory()) pending.push(file);
else if (item.isFile()) {
- const s = await fsp.lstat(file);
+ const s = await fsp.lstat(file, { bigint: true });
if (!s.isFile()) throw new Error('unsupported bundle entry');
- stamps.set(file, [s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs].join(':'));
+ const identity = signature(s);
+ files.set(file, { stamp: identity, digest: await digest(file, identity) });
} else throw new Error('unsupported bundle entry');
}
}
const same = (file: string) => {
- try { return stamps.has(file) && stamps.get(file) === stamp(file); } catch { return false; }
+ try { return files.get(file)?.stamp === stamp(file); } catch { return false; }
+ };
+ const current = () => {
+ if (!invalid) for (const file of loaded) if (!same(file)) { invalid = true; break; }
+ return !invalid;
};
for (const [file, original] of requiredStamps) {
- if (!original || stamps.get(file) !== original || !same(file)) throw new Error('bundle changed during launch');
+ const recorded = files.get(file);
+ const content = requiredDigests.get(file);
+ if (!original || recorded?.stamp !== original || !same(file)
+ || (content && content !== recorded.digest)) {
+ throw new Error('bundle changed during launch');
+ }
}
+ // Serialize reads per revision, bounding scratch memory and disk fan-out.
+ // Each queued caller reads afresh; no TTL or timestamp-based success cache.
+ let tail: Promise<unknown> = Promise.resolve();
+ const valid = (signal?: AbortSignal): Promise<boolean> => {
+ const check = tail.then(async () => {
+ if (signal?.aborted) return false;
+ if (!current()) return false;
+ try {
+ for (const file of loaded) {
+ const recorded = files.get(file)!;
+ if (await digest(file, recorded.stamp, signal) !== recorded.digest) { invalid = true; return false; }
+ }
+ return current();
+ } catch { if (!signal?.aborted) invalid = true; return false; }
+ });
+ tail = check;
+ return check;
+ };
+ if (!await valid()) throw new Error('bundle changed during launch');
return {
- valid() {
- if (!invalid) for (const file of loaded) if (!same(file)) { invalid = true; break; }
- return !invalid;
- },
+ current, valid,
accept(file: string) {
file = path.resolve(file);
if (invalid || !same(file)) { invalid = true; return false; }
diff --git a/src/main/features/web_apps/catalog.ts b/src/main/features/web_apps/catalog.ts
index 1cafecae..f82b9871 100644
--- a/src/main/features/web_apps/catalog.ts
+++ b/src/main/features/web_apps/catalog.ts
@@ -3,7 +3,7 @@ import { DATA_INPUTS, dataDefinitionSchema, commonMethod, type AppType } from '.
import { isAtomicWriteTempPath } from '../../storage';
import { z } from 'zod';
import { MAX_TEXT_FILE_BYTES } from '../../util/file-size-limits';
-import { zodToJsonSchema } from 'zod-to-json-schema';
+const { schemaToJson } = require('../../../../bin/schema-to-json.cjs');
export const SDK_VERSION = 1;
export const MANIFEST_FILE = 'orkas-app.json';
@@ -47,7 +47,7 @@ export const METHODS = {
'files.release': define('files', 'Release a file handle before closing the app.', z.object({ handle }).strict(), '{released:true}', { handle: '0123456789abcdef0123456789abcdef' }),
'ai.generate': define('ai', '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.', z.object({ prompt: z.string().min(1), maxTokens: z.number().int().positive().safe().optional() }).strict(), '{text,usage,stopReason}; token-limited output has stopReason=max_tokens. Cancel with AbortSignal.', { prompt: 'Write a short greeting.', maxTokens: 128 }),
'tools.list': define(null, '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.', empty, '{tools:[{name,capability,description,inputSchema}]}', {}),
- '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 } }),
+ '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.string(), 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', 'data'] as const;
@@ -70,7 +70,7 @@ export function describeMethod(method: string) {
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 };
+ inputSchema: schemaToJson(def.input), result: def.result, example: def.example };
}
export function catalogDocument(appType:AppType='local') {
const starter = appType === 'web' ? 'web' : 'starter';
@@ -81,11 +81,11 @@ export function catalogDocument(appType:AppType='local') {
: manifestSchema;
return { sdkVersion: SDK_VERSION,
manifest: { file: MANIFEST_FILE, schema: {
- ...zodToJsonSchema(schema, { $refStrategy: 'none' }),
+ ...schemaToJson(schema),
// 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 };
+ dataDefinition:schemaToJson(dataDefinitionSchema), 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
index 0d505be8..fd65a8a9 100644
--- a/src/main/features/web_apps/commercial-entry.ts
+++ b/src/main/features/web_apps/commercial-entry.ts
@@ -2,7 +2,7 @@ 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.';
+const message = 'Publishing apps requires 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 };
}
@@ -10,9 +10,8 @@ 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());
-}
+/** Publication is unavailable before preparing, uploading or changing app state. */
+export function publishApp() { return 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 {
diff --git a/src/main/features/web_apps/data-contract.ts b/src/main/features/web_apps/data-contract.ts
index b024078c..5e8d9f04 100644
--- a/src/main/features/web_apps/data-contract.ts
+++ b/src/main/features/web_apps/data-contract.ts
@@ -37,7 +37,7 @@ export const dataDefinitionSchema = z.object({version:z.literal(1),tables:z.arra
});
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();
+const insert=z.object({table:name,values:z.record(z.string(), 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(),
diff --git a/src/main/features/web_apps/host.ts b/src/main/features/web_apps/host.ts
index 25af8f74..e91a4852 100644
--- a/src/main/features/web_apps/host.ts
+++ b/src/main/features/web_apps/host.ts
@@ -16,7 +16,6 @@ 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> {
@@ -49,9 +48,6 @@ export async function appTools(uid: string, appUsage?: AppUsageScope): Promise<A
}
export const runtime = new WebAppRuntime({
- // Orkas keeps Web apps local; the private cloud-sync dirty marker is
- // intentionally absent while the runtime still receives its change hook.
- storageChanged: () => {},
activeUser: getActiveUserId,
language: getLanguage,
modelAvailable: () => hasConfiguredModel().configured,
@@ -92,11 +88,11 @@ 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);
- 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') {
+ // Publication governs online distribution, never local page availability.
+ // Missing identity limits SDK authority without blocking the document.
+ const appType = (isSaved ? saved.declaredSavedAppType(uid, source.appId)
+ : await saved.declaredArtifactAppType(uid, source.cid, source.artifactId)) ?? 'unresolved';
+ if (!manifestFile && appType !== 'web') {
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.
@@ -110,7 +106,8 @@ export async function resolveBundle(uid: string, source: Source): Promise<{ bund
const stat = fs.statSync(manifestFile.absPath);
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'); }
+ let manifestBytes: Buffer;
+ try { manifestBytes = fs.readFileSync(manifestFile.absPath); manifest = JSON.parse(manifestBytes.toString('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');
let title = t('artifact.title');
try {
@@ -120,19 +117,20 @@ export async function resolveBundle(uid: string, source: Source): Promise<{ bund
if (typeof meta.title === 'string') title = meta.title.slice(0, 120);
} catch { /* A missing legacy title uses the localized default. */ }
let revision: Awaited<ReturnType<typeof bundleRevision>>;
- try { revision = await bundleRevision(path.dirname(manifestFile.absPath), [initial.absPath, manifestFile.absPath]); }
+ try { revision = await bundleRevision(path.dirname(manifestFile.absPath), [initial.absPath, manifestFile.absPath], new Map([[manifestFile.absPath, manifestBytes]])); }
catch { throw new AppError('E_BUNDLE'); }
- return { url, entry, bundle: { appType, kind: isSaved ? 'saved' : 'artifact', key, title, entry, manifest, valid: () => revision.valid(),
+ return { url, entry, bundle: { appType, kind: isSaved ? 'saved' : 'artifact', key, title, entry, manifest,
+ current: () => revision.current(), valid: signal => revision.valid(signal),
resolve: rel => { const file = resolve(rel); return file && revision.accept(file.absPath) ? file : null; } } };
}
export async function openApp(uid: string, owner: number, source: Source) {
const found = await resolveBundle(uid, source);
+ if (getActiveUserId() !== uid) throw new AppError('E_CLOSED');
return found.bundle ? runtime.open(uid, owner, found.bundle) : { url: found.url, entry: found.entry };
}
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';
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 fb092319..d0bd66ee 100644
--- a/src/main/features/web_apps/preview.ts
+++ b/src/main/features/web_apps/preview.ts
@@ -15,8 +15,7 @@ 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';
+import { storedAppType } from './commercial-entry';
export const previewPreload = path.join(SRC_ROOT, 'main/features/web_apps/preview-preload.js');
export interface PreviewSdkEvidence {
@@ -29,22 +28,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 > 64 * 1024) throw new AppError('E_MANIFEST');
let manifest: unknown;
- try { manifest = manifestSchema.parse(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))); }
+ let manifestBytes: Buffer;
+ try { manifestBytes = fs.readFileSync(manifestPath); manifest = manifestSchema.parse(JSON.parse(manifestBytes.toString('utf8'))); }
catch { throw new AppError('E_MANIFEST'); }
let revision: Awaited<ReturnType<typeof bundleRevision>>;
- try { revision = await bundleRevision(root, [entry, manifestPath]); }
+ try { revision = await bundleRevision(root, [entry, manifestPath], new Map([[manifestPath, manifestBytes]])); }
catch { throw new AppError('E_BUNDLE'); }
return { appType, key: 'preview', title: 'HTML preview', entry: path.basename(entry), manifest,
- valid: () => revision.valid(),
+ current: () => revision.current(), valid: signal => revision.valid(signal),
resolve(rel) {
if (!rel || rel.includes('\\') || rel.split('/').some(p => !p || p === '.' || p === '..' || p.startsWith('.'))) return null;
const file = path.resolve(root, rel);
@@ -58,7 +56,6 @@ 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';
@@ -134,7 +131,7 @@ export async function createPreviewSdk(ses: Session, contents: WebContents, bund
if (event.url !== open.url) event.preventDefault();
});
ses.protocol.handle('chat-app', async request => {
- const resource = appResource(request, runtime);
+ const resource = await appResource(request, runtime);
if (!resource || resource.status !== 200) return new Response(null, { status: resource?.status ?? 403 });
try {
if ('body' in resource) return new Response(resource.body, { headers: { ...resource.headers, 'Content-Type': resource.mime } });
diff --git a/src/main/features/web_apps/resources.ts b/src/main/features/web_apps/resources.ts
index 94991b3f..edc44734 100644
--- a/src/main/features/web_apps/resources.ts
+++ b/src/main/features/web_apps/resources.ts
@@ -19,20 +19,21 @@ export function sdkScript(appType: 'local'|'web'='local') {
return scripts.get(appType)!;
}
export const APP_CSP = webContentCsp();
-export function appResource(request: Request, runtime: WebAppRuntime) {
+export async function appResource(request: Request, runtime: WebAppRuntime) {
const url = new URL(request.url);
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'));
+ const scoped = await runtime.resource(url.host, rel, request.headers.get('Origin'));
if (!scoped) return { status: 403 };
const headers: Record<string, string> = { 'Cache-Control': 'no-store',
'Cross-Origin-Resource-Policy': 'same-origin', 'X-Content-Type-Options': 'nosniff' };
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 };
+ const capabilityType = scoped.bundle.appType === 'local' ? 'local' : 'web';
+ if (rel === SDK_PATH) return { status: 200, body: sdkScript(capabilityType), mime: 'text/javascript; charset=utf-8', headers };
+ if (rel === artifacts.BRIDGE_RELPATH) return capabilityType==='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(capabilityType)), 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 0a14aad5..7ee8dfbf 100644
--- a/src/main/features/web_apps/runtime.ts
+++ b/src/main/features/web_apps/runtime.ts
@@ -14,20 +14,25 @@ import {createLogger} from '../../logger';
import { logErrorSummary } from '../../util/log-redact';
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); }
}
+class SourceRevisionError extends AppError {
+ constructor() { super('E_CLOSED'); }
+}
export interface Bundle {
browserOnly?: boolean;
kind?: 'saved' | 'artifact';
- appType?: AppType;
+ /** Unresolved is runtime-only; it allows rendering/common data, never host authority. */
+ appType?: AppType | 'unresolved';
key: string;
title: string;
entry: string;
manifest: unknown;
- valid?(): boolean;
+ /** Cheap rejection only; content validation remains authoritative. */
+ current?(): boolean;
+ valid?(signal?: AbortSignal): boolean | Promise<boolean>;
resolve(rel: string): { absPath: string; mime: string } | null;
}
export interface AppTool {
@@ -243,7 +248,6 @@ export class WebAppRuntime {
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);
@@ -262,16 +266,16 @@ export class WebAppRuntime {
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');
+ if (s.bundle.current?.() === false) {
+ this.close(uid, owner, token); throw new SourceRevisionError();
}
return s;
}
/** The existing artifact bridge is available only in its local task context. */
- canSubmitArtifact(uid: string, owner: number, token: string): boolean {
+ async canSubmitArtifact(uid: string, owner: number, token: string): Promise<boolean> {
try {
const s = this.current(uid, owner, token);
+ await this.check(s, s.controller.signal);
return !this.preview && s.bundle.kind === 'artifact' && s.bundle.appType === 'local';
} catch { return false; }
}
@@ -298,7 +302,9 @@ export class WebAppRuntime {
const instance = [...this.instances.values()].find(s => s.owner === owner && s.host === from.host);
if (!instance) return false;
const rel = to.pathname.slice(1).split('/').map(decodeURIComponent).join('/');
- return this.resource(to.host, rel, `chat-app://${from.host}`)?.resolved?.mime.startsWith('text/html') === true;
+ // This synchronous Electron navigation decision grants no resource or
+ // SDK access. The protocol waits for content validation before serving.
+ return this.resourceCandidate(to.host, rel, `chat-app://${from.host}`)?.resolved?.mime.startsWith('text/html') === true;
} catch { return false; }
}
cancelOriginRequests(owner: number, url: string): void {
@@ -325,13 +331,20 @@ export class WebAppRuntime {
if (!s.seen.add(requestId)) return error('E_LIMIT');
s.requests.get(requestId)?.abort();
}
- resource(host: string, rel: string, origin: string | null) {
+ private resourceCandidate(host: string, rel: string, origin: string | null) {
const s = [...this.instances.values()].find(item => item.host === host);
if (!s || s.uid !== this.host.activeUser() || s.controller.signal.aborted) return null;
try { this.current(s.uid, s.owner, s.token); } catch { return null; }
if (origin && origin !== `chat-app://${host}`) return null;
if (!rel || rel.includes('\\') || rel.split('/').some(p => !p || p === '.' || p === '..' || p.startsWith('.'))) return null;
- return { bundle: s.bundle, resolved: s.bundle.resolve(rel) };
+ return { instance: s, bundle: s.bundle, resolved: s.bundle.resolve(rel) };
+ }
+ async resource(host: string, rel: string, origin: string | null) {
+ const candidate = this.resourceCandidate(host, rel, origin);
+ if (!candidate) return null;
+ try { await this.check(candidate.instance, candidate.instance.controller.signal); }
+ catch { return null; }
+ return { bundle: candidate.bundle, resolved: candidate.resolved };
}
private requireCapability(s: Instance, capability: string): void {
if (!s.manifest.capabilities.includes(capability as any)) return error('E_NOT_DECLARED');
@@ -354,7 +367,7 @@ export class WebAppRuntime {
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');
- if(s.bundle.appType==='web'&&!commonMethod(method))return error('E_UNAVAILABLE');
+ if(s.bundle.appType!=='local'&&!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);
@@ -366,31 +379,38 @@ export class WebAppRuntime {
const signal = controller.signal;
try {
if (def.capability) this.requireCapability(s, def.capability);
- this.check(s, signal);
+ await this.check(s, signal);
const value = await this.execute(s, method as Method, parsed.data, signal, event => {
- this.check(s, signal); boundedJson(event, 64 * 1024); progress(event);
+ this.checkCurrent(s, signal); boundedJson(event, 64 * 1024); progress(event);
});
- if (method !== 'permissions.revoke') this.check(s, signal);
+ if (method !== 'permissions.revoke') await this.check(s, signal);
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.
// The request signal, not provider wording, determines SDK cancellation.
+ if (cause instanceof SourceRevisionError) throw cause;
if (signal.aborted) return error('E_CANCELLED');
throw cause;
} finally { s.requests.delete(requestId); }
}
- private check(s: Instance, signal: AbortSignal) {
+ private checkCurrent(s: Instance, signal: AbortSignal) {
if (signal.aborted) return error('E_CANCELLED');
this.current(s.uid, s.owner, s.token);
}
+ private async check(s: Instance, signal: AbortSignal) {
+ this.checkCurrent(s, signal);
+ const valid = await s.bundle.valid?.(signal);
+ this.checkCurrent(s, signal);
+ if (valid === false) { this.close(s.uid, s.owner, s.token); throw new SourceRevisionError(); }
+ }
private async store(s: Instance, action: string, input: any, signal: AbortSignal) {
const file = this.preview ? path.join(this.preview.storageRoot, input.scope === 'cloud' ? 'cloud-storage.json' : 'storage.json') : webAppDataFile(s.uid, s.bundle.key, input.scope);
let lock = this.stores.get(file);
if (!lock) { lock = { mutex: new Mutex(), users: 0 }; this.stores.set(file, lock); }
lock.users++;
try { return await lock.mutex.runExclusive(async () => {
- this.check(s, signal);
+ await this.check(s, signal);
if (!isPathAllowed(file, [this.preview?.storageRoot ?? (input.scope === 'cloud' ? userCloudRoot(s.uid) : userLocalRoot(s.uid))])) return error('E_FILE');
// App-local paths may not alias another application's private store.
for (const segment of [path.dirname(path.dirname(file)), path.dirname(file), file]) {
@@ -420,7 +440,7 @@ export class WebAppRuntime {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
this.dropStore(file);
}
- this.check(s, signal);
+ await 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() };
const next: Record<string, unknown> = Object.assign(Object.create(null), entries);
@@ -432,8 +452,8 @@ export class WebAppRuntime {
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);
+ await writeBytesAtomic(file, bytes, { shouldCommit: () => { this.checkCurrent(s, signal); return true; } });
+ await 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;
@@ -455,7 +475,7 @@ export class WebAppRuntime {
if (!lock) { lock = { mutex: new Mutex(), users: 0 }; this.stores.set(root, lock); }
lock.users++;
const guard = (target: string) => {
- this.check(s, signal);
+ this.checkCurrent(s, signal);
const boundary = this.preview?.storageRoot ?? (input.scope === 'cloud' ? userCloudRoot(s.uid) : userLocalRoot(s.uid));
if (!isPathAllowed(target, [boundary])) return error('E_FILE');
let current = target;
@@ -466,6 +486,7 @@ export class WebAppRuntime {
}
};
try { return await lock.mutex.runExclusive(async () => {
+ await this.check(s, signal);
guard(file);
if (action === 'appFiles.readText' || action === 'appFiles.readBase64') {
let handle;
@@ -525,8 +546,8 @@ export class WebAppRuntime {
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 (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 => {
+ case 'capabilities.describe': return (s.bundle.appType==='local'||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==='local'||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'),
@@ -536,7 +557,7 @@ export class WebAppRuntime {
}), unsupported: UNSUPPORTED };
case 'permissions.revoke': this.close(s.uid, s.owner, s.token); return { revoked: true };
case 'files.pick': {
- const selected = await this.host.pick(); this.check(s, signal);
+ const selected = await this.host.pick(); await this.check(s, signal);
if (!selected) return null;
const real = await fs.realpath(selected);
if (isPathAllowed(real, [WS_ROOT])) return error('E_FILE');
@@ -544,8 +565,8 @@ export class WebAppRuntime {
try {
const stat = await file.stat();
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return error('E_LIMIT');
- const bytes = await readFileBytes(file, () => this.check(s, signal));
- this.check(s, signal);
+ const bytes = await readFileBytes(file, () => this.checkCurrent(s, signal));
+ await this.check(s, signal);
const handle = id(); const name = path.basename(real);
s.handles.set(handle, { name, bytes });
return { handle, name, size: bytes.length };
@@ -560,7 +581,7 @@ export class WebAppRuntime {
case 'files.release': s.handles.delete(a.handle); return { released: true };
case 'files.saveAs': {
if (Buffer.byteLength(a.text, 'utf8') > MAX_FILE_BYTES) return error('E_LIMIT');
- const selected = await this.host.save(a.name); this.check(s, signal);
+ const selected = await this.host.save(a.name); await this.check(s, signal);
if (!selected) return null;
const parent = await fs.realpath(path.dirname(selected));
const target = path.join(parent, path.basename(selected));
@@ -571,7 +592,7 @@ export class WebAppRuntime {
const file = await fs.open(temp, 'wx', 0o600);
try { await file.writeFile(a.text, 'utf8'); await file.sync(); }
finally { await file.close(); }
- this.check(s, signal);
+ await this.check(s, signal);
// Atomic create-only publication, including on Windows; never replace.
await fs.link(temp, target);
} finally { await fs.unlink(temp).catch(() => {}); }
@@ -583,15 +604,15 @@ export class WebAppRuntime {
}
case 'tools.list': {
if (this.preview) return { tools: [] };
- const tools = await this.host.tools(s.uid, { id: s.token, owner: s.owner }); this.check(s, signal);
+ const tools = await this.host.tools(s.uid, { id: s.token, owner: s.owner }); await this.check(s, signal);
return { tools: tools.filter(tool => s.manifest.capabilities.includes(tool.capability)).map(({ execute: _execute, ...info }) => info) };
}
case 'tools.call': {
- const tools = await this.host.tools(s.uid, { id: s.token, owner: s.owner }); this.check(s, signal);
+ const tools = await this.host.tools(s.uid, { id: s.token, owner: s.owner }); await this.check(s, signal);
const tool = tools.find(tool => tool.name === a.name);
if (!tool) return error('E_TOOL');
- this.requireCapability(s, tool.capability); this.check(s, signal);
- const result = await tool.execute(a.arguments, signal); this.check(s, signal);
+ this.requireCapability(s, tool.capability); await this.check(s, signal);
+ const result = await tool.execute(a.arguments, signal); await this.check(s, signal);
// Never replay a tool because its result cannot fit the app boundary.
try { boundedJson(result); } catch { return error('E_RESULT_LIMIT'); }
return result;
diff --git a/src/main/ipc/web_apps.ts b/src/main/ipc/web_apps.ts
index 57b3135b..b73bbfa2 100644
--- a/src/main/ipc/web_apps.ts
+++ b/src/main/ipc/web_apps.ts
@@ -72,7 +72,7 @@ export const webAppInvokeHandlers = {
} catch (err) { return failure(err); }
},
'webApps.canSubmitArtifact': async (payload: any, ctx: Context) => {
- try { return { allowed: runtime.canSubmitArtifact(ctx.userId, ctx.sender.id, credential(payload)) }; }
+ try { return { allowed: await runtime.canSubmitArtifact(ctx.userId, ctx.sender.id, credential(payload)) }; }
catch { return { allowed: false }; }
},
'webApps.close': async (payload: any, ctx: Context) => {
diff --git a/src/renderer/modules/app-save-recovery.js b/src/renderer/modules/app-save-recovery.js
new file mode 100644
index 00000000..136276ce
--- /dev/null
+++ b/src/renderer/modules/app-save-recovery.js
@@ -0,0 +1,39 @@
+// All authoring surfaces share the same explicit export/clear recovery flow.
+(function () {
+ 'use strict';
+ async function save(channel, payload, label) {
+ const args = { ...payload };
+ let result;
+ try { result = await window.orkas.invoke(channel, args); }
+ catch (error) {
+ if (error?.code !== 'app_edit_data_migration') throw error;
+ result = { ok: false, code: error.code };
+ }
+ if ((result?.code || result?.error) !== 'app_edit_data_migration' || args.mode === 'new') return result;
+ const artifact = channel === 'conversations.artifacts.save';
+ const impact = await window.orkas.invoke(artifact
+ ? 'conversations.artifacts.dataImpact' : 'savedApps.dataImpactFromPath', args);
+ if (!impact?.ok) return impact;
+ const scope = impact.tables.map(table => `${table.name}: ${table.count} (${table.fields.join(', ')})`).join('\n');
+ const exportFirst = await uiConfirm({
+ message: label('apps.migration_export') + '\n' + scope,
+ okLabel: label('apps.migration_export_action'),
+ cancelLabel: label('apps.migration_continue'),
+ });
+ if (exportFirst) {
+ const exported = await window.orkas.invoke(artifact
+ ? 'conversations.artifacts.exportData' : 'savedApps.exportDataFromPath', { ...args, appId: impact.appId });
+ if (!exported?.ok || exported.canceled) return exported;
+ }
+ const confirmed = await uiConfirmDanger({
+ message: label('apps.migration_clear') + '\n' + scope,
+ dangerLabel: label('apps.migration_retry'),
+ });
+ if (!confirmed) return { ok: true, canceled: true };
+ return window.orkas.invoke(channel, {
+ ...args, mode: 'update',
+ recovery: { appId: impact.appId, clearVersion: impact.version, clearFingerprint: impact.fingerprint },
+ });
+ }
+ window.OrkasAppSave = { save };
+})();
diff --git a/src/renderer/modules/chat-artifact.js b/src/renderer/modules/chat-artifact.js
index 3901782d..7e995f4d 100644
--- a/src/renderer/modules/chat-artifact.js
+++ b/src/renderer/modules/chat-artifact.js
@@ -47,12 +47,8 @@
return fallback;
}
- function _notifyFail(prefix, err) {
- const msg = (err && err.message) ? err.message : String(err || '');
- try {
- if (typeof uiAlert === 'function') uiAlert(msg ? _t('artifact.failure_detail', `${prefix}: ${msg}`, { action: prefix, detail: msg }) : prefix);
- else _convLog.warn(prefix, msg);
- } catch (_) {}
+ function _notifyFail(prefix) {
+ try { if (typeof uiAlert === 'function') uiAlert(prefix); } catch (_) {}
}
// Card-header "⋯" popover state. One shared menu element appended to <body>,
@@ -214,7 +210,8 @@
<div class="chat-artifact-viewer-header">
<div class="chat-artifact-viewer-title"></div>
<div class="chat-file-viewer-actions">
- <button type="button" class="chat-file-viewer-save-app chat-artifact-viewer-save">${window.uiIconHtml('layout-grid', 'chat-file-viewer-save-app-icon')}</button>
+ <button type="button" class="chat-file-viewer-save-app chat-artifact-viewer-save" disabled>${window.uiIconHtml('layout-grid', 'chat-file-viewer-save-app-icon')}</button>
+ <button type="button" class="chat-file-viewer-save-new-app chat-artifact-viewer-save-new" hidden>${window.uiIconHtml('plus', 'chat-file-viewer-save-app-icon')}</button>
<button type="button" class="modal-close-btn chat-artifact-viewer-close">${window.uiIconHtml('x', 'modal-close-icon')}</button>
</div>
</div>
@@ -226,7 +223,8 @@
_viewerTitle = el.querySelector('.chat-artifact-viewer-title');
const updateLabels = () => {
for (const [action, key, fallback] of [
- ['save', 'artifact.menu_save', 'Save as app'],
+ ['save', el.dataset.hasSaveTarget === 'true' ? 'apps.update_original' : 'artifact.menu_save', 'Save as app'],
+ ['save-new', 'apps.save_new', 'Save new app'],
['close', 'common.close', 'Close'],
]) {
const button = el.querySelector(`.chat-artifact-viewer-${action}`);
@@ -236,26 +234,45 @@
button.dataset.tooltip = label;
}
};
+ el._updateSaveLabels = updateLabels;
updateLabels();
window.addEventListener('i18n-change', updateLabels);
el.querySelector('.chat-artifact-viewer-close')?.addEventListener('click', _closeViewer);
- const saveButton = el.querySelector('.chat-artifact-viewer-save');
- saveButton.addEventListener('click', async () => {
- if (saveButton.disabled || !_viewerFrame?.dataset.artifactId) return;
- saveButton.disabled = true;
- try {
- await _doSave({ cid: _viewerFrame.dataset.artifactCid, artifactId: _viewerFrame.dataset.artifactId });
- } finally { saveButton.disabled = false; }
- });
+ for (const action of ['save', 'save-new']) {
+ el.querySelector('.chat-artifact-viewer-' + action).addEventListener('click', async () => {
+ const save = el.querySelector('.chat-artifact-viewer-save');
+ const copy = el.querySelector('.chat-artifact-viewer-save-new');
+ if (save.disabled || !_viewerFrame?.dataset.artifactId) return;
+ const ctx = {cid:_viewerFrame.dataset.artifactCid, artifactId:_viewerFrame.dataset.artifactId,
+ saveMode:action === 'save-new' ? 'new' : el.dataset.hasSaveTarget === 'true' ? 'update' : 'auto'};
+ save.disabled = copy.disabled = true;
+ try { await _doSave(ctx); }
+ finally { await _refreshViewerSaveActions(); }
+ });
+ }
return el;
}
+ async function _refreshViewerSaveActions() {
+ if (!_viewerEl || !_viewerFrame) return;
+ const cid = _viewerFrame.dataset.artifactCid, artifactId = _viewerFrame.dataset.artifactId;
+ const save = _viewerEl.querySelector('.chat-artifact-viewer-save');
+ const copy = _viewerEl.querySelector('.chat-artifact-viewer-save-new');
+ save.disabled = copy.disabled = true;
+ let target = null;
+ try { target = (await window.orkas.invoke('conversations.artifacts.editTarget', {cid,artifactId}))?.target; }
+ catch (_) { /* Saving still validates the source at the owning boundary. */ }
+ if (cid !== _viewerFrame.dataset.artifactCid || artifactId !== _viewerFrame.dataset.artifactId) return;
+ _viewerEl.dataset.hasSaveTarget = String(!!target);
+ copy.hidden = !target;
+ _viewerEl._updateSaveLabels();
+ save.disabled = copy.disabled = false;
+ }
+
async function _openViewer(ctx) {
if (!ctx || !ctx.cid || !ctx.artifactId) return;
- 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();
@@ -271,10 +288,11 @@
_viewerFrame.setAttribute('title', title);
window.OrkasWebAppHost.open(_viewerFrame, { cid: ctx.cid, artifactId: ctx.artifactId });
_checkArtifactAvailability(_viewerFrame, ctx);
+ _refreshViewerSaveActions();
}
el.classList.add('is-open');
if (!_viewerKeyHandler) {
- _viewerKeyHandler = (e) => { if (e.key === 'Escape') _closeViewer(); };
+ _viewerKeyHandler = (e) => { if (e.isComposing || e.keyCode === 229) return; if (e.key === 'Escape') _closeViewer(); };
document.addEventListener('keydown', _viewerKeyHandler);
}
}
@@ -299,7 +317,7 @@
if (e.target && e.target.closest && e.target.closest('.chat-artifact-more')) return;
_closeMenu();
});
- document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && el.style.display !== 'none') _closeMenu(); });
+ document.addEventListener('keydown', (e) => { if (e.isComposing || e.keyCode === 229) return; if (e.key === 'Escape' && el.style.display !== 'none') _closeMenu(); });
window.addEventListener('scroll', _closeMenu, true);
window.addEventListener('resize', _closeMenu);
window.addEventListener('i18n-change', _closeMenu);
@@ -355,6 +373,7 @@
const el = _ensureMenuEl();
if (el.style.display !== 'none' && _menuAnchor === anchorBtn) { _closeMenu(); return; }
_closeMenu();
+ delete ctx.saveMode;
_menuCtx = ctx;
_menuAnchor = anchorBtn;
anchorBtn.classList.add('is-menu-open');
@@ -363,9 +382,10 @@
_renderMenuItems(el);
_positionMenu(el, anchorBtn);
try {
- const result = await window.orkas.invoke('conversations.artifacts.editTarget', { cid: String(ctx.cid) });
+ const result = await window.orkas.invoke('conversations.artifacts.editTarget', { cid: String(ctx.cid), artifactId: String(ctx.artifactId) });
if (result?.target && _menuCtx === ctx && el.style.display !== 'none') {
const save = el.querySelector('[data-action="save"]');
+ ctx.saveMode = 'new';
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;
@@ -384,19 +404,6 @@
frame.style.display = 'block';
}
- 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;
@@ -433,11 +440,8 @@
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') : '';
+ tag.hidden = true;
+ tag.textContent = '';
}
async function _checkArtifactAvailability(frame, ctx) {
@@ -461,56 +465,56 @@
_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) });
+ _logArtifactFailure('artifact_inspect', { error_code: 'artifact_operation_failed' });
}
}
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;
+ // A reopened SDK instance has a new isolated origin. Start a fresh frame
+ // document so the old app's navigation guard keeps rejecting cross-app
+ // navigation; the card and its app/storage identity stay unchanged.
_clearArtifactUnavailable(f);
- f.style.height = `${DEFAULT_FRAME_HEIGHT}px`;
- window.OrkasWebAppHost.open(f, { cid: ctx.cid, artifactId: ctx.artifactId });
- _checkArtifactAvailability(f, ctx);
+ const next = f.cloneNode(false);
+ next.removeAttribute('src');
+ next.style.height = `${DEFAULT_FRAME_HEIGHT}px`;
+ _bindArtifactLoadFailure(next, ctx);
+ window.OrkasWebAppHost.release(f);
+ f.parentNode.replaceChild(next, f);
+ if (f === _viewerFrame) _viewerFrame = next;
+ if (_menuCtx?.frame === f) _menuCtx.frame = next;
+ window.OrkasWebAppHost.open(next, { cid: ctx.cid, artifactId: ctx.artifactId });
+ _checkArtifactAvailability(next, ctx);
+ }
+
+ function _bindArtifactLoadFailure(frame, ctx) {
+ frame.addEventListener('orkas-app-error', event => {
+ event.preventDefault();
+ frame._orkasLoadFailed = true;
+ _showArtifactUnavailable(frame, '', () => _doReload({ ...ctx, frame }));
+ });
}
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); }
+ catch (err) { _logArtifactFailure('artifact_open_viewer', { error_code: 'artifact_operation_failed' }); _notifyFail(_t('artifact.open_failed', 'Could not open'), err); }
}
async function _doSave(ctx) {
- 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}});
- }
+ r = await window.OrkasAppSave.save('conversations.artifacts.save', {
+ cid: String(ctx.cid), artifactId: String(ctx.artifactId), mode: ctx.saveMode || 'auto',
+ }, _t);
+ if (r?.canceled) {
+ return;
}
} catch (err) {
const failure = _artifactSaveFailure(err, 'ipc');
@@ -520,7 +524,6 @@
return;
}
if (!r || r.ok === false) {
- if (window.OrkasCommercialEntry.isFailure(r)) return window.OrkasCommercialEntry.show();
const failure = _artifactSaveFailure(r, 'operation');
_logArtifactSaveFailure(failure);
@@ -595,18 +598,15 @@
frame.dataset.artifactId = String(ctx.artifactId);
frame.dataset.artifactAgent = String(ctx.agentId || '');
frame.dataset.artifactTitle = title;
+ frame.dataset.artifactRevision = String(ctx.revision || 0);
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 }));
- });
+ _bindArtifactLoadFailure(frame, ctx);
window.OrkasWebAppHost.open(frame, { cid: ctx.cid, artifactId: ctx.artifactId });
moreBtn.addEventListener('click', (e) => {
e.stopPropagation();
- _openMenu(moreBtn, { frame, cid: ctx.cid, artifactId: ctx.artifactId, title, agentId: ctx.agentId || '' });
+ const currentFrame = card.querySelector('iframe.chat-artifact-frame');
+ _openMenu(moreBtn, { frame: currentFrame, cid: ctx.cid, artifactId: ctx.artifactId, title: currentFrame.dataset.artifactTitle, agentId: ctx.agentId || '' });
});
card.appendChild(header);
@@ -615,14 +615,26 @@
_checkArtifactAvailability(frame, ctx);
}
- // Render every artifact on a message into the given bubble. Idempotent —
- // skips ids already mounted in this bubble (the finalize / append paths
- // can both touch the same bubble).
+ // One card per conversation/app identity. Revisions can arrive from live
+ // callbacks, final messages or history replay; only newer ones reload it.
function mountMessageArtifacts(bubbleEl, artifacts, cid) {
if (!bubbleEl || !Array.isArray(artifacts) || !artifacts.length) return;
for (const a of artifacts) {
if (!a || !a.id) continue;
- if (bubbleEl.querySelector(`iframe.chat-artifact-frame[data-artifact-id="${CSS.escape(String(a.id))}"]`)) continue;
+ const selector = `iframe.chat-artifact-frame[data-artifact-id="${CSS.escape(String(a.id))}"]`;
+ const existing = bubbleEl.querySelector(selector)
+ || Array.from(document.querySelectorAll(selector)).find(frame => frame.dataset.artifactCid === String(cid));
+ if (existing && existing.dataset.artifactCid === String(cid)) {
+ const revision = Number.isSafeInteger(a.revision) && a.revision > 0 ? a.revision : 0;
+ if (revision > Number(existing.dataset.artifactRevision || 0)) {
+ existing.dataset.artifactRevision = String(revision);
+ existing.dataset.artifactTitle = a.title || _t('artifact.title', 'Interactive app');
+ const label = existing.parentNode.querySelector('.chat-artifact-title');
+ if (label) { label.textContent = existing.dataset.artifactTitle; label.title = existing.dataset.artifactTitle; }
+ _doReload({ frame: existing, cid, artifactId: a.id });
+ }
+ continue;
+ }
const host = document.createElement('div');
host.className = 'chat-artifact-host';
bubbleEl.appendChild(host);
@@ -631,6 +643,7 @@
artifactId: a.id,
title: a.title || '',
agentId: a.agent_id || '',
+ revision: a.revision,
});
}
}
diff --git a/src/renderer/modules/commercial-entry.js b/src/renderer/modules/commercial-entry.js
index 178aca21..93a9afdd 100644
--- a/src/renderer/modules/commercial-entry.js
+++ b/src/renderer/modules/commercial-entry.js
@@ -1,6 +1,4 @@
(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';
@@ -30,49 +28,5 @@
});
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 };
+ window.OrkasCommercialEntry = { show, download, isFailure };
})();
diff --git a/src/renderer/modules/saved-apps.js b/src/renderer/modules/saved-apps.js
index 1c50ec5c..4018a9da 100644
--- a/src/renderer/modules/saved-apps.js
+++ b/src/renderer/modules/saved-apps.js
@@ -14,9 +14,8 @@
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 _appsLocalCache = null;
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;
@@ -154,7 +153,8 @@
root.setAttribute('aria-hidden', 'false');
if (!_appViewerKeyHandler) {
_appViewerKeyHandler = (e) => {
- if (e.key === 'Escape' && !document.querySelector('.chat-share-overlay') && _appViewerEl && _appViewerEl.classList.contains('is-open')) _closeAppViewer();
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Escape' && _appViewerEl && _appViewerEl.classList.contains('is-open')) _closeAppViewer();
};
document.addEventListener('keydown', _appViewerKeyHandler);
}
@@ -310,14 +310,11 @@
window.AppActionMenu = { toggle: _toggleActionMenu, close: () => { if (_rowMenuCustom) _closeRowMenu(); } };
// ── actions ─────────────────────────────────────────────────────────────
- async function _openApp(appId) {
+ async function _openApp(appId, online = false) {
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') });
- 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;
}
@@ -330,8 +327,7 @@
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');
+ const failure = _savedAppFailure(r, r && r.ok === false ? 'saved_app_open_failed' : 'invalid_response');
_appsLogFailure('saved_app_open', failure);
_fail(_t('apps.open_failed', 'Could not open the app'), { message: (r && r.error) || 'open failed' });
return;
@@ -352,10 +348,7 @@
// auto-send — the user completes the request and hits Send).
window.openSavedAppPreview = _openAppViewer;
- async function _editApp(appId) {
- const selected = (_appsCache || []).find(row => row.id === appId);
- if (selected && _appType(selected) === 'web') return window.OrkasCommercialEntry.show();
-
+ async function _editApp(appId, capabilities) {
let r;
try {
r = await window.orkas.invoke('savedApps.openForEditing', { appId: String(appId) });
@@ -365,8 +358,7 @@
return;
}
if (!r || r.ok === false) {
- if (window.OrkasCommercialEntry.isFailure(r)) return window.OrkasCommercialEntry.show();
- _appsLogFailure('saved_app_manage', { action: 'edit', ..._savedAppFailure(r, 'saved_app_edit_failed') });
+ _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;
}
@@ -396,9 +388,10 @@
const name = r.title || _t('artifact.title', 'Interactive app');
const input = document.getElementById('chat-input');
if (input) {
- const seed = _t('apps.edit_seed',
+ let seed = _t('apps.edit_seed',
'Modify the interactive app "{name}". Source: attached "{file}":',
{ name, file });
+ if (capabilities?.length) seed += '\n' + _t('apps.publish_adapt_seed', '', { capabilities: capabilities.map(c => _t('apps.capability_' + c, c)).join(', ') });
composerSetText(input, String(seed || '').trimEnd());
if (typeof autoGrow === 'function') autoGrow(input, 200);
if (typeof _saveDraft === 'function') _saveDraft(conv.conversation_id);
@@ -413,6 +406,8 @@
}
}
+ window.editSavedAppForWeb = _editApp;
+
async function _renameApp(appId) {
const cur = (_appsCache || []).find((a) => a.id === appId);
let next = null;
@@ -533,7 +528,6 @@
async function _createAppTask(prompt, onReady, appType) {
- if (appType === 'web' || appType === 'cloud') { await window.OrkasCommercialEntry.show(); return false; }
let stage = 'preflight';
let started = false;
try {
@@ -570,8 +564,7 @@
}
}
- function _openCreatePanel(draft = '', selectedTemplate = 'custom', selectedType = 'local') {
- if (selectedType === 'web' || selectedType === 'cloud') { void window.OrkasCommercialEntry.show(); return; }
+ function _openCreatePanel(draft = '', selectedTemplate = 'custom') {
if (_createPanel) return;
_closeRowMenu();
const previousFocus = document.activeElement;
@@ -585,9 +578,6 @@
<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>
@@ -625,7 +615,7 @@
const releaseFocusGuard = _uiKeepDialogFocus(overlay, idea);
const close = (retainDraft = true) => {
if (!overlay.isConnected) return;
- _createDraft = retainDraft ? { idea: idea.value, template: selectedTemplate, type: selectedType } : null;
+ _createDraft = retainDraft ? { idea: idea.value, template: selectedTemplate } : null;
releaseFocusGuard();
document.removeEventListener('keydown', onKey, true);
overlay.remove();
@@ -643,11 +633,6 @@
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]')) {
close(); return;
}
@@ -667,16 +652,16 @@
cancelButton.disabled = true;
idea.disabled = true;
createButton.setAttribute('aria-busy', 'true');
- overlay.querySelectorAll('[data-app-template],[data-app-type]').forEach(button => { button.disabled = true; });
- await _createAppTask(idea.value, () => close(false), selectedType);
+ overlay.querySelectorAll('[data-app-template]').forEach(button => { button.disabled = true; });
+ await _createAppTask(idea.value, () => close(false), 'local');
submitting = false;
updateSubmit();
cancelButton.disabled = false;
idea.disabled = false;
createButton.removeAttribute('aria-busy');
- overlay.querySelectorAll('[data-app-template],[data-app-type]').forEach(button => { button.disabled = false; });
+ overlay.querySelectorAll('[data-app-template]').forEach(button => { button.disabled = false; });
});
- _createPanel = { close, getDraft: () => idea.value, getTemplate: () => selectedTemplate, getType:()=>selectedType, isSubmitting: () => submitting };
+ _createPanel = { close, getDraft: () => idea.value, getTemplate: () => selectedTemplate, isSubmitting: () => submitting };
idea.focus();
}
@@ -696,7 +681,7 @@
grid.innerHTML = '';
const list = (Array.isArray(apps) ? apps : []).filter(app => {
if (!app || !app.id) return false;
- return _appType(app) === _appsFilter;
+ return true;
});
if (empty) empty.style.display = list.length ? 'none' : '';
if (countEl) countEl.textContent = list.length ? String(list.length) : '';
@@ -723,7 +708,7 @@
const icon = document.createElement('span');
icon.className = `app-card-icon is-${tones[hash % tones.length]}`;
icon.setAttribute('aria-hidden', 'true');
- icon.innerHTML = uiIconHtml(_appType(a) === 'web' ? 'cloud' : 'layout-grid');
+ icon.innerHTML = uiIconHtml('layout-grid');
const header = document.createElement('div');
header.className = 'app-card-header';
header.appendChild(icon);
@@ -802,52 +787,11 @@
}
}
- function _appType(app) {
- if (app.appType === 'local') return 'local';
- return app.appType === 'web' || app.appType === 'cloud' ? 'web' : 'local';
- }
- 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();
+ function repaintSavedApps() {
+ if (!_appsLocalCache) return;
+ _appsCache = _appsLocalCache;
+ _renderApps(_appsCache);
}
async function loadSavedApps(_force, options) {
@@ -856,15 +800,14 @@
_createPanel?.close(false);
_createDraft = null;
_appsCache = null;
+ _appsLocalCache = null;
_closeRowMenu();
_renderApps([]);
}
- _renderFilters();
const createButton = document.getElementById('apps-create-btn');
if (createButton) createButton.onclick = () => {
if (_createPanel) return;
-
- _openCreatePanel(_createDraft?.idea ?? '', _createDraft?.template ?? 'custom', _createDraft?.type ?? _appsFilter);
+ _openCreatePanel(_createDraft?.idea ?? '', _createDraft?.template ?? 'custom');
};
// List from disk before online revalidation. Legacy type recovery can need
// the service; it must not hold every app card behind a network request.
@@ -873,6 +816,7 @@
if(request!==_appsLoadGeneration)return;
if (!r || r.ok === false || !Array.isArray(r.apps)) throw new Error('saved_app_list_failed');
_appsCache = r.apps;
+ _appsLocalCache = r.apps;
} catch (_) {
if(request!==_appsLoadGeneration)return;
_appsLog.warn('savedApps.list failed', { error_code: 'saved_app_list_failed' });
@@ -884,14 +828,14 @@
window.addEventListener('i18n-change', () => {
_closeRowMenu();
if (_appsCache) _renderApps(_appsCache);
- _renderFilters();
if (_createPanel && !_createPanel.isSubmitting()) {
const selectedTemplate = _createPanel.getTemplate();
- const draft = _createPanel.getDraft(),selectedType=_createPanel.getType();
+ const draft = _createPanel.getDraft();
_createPanel.close();
- _openCreatePanel(draft, selectedTemplate,selectedType);
+ _openCreatePanel(draft, selectedTemplate);
}
});
window.loadSavedApps = loadSavedApps;
+ window.repaintSavedApps = repaintSavedApps;
})();
diff --git a/test/e2e/artifact_revisions_e2e_lifecycle.spec.ts b/test/e2e/artifact_revisions_e2e_lifecycle.spec.ts
new file mode 100644
index 00000000..32b0a31e
--- /dev/null
+++ b/test/e2e/artifact_revisions_e2e_lifecycle.spec.ts
@@ -0,0 +1,66 @@
+import path from 'node:path';
+import { expect, test } from './fixtures/orkas';
+
+
+test('a corrected application keeps one card and its SDK data through reload and explicit save', async ({ orkas }, info) => {
+ const page = orkas.page!;
+ const state = await orkas.electronApp!.evaluate(async (_electron, input) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const uid = req(input.users).getActiveUserId();
+ const task = await req(input.chats).createConversation(uid, { title: 'Correct an application' });
+ const cid = task.conversation_id;
+ const events: any[] = [];
+ const tool = req(input.tools).createLocalTools({ userId: uid, cid, agentId: 'commander',
+ onArtifactCreated: (artifact: any) => events.push({ ...artifact, agent_id: 'commander' }),
+ artifactInteractionSmoke: async () => ({ ok: events.length > 0, blockers: events.length ? [] : ['fixture runtime issue'] }),
+ }).find((candidate: any) => candidate.name === 'create_artifact');
+ const files = (title: string) => [
+ { path: 'index.html', content: `<!doctype html><html><head><script src="/__orkas/sdk.js"></script></head><body><h1>${title}</h1><button onclick="this.textContent='Working'">Try</button></body></html>` },
+ { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }) },
+ ];
+ const result = await tool.execute({ title: 'Chat', files: files('Draft') }, { state: {} });
+ if (result.isError) throw new Error(result.content);
+ (globalThis as any).__artifactRevisionFixture = { tool, events, files, uid, cid };
+ return { cid, artifact: events[0] };
+ }, { users: path.resolve('src/main/features/users.ts'), chats: path.resolve('src/main/features/chats.ts'),
+ tools: path.resolve('src/main/model/core-agent/local-tools.ts') });
+ const mount = async (artifacts: any[]) => page.evaluate(({ cid, artifacts }) => {
+ let host = document.querySelector('#revision-app');
+ if (!host) {
+ host = document.createElement('div'); host.id = 'revision-app'; host.className = 'chat-bubble';
+ host.setAttribute('style', 'width:600px;max-width:100%;container-type:inline-size');
+ document.querySelector('#panel-new-chat')!.appendChild(host);
+ }
+ (window as any).mountMessageArtifacts(host, artifacts, cid);
+ }, { cid: state.cid, artifacts });
+ await mount([state.artifact]);
+ const frame = page.frameLocator('#revision-app iframe');
+ await expect(frame.locator('h1')).toHaveText('Draft');
+ await frame.locator('body').evaluate(async () => (window as any).orkasApp.storage.set({ key: 'draft', value: 'Keep my data' }));
+ const corrected = await orkas.electronApp!.evaluate(async () => {
+ const fixture = (globalThis as any).__artifactRevisionFixture;
+ const result = await fixture.tool.execute({ artifact_id: fixture.events[0].id, files: fixture.files('Corrected') }, { state: {} });
+ if (result.isError) throw new Error(result.content);
+ return fixture.events;
+ });
+ expect(corrected.map((item: any) => item.id)).toEqual([state.artifact.id, state.artifact.id]);
+ await mount(corrected);
+ await expect(page.locator('#revision-app .chat-artifact-card')).toHaveCount(1);
+ await expect(frame.locator('h1')).toHaveText('Corrected');
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'draft' }))).toEqual({ value: 'Keep my data' });
+ await frame.getByRole('button', { name: 'Try' }).click();
+ await expect(frame.getByRole('button', { name: 'Working' })).toBeVisible();
+ await page.screenshot({ path: info.outputPath('corrected-single-app.png') });
+ await page.reload();
+ await expect(page.locator('#panel-new-chat')).toHaveClass(/active/);
+ await mount(corrected);
+ await expect(page.locator('#revision-app .chat-artifact-card')).toHaveCount(1);
+ await expect(frame.locator('h1')).toHaveText('Corrected');
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'draft' }))).toEqual({ value: 'Keep my data' });
+ const saved: any = await orkas.invoke('conversations.artifacts.save', { cid: state.cid, artifactId: state.artifact.id });
+ expect(saved.ok).toBe(true);
+ const preview = await orkas.openPreview(() => page.evaluate(source => (window as any).OrkasPreviewWindows.open(source),
+ { kind: 'app', appId: saved.id, title: 'Chat' }));
+ await expect(preview.frameLocator('.saved-app-viewer-frame').locator('h1')).toHaveText('Corrected');
+ expect(orkas.modelRequests).toHaveLength(0);
+});
diff --git a/test/e2e/membership_e2e_credit_copy.spec.ts b/test/e2e/membership_e2e_credit_copy.spec.ts
new file mode 100644
index 00000000..bfde91c5
--- /dev/null
+++ b/test/e2e/membership_e2e_credit_copy.spec.ts
@@ -0,0 +1,24 @@
+import { expect, test } from './fixtures/orkas';
+
+test('saves a user-owned image service across language changes', async ({ orkas }, testInfo) => {
+ const page = orkas.page!;
+ await page.evaluate(async () => { await (window as any).setLang('en'); });
+ await page.locator('#settings-btn').click();
+ await page.locator('.settings-tab[data-settings-tab="credentials"]').click();
+ await page.locator('#settings-model-tab-image').click();
+ await page.locator('[data-settings-add="image"]').click();
+ await page.locator('#settings-image-provider .ai-select-trigger').click();
+ const choices = page.locator('.ai-select-popover [role="option"]');
+ await expect(choices.filter({ hasText: 'DouBao · Seedream 5.0 Lite' })).toHaveCount(1);
+ await expect(choices.filter({ hasText: 'DouBao · Seedream 5.0 Pro' })).toHaveCount(1);
+ await expect(choices.filter({ hasText: 'DouBao · Seedream 5.0 Lite' })).toBeVisible();
+ await page.screenshot({ path: testInfo.outputPath('image-service-picker-en.png') });
+ await choices.filter({ hasText: 'DouBao · Seedream 5.0 Lite' }).click();
+ await page.locator('#settings-image-key-input').fill('fixture-image-key');
+ await page.locator('#settings-image-add-btn').click();
+ await expect(page.locator('#settings-image-entries')).toContainText('DouBao · Seedream 5.0 Lite');
+ await page.setViewportSize({ width: 1000, height: 640 });
+ await page.evaluate(async () => { await (window as any).setLang('zh'); });
+ await expect(page.locator('#settings-image-entries')).toContainText('DouBao · Seedream 5.0 Lite');
+ await page.screenshot({ path: testInfo.outputPath('image-service-saved-zh-short.png') });
+});
diff --git a/test/e2e/resource_lifecycle_e2e_notes.spec.ts b/test/e2e/resource_lifecycle_e2e_notes.spec.ts
new file mode 100644
index 00000000..0fe38c9e
--- /dev/null
+++ b/test/e2e/resource_lifecycle_e2e_notes.spec.ts
@@ -0,0 +1,150 @@
+import path from 'node:path';
+import { writeFileSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { test } from './fixtures/web-app-eval';
+import { expect } from './fixtures/orkas';
+
+for (const variant of ['working', 'denied-order', 'memory-only', 'write-only', 'fake-list'] as const) {
+ test(`notes completion oracle observes real save/list/reopen: ${variant}`, async ({ sdkOrkas: orkas }, info) => {
+ const data = { version: 1, tables: [{ id: 'notes', name: 'notes', fields: [{ id: 'body', name: 'body', type: 'string' }],
+ access: { read: ['body'], insert: ['body'] } }] };
+ const query = `await orkasApp.data.query({table:'notes'${variant === 'denied-order' ? ",order:{field:'createdAt',direction:'desc'}" : ''}})`;
+ const entry = orkas.createWorkspaceFile('notes/index.html', `<!doctype html><html><head><script src="/__orkas/sdk.js"></script></head><body>
+ <label>Note<textarea></textarea></label><button>Save</button><h2>Notes</h2><ul></ul><p role="status"></p>
+ <script>const field=document.querySelector('textarea'),list=document.querySelector('ul');let rows=[];
+ async function refresh(){const r=${variant === 'memory-only' ? '{records:rows}' : query};list.replaceChildren();for(const row of r.records){const li=document.createElement('li');li.textContent=row.body;list.append(li);}}
+ document.querySelector('button').onclick=async()=>{try{
+ ${variant === 'memory-only' || variant === 'fake-list' ? "rows.push({body:field.value});" : "await orkasApp.data.insert({table:'notes',values:{body:field.value},requestId:crypto.randomUUID()});"}
+ ${variant === 'fake-list' ? "list.textContent=field.value;" : variant === 'write-only' ? '' : 'await refresh();'}
+ }catch(e){document.querySelector('[role=status]').textContent=e.code;}};
+ ${variant === 'write-only' || variant === 'fake-list' ? '' : "refresh().catch(e=>document.querySelector('[role=status]').textContent=e.code);"}
+ </script></body></html>`);
+ orkas.createWorkspaceFile('notes/orkas-app.json', JSON.stringify({ sdkVersion: 1, capabilities: ['data'], data }));
+ orkas.createWorkspaceFile('notes/__orkas-meta.json', JSON.stringify({ appType: 'web' }));
+ const marker = `Note ${randomUUID()}`;
+ const source = await orkas.electronApp!.evaluate(async (_, args) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const fs = req('node:fs'), path = req('node:path');
+ const artifacts = req(`${args.root}/src/main/features/chat_artifacts.ts`);
+ const chats = req(`${args.root}/src/main/features/chats.ts`);
+ const saved = req(`${args.root}/src/main/features/saved_apps.ts`);
+ const runtime = req(`${args.root}/src/main/features/web_apps/host.ts`).runtime;
+ const uid = req(`${args.root}/src/main/features/users.ts`).getActiveUserId();
+ const beforeApps = saved.listSavedApps(uid).map((app: any) => app.id).sort();
+ const chat = await chats.createConversation(uid, { title: 'Notes journey calibration' });
+ const files = ['index.html', 'orkas-app.json'].map(name => ({ path: name,
+ content: fs.readFileSync(path.join(path.dirname(args.entry), name), 'utf8') }));
+ const created = await artifacts.createArtifact(uid, chat.conversation_id, 'commander', { appType: 'web', files });
+ if (!created.ok) throw new Error('calibration-artifact-create-failed');
+ const manifest = JSON.parse(files[1].content);
+ const valid = artifacts.resolveArtifactDir(uid, chat.conversation_id, created.artifactId).ok
+ && artifacts.readArtifactMeta(uid, chat.conversation_id, created.artifactId)?.appType === 'web'
+ && JSON.stringify(manifest.capabilities) === JSON.stringify(['data']) && manifest.data?.tables?.length > 0;
+ const observed = { inserts: 0, reads: 0, calls: [] as Array<{ method: string; ok: boolean; code?: string }> };
+ const original = runtime.call;
+ // Observe successful production calls without fabricating an SDK answer.
+ runtime.call = async function (...call: any[]) {
+ try {
+ const value = await original.apply(this, call);
+ if (call[0] === uid && String(call[4]).startsWith('data.')) {
+ if (observed.calls.length < 64) observed.calls.push({ method: call[4], ok: true });
+ if ((call[4] === 'data.insert' || call[4] === 'data.insertIf') && value?.id) observed.inserts++;
+ if (call[4] === 'data.query' && value?.records?.some((row: any) => row.body === args.marker)) observed.reads++;
+ }
+ return value;
+ } catch (error) {
+ if (call[0] === uid && String(call[4]).startsWith('data.') && observed.calls.length < 64)
+ observed.calls.push({ method: call[4], ok: false, code: (error as any)?.code });
+ throw error;
+ }
+ };
+ (globalThis as any).__notesCompletion = { observed, runtime, original, saved, uid, beforeApps };
+ return { kind: 'artifact' as const, cid: chat.conversation_id, artifactId: created.artifactId, title: 'Notes', valid };
+ }, { root: path.resolve(__dirname, '../..'), entry, marker });
+ const evidence = { saved: false, listed: false, reopened: false, commonData: false, status: 'incomplete' };
+ const readObservation = () => orkas.electronApp!.evaluate(() => (globalThis as any).__notesCompletion.observed);
+ const open = () => orkas.openPreview(() => orkas.page!.evaluate(({ valid: _valid, ...source }) =>
+ (window as any).OrkasPreviewWindows.open(source), source));
+ let preview: Awaited<ReturnType<typeof open>> | undefined;
+ let inventoryPreserved = false;
+ try {
+ preview = await open();
+ let frame = preview.frameLocator('.chat-artifact-viewer-frame');
+ await frame.getByRole('textbox', { name: 'Note', exact: true }).fill(marker);
+ await frame.getByRole('button', { name: 'Save', exact: true }).click();
+ // Negative controls are ordinary UI outcomes, not swallowed test failures.
+ const deadline = Date.now() + 3_000;
+ while (Date.now() < deadline
+ && !(await frame.getByRole('listitem').filter({ hasText: marker }).isVisible())
+ && !(await frame.getByRole('status').textContent())) await preview.waitForTimeout(50);
+ if (variant === 'denied-order') await expect(frame.getByRole('status')).toHaveText('E_PERMISSION');
+ const first = await readObservation();
+ evidence.saved = first.inserts > 0;
+ evidence.listed = await frame.getByRole('listitem').filter({ hasText: marker }).isVisible() && first.reads > 0;
+ await orkas.closePreview(preview); preview = undefined;
+ await orkas.electronApp!.evaluate(async () => { await (globalThis as any).__notesCompletion.runtime.drainData(); });
+ if (evidence.saved && evidence.listed) {
+ preview = await open();
+ frame = preview.frameLocator('.chat-artifact-viewer-frame');
+ await expect(frame.getByRole('listitem').filter({ hasText: marker })).toBeVisible();
+ evidence.reopened = (await readObservation()).reads > first.reads;
+ }
+ evidence.commonData = evidence.saved && evidence.listed && evidence.reopened;
+ if (evidence.commonData) evidence.status = 'completed';
+ } finally {
+ try { if (preview && !preview.isClosed()) await orkas.closePreview(preview); }
+ finally {
+ inventoryPreserved = await orkas.electronApp!.evaluate(async () => {
+ const fixture = (globalThis as any).__notesCompletion;
+ fixture.runtime.call = fixture.original;
+ await fixture.runtime.drainData();
+ const unchanged = JSON.stringify(fixture.saved.listSavedApps(fixture.uid).map((app: any) => app.id).sort()) === JSON.stringify(fixture.beforeApps);
+ delete (globalThis as any).__notesCompletion;
+ return unchanged;
+ });
+ }
+ }
+ const observed = { evidence, bundleValid: source.valid, inventoryPreserved,
+ accepted: source.valid && inventoryPreserved && evidence.commonData };
+ expect(observed.accepted).toBe(variant === 'working');
+ writeFileSync(info.outputPath('journey.json'), JSON.stringify(observed, null, 2));
+ expect(evidence.commonData).toBe(variant === 'working');
+ if (variant === 'working') expect(evidence).toMatchObject({ saved: true, listed: true, reopened: true, status: 'completed' });
+ else expect(evidence.status).toBe('incomplete');
+ expect(orkas.modelRequests).toHaveLength(0);
+ });
+}
+
+test('caught SDK failures remain observations and the artifact is delivered in every viewport', async ({ sdkOrkas: orkas }, info) => {
+ const result = await orkas.electronApp!.evaluate(async (_, args) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const toolsModule = req(`${args.root}/src/main/model/core-agent/local-tools.ts`);
+ const artifacts = req(`${args.root}/src/main/features/chat_artifacts.ts`);
+ const { getActiveUserId } = req(`${args.root}/src/main/features/users.ts`);
+ const uid = getActiveUserId(), cid = 'sdk-observation-e2e';
+ let artifactId = '';
+ const tools = toolsModule.createLocalTools({ userId: uid, cid, onArtifactCreated: (a: any) => { artifactId = a.id; } });
+ const files = [{ path: 'index.html', content: `<!doctype html><html><head><script src="/__orkas/sdk.js"></script>
+ <style>button:focus-visible{outline:3px solid blue}</style></head><body><button>Update</button><output></output><script>
+ const out=document.querySelector('output');document.querySelector('button').onclick=()=>out.textContent='Updated';
+ // The defect used to disappear when it occurred outside the first viewport.
+ if(innerWidth<500)orkasApp.data.query({table:'notes',order:{field:'createdAt',direction:'desc'}}).catch(e=>out.textContent=e.code);
+ </script></body></html>` }, { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['data'],
+ data: { version: 1, tables: [{ id: 'notes', name: 'notes', fields: [{ id: 'body', name: 'body', type: 'string' }], access: { read: ['body'], insert: ['body'] } }] } }) }];
+ const created = await tools.find((t: any) => t.name === 'create_artifact').execute({ title: 'Editable notes', appType: 'web', files }, { state: {} });
+ const dir = artifacts.resolveArtifactDir(uid, cid, artifactId);
+ const preview = await tools.find((t: any) => t.name === 'html_preview').execute({ artifact_id: artifactId, target: 'responsive', screenshots: false }, { state: {} });
+ return { created, delivered: Boolean(artifactId && dir.ok), preview };
+ }, { root: path.resolve(__dirname, '../..') });
+ writeFileSync(info.outputPath('observations.json'), JSON.stringify(result, null, 2));
+ expect(result.delivered).toBe(true);
+ expect(result.created.isError).toBeUndefined();
+ expect(result.created.content).toContain('mobile data.query: E_PERMISSION');
+ expect(result.created.content).not.toContain('checks passed');
+ expect(result.created.content).toContain('not a full functional verification');
+ expect(result.preview.isError).toBeUndefined();
+ const evidence = JSON.parse(result.preview.content);
+ expect(evidence.sdk.calls).toEqual([]);
+ expect(evidence.sdkByViewport.find((item: any) => item.viewport === 'mobile').calls).toContainEqual({ method: 'data.query', code: 'E_PERMISSION' });
+ expect(evidence.blockers).toEqual([]);
+});
diff --git a/test/e2e/saved_apps_e2e_lifecycle.spec.ts b/test/e2e/saved_apps_e2e_lifecycle.spec.ts
index daf403a0..2c9ff592 100644
--- a/test/e2e/saved_apps_e2e_lifecycle.spec.ts
+++ b/test/e2e/saved_apps_e2e_lifecycle.spec.ts
@@ -1,20 +1,9 @@
-import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { appendFileSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { expectComposerText } from './fixtures/composer';
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!;
@@ -142,7 +131,7 @@ test.describe('My Apps', () => {
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-app-type]')).toHaveCount(0);
await expect(panel.locator('[data-create-submit]')).toBeEnabled();
}
await panel.screenshot({ path: testInfo.outputPath('retained-create-draft.png') });
@@ -155,79 +144,38 @@ test.describe('My Apps', () => {
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) => {
+ test('shows local and legacy web apps in one creation flow across languages and widths', 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>');
+ const entry = orkas.createWorkspaceFile('unified/index.html', '<h1>Inventory</h1>');
await orkas.invoke('savedApps.saveFromPath', { path: entry, title: 'Inventory' });
+ const creation = await orkas.invoke<any>('conversations.create', { title: 'Legacy web', assistance: { kind: 'app_creation', appType: 'web' } });
+ const web = orkas.createWorkspaceFile('legacy-web/index.html', '<h1>Notes</h1>');
+ await orkas.invoke('savedApps.saveFromPath', { path: web, title: 'Notes', cid: creation.conversation.conversation_id });
await openSidebarEntry(page, '#apps-btn');
- await expect(page.locator('.app-card')).toHaveCount(1);
+ await expect(page.locator('.app-card')).toHaveCount(2);
+ await expect(page.locator('[data-app-filter]')).toHaveCount(0);
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 });
+ for (const language of ['en', 'zh', 'de', 'ar']) {
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);
+ for (const width of [1133, 560]) {
+ await page.setViewportSize({width, height:720});
+ await expect(page.locator('#apps-publication-quota')).toHaveCount(0);
+ expect(await page.locator('#panel-apps').evaluate(el => el.scrollWidth <= el.clientWidth)).toBe(true);
+ await page.locator('#panel-apps').screenshot({path:testInfo.outputPath(`unified-${language}-${width}.png`)});
+ }
}
- 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' });
+ await page.locator('#apps-create-btn').click();
+ const panel = page.locator('.apps-create-panel');
+ await expect(panel.locator('[data-app-type]')).toHaveCount(0);
+ await panel.locator('textarea').fill('Keep this draft');
+ await page.evaluate(() => (window as any).setLang('zh'));
+ await expect(panel.locator('textarea')).toHaveValue('Keep this draft');
+ await panel.screenshot({path:testInfo.outputPath('unified-create.png')});
+ await panel.locator('[data-create-cancel]').click();
+ await page.locator('#apps-create-btn').click();
+ await expect(panel.locator('textarea')).toHaveValue('Keep this draft');
+ await panel.locator('[data-create-cancel]').click();
+ expect(orkas.modelRequests).toHaveLength(0);
});
for (const existingTaskCount of [0, 2]) {
@@ -242,7 +190,8 @@ test.describe('My Apps', () => {
await page.evaluate(() => (window as any).loadConversations());
await expect(page.locator('#conversation-list .conv-item')).toHaveCount(existingTaskCount);
await page.locator('.chat-rich-editor[data-rich-input-id="new-chat-input"]').fill('Unrelated home draft');
- await page.locator('#apps-btn').click();
+ await openSidebarEntry(page, '#apps-btn');
+
const opener = page.locator('#apps-create-btn');
await opener.click();
const panel = page.getByRole('dialog', { name: 'Create app', exact: true });
@@ -255,7 +204,7 @@ test.describe('My Apps', () => {
await idea.fill(' ');
await expect(submit).toBeDisabled();
await page.keyboard.press('Shift+Tab');
- await expect(panel.locator('[data-app-type=web]')).toBeFocused();
+ await expect(cancel).toBeFocused();
await idea.focus();
await idea.dispatchEvent('keydown', { key: 'Escape', isComposing: true });
await expect(panel).toBeVisible();
@@ -275,7 +224,7 @@ 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(panel.locator('[data-app-type]')).toHaveCount(0);
await expect(idea).toHaveValue(/snake game/i);
await idea.fill('Create an app to plan family meals');
await idea.press('Enter');
@@ -355,7 +304,7 @@ test.describe('My Apps', () => {
const page = orkas.page!;
const entry = orkas.createWorkspaceFile('app-gallery/index.html', '<!doctype html><h1>My app</h1>');
for (const title of ['Orkas · SDK 能力体验馆', '像素贪吃蛇', '霓虹贪吃蛇', '指挥官 · 智能体详情', '计算器应用', 'ROI 计算器', '长标题应用 <img src=x onerror=alert(1)> '.repeat(5)]) {
- await orkas.invoke('savedApps.saveFromPath', { path: entry, title });
+ await orkas.invoke('savedApps.saveFromPath', { path: entry, title, mode: 'new' });
}
await openSidebarEntry(page, '#apps-btn');
await expect(page.locator('.app-card')).toHaveCount(7);
@@ -424,20 +373,6 @@ test.describe('My Apps', () => {
await expect(card).toContainText('E2E Saved App');
await expect(page.locator('#apps-page-header-count')).toHaveText('1');
- const moreButton = card.locator('[data-app-more]');
- await expect(moreButton).toHaveCSS('position', 'absolute');
- await expect(moreButton).toHaveCSS('top', '12px');
- await expect(moreButton).toHaveCSS('right', '12px');
- await expect(moreButton).toBeHidden();
- await card.hover();
- await expect(moreButton).toBeVisible();
- await page.locator('.apps-page-header-title').hover();
- await expect(moreButton).toBeHidden();
- await card.focus();
- await expect(moreButton).toBeVisible();
- await page.locator('#apps-create-btn').focus();
- await expect(moreButton).toBeHidden();
-
const opened = orkas.electronApp!.waitForEvent('window');
await card.click();
const preview = await opened;
@@ -513,13 +448,13 @@ test.describe('My Apps', () => {
});
-test('labels each application artifact inside its bubble across languages and reopening', async ({ orkas }, testInfo) => {
+test('shows unified application artifacts 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) =>
+ const result = 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>' }],
@@ -542,20 +477,19 @@ test('labels each application artifact inside its bubble across languages and re
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(cards.locator('.chat-app-type-tag:visible')).toHaveCount(0);
await expect(page.locator('#chat-header .chat-app-type-tag')).toHaveCount(0);
await page.evaluate(() => (window as any).setLang('zh'));
- await expect(tags).toHaveText(['本地应用', '网页应用']);
+ await expect(cards.locator('.chat-app-type-tag:visible')).toHaveCount(0);
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
+ return title.right <= menu.left && el.scrollWidth <= el.clientWidth
&& bounds.left >= bubble.left && bounds.right <= bubble.right;
})).toBe(true);
}
@@ -567,50 +501,21 @@ test('labels each application artifact inside its bubble across languages and re
}
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');
+ await expect(cards.locator('.chat-app-type-tag:visible')).toHaveCount(0);
+ await expect(cards.locator('iframe')).toHaveCount(2);
});
-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 }) => {
+test('keeps legacy untyped artifacts usable without type labels', 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 created = await orkas.invoke<any>('conversations.create', { title: 'Untyped output', ...(assistance ? { assistance } : {}) });
const cid = created.conversation.conversation_id;
- const result = historicalArtifact(orkas.workspaceRoot, cid);
+ const result = await orkas.electronApp!.evaluate(async (_electron, args) =>
+ (process as any).mainModule.require(args.module).createArtifact('account-e2e', args.cid, 'commander', {
+ title: 'Untyped app', files: [{ path: 'index.html', content: '<!doctype html><h1>Untyped</h1>' }],
+ }), { module: path.resolve(__dirname, '../../src/main/features/chat_artifacts.ts'), 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' }));
@@ -625,22 +530,23 @@ test('labels an untyped artifact from its task: web in a web creation task, loca
}, 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());
+ await expect(tag).toBeHidden();
+ await expect(page.locator('#chat-history .chat-artifact-card iframe')).toHaveCount(1);
}
- expect(tags).toEqual(['Web app', 'Local app']);
});
-test('keeps the local application icon while the web entry only offers commercial guidance', async ({ orkas }) => {
+test('uses unified app icons for local and legacy web apps', async ({ orkas }, testInfo) => {
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' });
+ const creation = await orkas.invoke<any>('conversations.create', { title: 'Cloud example', assistance: { kind: 'app_creation', appType: 'web' } });
+ const cloud = orkas.createWorkspaceFile('icon-cloud/index.html', '<h1>Cloud</h1>');
+ await orkas.invoke('savedApps.saveFromPath', { path: cloud, title: 'Cloud example', cid: creation.conversation.conversation_id });
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);
+ await expect(page.locator('.app-card')).toHaveCount(2);
+ await expect(page.locator('.app-card-icon svg.is-layout-grid')).toHaveCount(2);
+ await expect(page.locator('.app-card-published')).toHaveCount(0);
+ await page.locator('#apps-grid').screenshot({ path: testInfo.outputPath('cloud-icons.png') });
});
/** Mono 8-bit PCM WAV whose sample bytes vary, so a shifted or truncated byte
@@ -770,10 +676,26 @@ test('saving an artifact shows exactly one confirmation toast and no dialog', as
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 });
+ const original=(await orkas.invoke<any>('savedApps.list')).apps[0].id;
+ const preview=await orkas.openPreview(()=>page.evaluate(input=>(window as any).openChatArtifactViewer(input),{cid,artifactId:result.artifactId,title:result.title}));
+ await expect(preview.locator('.chat-artifact-viewer-save')).toHaveAttribute('title','Update original app');
+ await expect(preview.locator('.chat-artifact-viewer-save-new')).toBeVisible();
+ await preview.locator('.chat-artifact-viewer-save-new').click();
+ await expect.poll(async()=>(await orkas.invoke<any>('savedApps.list')).apps.length).toBe(2);
+ const copy=(await orkas.invoke<any>('savedApps.list')).apps.find((app:any)=>app.id!==original).id;
+ writeFileSync(path.join(orkas.workspaceRoot,'account-e2e/cloud/chat_artifacts',cid,result.artifactId,'index.html'),'<h1>Updated artifact copy</h1>');
+ await expect(preview.locator('.chat-artifact-viewer-save')).toBeEnabled();
+ await preview.locator('.chat-artifact-viewer-save').click();
+ await expect(preview.locator('.chat-artifact-viewer-save')).toBeEnabled();
+ expect((await orkas.invoke<any>('savedApps.list')).apps).toHaveLength(2);
+ const root=path.join(orkas.workspaceRoot,'account-e2e/cloud/saved_apps');
+ expect(readFileSync(path.join(root,original,'index.html'),'utf8')).toContain('Saved artifact');
+ expect(readFileSync(path.join(root,copy,'index.html'),'utf8')).toContain('Updated artifact copy');
+ await orkas.closePreview(preview);
});
// UI review captures (zh, default window unless named -390): saved time, local delete
-// confirmation without a publication, and the create dialog type choice.
+// confirmation without a publication, and the unified create dialog.
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);
@@ -816,14 +738,165 @@ test('reads saved time, local delete confirmation and the create dialog in Chine
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 expect(panel.locator('[data-app-type]')).toHaveCount(0);
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 });
+ // The narrow dialog scrolls; its actions must remain reachable there.
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);
});
+
+test('file preview saves once, updates that app, saves an independent copy and remembers the copy after reopening', async ({ orkas }, testInfo) => {
+ const page=orkas.page!;
+ const entry=orkas.createWorkspaceFile('save-target/index.html','<h1>First version</h1>');
+ const open=()=>orkas.openPreview(()=>page.evaluate(file=>(window as any).openChatFileViewer(file,'index.html'),entry));
+ let preview=await open();
+ const primary=()=>preview.locator('.chat-file-viewer-save-app');
+ await expect(primary()).toHaveAttribute('title','Save as app');
+ await expect(preview.locator('.chat-file-viewer-save-new-app')).toBeHidden();
+ await primary().click();
+ await expect(primary()).toHaveAttribute('title','Update original app');
+ let apps=(await orkas.invoke<any>('savedApps.list')).apps;
+ expect(apps).toHaveLength(1);const original=apps[0].id;
+ await primary().click();
+ await expect(primary()).toBeEnabled();
+ expect((await orkas.invoke<any>('savedApps.list')).apps.map((app:any)=>app.id)).toEqual([original]);
+ await preview.locator('.chat-file-viewer-save-new-app').click();
+ await expect(primary()).toBeEnabled();
+ apps=(await orkas.invoke<any>('savedApps.list')).apps;expect(apps).toHaveLength(2);
+ const copy=apps.find((app:any)=>app.id!==original).id;
+ await preview.screenshot({path:testInfo.outputPath('file-update-and-copy.png')});
+ await orkas.closePreview(preview);
+ writeFileSync(entry,'<h1>Second version</h1>');
+ preview=await open();
+ await expect(primary()).toHaveAttribute('title','Update original app');
+ await primary().click();await expect(primary()).toBeEnabled();
+ const root=path.join(orkas.workspaceRoot,'account-e2e/cloud/saved_apps');
+ expect(readFileSync(path.join(root,original,'index.html'),'utf8')).toContain('First version');
+ expect(readFileSync(path.join(root,copy,'index.html'),'utf8')).toContain('Second version');
+ expect((await orkas.invoke<any>('savedApps.list')).apps).toHaveLength(2);
+ await orkas.closePreview(preview);
+ // A deleted copy must not redirect the source back to the untouched original.
+ expect((await orkas.invoke<any>('savedApps.delete',{appId:copy})).ok).toBe(true);
+ preview=await open();
+ await expect(primary()).toHaveAttribute('title','Save as app');
+ await expect(preview.locator('.chat-file-viewer-save-new-app')).toBeHidden();
+ await primary().click();
+ await expect(primary()).toHaveAttribute('title','Update original app');
+ apps=(await orkas.invoke<any>('savedApps.list')).apps;
+ expect(apps).toHaveLength(2);
+ const recreated=apps.find((app:any)=>app.id!==original).id;
+ expect(recreated).not.toBe(copy);
+ expect(readFileSync(path.join(root,original,'index.html'),'utf8')).toContain('First version');
+ expect(readFileSync(path.join(root,recreated,'index.html'),'utf8')).toContain('Second version');
+ await orkas.closePreview(preview);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('file preview exports, cancels and confirms incompatible data recovery in English and Chinese',async({orkas},testInfo)=>{
+ const entry=orkas.createWorkspaceFile('file-recovery/index.html','<h1>Original notes</h1>');
+ const definition={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]};
+ const manifest=orkas.createWorkspaceFile('file-recovery/orkas-app.json',JSON.stringify({sdkVersion:1,capabilities:['data'],data:definition}));
+ const app=await orkas.invoke<any>('savedApps.saveFromPath',{path:entry});expect(app.ok).toBe(true);
+ const exported=path.join(orkas.workspaceRoot,'file-recovery-export.sqlite');
+ const file=await orkas.electronApp!.evaluate(async({dialog},input)=>{
+ const main=(process as any).mainModule,{LocalAppData}=main.require(input.data),paths=main.require(input.paths),crypto=main.require('node:crypto');
+ const key=crypto.createHash('sha256').update(JSON.stringify(['saved',input.id])).digest('hex');
+ const file=paths.webAppSandboxRoot('account-e2e',key,'local')+'/data.sqlite';
+ const db=new LocalAppData(file,paths.userLocalRoot('account-e2e'),input.definition);
+ try{await db.call('data.insert',{table:'notes',values:{body:'KEEP'}});}finally{await db.close();}
+ (dialog as any).showSaveDialog=async()=>({canceled:false,filePath:input.exported});return file;
+ },{id:app.id,definition,exported,data:path.resolve('src/main/features/web_apps/data.ts'),paths:path.resolve('src/main/paths.ts')});
+ const inspect=(file:string,data:any,method='data.query')=>orkas.electronApp!.evaluate(async(_electron,input)=>{
+ const {LocalAppData}=(process as any).mainModule.require(input.module),db=new LocalAppData(input.file,input.boundary,input.data);
+ try{return await db.call(input.method,input.method==='data.query'?{table:'notes'}:{});}finally{await db.close();}
+ },{file,data,method,boundary:orkas.workspaceRoot,module:path.resolve('src/main/features/web_apps/data.ts')});
+ writeFileSync(entry,'<h1>Updated notes</h1>');const changed={version:1,tables:[]};
+ writeFileSync(manifest,JSON.stringify({sdkVersion:1,capabilities:['data'],data:changed}));
+ const preview=await orkas.openPreview(()=>orkas.page.evaluate(file=>(window as any).openChatFileViewer(file,'index.html'),entry));
+ const savedEntry=path.join(orkas.workspaceRoot,'account-e2e/cloud/saved_apps',app.id,'index.html');
+ for(const [language,width,height] of [['en',560,600],['zh',1080,720]] 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.locator('.ui-dialog-overlay:visible');
+ await expect(dialog).toContainText('notes: 1 (body)');
+ await dialog.locator(`[data-act="${language==='en'?'ok':'cancel'}"]`).click();
+ await expect(dialog).toContainText(language==='en'?'Clear all local records':'清空');
+ expect(await dialog.evaluate(el=>el.scrollWidth<=el.clientWidth)).toBe(true);
+ await preview.screenshot({path:testInfo.outputPath(`file-recovery-${language}.png`)});
+ await dialog.locator('[data-act="cancel"]').click();
+ expect(await inspect(file,definition)).toEqual({records:[{body:'KEEP'}]});
+ expect(readFileSync(savedEntry,'utf8')).toContain('Original notes');
+ await expect(preview.locator('.chat-file-viewer-save-app')).toBeVisible();
+ }
+ expect(await inspect(exported,definition)).toEqual({records:[{body:'KEEP'}]});
+ await preview.locator('.chat-file-viewer-save-app').click();
+ await preview.locator('.ui-dialog-overlay:visible [data-act="cancel"]').click();
+ await preview.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();
+ await expect.poll(()=>readFileSync(savedEntry,'utf8')).toContain('Updated notes');
+ expect(await inspect(file,changed,'internal.inspect')).toMatchObject({records:0});
+ expect((await orkas.invoke<any>('savedApps.list')).apps.map((item:any)=>item.id)).toEqual([app.id]);
+ expect(orkas.modelRequests).toHaveLength(0);
+});
+
+for(const manifest of [false,true])test(`legacy local app opens and reopens without changing metadata (manifest: ${manifest})`,async({orkas},testInfo)=>{
+ const entry=orkas.createWorkspaceFile('legacy-open/index.html','<!doctype html><html><body><h1>Legacy link app</h1><a href="https://legacy-app.example.invalid/">Website</a><output></output><script>const count=Number(localStorage.getItem("opens")||0)+1;localStorage.setItem("opens",String(count));document.querySelector("output").textContent=String(count);</script></body></html>');
+ if(manifest)orkas.createWorkspaceFile('legacy-open/orkas-app.json',JSON.stringify({sdkVersion:1,capabilities:[]}));
+ const app=await orkas.invoke<any>('savedApps.saveFromPath',{path:entry,title:'Legacy link app'});expect(app.ok).toBe(true);
+ const metaFile=path.join(orkas.workspaceRoot,'account-e2e/cloud/saved_apps',app.id,'__orkas-meta.json');
+ const meta=JSON.parse(readFileSync(metaFile,'utf8'));delete meta.appType;delete meta.browserStorage;
+ const before=JSON.stringify(meta);writeFileSync(metaFile,before);
+ await openSidebarEntry(orkas.page,'#apps-btn');
+ const card=orkas.page.locator(`.app-card[data-app-id="${app.id}"]`);await expect(card).toBeVisible();
+ for(let count=1;count<=2;count++){
+ const preview=await orkas.openPreview(()=>card.click());
+ await expect(preview.locator('.ui-dialog-overlay:visible')).toHaveCount(0);
+ const frame=preview.frameLocator('.saved-app-viewer-frame');
+ await expect(frame.locator('h1')).toHaveText('Legacy link app');
+ // SDK instances have ephemeral origins; legacy browser-only pages keep theirs.
+ await expect(frame.locator('output')).toHaveText(String(manifest?1:count));
+ expect(await frame.locator('body').evaluate(()=>typeof (window as any).orkas)).toBe('undefined');
+ if(count===1)await preview.screenshot({path:testInfo.outputPath('legacy-local-open.png')});
+ await preview.route('https://legacy-app.example.invalid/',route=>route.fulfill({contentType:'text/html',body:'<h1>Website loaded</h1>'}));
+ await frame.getByRole('link',{name:'Website'}).click();
+ await expect(frame.locator('h1')).toHaveText('Website loaded');
+ expect(await frame.locator('body').evaluate(()=>typeof (window as any).orkas)).toBe('undefined');
+ if(count===1)await preview.screenshot({path:testInfo.outputPath('legacy-url-open.png')});
+ await orkas.closePreview(preview);
+ }
+ expect(readFileSync(metaFile,'utf8')).toBe(before);expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('publication guidance preserves the app and direct publication refuses without changes', async ({ orkas }, testInfo) => {
+ const entry = orkas.createWorkspaceFile('publication-boundary/index.html', '<h1>Keep locally available</h1>');
+ const saved = await orkas.invoke<any>('savedApps.saveFromPath', { path: entry, title: 'Long app title kept while publishing requires the commercial version' });
+ expect(saved.ok).toBe(true);
+ const metadata = path.join(orkas.workspaceRoot, 'account-e2e/cloud/saved_apps', saved.id, '__orkas-meta.json');
+ const before = readFileSync(metadata, 'utf8');
+ for (const channel of ['appPublishing.prepare', 'appPublishing.publish', 'appPublishing.recover', 'appPublishing.unpublish']) {
+ expect(await orkas.invoke(channel, { appId: saved.id, snapshot: 'synthetic' }))
+ .toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
+ }
+ const page = orkas.page!;
+ await openSidebarEntry(page, '#apps-btn');
+ for (const [language, width] of [['en', 1133], ['zh', 560]] as const) {
+ await page.evaluate(language => (window as any).setLang(language), language);
+ await page.setViewportSize({width,height:720});
+ const card = page.locator(`.app-card[data-app-id="${saved.id}"]`);
+ await card.hover();
+ await card.locator('[data-app-more]').click();
+ await page.locator('.app-row-menu [data-action="publish"]').click();
+ const dialog = page.locator('.ui-dialog-overlay.open');
+ await expect(dialog).toContainText(language === 'zh' ? '发布' : 'publish', {ignoreCase:true});
+ expect(await dialog.evaluate(el => el.scrollWidth <= el.clientWidth)).toBe(true);
+ await dialog.screenshot({path:testInfo.outputPath(`publication-guidance-${language}-${width}.png`)});
+ await dialog.locator('[data-act="cancel"]').click();
+ await expect(card).toBeVisible();
+ await expect(card.locator('[data-app-more]')).toBeFocused();
+ expect(readFileSync(metadata, 'utf8')).toBe(before);
+ }
+ 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
index 07ce9e25..e93754e8 100644
--- a/test/e2e/web_app_permissions_e2e_usage.spec.ts
+++ b/test/e2e/web_app_permissions_e2e_usage.spec.ts
@@ -44,7 +44,10 @@ test('app approval uses Orkas UI, lasts for this use, isolates windows and honor
};</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'});
+ const second: any = await orkas.invoke('savedApps.saveFromPath', {path:entry,title:'Usage two',mode:'new'});
+ expect(first.ok).toBe(true);
+ expect(second.ok).toBe(true);
+ expect(second.id).not.toBe(first.id);
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);
diff --git a/test/e2e/web_app_sdk_e2e_lifecycle.spec.ts b/test/e2e/web_app_sdk_e2e_lifecycle.spec.ts
index 1d15f758..6403b1d8 100644
--- a/test/e2e/web_app_sdk_e2e_lifecycle.spec.ts
+++ b/test/e2e/web_app_sdk_e2e_lifecycle.spec.ts
@@ -1,17 +1,83 @@
import path from 'node:path';
+import { writeFileSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
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);
+test('web app common data survives closing and reopening while host inference remains unavailable',async({orkas},testInfo)=>{
+ const definition={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body'],count:true}}]};
+ const app=await orkas.electronApp!.evaluate(async(_electron,input)=>{
+ const main=(process as any).mainModule,artifacts=main.require(input.artifacts),saved=main.require(input.saved),chats=main.require(input.chats);const task=await chats.createConversation('account-e2e',{title:'Cloud data'});
+ const result=await artifacts.createArtifact('account-e2e',task.conversation_id,'helper',{appType:'web',files:[{path:'index.html',content:'<!doctype html><html><head><script src="/__orkas/sdk.js"></script></head><body><h1>Cloud notes</h1><input aria-label="Note"><button id="save">Save note</button><output></output><script>const refresh=async()=>{const value=await orkasApp.data.query({table:"notes"});document.querySelector("output").textContent=value.records.map(record=>record.body).join(";")||"Empty";};document.getElementById("save").onclick=async()=>{await orkasApp.data.insert({table:"notes",values:{body:document.querySelector("input").value}});await refresh();};refresh();</script></body></html>'},{path:'orkas-app.json',content:JSON.stringify({sdkVersion:1,capabilities:['data'],data:input.definition})}]});if(!result.ok)throw new Error(result.error);return saved.saveFromArtifact('account-e2e',task.conversation_id,result.artifactId);
+ },{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'),definition});
+ if(!app.ok)throw new Error(app.error);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.locator('output')).toHaveText('Empty');await frame.getByLabel('Note').fill('Retained locally');await frame.getByRole('button',{name:'Save note'}).click();await expect(frame.locator('output')).toHaveText('Retained locally');
+ expect(await frame.locator('body').evaluate(()=>(window as any).orkasApp.ai)).toBeUndefined();await orkas.closePreview(preview);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.locator('output')).toHaveText('Retained locally');await preview.screenshot({path:testInfo.outputPath('cloud-local-data.png')});expect(orkas.modelRequests).toHaveLength(0);
+});
+
+test('a closed saved app retains its records after a compatible update and process restart', async ({ orkas }, testInfo) => {
+ const definition = { version: 1, tables: [{ id: 'loans', name: 'loans', fields: [
+ { id: 'borrower', name: 'borrower', type: 'string' },
+ { id: 'item', name: 'item', type: 'string' },
+ ], access: { read: ['borrower', 'item'], insert: ['borrower', 'item'] } }] };
+ const html = (revision: number) => `<!doctype html><html><head><script src="/__orkas/sdk.js"></script></head><body>
+ <h1>Loan register ${revision}</h1><label>Borrower <input id="borrower"></label><label>Item <input id="item"></label>
+ <button id="save">Record loan</button><output></output><script>
+ const refresh=async()=>{const result=await orkasApp.data.query({table:'loans'});
+ document.querySelector('output').textContent=JSON.stringify(result.records);};
+ document.getElementById('save').onclick=async()=>{await orkasApp.data.insert({table:'loans',values:{
+ borrower:document.getElementById('borrower').value,item:document.getElementById('item').value}});await refresh();};
+ refresh();</script></body></html>`;
+ const entry = orkas.createWorkspaceFile('loans/index.html', html(1));
+ orkas.createWorkspaceFile('loans/orkas-app.json', JSON.stringify({ sdkVersion: 1, capabilities: ['data'], data: definition }));
+ const app: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, title: 'Loan register', mode: 'auto' });
+ expect(app.ok).toBe(true);
+ const row = { borrower: `Borrower ${randomUUID()}`, item: 'Radio 7' };
+ 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 frame.getByLabel('Borrower').fill(row.borrower);
+ await frame.getByLabel('Item', { exact: true }).fill(row.item);
+ await frame.getByRole('button', { name: 'Record loan' }).click();
+ await expect(frame.locator('output')).toHaveText(JSON.stringify([row]));
+ await orkas.closePreview(preview);
+ writeFileSync(entry, html(2));
+ const updated: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, mode: 'auto' });
+ expect(updated).toMatchObject({ ok: true, id: app.id });
+ await orkas.relaunch();
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const listed: any = await orkas.invoke('savedApps.list');
+ expect(listed.apps.map((value: any) => value.id)).toEqual([app.id]);
+ 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('heading')).toHaveText('Loan register 2');
+ await expect(frame.locator('output')).toHaveText(JSON.stringify([row]));
+ const heading = await frame.getByRole('heading').innerText();
+ const visible = JSON.parse((await frame.locator('output').textContent())!);
+ await orkas.closePreview(preview);
+ const persisted = await orkas.electronApp!.evaluate(async (_electron, input) => {
+ const main = (process as any).mainModule, { LocalAppData } = main.require(input.module);
+ const paths = main.require(input.paths), crypto = main.require('node:crypto');
+ const key = crypto.createHash('sha256').update(JSON.stringify(['saved', input.id])).digest('hex');
+ const database = new LocalAppData(paths.webAppSandboxRoot('account-e2e', key, 'local') + '/data.sqlite',
+ paths.userLocalRoot('account-e2e'), input.definition);
+ try { return await database.call('data.query', { table: 'loans' }); }
+ finally { await database.close(); }
+ }, { id: app.id, definition, module: path.resolve('src/main/features/web_apps/data.ts'), paths: path.resolve('src/main/paths.ts') });
+ expect(persisted).toEqual({ records: [row] });
+ // A success-looking rendered row alone must not hide skipped writes,
+ // duplicate side effects, or stale code at this same consumer boundary.
+ const correct = { ids: listed.apps.map((value: any) => value.id), heading, records: persisted.records, visible };
+ const accepts = (value: typeof correct) => value.ids.length === 1 && value.ids[0] === app.id && value.heading === 'Loan register 2'
+ && JSON.stringify(value.records) === JSON.stringify([row]) && JSON.stringify(value.visible) === JSON.stringify([row]);
+ expect(accepts(correct)).toBe(true);
+ const controls = [
+ { name: 'correct', expected: true, value: correct },
+ { name: 'false-success-without-persisted-record', expected: false, value: { ...correct, records: [] } },
+ { name: 'duplicate-effect', expected: false, value: { ...correct, records: [row, row] } },
+ { name: 'stale-consumer', expected: false, value: { ...correct, heading: 'Loan register 1' } },
+ ].map(({ name, expected, value }) => ({ name, expected, accepted: accepts(value) }));
+ expect(controls.every(control => control.expected === control.accepted)).toBe(true);
+ await testInfo.attach('native-record-controls', { body: JSON.stringify(controls), contentType: 'application/json' });
expect(orkas.modelRequests).toHaveLength(0);
});
@@ -189,6 +255,39 @@ test('local pages, reload and rejected navigation preserve the app SDK', async (
expect(orkas.modelRequests).toHaveLength(0);
});
+test('a same-length source edit revokes the live SDK and protocol while reopening preserves saved data', async ({ orkas }) => {
+ const entry = orkas.createWorkspaceFile('revision/index.html', '<!doctype html><h1>Revision before</h1><script src="/__orkas/sdk.js"></script>');
+ orkas.createWorkspaceFile('revision/orkas-app.json', JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }));
+ const app: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, title: 'Source revision' });
+ await openSidebarEntry(orkas.page, '#apps-btn');
+ const open = () => orkas.openPreview(() => orkas.page.locator(`.app-card[data-app-id="${app.id}"]`).click());
+ const preview = await open();
+ const frame = preview.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(frame.getByRole('heading')).toHaveText('Revision before');
+ expect(await frame.locator('body').evaluate(() => (window as any).orkasApp.storage.set({ key: 'value', value: 'KEEP' }))).toEqual({ saved: true });
+ const mutation = await orkas.electronApp!.evaluate((_electron, input) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const fs = req('node:fs'), saved = req(input.module);
+ const file = saved.resolveSavedAppFilePath('account-e2e', input.id, 'index.html');
+ if (!file.ok) throw new Error('Source fixture is unavailable');
+ const before = fs.readFileSync(file.absPath, 'utf8'), after = before.replace('Revision before', 'Revision after!');
+ fs.writeFileSync(file.absPath, after);
+ return { changed: before !== after, sameLength: Buffer.byteLength(before) === Buffer.byteLength(after) };
+ }, { module: path.resolve('src/main/features/saved_apps.ts'), id: app.id });
+ expect(mutation).toEqual({ changed: true, sameLength: true });
+ expect(await frame.locator('body').evaluate(async () => {
+ try { await (window as any).orkasApp.storage.set({ key: 'value', value: 'WRONG' }); return 'unexpected-success'; }
+ catch (error: any) { return error.code; }
+ })).toBe('E_CLOSED');
+ expect(await frame.locator('body').evaluate(async () => (await fetch(location.href)).status)).toBe(403);
+ await preview.close();
+ const reopened = await open();
+ const fresh = reopened.locator('.saved-app-viewer-frame').contentFrame();
+ await expect(fresh.getByRole('heading')).toHaveText('Revision after!');
+ expect(await fresh.locator('body').evaluate(() => (window as any).orkasApp.storage.get({ key: 'value' }))).toEqual({ value: 'KEEP' });
+ 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');
diff --git a/test/e2e/web_app_sdk_e2e_runtime.spec.ts b/test/e2e/web_app_sdk_e2e_runtime.spec.ts
index c7d30bb9..69e43a3e 100644
--- a/test/e2e/web_app_sdk_e2e_runtime.spec.ts
+++ b/test/e2e/web_app_sdk_e2e_runtime.spec.ts
@@ -709,7 +709,7 @@ test('new ordinary apps isolate browser data across objects and accounts while r
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 });
+ const app: any = await orkas.invoke('savedApps.saveFromPath', { path: entry, title, mode: 'new' });
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');
@@ -851,7 +851,7 @@ test('historical web artifacts cannot submit conversation tasks with a forged lo
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, 'index.html'), '<h1>Historical browser app</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);
@@ -859,12 +859,15 @@ test('historical web artifacts cannot submit conversation tasks with a forged lo
(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 expect(iframe.contentFrame().locator('body')).toContainText('Historical browser app');
+ await expect(iframe).toHaveAttribute('src', /^chat-app:/);
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' });
+ const reopened: any = await orkas.invoke('webApps.open', { source: { cid, artifactId } });
+ expect(reopened).toMatchObject({ ok: true, token: expect.any(String) });
+ expect(await orkas.invoke('webApps.canSubmitArtifact', { token: reopened.token })).toMatchObject({ ok: true, allowed: false });
+ await orkas.invoke('webApps.close', { token: reopened.token });
expect(await orkas.page.evaluate(() => (window as any).unexpectedSubmissions)).toBe(0);
expect(orkas.modelRequests).toHaveLength(0);
});
diff --git a/test/main/features/bundle-revision.test.ts b/test/main/features/bundle-revision.test.ts
new file mode 100644
index 00000000..bdca5105
--- /dev/null
+++ b/test/main/features/bundle-revision.test.ts
@@ -0,0 +1,102 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { bundleRevision } from '../../../src/main/features/web_apps/bundle-revision';
+import { freezeFileMetadata } from '../../helpers/frozen-file-metadata';
+
+let root: string, entry: string;
+let restoreMetadata: (() => void) | undefined;
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-bundle-revision-'));
+ entry = path.join(root, 'index.html');
+ fs.writeFileSync(entry, '<h1>Before</h1>');
+});
+afterEach(() => { restoreMetadata?.(); restoreMetadata = undefined; fs.rmSync(root, { recursive: true, force: true }); });
+
+describe('application source revision', () => {
+ it('rejects a same-length edit even when every filesystem metadata field is unchanged, and stays revoked after restoration', async () => {
+ restoreMetadata = freezeFileMetadata([entry]);
+ const revision = await bundleRevision(root, [entry]);
+ expect(await revision.valid()).toBe(true);
+ fs.writeFileSync(entry, '<h1>After!</h1>');
+ expect(fs.readFileSync(entry, 'utf8')).toBe('<h1>After!</h1>');
+ expect(await revision.valid()).toBe(false);
+ fs.writeFileSync(entry, '<h1>Before</h1>');
+ expect(await revision.valid()).toBe(false);
+ expect(revision.accept(entry)).toBe(false);
+ });
+
+ it('checks a newly requested asset against its launch contents before it can be served', async () => {
+ const asset = path.join(root, 'script.js');
+ fs.writeFileSync(asset, 'window.value=1;');
+ restoreMetadata = freezeFileMetadata([entry, asset]);
+ const revision = await bundleRevision(root, [entry]);
+ expect(await revision.valid()).toBe(true);
+ fs.writeFileSync(asset, 'window.value=2;');
+ revision.accept(asset);
+ expect(await revision.valid()).toBe(false);
+ });
+
+ it('allows unchanged source and declared assets but rejects additions and deletion', async () => {
+ const asset = path.join(root, 'style.css'); fs.writeFileSync(asset, 'body{}');
+ const revision = await bundleRevision(root, [entry]);
+ expect(revision.accept(asset)).toBe(true);
+ expect(await revision.valid()).toBe(true);
+ const added = path.join(root, 'late.js'); fs.writeFileSync(added, 'late');
+ expect(revision.accept(added)).toBe(false);
+ expect(await revision.valid()).toBe(false);
+ const reopened = await bundleRevision(root, [entry]);
+ fs.unlinkSync(entry);
+ expect(await reopened.valid()).toBe(false);
+ });
+
+ it('binds already parsed authority bytes and does not poison an unchanged revision when a queued check is cancelled', async () => {
+ restoreMetadata = freezeFileMetadata([entry]);
+ fs.writeFileSync(entry, '<h1>After!</h1>');
+ await expect(bundleRevision(root, [entry], new Map([[entry, Buffer.from('<h1>Before</h1>')]])))
+ .rejects.toThrow('bundle changed during launch');
+ const revision = await bundleRevision(root, [entry]);
+ const controller = new AbortController(); controller.abort();
+ expect(await revision.valid(controller.signal)).toBe(false);
+ expect(await revision.valid()).toBe(true);
+ });
+
+ it('does not reuse a check that began before a later caller changed the source', async () => {
+ let entered!: () => void, release!: () => void;
+ const closing = new Promise<void>(resolve => { entered = resolve; });
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let holdNext = false;
+ restoreMetadata = freezeFileMetadata([entry], async file => {
+ if (file === entry && holdNext) {
+ holdNext = false; entered(); await gate;
+ }
+ });
+ const revision = await bundleRevision(root, [entry]);
+ holdNext = true;
+ let first: Promise<boolean> | undefined, second: Promise<boolean> | undefined;
+ try {
+ first = revision.valid(); await closing;
+ fs.writeFileSync(entry, '<h1>After!</h1>');
+ second = revision.valid(); release();
+ await first;
+ expect(await second).toBe(false);
+ expect(await revision.valid()).toBe(false);
+ } finally { release(); await Promise.allSettled([first, second]); }
+ });
+
+ it('reads the end of a large source asynchronously without accepting unchanged metadata as content proof', async () => {
+ const bytes = Buffer.alloc(8 * 1024 * 1024, 65); fs.writeFileSync(entry, bytes);
+ restoreMetadata = freezeFileMetadata([entry]);
+ const revision = await bundleRevision(root, [entry]);
+ const file = fs.openSync(entry, 'r+');
+ try { fs.writeSync(file, Buffer.from('B'), 0, 1, bytes.length - 1); }
+ finally { fs.closeSync(file); }
+ let yielded = false;
+ const heartbeat = new Promise<void>(resolve => setImmediate(() => { yielded = true; resolve(); }));
+ const valid = await revision.valid();
+ expect(yielded).toBe(true);
+ expect(valid).toBe(false);
+ await heartbeat;
+ });
+});
diff --git a/test/main/features/chat-artifact-revisions.test.ts b/test/main/features/chat-artifact-revisions.test.ts
new file mode 100644
index 00000000..56a00f82
--- /dev/null
+++ b/test/main/features/chat-artifact-revisions.test.ts
@@ -0,0 +1,87 @@
+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';
+
+vi.mock('../../../src/main/logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) }));
+const uid = 'revision-user', cid = 'revision-chat', agent = 'builder';
+let root: string, previous: string | undefined;
+beforeEach(async () => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-art-revision-'));
+ previous = process.env.ORKAS_WORKSPACE_ROOT; process.env.ORKAS_WORKSPACE_ROOT = root;
+ vi.resetModules();
+ (await import('../../../src/main/features/users')).activateUser(uid);
+});
+afterEach(() => { process.env.ORKAS_WORKSPACE_ROOT = previous; fs.rmSync(root, { recursive: true, force: true }); });
+const files = (body: string) => [{ path: 'index.html', content: `<!doctype html><button>${body}</button>` }];
+const directory = (id: string) => path.join(root, uid, 'cloud/chat_artifacts', cid, id);
+
+it.each(['local', 'web'] as const)('corrects a %s app without changing its identity, type, title or save destination', async appType => {
+ const m = await import('../../../src/main/features/chat_artifacts');
+ const saved = await import('../../../src/main/features/saved_apps');
+ const first = await m.createArtifact(uid, cid, agent, { title: 'Chat', appType, files: files('Draft') });
+ if (!first.ok) throw new Error(first.error);
+ const kept = await saved.saveFromArtifact(uid, cid, first.artifactId);
+ if (!kept.ok) throw new Error(kept.error);
+ const before = m.readArtifactMeta(uid, cid, first.artifactId)!;
+ const corrected = await m.createArtifact(uid, cid, agent, { artifactId: first.artifactId, files: files('Corrected') } as any);
+ expect(corrected).toMatchObject({ ok: true, artifactId: first.artifactId, revision: 2 });
+ expect(fs.readdirSync(path.dirname(directory(first.artifactId)))).toEqual([first.artifactId]);
+ expect(fs.readFileSync(path.join(directory(first.artifactId), 'index.html'), 'utf8')).toContain('Corrected');
+ expect(m.readArtifactMeta(uid, cid, first.artifactId)).toMatchObject({ ...before, revision: 2 });
+ const savedDir = path.join(root, uid, 'cloud/saved_apps', kept.id);
+ expect(fs.readFileSync(path.join(savedDir, 'index.html'), 'utf8')).toContain('Draft');
+ expect(await saved.saveFromArtifact(uid, cid, first.artifactId, 'auto')).toMatchObject({ ok: true, id: kept.id });
+ expect(fs.readFileSync(path.join(savedDir, 'index.html'), 'utf8')).toContain('Corrected');
+});
+
+it('keeps intentionally separate apps independent even when titles match', async () => {
+ const m = await import('../../../src/main/features/chat_artifacts');
+ const a = await m.createArtifact(uid, cid, agent, { title: 'Chat', files: files('One') });
+ const b = await m.createArtifact(uid, cid, agent, { title: 'Chat', files: files('Two') });
+ if (!a.ok || !b.ok) throw new Error('fixture creation failed');
+ expect(a.artifactId).not.toBe(b.artifactId);
+ expect(fs.readdirSync(path.dirname(directory(a.artifactId)))).toHaveLength(2);
+});
+
+it('rejects foreign, missing and malformed revision targets and type conversion without creating or changing an app', async () => {
+ const m = await import('../../../src/main/features/chat_artifacts');
+ const first = await m.createArtifact(uid, cid, agent, { files: files('Keep') });
+ if (!first.ok) throw new Error(first.error);
+ for (const [user, chat, actor, id, extra] of [
+ [uid, cid, 'other', first.artifactId, {}], [uid, 'other', agent, first.artifactId, {}],
+ ['other', cid, agent, first.artifactId, {}], [uid, cid, agent, 'missing', {}],
+ [uid, cid, agent, '../escape', {}], [uid, cid, agent, '', {}],
+ [uid, cid, agent, first.artifactId, { appType: 'web' }],
+ ] as const) {
+ expect(await m.createArtifact(user, chat, actor, { artifactId: id, files: files('Wrong'), ...extra } as any)).toMatchObject({ ok: false });
+ }
+ expect(fs.readFileSync(path.join(directory(first.artifactId), 'index.html'), 'utf8')).toContain('Keep');
+ expect(fs.readdirSync(path.dirname(directory(first.artifactId)))).toEqual([first.artifactId]);
+});
+
+it('retains the prior app when staging finalization fails and permits an explicit correction afterward', async () => {
+ const m = await import('../../../src/main/features/chat_artifacts');
+ const first = await m.createArtifact(uid, cid, agent, { files: files('Keep') });
+ if (!first.ok) throw new Error(first.error);
+ const input = { artifactId: first.artifactId, files: files('Fixed') };
+ const failed = await (m.createArtifact as any)(uid, cid, agent, input, async () => { throw new Error('fixture finalization failure'); });
+ expect(failed).toMatchObject({ ok: false });
+ expect(fs.readFileSync(path.join(directory(first.artifactId), 'index.html'), 'utf8')).toContain('Keep');
+ expect(await m.createArtifact(uid, cid, agent, input as any)).toMatchObject({ ok: true, artifactId: first.artifactId, revision: 2 });
+});
+
+it('does not activate a staged correction after a competing correction changed the original', async () => {
+ const m = await import('../../../src/main/features/chat_artifacts');
+ const first = await m.createArtifact(uid, cid, agent, { files: files('Keep') });
+ if (!first.ok) throw new Error(first.error);
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let staged = false;
+ const slow = (m.createArtifact as any)(uid, cid, agent, { artifactId: first.artifactId, files: files('Stale') }, async () => { staged = true; await gate; });
+ await vi.waitFor(() => expect(staged).toBe(true));
+ expect(await m.createArtifact(uid, cid, agent, { artifactId: first.artifactId, files: files('Latest') } as any)).toMatchObject({ ok: true });
+ release(); expect(await slow).toMatchObject({ ok: false });
+ expect(fs.readFileSync(path.join(directory(first.artifactId), 'index.html'), 'utf8')).toContain('Latest');
+ expect(fs.readdirSync(path.dirname(directory(first.artifactId)))).toEqual([first.artifactId]);
+});
diff --git a/test/main/features/chat_artifacts.test.ts b/test/main/features/chat_artifacts.test.ts
index 60cc7233..53207204 100644
--- a/test/main/features/chat_artifacts.test.ts
+++ b/test/main/features/chat_artifacts.test.ts
@@ -40,12 +40,12 @@ 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);
+ if(appType==='web')expect(saved.minimumClient).toBe('1.9.0');
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'});
+ expect(denied).toMatchObject({ok:false,error:'web applications cannot use host interfaces: declared local-only capabilities ai; web apps may declare only data'});
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'});
});
@@ -76,7 +76,6 @@ it.each([
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);
@@ -105,7 +104,7 @@ 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(result).toEqual({ ok: false, error: 'web applications cannot use host interfaces: declared local-only capabilities storage, ai; web apps may declare only data' });
expect(fs.existsSync(cidDir()) ? fs.readdirSync(cidDir()) : []).toEqual([]);
});
@@ -493,13 +492,7 @@ it('creates and serves the same media/model/font resources accepted by saved app
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 });
+ const 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 });
});
@@ -522,11 +515,12 @@ 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 () => {
+ it('stores the legacy cloud alias as a web application with the web declaration', 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);
+ expect(created.ok).toBe(true); if (!created.ok) return;
+ expect(m.readArtifactMeta(UID, CID, created.artifactId)?.appType).toBe('web');
+ expect(JSON.parse(fs.readFileSync(path.join(cidDir(), created.artifactId, '__orkas-meta.json'), 'utf8')).appType).toBe('web');
});
it.each([['desktop'], ['Web'], [1], [{ type: 'web' }]])('rejects unknown type %j without creating an artifact', async appType => {
@@ -537,12 +531,15 @@ describe('chat_artifacts › application type input', () => {
expect(m.listArtifacts(UID, CID)).toEqual([]);
});
- it('denies an undeclared web app and retains local auto-sizing authoring', async () => {
+ it('gives a web artifact without a declaration the empty data-only declaration and leaves its entry bytes unchanged', 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);
+ expect(created.ok).toBe(true); if (!created.ok) return;
+ const dir = path.join(cidDir(), created.artifactId);
+ expect(JSON.parse(fs.readFileSync(path.join(dir, 'orkas-app.json'), 'utf8'))).toEqual({ sdkVersion: 1, minimumClient: '1.9.0', capabilities: [] });
+ expect(fs.readFileSync(path.join(dir, 'index.html'))).toEqual(Buffer.from(html, 'utf8'));
+ // The local default keeps its auto-sizing bridge; only web skips it.
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);
diff --git a/test/main/features/saved-app-type-recovery.test.ts b/test/main/features/saved-app-type-recovery.test.ts
index 3ddcb7b2..13274474 100644
--- a/test/main/features/saved-app-type-recovery.test.ts
+++ b/test/main/features/saved-app-type-recovery.test.ts
@@ -84,7 +84,7 @@ it('rechecks the original app when an edit context loses its type and refuses da
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' });
+ .toMatchObject({ ok: false, error: 'app type must match the task or editing source' });
fs.writeFileSync(contextFile, '{ damaged');
await expect(f.saved.boundAppType(wire.uid, cid)).rejects.toMatchObject({ code: 'app_edit_context_unavailable' });
});
@@ -94,7 +94,7 @@ it('keeps a local edit on its original type and writes nothing for a conflicting
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(denied).toMatchObject({ ok: false, error: 'app type must match the task or editing source' });
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);
diff --git a/test/main/features/saved_apps.test.ts b/test/main/features/saved_apps.test.ts
index 6093a7fd..c9b25a92 100644
--- a/test/main/features/saved_apps.test.ts
+++ b/test/main/features/saved_apps.test.ts
@@ -129,15 +129,18 @@ describe('saved_apps › saveFromArtifact', () => {
} finally { loggerSpy.mockRestore(); }
});
- it('rejects destructive local schema replacement before changing the original code or records',async()=>{
+ it.each([false,true])('rejects destructive schema replacement and permits explicit recovery (existing edit task: %s)',async useEdit=>{
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 edit=useEdit?await savedApps.openForEditing(UID,saved.id):null;
+ if(edit&&!edit.ok)throw new Error(edit.error);
+ const cid=edit?.ok?(edit.conversation as any).conversation_id:CID;
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);
+ if(!useEdit)chatArtifacts.bindSavedApp(UID,cid,changed.artifactId,saved.id);
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();}
@@ -151,7 +154,7 @@ describe('saved_apps › saveFromArtifact', () => {
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([]);
+ const saved=await savedApps.saveFromPath(UID,path.join(source,'index.html'),{sourceCid:cid,fenceRoots:[tmpDir]});if(!saved.ok)throw new Error(saved.error);expect(savedApps.listSavedApps(UID).find(app=>app.id===saved.id)?.appType).toBe('web');
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()=>{
@@ -161,28 +164,31 @@ describe('saved_apps › saveFromArtifact', () => {
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);
+ if(!created.ok)throw new Error(created.error);
+ expect(chatArtifacts.readArtifactMeta(UID,cid,created.artifactId)?.appType).toBe('web');
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);
+ const created=await chatArtifacts.createArtifact(UID,CID,'helper',{appType:'web',files:[{path:'index.html',content:'<h1>Cloud</h1>'}]});
+ expect(created.ok).toBe(true);if(!created.ok)return;
+ const artifactMeta=path.join(tmpDir,UID,'cloud/chat_artifacts',CID,created.artifactId,'__orkas-meta.json');
+ fs.writeFileSync(artifactMeta,JSON.stringify({...JSON.parse(fs.readFileSync(artifactMeta,'utf8')),appType:storedType}));
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);
+ const kept=await savedApps.saveFromArtifact(UID,CID,created.artifactId);
+ expect(kept.ok).toBe(true);if(!kept.ok)return;
+ const savedMeta=path.join(APPS_ROOT(),kept.id,'__orkas-meta.json');
+ fs.writeFileSync(savedMeta,JSON.stringify({...JSON.parse(fs.readFileSync(savedMeta,'utf8')),appType:storedType}));
+ expect(savedApps.listSavedApps(UID).find(app=>app.id===kept.id)?.appType).toBe('web');
+ expect(JSON.parse(fs.readFileSync(savedMeta,'utf8')).appType).toBe(storedType);
+ const edited=await savedApps.openForEditing(UID,kept.id);
+ expect(edited.ok).toBe(true);if(!edited.ok)return;
+ const replacement=await chatArtifacts.createArtifact(UID,(edited.conversation as any).conversation_id,'helper',{files:[{path:'index.html',content:'<h1>Edited</h1>'}]});
+ expect(replacement.ok).toBe(true);if(!replacement.ok)return;
+ await savedApps.saveFromArtifact(UID,(edited.conversation as any).conversation_id,replacement.artifactId,'update');
+ expect(savedApps.listSavedApps(UID).find(app=>app.id===kept.id)?.appType).toBe('web');
+ const invalid=await chatArtifacts.createArtifact(UID,CID,'helper',{appType:'web',files:[{path:'index.html',content:'<h1>Invalid</h1>'},{path:'orkas-app.json',content:JSON.stringify({sdkVersion:1,capabilities:['ai']})}]});
+ expect(invalid.ok).toBe(false);
});
it('recovers an interrupted local replacement to the original and preserves revised binary bytes on later saves',async()=>{
const {savedApps,chatArtifacts}=await mods();
@@ -231,13 +237,54 @@ describe('saved_apps › saveFromArtifact', () => {
(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(updated).toMatchObject({ok:true,id:copy.id,title:'Revised'});
+ expect(fs.readFileSync(path.join(APPS_ROOT(),copy.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(fs.existsSync(path.join(APPS_ROOT(),copy.id,'obsolete.css'))).toBe(false);
+ expect(fs.readFileSync(path.join(APPS_ROOT(),original.id,'index.html'),'utf8')).toContain('Original');
expect(await reloaded.getEditTarget('another-account',cid)).toBeNull();
});
- it('refuses stale edit and deleted targets without destroying the newer saved application', async () => {
+ it('retains the destination binary assets when an earlier artifact updates its independently edited copy', async () => {
+ const { savedApps, chatArtifacts } = await mods();
+ const originalBytes = Buffer.from([1, 2, 3]);
+ const revisedBytes = Buffer.from([9, 8, 7]);
+ const originalArtifact = await makeArtifact('Original', [
+ { path: 'image.png', content: originalBytes.toString('base64'), encoding: 'base64' } as any,
+ ]);
+ const original = await savedApps.saveFromArtifact(UID, CID, originalArtifact);
+ 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 earlier = await chatArtifacts.createArtifact(UID, cid, 'helper', {
+ files: [{ path: 'index.html', content: '<h1>Copy</h1><img src="image.png">' }],
+ });
+ if (!earlier.ok) throw new Error(earlier.error);
+ const copy = await savedApps.saveFromArtifact(UID, cid, earlier.artifactId, 'new');
+ if (!copy.ok) throw new Error(copy.error);
+ const otherEdit = await savedApps.openForEditing(UID, copy.id);
+ if (!otherEdit.ok) throw new Error(otherEdit.error);
+ const otherCid = (otherEdit.conversation as any).conversation_id;
+ const replacement = await chatArtifacts.createArtifact(UID, otherCid, 'helper', {
+ files: [
+ { path: 'index.html', content: '<h1>Revised copy</h1><img src="image.png">' },
+ { path: 'image.png', content: revisedBytes.toString('base64'), encoding: 'base64' },
+ ],
+ });
+ if (!replacement.ok) throw new Error(replacement.error);
+ expect(await savedApps.saveFromArtifact(UID, otherCid, replacement.artifactId, 'auto'))
+ .toMatchObject({ ok: true, id: copy.id });
+ expect(fs.readFileSync(path.join(APPS_ROOT(), copy.id, 'image.png'))).toEqual(revisedBytes);
+ // The earlier card has no replacement image bytes. Its remembered copy,
+ // rather than the original task snapshot, owns the assets to retain.
+ expect(await savedApps.saveFromArtifact(UID, cid, earlier.artifactId, 'auto'))
+ .toMatchObject({ ok: true, id: copy.id });
+ expect(fs.readFileSync(path.join(APPS_ROOT(), copy.id, 'image.png'))).toEqual(revisedBytes);
+ expect(fs.readFileSync(path.join(APPS_ROOT(), original.id, 'image.png'))).toEqual(originalBytes);
+ expect(savedApps.listSavedApps(UID).map(app => app.id).sort()).toEqual([original.id, copy.id].sort());
+ });
+
+ it('overwrites the original code after another edit and saves independently after deletion', async () => {
const {savedApps,chatArtifacts}=await mods();
const original=await savedApps.saveFromArtifact(UID,CID,await makeArtifact('Original'));
if(!original.ok)throw new Error(original.error);
@@ -247,12 +294,289 @@ describe('saved_apps › saveFromArtifact', () => {
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');
+ expect(await savedApps.saveFromArtifact(UID,cid,revised.artifactId,'update')).toMatchObject({ok:true,id:original.id});
+ expect(fs.readFileSync(path.join(APPS_ROOT(),original.id,'index.html'),'utf8')).toContain('Changed');
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([]);
+ const recreated = await savedApps.saveFromArtifact(UID,cid,revised.artifactId,'update');
+ expect(recreated.ok).toBe(true);
+ if (recreated.ok) expect(recreated.id).not.toBe(original.id);
+ expect(savedApps.listSavedApps(UID)).toHaveLength(1);
+ });
+
+ it('saves a legacy artifact without host metadata and remembers its destination', async () => {
+ const {savedApps}=await mods();
+ const artifactId=await makeArtifact('Legacy');
+ fs.unlinkSync(path.join(tmpDir,UID,'cloud/chat_artifacts',CID,artifactId,'__orkas-meta.json'));
+ const saved=await savedApps.saveFromArtifact(UID,CID,artifactId,'auto');
+ expect(saved.ok).toBe(true);if(!saved.ok)return;
+ expect(await savedApps.saveFromArtifact(UID,CID,artifactId,'auto')).toMatchObject({ok:true,id:saved.id});
+ expect(savedApps.listSavedApps(UID)).toHaveLength(1);
+ });
+
+ it('remembers each artifact save across reopening and moves only that artifact to its explicit copy', async () => {
+ const {savedApps} = await mods();
+ const a = await makeArtifact('First'), b = await makeArtifact('Second');
+ const first = await savedApps.saveFromArtifact(UID,CID,a,'auto');
+ const second = await savedApps.saveFromArtifact(UID,CID,b,'auto');
+ if (!first.ok || !second.ok) throw new Error('save failed');
+ expect(first.id).not.toBe(second.id);
+ vi.resetModules();
+ (await import('../../../src/main/features/users')).activateUser(UID);
+ const reopened = await import('../../../src/main/features/saved_apps');
+ expect(await reopened.saveFromArtifact(UID,CID,a,'auto')).toMatchObject({ok:true,id:first.id});
+ const copy = await reopened.saveFromArtifact(UID,CID,a,'new');
+ if (!copy.ok) throw new Error(copy.error);
+ expect(copy.id).not.toBe(first.id);
+ expect(await reopened.saveFromArtifact(UID,CID,a,'auto')).toMatchObject({ok:true,id:copy.id});
+ expect(await reopened.saveFromArtifact(UID,CID,b,'auto')).toMatchObject({ok:true,id:second.id});
+ expect(reopened.listSavedApps(UID)).toHaveLength(3);
+ });
+
+ it('updates a saved workspace bundle through sibling files and preserves an independent copy', async () => {
+ const {savedApps} = await mods();
+ const root = path.join(tmpDir,'workspace','app');fs.mkdirSync(root,{recursive:true});
+ fs.writeFileSync(path.join(root,'index.html'),'<h1>First</h1>');fs.writeFileSync(path.join(root,'app.js'),'// first');
+ const opts = {sourceCid:CID,fenceRoots:[path.join(tmpDir,'workspace')],mode:'auto' as const};
+ const first = await savedApps.saveFromPath(UID,path.join(root,'index.html'),opts);
+ if (!first.ok) throw new Error(first.error);
+ fs.writeFileSync(path.join(root,'index.html'),'<h1>Second</h1>');
+ expect(await savedApps.saveFromPath(UID,path.join(root,'app.js'),opts)).toMatchObject({ok:true,id:first.id});
+ expect(fs.readFileSync(path.join(APPS_ROOT(),first.id,'index.html'),'utf8')).toContain('Second');
+ const copy = await savedApps.saveFromPath(UID,path.join(root,'app.js'),{...opts,mode:'new'});
+ if (!copy.ok) throw new Error(copy.error);
+ expect(copy.id).not.toBe(first.id);
+ expect(await savedApps.saveFromPath(UID,path.join(root,'index.html'),opts)).toMatchObject({ok:true,id:copy.id});
+ });
+
+ it.each(['local', 'web'] as const)(
+ 'retains the saved %s identity when another task updates the same workspace source', async originalType => {
+ const { savedApps } = await mods();
+ const chats = await import('../../../src/main/features/chats');
+ const otherType = originalType === 'web' ? 'local' : 'web';
+ const originalTask = await chats.createConversation(UID, {
+ assistance: { kind: 'app_creation', appType: originalType },
+ });
+ const otherTask = await chats.createConversation(UID, {
+ assistance: { kind: 'app_creation', appType: otherType },
+ });
+ const root = path.join(tmpDir, 'workspace', 'shared-identity');
+ fs.mkdirSync(root, { recursive: true });
+ const entry = path.join(root, 'index.html');
+ fs.writeFileSync(entry, '<h1>Original</h1>');
+ const options = { mode: 'auto' as const, fenceRoots: [path.dirname(root)] };
+ const original = await savedApps.saveFromPath(UID, entry, {
+ ...options, sourceCid: originalTask.conversation_id,
+ });
+ if (!original.ok) throw new Error(original.error);
+ expect(await savedApps.resolveSavedAppType(UID, original.id)).toBe(originalType);
+ fs.writeFileSync(entry, '<h1>Updated from another task</h1>');
+ expect(await savedApps.saveFromPath(UID, entry, {
+ ...options, sourceCid: otherTask.conversation_id,
+ })).toMatchObject({ ok: true, id: original.id });
+ expect(savedApps.listSavedApps(UID)).toMatchObject([{ id: original.id, appType: originalType }]);
+ const served = savedApps.resolveSavedAppFilePath(UID, original.id, 'index.html');
+ if (!served.ok) throw new Error(served.error);
+ expect(served.appType).toBe(originalType);
+ expect(fs.readFileSync(served.absPath, 'utf8')).toBe('<h1>Updated from another task</h1>');
+ vi.resetModules();
+ (await import('../../../src/main/features/users')).activateUser(UID);
+ const reopened = await import('../../../src/main/features/saved_apps');
+ expect(await reopened.getSaveTarget(UID, otherTask.conversation_id, { rootDir: root }))
+ .toMatchObject({ appId: original.id, appType: originalType });
+ expect(await reopened.resolveSavedAppType(UID, original.id)).toBe(originalType);
+ // An explicit new copy still belongs to its new creation context.
+ const copy = await reopened.saveFromPath(UID, entry, {
+ ...options, mode: 'new', sourceCid: otherTask.conversation_id,
+ });
+ if (!copy.ok) throw new Error(copy.error);
+ expect(copy.id).not.toBe(original.id);
+ expect(await reopened.resolveSavedAppType(UID, copy.id)).toBe(otherType);
+ expect(await reopened.resolveSavedAppType(UID, original.id)).toBe(originalType);
+ expect(reopened.listSavedApps(UID)).toHaveLength(2);
+ },
+ );
+
+ it.each(['artifact', 'workspace', 'workspace across tasks'] as const)(
+ 'coalesces simultaneous automatic saves of one %s into one durable app', async source => {
+ const { savedApps } = await mods();
+ const artifactId = await makeArtifact('Shared source');
+ const root = path.join(tmpDir, 'workspace', 'shared-app');
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, 'index.html'), '<h1>Shared source</h1>');
+ fs.writeFileSync(path.join(root, 'app.js'), 'window.shared = true;');
+ const save = (second: boolean) => source === 'artifact'
+ ? savedApps.saveFromArtifact(UID, CID, artifactId, 'auto')
+ : savedApps.saveFromPath(UID, path.join(root, second ? 'app.js' : 'index.html'), {
+ mode: 'auto', fenceRoots: [path.dirname(root)],
+ sourceCid: second && source === 'workspace across tasks' ? 'other-task' : CID,
+ });
+ const results = await Promise.all([save(false), save(true)]);
+ expect(results.every(result => result.ok)).toBe(true);
+ if (!results[0].ok || !results[1].ok) throw new Error('save failed');
+ expect(results[1].id).toBe(results[0].id);
+ expect(savedApps.listSavedApps(UID).map(app => app.id)).toEqual([results[0].id]);
+ expect(fs.readFileSync(path.join(APPS_ROOT(), results[0].id, 'index.html'), 'utf8')).toContain('Shared source');
+ expect(fs.readdirSync(APPS_ROOT())).toEqual([results[0].id]);
+ expect(await save(true)).toMatchObject({ ok: true, id: results[0].id });
+ },
+ );
+
+ it.each(['artifact', 'workspace'] as const)(
+ 'rolls back a new %s copy when its association cannot persist, then retries without losing the original', async source => {
+ const { savedApps } = await mods();
+ const artifactId = await makeArtifact('Original');
+ const root = path.join(tmpDir, 'workspace', 'binding-app');
+ fs.mkdirSync(root, { recursive: true });
+ const entry = path.join(root, 'index.html');
+ fs.writeFileSync(entry, '<h1>Original</h1>');
+ const save = (mode: 'auto' | 'new') => source === 'artifact'
+ ? savedApps.saveFromArtifact(UID, CID, artifactId, mode)
+ : savedApps.saveFromPath(UID, entry, { mode, sourceCid: CID, fenceRoots: [path.dirname(root)] });
+ const original = await save('auto');
+ if (!original.ok) throw new Error(original.error);
+ const target = () => savedApps.getSaveTarget(UID, CID, source === 'artifact' ? { artifactId } : { rootDir: root });
+ const storage = await import('../../../src/main/storage');
+ const write = storage.writeTextAtomicSync;
+ const fault = vi.spyOn(storage, 'writeTextAtomicSync').mockImplementation((file, ...args) => {
+ const association = source === 'artifact'
+ ? file === path.join(tmpDir, UID, 'cloud/chat_artifacts', CID, artifactId, '__orkas-meta.json')
+ : path.basename(file).startsWith('source-');
+ if (association) throw Object.assign(new Error('synthetic association disk full'), { code: 'ENOSPC' });
+ return write(file, ...args);
+ });
+ try { expect(await save('new')).toMatchObject({ ok: false, error: 'app_save_failed' }); }
+ finally { fault.mockRestore(); }
+ expect(fs.readdirSync(APPS_ROOT())).toEqual([original.id]);
+ expect(await target()).toMatchObject({ appId: original.id });
+ expect(fs.readFileSync(path.join(APPS_ROOT(), original.id, 'index.html'), 'utf8')).toContain('Original');
+ const retry = await save('new');
+ if (!retry.ok) throw new Error(retry.error);
+ expect(retry.id).not.toBe(original.id);
+ expect(await save('auto')).toMatchObject({ ok: true, id: retry.id });
+ expect(savedApps.listSavedApps(UID)).toHaveLength(2);
+ },
+ );
+
+ it.each(['missing-id', 'empty-id', 'array', 'unknown-version'] as const)(
+ 'refuses a damaged workspace destination binding (%s) without overwriting an edit original', async shape => {
+ const { savedApps } = 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 root = path.join(tmpDir, 'workspace', 'independent-copy');
+ fs.mkdirSync(root, { recursive: true });
+ const entry = path.join(root, 'index.html');
+ fs.writeFileSync(entry, '<h1>Independent copy</h1>');
+ const opts = { sourceCid: cid, fenceRoots: [path.dirname(root)] };
+ const copy = await savedApps.saveFromPath(UID, entry, { ...opts, mode: 'new' });
+ if (!copy.ok) throw new Error(copy.error);
+ const edits = path.join(tmpDir, UID, 'local', 'app-edits');
+ const bindings = fs.readdirSync(edits).filter(name => name.startsWith('source-') && name.endsWith('.json'));
+ expect(bindings).toHaveLength(1);
+ const file = path.join(edits, bindings[0]);
+ const valid = fs.readFileSync(file, 'utf8');
+ const invalid = shape === 'array' ? [] : shape === 'empty-id' ? { version: 1, appId: '' }
+ : shape === 'unknown-version' ? { version: 999, appId: copy.id } : { version: 1 };
+ fs.writeFileSync(file, JSON.stringify(invalid));
+ fs.writeFileSync(entry, '<h1>New revision</h1>');
+ expect(await savedApps.saveFromPath(UID, entry, { ...opts, mode: 'auto' }))
+ .toMatchObject({ ok: false, error: 'app_edit_target_missing' });
+ await expect(savedApps.getSaveTarget(UID, cid, { rootDir: root })).rejects.toThrow('app_save_binding_unavailable');
+ expect(fs.readFileSync(path.join(APPS_ROOT(), original.id, 'index.html'), 'utf8')).toContain('Original');
+ expect(fs.readFileSync(path.join(APPS_ROOT(), copy.id, 'index.html'), 'utf8')).toContain('Independent copy');
+ expect(savedApps.listSavedApps(UID)).toHaveLength(2);
+ fs.writeFileSync(file, valid);
+ expect(await savedApps.saveFromPath(UID, entry, { ...opts, mode: 'auto' }))
+ .toMatchObject({ ok: true, id: copy.id });
+ expect(fs.readFileSync(path.join(APPS_ROOT(), copy.id, 'index.html'), 'utf8')).toContain('New revision');
+ expect(fs.readFileSync(path.join(APPS_ROOT(), original.id, 'index.html'), 'utf8')).toContain('Original');
+ },
+ );
+
+ it.each(['empty-id', 'invalid-id', 'invalid-json'] as const)(
+ 'refuses a damaged artifact destination binding (%s) without overwriting an edit original', async shape => {
+ 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 artifact = await chatArtifacts.createArtifact(UID, cid, 'helper', {
+ files: [{ path: 'index.html', content: '<h1>Independent copy</h1>' }],
+ });
+ if (!artifact.ok) throw new Error(artifact.error);
+ const copy = await savedApps.saveFromArtifact(UID, cid, artifact.artifactId, 'new');
+ if (!copy.ok) throw new Error(copy.error);
+ const file = path.join(tmpDir, UID, 'cloud', 'chat_artifacts', cid, artifact.artifactId, '__orkas-meta.json');
+ const valid = fs.readFileSync(file, 'utf8');
+ fs.writeFileSync(file, shape === 'invalid-json' ? '{ damaged'
+ : JSON.stringify({ ...JSON.parse(valid), savedAppId: shape === 'empty-id' ? '' : '../wrong' }));
+ expect(await savedApps.saveFromArtifact(UID, cid, artifact.artifactId, 'auto'))
+ .toMatchObject({ ok: false, error: 'app_edit_target_missing' });
+ await expect(savedApps.getSaveTarget(UID, cid, { artifactId: artifact.artifactId }))
+ .rejects.toThrow('app_save_binding_unavailable');
+ expect(fs.readFileSync(path.join(APPS_ROOT(), original.id, 'index.html'), 'utf8')).toContain('Original');
+ expect(fs.readFileSync(path.join(APPS_ROOT(), copy.id, 'index.html'), 'utf8')).toContain('Independent copy');
+ expect(savedApps.listSavedApps(UID)).toHaveLength(2);
+ fs.writeFileSync(file, valid);
+ expect(await savedApps.saveFromArtifact(UID, cid, artifact.artifactId, 'auto'))
+ .toMatchObject({ ok: true, id: copy.id });
+ },
+ );
+
+ it('creates a fresh destination after deleting an explicit copy without falling back to the edit original', 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: '<h1>Independent edit</h1>' }],
+ });
+ if (!revised.ok) throw new Error(revised.error);
+ const copy = await savedApps.saveFromArtifact(UID, cid, revised.artifactId, 'new');
+ if (!copy.ok) throw new Error(copy.error);
+ expect((await savedApps.deleteSavedApp(UID, copy.id)).ok).toBe(true);
+ expect(await savedApps.getSaveTarget(UID, cid, { artifactId: revised.artifactId })).toBeNull();
+ const recreated = await savedApps.saveFromArtifact(UID, cid, revised.artifactId, 'auto');
+ if (!recreated.ok) throw new Error(recreated.error);
+ expect([original.id, copy.id]).not.toContain(recreated.id);
+ expect(fs.readFileSync(path.join(APPS_ROOT(), original.id, 'index.html'), 'utf8')).toContain('Original');
+ expect(fs.readFileSync(path.join(APPS_ROOT(), recreated.id, 'index.html'), 'utf8')).toContain('Independent edit');
+ expect(await savedApps.saveFromArtifact(UID, cid, revised.artifactId, 'auto')).toMatchObject({ ok: true, id: recreated.id });
+ expect(savedApps.listSavedApps(UID)).toHaveLength(2);
+ });
+
+ it.each([1, 2])('recovers legacy provenance only with a unique destination (%s existing copies)', async copies => {
+ const { savedApps } = await mods();
+ const artifactId = await makeArtifact('Legacy source');
+ const ids: string[] = [];
+ for (let i = 0; i < copies; i++) {
+ const saved = await savedApps.saveFromArtifact(UID, CID, artifactId, 'new');
+ if (!saved.ok) throw new Error(saved.error);
+ ids.push(saved.id);
+ }
+ const metaFile = path.join(tmpDir, UID, 'cloud/chat_artifacts', CID, artifactId, '__orkas-meta.json');
+ const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
+ delete meta.savedAppId;
+ fs.writeFileSync(metaFile, JSON.stringify(meta));
+ const entry = path.join(path.dirname(metaFile), 'index.html');
+ fs.writeFileSync(entry, '<h1>Recovered revision</h1>');
+ const target = await savedApps.getSaveTarget(UID, CID, { artifactId });
+ if (copies === 1) expect(target).toMatchObject({ appId: ids[0] });
+ else expect(target).toBeNull();
+ const result = await savedApps.saveFromArtifact(UID, CID, artifactId, 'auto');
+ if (!result.ok) throw new Error(result.error);
+ if (copies === 1) expect(result.id).toBe(ids[0]);
+ else {
+ expect(ids).not.toContain(result.id);
+ for (const id of ids) expect(fs.readFileSync(path.join(APPS_ROOT(), id, 'index.html'), 'utf8')).toContain('Legacy source');
+ }
+ expect(await savedApps.saveFromArtifact(UID, CID, artifactId, 'auto')).toMatchObject({ ok: true, id: result.id });
+ expect(savedApps.listSavedApps(UID)).toHaveLength(copies === 1 ? 1 : 3);
});
it('finds a deeply nested source inside its workspace without crossing the workspace fence', async () => {
const workspace = path.join(tmpDir, 'workspace', 'deep-app');
@@ -684,7 +1008,7 @@ describe('saved_apps › saveFromPath', () => {
expect(app).toHaveProperty('token');
if (!('token' in app)) throw new Error('SDK app was not opened');
expect(await runtime.call(UID, 17, app.token, 'q1', 'host.getContext', {})).toMatchObject({ sdkVersion: 1 });
- const resource = runtime.resource(new URL(app.url).host, nested, null);
+ const resource = await runtime.resource(new URL(app.url).host, nested, null);
expect(resource?.resolved).toHaveProperty('absPath');
expect(fs.readFileSync(resource!.resolved!.absPath, 'utf8')).toBe('window.deep = 42');
runtime.closeOwner(17);
@@ -813,14 +1137,14 @@ describe('saved_apps › rename / delete', () => {
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});
+ const app=runtime.open(UID,123,{key,title:'Delete data',entry:'index.html',appType:'web',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');
+ try{await draining;expect(()=>runtime.open(UID,124,{key,title:'Concurrent opening',entry:'index.html',appType:'web',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');
@@ -880,12 +1204,12 @@ describe('saved_apps › listSavedApps', () => {
});
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>' }] });
+ const artifact = await chatArtifacts.createArtifact(UID, CID, 'helper', { appType: 'web',
+ files: [{ path: 'index.html', content: '<h1>Recoverable web 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');
+ expect(savedApps.listSavedApps(UID)[0].appType).toBe('web');
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' })]);
@@ -985,6 +1309,144 @@ describe('saved_apps › listSavedApps', () => {
});
describe('saved_apps › openForEditing', () => {
+ it.each(['source', 'bundle'] as const)('rejects an unreadable nested %s inventory and retries with all source files', async stage => {
+ const { savedApps } = await mods();
+ const script = 'window.preservedNestedSource = 42;';
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Nested source', [
+ { path: 'assets/app.js', content: script },
+ ]));
+ if (!saved.ok) throw new Error(saved.error);
+ const chats = await import('../../../src/main/features/chats');
+ const before = (await chats.listConversations(UID)).map(item => item.conversation_id);
+ const nodeFs = (await import('node:fs')).default;
+ const { syncBuiltinESMExports } = await import('node:module');
+ const readdir = nodeFs.readdirSync;
+ let snapshotReads = 0;
+ let failures = 0;
+ const fault = vi.spyOn(nodeFs, 'readdirSync').mockImplementation(((target: any, ...args: any[]) => {
+ const dir = String(target);
+ if (path.basename(dir) === 'assets') {
+ const snapshot = dir.includes(`${path.sep}snapshot${path.sep}`);
+ if (snapshot) snapshotReads++;
+ if (stage === 'source' || (snapshot && snapshotReads === 2)) {
+ failures++;
+ throw Object.assign(new Error('PRIVATE nested directory unavailable'), { code: 'EIO' });
+ }
+ }
+ return (readdir as any)(target, ...args);
+ }) as any);
+ syncBuiltinESMExports();
+ try {
+ expect.soft(await savedApps.openForEditing(UID, saved.id)).toEqual({ ok: false, error: 'app_edit_snapshot_failed' });
+ expect.soft((await chats.listConversations(UID)).map(item => item.conversation_id)).toEqual(before);
+ const edits = path.join(tmpDir, UID, 'local/app-edits');
+ expect.soft(fs.existsSync(edits) ? fs.readdirSync(edits) : []).toEqual([]);
+ expect(failures).toBeGreaterThan(0);
+ } finally { fault.mockRestore(); syncBuiltinESMExports(); }
+ expect(fs.readFileSync(path.join(APPS_ROOT(), saved.id, 'assets/app.js'), 'utf8')).toBe(script);
+ const retry = await savedApps.openForEditing(UID, saved.id);
+ if (!retry.ok) throw new Error(retry.error);
+ const cid = (retry.conversation as any).conversation_id;
+ expect(fs.readFileSync(path.join(attachDir(cid), retry.sourceFileName), 'utf8')).toContain(script);
+ });
+
+ it('does not deliver an incomplete source bundle as a successful edit after a text read fails', async () => {
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Complete source', [
+ { path: 'style.css', content: 'body { color: navy; }' },
+ ]));
+ if (!saved.ok) throw new Error(saved.error);
+ const chats = await import('../../../src/main/features/chats');
+ const before = (await chats.listConversations(UID)).length;
+ const fsp = await import('node:fs/promises');
+ const { readFile } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ const fault = vi.spyOn(fsp, 'readFile').mockImplementation(((file: any, ...args: any[]) => {
+ if (String(file).includes(`${path.sep}snapshot${path.sep}`) && path.basename(String(file)) === 'style.css') {
+ return Promise.reject(Object.assign(new Error('PRIVATE source text read failure'), { code: 'EIO' }));
+ }
+ return (readFile as any)(file, ...args);
+ }) as any);
+ try {
+ expect.soft(await savedApps.openForEditing(UID, saved.id)).toEqual({ ok: false, error: 'app_edit_snapshot_failed' });
+ expect.soft((await chats.listConversations(UID)).length).toBe(before);
+ const edits = path.join(tmpDir, UID, 'local/app-edits');
+ expect.soft(fs.existsSync(edits) ? fs.readdirSync(edits) : []).toEqual([]);
+ } finally { fault.mockRestore(); }
+ expect(fs.readFileSync(path.join(APPS_ROOT(), saved.id, 'style.css'), 'utf8')).toBe('body { color: navy; }');
+ const retry = await savedApps.openForEditing(UID, saved.id);
+ if (!retry.ok) throw new Error(retry.error);
+ const bundle = fs.readFileSync(path.join(attachDir((retry.conversation as any).conversation_id), retry.sourceFileName), 'utf8');
+ expect(bundle).toContain('body { color: navy; }');
+ });
+
+ it('returns a recoverable failure when the initial source stream fails, preserving the app for retry', async () => {
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Retry source', [
+ { path: 'style.css', content: 'body { color: navy; }' },
+ ]));
+ if (!saved.ok) throw new Error(saved.error);
+ const chats = await import('../../../src/main/features/chats');
+ const before = (await chats.listConversations(UID)).map(c => c.conversation_id);
+ const dir = path.join(APPS_ROOT(), saved.id);
+ const source = Object.fromEntries(fs.readdirSync(dir).map(rel => [rel, fs.readFileSync(path.join(dir, rel))]));
+ const nodeFs = (await import('node:fs')).default;
+ const { syncBuiltinESMExports } = await import('node:module');
+ const { Readable } = await import('node:stream');
+ const read = nodeFs.createReadStream;
+ const spy = vi.spyOn(nodeFs, 'createReadStream').mockImplementation(((file: any, ...args: any[]) => {
+ if (String(file) === path.join(dir, 'index.html')) return Readable.from((async function* () {
+ throw Object.assign(new Error('PRIVATE source read failure'), { code: 'EIO' });
+ })());
+ return (read as any)(file, ...args);
+ }) as any);
+ syncBuiltinESMExports();
+ try {
+ await expect(savedApps.openForEditing(UID, saved.id)).resolves.toEqual({ ok: false, error: 'app_edit_snapshot_failed' });
+ } finally { spy.mockRestore(); syncBuiltinESMExports(); }
+ expect((await chats.listConversations(UID)).map(c => c.conversation_id)).toEqual(before);
+ expect(savedApps.listSavedApps(UID).map(app => app.id)).toEqual([saved.id]);
+ for (const [rel, bytes] of Object.entries(source)) expect(fs.readFileSync(path.join(dir, rel))).toEqual(bytes);
+ const edits = path.join(tmpDir, UID, 'local/app-edits');
+ expect(fs.existsSync(edits) ? fs.readdirSync(edits) : []).toEqual([]);
+ const retry = await savedApps.openForEditing(UID, saved.id);
+ if (!retry.ok) throw new Error(retry.error);
+ const cid = (retry.conversation as any).conversation_id;
+ const bundle = fs.readFileSync(path.join(attachDir(cid), retry.sourceFileName), 'utf8');
+ expect(bundle).toContain('<h1>Retry source</h1>');
+ expect(bundle).toContain('body { color: navy; }');
+ });
+
+ it('opens complete large source without synchronous whole-file reads and retains the source fingerprint', async () => {
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Large source'));
+ if (!saved.ok) throw new Error(saved.error);
+ const source = '/* preserved source */\n'.repeat(200_000);
+ fs.writeFileSync(path.join(APPS_ROOT(), saved.id, 'large.js'), source);
+ const nodeFs = (await import('node:fs')).default;
+ const { syncBuiltinESMExports } = await import('node:module');
+ const read = nodeFs.readFileSync;
+ let synchronousSourceReads = 0;
+ const spy = vi.spyOn(nodeFs, 'readFileSync').mockImplementation(((file: any, ...args: any[]) => {
+ if (path.basename(String(file)) === 'large.js') synchronousSourceReads += 1;
+ return (read as any)(file, ...args);
+ }) as any);
+ syncBuiltinESMExports();
+ let result: Awaited<ReturnType<typeof savedApps.openForEditing>>;
+ try { result = await savedApps.openForEditing(UID, saved.id); }
+ finally { spy.mockRestore(); syncBuiltinESMExports(); }
+ expect(result.ok).toBe(true);
+ expect(synchronousSourceReads).toBe(0);
+ if (!result.ok) throw new Error(result.error);
+ const cid = (result.conversation as any).conversation_id;
+ const bundle = fs.readFileSync(path.join(attachDir(cid), result.sourceFileName), 'utf8');
+ expect(bundle).toContain(source);
+ const context = JSON.parse(fs.readFileSync(path.join(tmpDir, UID, 'local/app-edits', cid, 'context.json'), 'utf8'));
+ const hash = crypto.createHash('sha256');
+ for (const rel of fs.readdirSync(path.join(APPS_ROOT(), saved.id)).sort()) {
+ hash.update(JSON.stringify(rel)).update('\0').update(fs.readFileSync(path.join(APPS_ROOT(), saved.id, rel))).update('\0');
+ }
+ expect(context.fingerprint).toBe(hash.digest('hex'));
+ });
it('creates a conversation and bundles every source file into app-source.md', async () => {
const { savedApps, chatArtifacts } = await mods();
const chats = await import('../../../src/main/features/chats');
@@ -1026,22 +1488,28 @@ describe('saved_apps › openForEditing', () => {
expect((await chats.listConversations(UID)).length).toBe(before);
});
- it('rolls back the new conversation when the source attachment cannot be created', async () => {
+ it.each(['returned', 'thrown'] as const)('rolls back the new conversation when the source attachment cannot be created (%s)', async failure => {
const { savedApps } = await mods();
const chats = await import('../../../src/main/features/chats');
const chatAttachments = await import('../../../src/main/features/chat_attachments');
const aid = await makeArtifact('Attachment failure');
const saved = (await savedApps.saveFromArtifact(UID, CID, aid));
if (!saved.ok) throw new Error('save failed');
- vi.spyOn(chatAttachments, 'uploadAttachment').mockResolvedValue({
- ok: false,
- error: 'injected attachment failure',
- });
+ const upload = vi.spyOn(chatAttachments, 'uploadAttachment');
+ if (failure === 'thrown') upload.mockRejectedValue(Object.assign(new Error('PRIVATE attachment failure'), { code: 'EACCES' }));
+ else upload.mockResolvedValue({ ok: false, error: 'injected attachment failure' });
const before = (await chats.listConversations(UID)).length;
- const result = await savedApps.openForEditing(UID, saved.id);
- expect(result).toEqual({ ok: false, error: 'injected attachment failure' });
- expect((await chats.listConversations(UID)).length).toBe(before);
+ let result: unknown;
+ try { result = await savedApps.openForEditing(UID, saved.id); }
+ catch { result = { rejected: true }; }
+ expect.soft(result).toEqual({ ok: false, error: failure === 'thrown' ? 'app_edit_snapshot_failed' : 'injected attachment failure' });
+ expect.soft((await chats.listConversations(UID)).length).toBe(before);
+ expect(savedApps.listSavedApps(UID).map(app => app.id)).toEqual([saved.id]);
+ const edits = path.join(tmpDir, UID, 'local/app-edits');
+ expect.soft(fs.existsSync(edits) ? fs.readdirSync(edits) : []).toEqual([]);
+ upload.mockRestore();
+ expect((await savedApps.openForEditing(UID, saved.id)).ok).toBe(true);
});
it('does not bundle files through a symlinked saved-app directory', async () => {
@@ -1260,10 +1728,77 @@ describe('saved_apps › delete interrupted by a process stop', () => {
return (await import('../../../src/main/features/saved_apps'));
}
+ it('keeps a committed update successful without tombstoning files when later inventory reads fail', async () => {
+
+ const { savedApps, chatArtifacts } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Keep committed source', [
+ { path: 'assets/app.js', content: 'window.version = 1;' },
+ ]));
+ 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 revised = await chatArtifacts.createArtifact(UID, cid, 'helper', { files: [
+ { path: 'index.html', content: '<h1>Committed update</h1>' },
+ { path: 'assets/app.js', content: 'window.version = 2;' },
+ ] });
+ if (!revised.ok) throw new Error(revised.error);
+ const app = path.join(APPS_ROOT(), saved.id);
+ const nodeFs = (await import('node:fs')).default;
+ const { syncBuiltinESMExports } = await import('node:module');
+ const rename = nodeFs.renameSync, readdir = nodeFs.readdirSync;
+ let committed = false;
+ const swap = vi.spyOn(nodeFs, 'renameSync').mockImplementation((from, to) => {
+ rename(from, to);
+ if (String(to) === app) committed = true;
+ });
+ const fault = vi.spyOn(nodeFs, 'readdirSync').mockImplementation(((target: any, ...args: any[]) => {
+ if (committed && String(target) === app) throw Object.assign(new Error('PRIVATE post-save inventory unavailable'), { code: 'EIO' });
+ return (readdir as any)(target, ...args);
+ }) as any);
+ syncBuiltinESMExports();
+ try {
+ expect.soft(await savedApps.saveFromArtifact(UID, cid, revised.artifactId, 'update')).toMatchObject({ ok: true, id: saved.id });
+ expect(committed).toBe(true);
+ } finally { swap.mockRestore(); fault.mockRestore(); syncBuiltinESMExports(); }
+ expect(fs.readFileSync(path.join(app, 'assets/app.js'), 'utf8')).toBe('window.version = 2;');
+ expect(fs.readFileSync(path.join(app, 'index.html'), 'utf8')).toContain('Committed update');
+
+ });
+
+ it.each(['app', 'cloud'] as const)('retains the app and private data when the %s deletion inventory cannot be read', async source => {
+
+ const { savedApps } = await mods();
+ const saved = await savedApps.saveFromArtifact(UID, CID, await makeArtifact('Delete after retry', [
+ { path: 'assets/app.js', content: 'window.keepUntilDelete = true;' },
+ ]));
+ if (!saved.ok) throw new Error(saved.error);
+ const data = seed(dataKey(saved.id));
+ const app = path.join(APPS_ROOT(), saved.id);
+ const blocked = source === 'app' ? path.join(app, 'assets') : path.join(data.cloud, 'files');
+ const nodeFs = (await import('node:fs')).default;
+ const { syncBuiltinESMExports } = await import('node:module');
+ const readdir = nodeFs.readdirSync;
+ const fault = vi.spyOn(nodeFs, 'readdirSync').mockImplementation(((target: any, ...args: any[]) => {
+ if (String(target) === blocked) throw Object.assign(new Error('PRIVATE delete inventory unavailable'), { code: 'EIO' });
+ return (readdir as any)(target, ...args);
+ }) as any);
+ syncBuiltinESMExports();
+ try {
+ expect.soft(await savedApps.deleteSavedApp(UID, saved.id)).toEqual({ ok: false, error: 'app_delete_failed' });
+ } finally { fault.mockRestore(); syncBuiltinESMExports(); }
+ expect.soft(fs.existsSync(path.join(app, 'assets/app.js'))).toBe(true);
+ expect.soft(fs.existsSync(path.join(data.cloud, 'files/note.txt'))).toBe(true);
+ expect.soft(fs.existsSync(path.join(data.local, 'data.sqlite'))).toBe(true);
+ expect(await savedApps.deleteSavedApp(UID, saved.id)).toEqual({ ok: true });
+ expect(fs.existsSync(app)).toBe(false);
+ expect(fs.existsSync(data.cloud)).toBe(false);
+
+ });
+
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'));
@@ -1289,8 +1824,6 @@ describe('saved_apps › delete interrupted by a process stop', () => {
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));
@@ -1300,7 +1833,6 @@ describe('saved_apps › delete interrupted by a process stop', () => {
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'));
@@ -1411,3 +1943,146 @@ describe('editing snapshot retention', () => {
expect(fs.existsSync(other)).toBe(true);
});
});
+
+describe('workspace save identity and recovery', () => {
+ it('identifies one physical workspace through a symlink alias', async () => {
+ const { savedApps } = await mods();
+ const workspace = path.join(tmpDir, 'workspace');
+ const root = path.join(workspace, 'app');
+ const alias = path.join(workspace, 'alias');
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, 'index.html'), '<h1>Original</h1>');
+ fs.symlinkSync(root, alias, 'dir');
+ const options = { mode: 'auto' as const, sourceCid: CID, fenceRoots: [workspace] };
+ const first = await savedApps.saveFromPath(UID, path.join(root, 'index.html'), options);
+ if (!first.ok) throw new Error(first.error);
+ fs.writeFileSync(path.join(root, 'index.html'), '<h1>Updated</h1>');
+ const second = await savedApps.saveFromPath(UID, path.join(alias, 'index.html'), options);
+ if (!second.ok) throw new Error(second.error);
+ expect(second.id).toBe(first.id);
+ expect(savedApps.listSavedApps(UID)).toHaveLength(1);
+ });
+ it.each(['app.js', 'style.css', '.'])('keeps the chosen entry when updating through %s', async sibling => {
+ const { savedApps } = await mods();
+ const workspace = path.join(tmpDir, 'workspace');
+ const root = path.join(workspace, 'app');
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, 'game.html'), '<h1>Game main entry</h1>');
+ fs.writeFileSync(path.join(root, 'about.html'), '<h1>About this game</h1>');
+ fs.writeFileSync(path.join(root, 'app.js'), '// shared logic');
+ fs.writeFileSync(path.join(root, 'style.css'), 'body{}');
+ const options = { mode: 'auto' as const, sourceCid: CID, fenceRoots: [workspace] };
+ const first = await savedApps.saveFromPath(UID, path.join(root, 'game.html'), options);
+ if (!first.ok) throw new Error(first.error);
+ expect(savedApps.resolveSavedAppIndex(UID, first.id)).toMatchObject({ok:true,absPath:path.join(APPS_ROOT(),first.id,'game.html')});
+ const second = await savedApps.saveFromPath(UID, path.join(root, sibling), options);
+ expect(second).toMatchObject({ok:true,id:first.id});
+ expect(savedApps.resolveSavedAppIndex(UID, first.id)).toMatchObject({ok:true,absPath:path.join(APPS_ROOT(),first.id,'game.html')});
+ });
+ it('exports and explicitly recovers incompatible workspace data without accepting stale consent', async () => {
+ const { savedApps } = await mods();
+ const workspace = path.join(tmpDir, 'workspace');
+ const root = path.join(workspace, 'app');
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, 'index.html'), '<h1>Original</h1>');
+ const definition:any = {version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]};
+ const manifest = path.join(root, 'orkas-app.json');
+ fs.writeFileSync(manifest, JSON.stringify({sdkVersion:1,capabilities:['data'],data:definition}));
+ const options = { mode: 'auto' as const, sourceCid: CID, fenceRoots: [workspace] };
+ const first = await savedApps.saveFromPath(UID, path.join(root, 'index.html'), options);
+ if (!first.ok) throw new Error(first.error);
+ const key = crypto.createHash('sha256').update(JSON.stringify(['saved',first.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 db = new LocalAppData(file,path.join(tmpDir,UID,'local'),definition);
+ try { await db.call('data.insert',{table:'notes',values:{body:'KEEP'}}); } finally { await db.close(); }
+ const changed = {version:1,tables:[{id:'notes',name:'notes',fields:[],access:{read:[],insert:[]}}]};
+ fs.writeFileSync(manifest, JSON.stringify({sdkVersion:1,capabilities:['data'],data:changed}));
+ const result = await savedApps.saveFromPath(UID,path.join(root,'index.html'),options);
+ expect(result).toEqual({ok:false,error:'app_edit_data_migration'});
+ const again = new LocalAppData(file,path.join(tmpDir,UID,'local'),definition);
+ try { expect(await again.call('data.query',{table:'notes'})).toEqual({records:[{body:'KEEP'}]}); } finally { await again.close(); }
+ const impact = await savedApps.appDataImpact(UID,CID,{rootDir:root});
+ if (!impact.ok) throw new Error(impact.error);
+ expect(impact).toMatchObject({appId:first.id,records:1});
+ const exported = path.join(tmpDir,'export.sqlite');
+ expect(await savedApps.exportAppData(UID,CID,{rootDir:root},exported,first.id)).toEqual({ok:true});
+ const backup = new LocalAppData(exported,tmpDir,definition);
+ try { expect(await backup.call('data.query',{table:'notes'})).toEqual({records:[{body:'KEEP'}]}); } finally { await backup.close(); }
+ const recovery = {appId:first.id,clearVersion:impact.version,clearFingerprint:impact.fingerprint};
+ for (const invalid of [{...recovery,appId:'different-app'}, {...recovery,clearVersion:impact.version+1}, {...recovery,clearFingerprint:'outdated'}]) {
+ expect(await savedApps.saveFromPath(UID,path.join(root,'index.html'),{...options,recovery:invalid})).toMatchObject({ok:false,error:'app_edit_conflict'});
+ }
+ expect(await savedApps.saveFromPath(UID,path.join(root,'index.html'),{...options,recovery})).toMatchObject({ok:true,id:first.id});
+ const cleared = new LocalAppData(file,path.join(tmpDir,UID,'local'),changed);
+ try { expect(await cleared.call('internal.inspect',{})).toMatchObject({records:0}); } finally { await cleared.close(); }
+ fs.rmSync(path.join(APPS_ROOT(),first.id),{recursive:true});
+ expect(await savedApps.saveFromPath(UID,path.join(root,'index.html'),{...options,recovery})).toMatchObject({ok:false,error:'app_edit_conflict'});
+ expect(savedApps.listSavedApps(UID)).toHaveLength(0);
+
+ });
+});
+
+describe('workspace alias binding compatibility', () => {
+ async function fixture() {
+ const {savedApps}=await mods();
+ const workspace=path.join(tmpDir,'workspace'),root=path.join(workspace,'app'),alias=path.join(workspace,'alias');
+ fs.mkdirSync(root,{recursive:true});fs.writeFileSync(path.join(root,'index.html'),'<h1>Original</h1>');
+ fs.symlinkSync(root,alias,process.platform==='win32'?'junction':'dir');
+ const options={mode:'auto' as const,fenceRoots:[workspace]};
+ const save=(dir:string,mode:'auto'|'new'='auto',sourceCid=CID)=>savedApps.saveFromPath(UID,path.join(dir,'index.html'),{...options,mode,sourceCid});
+ const binding=(dir:string)=>path.join(tmpDir,UID,'local/app-edits',`source-${crypto.createHash('sha256').update(path.resolve(dir)).digest('hex')}.json`);
+ return {savedApps,root,alias,save,binding};
+ }
+ it('serializes concurrent aliases across tasks and retargets both after an explicit copy',async()=>{
+ const {savedApps,root,alias,save}=await fixture();
+ const [first,second]=await Promise.all([save(alias),save(root,'auto','another-task')]);
+ if(!first.ok||!second.ok)throw new Error('save failed');
+ expect(second.id).toBe(first.id);expect(savedApps.listSavedApps(UID)).toHaveLength(1);
+ const copy=await save(alias,'new');if(!copy.ok)throw new Error(copy.error);
+ fs.writeFileSync(path.join(root,'index.html'),'<h1>Copy revision</h1>');
+ expect(await save(root)).toMatchObject({ok:true,id:copy.id});
+ expect(fs.readFileSync(path.join(APPS_ROOT(),first.id,'index.html'),'utf8')).toContain('Original');
+ expect(fs.readFileSync(path.join(APPS_ROOT(),copy.id,'index.html'),'utf8')).toContain('Copy revision');
+ fs.rmSync(path.join(APPS_ROOT(),copy.id),{recursive:true});
+ const recreated=await save(alias);if(!recreated.ok)throw new Error(recreated.error);
+ expect(recreated.id).not.toBe(first.id);expect(recreated.id).not.toBe(copy.id);
+ expect(await save(root)).toMatchObject({ok:true,id:recreated.id});
+ });
+ it.each(['binding','provenance'])('recovers a legacy alias %s without losing its destination',async evidence=>{
+ const {savedApps,root,alias,save,binding}=await fixture();
+ const original=await save(alias);if(!original.ok)throw new Error(original.error);
+ fs.unlinkSync(binding(fs.realpathSync(root)));
+ const metaFile=path.join(APPS_ROOT(),original.id,'__orkas-meta.json');
+ const meta=JSON.parse(fs.readFileSync(metaFile,'utf8'));
+ meta.sourcePathKey=crypto.createHash('sha256').update(path.resolve(alias)).digest('hex');
+ fs.writeFileSync(metaFile,JSON.stringify(meta));
+ if(evidence==='binding')fs.writeFileSync(binding(alias),JSON.stringify({version:1,appId:original.id}));
+ expect(await save(alias)).toMatchObject({ok:true,id:original.id});
+ expect(await save(root)).toMatchObject({ok:true,id:original.id});
+ expect(savedApps.listSavedApps(UID)).toHaveLength(1);
+ });
+ it('refuses conflicting legacy aliases until an explicit copy establishes one destination',async()=>{
+ const {savedApps,root,alias,save,binding}=await fixture();
+ const a=await save(root),b=await save(alias,'new');if(!a.ok||!b.ok)throw new Error('save failed');
+ fs.writeFileSync(binding(fs.realpathSync(root)),JSON.stringify({version:1,appId:a.id}));
+ fs.writeFileSync(binding(alias),JSON.stringify({version:1,appId:b.id}));
+ expect(await save(alias)).toMatchObject({ok:false,error:'app_edit_target_missing'});
+ expect(savedApps.listSavedApps(UID)).toHaveLength(2);
+ const chosen=await save(alias,'new');if(!chosen.ok)throw new Error(chosen.error);
+ expect(await save(root)).toMatchObject({ok:true,id:chosen.id});
+ expect(await save(alias)).toMatchObject({ok:true,id:chosen.id});
+ });
+ it('keeps the saved entry when missing and permits an explicit replacement HTML',async()=>{
+ const {savedApps,root}=await fixture();
+ fs.writeFileSync(path.join(root,'game.html'),'<title>Game</title>');fs.writeFileSync(path.join(root,'app.js'),'// code');
+ const options={mode:'auto' as const,fenceRoots:[path.dirname(root)]};
+ const app=await savedApps.saveFromPath(UID,path.join(root,'game.html'),options);if(!app.ok)throw new Error(app.error);
+ fs.unlinkSync(path.join(root,'game.html'));
+ expect(await savedApps.saveFromPath(UID,path.join(root,'app.js'),options)).toMatchObject({ok:false});
+ expect(savedApps.resolveSavedAppIndex(UID,app.id)).toMatchObject({ok:true,absPath:path.join(APPS_ROOT(),app.id,'game.html')});
+ expect(await savedApps.saveFromPath(UID,path.join(root,'index.html'),options)).toMatchObject({ok:true,id:app.id,entry:'index.html'});
+ const copy=await savedApps.saveFromPath(UID,root,{...options,mode:'new'});if(!copy.ok)throw new Error(copy.error);
+ expect(copy.id).not.toBe(app.id);expect(copy.entry).toBe('index.html');
+ });
+});
diff --git a/test/main/features/web-app-commercial-entry.test.ts b/test/main/features/web-app-commercial-entry.test.ts
index 72f1abd5..b3118619 100644
--- a/test/main/features/web-app-commercial-entry.test.ts
+++ b/test/main/features/web-app-commercial-entry.test.ts
@@ -38,25 +38,68 @@ function snapshot(dir: string): unknown {
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));
+describe('unified apps and the publication boundary', () => {
+ it.each(['local', 'web', 'cloud'])('creates, saves, reopens, previews and edits a %s app locally', async appType => {
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 created = await artifacts.createArtifact(uid, 'new-task', 'commander', { appType, files: [
+ { path: 'index.html', content: '<h1>Locally available</h1>' },
+ { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: [] }) },
+ ] });
+ expect(created.ok).toBe(true); if (!created.ok) throw new Error(created.error);
+ const stored = await saved.saveFromArtifact(uid, 'new-task', created.artifactId);
+ expect(stored.ok).toBe(true); if (!stored.ok) throw new Error(stored.error);
+ expect(saved.listSavedApps(uid).map(app => app.id)).toContain(stored.id);
+ const host = await import('../../../src/main/features/web_apps/host');
+ const opened = await host.openApp(uid, 4, { appId: stored.id });
+ expect(opened.url).toMatch(/^chat-app:/);
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);
+ const paths = await import('../../../src/main/paths');
+ const preview = await previewBundle(path.join(paths.savedAppDir(uid, stored.id), 'index.html'));
+ expect(preview?.resolve('index.html')).toMatchObject({ mime: 'text/html; charset=utf-8' });
+ expect(await saved.openForEditing(uid, stored.id)).toMatchObject({ ok: true });
+ host.runtime.closeUser(uid); await host.runtime.drainData();
});
+ it.each(['web', 'cloud'])('retains existing %s source and capability identity while saving and editing', 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 before = snapshot(savedDir);
+ const saved = await import('../../../src/main/features/saved_apps');
+ expect(saved.listSavedApps(uid).map(app => app.id)).toContain('historic-app');
+ expect(await saved.saveFromArtifact(uid, 'historic', 'historic')).toMatchObject({ ok: true });
+ expect(await saved.saveFromPath(uid, path.join(artifactDir, 'index.html'))).toMatchObject({ ok: true });
+ const edited = await saved.openForEditing(uid, 'historic-app');
+ expect(edited.ok).toBe(true);
+ expect(snapshot(savedDir)).toEqual(before);
+ expect(await saved.resolveSavedAppType(uid, 'historic-app')).toBe('web');
+ });
+
+ it('keeps legacy web SDK data available without granting host-only capabilities', async () => {
+ 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: 'web', entry: 'index.html', title: 'Retained',
+ manifest: { sdkVersion: 1, capabilities: [] }, resolve: () => null } as any;
+ const opened = runtime.open(uid, 1, bundle);
+ expect(opened.url).toMatch(/^chat-app:/);
+ expect(await runtime.call(uid, 1, opened.token, 'context', 'host.getContext', {})).toMatchObject({ language: 'en', sdkVersion: 1 });
+ await expect(runtime.call(uid, 1, opened.token, 'host-file', 'files.pick', {})).rejects.toMatchObject({ code: 'E_UNAVAILABLE' });
+ expect(called).not.toHaveBeenCalled(); runtime.closeUser(uid); await runtime.drainData();
+ });
+
+ it('refuses publication before changing saved apps, artifacts, or edit drafts', async () => {
+ const paths = await import('../../../src/main/paths');
+ seed(paths.savedAppDir(uid, 'historic-app'), 'web');
+ seed(path.join(paths.chatArtifactCidDir(uid, 'historic'), 'historic'), 'web');
+ const before = snapshot(path.join(root, 'data'));
+ const { publishApp } = await import('../../../src/main/features/web_apps/commercial-entry');
+ expect(publishApp()).toMatchObject(receipt);
+ expect(snapshot(path.join(root, 'data'))).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');
@@ -76,101 +119,20 @@ describe('commercial web application boundary', () => {
} 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 });
- });
+it.each(['web','cloud'])('retains an unrecognized %s save journal and staging bytes for recovery', async appType => {
+ const paths = await import('../../../src/main/paths');
+ const editing = path.join(paths.userAppEditsDir(uid), 'interrupted-edit');
+ const temporary = paths.savedAppDir(uid, 'retained-app.tmp-01234567');
+ seed(paths.savedAppDir(uid, 'retained-app'), appType);
+ seed(temporary, appType);
+ fs.mkdirSync(editing, {recursive:true});
+ fs.writeFileSync(path.join(editing,'context.json'), JSON.stringify({version:1,appId:'retained-app',appType,title:'Retained',fingerprint:'0'.repeat(64)}));
+ fs.writeFileSync(path.join(editing,'save-journal.json'), JSON.stringify({version:1,appId:'retained-app',temporary:'retained-app.tmp-01234567',before:'0'.repeat(64),after:'1'.repeat(64)}));
+ const beforeApps = snapshot(paths.userSavedAppsDir(uid)), beforeEdits = snapshot(editing);
+ const saved = await import('../../../src/main/features/saved_apps');
+ saved.listSavedApps(uid); await saved.cleanupEditSnapshots(uid);
+ expect(snapshot(paths.userSavedAppsDir(uid))).toEqual(beforeApps);
+ expect(snapshot(editing)).toEqual(beforeEdits);
});
diff --git a/test/main/features/web-app-host.test.ts b/test/main/features/web-app-host.test.ts
index 0300c8ef..521eb45a 100644
--- a/test/main/features/web-app-host.test.ts
+++ b/test/main/features/web-app-host.test.ts
@@ -4,6 +4,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { EventEmitter } from 'node:events';
+import { freezeFileMetadata } from '../../helpers/frozen-file-metadata';
const connector = vi.hoisted(() => ({ instances: [] as any[], call: vi.fn(async () => ({ content: [{ type: 'text', text: 'Verified remote result' }] })), approve: vi.fn(async () => false) }));
@@ -93,7 +94,7 @@ describe('Web host reuses owning services', () => {
...(frameAvailable ? { frame: { url: app.url } } : { initiator: { url: app.url } }) };
sender.emit('will-frame-navigate', event);
expect(event.preventDefault.mock.calls.length).toBe(allowed ? 0 : 1);
- if (allowed) expect(appResource(new Request(destination))).toMatchObject({ status: 200 });
+ if (allowed) expect(await appResource(new Request(destination))).toMatchObject({ status: 200 });
}
}
// An external child navigating from about:blank must not revoke its parent.
@@ -139,10 +140,10 @@ describe('Web host reuses owning services', () => {
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 });
+ expect(await appResource(new Request(app.url))).toEqual({ status: 403 });
} else {
expect(await runtime.call(uid, sender.id, app.token, 'after', 'storage.keys', {})).toEqual({ keys: [] });
- expect(appResource(new Request(app.url))).toMatchObject({ status: 200 });
+ expect(await appResource(new Request(app.url))).toMatchObject({ status: 200 });
}
}
}
@@ -216,14 +217,53 @@ describe('Web host reuses owning services', () => {
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 }));
- expect(appResource(new Request(app.url))).toMatchObject({ status: 200, source: 'chat_app_artifact' });
- const sdk: any = appResource(new Request(new URL('/__orkas/sdk.js', app.url)));
+ expect(await appResource(new Request(app.url))).toMatchObject({ status: 200, source: 'chat_app_artifact' });
+ const sdk: any = await appResource(new Request(new URL('/__orkas/sdk.js', app.url)));
expect(sdk.body).toContain('"ai.generate"'); expect(sdk.headers['Access-Control-Allow-Origin']).toBeUndefined();
- expect(appResource(new Request(app.url, { headers: { Origin: 'chat-app://foreign' } }))).toEqual({ status: 403 });
+ expect(await appResource(new Request(app.url, { headers: { Origin: 'chat-app://foreign' } }))).toEqual({ status: 403 });
const file: any = artifact.resolveArtifactFilePath(uid, 'cid-test', created.artifactId, 'index.html');
fs.writeFileSync(file.absPath, '<h1>Replaced code</h1>');
await expect(runtime.call(uid, 1, app.token, 'stale', 'storage.keys', {})).rejects.toMatchObject({ code: 'E_CLOSED' });
- expect(appResource(new Request(app.url))).toEqual({ status: 403 });
+ expect(await appResource(new Request(app.url))).toEqual({ status: 403 });
+ });
+ it.each([
+ ['artifact', 'write'], ['saved', 'write'], ['artifact', 'resource'], ['saved', 'resource'], ['artifact', 'submit'],
+ ] as const)('revokes %s authority at the %s boundary after a same-length source edit', async (kind, boundary) => {
+ 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 created = await artifacts.createArtifact(uid, 'content-revision', 'agent', { files: [
+ { path: 'index.html', content: '<h1>Before</h1>' },
+ { path: 'orkas-app.json', content: JSON.stringify({ sdkVersion: 1, capabilities: ['storage'] }) },
+ ] });
+ if (!created.ok) throw new Error(created.error);
+ const copy = await saved.saveFromArtifact(uid, 'content-revision', created.artifactId);
+ if (!copy.ok) throw new Error(copy.error);
+ const source = kind === 'saved' ? { appId: copy.id } : { cid: 'content-revision', artifactId: created.artifactId };
+ const file = kind === 'saved' ? saved.resolveSavedAppFilePath(uid, copy.id, 'index.html')
+ : artifacts.resolveArtifactFilePath(uid, 'content-revision', created.artifactId, 'index.html');
+ if (!file.ok) throw new Error(file.error);
+ const before = fs.readFileSync(file.absPath, 'utf8');
+ const after = before.replace('Before', 'After!');
+ expect(after).not.toBe(before);
+ expect(Buffer.byteLength(after)).toBe(Buffer.byteLength(before));
+ const restore = freezeFileMetadata([file.absPath]);
+ try {
+ const app: any = await openApp(uid, 1, source);
+ expect(await runtime.call(uid, 1, app.token, 'before', 'storage.set', { key: 'value', value: 'KEEP' })).toEqual({ saved: true });
+ expect(await appResource(new Request(app.url))).toMatchObject({ status: 200 });
+ if (boundary === 'submit') expect(await runtime.canSubmitArtifact(uid, 1, app.token)).toBe(true);
+ fs.writeFileSync(file.absPath, after);
+ expect(fs.readFileSync(file.absPath, 'utf8')).toBe(after);
+ if (boundary === 'resource') expect(await appResource(new Request(app.url))).toEqual({ status: 403 });
+ else if (boundary === 'submit') expect(await runtime.canSubmitArtifact(uid, 1, app.token)).toBe(false);
+ else await expect(runtime.call(uid, 1, app.token, 'after', 'storage.set', { key: 'value', value: 'WRONG' }))
+ .rejects.toMatchObject({ code: 'E_CLOSED' });
+ await expect(runtime.call(uid, 1, app.token, 'still-closed', 'storage.keys', {})).rejects.toMatchObject({ code: 'E_CLOSED' });
+ expect(await appResource(new Request(app.url))).toEqual({ status: 403 });
+ const reopened: any = await openApp(uid, 1, source);
+ expect(await runtime.call(uid, 1, reopened.token, 'read', 'storage.get', { key: 'value' })).toEqual({ value: 'KEEP' });
+ } finally { restore(); }
});
});
@@ -250,19 +290,19 @@ it('isolates new ordinary objects and accounts with short stable origins and no
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 });
+ expect(await appResource(new Request(app.url))).toMatchObject({ status: 200 });
+ expect(await 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 });
+ expect(await appResource(new Request(new URL(rel, app.url)))).toMatchObject({ status: 403 });
+ expect(await 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 });
+ expect(await 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 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);
@@ -270,10 +310,10 @@ it('isolates new ordinary objects and accounts with short stable origins and no
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 });
+ expect(await 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 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 3154da0b..5c1a2e8f 100644
--- a/test/main/features/web-app-ipc.test.ts
+++ b/test/main/features/web-app-ipc.test.ts
@@ -69,9 +69,9 @@ it('admits submission only from a live local artifact owned by the active accoun
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' }));
+ for (const app of [runtime.open('user', 1, { ...bundle, kind: 'saved' }),
+ runtime.open('user', 1, { ...bundle, appType: 'web' })])
+ expect(await check(app.token)).toEqual({ allowed: false });
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 });
@@ -155,3 +155,26 @@ it('scopes cancellation and duplicate IDs to the originating app instance', asyn
expect(await collect(call(sibling.token, 'same-id'))).toEqual([{ type: 'result', ok: false, value: { code: 'E_DUPLICATE' } }]);
expect(generate).toHaveBeenCalledOnce();
});
+
+it.each(['cancel', 'close', 'account-switch'] as const)('does not dispatch after %s during asynchronous source validation', async action => {
+ let uid = 'user', release!: () => void, entered!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ const generate = vi.fn(async () => ({ text: 'Must not run' }));
+ const { open, call, webAppCall, ctx } = await setup(generate, () => uid);
+ let first = true;
+ const app = runtime.open(uid, 1, { key: 'guarded', title: 'Guarded', entry: 'index.html',
+ manifest: { sdkVersion: 1, capabilities: ['ai'] }, resolve: () => null,
+ valid: async () => { if (first) { first = false; entered(); await gate; } return true; } });
+ const pending = collect(call(app.token, 'guarded'));
+ await started;
+ if (action === 'cancel') runtime.cancel('user', 1, app.token, 'guarded');
+ else if (action === 'close') runtime.close('user', 1, app.token);
+ else { uid = 'other'; runtime.closeUser('user'); }
+ release();
+ expect(await pending).toEqual([{ type: 'result', ok: false, value: { code: 'E_CANCELLED' } }]);
+ expect(generate).not.toHaveBeenCalled();
+ const recovered = action === 'cancel' ? app : open();
+ expect(await collect(webAppCall({ token: recovered.token, requestId: 'fresh', method: 'host.getContext', args: {} },
+ ctx(), new AbortController().signal))).toMatchObject([{ type: 'result', ok: true }]);
+});
diff --git a/test/main/features/web-app-preview.test.ts b/test/main/features/web-app-preview.test.ts
index 52a93ecc..dcb51342 100644
--- a/test/main/features/web-app-preview.test.ts
+++ b/test/main/features/web-app-preview.test.ts
@@ -3,6 +3,7 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { previewBundle } from '../../../src/main/features/web_apps/preview';
+import { freezeFileMetadata } from '../../helpers/frozen-file-metadata';
let root: string, entry: string;
beforeEach(() => {
@@ -30,9 +31,9 @@ describe('preview source opt-in and revision isolation', () => {
manifest(); const bundle = (await previewBundle(entry))!;
expect(bundle.resolve('index.html')).toEqual({ absPath: entry, mime: 'text/html; charset=utf-8' });
for (const rel of ['../private.txt', '/private.txt', 'dir/../../private.txt', '.env', 'dir\\file']) expect(bundle.resolve(rel)).toBeNull();
- expect(bundle.valid!()).toBe(true);
+ expect(await bundle.valid!()).toBe(true);
fs.writeFileSync(entry, '<h1>Changed</h1>');
- expect(bundle.valid!()).toBe(false); expect(bundle.resolve('index.html')).toBeNull();
+ expect(await bundle.valid!()).toBe(false); expect(bundle.resolve('index.html')).toBeNull();
});
it('rejects linked manifests, sibling files and linked assets before launching', async () => {
const outside = path.join(root, 'outside.json'); fs.writeFileSync(outside, '{"sdkVersion":1,"capabilities":[]}');
@@ -44,6 +45,23 @@ describe('preview source opt-in and revision isolation', () => {
});
});
+it('rejects changed preview content at the actual protocol boundary despite identical metadata', async () => {
+ const { EventEmitter } = await import('node:events');
+ const { createPreviewSdk } = await import('../../../src/main/features/web_apps/preview');
+ manifest();
+ const restore = freezeFileMetadata([entry]);
+ const contents: any = Object.assign(new EventEmitter(), { id: 20, mainFrame: {}, isDestroyed: () => false });
+ let resource!: (request: Request) => Promise<Response>;
+ const session: any = { protocol: { handle: (_scheme: string, handler: typeof resource) => { resource = handler; }, unhandle() {} } };
+ let preview: Awaited<ReturnType<typeof createPreviewSdk>> | undefined;
+ try {
+ preview = await createPreviewSdk(session, contents, (await previewBundle(entry))!);
+ expect((await resource(new Request(preview.origin + '/index.html'))).status).toBe(200);
+ fs.writeFileSync(entry, '<h1>Changed</h1>');
+ expect((await resource(new Request(preview.origin + '/index.html'))).status).toBe(403);
+ } finally { try { await preview?.dispose(); } finally { restore(); } }
+});
+
it('accepts only its own trusted frame, token and narrow operations, then revokes resources and deletes storage', async () => {
const { EventEmitter } = await import('node:events');
const { createPreviewSdk } = await import('../../../src/main/features/web_apps/preview');
diff --git a/test/main/features/web_apps.test.ts b/test/main/features/web_apps.test.ts
index 93a0a1b9..1ee2f8d2 100644
--- a/test/main/features/web_apps.test.ts
+++ b/test/main/features/web_apps.test.ts
@@ -101,7 +101,7 @@ describe('Web app capability journeys', () => {
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 b = { ...bundle('stalled-query', ['data']), appType: 'web' as const, manifest: { sdkVersion: 1, capabilities: ['data'], data: definition } };
const workers = new Set<unknown>();
let stall = false;
const post = Worker.prototype.postMessage;
@@ -124,10 +124,10 @@ describe('Web app capability journeys', () => {
} finally { spy.mockRestore(); }
});
- it('lets a local app describe the method shown in its supplied discovery example', async () => {
+ it('lets a web 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 app = runtime.open(uid, 1, { ...bundle('cloud-discovery-example', []), appType: 'web' });
+ const supplied = await 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 });
@@ -135,26 +135,26 @@ describe('Web app capability journeys', () => {
expect(host.tools).not.toHaveBeenCalled();
});
- it.each(['local'] as const)('serves the matching %s authoring contract and invalidates it on closure', async appType => {
+ it.each(['local', 'web'] 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);
+ const result = await 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);
+ expect((await 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 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='web';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 b={...bundle('common',['data']),appType:'web' 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'}]});
@@ -173,15 +173,16 @@ describe('Web app capability journeys', () => {
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('denies cloud host calls using trusted bundle type even after the page changes its manifest',async()=>{
+ const b={...bundle('cloud',[]),appType:'web' as const};
+ const opened=runtime.open(uid,1,b);
+ (b.manifest as any).capabilities.push('ai','storage');
+ for(const [method,args] of [['ai.generate',{prompt:'No spend'}],['storage.set',{key:'private',value:1}],['tools.list',{}]] as const)
+ await expect(call(opened.token,method,args)).rejects.toMatchObject({code:'E_UNAVAILABLE'});
+ expect(host.generate).not.toHaveBeenCalled();expect(host.tools).not.toHaveBeenCalled();
+ const catalog=await call(opened.token,'capabilities.list');
+ expect(catalog.methods.some((m:any)=>m.name.startsWith('storage.')||m.name.startsWith('ai.')||m.name.startsWith('tools.'))).toBe(false);
});
-
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';
@@ -266,12 +267,12 @@ describe('Web app capability journeys', () => {
expect(await call(b.token,'storage.get',{key:'private'})).toEqual({value:null});
await expect(runtime.call(uid,2,a.token,'foreign','storage.keys',{})).rejects.toMatchObject({code:'E_CLOSED'});
const hostname=new URL(a.url).host;
- expect(runtime.resource(hostname,'index.html','chat-app://foreign')).toBeNull();
- expect(runtime.resource(hostname,'../private',null)).toBeNull();
+ expect(await runtime.resource(hostname,'index.html','chat-app://foreign')).toBeNull();
+ expect(await runtime.resource(hostname,'../private',null)).toBeNull();
runtime.closeUser(uid); uid='account-b';
await expect(call(a.token,'storage.keys')).rejects.toMatchObject({code:'E_CLOSED'});
expect(await call(open().token,'storage.get',{key:'private'})).toEqual({value:null});
- expect(runtime.resource(hostname,'index.html',null)).toBeNull();
+ expect(await runtime.resource(hostname,'index.html',null)).toBeNull();
});
it('reads only selected snapshots and exports real bytes without overwriting existing files', async () => {
const source=path.join(root,'source.txt'), output=path.join(root,'export.txt'); await fs.writeFile(source,'Original α');
@@ -460,7 +461,7 @@ describe('Web app resource lifetime and contention', () => {
expect(await call(a.token, 'storage.get', { key: 'draft' })).toEqual({ value: 'Still working' });
await call(a.token, 'permissions.revoke');
await expect(call(a.token, 'storage.keys')).rejects.toMatchObject({ code: 'E_CLOSED' });
- expect(runtime.resource(new URL(a.url).host, 'index.html', null)).toBeNull();
+ expect(await runtime.resource(new URL(a.url).host, 'index.html', null)).toBeNull();
} finally { time.mockRestore(); }
});
});
@@ -1009,9 +1010,17 @@ it('shares initial host discovery across concurrent requests and cancels all wor
} finally { vi.useRealTimers(); }
});
+it('cannot obtain hosted publication authority from a standalone browser',async()=>{
+ const {runInNewContext}=await import('node:vm');const {sdkScript}=await import('../../../src/main/features/web_apps/resources');
+ const fetch=vi.fn(),window:any={addEventListener:vi.fn()};window.parent=window;
+ runInNewContext(sdkScript('web'),{window,location:{protocol:'https:',hostname:'example.invalid'},document:{currentScript:null,documentElement:{lang:'en'}},navigator:{language:'en'},crypto:(await import('node:crypto')).webcrypto,fetch,AbortController,setTimeout,clearTimeout});
+ await expect(window.orkasApp.data.insert({table:'messages',values:{body:'Keep private'}})).rejects.toMatchObject({code:'E_HOST_UNAVAILABLE'});
+ expect(fetch).not.toHaveBeenCalled();
+});
+
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);
+ const b=bundle('conformance',['data']);b.appType='web';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);}
@@ -1021,7 +1030,7 @@ it('matches the shared independent data contract fixtures through the real brows
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);
+ const b=bundle('group-boundary',['data']);b.appType='web';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'});
});
@@ -1029,14 +1038,43 @@ it('fails grouped analytics explicitly when more than one hundred groups match',
// 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',
+const webBundle = (name: string, data?: any): Bundle => ({ ...bundle(name, data ? ['data'] : []), appType: 'web',
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' }));
+it('denies every registered host method to a web app before any host adapter or sandbox write runs', async () => {
+ const { METHODS } = await import('../../../src/main/features/web_apps/catalog');
+ const { webAppSandboxRoot } = await import('../../../src/main/paths');
+ const hostOnly = Object.keys(METHODS).filter(name => !WEB_COMMON_V1.includes(name));
+ // Guard the derived list: new registry entries are covered automatically,
+ // and an empty or truncated list cannot make this case pass vacuously.
+ expect(hostOnly).toEqual(expect.arrayContaining(['storage.set', 'appFiles.writeText', 'files.pick', 'files.saveAs', 'ai.generate', 'tools.list', 'tools.call', 'permissions.revoke']));
+ const b = webBundle('web-registry'); const app = runtime.open(uid, 1, b);
+ for (const name of hostOnly) {
+ await expect(call(app.token, name, (METHODS as any)[name].example), name).rejects.toMatchObject({ code: 'E_UNAVAILABLE' });
+ }
for (const adapter of [host.pick, host.save, host.generate, host.tools]) expect(adapter).not.toHaveBeenCalled();
+ for (const scope of ['local', 'cloud'] as const) expect(nativeFs.existsSync(webAppSandboxRoot(uid, b.key, scope))).toBe(false);
+ // permissions.revoke was denied, so the instance is still open and usable.
+ expect(await call(app.token, 'host.getContext')).toMatchObject({ sdkVersion: 1 });
+});
+
+it('serves a web app only the common SDK surface inside Orkas: no bridge script, no host stubs, no host schemas', async () => {
+ const { runInNewContext } = await import('node:vm');
+ const { appResource } = await import('../../../src/main/features/web_apps/resources');
+ const { METHODS } = await import('../../../src/main/features/web_apps/catalog');
+ const app = runtime.open(uid, 1, webBundle('web-resources'));
+ const at = (rel: string) => appResource(new Request(new URL('/' + rel, app.url)), runtime);
+ expect(await at('__orkas/bridge.js')).toEqual({ status: 403 });
+ const sdk = await at('__orkas/sdk.js'); expect(sdk?.status).toBe(200);
+ const parent = { postMessage: vi.fn() }, window: any = { addEventListener: vi.fn(), parent };
+ runInNewContext(sdk!.body!, { window, parent, location: { protocol: 'chat-app:', hostname: new URL(app.url).host }, crypto: (await import('node:crypto')).webcrypto, setTimeout, clearTimeout });
+ const exposed = Object.entries(window.orkasApp).flatMap(([group, value]) => value && typeof value === 'object' ? Object.keys(value as object).map(method => `${group}.${method}`) : []);
+ expect(exposed.sort()).toEqual(WEB_COMMON_V1);
+ for (const name of Object.keys(METHODS).filter(name => !WEB_COMMON_V1.includes(name))) {
+ await expect(call(app.token, 'capabilities.describe', { method: name }), name).rejects.toMatchObject({ code: 'E_METHOD' });
+ }
+ expect(await call(app.token, 'capabilities.describe', { method: 'data.insertIf' })).toMatchObject({ name: 'data.insertIf', appTypes: ['local', 'web'] });
});
it('matches the shared stateful data scenarios: retries, relations, read filters, capacity and stable pages', async () => {
@@ -1090,7 +1128,7 @@ it('isolates formal data by application and account and closes the previous acco
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 => {
+it.each(['local', 'web'] 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' } });
diff --git a/test/main/ipc/saved-app-delete-recycle.test.ts b/test/main/ipc/saved-app-delete-recycle.test.ts
index 973e607d..6551fb4a 100644
--- a/test/main/ipc/saved-app-delete-recycle.test.ts
+++ b/test/main/ipc/saved-app-delete-recycle.test.ts
@@ -19,6 +19,15 @@ vi.mock('../../../src/main/model/client', () => ({
async *streamChatWithModel() { yield { type: 'done' }; },
async chatWithModel() { return { ok: true, text: '' }; },
}));
+// Deletion now verifies publication for every saved app, including legacy local metadata.
+vi.mock('../../../src/main/features/account/state', () => ({ isSessionVerified: () => true }));
+vi.mock('../../../src/main/features/account/token_store', () => ({
+ getSession: () => ({ user_id: 'uSavedAppDeleteRecycle', session_id: 'synthetic' }),
+ isCurrentSession: () => true,
+}));
+vi.mock('../../../src/main/features/account/http', async original => ({
+ ...await original<any>(), getJson: async () => ({ok:true,data:{apps:[],quota:{tier:'lite',used:0,limit:3,deadline:0,excess:0}}}),
+}));
vi.mock('node:fs/promises', async importOriginal => {
const actual = await importOriginal<typeof import('node:fs/promises')>();
return { ...actual, rm: vi.fn(actual.rm) };
diff --git a/test/main/ipc/saved-app-path-recovery.test.ts b/test/main/ipc/saved-app-path-recovery.test.ts
new file mode 100644
index 00000000..5a482c3f
--- /dev/null
+++ b/test/main/ipc/saved-app-path-recovery.test.ts
@@ -0,0 +1,107 @@
+/** File-save recovery keeps authorization, identity and data across native dialogs. */
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import * as crypto from 'node:crypto';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { trustedIpcSender } from '../../helpers/trusted-ipc-sender';
+import { drainMainRuntimeForTest } from '../../helpers/drain-main-runtime';
+
+vi.mock('electron', () => ({
+ app: { isPackaged: false },
+ ipcMain: { handle: vi.fn(), on: vi.fn() },
+ dialog: { showSaveDialog: vi.fn(async () => ({ canceled: true, filePath: undefined })) },
+ BrowserWindow: { getAllWindows: vi.fn(() => []), getFocusedWindow: vi.fn(() => null) },
+ shell: { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') },
+ systemPreferences: { getMediaAccessStatus: vi.fn(() => 'granted'), askForMediaAccess: vi.fn(async () => true) },
+}));
+vi.mock('../../../src/main/model/client', () => ({
+ async *streamChatWithModel() { yield { type: 'done' }; },
+ async chatWithModel() { return { ok: true, text: '' }; },
+}));
+const UID = 'uSavedAppPathRecovery';
+let tmpDir: string, previousWorkspace: string | undefined;
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-saved-app-recovery-'));
+ previousWorkspace = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+ vi.clearAllMocks();
+ (await import('../../../src/main/features/users')).activateUser(UID);
+});
+afterEach(async () => {
+ await drainMainRuntimeForTest();
+ if (previousWorkspace === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;
+ else process.env.ORKAS_WORKSPACE_ROOT = previousWorkspace;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function invoke(channel: string, payload: Record<string, unknown>): Promise<any> {
+ const electron = await import('electron') as any;
+ const { register } = await import('../../../src/main/ipc/index');
+ register();
+ const call = electron.ipcMain.handle.mock.calls.find(([name]: [string]) => name === 'orkas.invoke');
+ return call[1]({ sender: trustedIpcSender() }, { channel, payload });
+}
+
+async function sourceWithData() {
+ const workspace=path.join(tmpDir,'workspace'),root=path.join(workspace,'app');
+ fs.mkdirSync(root,{recursive:true});
+ (await import('../../../src/main/features/user_workspace')).setWorkspacePath(UID,workspace);
+ const entry=path.join(root,'index.html'),manifest=path.join(root,'orkas-app.json');
+ const definition:any={version:1,tables:[{id:'notes',name:'notes',fields:[{id:'body',name:'body',type:'string'}],access:{read:['body'],insert:['body']}}]};
+ fs.writeFileSync(entry,'<h1>Original</h1>');fs.writeFileSync(manifest,JSON.stringify({sdkVersion:1,capabilities:['data'],data:definition}));
+ const payload={path:entry};const app=await invoke('savedApps.saveFromPath',payload);expect(app.ok).toBe(true);
+ const {LocalAppData}=await import('../../../src/main/features/web_apps/data');
+ const key=crypto.createHash('sha256').update(JSON.stringify(['saved',app.id])).digest('hex');
+ const file=path.join(tmpDir,UID,'local/web_apps',key,'data.sqlite');
+ const db=new LocalAppData(file,path.join(tmpDir,UID,'local'),definition);try{await db.call('data.insert',{table:'notes',values:{body:'KEEP'}});}finally{await db.close();}
+ const records=async()=>{const db=new LocalAppData(file,path.join(tmpDir,UID,'local'),definition);try{return await db.call('data.query',{table:'notes'});}finally{await db.close();}};
+ fs.writeFileSync(entry,'<h1>Updated</h1>');fs.writeFileSync(manifest,JSON.stringify({sdkVersion:1,capabilities:['data'],data:{version:1,tables:[]}}));
+ return {payload,app,records};
+}
+
+it('opens an untyped app externally and still rejects invalid paths',async()=>{
+ const {app}=await sourceWithData();
+ fs.writeFileSync(path.join(tmpDir,UID,'cloud/saved_apps',app.id,'__orkas-meta.json'),'{}');
+ const {shell}=await import('electron');
+ expect(await invoke('savedApps.openExternal',{appId:app.id})).toMatchObject({ok:true});
+ expect(shell.openPath).toHaveBeenCalledExactlyOnceWith(path.join(tmpDir,UID,'cloud/saved_apps',app.id,'index.html'));
+ for(const appId of ['../outside','missing-app'])
+ expect(await invoke('savedApps.openExternal',{appId})).toMatchObject({ok:false});
+ expect(shell.openPath).toHaveBeenCalledTimes(1);
+});
+
+it('exposes impact/export and applies confirmed file recovery through real IPC',async()=>{
+ const {payload,app,records}=await sourceWithData();
+ expect(await invoke('savedApps.saveFromPath',payload)).toMatchObject({ok:false,code:'app_edit_data_migration'});
+ expect(await records()).toEqual({records:[{body:'KEEP'}]});
+ const impact=await invoke('savedApps.dataImpactFromPath',payload);expect(impact).toMatchObject({ok:true,appId:app.id,records:1});
+ const {dialog}=await import('electron');const exported=path.join(tmpDir,'backup.sqlite');
+ vi.mocked(dialog.showSaveDialog).mockResolvedValue({canceled:false,filePath:exported});
+ expect(await invoke('savedApps.exportDataFromPath',{...payload,appId:impact.appId})).toEqual({ok:true});expect(fs.statSync(exported).size).toBeGreaterThan(0);
+ expect(await invoke('savedApps.saveFromPath',{...payload,mode:'update',recovery:{appId:impact.appId,clearVersion:impact.version,clearFingerprint:impact.fingerprint}})).toMatchObject({ok:true,id:app.id});
+ expect(fs.readFileSync(path.join(tmpDir,UID,'cloud/saved_apps',app.id,'index.html'),'utf8')).toContain('Updated');
+});
+
+it.each(['cancel','account-switch','retarget'] as const)('does not export or clear after %s during the native dialog',async action=>{
+ const {payload,app,records}=await sourceWithData();const {dialog}=await import('electron');
+ const destination=path.join(tmpDir,'blocked-export.sqlite');
+ vi.mocked(dialog.showSaveDialog).mockImplementation(async()=>{
+ if(action==='account-switch')(await import('../../../src/main/features/users')).activateUser('other');
+ if(action==='retarget')expect(await invoke('savedApps.saveFromPath',{...payload,mode:'new'})).toMatchObject({ok:true});
+ return {canceled:action==='cancel',filePath:destination};
+ });
+ const result=await invoke('savedApps.exportDataFromPath',{...payload,appId:app.id});
+ expect(result).toMatchObject(action==='cancel'?{ok:true,canceled:true}:{ok:false});
+ expect(fs.existsSync(destination)).toBe(false);expect(await records()).toEqual({records:[{body:'KEEP'}]});
+});
+
+it('refuses private paths before resolving data or opening a native dialog',async()=>{
+ const {payload,app}=await sourceWithData();const {dialog}=await import('electron');
+ const privateEntry=path.join(tmpDir,UID,'cloud/saved_apps',app.id,'index.html');
+ for(const channel of ['savedApps.dataImpactFromPath','savedApps.exportDataFromPath']) {
+ expect(await invoke(channel,{...payload,path:privateEntry,appId:app.id})).toMatchObject({ok:false});
+ }
+ expect(dialog.showSaveDialog).not.toHaveBeenCalled();
+});
diff --git a/test/main/quality/web-app-sdk-builtin.test.ts b/test/main/quality/web-app-sdk-builtin.test.ts
index 902c16cc..e5712e0b 100644
--- a/test/main/quality/web-app-sdk-builtin.test.ts
+++ b/test/main/quality/web-app-sdk-builtin.test.ts
@@ -95,6 +95,24 @@ describe('Web app authoring package', () => {
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('the documented timestamp query uses declared read authority and returned fields', async () => {
+ const text = fs.readFileSync(path.join(skill, 'references/common.md'), 'utf8');
+ const example = JSON.parse(/```json\n([\s\S]*?)\n```/.exec(text)![1]);
+ const { LocalAppData } = await import('../../../src/main/features/web_apps/data');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-sdk-query-example-'));
+ const definition = { version: 1, tables: [{ id: 'messages', name: 'messages',
+ fields: [{ id: 'body', name: 'body', type: 'string' }], access: example.access }] };
+ const db = new LocalAppData(path.join(dir, 'data.sqlite'), dir, definition as any);
+ try {
+ await db.call('data.insert', { table: 'messages', values: { body: 'Retained' } });
+ const response: any = await db.call('data.query', example.query);
+ expect(response.records).toHaveLength(1);
+ expect(response.records[0].body).toBe('Retained');
+ expect(Number.isFinite(Date.parse(response.records[0].createdAt))).toBe(true);
+ expect(response.records[0]).not.toHaveProperty('id');
+ await expect(db.call('data.query', { ...example.query, fields: ['id'] })).rejects.toMatchObject({ code: 'E_PERMISSION' });
+ } finally { await db.close(); fs.rmSync(dir, { recursive: true, force: true }); }
+ });
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');
diff --git a/test/renderer/app-save-recovery.test.ts b/test/renderer/app-save-recovery.test.ts
new file mode 100644
index 00000000..f8c0c83c
--- /dev/null
+++ b/test/renderer/app-save-recovery.test.ts
@@ -0,0 +1,45 @@
+import {readFileSync} from 'node:fs';
+import {resolve} from 'node:path';
+import vm from 'node:vm';
+import {expect,it,vi} from 'vitest';
+
+const source=readFileSync(resolve(__dirname,'../../src/renderer/modules/app-save-recovery.js'),'utf8');
+for(const artifact of [true,false]) {
+ const channel=artifact?'conversations.artifacts.save':'savedApps.saveFromPath';
+ const args=artifact?{cid:'task',artifactId:'artifact',mode:'auto'}:{path:'/workspace/app/index.html',cid:'task',mode:'auto'};
+ const impactChannel=artifact?'conversations.artifacts.dataImpact':'savedApps.dataImpactFromPath';
+ const exportChannel=artifact?'conversations.artifacts.exportData':'savedApps.exportDataFromPath';
+ const impact={ok:true,appId:'original',version:7,fingerprint:'confirmed-code',tables:[{name:'notes',count:2,fields:['body']}]};
+ const setup=(options:{clear?:boolean;export?:boolean;exportResult?:any;impactResult?:any;throwMigration?:boolean}={})=>{
+ const invoke=vi.fn(async(name:string,payload:any)=>{
+ if(name===impactChannel)return options.impactResult||impact;
+ if(name===exportChannel)return options.exportResult||{ok:true};
+ if(payload.recovery)return {ok:true,id:'original'};
+ if(options.throwMigration)throw Object.assign(new Error('migration'),{code:'app_edit_data_migration'});
+ return {ok:false,code:'app_edit_data_migration'};
+ });
+ const context:any={window:{orkas:{invoke}},uiConfirm:vi.fn(async()=>options.export??true),uiConfirmDanger:vi.fn(async()=>options.clear??true)};
+ vm.createContext(context);vm.runInContext(source,context);
+ return {...context,invoke,save:(payload=args)=>context.window.OrkasAppSave.save(channel,payload,(key:string)=>key)};
+ };
+ it(`${channel}: exports before an explicitly confirmed retry and binds consent to the inspected app`,async()=>{
+ const h=setup();expect(await h.save()).toEqual({ok:true,id:'original'});
+ expect(h.invoke.mock.calls.map(call=>call[0])).toEqual([channel,impactChannel,exportChannel,channel]);
+ expect(h.invoke.mock.calls[2][1]).toMatchObject({appId:'original'});
+ expect(h.invoke.mock.calls[3][1]).toEqual({...args,mode:'update',recovery:{appId:'original',clearVersion:7,clearFingerprint:'confirmed-code'}});
+ expect(h.uiConfirm.mock.calls[0][0].message).toContain('notes: 2 (body)');
+ });
+ it.each([{ok:true,canceled:true},{ok:false,code:'app_edit_data_export_failed'}])(`${channel}: stops on unsuccessful export %j`,async exportResult=>{
+ const h=setup({exportResult});expect(await h.save()).toEqual(exportResult);expect(h.uiConfirmDanger).not.toHaveBeenCalled();expect(h.invoke.mock.calls.filter(call=>call[0]===channel)).toHaveLength(1);
+ });
+ it(`${channel}: canceling clear never retries or reports success`,async()=>{
+ const h=setup({clear:false,export:false});expect(await h.save()).toEqual({ok:true,canceled:true});expect(h.invoke).toHaveBeenCalledTimes(2);
+ });
+ it(`${channel}: cannot recover when the target is missing`,async()=>{
+ const impactResult={ok:false,error:'app_edit_target_missing'},h=setup({impactResult});expect(await h.save()).toEqual(impactResult);expect(h.uiConfirm).not.toHaveBeenCalled();
+ });
+ it(`${channel}: supports structured IPC rejection but never clears on Save as new`,async()=>{
+ const h=setup({throwMigration:true,export:false});expect(await h.save()).toEqual({ok:true,id:'original'});
+ const copy=setup();expect(await copy.save({...args,mode:'new'})).toMatchObject({ok:false});expect(copy.invoke).toHaveBeenCalledTimes(1);expect(copy.uiConfirm).not.toHaveBeenCalled();
+ });
+}
diff --git a/test/renderer/artifact-revisions.test.ts b/test/renderer/artifact-revisions.test.ts
new file mode 100644
index 00000000..e1e77381
--- /dev/null
+++ b/test/renderer/artifact-revisions.test.ts
@@ -0,0 +1,42 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+import { expect, it, vi } from 'vitest';
+import { MiniDocument } from './helpers/mini-dom';
+
+it('refreshes one card for corrections across streamed events and history while keeping independent apps and chats separate', () => {
+ const document = new MiniDocument();
+ const open = vi.fn();
+ const context: any = { document, CSS: { escape: (value: string) => value },
+ MutationObserver: class { observe() {} },
+ window: { addEventListener() {}, OrkasWebAppHost: { open, release: vi.fn() },
+ orkas: { invoke: async () => ({ ok: true, status: 'ok', appType: 'local' }) } } };
+ context.globalThis = context.window;
+ vm.createContext(context);
+ for (const module of ['artifact-security', 'chat-artifact']) vm.runInContext(
+ readFileSync(path.resolve(__dirname, `../../src/renderer/modules/${module}.js`), 'utf8'), context);
+ const bubble = () => { const node = document.createElement('div'); document.body.appendChild(node); return node; };
+ const first = bubble(), next = bubble();
+ const conversation = readFileSync(path.resolve(__dirname, '../../src/renderer/modules/conversation.js'), 'utf8');
+ Object.assign(context, { _normalizeCreatedAgents: () => false, _normalizeCreatedSkills: () => false,
+ _processItemsHaveRenderableLine: () => false, _isInterruptedAssistantMessage: () => false });
+ vm.runInContext(conversation.slice(conversation.indexOf('function _messageRecordHasMountedSidecars('),
+ conversation.indexOf('\nfunction _processItemsHaveRenderableLine(')), context);
+ const mount = (host: any, revision: number, title = 'Chat', id = 'one', cid = 'chat') =>
+ context.window.mountMessageArtifacts(host, [{ id, title, revision, agent_id: 'builder' }], cid);
+ mount(first, 1); mount(first, 1);
+ expect(open).toHaveBeenCalledTimes(1);
+ mount(next, 2, 'Corrected');
+ expect(document.querySelectorAll('.chat-artifact-card')).toHaveLength(1);
+ expect(first.querySelector('iframe')!.dataset.artifactId).toBe('one');
+ expect(first.querySelector('.chat-artifact-title')!.textContent).toBe('Corrected');
+ expect(context._messageRecordHasMountedSidecars({ artifacts: [{ id: 'one' }] }, next, { cid: 'chat' })).toBe(true);
+ expect(context._messageRecordHasMountedSidecars({ artifacts: [{ id: 'one' }] }, next, { cid: 'foreign' })).toBe(false);
+ expect(open).toHaveBeenCalledTimes(2);
+ mount(next, 1, 'Old'); mount(next, 2, 'Corrected');
+ expect(open).toHaveBeenCalledTimes(2);
+ expect(first.querySelector('.chat-artifact-title')!.textContent).toBe('Corrected');
+ mount(next, 1, 'Chat', 'two'); mount(bubble(), 1, 'Chat', 'one', 'other-chat');
+ expect(document.querySelectorAll('.chat-artifact-card')).toHaveLength(3);
+ expect(open).toHaveBeenCalledTimes(4);
+});
diff --git a/test/renderer/artifact-submit.test.ts b/test/renderer/artifact-submit.test.ts
index f25015b8..cd46491c 100644
--- a/test/renderer/artifact-submit.test.ts
+++ b/test/renderer/artifact-submit.test.ts
@@ -16,6 +16,11 @@ function setup(failOpen = false) {
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; } };
+ e.cloneNode = () => Object.assign(element(tag), { dataset: { ...e.dataset }, style: { ...e.style }, className: e.className });
+ e.replaceChild = (next: any, previous: any) => {
+ e.children[e.children.indexOf(previous)] = next; next.parentNode = e;
+ previous.parentNode = null; previous.isConnected = false;
+ };
if (tag === 'iframe') { e.contentWindow = {}; frames.push(e); }
return e;
}
@@ -80,8 +85,8 @@ it('keeps automatic failures in each card and retries only the selected card', a
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();
+ await vi.waitFor(() => expect(h.frames.at(-1).src).toBe('chat-app://app-fixture/index.html'));
+ expect(h.frames.at(-1)._orkasUnavailablePanel).toBeFalsy();
expect(h.frames[1]._orkasUnavailablePanel).toBeTruthy();
});
diff --git a/test/renderer/commercial-entry.test.ts b/test/renderer/commercial-entry.test.ts
index 36453572..a6a2aca1 100644
--- a/test/renderer/commercial-entry.test.ts
+++ b/test/renderer/commercial-entry.test.ts
@@ -67,34 +67,10 @@ describe('commercial entry actions', () => {
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 () => {
+ it('recognizes only an explicit publication refusal receipt', () => {
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();
+ expect(h.api.isFailure({ok:false, code:'E_COMMERCIAL_REQUIRED', feature:'web_apps'})).toBe(true);
+ for (const value of ['Publish requires commercial Orkas', null, {ok:true,code:'E_COMMERCIAL_REQUIRED',feature:'web_apps'},
+ {ok:false,code:'E_COMMERCIAL_REQUIRED',feature:'other'}, {ok:false,code:'E_FAILED',feature:'web_apps'}]) expect(h.api.isFailure(value)).toBeFalsy();
});
});
diff --git a/test/renderer/helpers/apps-renderer.ts b/test/renderer/helpers/apps-renderer.ts
index 35f112fa..5159dbc6 100644
--- a/test/renderer/helpers/apps-renderer.ts
+++ b/test/renderer/helpers/apps-renderer.ts
@@ -100,10 +100,7 @@ export function loadAppsRenderer(options: { invoke: Invoke; lang?: 'zh' | 'en';
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),
diff --git a/test/renderer/save-as-app-entry-visibility.test.ts b/test/renderer/save-as-app-entry-visibility.test.ts
index 0dd3b074..a2438bbd 100644
--- a/test/renderer/save-as-app-entry-visibility.test.ts
+++ b/test/renderer/save-as-app-entry-visibility.test.ts
@@ -1,5 +1,5 @@
// "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
+// file menu. Oracle: docs/test/my-apps-regression.md save entries 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.
@@ -78,10 +78,15 @@ function fileViewer(invoke: (channel: string, payload: any) => Promise<any>) {
const context: any = { window: { orkas: { invoke } }, warnings };
vm.createContext(context);
vm.runInContext(`
- var _viewerSaveAppBtn = { hidden: true, disabled: true };
+ function button() { return { hidden: true, disabled: true, dataset: {}, attributes: {},
+ setAttribute(name, value) { this.attributes[name] = value; } }; }
+ var _viewerSaveAppBtn = button(), _viewerSaveNewAppBtn = button();
var _viewerCurrentPath = null, _viewerCurrentCid = 'conversation-1', _viewerCurrentProjectId = null;
+ var _viewerRenderSeq = 0;
var _viewerLog = { warn: (...args) => warnings.push(args) };
function _isViewerOpen() { return true; }
+ ${extractFunction(viewerSource, '_viewerLabel')}
+ ${extractFunction(viewerSource, '_setViewerButtonLabel')}
${extractFunction(viewerSource, '_viewerFileActionPayload')}
${extractFunction(viewerSource, '_setSaveAppVisible')}
${extractFunction(viewerSource, '_refreshSaveAppButton')}
@@ -90,7 +95,10 @@ function fileViewer(invoke: (channel: string, payload: any) => Promise<any>) {
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 };
+ return {
+ visible: (target: string) => context.previewSaveAppVisible(target) as Promise<boolean>, warnings,
+ copyVisible: () => !context._viewerSaveNewAppBtn.hidden && !context._viewerSaveNewAppBtn.disabled,
+ };
}
class MenuNode {
@@ -147,6 +155,7 @@ describe('Save as app entry visibility by file type', () => {
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.copyVisible()).toBe(false);
expect(viewer.warnings).toEqual([]);
});
@@ -161,6 +170,16 @@ describe('Save as app entry visibility by file type', () => {
expect(await conversationFileMenu(invoke)(path.join(workspace,'index.html'))).toBe(true);
});
+ it('offers a copy only for an eligible source with a saved destination and clears it for the next file', async () => {
+ const viewer = fileViewer(async (channel, payload) => ({
+ ...await inspectionIpc(channel, payload), target: { appId: 'existing-app' },
+ }));
+ expect(await viewer.visible(path.join(workspace, 'app', 'index.html'))).toBe(true);
+ expect(viewer.copyVisible()).toBe(true);
+ expect(await viewer.visible(path.join(workspace, 'app', 'logo.png'))).toBe(false);
+ expect(viewer.copyVisible()).toBe(false);
+ });
+
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'); },
diff --git a/test/renderer/saved-app-telemetry.test.ts b/test/renderer/saved-app-telemetry.test.ts
index cba171d2..e9cb9a9a 100644
--- a/test/renderer/saved-app-telemetry.test.ts
+++ b/test/renderer/saved-app-telemetry.test.ts
@@ -1,9 +1,14 @@
+import { composerAccessorSource } from './composer-test-source';
+import { conversationCacheSource } from './conversation-cache-test-source';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
+const recoverySource = readFileSync(resolve(__dirname, '../../src/renderer/modules/app-save-recovery.js'), 'utf8');
const modulesDir = resolve(__dirname, '../../src/renderer/modules');
+const savedAppsSource = readFileSync(resolve(modulesDir, 'saved-apps.js'), 'utf8');
+const artifactSource = readFileSync(resolve(modulesDir, 'chat-artifact.js'), 'utf8');
const fileViewerSource = readFileSync(resolve(modulesDir, 'chat-file-viewer.js'), 'utf8');
const conversationInfoSource = readFileSync(resolve(modulesDir, 'conversation-info.js'), 'utf8');
@@ -26,6 +31,353 @@ function extractFunction(source: string, name: string): string {
throw new Error(`unterminated ${name}`);
}
+function loadSavedApps(invoke: (channel: string, payload?: any) => Promise<any>, options: {
+ presentationFailure?: boolean;
+} = {}) {
+ const warnings: Array<Record<string, any>> = [];
+ const executable = savedAppsSource.replace(
+ 'window.loadSavedApps = loadSavedApps;',
+ 'window.loadSavedApps = loadSavedApps; window.__savedAppActions = { open: _openApp, edit: _editApp, rename: _renameApp, delete: _deleteApp, create: _createAppTask };',
+ );
+ const context: any = {
+ console,
+ Date,
+ Math,
+ Set,
+ setTimeout: (handler: () => void) => handler(),
+ createLogger: () => ({
+ warn: (_message: string, data: Record<string, any>) => warnings.push(data),
+ error: vi.fn(),
+ }),
+ t: (key: string) => key,
+ uiAlert: vi.fn(),
+ uiPrompt: vi.fn(async () => 'Renamed app'),
+ uiConfirmDanger: vi.fn(async () => true),
+ window: {
+ OrkasArtifactSecurity: {
+ SANDBOX: 'allow-scripts',
+ trustedArtifactMessage: () => false,
+ safeExternalHttpUrl: () => '',
+ },
+ addEventListener: vi.fn(),
+ open: vi.fn(),
+ orkas: { invoke: vi.fn(invoke) },
+ },
+ document: {
+ body: { appendChild: vi.fn() },
+ addEventListener: vi.fn(),
+ createElement: vi.fn(),
+ getElementById: () => {
+ if (options.presentationFailure) throw new Error('/Users/test/private/presentation');
+ return null;
+ },
+ querySelectorAll: () => [],
+ querySelector: () => null,
+ documentElement: { getAttribute: () => 'en' },
+ },
+ navigator: { language: 'en' },
+ };
+ vm.createContext(context);
+ vm.runInContext(recoverySource, context);
+ vm.runInContext(composerAccessorSource, context);
+ vm.runInContext(conversationCacheSource, context);
+ vm.runInContext(executable, context, { filename: 'saved-apps.js' });
+ return { context, warnings };
+}
+
+describe('saved app recovery and privacy', () => {
+
+ it('preserves the creation form when task creation is rejected and reports no private data', async () => {
+ const harness = loadSavedApps(async () => { throw new Error('/private/customer-description'); });
+ harness.context.ensureModelConfigured = () => true;
+ harness.context._autoTitle = (text: string) => text;
+ const close = vi.fn();
+ expect(await harness.context.window.__savedAppActions.create('private customer idea', close, 'web')).toBe(false);
+ expect(close).not.toHaveBeenCalled();
+ expect(harness.context.uiAlert).toHaveBeenCalled();
+ });
+
+ it('reports accepted creation once even when execution later fails', async () => {
+ const harness = loadSavedApps(async () => ({ conversation: { conversation_id: 'new-task' } }));
+ Object.assign(harness.context, {
+ ensureModelConfigured: () => true, _autoTitle: (text: string) => text,
+ conversations: [{ conversation_id: 'new-task', processing: true }],
+ renderConversationList: vi.fn(), setView: vi.fn(), _restoreDraft: vi.fn(), setChatRecipient: vi.fn(),
+ _rememberSentComposerSnapshot: vi.fn(),
+ sendInConversation: vi.fn(async (_cid: string, _prompt: string, _extra: unknown, options: any) => {
+ options.onAccepted(); options.onAccepted();
+ throw new Error('later execution failure');
+ }),
+ });
+ const close = vi.fn();
+ expect(await harness.context.window.__savedAppActions.create('private idea', close)).toBe(true);
+ expect(harness.context.window.orkas.invoke).toHaveBeenCalledWith(
+ 'conversations.create', { title: 'private idea', assistance: { kind: 'app_creation' } },
+ );
+ expect(harness.context.sendInConversation).toHaveBeenCalledWith(
+ 'new-task', 'private idea', { title_text: 'private idea' }, expect.any(Object),
+ );
+ expect(close).toHaveBeenCalledOnce();
+ expect(harness.context.conversations).toHaveLength(1);
+ expect(harness.context.conversations[0]).toMatchObject({ conversation_id: 'new-task', processing: true });
+ expect(harness.context.uiAlert).not.toHaveBeenCalled();
+ });
+
+ it('keeps a refused rename recoverable and hides private diagnostics', async () => {
+ const harness = loadSavedApps(async (channel) => {
+ if (channel === 'savedApps.rename') {
+ return { ok: false, error: '/Users/test/private/saved_apps/secret-app' };
+ }
+ return { apps: [] };
+ });
+
+ await harness.context.window.__savedAppActions.rename('private-app-id');
+ expect(harness.context.window.orkas.invoke).toHaveBeenCalledExactlyOnceWith('savedApps.rename',{appId:'private-app-id',title:'Renamed app'});
+ expect(harness.context.uiAlert).toHaveBeenCalledOnce();
+ const diagnostics = JSON.stringify(harness.warnings);
+ expect(diagnostics).not.toContain('/Users/test');
+ expect(diagnostics).not.toContain('private-app-id');
+ expect(diagnostics).not.toContain('Renamed app');
+ });
+
+ it('keeps edit success when post-create navigation or draft presentation fails', async () => {
+ const harness = loadSavedApps(async (channel) => {
+ if (channel === 'savedApps.openForEditing') {
+ return { ok: true, conversation: { conversation_id: 'private-conversation' } };
+ }
+ return { apps: [] };
+ }, { presentationFailure: true });
+
+ await harness.context.window.__savedAppActions.edit('private-app-id');
+ expect(harness.context.window.orkas.invoke).toHaveBeenCalledExactlyOnceWith('savedApps.openForEditing',{appId:'private-app-id'});
+ expect(harness.context.uiAlert).not.toHaveBeenCalled();
+ expect(harness.warnings).toHaveLength(1);
+ expect(JSON.stringify(harness.warnings)).not.toContain('/Users/test');
+ });
+
+ it('reuses an edit conversation already read by the sidebar while the edit receipt is pending', async () => {
+ let releaseEdit!: (value: unknown) => void;
+ const harness = loadSavedApps(() => new Promise((resolve) => { releaseEdit = resolve; }));
+ Object.assign(harness.context, { conversations: [], renderConversationList: vi.fn(), setView: vi.fn() });
+ const editing = harness.context.window.__savedAppActions.edit('fixture-app');
+ const current = { conversation_id: 'edit-task', title: 'User renamed edit task', title_manually_set: true,
+ created_at: '2026-05-15T09:00:00Z', updated_at: '2026-05-15T09:01:00Z',
+ last_active_at: '2026-05-15T09:01:00Z', processing: false };
+ harness.context._appendConversationSlice([current]);
+ releaseEdit({ ok: true, conversation: { conversation_id: 'edit-task', title: 'Creation title',
+ created_at: '2026-05-15T09:00:00Z', updated_at: '2026-05-15T09:00:00Z' } });
+ await editing;
+ expect(harness.context.conversations).toEqual([current]);
+ expect(harness.context.setView).toHaveBeenCalledExactlyOnceWith('conversation', 'edit-task', { skipLoad: true });
+ expect(harness.warnings).toEqual([]);
+ });
+
+ it('reports a failed open without exposing app identity or raw paths', async () => {
+ const harness = loadSavedApps(async () => {
+ throw new Error('/Users/test/private/saved_apps/app/index.html');
+ });
+
+ await harness.context.window.__savedAppActions.open('private-app-id');
+ expect(harness.context.uiAlert).toHaveBeenCalledWith('Could not open the app');
+ expect(harness.warnings).toHaveLength(1);
+ expect(JSON.stringify(harness.warnings)).not.toMatch(/alice|private-app-id/);
+ });
+
+ it('opens or refocuses one native window per request and recovers from a window failure', async () => {
+ const harness = loadSavedApps(async () => ({ ok: true }));
+ const open = vi.fn(async () => ({ ok: true }));
+ harness.context.window.OrkasPreviewWindows = { open };
+ await harness.context.window.__savedAppActions.open('private-app-id');
+
+ open.mockResolvedValueOnce({ ok: true, reused: true } as any);
+ await harness.context.window.__savedAppActions.open('private-app-id');
+ open.mockResolvedValueOnce({ ok: false } as any);
+ await harness.context.window.__savedAppActions.open('private-app-id');
+ expect(open).toHaveBeenCalledTimes(3);
+ expect(harness.context.window.orkas.invoke).not.toHaveBeenCalled();
+ expect(harness.warnings).toHaveLength(1);
+ });
+
+ it('separates edit saves, declined data migrations, and structured save rejections', async () => {
+ const run = async (invoke: (channel: string, payload: any) => Promise<any>, confirm = { export: false, clear: true }) => {
+ const context: any = {
+ Date, Math, Object,
+ window: { orkas: { invoke: vi.fn(invoke) } },
+ _convLog: { warn: vi.fn() },
+ _notifyFail: vi.fn(),
+ _t: (_key: string, fallback: string) => fallback,
+ uiConfirm: vi.fn(async () => confirm.export),
+ uiConfirmDanger: vi.fn(async () => confirm.clear),
+ uiToast: vi.fn(),
+ loadSavedApps: vi.fn(),
+ };
+ vm.createContext(context);
+ vm.runInContext(recoverySource, context);
+ vm.runInContext([
+ extractFunction(artifactSource, '_artifactSaveFailure'),
+ extractFunction(artifactSource, '_logArtifactFailure'),
+ extractFunction(artifactSource, '_logArtifactSaveFailure'),
+ extractFunction(artifactSource, '_doSave'),
+ ].join('\n'), context);
+ await context._doSave({ cid: 'private-cid', artifactId: 'private-artifact', saveMode: 'update' });
+ return context;
+ };
+ const migration = { ok: false, code: 'app_edit_data_migration', error: '/Users/test/private' };
+ const impact = { ok: true, tables: [{ name: 'private_table', count: 2, fields: ['private_field'] }], version: 1, fingerprint: 'f' };
+ const success = await run(async (channel) => (channel === 'conversations.artifacts.dataImpact' ? impact : { ok: true }));
+ expect(success.loadSavedApps).toHaveBeenCalledOnce();
+ const canceled = await run(async (channel) => (channel === 'conversations.artifacts.dataImpact' ? impact : migration), { export: false, clear: false });
+ expect(canceled.loadSavedApps).not.toHaveBeenCalled(); expect(canceled._notifyFail).not.toHaveBeenCalled();
+ const rejected = await run(async () => ({ ok: false, code: 'app_type_mismatch', error: 'Private message' }));
+ expect(rejected.loadSavedApps).not.toHaveBeenCalled(); expect(rejected._notifyFail).toHaveBeenCalledOnce();
+ });
+
+ it('keeps artifact save success when toast presentation fails', async () => {
+ const warnings: any[] = [];
+ const context: any = {
+ Date,
+ Math,
+ Object,
+ window: { orkas: { invoke: vi.fn(async () => ({ ok: true })) } },
+ _convLog: { warn: (_message: string, payload: any) => warnings.push(payload) },
+ _notifyFail: vi.fn(),
+ _t: (_key: string, fallback: string) => fallback,
+ uiToast: () => { throw new Error('/Users/test/private/toast'); },
+ loadSavedApps: vi.fn(),
+ };
+ vm.createContext(context);
+ vm.runInContext(recoverySource, context);
+ vm.runInContext(composerAccessorSource, context);
+ vm.runInContext([
+ extractFunction(artifactSource, '_artifactSaveFailure'),
+ extractFunction(artifactSource, '_logArtifactFailure'),
+ extractFunction(artifactSource, '_logArtifactSaveFailure'),
+ extractFunction(artifactSource, '_doSave'),
+ ].join('\n'), context);
+
+ await context._doSave({ cid: 'private-cid', artifactId: 'private-artifact' });
+ expect(context._notifyFail).not.toHaveBeenCalled();
+ expect(context.window.orkas.invoke).toHaveBeenCalledOnce();
+ expect(JSON.stringify(warnings)).not.toMatch(/alice|private-cid|private-artifact/);
+ });
+
+ it.each([false,true])('does not replay a file-preview save after cancellation or failed toast (canceled: %s)', async canceled => {
+ const warnings: any[] = [];
+ const context: any = {
+ Date,
+ Math,
+ Object,
+ _viewerRenderSeq: 1,
+ _viewerCurrentPath: '/Users/test/private/app.html',
+ _viewerCurrentCid: 'private-cid',
+ _viewerCurrentProjectId: null,
+ _viewerSaveAppBtn: { disabled: false, innerHTML: '' },
+ _viewerDirty: false,
+ _kindOf: () => 'html',
+ _viewerLogFailure: (name: string, payload: any) => warnings.push({ name, payload }),
+ _viewerShowAlert: vi.fn(),
+ _viewerLabel: (_key: string, fallback: string) => fallback,
+ _viewerSaveAppButtonHtml: () => '<button>',
+ _setSaveAppVisible: vi.fn(),
+ _viewerFileActionPayload: () => ({ path: '/Users/test/private/app.html' }),
+ _scheduleSaveAppButtonRestore: vi.fn(),
+ window: { orkas: { invoke: vi.fn(async () => ({ ok: true, canceled })) } },
+ uiToast: () => { throw new Error('/Users/test/private/toast'); },
+ loadSavedApps: vi.fn(),
+ };
+ vm.createContext(context);
+ vm.runInContext(recoverySource, context);
+ vm.runInContext(composerAccessorSource, context);
+ vm.runInContext([
+ extractFunction(fileViewerSource, '_viewerStableFailure'),
+ extractFunction(fileViewerSource, '_viewerDurationSince'),
+ extractFunction(fileViewerSource, '_onSaveAppClick'),
+ ].join('\n'), context);
+
+ await context._onSaveAppClick();
+ expect(context.window.orkas.invoke).toHaveBeenCalledExactlyOnceWith('savedApps.saveFromPath',{path:'/Users/test/private/app.html'});
+ expect(context._viewerShowAlert).not.toHaveBeenCalled();
+ expect(warnings).toHaveLength(canceled?0:1);
+ expect(JSON.stringify(warnings)).not.toContain('/Users/test');
+ });
+
+ it('does not replay a completed Library import when its button presentation fails', async () => {
+ const warnings: any[] = [];
+ const button: any = { disabled: false };
+ Object.defineProperty(button, 'innerHTML', {
+ get: () => '',
+ set: () => { throw new Error('/Users/test/private/button'); },
+ });
+ const context: any = {
+ Date,
+ Math,
+ Object,
+ _viewerRenderSeq: 1,
+ _viewerCurrentPath: '/Users/test/private/note.md',
+ _viewerCurrentCid: 'private-cid',
+ _viewerCurrentProjectId: null,
+ _viewerLibraryProjectScoped: false,
+ _viewerAddLibraryBtn: button,
+ _viewerCanAddToLibrary: () => true,
+ _kindOf: () => 'markdown',
+ _viewerLogFailure: (name: string, payload: any) => warnings.push({ name, payload }),
+ _viewerShowAlert: vi.fn(),
+ _viewerLabel: (_key: string, fallback: string) => fallback,
+ _viewerAddLibraryButtonHtml: () => '<button>',
+ _scheduleAddLibraryButtonRestore: vi.fn(),
+ window: { orkas: { invoke: vi.fn(async () => ({ ok: true, scope: 'global' })) } },
+ currentView: 'contexts',
+ loadContexts: vi.fn(),
+ };
+ vm.createContext(context);
+ vm.runInContext(recoverySource, context);
+ vm.runInContext(composerAccessorSource, context);
+ vm.runInContext([
+ extractFunction(fileViewerSource, '_viewerStableFailure'),
+ extractFunction(fileViewerSource, '_viewerDurationSince'),
+ extractFunction(fileViewerSource, '_onAddLibraryClick'),
+ ].join('\n'), context);
+
+ await context._onAddLibraryClick();
+ expect(context.window.orkas.invoke).toHaveBeenCalledExactlyOnceWith('library.importProduced',{path:'/Users/test/private/note.md',cid:'private-cid'});
+ expect(context._viewerShowAlert).not.toHaveBeenCalled();
+ expect(warnings).toHaveLength(1);
+ expect(JSON.stringify(warnings)).not.toContain('/Users/test');
+ });
+
+ it.each([false,true])('does not replay a conversation save after cancellation or failed toast (canceled: %s)', async canceled => {
+ const warnings: any[] = [];
+ const context: any = {
+ Date,
+ Math,
+ Object,
+ window: {
+ orkas: { invoke: vi.fn(async () => ({ ok: true, canceled })) },
+ },
+ _infoLog: { warn: (_message: string, payload: any) => warnings.push(payload) },
+ _fileActionPayload: () => ({ path: '/Users/test/private/app.html' }),
+ _label: (_key: string, fallback: string) => fallback,
+ uiToast: () => { throw new Error('/Users/test/private/toast'); },
+ loadSavedApps: vi.fn(),
+ };
+ vm.createContext(context);
+ vm.runInContext(recoverySource, context);
+ vm.runInContext(composerAccessorSource, context);
+ vm.runInContext([
+ extractFunction(conversationInfoSource, '_baseName'),
+ extractFunction(conversationInfoSource, '_extForName'),
+ extractFunction(conversationInfoSource, '_savedAppSaveFailure'),
+ extractFunction(conversationInfoSource, '_logSavedAppSaveFailure'),
+ extractFunction(conversationInfoSource, '_saveEntryAsApp'),
+ ].join('\n'), context);
+
+ await context._saveEntryAsApp('/Users/test/private/app.html', 'private-cid', 'file');
+ expect(context.window.orkas.invoke).toHaveBeenCalledExactlyOnceWith('savedApps.saveFromPath',{path:'/Users/test/private/app.html'});
+ expect(warnings).toHaveLength(canceled?0:1);
+ expect(JSON.stringify(warnings)).not.toMatch(/alice|private-cid/);
+ });
+});
+
describe('Save-as-App failure alerts', () => {
// Raw IPC/main errors can carry absolute local paths and English internals;
// the user sees only the localized action copy, and logs stay code-only.
@@ -45,6 +397,7 @@ describe('Save-as-App failure alerts', () => {
const context: any = {
Date, Math, Object, String,
t: (key: string) => table[key] || key,
+ _viewerRenderSeq: 1,
_viewerCurrentPath: '/Users/test/private/project/app.html',
_viewerSaveAppBtn: { disabled: false, innerHTML: '' },
_viewerDirty: false,
@@ -58,6 +411,7 @@ describe('Save-as-App failure alerts', () => {
window: { orkas: { invoke: vi.fn(invoke) } },
};
vm.createContext(context);
+ vm.runInContext(recoverySource, context);
vm.runInContext([
extractFunction(fileViewerSource, '_viewerLabel'),
extractFunction(fileViewerSource, '_viewerStableFailure'),
@@ -79,12 +433,13 @@ describe('Save-as-App failure alerts', () => {
const context: any = {
Date, Math, Object, String,
t: (key: string) => table[key] || key,
- window: { orkas: { invoke: vi.fn(invoke) } },
+ window: {orkas:{invoke:vi.fn(invoke)}},
_infoLog: { warn: (_message: string, payload: any) => warnings.push(payload) },
_fileActionPayload: () => ({ path: '/Users/test/private/project/app.html' }),
uiAlert: async (message: string) => { alerts.push(message); },
};
vm.createContext(context);
+ vm.runInContext(recoverySource, context);
vm.runInContext([
extractFunction(conversationInfoSource, '_label'),
extractFunction(conversationInfoSource, '_baseName'),
@@ -94,45 +449,9 @@ describe('Save-as-App failure alerts', () => {
extractFunction(conversationInfoSource, '_saveEntryAsApp'),
].join('\n'), context);
- await context._saveEntryAsApp('/Users/test/private/project/app.html', 'private-cid');
+ await context._saveEntryAsApp('/Users/test/private/project/app.html', 'private-cid', 'file');
expect(alerts).toEqual([table[_mode === 'root_refused' ? 'apps.save_root_folder_required' : 'apps.save_failed']]);
expect(JSON.stringify(warnings)).not.toContain('/Users/');
});
});
-
-
-describe('historical web receipts at file entry points', () => {
- it.each(['preview save', 'conversation save', 'preview open'])('guides once without a generic error or local success effects: %s', async entry => {
- const receipt = { ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' };
- const show = vi.fn(async () => {}), alert = vi.fn(), warn = vi.fn(), restore = vi.fn();
- const invoke = vi.fn(async () => receipt);
- const context: any = {
- window: { orkas: { invoke }, OrkasPreviewWindows: { open: invoke, options: () => ({}) } },
- _viewerCurrentPath: '/fixture/app.html', _viewerSaveAppBtn: { disabled: false }, _viewerDirty: false,
- _viewerLabel: (_key: string, fallback: string) => fallback,
- _viewerSaveAppButtonHtml: () => '<button>', _setSaveAppVisible: vi.fn(),
- _viewerFileActionPayload: () => ({ path: '/fixture/app.html' }),
- _fileActionPayload: () => ({ path: '/fixture/app.html' }),
- _scheduleSaveAppButtonRestore: restore, _viewerShowAlert: alert, uiAlert: alert,
- _viewerLogFailure: warn, _logSavedAppSaveFailure: warn,
- _ensureViewerFileExists: async () => true, _kindOf: () => 'html',
- };
- vm.createContext(context);
- vm.runInContext(readFileSync(resolve(modulesDir, 'commercial-entry.js'), 'utf8'), context);
- context.window.OrkasCommercialEntry.show = show;
- if (entry === 'conversation save') {
- vm.runInContext(extractFunction(conversationInfoSource, '_saveEntryAsApp'), context);
- await context._saveEntryAsApp('/fixture/app.html', 'task');
- } else if (entry === 'preview save') {
- vm.runInContext(extractFunction(fileViewerSource, '_onSaveAppClick'), context);
- await context._onSaveAppClick();
- expect(restore).toHaveBeenCalledExactlyOnceWith('/fixture/app.html', '<button>');
- } else {
- vm.runInContext(extractFunction(fileViewerSource, 'openChatFileViewer'), context);
- await expect(context.openChatFileViewer('/fixture/app.html')).resolves.toBe(receipt);
- }
- expect(show).toHaveBeenCalledOnce(); expect(invoke).toHaveBeenCalledOnce();
- expect(alert).not.toHaveBeenCalled(); expect(warn).not.toHaveBeenCalled();
- });
-});
diff --git a/test/renderer/saved-apps-journeys.test.ts b/test/renderer/saved-apps-journeys.test.ts
index f4c234f7..5fd25089 100644
--- a/test/renderer/saved-apps-journeys.test.ts
+++ b/test/renderer/saved-apps-journeys.test.ts
@@ -50,19 +50,16 @@ describe('My Apps list refresh', () => {
});
});
-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');
+describe('My Apps publication entry', () => {
+ it.each(['local', 'web', 'cloud'])('keeps a %s app and its draft when publication guidance is cancelled', async appType => {
+ const h = await openPanel(apps([{ id: 'app-weather', title: 'Weather', appType, savedAt }]));
+ await h.chooseMenuAction('app-weather', 'publish');
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.dialogText(dialog)).toBe(h.context.t('apps.commercial_required'));
expect(h.channels()).toEqual(['savedApps.list']);
+ dialog.querySelector('[data-act="cancel"]')!.click(); await flush();
+ expect(h.openDialogs()).toHaveLength(0); expect(h.cards()).toEqual(['app-weather']);
+ expect(h.warnings).toEqual([]);
});
});
@@ -145,15 +142,11 @@ describe('My Apps edit', () => {
});
});
-describe('My Apps creation type', () => {
- it.each(['cancel', 'escape', 'backdrop'])('retains the idea and selected type after %s without creating a task', async dismissal => {
+describe('My Apps unified creation', () => {
+ it.each(['cancel', 'escape', 'backdrop'])('retains the idea 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');
@@ -161,7 +154,7 @@ describe('My Apps creation type', () => {
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-app-type]')).toBeNull();
expect(h.$('[data-create-submit]')!.disabled).toBe(false);
expect(h.channels()).toEqual(['savedApps.list']);
});
@@ -178,10 +171,7 @@ describe('My Apps creation type', () => {
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) => {
+ it('creates an app without asking for a runtime type', async () => {
const accepted = deferred();
const h = await openPanel(apps([], channel => {
if (channel !== 'conversations.create') throw new Error('unexpected IPC');
@@ -193,23 +183,21 @@ describe('My Apps creation type', () => {
_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();
+ expect(overlay.querySelector('[data-app-type]')).toBeNull();
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 } }],
+ ['conversations.create', { title: 'Habit tracker', assistance: { kind: 'app_creation', appType: 'local' } }],
]);
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');
+ expect(h.$('[data-app-type]')).toBeNull();
});
});
@@ -258,3 +246,11 @@ describe('My Apps failure alerts', () => {
expect(h.cards()).toEqual(['app-budget']);
});
});
+
+ it('shows old local and web apps together and offers publishing for both', async () => {
+ const h = await openPanel(apps([budget,{id:'old-web',title:'Web',appType:'web',savedAt}]));
+ expect(h.cards()).toEqual(['app-budget','old-web']);
+ expect(h.$('[data-app-filter]')).toBeNull();
+ h.card('app-budget')!.querySelector('[data-app-more]')!.click();
+ expect(h.$('.app-row-menu [data-action="publish"]')).not.toBeNull();
+});