pi-web-ui 0.114.3 → 0.116.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/bin/pi-web-ui.mjs +90 -8
  3. package/dist/gh-comment-781.md +5 -0
  4. package/dist/server/agent-service-daemon.js +522 -32
  5. package/dist/server/agent-service.js +954 -402
  6. package/dist/server/canvas/canvas-dispatch.js +13 -1
  7. package/dist/server/client-state.js +42 -2
  8. package/dist/server/communicate-tool.js +2 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +100 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +362 -13
  16. package/dist/server/device-center/collab-tool.js +824 -13
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +20 -0
  22. package/dist/server/device-center/execution-settings.js +213 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +392 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +186 -96
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +210 -0
  30. package/dist/server/device-center/group-context.js +179 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +233 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub-locks.js +320 -0
  37. package/dist/server/device-center/hub-page.js +13 -33
  38. package/dist/server/device-center/hub-webhooks.js +165 -0
  39. package/dist/server/device-center/hub.js +2379 -107
  40. package/dist/server/device-center/human-interaction.js +232 -0
  41. package/dist/server/device-center/integration-errors.js +25 -0
  42. package/dist/server/device-center/local-hub.js +20 -1
  43. package/dist/server/device-center/local-page.js +17 -0
  44. package/dist/server/device-center/local.js +430 -41
  45. package/dist/server/device-center/main.js +11 -1
  46. package/dist/server/device-center/partition-log.js +293 -0
  47. package/dist/server/device-center/path-portal.js +11 -3
  48. package/dist/server/device-center/relay.js +364 -35
  49. package/dist/server/device-center/report-metadata.js +66 -0
  50. package/dist/server/device-center/report-upload.js +63 -0
  51. package/dist/server/device-center/runtime.js +598 -41
  52. package/dist/server/device-center/smoke-preview.js +3 -0
  53. package/dist/server/device-center/store.js +203 -41
  54. package/dist/server/device-center/task-context-budget.js +161 -0
  55. package/dist/server/device-center/task-journal.js +385 -0
  56. package/dist/server/device-center/task-plan.js +33 -0
  57. package/dist/server/device-center/task-progress.js +141 -0
  58. package/dist/server/device-center/task-recovery.js +452 -0
  59. package/dist/server/device-center/task-report-outbox.js +216 -0
  60. package/dist/server/device-center/task-report.js +384 -0
  61. package/dist/server/device-center/task-scheduler.js +445 -0
  62. package/dist/server/device-center/task-state.js +333 -0
  63. package/dist/server/device-center/transfer-stream.js +1006 -0
  64. package/dist/server/device-center/transfers.js +841 -8
  65. package/dist/server/dispatch-domain-handlers.js +35 -6
  66. package/dist/server/dsh/dsh-agent-service.js +6 -0
  67. package/dist/server/durable/durable-capabilities.js +11 -0
  68. package/dist/server/engine-probe.js +112 -1
  69. package/dist/server/global-loader.js +119 -19
  70. package/dist/server/goal-service.js +10 -5
  71. package/dist/server/index.js +222 -29
  72. package/dist/server/managed.js +2 -0
  73. package/dist/server/markers/builtins/services.js +123 -0
  74. package/dist/server/markers/builtins/todo.js +189 -0
  75. package/dist/server/markers-list-tool.js +34 -0
  76. package/dist/server/message-deletion.js +40 -0
  77. package/dist/server/message-window.js +9 -0
  78. package/dist/server/model-admin.js +48 -6
  79. package/dist/server/model-enrich.js +10 -1
  80. package/dist/server/orchestrator.js +109 -0
  81. package/dist/server/patch-executable-lookup.js +396 -0
  82. package/dist/server/payload-limits.js +2 -0
  83. package/dist/server/plugin-llm.js +100 -9
  84. package/dist/server/plugins.js +65 -7
  85. package/dist/server/preset-fields.js +24 -0
  86. package/dist/server/preset-share.js +2 -0
  87. package/dist/server/prompt-base-store.js +85 -0
  88. package/dist/server/prompt-composer.js +44 -2
  89. package/dist/server/protocol-version.js +1 -1
  90. package/dist/server/protocol.js +2 -2
  91. package/dist/server/reasoning-registry.js +207 -0
  92. package/dist/server/remote-ssh-service.js +22 -9
  93. package/dist/server/resolve-global-sdk.js +2 -0
  94. package/dist/server/session-search.js +1 -1
  95. package/dist/server/settings-service.js +90 -39
  96. package/dist/server/skill-content-filler.js +29 -8
  97. package/dist/server/skill-tool.js +12 -3
  98. package/dist/server/startup-banner.js +35 -0
  99. package/dist/server/subagent-helpers.js +4 -1
  100. package/dist/server/subagents.js +52 -37
  101. package/dist/server/system-prompt-soul.js +41 -0
  102. package/dist/server/tool-host-factories.js +1 -0
  103. package/dist/server/tool-manager.js +17 -9
  104. package/dist/server/unauthorized-page.js +319 -0
  105. package/dist/server/univer-service.js +448 -0
  106. package/dist/server/universal/drivers/dsh-driver.js +379 -0
  107. package/dist/server/universal/universal-session.js +5 -0
  108. package/dist/server/webui-context.js +25 -5
  109. package/dist/test-artifact.md +9 -0
  110. package/dist/test-preview-modal.md +11 -0
  111. package/dist/test-report.html +20 -0
  112. package/docs/README.md +94 -0
  113. package/docs/architecture-plugins.md +946 -0
  114. package/docs/device-center.md +106 -12
  115. package/docs/dsh-engine.md +10 -10
  116. package/extensions/webui.ts +43 -1
  117. package/package.json +2 -1
  118. package/themes/aetheris.css +5 -0
  119. package/themes/ayu-light.css +6 -0
  120. package/themes/bases/flow-base.css +68 -68
  121. package/themes/catppuccin-latte.css +6 -0
  122. package/themes/catppuccin.css +6 -0
  123. package/themes/claude-code-dark.css +5 -0
  124. package/themes/codex.css +6 -0
  125. package/themes/cyberpunk.css +6 -0
  126. package/themes/dark-teal.css +6 -1
  127. package/themes/dazzle.css +6 -0
  128. package/themes/everforest-light.css +6 -0
  129. package/themes/flow-light.css +8 -1
  130. package/themes/flow.css +6 -1
  131. package/themes/geist.css +6 -0
  132. package/themes/gruvbox-light.css +6 -0
  133. package/themes/kanagawa-lotus.css +6 -0
  134. package/themes/md-preview.css +6 -0
  135. package/themes/mist.css +6 -0
  136. package/themes/nord.css +6 -0
  137. package/themes/one-dark.css +6 -0
  138. package/themes/paper.css +6 -0
  139. package/themes/rose-pine-dawn.css +6 -0
  140. package/themes/sakura.css +6 -0
  141. package/themes/solarized-light.css +6 -0
  142. package/themes/tokyo-night.css +6 -0
  143. package/themes/translucent.css +6 -0
  144. package/themes/transparent.css +6 -0
  145. package/themes/vs-code-dark.css +5 -0
  146. package/themes/wallpaper-flow.css +5 -1
  147. package/themes/wallpaper-obsidian.css +6 -0
  148. package/themes/white.css +6 -0
  149. package/themes/zhujian-dark.css +6 -1
  150. package/themes/zhujian.css +6 -1
  151. package/themes/zhupi-dark.css +6 -1
  152. package/themes/zhupi.css +6 -1
  153. package/web/dist/.build-assets.json +1 -1
  154. package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
  155. package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
  156. package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
  157. package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
  158. package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
  159. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
  160. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
  161. package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
  162. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
  163. package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
  164. package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
  165. package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
  166. package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
  167. package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
  168. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
  169. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
  170. package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
  171. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
  172. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
  173. package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
  174. package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
  175. package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
  176. package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
  177. package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
  178. package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
  179. package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
  180. package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
  181. package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
  182. package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
  183. package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
  184. package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
  185. package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
  186. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  187. package/web/dist/assets/index-C6DwztqE.css +1 -0
  188. package/web/dist/assets/index-CuN802Sj.js +93 -0
  189. package/web/dist/assets/index-EH5Fw9fa.js +93 -0
  190. package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
  191. package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
  192. package/web/dist/assets/theme-D2l_mLNo.js +1 -0
  193. package/web/dist/index.html +10 -9
  194. package/web/dist/sw.js +1 -1
  195. package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
  196. package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
  197. package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
  198. package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
  199. package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
  200. package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
  201. package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
  202. package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
  203. package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
  204. package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
  205. package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
  206. package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
  207. package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
  208. package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
  209. package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
  210. package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
  211. package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
  212. package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
  213. package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
  214. package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
  215. package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
  216. package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
  217. package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
  218. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  219. package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
  220. package/web/dist/assets/index-DK3F5ZJo.js +0 -85
  221. package/web/dist/assets/index-DQMii2he.js +0 -85
  222. package/web/dist/assets/index-vwBnwzkr.css +0 -1
  223. package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
  224. package/web/dist/assets/theme-D2DMH6tH.js +0 -1
