pi-web-ui 0.114.0 → 0.114.2
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 +45 -0
- package/bin/pi-web-ui.mjs +15 -7
- package/dist/server/agent-service.js +190 -65
- package/dist/server/attachments.js +48 -2
- package/dist/server/canvas/canvas-agent-tool.js +3 -3
- package/dist/server/canvas/canvas-cards.js +1 -1
- package/dist/server/canvas/canvas-scheduled-task.js +45 -0
- package/dist/server/canvas/canvas-validation.js +1 -1
- package/dist/server/client-state.js +6 -2
- package/dist/server/communicate-tool.js +37 -11
- package/dist/server/device-center/connector.js +33 -14
- package/dist/server/device-center/hub-page.js +1 -1
- package/dist/server/device-center/hub.js +2 -1
- package/dist/server/device-center/local-hub.js +92 -0
- package/dist/server/device-center/local.js +60 -7
- package/dist/server/device-center/path-portal.js +1 -1
- package/dist/server/device-center/relay.js +45 -8
- package/dist/server/dispatch-domain-handlers.js +1 -0
- package/dist/server/dsh/dsh-agent-service.js +5 -1
- package/dist/server/durable/durable-event-projector.js +19 -3
- package/dist/server/durable/durable-models.js +134 -65
- package/dist/server/engine-probe.js +36 -6
- package/dist/server/global-loader.js +40 -2
- package/dist/server/index.js +56 -32
- package/dist/server/model-resolver.js +4 -1
- package/dist/server/patch-bash-process.js +125 -0
- package/dist/server/plugins.js +26 -2
- package/dist/server/preset-fields.js +7 -0
- package/dist/server/preset-share.js +1 -0
- package/dist/server/prompt-templates.js +106 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/schedule-agent-tool.js +49 -26
- package/dist/server/scheduler-tasks.js +129 -11
- package/dist/server/settings-service.js +6 -0
- package/dist/server/text-quote.js +9 -0
- package/dist/server/tool-manager.js +2 -1
- package/dist/server/universal/drivers/claude-code.js +5 -0
- package/dist/server/universal/drivers/codex.js +336 -0
- package/dist/server/universal/index.js +1 -0
- package/dist/server/universal/universal-attachments.js +24 -1
- package/dist/server/universal/universal-session.js +42 -18
- package/docs/device-center.md +9 -3
- package/package.json +2 -2
- package/plugins/catalog.json +10 -0
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BIlQ89vr.js +1 -0
- package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +1 -0
- package/web/dist/assets/{CanvasStudio-BEJZE5BI.js → CanvasStudio-B3W6b_rA.js} +3 -3
- package/web/dist/assets/{CanvasStudio-CgUNHqos.js → CanvasStudio-Csv1Sj1-.js} +3 -3
- package/web/dist/assets/DeviceCenter-BQdDcO8A.js +3 -0
- package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +3 -0
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
- package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
- package/web/dist/assets/FilePreview-B9xoU6ON.js +2 -0
- package/web/dist/assets/FilePreview-DUQpVZkH.js +2 -0
- package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +1 -0
- package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +1 -0
- package/web/dist/assets/GroupConversation-CyIpQzDd.js +1 -0
- package/web/dist/assets/GroupConversation-DgYV3uYS.js +1 -0
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
- package/web/dist/assets/SCMPanel-imYI2Ecw.js +2 -0
- package/web/dist/assets/SCMPanel-sVZcV7dR.js +2 -0
- package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +20 -0
- package/web/dist/assets/SettingsModal-mb4e34-0.js +20 -0
- package/web/dist/assets/{TerminalPanel-DL20uKgU.js → TerminalPanel-CLkJJvxg.js} +2 -2
- package/web/dist/assets/{TerminalPanel-D6cPRFei.js → TerminalPanel-DpcIellm.js} +2 -2
- package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +1 -0
- package/web/dist/assets/TuiOverlayModal-DCu01lks.js +1 -0
- package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
- package/web/dist/assets/{desktop-DPyTy4M3.js → desktop-YguLbrX1.js} +1 -1
- package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
- package/web/dist/assets/index-Cdh3sibd.js +85 -0
- package/web/dist/assets/index-DDZMv6LO.css +1 -0
- package/web/dist/assets/index-DWw_SxRq.js +85 -0
- package/web/dist/assets/{plugin-host-CqA4yW6w.js → plugin-host-BRBg6zmQ.js} +1 -1
- package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/device-center/local-page.js +0 -17
- package/dist/server/device-center/smoke-preview.js +0 -3
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/BgTasksModal-CS7UNzcw.js +0 -1
- package/web/dist/assets/BgTasksModal-Dk-tp78W.js +0 -1
- package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +0 -3
- package/web/dist/assets/DeviceCenter-CVblvhNX.js +0 -3
- package/web/dist/assets/Dropdown-Oug0DDte.js +0 -1
- package/web/dist/assets/FilePreview-CvdX6nr6.js +0 -2
- package/web/dist/assets/FilePreview-kCZhfBAF.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +0 -1
- package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +0 -1
- package/web/dist/assets/GroupConversation-Cgo4xbpa.js +0 -1
- package/web/dist/assets/GroupConversation-DZ71jEi8.js +0 -1
- package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +0 -2
- package/web/dist/assets/PiSetupModal-mkWPSxMj.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +0 -1
- package/web/dist/assets/SCMPanel-BP1TUT-V.js +0 -2
- package/web/dist/assets/SCMPanel-BscPm9kf.js +0 -2
- package/web/dist/assets/SettingsModal-C8UgMjVM.js +0 -20
- package/web/dist/assets/SettingsModal-VynB7jNb.js +0 -20
- package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +0 -1
- package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +0 -1
- package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +0 -1
- package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +0 -1
- package/web/dist/assets/app-globals-CnO6KlEM.js +0 -325
- package/web/dist/assets/index-CPgAH5q7.js +0 -83
- package/web/dist/assets/index-Cje8iugL.js +0 -83
- package/web/dist/assets/index-DnKeiDbj.css +0 -1
- package/web/dist/assets/theme-BqdAjEjF.js +0 -1
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { isSafeGraphId, loadCanvasGraph } from "./canvas-store.js";
|
|
4
|
+
import { assertCanvasGraph } from "./canvas-validation.js";
|
|
5
|
+
/** Scheduling must never recreate a deleted default graph. */
|
|
6
|
+
export function loadScheduledCanvas(dataDir, graphId) {
|
|
7
|
+
if (!isSafeGraphId(graphId))
|
|
8
|
+
throw new Error("Invalid canvas graph id");
|
|
9
|
+
if (!existsSync(join(dataDir, "canvas", `${graphId}.json`)))
|
|
10
|
+
throw new Error(`Canvas graph not found: ${graphId}`);
|
|
11
|
+
const graph = loadCanvasGraph(dataDir, graphId);
|
|
12
|
+
assertCanvasGraph(graph);
|
|
13
|
+
if (graph.id !== graphId)
|
|
14
|
+
throw new Error("Canvas graph id mismatch");
|
|
15
|
+
return graph;
|
|
16
|
+
}
|
|
17
|
+
export function validateScheduledCanvas(dataDir, task) {
|
|
18
|
+
if (task.target === "canvas")
|
|
19
|
+
loadScheduledCanvas(dataDir, task.graphId ?? "");
|
|
20
|
+
}
|
|
21
|
+
/** Await the existing orchestrator and report its actual outcome, including approval pauses. */
|
|
22
|
+
export async function executeScheduledCanvas(dataDir, orchestrator, task) {
|
|
23
|
+
const graphId = task.graphId ?? "";
|
|
24
|
+
let runId;
|
|
25
|
+
try {
|
|
26
|
+
const graph = loadScheduledCanvas(dataDir, graphId);
|
|
27
|
+
await orchestrator.runAll(graph, task.prompt || undefined, task.cwd);
|
|
28
|
+
runId = graph.run?.id;
|
|
29
|
+
if (!runId)
|
|
30
|
+
throw new Error("Canvas run did not start");
|
|
31
|
+
// Read back authoritative state to detect deletion, cancellation, or replacement during execution.
|
|
32
|
+
const current = loadScheduledCanvas(dataDir, graphId);
|
|
33
|
+
if (current.run?.id !== runId)
|
|
34
|
+
throw new Error("Canvas run was replaced before completion");
|
|
35
|
+
return {
|
|
36
|
+
ok: current.status === "completed",
|
|
37
|
+
graphId,
|
|
38
|
+
runId,
|
|
39
|
+
...(current.status === "completed" ? {} : { error: current.run?.error || `Canvas run ${current.status}` }),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
return { ok: false, graphId, ...(runId ? { runId } : {}), error: error.message };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -911,6 +911,9 @@ export class ClientStateStore {
|
|
|
911
911
|
questionPresentation: stored?.questionPresentation === "all" || stored?.questionPresentation === "manual"
|
|
912
912
|
? stored.questionPresentation
|
|
913
913
|
: "queue",
|
|
914
|
+
toolApprovalPresentation: stored?.toolApprovalPresentation === "queue" || stored?.toolApprovalPresentation === "manual"
|
|
915
|
+
? stored.toolApprovalPresentation
|
|
916
|
+
: "all",
|
|
914
917
|
questionTimeoutSeconds: Number.isFinite(stored?.questionTimeoutSeconds) && Number(stored?.questionTimeoutSeconds) >= 0
|
|
915
918
|
? Math.floor(Number(stored?.questionTimeoutSeconds))
|
|
916
919
|
: 240,
|
|
@@ -996,6 +999,7 @@ export class ClientStateStore {
|
|
|
996
999
|
editSoftEnabled: settings.editSoftEnabled ?? cur.editSoftEnabled ?? false,
|
|
997
1000
|
questionnaireEnabled: settings.questionnaireEnabled ?? cur.questionnaireEnabled ?? true,
|
|
998
1001
|
questionPresentation: settings.questionPresentation ?? cur.questionPresentation ?? "queue",
|
|
1002
|
+
toolApprovalPresentation: settings.toolApprovalPresentation ?? cur.toolApprovalPresentation ?? "all",
|
|
999
1003
|
questionTimeoutSeconds: settings.questionTimeoutSeconds ?? cur.questionTimeoutSeconds ?? 240,
|
|
1000
1004
|
goalModeEnabled: settings.goalModeEnabled ?? cur.goalModeEnabled ?? true,
|
|
1001
1005
|
parallelReminderEnabled: settings.parallelReminderEnabled ?? cur.parallelReminderEnabled ?? true,
|
|
@@ -1490,7 +1494,7 @@ export class ClientStateStore {
|
|
|
1490
1494
|
/** 读取某客户端(标签页)上次使用的引擎(未设置返回 undefined)。 */
|
|
1491
1495
|
getClientEngine(clientId) {
|
|
1492
1496
|
const eng = this.load()[clientId]?.engine;
|
|
1493
|
-
return eng === "dsh" || eng === "pi" || eng === "claude" || eng === "durable" ? eng : undefined;
|
|
1497
|
+
return eng === "dsh" || eng === "pi" || eng === "codex" || eng === "claude" || eng === "durable" ? eng : undefined;
|
|
1494
1498
|
}
|
|
1495
1499
|
/** 保存某客户端(标签页)当前使用的引擎。 */
|
|
1496
1500
|
saveClientEngine(clientId, engine) {
|
|
@@ -1503,7 +1507,7 @@ export class ClientStateStore {
|
|
|
1503
1507
|
/** 读取全局默认引擎(存在 __settings__ 下,新标签页及服务重启后默认跟随)。 */
|
|
1504
1508
|
getDefaultEngine() {
|
|
1505
1509
|
const eng = this.load()[ClientStateStore.GLOBAL_SETTINGS_KEY]?.defaultEngine;
|
|
1506
|
-
return eng === "dsh" || eng === "pi" || eng === "claude" || eng === "durable" ? eng : undefined;
|
|
1510
|
+
return eng === "dsh" || eng === "pi" || eng === "codex" || eng === "claude" || eng === "durable" ? eng : undefined;
|
|
1507
1511
|
}
|
|
1508
1512
|
/** 保存全局默认引擎。 */
|
|
1509
1513
|
saveDefaultEngine(engine) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
|
+
import { Value } from "typebox/value";
|
|
2
3
|
export function makeCommunicateTool(host) {
|
|
3
4
|
const option = Type.Object({
|
|
4
5
|
label: Type.String({ minLength: 1 }),
|
|
@@ -21,7 +22,29 @@ export function makeCommunicateTool(host) {
|
|
|
21
22
|
optionsMap: Type.Optional(Type.Record(Type.String(), options)),
|
|
22
23
|
});
|
|
23
24
|
const target = Type.String({ minLength: 1, description: "parent, root, or a stable execution ID" });
|
|
24
|
-
const
|
|
25
|
+
const questions = Type.Array(question, { minItems: 1, maxItems: 3 });
|
|
26
|
+
const message = Type.String({ description: "Message to send (nonempty for send), or optional context for request" });
|
|
27
|
+
const timeoutSeconds = Type.Number({ minimum: 0, maximum: 86400 });
|
|
28
|
+
const requestId = Type.String({ minLength: 1 });
|
|
29
|
+
const answers = Type.Array(Type.Object({
|
|
30
|
+
id: Type.String(),
|
|
31
|
+
selected: Type.Array(Type.String()),
|
|
32
|
+
custom: Type.Optional(Type.String()),
|
|
33
|
+
}), { minItems: 1, maxItems: 3 });
|
|
34
|
+
// Providers need root properties; action-specific requirements are enforced at execution.
|
|
35
|
+
const parameters = Type.Object({
|
|
36
|
+
action: Type.Union([
|
|
37
|
+
Type.Literal("read"),
|
|
38
|
+
Type.Literal("send"),
|
|
39
|
+
Type.Literal("request"),
|
|
40
|
+
Type.Literal("reply"),
|
|
41
|
+
Type.Literal("escalate"),
|
|
42
|
+
], {
|
|
43
|
+
description: "read: inbox; send: requires to/message; request: to/questions; reply: requestId/answers; escalate: requestId",
|
|
44
|
+
}),
|
|
45
|
+
...Type.Partial(Type.Object({ to: target, message, questions, timeoutSeconds, requestId, answers })).properties,
|
|
46
|
+
});
|
|
47
|
+
const actionParameters = Type.Union([
|
|
25
48
|
Type.Object({ action: Type.Literal("read") }),
|
|
26
49
|
Type.Object({
|
|
27
50
|
action: Type.Literal("send"),
|
|
@@ -31,22 +54,18 @@ export function makeCommunicateTool(host) {
|
|
|
31
54
|
Type.Object({
|
|
32
55
|
action: Type.Literal("request"),
|
|
33
56
|
to: target,
|
|
34
|
-
questions
|
|
35
|
-
message: Type.Optional(
|
|
36
|
-
timeoutSeconds: Type.Optional(
|
|
57
|
+
questions,
|
|
58
|
+
message: Type.Optional(message),
|
|
59
|
+
timeoutSeconds: Type.Optional(timeoutSeconds),
|
|
37
60
|
}),
|
|
38
61
|
Type.Object({
|
|
39
62
|
action: Type.Literal("reply"),
|
|
40
|
-
requestId
|
|
41
|
-
answers
|
|
42
|
-
id: Type.String(),
|
|
43
|
-
selected: Type.Array(Type.String()),
|
|
44
|
-
custom: Type.Optional(Type.String()),
|
|
45
|
-
}), { minItems: 1, maxItems: 3 }),
|
|
63
|
+
requestId,
|
|
64
|
+
answers,
|
|
46
65
|
}),
|
|
47
66
|
Type.Object({
|
|
48
67
|
action: Type.Literal("escalate"),
|
|
49
|
-
requestId
|
|
68
|
+
requestId,
|
|
50
69
|
}),
|
|
51
70
|
]);
|
|
52
71
|
return {
|
|
@@ -64,6 +83,13 @@ export function makeCommunicateTool(host) {
|
|
|
64
83
|
],
|
|
65
84
|
parameters,
|
|
66
85
|
execute: async (_id, params, signal) => {
|
|
86
|
+
// Adapters may call execute directly, bypassing SDK argument validation.
|
|
87
|
+
for (const schema of [parameters, actionParameters]) {
|
|
88
|
+
const errors = Value.Errors(schema, params);
|
|
89
|
+
if (errors.length) {
|
|
90
|
+
throw new Error(`Invalid communicate arguments: ${errors.map((error) => `${error.instancePath || "/"}: ${error.message}`).join("; ")}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
67
93
|
const { action, ...args } = params;
|
|
68
94
|
const result = await host.communicate(action, args, signal);
|
|
69
95
|
// Host results are bounded by the service; guard adapters too (wire details <=64KB).
|
|
@@ -206,23 +206,42 @@ export function createDeviceConnector(options) {
|
|
|
206
206
|
delete responseHeaders.location;
|
|
207
207
|
}
|
|
208
208
|
sendFrame(ws, { type: "response", id, status: res.statusCode, headers: responseHeaders });
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
209
|
+
void (async () => {
|
|
210
|
+
let bytes = 0;
|
|
211
|
+
try {
|
|
212
|
+
// Pull only as fast as the relay socket drains, instead of aborting bursts.
|
|
213
|
+
for await (const data of res) {
|
|
214
|
+
const chunk = Buffer.from(data);
|
|
215
|
+
bytes += chunk.length;
|
|
216
|
+
if (bytes > RELAY_LIMITS.body)
|
|
217
|
+
throw new Error("Response too large");
|
|
218
|
+
for (let offset = 0; offset < chunk.length; offset += RELAY_LIMITS.chunk) {
|
|
219
|
+
while (ws.bufferedAmount > RELAY_LIMITS.queue / 2) {
|
|
220
|
+
if (!streams.has(id) || ws.readyState !== WebSocket.OPEN)
|
|
221
|
+
throw new Error("Cancelled");
|
|
222
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
223
|
+
}
|
|
224
|
+
if (!streams.has(id) || ws.readyState !== WebSocket.OPEN)
|
|
225
|
+
throw new Error("Cancelled");
|
|
226
|
+
await new Promise((resolve, reject) => {
|
|
227
|
+
ws.send(JSON.stringify({
|
|
228
|
+
type: "response_body",
|
|
229
|
+
id,
|
|
230
|
+
data: chunk.subarray(offset, offset + RELAY_LIMITS.chunk).toString("base64"),
|
|
231
|
+
}), (error) => (error ? reject(error) : resolve()));
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
sendFrame(ws, { type: "response_end", id });
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
213
238
|
res.destroy();
|
|
214
|
-
dispose(id);
|
|
215
239
|
sendFrame(ws, { type: "error", id });
|
|
216
240
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
});
|
|
222
|
-
res.on("error", () => {
|
|
223
|
-
sendFrame(ws, { type: "error", id });
|
|
224
|
-
dispose(id);
|
|
225
|
-
});
|
|
241
|
+
finally {
|
|
242
|
+
dispose(id);
|
|
243
|
+
}
|
|
244
|
+
})();
|
|
226
245
|
});
|
|
227
246
|
stream.req = req;
|
|
228
247
|
req.on("error", () => {
|
|
@@ -39,7 +39,7 @@ function renderRooms(){$('room-list').replaceChildren();for(const room of rooms)
|
|
|
39
39
|
function selectRoom(id){if(id===roomId)return;invalidate();roomId=id;roomData=null;clearComposer();$('error').textContent='';renderRooms();renderRoom();refresh();}
|
|
40
40
|
async function refresh(){if(!account)return;const version=++refreshVersion,epoch=generation,id=roomId;if(pollController)pollController.abort();clearTimeout(pollTimer);const controller=new AbortController();pollController=controller;$('connection').textContent=t('connecting');const timeout=setTimeout(()=>controller.abort(),15000);try{const result=await Promise.all([api('/api/devices',undefined,controller.signal),api('/api/bots',undefined,controller.signal),id?api('/api/rooms/'+encodeURIComponent(id),undefined,controller.signal):Promise.resolve(null)]);if(epoch!==generation||version!==refreshVersion)return;devices=result[0].devices.filter(device=>!revokedIds.has(device.id));bots=result[1].bots.filter(bot=>!revokedIds.has(bot.deviceId));roomData=result[2];if(roomData){const allowed=new Set(roomMembers().map(device=>device.id));mentions=mentions.filter(item=>allowed.has(item.id));}renderDevices();renderRoom();renderMentions();$('connection').textContent=t('connected');$('connection').className='ok';}catch(error){if(epoch!==generation||version!==refreshVersion)return;controller.abort();$('connection').textContent=t('connectionError');$('connection').className='error';fail(error.name==='AbortError'?new Error('Request timed out'):error);}finally{clearTimeout(timeout);if(epoch===generation&&version===refreshVersion){pollController=null;pollTimer=setTimeout(refresh,3000);}}}
|
|
41
41
|
function roomMembers(){return roomData?bots.filter(bot=>bot.enabled&&roomData.room.botIds.includes(bot.id)):[];}
|
|
42
|
-
function renderRoom(){$('room-title').textContent=roomData?roomData.room.name:t('chooseRoom');$('message-form').hidden=!roomData;const messages=$('messages'),tasks=$('tasks');const nearEnd=
|
|
42
|
+
function renderRoom(){$('room-title').textContent=roomData?roomData.room.name:t('chooseRoom');$('message-form').hidden=!roomData;const messages=$('messages'),tasks=$('tasks'),scroller=messages.parentElement;const scrollTop=scroller.scrollTop,nearEnd=scroller.scrollHeight-scrollTop-scroller.clientHeight<60;messages.replaceChildren();tasks.replaceChildren();const empty=!roomData||(!roomData.messages.length&&!roomData.tasks.length);$('chat-empty').hidden=!empty;$('empty-title').textContent=t(roomData?'emptyGroupTitle':'emptyTitle');$('empty-hint').textContent=t(roomData?'emptyGroupHint':'emptyHint');if(!roomData)return;for(const message of roomData.messages){const card=node('article',undefined,'message '+(message.sender.type==='human'?'human':'device'));const meta=node('div',undefined,'message-meta');const time=node('time',new Date(message.createdAt).toLocaleTimeString(lang,{hour:'2-digit',minute:'2-digit'}));time.dateTime=new Date(message.createdAt).toISOString();time.title=new Date(message.createdAt).toLocaleString(lang);meta.append(node('strong',message.sender.name),time);card.append(meta,node('p',message.text,'message-body'));messages.append(card);}for(const task of roomData.tasks){const card=node('article',undefined,'card');const device=bots.find(item=>item.id===task.botId);card.append(node('h3',(device?device.name:task.botId)+' · '+t(task.status)),node('p',task.id+' · '+task.deviceId,'muted'),node('p',task.text));if(task.report)card.append(node('pre',task.report,task.status==='failed'?'error':''));if(task.handoff)card.append(node('pre',JSON.stringify(task.handoff,null,2)));const row=node('div',undefined,'row');const select=node('select');select.setAttribute('aria-label',t('transfer'));const empty=node('option',t('transfer'));empty.value='';select.append(empty);for(const member of roomMembers()){const option=node('option',member.name+' · '+member.id.slice(-8)+' · '+t(member.online?'online':'offline'));option.value=member.id;select.append(option);}const button=node('button',t('prepare'));button.type='button';button.addEventListener('click',()=>{const member=roomMembers().find(item=>item.id===select.value);if(!member){fail(t('noTarget'));return;}clearComposer();mentions=[{id:member.id,name:member.name}];parentTaskId=task.id;$('parent').textContent=task.id;const handoff=task.handoff||{};for(const key of ['repository','commit','branch','instructions'])$(key).value=handoff[key]||'';$('message').value='@'+member.name+' '+task.text;$('handoff').open=true;renderMentions();$('message').focus();});row.append(select,button);card.append(row);tasks.append(card);}scroller.scrollTop=nearEnd?scroller.scrollHeight:scrollTop;}
|
|
43
43
|
function renderMentions(){$('mentions').replaceChildren();for(const mention of mentions){const chip=node('span',undefined,'chip');chip.append(node('span','@'+mention.name+' · '+mention.id.slice(-8)));const remove=node('button','×');remove.type='button';remove.setAttribute('aria-label',t('clear')+' '+mention.name);remove.addEventListener('click',()=>{mentions=mentions.filter(item=>item.id!==mention.id);renderMentions();});chip.append(remove);$('mentions').append(chip);}$('send-hint').textContent=mentions.length?t('taskHint')+mentions.map(item=>item.name+' ('+item.id.slice(-8)+')').join(', '):t('chatOnly');}
|
|
44
44
|
function closeSuggestions(){atStart=-1;candidates=[];$('suggestions').hidden=true;$('message').setAttribute('aria-expanded','false');$('message').removeAttribute('aria-activedescendant');}
|
|
45
45
|
function updateSuggestions(){const input=$('message'),before=input.value.slice(0,input.selectionStart);const match=/(?:^|\s)@([^@\n]*)$/.exec(before);if(!match){closeSuggestions();return;}atStart=before.lastIndexOf('@');const query=match[1].toLocaleLowerCase();candidates=roomMembers().filter(device=>!mentions.some(item=>item.id===device.id)&&device.name.toLocaleLowerCase().includes(query));selectedSuggestion=0;paintSuggestions();}
|
|
@@ -748,7 +748,8 @@ export async function createDeviceHub(options) {
|
|
|
748
748
|
...(error.code === "ACTIVE_TASKS" ? { code: "ACTIVE_TASKS" } : {}),
|
|
749
749
|
});
|
|
750
750
|
});
|
|
751
|
-
const server = createServer(
|
|
751
|
+
const server = options.server ?? createServer();
|
|
752
|
+
server.on("request", (req, res) => {
|
|
752
753
|
if (options.relay?.handleRequest?.(req, res))
|
|
753
754
|
return;
|
|
754
755
|
app(req, res);
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { hostname } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { createDeviceHub } from "./hub.js";
|
|
6
|
+
import { createDeviceRelay } from "./relay.js";
|
|
7
|
+
import { hashSecret } from "./store.js";
|
|
8
|
+
/** Private loopback Hub: uses the same authenticated Bot, room and task paths as a remote Hub. */
|
|
9
|
+
export async function createLocalDeviceHub(dataDir) {
|
|
10
|
+
const server = createServer();
|
|
11
|
+
await new Promise((resolve, reject) => {
|
|
12
|
+
server.once("error", reject);
|
|
13
|
+
server.listen(0, "127.0.0.1", () => {
|
|
14
|
+
server.off("error", reject);
|
|
15
|
+
resolve();
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
const address = server.address();
|
|
19
|
+
if (!address || typeof address === "string")
|
|
20
|
+
throw new Error("Local Hub address unavailable");
|
|
21
|
+
const hubUrl = `http://127.0.0.1:${address.port}`;
|
|
22
|
+
let hub;
|
|
23
|
+
let relay;
|
|
24
|
+
try {
|
|
25
|
+
hub = await createDeviceHub({
|
|
26
|
+
dataDir: join(dataDir, "local-device-hub"),
|
|
27
|
+
publicUrl: hubUrl,
|
|
28
|
+
server,
|
|
29
|
+
isOnline: (id) => relay?.isOnline(id) ?? false,
|
|
30
|
+
});
|
|
31
|
+
const credential = randomBytes(32).toString("hex");
|
|
32
|
+
const uiCredential = randomBytes(32).toString("hex");
|
|
33
|
+
// Stable local identity and durable rooms; credentials are rotated on every process start.
|
|
34
|
+
const accountId = "local-account";
|
|
35
|
+
const deviceId = "local-device";
|
|
36
|
+
await hub.store.transact((draft) => {
|
|
37
|
+
if (!draft.accounts.some((account) => account.id === accountId))
|
|
38
|
+
draft.accounts.push({ id: accountId, username: "local", passwordHash: "", createdAt: Date.now() });
|
|
39
|
+
const device = {
|
|
40
|
+
id: deviceId,
|
|
41
|
+
accountId,
|
|
42
|
+
name: hostname(),
|
|
43
|
+
credentialHash: hashSecret(credential),
|
|
44
|
+
uiCredentialHash: hashSecret(uiCredential),
|
|
45
|
+
createdAt: Date.now(),
|
|
46
|
+
};
|
|
47
|
+
const previous = draft.devices.find((entry) => entry.id === deviceId);
|
|
48
|
+
if (previous)
|
|
49
|
+
Object.assign(previous, device, { createdAt: previous.createdAt });
|
|
50
|
+
else
|
|
51
|
+
draft.devices.push(device);
|
|
52
|
+
});
|
|
53
|
+
relay = createDeviceRelay({
|
|
54
|
+
server,
|
|
55
|
+
publicUrl: hubUrl,
|
|
56
|
+
getAccount: hub.getRelayAccount,
|
|
57
|
+
authenticateDevice: (id, token) => hub.store.authenticateDevice(id, token),
|
|
58
|
+
ownsDevice: (owner, id) => hub.store.getDeviceOwner(id) === owner,
|
|
59
|
+
onTaskEvent: async (id, event) => {
|
|
60
|
+
await hub.acceptTaskEvent(id, event);
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
hub.setRelay({
|
|
64
|
+
onTask: relay.sendTask,
|
|
65
|
+
onRevoke: relay.revoke,
|
|
66
|
+
handleRequest: relay.handleRequest,
|
|
67
|
+
});
|
|
68
|
+
const config = {
|
|
69
|
+
hubUrl,
|
|
70
|
+
name: hostname(),
|
|
71
|
+
deviceId,
|
|
72
|
+
credential,
|
|
73
|
+
uiCredential,
|
|
74
|
+
allowExecution: true,
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
config,
|
|
78
|
+
async close() {
|
|
79
|
+
relay?.close();
|
|
80
|
+
await hub?.close();
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
relay?.close();
|
|
86
|
+
if (hub)
|
|
87
|
+
await hub.close();
|
|
88
|
+
else
|
|
89
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -6,6 +6,7 @@ import { getLocalBotOptions } from "./bot-catalog.js";
|
|
|
6
6
|
import { isIP } from "node:net";
|
|
7
7
|
import { installHubSetupRoutes } from "./hub-setup.js";
|
|
8
8
|
import { DeviceWorkspaceError } from "./workspaces.js";
|
|
9
|
+
import { createLocalDeviceHub } from "./local-hub.js";
|
|
9
10
|
import { createLocalBotRegistry } from "./bots.js";
|
|
10
11
|
/** Hub enrollment accepts HTTP(S) origins, including public IP addresses. */
|
|
11
12
|
export function normalizeHubUrl(input) {
|
|
@@ -58,6 +59,34 @@ export async function installLocalDeviceCenter(options) {
|
|
|
58
59
|
const bots = options.bots ?? (await createLocalBotRegistry(options.dataDir));
|
|
59
60
|
let config;
|
|
60
61
|
let connection;
|
|
62
|
+
let localHub;
|
|
63
|
+
let localStarting;
|
|
64
|
+
const activeConfig = () => config ?? localHub?.config;
|
|
65
|
+
async function ensureLocalHub() {
|
|
66
|
+
if (config || localHub || closed)
|
|
67
|
+
return;
|
|
68
|
+
if (!localStarting) {
|
|
69
|
+
localStarting = (async () => {
|
|
70
|
+
const hub = await createLocalDeviceHub(options.dataDir);
|
|
71
|
+
try {
|
|
72
|
+
const { uiCredential: _uiCredential, ...agentConfig } = hub.config;
|
|
73
|
+
localHub = hub;
|
|
74
|
+
connection = await options.connect(agentConfig, syncBots);
|
|
75
|
+
await syncBots();
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
await connection?.close();
|
|
79
|
+
connection = undefined;
|
|
80
|
+
localHub = undefined;
|
|
81
|
+
await hub.close();
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
})().finally(() => {
|
|
85
|
+
localStarting = undefined;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
await localStarting;
|
|
89
|
+
}
|
|
61
90
|
let pending;
|
|
62
91
|
let generation = 0;
|
|
63
92
|
let closed = false;
|
|
@@ -79,8 +108,11 @@ export async function installLocalDeviceCenter(options) {
|
|
|
79
108
|
}
|
|
80
109
|
}
|
|
81
110
|
async function reconnect() {
|
|
111
|
+
await localStarting;
|
|
82
112
|
await connection?.close();
|
|
83
113
|
connection = undefined;
|
|
114
|
+
await localHub?.close();
|
|
115
|
+
localHub = undefined;
|
|
84
116
|
await bots.setScope(config ? JSON.stringify([config.hubUrl, config.deviceId]) : "unpaired");
|
|
85
117
|
if (config && !closed) {
|
|
86
118
|
const { uiCredential: _uiCredential, ...agentConfig } = config;
|
|
@@ -88,7 +120,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
88
120
|
}
|
|
89
121
|
}
|
|
90
122
|
async function syncBots() {
|
|
91
|
-
const captured =
|
|
123
|
+
const captured = activeConfig();
|
|
92
124
|
if (!captured || closed)
|
|
93
125
|
return;
|
|
94
126
|
const response = await fetch(`${captured.hubUrl}/api/agent/bots`, {
|
|
@@ -109,7 +141,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
109
141
|
await response.body?.cancel();
|
|
110
142
|
if (!response.ok)
|
|
111
143
|
throw new Error("Bot configuration saved locally, but Hub synchronization failed; retry after reconnecting");
|
|
112
|
-
if (
|
|
144
|
+
if (activeConfig() !== captured || closed)
|
|
113
145
|
throw new Error("Device binding changed during Bot synchronization");
|
|
114
146
|
}
|
|
115
147
|
async function hubRequest(hubUrl, path, body) {
|
|
@@ -177,11 +209,28 @@ export async function installLocalDeviceCenter(options) {
|
|
|
177
209
|
connected: connection?.isConnected?.() ?? false,
|
|
178
210
|
});
|
|
179
211
|
});
|
|
212
|
+
// Account chat discovery is safe to relay; local settings remain device-only.
|
|
213
|
+
options.app.get("/api/device-center/chat-status", async (_req, res) => {
|
|
214
|
+
try {
|
|
215
|
+
await serialize(ensureLocalHub);
|
|
216
|
+
const current = activeConfig();
|
|
217
|
+
res.json({ hubUrl: current?.hubUrl, deviceId: current?.deviceId, ...(!config ? { local: true } : {}) });
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
res.status(503).json({ code: "LOCAL_HUB_UNAVAILABLE", error: "Local collaboration could not start" });
|
|
221
|
+
}
|
|
222
|
+
});
|
|
180
223
|
const activeRequests = new Set();
|
|
181
224
|
let inFlight = 0;
|
|
182
225
|
function userRoute(method, path, fields) {
|
|
183
226
|
options.app[method](`/api/device-center/${path}`, async (req, res) => {
|
|
184
|
-
|
|
227
|
+
try {
|
|
228
|
+
await serialize(ensureLocalHub);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
return res.status(503).json({ code: "LOCAL_HUB_UNAVAILABLE", error: "Local collaboration could not start" });
|
|
232
|
+
}
|
|
233
|
+
const captured = activeConfig();
|
|
185
234
|
const capturedGeneration = generation;
|
|
186
235
|
if (!captured)
|
|
187
236
|
return res.status(409).json({ code: "NOT_PAIRED", error: "Pair this computer first" });
|
|
@@ -240,7 +289,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
240
289
|
finally {
|
|
241
290
|
await reader.cancel();
|
|
242
291
|
}
|
|
243
|
-
if (closed ||
|
|
292
|
+
if (closed || activeConfig() !== captured || generation !== capturedGeneration)
|
|
244
293
|
return res.status(409).json({ code: "DEVICE_CHANGED", error: "Device binding changed; refresh" });
|
|
245
294
|
if (!response.ok) {
|
|
246
295
|
const failure = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
@@ -259,7 +308,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
259
308
|
res.status(response.status).json(data);
|
|
260
309
|
}
|
|
261
310
|
catch {
|
|
262
|
-
if (!res.destroyed && (closed ||
|
|
311
|
+
if (!res.destroyed && (closed || activeConfig() !== captured || generation !== capturedGeneration))
|
|
263
312
|
return res.status(409).json({ code: "DEVICE_CHANGED", error: "Device binding changed; refresh" });
|
|
264
313
|
if (!res.destroyed)
|
|
265
314
|
res.status(502).json({ code: "HUB_UNAVAILABLE", error: "Hub request failed or exceeded response limit" });
|
|
@@ -457,9 +506,10 @@ export async function installLocalDeviceCenter(options) {
|
|
|
457
506
|
return {
|
|
458
507
|
syncBots,
|
|
459
508
|
getConfig() {
|
|
460
|
-
|
|
509
|
+
const current = activeConfig();
|
|
510
|
+
if (!current)
|
|
461
511
|
return undefined;
|
|
462
|
-
const { uiCredential: _uiCredential, ...agentConfig } =
|
|
512
|
+
const { uiCredential: _uiCredential, ...agentConfig } = current;
|
|
463
513
|
return agentConfig;
|
|
464
514
|
},
|
|
465
515
|
async close() {
|
|
@@ -469,8 +519,11 @@ export async function installLocalDeviceCenter(options) {
|
|
|
469
519
|
for (const controller of activeRequests)
|
|
470
520
|
controller.abort();
|
|
471
521
|
await serial;
|
|
522
|
+
await localStarting;
|
|
472
523
|
await connection?.close();
|
|
473
524
|
connection = undefined;
|
|
525
|
+
await localHub?.close();
|
|
526
|
+
localHub = undefined;
|
|
474
527
|
},
|
|
475
528
|
};
|
|
476
529
|
}
|
|
@@ -45,7 +45,7 @@ export function transformPortalHtml(html, base) {
|
|
|
45
45
|
const content = html
|
|
46
46
|
.replace(/<base\b[^>]*>/gi, "")
|
|
47
47
|
.replace(/\b(src|href|action|poster)\s*=\s*(["'])\/(?!\/)([^"']*)\2/gi, (_all, name, quote, path) => `${name}=${quote}${base}${path}${quote}`);
|
|
48
|
-
const ready = `<script>const
|
|
48
|
+
const ready = `<script>(()=>{let ready=false,banner;const update=()=>{const root=document.getElementById('root'),status=document.querySelector('.status-conn');if(!ready&&((root&&root.childElementCount)||(!root&&document.readyState==='complete'))){ready=true;parent.postMessage({type:'device-portal-ready'},'*')}if(!ready||!status)return;if(!banner){banner=document.createElement('div');banner.setAttribute('role','status');banner.style.cssText='position:fixed;top:8px;left:50%;transform:translateX(-50%);z-index:2147483647;max-width:90vw;padding:8px 12px;border-radius:8px;background:#303137;color:#eee;font:13px system-ui;box-shadow:0 2px 12px #0006';banner.textContent='连接已断开,正在自动重试,请稍候… / Disconnected. Retrying automatically, please wait…';document.body.append(banner)}banner.hidden=status.classList.contains('ok')};setInterval(update,200);update()})();</script>`;
|
|
49
49
|
return `<!doctype html><base href="${base}">` + content.replace(/<!doctype[^>]*>/i, "") + ready;
|
|
50
50
|
}
|
|
51
51
|
/** Only the entry HTML is collected; every other body retains relay streaming. */
|
|
@@ -98,7 +98,7 @@ export function safePath(path, method = "GET") {
|
|
|
98
98
|
if (normalized === "/api/device-center" || normalized.startsWith("/api/device-center/")) {
|
|
99
99
|
// Only account-scoped chat routes may cross a device portal.
|
|
100
100
|
if (method === "GET") {
|
|
101
|
-
return /^\/api\/device-center\/(devices|bots|rooms(?:\/[^/]+)?)$/.test(normalized);
|
|
101
|
+
return /^\/api\/device-center\/(chat-status|devices|bots|rooms(?:\/[^/]+)?)$/.test(normalized);
|
|
102
102
|
}
|
|
103
103
|
if (method === "POST")
|
|
104
104
|
return /^\/api\/device-center\/rooms(?:\/[^/]+\/(messages|rename|members|delete))?$/.test(normalized);
|
|
@@ -401,6 +401,26 @@ export function createDeviceRelay(options) {
|
|
|
401
401
|
if (!["http:", "https:"].includes(hub.protocol) || hub.pathname !== "/" || hub.search)
|
|
402
402
|
throw new Error("publicUrl must be an HTTP(S) root origin");
|
|
403
403
|
const devices = new Map();
|
|
404
|
+
// Slow browser responses apply transport backpressure instead of losing resource bodies.
|
|
405
|
+
const stalledResponses = new WeakMap();
|
|
406
|
+
function pauseForResponse(ws, res) {
|
|
407
|
+
let stalled = stalledResponses.get(ws);
|
|
408
|
+
if (!stalled)
|
|
409
|
+
stalledResponses.set(ws, (stalled = new Set()));
|
|
410
|
+
if (stalled.has(res))
|
|
411
|
+
return;
|
|
412
|
+
stalled.add(res);
|
|
413
|
+
ws.pause();
|
|
414
|
+
const resume = () => {
|
|
415
|
+
res.off("drain", resume);
|
|
416
|
+
res.off("close", resume);
|
|
417
|
+
stalled.delete(res);
|
|
418
|
+
if (!stalled.size && ws.readyState === WebSocket.OPEN)
|
|
419
|
+
ws.resume();
|
|
420
|
+
};
|
|
421
|
+
res.once("drain", resume);
|
|
422
|
+
res.once("close", resume);
|
|
423
|
+
}
|
|
404
424
|
const tickets = new Map();
|
|
405
425
|
const sessions = new Map();
|
|
406
426
|
const capabilities = new Map();
|
|
@@ -412,7 +432,7 @@ export function createDeviceRelay(options) {
|
|
|
412
432
|
session.deviceId === id &&
|
|
413
433
|
session.expiresAt > Date.now() &&
|
|
414
434
|
path?.path &&
|
|
415
|
-
safePath(path.path,
|
|
435
|
+
(!websocket || safePath(path.path, "WS")) &&
|
|
416
436
|
(!req.headers.origin || req.headers.origin === "null") &&
|
|
417
437
|
(!websocket || req.headers.origin === "null"));
|
|
418
438
|
}
|
|
@@ -642,22 +662,38 @@ export function createDeviceRelay(options) {
|
|
|
642
662
|
res.writeHead(204, portalHeaders(hub, capabilityBase(id, path.token))).end();
|
|
643
663
|
return true;
|
|
644
664
|
}
|
|
665
|
+
// Only authenticated capability requests receive opaque-origin response headers.
|
|
666
|
+
if (path) {
|
|
667
|
+
for (const [key, value] of Object.entries(portalHeaders(hub, capabilityBase(id, path.token))))
|
|
668
|
+
res.setHeader(key, value);
|
|
669
|
+
}
|
|
670
|
+
const forwardPath = path ? path.path : req.url;
|
|
671
|
+
// Serve account binding at the Hub, including compatibility for older device UIs.
|
|
672
|
+
// Never forward the local management status endpoint or expose its settings.
|
|
673
|
+
if (path &&
|
|
674
|
+
req.method === "GET" &&
|
|
675
|
+
["/api/device-center/chat-status", "/api/device-center/status"].includes(forwardPath?.split("?")[0] ?? "")) {
|
|
676
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
677
|
+
res.end(JSON.stringify({ hubUrl: hub.origin, deviceId: id }));
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
645
680
|
const entry = devices.get(id);
|
|
646
681
|
if (!entry || entry.streams.size >= RELAY_LIMITS.streams) {
|
|
647
682
|
res.writeHead(503).end();
|
|
648
683
|
return true;
|
|
649
684
|
}
|
|
650
|
-
const forwardPath = path ? path.path : req.url;
|
|
651
685
|
if (!safePath(forwardPath, req.method)) {
|
|
652
686
|
res.writeHead(400).end();
|
|
653
687
|
return true;
|
|
654
688
|
}
|
|
689
|
+
// Only entry documents are rewritten; preserve negotiated compression for assets.
|
|
690
|
+
const rewriteHtml = !!path && ["/", "/desktop"].includes(path.path.split("?")[0]);
|
|
655
691
|
const streamId = randomBytes(12).toString("hex");
|
|
656
692
|
addStream(entry, streamId, {
|
|
657
693
|
res,
|
|
658
694
|
...(path
|
|
659
695
|
? {
|
|
660
|
-
portal: createPortalResponse(res, hub, capabilityBase(id, path.token),
|
|
696
|
+
portal: createPortalResponse(res, hub, capabilityBase(id, path.token), rewriteHtml),
|
|
661
697
|
}
|
|
662
698
|
: {}),
|
|
663
699
|
});
|
|
@@ -667,7 +703,7 @@ export function createDeviceRelay(options) {
|
|
|
667
703
|
id: streamId,
|
|
668
704
|
method: req.method,
|
|
669
705
|
path: forwardPath,
|
|
670
|
-
headers: { ...cleanHeaders(req.headers), ...(
|
|
706
|
+
headers: { ...cleanHeaders(req.headers), ...(rewriteHtml ? { "accept-encoding": "identity" } : {}) },
|
|
671
707
|
});
|
|
672
708
|
req.on("data", (chunk) => {
|
|
673
709
|
bytes += chunk.length;
|
|
@@ -828,12 +864,13 @@ export function createDeviceRelay(options) {
|
|
|
828
864
|
else if (item.res?.headersSent)
|
|
829
865
|
item.res.write(data);
|
|
830
866
|
}
|
|
831
|
-
if (item.bytes > RELAY_LIMITS.body ||
|
|
832
|
-
(!item.portal && !item.res?.headersSent) ||
|
|
833
|
-
item.res.writableLength > RELAY_LIMITS.queue) {
|
|
867
|
+
if (item.bytes > RELAY_LIMITS.body || (!item.portal && !item.res?.headersSent)) {
|
|
834
868
|
item.res?.destroy();
|
|
835
869
|
sendFrame(ws, { type: "cancel", id: frame.id });
|
|
836
870
|
}
|
|
871
|
+
else if (item.res && item.res.writableLength > RELAY_LIMITS.queue / 2) {
|
|
872
|
+
pauseForResponse(ws, item.res);
|
|
873
|
+
}
|
|
837
874
|
}
|
|
838
875
|
else if (frame.type === "response_end" || frame.type === "error") {
|
|
839
876
|
if (frame.type === "error")
|
|
@@ -650,6 +650,7 @@ export function handleSettingsMessage(msg, cs, send) {
|
|
|
650
650
|
editSoftEnabled: msg.editSoftEnabled,
|
|
651
651
|
questionnaireEnabled: msg.questionnaireEnabled,
|
|
652
652
|
questionPresentation: msg.questionPresentation,
|
|
653
|
+
toolApprovalPresentation: msg.toolApprovalPresentation,
|
|
653
654
|
questionTimeoutSeconds: msg.questionTimeoutSeconds,
|
|
654
655
|
parallelReminderEnabled: msg.parallelReminderEnabled,
|
|
655
656
|
goalModeEnabled: msg.goalModeEnabled,
|