pi-web-ui 0.114.2 → 0.115.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.
- package/CHANGELOG.md +55 -1
- package/bin/pi-web-ui.mjs +69 -7
- package/dist/server/agent-service-daemon.js +440 -32
- package/dist/server/agent-service.js +878 -383
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +25 -0
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/context-usage.js +105 -0
- package/dist/server/conversation-communication.js +14 -0
- package/dist/server/conversation-identity.js +27 -0
- package/dist/server/device-center/approval-summary.js +31 -0
- package/dist/server/device-center/bot-catalog.js +21 -7
- package/dist/server/device-center/bot-execution.js +72 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +328 -10
- package/dist/server/device-center/collab-tool.js +738 -12
- package/dist/server/device-center/connector.js +359 -23
- package/dist/server/device-center/desktop-page.js +22 -16
- package/dist/server/device-center/device-integration.js +595 -0
- package/dist/server/device-center/execution-guides.js +32 -0
- package/dist/server/device-center/execution-instructions.js +19 -0
- package/dist/server/device-center/execution-settings.js +100 -0
- package/dist/server/device-center/execution-system-prompt.js +38 -0
- package/dist/server/device-center/execution-workspace.js +20 -0
- package/dist/server/device-center/executor.js +389 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +180 -91
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +208 -0
- package/dist/server/device-center/group-context.js +109 -0
- package/dist/server/device-center/group-events.js +136 -0
- package/dist/server/device-center/group-plan-guard.js +138 -0
- package/dist/server/device-center/hub-conversations.js +178 -0
- package/dist/server/device-center/hub-deliveries.js +277 -0
- package/dist/server/device-center/hub-integration.js +451 -0
- package/dist/server/device-center/hub.js +1544 -80
- package/dist/server/device-center/human-interaction.js +232 -0
- package/dist/server/device-center/integration-errors.js +25 -0
- package/dist/server/device-center/local-hub.js +18 -0
- package/dist/server/device-center/local.js +356 -40
- package/dist/server/device-center/main.js +11 -1
- package/dist/server/device-center/path-portal.js +11 -3
- package/dist/server/device-center/relay.js +364 -35
- package/dist/server/device-center/report-metadata.js +66 -0
- package/dist/server/device-center/report-upload.js +63 -0
- package/dist/server/device-center/runtime.js +549 -41
- package/dist/server/device-center/store.js +66 -3
- package/dist/server/device-center/task-context-budget.js +161 -0
- package/dist/server/device-center/task-journal.js +385 -0
- package/dist/server/device-center/task-plan.js +33 -0
- package/dist/server/device-center/task-progress.js +141 -0
- package/dist/server/device-center/task-recovery.js +452 -0
- package/dist/server/device-center/task-report-outbox.js +216 -0
- package/dist/server/device-center/task-report.js +384 -0
- package/dist/server/device-center/task-scheduler.js +400 -0
- package/dist/server/device-center/task-state.js +333 -0
- package/dist/server/device-center/transfer-stream.js +1006 -0
- package/dist/server/device-center/transfers.js +815 -8
- package/dist/server/dispatch-domain-handlers.js +21 -3
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +89 -13
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -0
- package/dist/server/patch-executable-lookup.js +396 -0
- package/dist/server/payload-limits.js +2 -0
- package/dist/server/plugin-llm.js +100 -9
- package/dist/server/plugins.js +1 -0
- package/dist/server/preset-fields.js +24 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/prompt-base-store.js +85 -0
- package/dist/server/prompt-composer.js +5 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- package/dist/server/remote-ssh-service.js +22 -9
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/session-search.js +1 -1
- package/dist/server/settings-service.js +90 -39
- package/dist/server/skill-content-filler.js +29 -8
- package/dist/server/skill-tool.js +12 -3
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +50 -36
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/docs/README.md +94 -0
- package/docs/device-center.md +100 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +1 -1
- package/themes/aetheris.css +5 -0
- package/themes/ayu-light.css +6 -0
- package/themes/bases/flow-base.css +68 -68
- package/themes/catppuccin-latte.css +6 -0
- package/themes/catppuccin.css +6 -0
- package/themes/claude-code-dark.css +5 -0
- package/themes/codex.css +6 -0
- package/themes/cyberpunk.css +6 -0
- package/themes/dark-teal.css +6 -1
- package/themes/dazzle.css +6 -0
- package/themes/everforest-light.css +6 -0
- package/themes/flow-light.css +8 -1
- package/themes/flow.css +6 -1
- package/themes/geist.css +6 -0
- package/themes/gruvbox-light.css +6 -0
- package/themes/kanagawa-lotus.css +6 -0
- package/themes/md-preview.css +6 -0
- package/themes/mist.css +6 -0
- package/themes/nord.css +6 -0
- package/themes/one-dark.css +6 -0
- package/themes/paper.css +6 -0
- package/themes/rose-pine-dawn.css +6 -0
- package/themes/sakura.css +6 -0
- package/themes/solarized-light.css +6 -0
- package/themes/tokyo-night.css +6 -0
- package/themes/translucent.css +6 -0
- package/themes/transparent.css +6 -0
- package/themes/vs-code-dark.css +5 -0
- package/themes/wallpaper-flow.css +5 -1
- package/themes/wallpaper-obsidian.css +6 -0
- package/themes/white.css +6 -0
- package/themes/zhujian-dark.css +6 -1
- package/themes/zhujian.css +6 -1
- package/themes/zhupi-dark.css +6 -1
- package/themes/zhupi.css +6 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
- package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
- package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
- package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
- package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
- package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
- package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
- package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
- package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
- package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
- package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
- package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
- package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
- package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
- package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
- package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
- package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
- package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-CsFs_HMb.css +1 -0
- package/web/dist/assets/index-DHeeHS_l.js +85 -0
- package/web/dist/assets/index-DTZch8uz.js +85 -0
- package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
- package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
- package/web/dist/assets/theme-BXGpyTMh.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
- package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
- package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
- package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
- package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
- package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
- package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
- package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
- package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
- package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
- package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
- package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
- package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
- package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
- package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
- package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
- package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
- package/web/dist/assets/index-Cdh3sibd.js +0 -85
- package/web/dist/assets/index-DDZMv6LO.css +0 -1
- package/web/dist/assets/index-DWw_SxRq.js +0 -85
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
- package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import express, {} from "express";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
|
|
3
|
+
import { mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
+
import { DEVICE_FILE_SYNC_LIMITS } from "./file-sync.js";
|
|
6
|
+
import { CHUNKED_TRANSFER_LIMITS as TRANSFER_LIMITS, validateChunkedManifest, } from "./transfer-stream.js";
|
|
5
7
|
function membership(ids) {
|
|
6
8
|
return createHash("sha256")
|
|
7
9
|
.update(JSON.stringify([...ids].sort()))
|
|
@@ -9,6 +11,7 @@ function membership(ids) {
|
|
|
9
11
|
}
|
|
10
12
|
const TTL = 24 * 60 * 60 * 1000;
|
|
11
13
|
const MAX_RECEIPTS = 1000;
|
|
14
|
+
const MAX_REGISTRY_BYTES = 32 * 1024 * 1024;
|
|
12
15
|
const MAX_PACKET = 12 * 1024 * 1024;
|
|
13
16
|
function fail(status, message) {
|
|
14
17
|
throw Object.assign(new Error(message), { status });
|
|
@@ -22,10 +25,25 @@ export function transferSummary(value) {
|
|
|
22
25
|
return {};
|
|
23
26
|
const source = value;
|
|
24
27
|
const result = {};
|
|
25
|
-
for (const key of [
|
|
26
|
-
|
|
28
|
+
for (const key of [
|
|
29
|
+
"revision",
|
|
30
|
+
"totalBytes",
|
|
31
|
+
"version",
|
|
32
|
+
"status",
|
|
33
|
+
"percent",
|
|
34
|
+
"chunkIndex",
|
|
35
|
+
"received",
|
|
36
|
+
"totalChunks",
|
|
37
|
+
"transferredBytes",
|
|
38
|
+
"totalFiles",
|
|
39
|
+
"completedFiles",
|
|
40
|
+
]) {
|
|
41
|
+
if (typeof source[key] === "number" || typeof source[key] === "string" || typeof source[key] === "boolean")
|
|
27
42
|
result[key] = source[key];
|
|
28
43
|
}
|
|
44
|
+
if (Array.isArray(source.receivedChunks)) {
|
|
45
|
+
result.receivedChunks = source.receivedChunks.filter((v) => Number.isSafeInteger(v)).slice(0, 4096);
|
|
46
|
+
}
|
|
29
47
|
for (const key of ["applied", "unchanged"]) {
|
|
30
48
|
if (Array.isArray(source[key]))
|
|
31
49
|
result[key] = source[key].filter((v) => typeof v === "string").slice(0, 200);
|
|
@@ -33,16 +51,57 @@ export function transferSummary(value) {
|
|
|
33
51
|
for (const key of ["files", "rejected"]) {
|
|
34
52
|
if (!Array.isArray(source[key]))
|
|
35
53
|
continue;
|
|
54
|
+
const originalLength = source[key].length;
|
|
36
55
|
result[key] = source[key].slice(0, 200).map((item) => {
|
|
37
56
|
const entry = {};
|
|
38
57
|
if (item && typeof item === "object")
|
|
39
|
-
for (const k of ["path", "size", "sha256", "baseline", "status"]) {
|
|
58
|
+
for (const k of ["path", "size", "sha256", "baseline", "status", "chunkCount", "firstChunkIndex", "offset"]) {
|
|
40
59
|
const v = item[k];
|
|
41
60
|
if (typeof v === "string" || typeof v === "number" || v === null)
|
|
42
61
|
entry[k] = v;
|
|
43
62
|
}
|
|
44
63
|
return entry;
|
|
45
64
|
});
|
|
65
|
+
if (key === "files") {
|
|
66
|
+
const count = Number.isSafeInteger(source.totalFiles) ? source.totalFiles : originalLength;
|
|
67
|
+
result.totalFiles = count;
|
|
68
|
+
result.truncated = count > result.files.length;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (Number.isSafeInteger(source.totalExcluded) && source.totalExcluded >= 0)
|
|
72
|
+
result.totalExcluded = source.totalExcluded;
|
|
73
|
+
if (Array.isArray(source.exclusions)) {
|
|
74
|
+
const exclusions = [];
|
|
75
|
+
let bytes = 2; // JSON array brackets, including UTF-8 path bytes and escaping.
|
|
76
|
+
for (const item of source.exclusions.slice(0, DEVICE_FILE_SYNC_LIMITS.exclusions)) {
|
|
77
|
+
if (!item || typeof item !== "object")
|
|
78
|
+
continue;
|
|
79
|
+
const { path, reason } = item;
|
|
80
|
+
if (typeof path !== "string" ||
|
|
81
|
+
!path ||
|
|
82
|
+
Buffer.byteLength(path) > 1024 ||
|
|
83
|
+
Buffer.from(path).toString("utf8") !== path ||
|
|
84
|
+
path.normalize("NFC") !== path ||
|
|
85
|
+
/[\\:\x00-\x1f\x7f<>"|?*]/.test(path) ||
|
|
86
|
+
path.split("/").length > 32 ||
|
|
87
|
+
path
|
|
88
|
+
.split("/")
|
|
89
|
+
.some((part) => !part ||
|
|
90
|
+
part === "." ||
|
|
91
|
+
part === ".." ||
|
|
92
|
+
/[. ]$/.test(part) ||
|
|
93
|
+
Buffer.byteLength(part) > 255 ||
|
|
94
|
+
/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part)) ||
|
|
95
|
+
(reason !== "ignored" && reason !== "sensitive"))
|
|
96
|
+
continue;
|
|
97
|
+
const entry = { path, reason };
|
|
98
|
+
const additional = Buffer.byteLength(JSON.stringify(entry)) + (exclusions.length ? 1 : 0);
|
|
99
|
+
if (bytes + additional > DEVICE_FILE_SYNC_LIMITS.exclusionBytes)
|
|
100
|
+
break;
|
|
101
|
+
bytes += additional;
|
|
102
|
+
exclusions.push(entry);
|
|
103
|
+
}
|
|
104
|
+
result.exclusions = exclusions;
|
|
46
105
|
}
|
|
47
106
|
for (const key of ["manifest", "preview"])
|
|
48
107
|
if (source[key] && typeof source[key] === "object")
|
|
@@ -58,6 +117,8 @@ export async function installDeviceTransfers(options) {
|
|
|
58
117
|
const path = join(options.dataDir, "device-transfers.json");
|
|
59
118
|
let receipts = [];
|
|
60
119
|
try {
|
|
120
|
+
if ((await stat(path)).size > MAX_REGISTRY_BYTES)
|
|
121
|
+
throw new Error("Transfer registry storage limit reached");
|
|
61
122
|
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
62
123
|
if (!Array.isArray(parsed) || parsed.length > MAX_RECEIPTS)
|
|
63
124
|
throw new Error("Invalid transfer receipts");
|
|
@@ -77,10 +138,45 @@ export async function installDeviceTransfers(options) {
|
|
|
77
138
|
!Number.isSafeInteger(row.sourceBotRevision) ||
|
|
78
139
|
!Number.isSafeInteger(row.targetBotRevision) ||
|
|
79
140
|
!Number.isFinite(row.expiresAt) ||
|
|
80
|
-
(row.applyStarted !== undefined && typeof row.applyStarted !== "boolean")
|
|
141
|
+
(row.applyStarted !== undefined && typeof row.applyStarted !== "boolean") ||
|
|
142
|
+
(row.job !== undefined &&
|
|
143
|
+
((row.job.stopUnconfirmed !== undefined && typeof row.job.stopUnconfirmed !== "boolean") ||
|
|
144
|
+
!field(row.job.idempotencyKey) ||
|
|
145
|
+
!field(row.job.fingerprint) ||
|
|
146
|
+
!Array.isArray(row.job.paths) ||
|
|
147
|
+
row.job.paths.length > DEVICE_FILE_SYNC_LIMITS.files ||
|
|
148
|
+
!row.job.paths.every(field) ||
|
|
149
|
+
typeof row.job.recursive !== "boolean" ||
|
|
150
|
+
![
|
|
151
|
+
"queued",
|
|
152
|
+
"staging",
|
|
153
|
+
"interrupted",
|
|
154
|
+
"ready",
|
|
155
|
+
"applying",
|
|
156
|
+
"applied",
|
|
157
|
+
"failed",
|
|
158
|
+
"cancelling",
|
|
159
|
+
"cancelled",
|
|
160
|
+
].includes(row.job.status) ||
|
|
161
|
+
!row.job.summary ||
|
|
162
|
+
typeof row.job.summary !== "object")))
|
|
81
163
|
throw new Error("Invalid transfer receipts");
|
|
164
|
+
if (row.job?.manifest) {
|
|
165
|
+
validateChunkedManifest(row.job.manifest);
|
|
166
|
+
if (row.job.manifest.transferId !== row.localTransferId ||
|
|
167
|
+
createHash("sha256").update(JSON.stringify(row.job.manifest)).digest("hex") !== row.job.manifestHash ||
|
|
168
|
+
row.job.manifest.files.some((file) => file.chunkHashes?.length !== file.chunkCount))
|
|
169
|
+
throw new Error("Invalid persisted manifest binding");
|
|
170
|
+
}
|
|
82
171
|
}
|
|
83
|
-
receipts = parsed.filter((row) => row.expiresAt > Date.now());
|
|
172
|
+
receipts = parsed.filter((row) => row.expiresAt > Date.now() || row.job?.stopUnconfirmed);
|
|
173
|
+
for (const row of receipts)
|
|
174
|
+
if (row.job && ["queued", "staging", "cancelling", "applying"].includes(row.job.status)) {
|
|
175
|
+
row.job.status = row.applyStarted ? "failed" : "interrupted";
|
|
176
|
+
row.job.error = row.applyStarted
|
|
177
|
+
? "Apply outcome requires inspection"
|
|
178
|
+
: "Transfer interrupted; explicitly resume the saved manifest";
|
|
179
|
+
}
|
|
84
180
|
}
|
|
85
181
|
catch (error) {
|
|
86
182
|
if (error.code !== "ENOENT")
|
|
@@ -89,8 +185,10 @@ export async function installDeviceTransfers(options) {
|
|
|
89
185
|
let queue = Promise.resolve();
|
|
90
186
|
function transact(fn) {
|
|
91
187
|
const job = queue.then(async () => {
|
|
92
|
-
const draft = structuredClone(receipts.filter((row) => row.expiresAt > Date.now()));
|
|
188
|
+
const draft = structuredClone(receipts.filter((row) => row.expiresAt > Date.now() || row.job?.stopUnconfirmed));
|
|
93
189
|
const result = fn(draft);
|
|
190
|
+
if (Buffer.byteLength(JSON.stringify(draft)) > MAX_REGISTRY_BYTES)
|
|
191
|
+
fail(429, "Transfer registry storage limit reached");
|
|
94
192
|
await mkdir(options.dataDir, { recursive: true, mode: 0o700 });
|
|
95
193
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
96
194
|
try {
|
|
@@ -131,7 +229,7 @@ export async function installDeviceTransfers(options) {
|
|
|
131
229
|
const body = req.body;
|
|
132
230
|
if (!body ||
|
|
133
231
|
Buffer.byteLength(JSON.stringify(body)) > MAX_PACKET ||
|
|
134
|
-
!["stage", "preview", "apply"].includes(body.action) ||
|
|
232
|
+
!["stage", "preview", "apply", "init", "chunk", "status", "abort"].includes(body.action) ||
|
|
135
233
|
!field(body.roomId) ||
|
|
136
234
|
!field(body.sourceBotId) ||
|
|
137
235
|
!field(body.targetBotId))
|
|
@@ -216,6 +314,140 @@ export async function installDeviceTransfers(options) {
|
|
|
216
314
|
draft.push(receipt);
|
|
217
315
|
});
|
|
218
316
|
}
|
|
317
|
+
else if (body.action === "init") {
|
|
318
|
+
if (!body.manifest || typeof body.manifest !== "object")
|
|
319
|
+
fail(400, "Manifest required");
|
|
320
|
+
await queue;
|
|
321
|
+
if (receipts.filter((r) => r.expiresAt > Date.now()).length >= MAX_RECEIPTS)
|
|
322
|
+
fail(429, "Transfer receipt limit reached");
|
|
323
|
+
result = await options.relay.callDevice(targetDeviceId, "transfer_init", {
|
|
324
|
+
roomId: body.roomId,
|
|
325
|
+
sourceBotId: body.sourceBotId,
|
|
326
|
+
targetBotId: body.targetBotId,
|
|
327
|
+
sourceBotRevision: sourceBot.revision,
|
|
328
|
+
targetBotRevision: targetBot.revision,
|
|
329
|
+
manifest: body.manifest,
|
|
330
|
+
}, { signal: controller.signal });
|
|
331
|
+
controller.signal.throwIfAborted();
|
|
332
|
+
authorize();
|
|
333
|
+
const local = result;
|
|
334
|
+
const localId = local?.transferId ?? local?.id;
|
|
335
|
+
if (!field(localId))
|
|
336
|
+
fail(502, "Invalid device transfer response");
|
|
337
|
+
receipt = {
|
|
338
|
+
id: randomUUID(),
|
|
339
|
+
sourceDeviceId: auth.device.id,
|
|
340
|
+
accountId: auth.account.id,
|
|
341
|
+
roomId: body.roomId,
|
|
342
|
+
targetDeviceId: targetDeviceId,
|
|
343
|
+
sourceBotId: sourceBot.id,
|
|
344
|
+
targetBotId: targetBot.id,
|
|
345
|
+
sourceBotRevision: sourceBot.revision,
|
|
346
|
+
targetBotRevision: targetBot.revision,
|
|
347
|
+
localTransferId: localId,
|
|
348
|
+
roomMembers,
|
|
349
|
+
expiresAt: Date.now() + TTL,
|
|
350
|
+
};
|
|
351
|
+
await transact((draft) => {
|
|
352
|
+
if (draft.length >= MAX_RECEIPTS)
|
|
353
|
+
fail(429, "Transfer receipt limit reached");
|
|
354
|
+
draft.push(receipt);
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
else if (body.action === "chunk") {
|
|
358
|
+
if (!field(body.transferId) || !body.chunk || typeof body.chunk !== "object")
|
|
359
|
+
fail(400, "Transfer ID and chunk required");
|
|
360
|
+
await queue;
|
|
361
|
+
const found = receipts.find((r) => r.id === body.transferId &&
|
|
362
|
+
r.expiresAt > Date.now() &&
|
|
363
|
+
r.sourceDeviceId === auth.device.id &&
|
|
364
|
+
r.accountId === auth.account.id &&
|
|
365
|
+
r.roomId === body.roomId &&
|
|
366
|
+
r.targetDeviceId === targetDeviceId &&
|
|
367
|
+
r.sourceBotId === sourceBot.id &&
|
|
368
|
+
r.targetBotId === targetBot.id &&
|
|
369
|
+
r.sourceBotRevision === sourceBot.revision &&
|
|
370
|
+
r.targetBotRevision === targetBot.revision &&
|
|
371
|
+
r.roomMembers === roomMembers);
|
|
372
|
+
if (!found)
|
|
373
|
+
fail(403, "Transfer access denied");
|
|
374
|
+
receipt = { ...found };
|
|
375
|
+
controller.signal.throwIfAborted();
|
|
376
|
+
authorize();
|
|
377
|
+
result = await options.relay.callDevice(receipt.targetDeviceId, "transfer_chunk", {
|
|
378
|
+
roomId: receipt.roomId,
|
|
379
|
+
sourceBotId: receipt.sourceBotId,
|
|
380
|
+
targetBotId: receipt.targetBotId,
|
|
381
|
+
sourceBotRevision: receipt.sourceBotRevision,
|
|
382
|
+
targetBotRevision: receipt.targetBotRevision,
|
|
383
|
+
transferId: receipt.localTransferId,
|
|
384
|
+
chunk: { ...body.chunk, transferId: receipt.localTransferId },
|
|
385
|
+
}, { signal: controller.signal });
|
|
386
|
+
controller.signal.throwIfAborted();
|
|
387
|
+
authorize();
|
|
388
|
+
}
|
|
389
|
+
else if (body.action === "status") {
|
|
390
|
+
if (!field(body.transferId))
|
|
391
|
+
fail(400, "Transfer ID required");
|
|
392
|
+
await queue;
|
|
393
|
+
const found = receipts.find((r) => r.id === body.transferId &&
|
|
394
|
+
r.expiresAt > Date.now() &&
|
|
395
|
+
r.sourceDeviceId === auth.device.id &&
|
|
396
|
+
r.accountId === auth.account.id &&
|
|
397
|
+
r.roomId === body.roomId &&
|
|
398
|
+
r.targetDeviceId === targetDeviceId &&
|
|
399
|
+
r.sourceBotId === sourceBot.id &&
|
|
400
|
+
r.targetBotId === targetBot.id &&
|
|
401
|
+
r.sourceBotRevision === sourceBot.revision &&
|
|
402
|
+
r.targetBotRevision === targetBot.revision &&
|
|
403
|
+
r.roomMembers === roomMembers);
|
|
404
|
+
if (!found)
|
|
405
|
+
fail(403, "Transfer access denied");
|
|
406
|
+
receipt = { ...found };
|
|
407
|
+
controller.signal.throwIfAborted();
|
|
408
|
+
authorize();
|
|
409
|
+
result = await options.relay.callDevice(receipt.targetDeviceId, "transfer_status", {
|
|
410
|
+
roomId: receipt.roomId,
|
|
411
|
+
sourceBotId: receipt.sourceBotId,
|
|
412
|
+
targetBotId: receipt.targetBotId,
|
|
413
|
+
sourceBotRevision: receipt.sourceBotRevision,
|
|
414
|
+
targetBotRevision: receipt.targetBotRevision,
|
|
415
|
+
transferId: receipt.localTransferId,
|
|
416
|
+
}, { signal: controller.signal });
|
|
417
|
+
controller.signal.throwIfAborted();
|
|
418
|
+
authorize();
|
|
419
|
+
}
|
|
420
|
+
else if (body.action === "abort") {
|
|
421
|
+
if (!field(body.transferId))
|
|
422
|
+
fail(400, "Transfer ID required");
|
|
423
|
+
await queue;
|
|
424
|
+
const found = receipts.find((r) => r.id === body.transferId &&
|
|
425
|
+
r.expiresAt > Date.now() &&
|
|
426
|
+
r.sourceDeviceId === auth.device.id &&
|
|
427
|
+
r.accountId === auth.account.id &&
|
|
428
|
+
r.roomId === body.roomId &&
|
|
429
|
+
r.targetDeviceId === targetDeviceId &&
|
|
430
|
+
r.sourceBotId === sourceBot.id &&
|
|
431
|
+
r.targetBotId === targetBot.id &&
|
|
432
|
+
r.sourceBotRevision === sourceBot.revision &&
|
|
433
|
+
r.targetBotRevision === targetBot.revision &&
|
|
434
|
+
r.roomMembers === roomMembers);
|
|
435
|
+
if (!found)
|
|
436
|
+
fail(403, "Transfer access denied");
|
|
437
|
+
receipt = { ...found };
|
|
438
|
+
controller.signal.throwIfAborted();
|
|
439
|
+
authorize();
|
|
440
|
+
result = await options.relay.callDevice(receipt.targetDeviceId, "transfer_abort", {
|
|
441
|
+
roomId: receipt.roomId,
|
|
442
|
+
sourceBotId: receipt.sourceBotId,
|
|
443
|
+
targetBotId: receipt.targetBotId,
|
|
444
|
+
sourceBotRevision: receipt.sourceBotRevision,
|
|
445
|
+
targetBotRevision: receipt.targetBotRevision,
|
|
446
|
+
transferId: receipt.localTransferId,
|
|
447
|
+
}, { signal: controller.signal });
|
|
448
|
+
controller.signal.throwIfAborted();
|
|
449
|
+
authorize();
|
|
450
|
+
}
|
|
219
451
|
else {
|
|
220
452
|
if (!field(body.transferId))
|
|
221
453
|
fail(400, "Transfer ID required");
|
|
@@ -290,4 +522,579 @@ export async function installDeviceTransfers(options) {
|
|
|
290
522
|
}
|
|
291
523
|
}
|
|
292
524
|
});
|
|
525
|
+
function getOwner(req) {
|
|
526
|
+
const fromHub = options.hub?.getRelayAccount?.(req);
|
|
527
|
+
if (fromHub)
|
|
528
|
+
return fromHub;
|
|
529
|
+
const fromCustom = options.getAccount?.(req);
|
|
530
|
+
if (fromCustom)
|
|
531
|
+
return fromCustom;
|
|
532
|
+
return undefined;
|
|
533
|
+
}
|
|
534
|
+
// Human requests are persisted before scheduling; the Hub only coordinates fixed Bot RPCs.
|
|
535
|
+
const running = new Map();
|
|
536
|
+
const maxJobs = 4;
|
|
537
|
+
let closing = false;
|
|
538
|
+
function releaseSlot(id) {
|
|
539
|
+
const slot = running.get(id);
|
|
540
|
+
if (!slot || slot.blocked)
|
|
541
|
+
return;
|
|
542
|
+
clearTimeout(slot.deadline);
|
|
543
|
+
running.delete(id);
|
|
544
|
+
}
|
|
545
|
+
function authorize(row) {
|
|
546
|
+
const state = store.snapshot();
|
|
547
|
+
const room = state.rooms.find((r) => r.id === row.roomId && r.accountId === row.accountId);
|
|
548
|
+
const source = state.bots.find((b) => b.id === row.sourceBotId && b.accountId === row.accountId);
|
|
549
|
+
const target = state.bots.find((b) => b.id === row.targetBotId && b.accountId === row.accountId);
|
|
550
|
+
if (!room ||
|
|
551
|
+
membership(room.botIds ?? []) !== row.roomMembers ||
|
|
552
|
+
!room.botIds.includes(row.sourceBotId) ||
|
|
553
|
+
!room.botIds.includes(row.targetBotId) ||
|
|
554
|
+
!source ||
|
|
555
|
+
!target ||
|
|
556
|
+
source.deviceId !== row.sourceDeviceId ||
|
|
557
|
+
target.deviceId !== row.targetDeviceId ||
|
|
558
|
+
source.revision !== row.sourceBotRevision ||
|
|
559
|
+
target.revision !== row.targetBotRevision ||
|
|
560
|
+
!source.enabled ||
|
|
561
|
+
!target.enabled)
|
|
562
|
+
fail(403, "Transfer scope changed");
|
|
563
|
+
for (const id of [row.sourceDeviceId, row.targetDeviceId])
|
|
564
|
+
if (!state.devices.some((d) => d.id === id && d.accountId === row.accountId))
|
|
565
|
+
fail(403, "Transfer device unavailable");
|
|
566
|
+
}
|
|
567
|
+
function payload(row) {
|
|
568
|
+
return {
|
|
569
|
+
roomId: row.roomId,
|
|
570
|
+
sourceBotId: row.sourceBotId,
|
|
571
|
+
targetBotId: row.targetBotId,
|
|
572
|
+
sourceBotRevision: row.sourceBotRevision,
|
|
573
|
+
targetBotRevision: row.targetBotRevision,
|
|
574
|
+
transferId: row.localTransferId,
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
async function rpc(row, action, extra, signal, source = false) {
|
|
578
|
+
signal.throwIfAborted();
|
|
579
|
+
authorize(row);
|
|
580
|
+
const result = await options.relay.callDevice(source ? row.sourceDeviceId : row.targetDeviceId, action, {
|
|
581
|
+
...payload(row),
|
|
582
|
+
...(source ? { targetBotId: row.sourceBotId, targetBotRevision: row.sourceBotRevision } : {}),
|
|
583
|
+
...extra,
|
|
584
|
+
}, { signal });
|
|
585
|
+
signal.throwIfAborted();
|
|
586
|
+
authorize(row);
|
|
587
|
+
return result;
|
|
588
|
+
}
|
|
589
|
+
async function updateJob(id, fn) {
|
|
590
|
+
return transact((draft) => {
|
|
591
|
+
const row = draft.find((r) => r.id === id);
|
|
592
|
+
if (!row?.job)
|
|
593
|
+
fail(404, "Transfer missing");
|
|
594
|
+
fn(row.job);
|
|
595
|
+
return row;
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
function view(row) {
|
|
599
|
+
return {
|
|
600
|
+
...row.job?.summary,
|
|
601
|
+
transferId: row.id,
|
|
602
|
+
roomId: row.roomId,
|
|
603
|
+
sourceBotId: row.sourceBotId,
|
|
604
|
+
targetBotId: row.targetBotId,
|
|
605
|
+
sourceBotRevision: row.sourceBotRevision,
|
|
606
|
+
targetBotRevision: row.targetBotRevision,
|
|
607
|
+
manifestHash: row.job?.manifestHash,
|
|
608
|
+
status: row.job?.status ?? (row.applyStarted ? "applied" : "interrupted"),
|
|
609
|
+
error: row.job?.error,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
function findUser(req) {
|
|
613
|
+
const owner = getOwner(req);
|
|
614
|
+
if (!owner)
|
|
615
|
+
fail(401, "Authentication required");
|
|
616
|
+
const row = receipts.find((r) => r.id === req.params.transferId &&
|
|
617
|
+
r.roomId === req.params.id &&
|
|
618
|
+
r.accountId === owner.id &&
|
|
619
|
+
(r.expiresAt > Date.now() || r.job?.stopUnconfirmed === true));
|
|
620
|
+
if (!row)
|
|
621
|
+
fail(404, "Transfer missing or expired");
|
|
622
|
+
authorize(row);
|
|
623
|
+
return row;
|
|
624
|
+
}
|
|
625
|
+
async function confirmStopped(row) {
|
|
626
|
+
if (!row.job?.stopUnconfirmed && !running.get(row.id)?.blocked)
|
|
627
|
+
return;
|
|
628
|
+
const signal = AbortSignal.timeout(30_000);
|
|
629
|
+
for (const source of [true, false]) {
|
|
630
|
+
const result = (await rpc(row, "transfer_fence", {}, signal, source));
|
|
631
|
+
if (result?.ok !== true)
|
|
632
|
+
fail(409, "Device IO stop not confirmed");
|
|
633
|
+
}
|
|
634
|
+
authorize(row);
|
|
635
|
+
await updateJob(row.id, (job) => {
|
|
636
|
+
delete job.stopUnconfirmed;
|
|
637
|
+
});
|
|
638
|
+
authorize(row);
|
|
639
|
+
const slot = running.get(row.id);
|
|
640
|
+
if (slot?.blocked) {
|
|
641
|
+
slot.blocked = false;
|
|
642
|
+
releaseSlot(row.id);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
function responseError(res, error) {
|
|
646
|
+
const status = Number(error?.status) || 502;
|
|
647
|
+
res.status(status).json({
|
|
648
|
+
error: status === 502 ? "Transfer operation failed; inspect status and resume explicitly" : error.message,
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
function reserve(row) {
|
|
652
|
+
if (closing)
|
|
653
|
+
fail(503, "Transfer scheduler closing");
|
|
654
|
+
if (running.has(row.id))
|
|
655
|
+
fail(409, "Transfer operation already running");
|
|
656
|
+
if (receipts.some((r) => r.job?.stopUnconfirmed &&
|
|
657
|
+
[r.sourceDeviceId, r.targetDeviceId].some((d) => d === row.sourceDeviceId || d === row.targetDeviceId)))
|
|
658
|
+
fail(409, "Device IO stop unconfirmed; recovery required");
|
|
659
|
+
if (running.size >= maxJobs ||
|
|
660
|
+
[...running.values()].some((slot) => slot.deviceIds.some((d) => d === row.sourceDeviceId || d === row.targetDeviceId)))
|
|
661
|
+
fail(429, "Transfer capacity busy");
|
|
662
|
+
const controller = new AbortController();
|
|
663
|
+
const deadline = setTimeout(() => controller.abort(new Error("Transfer deadline exceeded")), 20 * 60 * 1000);
|
|
664
|
+
deadline.unref();
|
|
665
|
+
const slot = {
|
|
666
|
+
controller,
|
|
667
|
+
done: Promise.resolve(),
|
|
668
|
+
deviceIds: [row.sourceDeviceId, row.targetDeviceId],
|
|
669
|
+
blocked: false,
|
|
670
|
+
deadline,
|
|
671
|
+
};
|
|
672
|
+
running.set(row.id, slot);
|
|
673
|
+
return slot;
|
|
674
|
+
}
|
|
675
|
+
function schedule(row, slot) {
|
|
676
|
+
const signal = slot.controller.signal;
|
|
677
|
+
slot.done = (async () => {
|
|
678
|
+
try {
|
|
679
|
+
row = await updateJob(row.id, (j) => {
|
|
680
|
+
j.status = "staging";
|
|
681
|
+
delete j.error;
|
|
682
|
+
});
|
|
683
|
+
signal.throwIfAborted();
|
|
684
|
+
authorize(row);
|
|
685
|
+
let manifest = row.job.manifest;
|
|
686
|
+
if (!manifest) {
|
|
687
|
+
const result = (await rpc(row, "transfer_prepare_export", { paths: row.job.paths, recursive: row.job.recursive }, signal, true));
|
|
688
|
+
manifest = "manifest" in result ? result.manifest : result;
|
|
689
|
+
if (!manifest ||
|
|
690
|
+
manifest.version !== 2 ||
|
|
691
|
+
!Array.isArray(manifest.files) ||
|
|
692
|
+
manifest.files.length > TRANSFER_LIMITS.maxFiles ||
|
|
693
|
+
!Number.isSafeInteger(manifest.totalBytes) ||
|
|
694
|
+
manifest.totalBytes > TRANSFER_LIMITS.maxTransferBytes ||
|
|
695
|
+
!Number.isSafeInteger(manifest.totalChunks) ||
|
|
696
|
+
manifest.totalChunks >
|
|
697
|
+
TRANSFER_LIMITS.maxTransferBytes / TRANSFER_LIMITS.minChunkBytes + TRANSFER_LIMITS.maxFiles)
|
|
698
|
+
fail(502, "Invalid manifest");
|
|
699
|
+
manifest = { ...manifest, transferId: row.localTransferId };
|
|
700
|
+
validateChunkedManifest(manifest);
|
|
701
|
+
if (manifest.files.some((file) => !file.chunkHashes || file.chunkHashes.length !== file.chunkCount))
|
|
702
|
+
fail(502, "Source chunk hashes required");
|
|
703
|
+
const saved = manifest;
|
|
704
|
+
row = await updateJob(row.id, (j) => {
|
|
705
|
+
j.manifest = saved;
|
|
706
|
+
j.manifestHash = createHash("sha256").update(JSON.stringify(saved)).digest("hex");
|
|
707
|
+
j.summary = transferSummary(saved);
|
|
708
|
+
});
|
|
709
|
+
signal.throwIfAborted();
|
|
710
|
+
authorize(row);
|
|
711
|
+
}
|
|
712
|
+
const initial = (await rpc(row, "transfer_init", { manifest }, signal));
|
|
713
|
+
const received = new Set(initial.receivedChunks ?? []);
|
|
714
|
+
for (const file of manifest.files) {
|
|
715
|
+
for (let i = 0; i < file.chunkCount; i++) {
|
|
716
|
+
const chunkIndex = file.firstChunkIndex + i;
|
|
717
|
+
if (received.has(chunkIndex))
|
|
718
|
+
continue;
|
|
719
|
+
const chunk = (await rpc(row, "transfer_read_chunk", {
|
|
720
|
+
path: file.path,
|
|
721
|
+
offset: i * manifest.chunkSize,
|
|
722
|
+
size: Math.min(manifest.chunkSize, file.size - i * manifest.chunkSize),
|
|
723
|
+
expectedFileSize: file.size,
|
|
724
|
+
expectedChunkSha256: file.chunkHashes[i],
|
|
725
|
+
}, signal, true));
|
|
726
|
+
if (typeof chunk.data !== "string" ||
|
|
727
|
+
typeof chunk.sha256 !== "string" ||
|
|
728
|
+
chunk.sha256 !== file.chunkHashes[i] ||
|
|
729
|
+
createHash("sha256").update(Buffer.from(chunk.data, "base64")).digest("hex") !== chunk.sha256)
|
|
730
|
+
fail(502, "Invalid source chunk");
|
|
731
|
+
const progress = await rpc(row, "transfer_chunk", {
|
|
732
|
+
chunk: {
|
|
733
|
+
transferId: row.localTransferId,
|
|
734
|
+
chunkIndex,
|
|
735
|
+
path: file.path,
|
|
736
|
+
offset: i * manifest.chunkSize,
|
|
737
|
+
size: Math.min(manifest.chunkSize, file.size - i * manifest.chunkSize),
|
|
738
|
+
data: chunk.data,
|
|
739
|
+
sha256: chunk.sha256,
|
|
740
|
+
},
|
|
741
|
+
}, signal);
|
|
742
|
+
row = await updateJob(row.id, (j) => {
|
|
743
|
+
j.summary = { ...j.summary, ...transferSummary(progress) };
|
|
744
|
+
});
|
|
745
|
+
signal.throwIfAborted();
|
|
746
|
+
authorize(row);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
const preview = await rpc(row, "transfer_preview", {}, signal);
|
|
750
|
+
await updateJob(row.id, (j) => {
|
|
751
|
+
j.status = "ready";
|
|
752
|
+
j.summary = { ...j.summary, ...transferSummary(preview) };
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
catch (error) {
|
|
756
|
+
slot.blocked = !!error?.stopUnconfirmed;
|
|
757
|
+
await updateJob(row.id, (j) => {
|
|
758
|
+
if (slot.blocked)
|
|
759
|
+
j.stopUnconfirmed = true;
|
|
760
|
+
if (j.status !== "cancelling" && j.status !== "cancelled") {
|
|
761
|
+
j.status = signal.aborted ? "failed" : "interrupted";
|
|
762
|
+
j.error = slot.blocked
|
|
763
|
+
? "Sender stop unconfirmed; device recovery required"
|
|
764
|
+
: "Transfer interrupted; explicitly resume the saved manifest";
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
finally {
|
|
769
|
+
if (!slot.blocked &&
|
|
770
|
+
running.get(row.id) === slot &&
|
|
771
|
+
receipts.find((r) => r.id === row.id)?.job?.status !== "cancelling")
|
|
772
|
+
releaseSlot(row.id);
|
|
773
|
+
}
|
|
774
|
+
})();
|
|
775
|
+
// A storage failure is visible as an interrupted job after restart; never log raw RPC data.
|
|
776
|
+
void slot.done.catch(() => { });
|
|
777
|
+
}
|
|
778
|
+
options.app.get("/api/rooms/:id/transfers", async (req, res) => {
|
|
779
|
+
try {
|
|
780
|
+
const owner = getOwner(req);
|
|
781
|
+
if (!owner)
|
|
782
|
+
fail(401, "Authentication required");
|
|
783
|
+
if (!store.snapshot().rooms.some((r) => r.id === req.params.id && r.accountId === owner.id))
|
|
784
|
+
fail(404, "Room missing");
|
|
785
|
+
const rows = receipts.filter((r) => r.roomId === req.params.id &&
|
|
786
|
+
r.accountId === owner.id &&
|
|
787
|
+
(r.expiresAt > Date.now() || r.job?.stopUnconfirmed === true));
|
|
788
|
+
const transfers = rows.map((r) => {
|
|
789
|
+
try {
|
|
790
|
+
authorize(r);
|
|
791
|
+
return view(r);
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
return { ...view(r), status: "failed", error: "Transfer scope changed" };
|
|
795
|
+
}
|
|
796
|
+
});
|
|
797
|
+
// Older agent-created receipts have no sender job; query only their bounded tail.
|
|
798
|
+
for (const row of rows.filter((r) => !r.job && !r.applyStarted).slice(-10)) {
|
|
799
|
+
try {
|
|
800
|
+
const status = await rpc(row, "transfer_status", {}, AbortSignal.timeout(3000));
|
|
801
|
+
Object.assign(transfers.find((t) => t.transferId === row.id), transferSummary(status));
|
|
802
|
+
}
|
|
803
|
+
catch {
|
|
804
|
+
/* Keep interruption visible if the receiver cannot be inspected. */
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
res.json({ transfers });
|
|
808
|
+
}
|
|
809
|
+
catch (error) {
|
|
810
|
+
responseError(res, error);
|
|
811
|
+
}
|
|
812
|
+
});
|
|
813
|
+
options.app.post("/api/rooms/:id/transfers/start", async (req, res) => {
|
|
814
|
+
let reserved;
|
|
815
|
+
let row;
|
|
816
|
+
try {
|
|
817
|
+
const owner = getOwner(req);
|
|
818
|
+
if (!owner)
|
|
819
|
+
fail(401, "Authentication required");
|
|
820
|
+
const body = req.body ?? {};
|
|
821
|
+
if (!field(body.idempotencyKey) ||
|
|
822
|
+
!field(body.sourceBotId) ||
|
|
823
|
+
!field(body.targetBotId) ||
|
|
824
|
+
!Array.isArray(body.paths) ||
|
|
825
|
+
!body.paths.length ||
|
|
826
|
+
body.paths.length > DEVICE_FILE_SYNC_LIMITS.files ||
|
|
827
|
+
!body.paths.every(field) ||
|
|
828
|
+
(body.recursive !== undefined && typeof body.recursive !== "boolean"))
|
|
829
|
+
fail(400, "Idempotency key, Bots and bounded paths required");
|
|
830
|
+
await queue;
|
|
831
|
+
const state = store.snapshot();
|
|
832
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
833
|
+
const source = state.bots.find((b) => b.id === body.sourceBotId);
|
|
834
|
+
const target = state.bots.find((b) => b.id === body.targetBotId);
|
|
835
|
+
if (!room || !source || !target)
|
|
836
|
+
fail(404, "Room or Bot missing");
|
|
837
|
+
if (source.id === target.id)
|
|
838
|
+
fail(400, "Source and target Bots must differ");
|
|
839
|
+
const paths = [...new Set(body.paths)].sort();
|
|
840
|
+
const fingerprint = createHash("sha256")
|
|
841
|
+
.update(JSON.stringify([
|
|
842
|
+
room.id,
|
|
843
|
+
source.id,
|
|
844
|
+
source.revision,
|
|
845
|
+
target.id,
|
|
846
|
+
target.revision,
|
|
847
|
+
paths,
|
|
848
|
+
body.recursive === true,
|
|
849
|
+
membership(room.botIds),
|
|
850
|
+
]))
|
|
851
|
+
.digest("hex");
|
|
852
|
+
const existing = receipts.find((r) => r.accountId === owner.id && r.job?.idempotencyKey === body.idempotencyKey);
|
|
853
|
+
if (existing) {
|
|
854
|
+
if (existing.job.fingerprint !== fingerprint)
|
|
855
|
+
fail(409, "Idempotency key belongs to another request");
|
|
856
|
+
authorize(existing);
|
|
857
|
+
return res.json(view(existing));
|
|
858
|
+
}
|
|
859
|
+
row = {
|
|
860
|
+
id: randomUUID(),
|
|
861
|
+
sourceDeviceId: source.deviceId,
|
|
862
|
+
targetDeviceId: target.deviceId,
|
|
863
|
+
sourceBotId: source.id,
|
|
864
|
+
targetBotId: target.id,
|
|
865
|
+
sourceBotRevision: source.revision,
|
|
866
|
+
targetBotRevision: target.revision,
|
|
867
|
+
accountId: owner.id,
|
|
868
|
+
roomId: room.id,
|
|
869
|
+
roomMembers: membership(room.botIds),
|
|
870
|
+
localTransferId: randomUUID(),
|
|
871
|
+
expiresAt: Date.now() + TTL,
|
|
872
|
+
job: {
|
|
873
|
+
idempotencyKey: body.idempotencyKey,
|
|
874
|
+
fingerprint,
|
|
875
|
+
paths,
|
|
876
|
+
recursive: body.recursive === true,
|
|
877
|
+
status: "queued",
|
|
878
|
+
summary: {},
|
|
879
|
+
},
|
|
880
|
+
};
|
|
881
|
+
authorize(row);
|
|
882
|
+
reserved = reserve(row);
|
|
883
|
+
const candidate = row;
|
|
884
|
+
row = await transact((draft) => {
|
|
885
|
+
if (draft.length >= MAX_RECEIPTS)
|
|
886
|
+
fail(429, "Transfer registry full");
|
|
887
|
+
if (draft.some((r) => r.accountId === owner.id && r.job?.idempotencyKey === body.idempotencyKey))
|
|
888
|
+
fail(409, "Request already registered; retry the same key");
|
|
889
|
+
draft.push(candidate);
|
|
890
|
+
return candidate;
|
|
891
|
+
});
|
|
892
|
+
authorize(row);
|
|
893
|
+
schedule(row, reserved);
|
|
894
|
+
res.status(202).json(view(row));
|
|
895
|
+
}
|
|
896
|
+
catch (error) {
|
|
897
|
+
if (reserved && row) {
|
|
898
|
+
releaseSlot(row.id);
|
|
899
|
+
await updateJob(row.id, (j) => {
|
|
900
|
+
j.status = "interrupted";
|
|
901
|
+
j.error = "Transfer startup interrupted";
|
|
902
|
+
}).catch(() => { });
|
|
903
|
+
}
|
|
904
|
+
responseError(res, error);
|
|
905
|
+
}
|
|
906
|
+
});
|
|
907
|
+
options.app.post("/api/rooms/:id/transfers/:transferId/resume", async (req, res) => {
|
|
908
|
+
let slot;
|
|
909
|
+
let row;
|
|
910
|
+
try {
|
|
911
|
+
row = findUser(req);
|
|
912
|
+
const body = req.body ?? {};
|
|
913
|
+
if (!row.job ||
|
|
914
|
+
row.applyStarted ||
|
|
915
|
+
!["interrupted", "failed"].includes(row.job.status) ||
|
|
916
|
+
body.manifestHash !== row.job.manifestHash ||
|
|
917
|
+
body.sourceBotRevision !== row.sourceBotRevision ||
|
|
918
|
+
body.targetBotRevision !== row.targetBotRevision)
|
|
919
|
+
fail(409, "Explicit saved manifest and original Bot revisions required");
|
|
920
|
+
if (!row.job.manifest)
|
|
921
|
+
fail(409, "No saved manifest; start a new request");
|
|
922
|
+
await confirmStopped(row);
|
|
923
|
+
authorize(row);
|
|
924
|
+
slot = reserve(row);
|
|
925
|
+
const id = row.id;
|
|
926
|
+
row = await transact((draft) => {
|
|
927
|
+
const current = draft.find((r) => r.id === id);
|
|
928
|
+
current.job.status = "queued";
|
|
929
|
+
current.expiresAt = Date.now() + TTL;
|
|
930
|
+
return current;
|
|
931
|
+
});
|
|
932
|
+
authorize(row);
|
|
933
|
+
schedule(row, slot);
|
|
934
|
+
res.status(202).json(view(row));
|
|
935
|
+
}
|
|
936
|
+
catch (error) {
|
|
937
|
+
if (slot && row) {
|
|
938
|
+
releaseSlot(row.id);
|
|
939
|
+
await updateJob(row.id, (j) => {
|
|
940
|
+
j.status = "interrupted";
|
|
941
|
+
j.error = "Transfer resume interrupted";
|
|
942
|
+
}).catch(() => { });
|
|
943
|
+
}
|
|
944
|
+
responseError(res, error);
|
|
945
|
+
}
|
|
946
|
+
});
|
|
947
|
+
options.app.get("/api/rooms/:id/transfers/:transferId/preview", async (req, res) => {
|
|
948
|
+
try {
|
|
949
|
+
const row = findUser(req);
|
|
950
|
+
if (row.job?.status !== "ready")
|
|
951
|
+
fail(409, "Transfer is not ready");
|
|
952
|
+
const result = await rpc(row, "transfer_preview", {}, AbortSignal.timeout(30_000));
|
|
953
|
+
res.json({ ...transferSummary(result), transferId: row.id });
|
|
954
|
+
}
|
|
955
|
+
catch (error) {
|
|
956
|
+
responseError(res, error);
|
|
957
|
+
}
|
|
958
|
+
});
|
|
959
|
+
options.app.post("/api/rooms/:id/transfers/:transferId/apply", async (req, res) => {
|
|
960
|
+
let slot;
|
|
961
|
+
let row;
|
|
962
|
+
try {
|
|
963
|
+
row = findUser(req);
|
|
964
|
+
const body = req.body ?? {};
|
|
965
|
+
if (!field(body.revision) ||
|
|
966
|
+
!Array.isArray(body.overwritePaths) ||
|
|
967
|
+
body.overwritePaths.length > TRANSFER_LIMITS.maxFiles ||
|
|
968
|
+
!body.overwritePaths.every(field))
|
|
969
|
+
fail(400, "Explicit revision and overwrite paths required");
|
|
970
|
+
if (!row.job && !row.applyStarted) {
|
|
971
|
+
const preview = await rpc(row, "transfer_preview", {}, AbortSignal.timeout(30_000));
|
|
972
|
+
const id = row.id;
|
|
973
|
+
row = await transact((draft) => {
|
|
974
|
+
const current = draft.find((r) => r.id === id);
|
|
975
|
+
if (current.applyStarted)
|
|
976
|
+
fail(409, "Apply already attempted");
|
|
977
|
+
current.job = {
|
|
978
|
+
idempotencyKey: `agent:${id}`,
|
|
979
|
+
fingerprint: id,
|
|
980
|
+
paths: [],
|
|
981
|
+
recursive: false,
|
|
982
|
+
status: "ready",
|
|
983
|
+
summary: transferSummary(preview),
|
|
984
|
+
};
|
|
985
|
+
return current;
|
|
986
|
+
});
|
|
987
|
+
authorize(row);
|
|
988
|
+
}
|
|
989
|
+
if (row.job?.status !== "ready" || row.applyStarted)
|
|
990
|
+
fail(409, "Transfer not ready or apply already attempted");
|
|
991
|
+
slot = reserve(row);
|
|
992
|
+
row = await transact((draft) => {
|
|
993
|
+
const current = draft.find((r) => r.id === row.id);
|
|
994
|
+
if (current.applyStarted || current.job?.status !== "ready")
|
|
995
|
+
fail(409, "Apply already attempted");
|
|
996
|
+
current.applyStarted = true;
|
|
997
|
+
current.job.status = "applying";
|
|
998
|
+
return current;
|
|
999
|
+
});
|
|
1000
|
+
const activeRow = row;
|
|
1001
|
+
slot.done = (async () => {
|
|
1002
|
+
const result = await rpc(activeRow, "transfer_apply", { revision: body.revision, overwritePaths: body.overwritePaths }, slot.controller.signal);
|
|
1003
|
+
await updateJob(activeRow.id, (j) => {
|
|
1004
|
+
j.status = "applied";
|
|
1005
|
+
j.summary = { ...j.summary, ...transferSummary(result) };
|
|
1006
|
+
});
|
|
1007
|
+
})();
|
|
1008
|
+
await slot.done;
|
|
1009
|
+
res.json(view(receipts.find((r) => r.id === activeRow.id)));
|
|
1010
|
+
}
|
|
1011
|
+
catch (error) {
|
|
1012
|
+
if (slot)
|
|
1013
|
+
slot.blocked = !!error?.stopUnconfirmed;
|
|
1014
|
+
if (row && slot)
|
|
1015
|
+
await updateJob(row.id, (j) => {
|
|
1016
|
+
if (slot.blocked)
|
|
1017
|
+
j.stopUnconfirmed = true;
|
|
1018
|
+
j.status = "failed";
|
|
1019
|
+
j.error = "Apply failed; inspect target before starting a new transfer";
|
|
1020
|
+
}).catch(() => { });
|
|
1021
|
+
responseError(res, error);
|
|
1022
|
+
}
|
|
1023
|
+
finally {
|
|
1024
|
+
if (slot && row && running.get(row.id) === slot)
|
|
1025
|
+
releaseSlot(row.id);
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
const aborting = new Set();
|
|
1029
|
+
options.app.post("/api/rooms/:id/transfers/:transferId/abort", async (req, res) => {
|
|
1030
|
+
let ownsAbort = false;
|
|
1031
|
+
let slot;
|
|
1032
|
+
let row;
|
|
1033
|
+
try {
|
|
1034
|
+
row = findUser(req);
|
|
1035
|
+
if (!row.job || row.applyStarted)
|
|
1036
|
+
fail(409, "Cannot abort an applied or applying transfer");
|
|
1037
|
+
if (row.job.status === "cancelled")
|
|
1038
|
+
return res.json(view(row));
|
|
1039
|
+
if (aborting.has(row.id))
|
|
1040
|
+
fail(409, "Transfer cancellation already running");
|
|
1041
|
+
aborting.add(row.id);
|
|
1042
|
+
ownsAbort = true;
|
|
1043
|
+
await confirmStopped(row);
|
|
1044
|
+
authorize(row);
|
|
1045
|
+
const active = running.get(row.id);
|
|
1046
|
+
row = await updateJob(row.id, (j) => {
|
|
1047
|
+
j.status = "cancelling";
|
|
1048
|
+
});
|
|
1049
|
+
authorize(row);
|
|
1050
|
+
active?.controller.abort(new Error("Transfer cancelled"));
|
|
1051
|
+
if (active)
|
|
1052
|
+
await active.done;
|
|
1053
|
+
if (active?.blocked)
|
|
1054
|
+
fail(409, "Sender stop unconfirmed; device recovery required");
|
|
1055
|
+
authorize(row);
|
|
1056
|
+
if (active && running.get(row.id) === active)
|
|
1057
|
+
releaseSlot(row.id);
|
|
1058
|
+
slot = reserve(row);
|
|
1059
|
+
const activeRow = row;
|
|
1060
|
+
slot.done = (async () => {
|
|
1061
|
+
await rpc(activeRow, "transfer_abort", {}, slot.controller.signal);
|
|
1062
|
+
await updateJob(activeRow.id, (j) => {
|
|
1063
|
+
j.status = "cancelled";
|
|
1064
|
+
delete j.error;
|
|
1065
|
+
});
|
|
1066
|
+
})();
|
|
1067
|
+
await slot.done;
|
|
1068
|
+
res.json(view(receipts.find((r) => r.id === activeRow.id)));
|
|
1069
|
+
}
|
|
1070
|
+
catch (error) {
|
|
1071
|
+
if (slot)
|
|
1072
|
+
slot.blocked = !!error?.stopUnconfirmed;
|
|
1073
|
+
if (row && ownsAbort)
|
|
1074
|
+
await updateJob(row.id, (j) => {
|
|
1075
|
+
if (slot?.blocked)
|
|
1076
|
+
j.stopUnconfirmed = true;
|
|
1077
|
+
if (j.status === "cancelling") {
|
|
1078
|
+
j.status = "interrupted";
|
|
1079
|
+
j.error = "Cancellation incomplete; retry abort";
|
|
1080
|
+
}
|
|
1081
|
+
}).catch(() => { });
|
|
1082
|
+
responseError(res, error);
|
|
1083
|
+
}
|
|
1084
|
+
finally {
|
|
1085
|
+
if (row && ownsAbort)
|
|
1086
|
+
aborting.delete(row.id);
|
|
1087
|
+
if (slot && row && running.get(row.id) === slot)
|
|
1088
|
+
releaseSlot(row.id);
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
return {
|
|
1092
|
+
async close() {
|
|
1093
|
+
closing = true;
|
|
1094
|
+
for (const slot of running.values())
|
|
1095
|
+
slot.controller.abort(new Error("Scheduler closing"));
|
|
1096
|
+
await Promise.allSettled([...running.values()].map((slot) => slot.done));
|
|
1097
|
+
await queue;
|
|
1098
|
+
},
|
|
1099
|
+
};
|
|
293
1100
|
}
|