@@ -0,0 +1,293 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, open, readFile, readdir, rename, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ /**
5
+ * Append-only partitioned log for collections that dominate Hub state size.
6
+ *
7
+ * One file per partition (room or conversation), one JSON object per line:
8
+ * {"v":1,"op":"upsert","value":{...}}
9
+ * {"v":1,"op":"del","ids":["..."]}
10
+ *
11
+ * Durability model: the owner persists its index file first and calls `commit` afterwards, so a log
12
+ * entry always describes state that is already durable. Deletions are appended as tombstones and
13
+ * compacted away once they outnumber live rows, which keeps steady-state growth O(1) per mutation.
14
+ * A crash can only leave a partial trailing line (repaired on load) or un-tombstoned rows (trimmed
15
+ * by the caller's retention on load), never a torn index file.
16
+ */
17
+ const PARTITION = /^[A-Za-z0-9_-]{1,128}$/;
18
+ const PARTITION_SUFFIX = ".jsonl";
19
+ export const LOG_MAX_DELETES = 200;
20
+ export class PartitionedAppendLog {
21
+ dir;
22
+ partitionOf;
23
+ idOf;
24
+ retention;
25
+ protect;
26
+ maxDeletes;
27
+ /** Digest of the rows already written, so a commit only serializes what changed. */
28
+ cache = new Map();
29
+ deletes = new Map();
30
+ lines = new Map();
31
+ constructor(options) {
32
+ this.dir = options.dir;
33
+ this.partitionOf = options.partition;
34
+ this.idOf = options.id;
35
+ this.retention = options.retention;
36
+ this.protect = options.protect;
37
+ this.maxDeletes = options.maxDeletes ?? LOG_MAX_DELETES;
38
+ }
39
+ file(partition) {
40
+ return PARTITION.test(partition) ? join(this.dir, `${partition}${PARTITION_SUFFIX}`) : null;
41
+ }
42
+ digest(value) {
43
+ return createHash("sha1").update(JSON.stringify(value)).digest("hex");
44
+ }
45
+ /**
46
+ * Load every existing partition in the given parent set; rows of removed parents are ignored.
47
+ * `sweep` removes log files whose parent no longer exists (crash leftovers); read-only callers skip it.
48
+ */
49
+ async load(partitions, options = {}) {
50
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
51
+ const existing = new Set();
52
+ for (const partition of partitions)
53
+ if (PARTITION.test(partition))
54
+ existing.add(partition);
55
+ // Files whose parent was removed by a committed transaction (crash between the two writes).
56
+ for (const entry of options.sweep === false ? [] : await readdir(this.dir)) {
57
+ const partition = entry.endsWith(PARTITION_SUFFIX) ? entry.slice(0, -PARTITION_SUFFIX.length) : "";
58
+ if (!partition || !PARTITION.test(partition) || existing.has(partition))
59
+ continue;
60
+ await unlink(join(this.dir, entry)).catch(() => { });
61
+ }
62
+ const rows = [];
63
+ for (const partition of existing) {
64
+ const loaded = await this.readPartition(partition);
65
+ if (!loaded)
66
+ continue;
67
+ rows.push(...loaded.values);
68
+ // Repair a partition left oversized by a lost tombstone/compaction.
69
+ const overRetention = this.retention !== undefined && loaded.rawRows > this.retention;
70
+ if (loaded.needsRepair || overRetention || loaded.deletes > this.maxDeletes)
71
+ await this.rewrite(partition, loaded.values);
72
+ }
73
+ return rows;
74
+ }
75
+ withRetention(values) {
76
+ if (this.retention === undefined || values.length <= this.retention)
77
+ return values;
78
+ const kept = new Set();
79
+ const protectedRows = this.protect ? values.filter((value) => this.protect(value)) : [];
80
+ for (const row of protectedRows)
81
+ kept.add(this.idOf(row));
82
+ const rest = values.filter((value) => !kept.has(this.idOf(value)));
83
+ const remaining = Math.max(0, this.retention - kept.size);
84
+ // slice(-0) would return the whole array, so only take a window when there is room left.
85
+ for (const row of remaining > 0 ? rest.slice(-remaining) : [])
86
+ kept.add(this.idOf(row));
87
+ return values.filter((value) => kept.has(this.idOf(value)));
88
+ }
89
+ async readPartition(partition) {
90
+ const file = this.file(partition);
91
+ if (!file)
92
+ return null;
93
+ let raw;
94
+ try {
95
+ raw = await readFile(file, "utf8");
96
+ }
97
+ catch (error) {
98
+ if (error.code === "ENOENT")
99
+ return null;
100
+ throw error;
101
+ }
102
+ let complete = raw;
103
+ let needsRepair = false;
104
+ // A crash during append can leave a partial last line; ignore and truncate it before appending.
105
+ if (raw.length && !raw.endsWith("\n")) {
106
+ const cut = raw.lastIndexOf("\n");
107
+ complete = cut >= 0 ? raw.slice(0, cut + 1) : "";
108
+ needsRepair = true;
109
+ }
110
+ const live = new Map();
111
+ let deletes = 0;
112
+ let lines = 0;
113
+ for (const line of complete.split("\n")) {
114
+ if (!line)
115
+ continue;
116
+ lines++;
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(line);
120
+ }
121
+ catch {
122
+ // Only a torn tail is expected; anything else is corruption and is skipped explicitly.
123
+ needsRepair = true;
124
+ continue;
125
+ }
126
+ if (!parsed || parsed.v !== 1) {
127
+ needsRepair = true;
128
+ continue;
129
+ }
130
+ if (parsed.op === "del" && Array.isArray(parsed.ids)) {
131
+ deletes += parsed.ids.length;
132
+ for (const id of parsed.ids)
133
+ if (typeof id === "string")
134
+ live.delete(id);
135
+ continue;
136
+ }
137
+ if (parsed.op === "upsert" && parsed.value && typeof parsed.value === "object") {
138
+ const id = this.idOf(parsed.value);
139
+ if (typeof id !== "string" || !id) {
140
+ needsRepair = true;
141
+ continue;
142
+ }
143
+ live.set(id, parsed.value);
144
+ continue;
145
+ }
146
+ needsRepair = true;
147
+ }
148
+ const rawValues = [...live.values()];
149
+ const values = this.withRetention(rawValues);
150
+ const cache = new Map();
151
+ for (const value of values)
152
+ cache.set(this.idOf(value), this.digest(value));
153
+ this.cache.set(partition, cache);
154
+ this.deletes.set(partition, deletes);
155
+ this.lines.set(partition, lines);
156
+ return { values, rawRows: rawValues.length, deletes, needsRepair };
157
+ }
158
+ /**
159
+ * Apply the diff between what is on disk (cache) and `next`. Partitions that no longer exist are
160
+ * removed. When the write fails partway, each touched file is truncated back to its previous size
161
+ * so a rejected transaction cannot leave phantom rows behind.
162
+ */
163
+ async commit(next, partitions) {
164
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
165
+ const grouped = new Map();
166
+ for (const value of next) {
167
+ const partition = this.partitionOf(value);
168
+ if (!partitions.has(partition) || !PARTITION.test(partition))
169
+ continue;
170
+ const bucket = grouped.get(partition) ?? [];
171
+ bucket.push({ value, digest: this.digest(value) });
172
+ grouped.set(partition, bucket);
173
+ }
174
+ const removedPartitions = [...this.cache.keys()].filter((partition) => !partitions.has(partition) && PARTITION.test(partition));
175
+ // Partitions whose rows were all removed may have no `grouped` bucket; they still need tombstones.
176
+ const touched = new Set([...grouped.keys(), ...this.cache.keys(), ...removedPartitions]);
177
+ // Pre-append sizes so a rejected transaction cannot leave phantom rows behind.
178
+ const rollback = new Map();
179
+ try {
180
+ for (const partition of removedPartitions) {
181
+ const file = this.file(partition);
182
+ if (file)
183
+ await unlink(file).catch(() => { });
184
+ this.cache.delete(partition);
185
+ this.deletes.delete(partition);
186
+ this.lines.delete(partition);
187
+ }
188
+ for (const partition of [...touched].sort()) {
189
+ const file = this.file(partition);
190
+ if (!file || removedPartitions.includes(partition))
191
+ continue;
192
+ const previous = this.cache.get(partition) ?? new Map();
193
+ const bucket = grouped.get(partition) ?? [];
194
+ const present = new Set(bucket.map((entry) => this.idOf(entry.value)));
195
+ const added = bucket.filter((entry) => previous.get(this.idOf(entry.value)) !== entry.digest);
196
+ const removed = [...previous.keys()].filter((id) => !present.has(id));
197
+ if (!added.length && !removed.length)
198
+ continue;
199
+ rollback.set(file, await this.size(file));
200
+ const handle = await open(file, "a");
201
+ try {
202
+ let payload = "";
203
+ for (const entry of added)
204
+ payload += `${JSON.stringify({ v: 1, op: "upsert", value: entry.value })}\n`;
205
+ if (removed.length)
206
+ payload += `${JSON.stringify({ v: 1, op: "del", ids: removed })}\n`;
207
+ await handle.writeFile(payload);
208
+ await handle.sync();
209
+ }
210
+ finally {
211
+ await handle.close();
212
+ }
213
+ const cache = new Map();
214
+ for (const entry of bucket)
215
+ cache.set(this.idOf(entry.value), entry.digest);
216
+ this.cache.set(partition, cache);
217
+ const deletes = (this.deletes.get(partition) ?? 0) + removed.length;
218
+ const lines = (this.lines.get(partition) ?? previous.size) + added.length + (removed.length ? 1 : 0);
219
+ this.deletes.set(partition, deletes);
220
+ this.lines.set(partition, lines);
221
+ if (deletes >= this.maxDeletes || (this.retention && lines > this.retention * 2)) {
222
+ await this.rewrite(partition, bucket.map((entry) => entry.value));
223
+ this.deletes.set(partition, 0);
224
+ this.lines.set(partition, bucket.length);
225
+ // The file is a full snapshot now; rollback must not truncate it to the old append offset.
226
+ rollback.set(file, await this.size(file));
227
+ }
228
+ }
229
+ }
230
+ catch (error) {
231
+ for (const [file, size] of rollback)
232
+ await this.truncate(file, size).catch(() => { });
233
+ this.cache.clear();
234
+ this.deletes.clear();
235
+ this.lines.clear();
236
+ throw error;
237
+ }
238
+ }
239
+ async size(file) {
240
+ try {
241
+ const handle = await open(file, "r");
242
+ try {
243
+ return (await handle.stat()).size;
244
+ }
245
+ finally {
246
+ await handle.close();
247
+ }
248
+ }
249
+ catch (error) {
250
+ if (error.code === "ENOENT")
251
+ return 0;
252
+ throw error;
253
+ }
254
+ }
255
+ async truncate(file, size) {
256
+ const handle = await open(file, "r+");
257
+ try {
258
+ await handle.truncate(size);
259
+ await handle.sync();
260
+ }
261
+ finally {
262
+ await handle.close();
263
+ }
264
+ }
265
+ async rewrite(partition, values) {
266
+ const file = this.file(partition);
267
+ if (!file)
268
+ return;
269
+ const temporary = `${file}.${createHash("sha1").update(`${Date.now()}:${Math.random()}`).digest("hex")}.tmp`;
270
+ const payload = values.map((value) => `${JSON.stringify({ v: 1, op: "upsert", value })}\n`).join("");
271
+ const handle = await open(temporary, "w", 0o600);
272
+ try {
273
+ await handle.writeFile(payload);
274
+ await handle.sync();
275
+ }
276
+ finally {
277
+ await handle.close();
278
+ }
279
+ await rename(temporary, file);
280
+ const cache = new Map();
281
+ for (const value of values)
282
+ cache.set(this.idOf(value), this.digest(value));
283
+ this.cache.set(partition, cache);
284
+ }
285
+ /** Re-read a partition after an external change (used by tests and failure recovery). */
286
+ async reload(partitions) {
287
+ for (const partition of partitions) {
288
+ this.cache.delete(partition);
289
+ this.deletes.delete(partition);
290
+ this.lines.delete(partition);
291
+ }
292
+ }
293
+ }
@@ -32,12 +32,20 @@ export function portalHeaders(hub, base) {
32
32
  "x-content-type-options": "nosniff",
33
33
  };
34
34
  }
35
- export function wrapperHtml(base, initialPath = "") {
35
+ export function wrapperHtml(base, initialPath = "", desktopHub, deviceLabel = "Device") {
36
+ const title = `${deviceLabel} · pi-web-ui`.replace(/[&<>"']/g, (char) => {
37
+ return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char];
38
+ });
36
39
  const nonce = randomBytes(16).toString("hex");
37
- const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Device</title><style nonce="${nonce}">html,body,iframe{width:100%;height:100%;margin:0;border:0;display:block}body{background:#17181c;color:#eee;font:14px system-ui}#loading{position:fixed;inset:0;display:grid;place-content:center;text-align:center;gap:14px;background:#17181c}#loading[hidden]{display:none}button,a{padding:10px 16px;color:inherit;background:#303137;border:1px solid #555;border-radius:8px;text-decoration:none;cursor:pointer}p{color:#aaa;max-width:420px;line-height:1.7}</style></head><body><iframe sandbox="allow-scripts allow-forms allow-downloads" referrerpolicy="no-referrer"></iframe><div id="loading"><strong id="title">正在连接设备… / Connecting…</strong><p id="hint">正在加载远程页面,请稍候。 / Loading the remote page.</p><div><button id="retry" type="button">重新连接 / Retry</button> <a href="/">返回设备中心 / Hub</a></div></div><script nonce="${nonce}">const frame=document.querySelector('iframe'),loading=document.getElementById('loading');let timer;const connect=()=>{loading.hidden=false;document.getElementById('title').textContent='正在连接设备… / Connecting…';frame.src=${JSON.stringify(base + initialPath)}+location.hash;clearTimeout(timer);timer=setTimeout(()=>{document.getElementById('title').textContent='设备页面加载超时 / Connection timed out';document.getElementById('hint').textContent='请重试;若设备离线或入口已过期,请返回设备中心重新打开。 / Retry, or reopen the device from the Hub.';},20000)};document.getElementById('retry').onclick=connect;connect();addEventListener('message',event=>{if(event.source!==frame.contentWindow||event.origin!=='null')return;const data=event.data;if(data?.type==='device-portal-ready'){clearTimeout(timer);loading.hidden=true;return}if(!data||data.type!=='device-session-hash'||typeof data.hash!=='string'||!/^#s=[a-zA-Z0-9_-]{1,256}$/.test(data.hash))return;history.replaceState(null,'',location.pathname+data.hash)});</script></body></html>`;
40
+ // Desktop tickets may be embedded by a paired device UI on another origin.
41
+ // The device content remains in the opaque sandbox, even when this wrapper is embedded.
42
+ const frameBase = desktopHub ? new URL(base, desktopHub).href : base;
43
+ const frameSource = desktopHub ? `${desktopHub.origin}${base}` : "'self'";
44
+ const ancestors = desktopHub ? "http: https:" : "'self'";
45
+ const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title><style nonce="${nonce}">html,body,iframe{width:100%;height:100%;margin:0;border:0;display:block}body{background:#17181c;color:#eee;font:14px system-ui}#loading{position:fixed;inset:0;display:grid;place-content:center;text-align:center;gap:14px;background:#17181c}#loading[hidden]{display:none}button,a{padding:10px 16px;color:inherit;background:#303137;border:1px solid #555;border-radius:8px;text-decoration:none;cursor:pointer}p{color:#aaa;max-width:420px;line-height:1.7}</style></head><body><iframe sandbox="allow-scripts allow-forms allow-downloads" allowfullscreen referrerpolicy="no-referrer"></iframe><div id="loading"><strong id="title">正在连接设备… / Connecting…</strong><p id="hint">正在加载远程页面,请稍候。 / Loading the remote page.</p><div><button id="retry" type="button">重新连接 / Retry</button> <a href="/">返回设备中心 / Hub</a></div></div><script nonce="${nonce}">const frame=document.querySelector('iframe'),loading=document.getElementById('loading');let timer;const connect=()=>{loading.hidden=false;document.getElementById('title').textContent='正在连接设备… / Connecting…';frame.src=${JSON.stringify(frameBase + initialPath)}+location.hash;clearTimeout(timer);timer=setTimeout(()=>{document.getElementById('title').textContent='设备页面加载超时 / Connection timed out';document.getElementById('hint').textContent='请重试;若设备离线或入口已过期,请返回设备中心重新打开。 / Retry, or reopen the device from the Hub.';},20000)};document.getElementById('retry').onclick=connect;connect();addEventListener('message',event=>{if(event.source!==frame.contentWindow||event.origin!=='null')return;const data=event.data;if(data?.type==='device-portal-ready'){clearTimeout(timer);loading.hidden=true;return}if(!data||data.type!=='device-session-hash'||typeof data.hash!=='string'||!/^#s=[a-zA-Z0-9_-]{1,256}$/.test(data.hash))return;history.replaceState(null,'',location.pathname+data.hash)});</script></body></html>`;
38
46
  return {
39
47
  html,
40
- csp: `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; frame-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'`,
48
+ csp: `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; frame-src ${frameSource}; base-uri 'none'; form-action 'none'; frame-ancestors ${ancestors}`,
41
49
  };
42
50
  }
43
51
  export function transformPortalHtml(html, base) {