@ryuu-64/dsh-session-tools 0.6.0 → 0.8.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/README.md +49 -170
- package/lib/client.js +397 -2
- package/lib/communication-permissions.js +101 -0
- package/lib/communication-remote.js +64 -0
- package/lib/index.js +96 -51
- package/lib/session-activity.js +26 -14
- package/lib/session-discovery.js +213 -0
- package/package.json +99 -76
package/lib/client.js
CHANGED
|
@@ -14,6 +14,7 @@ window.__ModuleLoader__.load({
|
|
|
14
14
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
15
15
|
|
|
16
16
|
const react = require("react");
|
|
17
|
+
const { MenuItemButton, Modal, Button, Switch, ReferenceIconRegular } = require("@deepseek-ai/dsh-client-ui-primitives");
|
|
17
18
|
|
|
18
19
|
/** Slots this client half needs before it can register anything. */
|
|
19
20
|
const inject = ["slots", "sessions"];
|
|
@@ -107,23 +108,417 @@ window.__ModuleLoader__.load({
|
|
|
107
108
|
title,
|
|
108
109
|
),
|
|
109
110
|
react.createElement("span", { style: { opacity: 0.55, fontFamily: "ui-monospace, monospace", fontSize: "11px" } }, created.sessionId),
|
|
111
|
+
react.createElement("div", { style: { flexBasis: "100%" } }, react.createElement(MessageStateRow, { block: props.block })),
|
|
110
112
|
);
|
|
111
113
|
}
|
|
112
114
|
|
|
115
|
+
|
|
116
|
+
const statusLabels = {
|
|
117
|
+
queued: "已排队", delivered: "已交给目标", turnCompleted: "目标本轮结束(不等于任务成功)",
|
|
118
|
+
discarded: "取消", cancelled: "取消", interrupted: "中断", failed: "失败", incomplete: "未完整结束",
|
|
119
|
+
blocked: "未完整结束", unknown: "暂无法确认",
|
|
120
|
+
};
|
|
121
|
+
function MessageStateRow({ block }) {
|
|
122
|
+
const text = resultText(block);
|
|
123
|
+
if (block?.kind !== "tool-result") return react.createElement("span", { role: "status" }, "正在处理…");
|
|
124
|
+
const meta = block.meta;
|
|
125
|
+
if (block.isError || meta?.scope === "sessionOverview" || typeof meta?.messageId !== "string") {
|
|
126
|
+
return react.createElement("div", { style: { whiteSpace: "pre-wrap", overflowWrap: "anywhere" } }, text || "暂无法确认");
|
|
127
|
+
}
|
|
128
|
+
return react.createElement("div", { style: { display: "grid", gap: 6 } },
|
|
129
|
+
react.createElement("strong", null, statusLabels[meta.messageStatus] ?? "暂无法确认"),
|
|
130
|
+
meta.waitStatus === "timedOut" && react.createElement("div", null, "等待超时。没有重发,也没有取消;请用同一消息编号继续查询。"),
|
|
131
|
+
meta.waitStatus === "callerCancelled" && react.createElement("div", null, "已停止等待,目标会话继续处理。"),
|
|
132
|
+
react.createElement("details", null, react.createElement("summary", null, "消息编号与结果详情"),
|
|
133
|
+
react.createElement("div", { style: { whiteSpace: "pre-wrap", overflowWrap: "anywhere", color: "var(--dsw-alias-label-secondary)" } }, text)));
|
|
134
|
+
}
|
|
135
|
+
const remoteContribution = (() => {
|
|
136
|
+
// TypertSchema requires parse(value); keep these strict schemas local to
|
|
137
|
+
// this browser bundle because Zod is not a platform module seed.
|
|
138
|
+
const scalar = check => value => {
|
|
139
|
+
if (!check(value)) throw new TypeError("Invalid session communication field");
|
|
140
|
+
return value;
|
|
141
|
+
};
|
|
142
|
+
const object = fields => ({ parse(value) {
|
|
143
|
+
if (!value || typeof value !== "object" || Array.isArray(value)
|
|
144
|
+
|| Object.keys(value).some(key => !Object.hasOwn(fields, key))
|
|
145
|
+
|| Object.keys(fields).some(key => !Object.hasOwn(value, key))) {
|
|
146
|
+
throw new TypeError("Invalid session communication object");
|
|
147
|
+
}
|
|
148
|
+
return Object.fromEntries(Object.entries(fields).map(([key, parse]) => [key, parse(value[key])]));
|
|
149
|
+
} });
|
|
150
|
+
const sessionId = scalar(value => typeof value === "string" && value.length >= 1 && value.length <= 1024);
|
|
151
|
+
const boolean = scalar(value => typeof value === "boolean");
|
|
152
|
+
const revision = scalar(value => Number.isSafeInteger(value) && value >= 0);
|
|
153
|
+
const getSchema = object({ sessionId });
|
|
154
|
+
const setSchema = object({ sessionId, send: boolean, receive: boolean, expectedRevision: revision });
|
|
155
|
+
const recordSchema = object({ send: boolean, receive: boolean, revision });
|
|
156
|
+
const setResultSchema = object({ status: scalar(value => value === "saved" || value === "conflict"), current: value => recordSchema.parse(value) });
|
|
157
|
+
return {
|
|
158
|
+
package: "@ryuu-64/dsh-session-tools",
|
|
159
|
+
descriptors: ["get", "set"].map(method => ({
|
|
160
|
+
id: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}`,
|
|
161
|
+
service: "sessionCommunication", namespace: "sessionCommunication", method,
|
|
162
|
+
invocation: { kind: "direct" },
|
|
163
|
+
parameters: [{ name: "request", wire: "request", source: "json", codec: {
|
|
164
|
+
mode: "strict", typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:request`,
|
|
165
|
+
create: () => method === "get" ? getSchema : setSchema,
|
|
166
|
+
} }],
|
|
167
|
+
result: {
|
|
168
|
+
mode: "strict", typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:result`,
|
|
169
|
+
create: () => method === "get" ? recordSchema : setResultSchema,
|
|
170
|
+
},
|
|
171
|
+
})),
|
|
172
|
+
};
|
|
173
|
+
})();
|
|
174
|
+
function validRecord(value) {
|
|
175
|
+
return value && typeof value.send === "boolean" && typeof value.receive === "boolean" && Number.isSafeInteger(value.revision) && value.revision >= 0;
|
|
176
|
+
}
|
|
177
|
+
// One authoritative cache per client, shared by every pane and the menu.
|
|
178
|
+
// Other windows are reconciled by bounded polling and focus/visibility reads.
|
|
179
|
+
function createCommunicationStore() {
|
|
180
|
+
let api;
|
|
181
|
+
const entries = new Map();
|
|
182
|
+
const entryFor = id => {
|
|
183
|
+
if (!entries.has(id)) entries.set(id, { listeners: new Set(), active: 0, token: 0, reading: false, saving: false,
|
|
184
|
+
value: { record: null, busy: false, failed: false, notice: "正在读取设置…" } });
|
|
185
|
+
return entries.get(id);
|
|
186
|
+
};
|
|
187
|
+
const publish = (entry, patch) => {
|
|
188
|
+
entry.value = { ...entry.value, ...patch };
|
|
189
|
+
entry.listeners.forEach(listener => listener());
|
|
190
|
+
};
|
|
191
|
+
const read = async (id, verifyPending = false) => {
|
|
192
|
+
const entry = entryFor(id);
|
|
193
|
+
if (!api || entry.reading || (entry.saving && !verifyPending)) return;
|
|
194
|
+
entry.reading = true;
|
|
195
|
+
if (!entry.value.record) publish(entry, { busy: true });
|
|
196
|
+
const token = ++entry.token;
|
|
197
|
+
let timer;
|
|
198
|
+
try {
|
|
199
|
+
const result = await Promise.race([api.get({ sessionId: id }), new Promise((_, reject) => {
|
|
200
|
+
timer = setTimeout(() => reject(new Error("read timeout")), 12000);
|
|
201
|
+
})]);
|
|
202
|
+
if (token !== entry.token) return;
|
|
203
|
+
if (!result.ok || !validRecord(result.value)) throw new Error("unavailable");
|
|
204
|
+
if (entry.value.record && result.value.revision < entry.value.record.revision) return;
|
|
205
|
+
const changed = entry.value.record && result.value.revision !== entry.value.record.revision;
|
|
206
|
+
publish(entry, { record: result.value, failed: changed ? false : !!entry.value.record && entry.value.failed,
|
|
207
|
+
notice: entry.saving ? "已读取当前设置,保存请求仍未结束;暂不能再次更改。" : changed ? "设置已在其他页面更改,已同步最新状态。" : entry.value.record ? entry.value.notice : "已读取最新设置。更改后立即生效。" });
|
|
208
|
+
} catch {
|
|
209
|
+
if (token === entry.token) publish(entry, { record: null, failed: true, notice: "状态未知,暂时无法读取设置。请重试。" });
|
|
210
|
+
} finally {
|
|
211
|
+
clearTimeout(timer); entry.reading = false;
|
|
212
|
+
if (token === entry.token) publish(entry, { busy: entry.saving });
|
|
213
|
+
if (!entry.listeners.size && !entry.saving) entries.delete(id);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
const change = async (id, key, next) => {
|
|
217
|
+
const entry = entryFor(id), record = entry.value.record;
|
|
218
|
+
if (!api || !record || entry.saving) return;
|
|
219
|
+
const owner = api;
|
|
220
|
+
entry.saving = true; ++entry.token;
|
|
221
|
+
publish(entry, { busy: true, failed: false, notice: "正在保存…" });
|
|
222
|
+
// A timeout cannot cancel an accepted write. Keep the write lock until
|
|
223
|
+
// it settles; never replay it or offer a misleading rollback.
|
|
224
|
+
let timedOut = false, staleResponse = false;
|
|
225
|
+
const timer = setTimeout(() => {
|
|
226
|
+
if (api !== owner) return;
|
|
227
|
+
timedOut = true;
|
|
228
|
+
publish(entry, { record: null, failed: true, notice: "保存结果尚未确认,仍在等待。不会重复提交;关闭面板不会取消更改。" });
|
|
229
|
+
void read(id, true);
|
|
230
|
+
}, 12000);
|
|
231
|
+
try {
|
|
232
|
+
const result = await owner.set({ sessionId: id, send: record.send, receive: record.receive, [key]: next, expectedRevision: record.revision });
|
|
233
|
+
if (api !== owner) return;
|
|
234
|
+
if (!result.ok || !validRecord(result.value?.current) || !["saved", "conflict"].includes(result.value?.status)) throw new Error("unconfirmed");
|
|
235
|
+
if (entry.value.record && result.value.current.revision < entry.value.record.revision) { staleResponse = true; return; }
|
|
236
|
+
publish(entry, { record: result.value.current, failed: result.value.status === "conflict",
|
|
237
|
+
notice: result.value.status === "saved" ? "已保存,立即生效。" : "设置已在其他页面更改。已显示最新设置,请确认后再操作。" });
|
|
238
|
+
} catch {
|
|
239
|
+
if (api !== owner) return;
|
|
240
|
+
publish(entry, { record: null, failed: true, notice: "保存结果暂无法确认,正在重新读取;不会自动重复保存。" });
|
|
241
|
+
} finally {
|
|
242
|
+
clearTimeout(timer); ++entry.token; entry.saving = false; publish(entry, { busy: false });
|
|
243
|
+
if (api !== owner || timedOut || staleResponse || !entry.value.record) void read(id);
|
|
244
|
+
else if (!entry.listeners.size && !entry.reading) entries.delete(id);
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
const refresh = () => { if (document.visibilityState === "hidden") return; for (const [id, entry] of entries) if (entry.active) void read(id); };
|
|
248
|
+
return {
|
|
249
|
+
connect(value) {
|
|
250
|
+
api = value; refresh();
|
|
251
|
+
return () => {
|
|
252
|
+
if (api !== value) return;
|
|
253
|
+
api = undefined;
|
|
254
|
+
for (const entry of entries.values()) {
|
|
255
|
+
++entry.token;
|
|
256
|
+
publish(entry, { record: null, busy: entry.saving, failed: true, notice: "连接已断开,状态未知。恢复连接后会重新读取。" });
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
},
|
|
260
|
+
get: id => entryFor(id).value, read, change,
|
|
261
|
+
subscribe(id, listener, active) {
|
|
262
|
+
const entry = entryFor(id); entry.listeners.add(listener);
|
|
263
|
+
if (active) entry.active++;
|
|
264
|
+
if (active && entry.active === 1) {
|
|
265
|
+
entry.timer = setInterval(() => { if (document.visibilityState !== "hidden") void read(id); }, 3000);
|
|
266
|
+
window.addEventListener("focus", refresh);
|
|
267
|
+
document.addEventListener("visibilitychange", refresh);
|
|
268
|
+
}
|
|
269
|
+
if (active) void read(id);
|
|
270
|
+
return () => {
|
|
271
|
+
entry.listeners.delete(listener);
|
|
272
|
+
if (active) entry.active--;
|
|
273
|
+
if (!entry.active) clearInterval(entry.timer);
|
|
274
|
+
if (![...entries.values()].some(item => item.active)) {
|
|
275
|
+
window.removeEventListener("focus", refresh); document.removeEventListener("visibilitychange", refresh);
|
|
276
|
+
}
|
|
277
|
+
if (!entry.listeners.size && !entry.reading && !entry.saving) entries.delete(id);
|
|
278
|
+
};
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function CommunicationControls({ sessionId, store, compact = false, visible = true }) {
|
|
283
|
+
const subscribe = react.useCallback(listener => store.subscribe(sessionId, listener, visible), [store, sessionId, visible]);
|
|
284
|
+
const snapshot = react.useCallback(() => store.get(sessionId), [store, sessionId]);
|
|
285
|
+
const { record, busy, failed, notice } = react.useSyncExternalStore(subscribe, snapshot);
|
|
286
|
+
react.useEffect(() => { if (visible) void store.read(sessionId); }, [store, sessionId, visible]);
|
|
287
|
+
const row = (key, label, description) => react.createElement("div", { key, style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: compact ? 8 : 24, padding: compact ? "10px 0" : "16px 0", borderBottom: "0.5px solid var(--dsw-alias-border-l2)" } },
|
|
288
|
+
react.createElement("div", { title: description, style: { flex: 1, minWidth: 0, fontSize: compact ? 13 : 14, lineHeight: "20px", color: "var(--dsw-alias-label-primary)" } }, label,
|
|
289
|
+
!compact && react.createElement("div", { style: { marginTop: 4, fontSize: 12, lineHeight: "18px", color: "var(--dsw-alias-label-secondary)" } }, description)),
|
|
290
|
+
react.createElement("span", { "aria-hidden": true, style: { flexShrink: 0, color: "var(--dsw-alias-label-secondary)", fontSize: 12 } }, record ? record[key] ? "开启" : "关闭" : "未知"),
|
|
291
|
+
record && react.createElement(Switch, { checked: record[key], onChange: value => void store.change(sessionId, key, value), label, disabled: busy }));
|
|
292
|
+
return react.createElement("section", { "aria-label": "会话通信", "aria-busy": busy, "data-communication-session": sessionId, style: { padding: compact ? "0 6px 12px" : 0, minWidth: 0 } },
|
|
293
|
+
row("receive", "接收其他会话消息", "关闭会拒绝新的插件消息:未送达、未排队;已接收消息继续处理。"),
|
|
294
|
+
row("send", "向其他会话发送", "也控制创建带首条消息的新会话。"),
|
|
295
|
+
(!compact || record?.receive === false) && react.createElement("p", { style: { color: "var(--dsw-alias-label-secondary)", fontSize: 12, lineHeight: "18px" } }, "仅控制本插件的新消息。关闭接收后,新消息未送达、未排队;已经接收的消息继续处理,历史仍可查看。"),
|
|
296
|
+
react.createElement("div", { role: failed ? "alert" : "status", "aria-live": "polite", style: { marginTop: 8, fontSize: 12, lineHeight: "18px", color: failed ? "var(--dsw-alias-state-error-primary)" : "var(--dsw-alias-label-secondary)" } }, notice),
|
|
297
|
+
!record && !busy && react.createElement(Button, { variant: "outline", onClick: () => void store.read(sessionId) }, "重新读取"));
|
|
298
|
+
}
|
|
299
|
+
function CommunicationForm({ request, store, close }) {
|
|
300
|
+
return react.createElement(Modal, { open: true, onClose: close, closeLabel: "关闭", title: "会话通信", description: request.title || request.sessionId,
|
|
301
|
+
footer: react.createElement(Button, { variant: "outline", onClick: close }, "关闭"),
|
|
302
|
+
}, react.createElement(CommunicationControls, { sessionId: request.sessionId, store }));
|
|
303
|
+
}
|
|
304
|
+
/** Direct ordinary children from the public, durable host catalog.
|
|
305
|
+
* The client controller maps header.parentSession to summary.parentId.
|
|
306
|
+
* Never infer lineage from workspace, title or message text. Native
|
|
307
|
+
* subagents keep their existing catalog and continuation semantics.
|
|
308
|
+
*/
|
|
309
|
+
function RelatedConversationRows({ sessionId, useSessions, useWorkspaces, openSession }) {
|
|
310
|
+
const catalog = useSessions(state => state);
|
|
311
|
+
const workspaces = useWorkspaces(state => state);
|
|
312
|
+
const [expandedSession, setExpandedSession] = react.useState(null);
|
|
313
|
+
const expanded = expandedSession === sessionId;
|
|
314
|
+
const scrollRegion = react.useRef(null);
|
|
315
|
+
const firstAdded = react.useRef(null);
|
|
316
|
+
const expansion = react.useRef(null);
|
|
317
|
+
react.useLayoutEffect(() => {
|
|
318
|
+
const pending = expansion.current, region = scrollRegion.current;
|
|
319
|
+
if (!expanded || !pending || !region) return;
|
|
320
|
+
expansion.current = null;
|
|
321
|
+
region.scrollTop = pending.scrollTop;
|
|
322
|
+
if (pending.keyboard && firstAdded.current) {
|
|
323
|
+
firstAdded.current.focus({ preventScroll: true });
|
|
324
|
+
const item = firstAdded.current.getBoundingClientRect(), bounds = region.getBoundingClientRect();
|
|
325
|
+
if (item.height > bounds.height) region.scrollTop += item.top - bounds.top;
|
|
326
|
+
else if (item.bottom > bounds.bottom) region.scrollTop += item.bottom - bounds.bottom;
|
|
327
|
+
else if (item.top < bounds.top) region.scrollTop -= bounds.top - item.top;
|
|
328
|
+
}
|
|
329
|
+
}, [expanded]);
|
|
330
|
+
// Identity order is stable across activity/title updates and remounts.
|
|
331
|
+
const children = catalog.ids.map(id => catalog.byId[id]).filter(row =>
|
|
332
|
+
row && row.id !== sessionId && row.parentId === sessionId && row.origin !== "subagent" && !workspaces.archivedSessionIds.includes(row.id))
|
|
333
|
+
.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
334
|
+
const parentId = catalog.byId[sessionId]?.parentId;
|
|
335
|
+
const parent = parentId && parentId !== sessionId ? catalog.byId[parentId] : null;
|
|
336
|
+
const workspaceOf = id => workspaces.items.find(item => item.sessionIds.includes(id));
|
|
337
|
+
const currentWorkspace = workspaceOf(sessionId);
|
|
338
|
+
const titleOf = row => row.title?.trim() ? row.title : row.id;
|
|
339
|
+
const visible = expanded ? children : children.slice(0, 3);
|
|
340
|
+
const listId = "session-tools-children-" + sessionId;
|
|
341
|
+
if ((!parentId || parentId === sessionId) && children.length === 0) return react.createElement("p", { style: { margin: 8, color: "var(--dsw-alias-label-secondary)", fontSize: 13 } }, "当前对话还没有相关对话。");
|
|
342
|
+
return react.createElement("section", {
|
|
343
|
+
"aria-label": "相关对话", ref: scrollRegion,
|
|
344
|
+
style: { padding: "4px 6px 6px", minWidth: 0, minHeight: 0, overflowY: "auto" },
|
|
345
|
+
},
|
|
346
|
+
parentId && parentId !== sessionId ? react.createElement(Button, {
|
|
347
|
+
variant: "ghost", disabled: workspaces.archivedSessionIds.includes(parentId), onClick: () => openSession(parentId),
|
|
348
|
+
style: { width: "100%", justifyContent: "flex-start", height: "auto", padding: "6px 8px", textAlign: "left", whiteSpace: "normal", overflowWrap: "anywhere" },
|
|
349
|
+
}, (workspaces.archivedSessionIds.includes(parentId) ? "父对话已归档 · " : "返回父对话 · ") + (parent ? titleOf(parent) : parentId)) : null,
|
|
350
|
+
children.length ? react.createElement(react.Fragment, null,
|
|
351
|
+
react.createElement("div", { style: { padding: "2px 8px", fontSize: 12, lineHeight: "18px", color: "var(--dsw-alias-label-secondary)" } }, "创建的对话 · " + children.length),
|
|
352
|
+
react.createElement("div", { id: listId }, visible.map((child, index) => {
|
|
353
|
+
const workspace = workspaceOf(child.id);
|
|
354
|
+
const crossWorkspace = workspaces.phase === "ready" && workspaces.state !== "error" && workspace?.workspaceId !== currentWorkspace?.workspaceId;
|
|
355
|
+
return react.createElement(Button, {
|
|
356
|
+
key: child.id, ref: index === 3 ? firstAdded : undefined, variant: "ghost", title: child.id, onClick: () => openSession(child.id),
|
|
357
|
+
style: { width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "6px 8px", height: "auto", minWidth: 0, textAlign: "left" },
|
|
358
|
+
},
|
|
359
|
+
react.createElement("span", { style: { minWidth: 0, overflowWrap: "anywhere", whiteSpace: "normal", fontSize: 13, lineHeight: "20px" } },
|
|
360
|
+
titleOf(child),
|
|
361
|
+
crossWorkspace ? react.createElement("span", { style: { display: "block", fontSize: 11, color: "var(--dsw-alias-label-secondary)" } }, "跨工作区 · " + (workspace?.title || workspace?.path || "未分组")) : null),
|
|
362
|
+
react.createElement("span", { style: { flexShrink: 0, color: "var(--dsw-alias-label-secondary)", fontSize: 12 } }, child.running === true ? "运行中" : child.running === false ? "空闲" : "状态未知"));
|
|
363
|
+
})),
|
|
364
|
+
children.length > 3 ? react.createElement(Button, {
|
|
365
|
+
variant: "ghost", "aria-expanded": expanded, "aria-controls": listId,
|
|
366
|
+
onClick: event => {
|
|
367
|
+
expansion.current = expanded ? null : { keyboard: event.detail === 0, scrollTop: scrollRegion.current?.scrollTop || 0 };
|
|
368
|
+
setExpandedSession(expanded ? null : sessionId);
|
|
369
|
+
},
|
|
370
|
+
style: { width: "100%", fontSize: 12, height: "auto", padding: "6px 8px" },
|
|
371
|
+
}, expanded ? "收起列表" : "展开更多(" + (children.length - 3) + ")") : null) : null);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const RELATIONS_TAB = "@ryuu-64/dsh-session-tools/relations";
|
|
375
|
+
const RELATIONS_KIND = "session-tools.relations";
|
|
376
|
+
// Only the automatic first reveal is plugin-owned. All pane geometry,
|
|
377
|
+
// collapse, movement, docking and layout persistence belong to DSH.
|
|
378
|
+
function hasRelations(sessionId, catalog, workspaces) {
|
|
379
|
+
const archived = workspaces.archivedSessionIds;
|
|
380
|
+
const parentId = catalog.byId[sessionId]?.parentId;
|
|
381
|
+
return (!!parentId && parentId !== sessionId && !!catalog.byId[parentId] && !archived.includes(parentId)) ||
|
|
382
|
+
catalog.ids.some(id => {
|
|
383
|
+
const row = catalog.byId[id];
|
|
384
|
+
return row && id !== sessionId && row.parentId === sessionId && row.origin !== "subagent" && !archived.includes(id);
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
function RelationsTab(props) {
|
|
388
|
+
const { tab } = props.useTabInfo();
|
|
389
|
+
react.useLayoutEffect(() => {
|
|
390
|
+
props.visibility.set(tab.id, tab.visible);
|
|
391
|
+
return () => props.visibility.delete(tab.id);
|
|
392
|
+
}, [props.visibility, tab.id, tab.visible]);
|
|
393
|
+
return react.createElement("div", {
|
|
394
|
+
"data-session-tools-tab": props.sessionId,
|
|
395
|
+
style: { height: "100%", minHeight: 0, overflow: "auto", padding: 8, boxSizing: "border-box" },
|
|
396
|
+
}, react.createElement(CommunicationControls, { key: props.sessionId, sessionId: props.sessionId, store: props.communication, compact: true, visible: tab.visible }),
|
|
397
|
+
react.createElement(RelatedConversationRows, { ...props, key: tab.id }));
|
|
398
|
+
}
|
|
399
|
+
function RelationsEntry(props) {
|
|
400
|
+
const catalog = props.useSessions(state => state);
|
|
401
|
+
const workspaces = props.useWorkspaces(state => state);
|
|
402
|
+
const mounted = react.useSyncExternalStore(props.sidebar?.mounted.subscribe ?? (() => () => {}), props.sidebar?.mounted.getSnapshot ?? (() => undefined));
|
|
403
|
+
const available = workspaces.phase === "ready" && hasRelations(props.sessionId, catalog, workspaces);
|
|
404
|
+
react.useEffect(() => {
|
|
405
|
+
if (!props.sidebar || !available || mounted !== props.sessionId || props.wasShown(props.sessionId)) return;
|
|
406
|
+
// This is synchronous and rechecks the host's owner before opening.
|
|
407
|
+
// Record success only after the native tab actually exists.
|
|
408
|
+
props.reveal(props.sessionId, true);
|
|
409
|
+
}, [available, mounted, props.sessionId, props.reveal, props.wasShown]);
|
|
410
|
+
if (!props.sessionId) return null;
|
|
411
|
+
return react.createElement(Button, {
|
|
412
|
+
variant: "ghost", size: "sm", title: props.sidebar ? "会话通信与相关对话" : "会话工具不可用:宿主未提供会话工具停靠接口", "aria-label": props.sidebar ? "会话通信与相关对话" : "会话工具不可用:宿主未提供会话工具停靠接口", disabled: !props.sidebar,
|
|
413
|
+
style: { flex: "none", width: 28, padding: 0, color: "var(--dsw-alias-label-secondary)" },
|
|
414
|
+
onClick: () => props.reveal(props.sessionId, false),
|
|
415
|
+
}, react.createElement(ReferenceIconRegular, { kind: "session", size: 16 }));
|
|
416
|
+
}
|
|
417
|
+
function registerCommunicationUI(ctx, store) {
|
|
418
|
+
let request = null;
|
|
419
|
+
const listeners = new Set();
|
|
420
|
+
const publish = value => { request = value; for (const listener of listeners) listener(); };
|
|
421
|
+
const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener); };
|
|
422
|
+
function Overlay() {
|
|
423
|
+
const current = react.useSyncExternalStore(subscribe, () => request);
|
|
424
|
+
return current ? react.createElement(CommunicationForm, { key: current.sessionId, request: current, store, close: () => publish(null) }) : null;
|
|
425
|
+
}
|
|
426
|
+
ctx.slots.inject("shell.overlay", () => ctx.slots.register({ name: "shell.overlay", id: "session-tools.communication" }, Overlay));
|
|
427
|
+
ctx.slots.inject("sidebar.workspaces.session.menu.item", () => ctx.slots.register({ name: "sidebar.workspaces.session.menu.item", id: "session-tools.communication", order: 350 },
|
|
428
|
+
({ sessionId, displayTitle, useMenuOpenState }) => {
|
|
429
|
+
const [, setMenuOpen] = useMenuOpenState();
|
|
430
|
+
return react.createElement(MenuItemButton, { onSelect: () => { setMenuOpen(false); publish({ sessionId, title: displayTitle }); } }, "会话通信…");
|
|
431
|
+
}));
|
|
432
|
+
}
|
|
433
|
+
|
|
113
434
|
/**
|
|
114
435
|
* Wait for the tool view slot list to exist, then register a keyed row that
|
|
115
436
|
* replaces the default card for `session_create`.
|
|
116
437
|
* @param ctx - the browser plugin context.
|
|
117
438
|
*/
|
|
118
439
|
function apply(ctx) {
|
|
119
|
-
|
|
440
|
+
const communication = createCommunicationStore();
|
|
441
|
+
ctx.inject(["remote"], async scope => {
|
|
442
|
+
try {
|
|
443
|
+
await scope.remote.$mount(remoteContribution);
|
|
444
|
+
scope.inject(["remote.sessionCommunication"], ui => {
|
|
445
|
+
ui.effect(() => communication.connect(ui.remote.sessionCommunication));
|
|
446
|
+
registerCommunicationUI(ui, communication);
|
|
447
|
+
});
|
|
448
|
+
} catch(error) { console.error("[session-tools] communication UI initialization failed", error); throw error; }
|
|
449
|
+
});
|
|
450
|
+
ctx.slots.inject("tool.call.toolview", function* () {
|
|
451
|
+
for (const key of ["session_send", "session_wait"]) yield ctx.slots.register({ name: "tool.call.toolview", key }, MessageStateRow);
|
|
452
|
+
});
|
|
453
|
+
const register = (scope, openSession) => {
|
|
454
|
+
let capabilities = {};
|
|
455
|
+
const listeners = new Set();
|
|
456
|
+
const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener); };
|
|
457
|
+
const snapshot = () => capabilities;
|
|
458
|
+
scope.slots.inject("conversation.session.header.utilities", () => scope.slots.register({
|
|
459
|
+
name: "conversation.session.header.utilities", id: "session-tools.relations",
|
|
460
|
+
}, props => react.createElement(RelationsEntry, { ...props, ...react.useSyncExternalStore(subscribe, snapshot) })));
|
|
461
|
+
scope.inject(["sidebarRight", "sidebarRightTabs"], ui => {
|
|
462
|
+
const sidebar = ui.sidebarRight;
|
|
463
|
+
if (!["openTab", "tabsIn", "focus"].every(key => typeof sidebar[key] === "function") || typeof sidebar.mounted?.getSnapshot !== "function" || typeof sidebar.mounted?.subscribe !== "function" || typeof sidebar.tabDomain?.occurrence !== "function" || typeof ui.sidebarRightTabs.register !== "function") return;
|
|
464
|
+
const shown = new Set(), visibility = new Map();
|
|
465
|
+
const storageKey = id => "dsh-session-tools:relations-shown:" + id;
|
|
466
|
+
const wasShown = id => {
|
|
467
|
+
if (shown.has(id)) return true;
|
|
468
|
+
try { return localStorage.getItem(storageKey(id)) === "1"; } catch { return false; }
|
|
469
|
+
};
|
|
470
|
+
const markShown = id => {
|
|
471
|
+
shown.add(id);
|
|
472
|
+
try { localStorage.setItem(storageKey(id), "1"); } catch { /* In-memory suppression still respects a close this run. */ }
|
|
473
|
+
};
|
|
474
|
+
const reveal = (id, automatic) => {
|
|
475
|
+
if (ui.sidebarRight.mounted.getSnapshot() !== id) return;
|
|
476
|
+
const existing = ui.sidebarRight.tabsIn(id).find(tab => tab.kind === RELATIONS_KIND);
|
|
477
|
+
if (existing) {
|
|
478
|
+
// A restored layout must keep the user's selected tab and collapsed state.
|
|
479
|
+
if (!automatic) {
|
|
480
|
+
const occurrence = sidebar.tabDomain.occurrence(id, { id: existing.id });
|
|
481
|
+
if (typeof sidebar.revealOccurrence === "function") sidebar.revealOccurrence(occurrence);
|
|
482
|
+
else if (visibility.get(existing.id)) sidebar.focus(existing.id);
|
|
483
|
+
else occurrence.tabActions.openTab(RELATIONS_KIND);
|
|
484
|
+
}
|
|
485
|
+
} else ui.sidebarRight.openTab(RELATIONS_KIND);
|
|
486
|
+
if (ui.sidebarRight.tabsIn(id).some(tab => tab.kind === RELATIONS_KIND)) markShown(id);
|
|
487
|
+
};
|
|
488
|
+
ui.effect(() => ui.sidebarRightTabs.register({
|
|
489
|
+
id: RELATIONS_TAB, kind: RELATIONS_KIND, keepMounted: true,
|
|
490
|
+
title: () => "会话",
|
|
491
|
+
}));
|
|
492
|
+
ui.slots.inject("sidebar.right.pane.tab", () => ui.slots.register({
|
|
493
|
+
name: "sidebar.right.pane.tab", key: RELATIONS_TAB, inject: () => ({ openSession, visibility, communication }),
|
|
494
|
+
}, RelationsTab));
|
|
495
|
+
ui.effect(() => {
|
|
496
|
+
capabilities = { sidebar, reveal, wasShown };
|
|
497
|
+
listeners.forEach(listener => listener());
|
|
498
|
+
return () => { capabilities = {}; listeners.forEach(listener => listener()); };
|
|
499
|
+
});
|
|
500
|
+
});
|
|
501
|
+
return scope.slots.inject("tool.call.toolview", () => scope.slots.register(
|
|
120
502
|
{
|
|
121
503
|
name: "tool.call.toolview",
|
|
122
504
|
key: "session_create",
|
|
123
|
-
inject: () => ({ openSession
|
|
505
|
+
inject: () => ({ openSession }),
|
|
124
506
|
},
|
|
125
507
|
SessionCreateRow,
|
|
126
508
|
));
|
|
509
|
+
};
|
|
510
|
+
// Pre-0.2 hosts put UI selection on sessions. In 0.2 the Session
|
|
511
|
+
// Controller only owns data/references; UIWorkspace owns mainView
|
|
512
|
+
// retention, selection, panel reveal and release. Do not retain a
|
|
513
|
+
// second reference here or await a history load before navigating.
|
|
514
|
+
if (typeof ctx.sessions.open === "function") {
|
|
515
|
+
register(ctx, (sessionId) => ctx.sessions.open(sessionId));
|
|
516
|
+
} else {
|
|
517
|
+
// Package client.inject is not a startup-order guarantee. Wait for
|
|
518
|
+
// the actual service and bind the row to that service's lifetime.
|
|
519
|
+
ctx.inject(["uiWorkspace"], (scope) => register(scope,
|
|
520
|
+
(sessionId) => scope.uiWorkspace.openSession(sessionId)));
|
|
521
|
+
}
|
|
127
522
|
}
|
|
128
523
|
|
|
129
524
|
exports.apply = apply;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { HarnessError } from '@deepseek-ai/dsh-llm';
|
|
2
|
+
import { symbols } from '@deepseek-ai/cordis';
|
|
3
|
+
import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
const recordSchema = z.object({
|
|
7
|
+
send: z.boolean(), receive: z.boolean(), revision: z.number().int().nonnegative().safe(),
|
|
8
|
+
}).strict();
|
|
9
|
+
const spec = defineDomain({
|
|
10
|
+
name: 'session_tools_communication', version: 1,
|
|
11
|
+
// Authoritative data: malformed records reject the whole domain, never skip.
|
|
12
|
+
tables: { sessions: domainTable(recordSchema) },
|
|
13
|
+
});
|
|
14
|
+
const states = new WeakMap();
|
|
15
|
+
const defaults = Object.freeze({ send: true, receive: true, revision: 0 });
|
|
16
|
+
export class CommunicationDenied extends HarnessError {
|
|
17
|
+
constructor(direction) {
|
|
18
|
+
super(`未送达、未排队:${direction === 'send' ? '来源会话已关闭发送。' : '目标会话已关闭接收。'}没有消息回执;通信权限改变前不要重复发送。`, 'session-tools/permission-denied');
|
|
19
|
+
this.name = 'CommunicationDenied';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export const sessionIdentitySchema = z.string().min(1).max(1024);
|
|
23
|
+
function sessionKey(id) {
|
|
24
|
+
sessionIdentitySchema.parse(id);
|
|
25
|
+
return id;
|
|
26
|
+
}
|
|
27
|
+
export function trustedSource(exec) { return sessionKey(exec?.agent?.session?.header?.id); }
|
|
28
|
+
|
|
29
|
+
/** One queue shared by all plugin instances, writes and final admissions alike. */
|
|
30
|
+
export function communicationPermissions(ctx) {
|
|
31
|
+
const service = ctx.get('storageDomain');
|
|
32
|
+
if (typeof service?.open !== 'function') throw new Error('Session communication controls require DSH 0.2.0-rc.2 storageDomain.');
|
|
33
|
+
const identity = service[symbols.original] ?? service;
|
|
34
|
+
let state = states.get(identity);
|
|
35
|
+
if (state) return state;
|
|
36
|
+
const ready = service.open(spec);
|
|
37
|
+
// Keep a malformed/unavailable domain closed, while avoiding unhandled rejection.
|
|
38
|
+
ready.catch(() => {});
|
|
39
|
+
let tail = Promise.resolve();
|
|
40
|
+
const serial = (action) => {
|
|
41
|
+
const result = tail.then(async () => action((await ready).table('sessions')));
|
|
42
|
+
tail = result.then(() => {}, () => {});
|
|
43
|
+
return result;
|
|
44
|
+
};
|
|
45
|
+
const read = (table, id) => ({ ...recordSchema.parse(table.get(sessionKey(id)) ?? defaults) });
|
|
46
|
+
const check = (table, sourceId, targetId) => {
|
|
47
|
+
if (!read(table, sourceId).send) throw new CommunicationDenied('send');
|
|
48
|
+
if (targetId !== undefined && !read(table, targetId).receive) throw new CommunicationDenied('receive');
|
|
49
|
+
};
|
|
50
|
+
state = {
|
|
51
|
+
get: (id) => serial(table => read(table, id)),
|
|
52
|
+
check: (sourceId, targetId) => serial(table => check(table, sourceId, targetId)),
|
|
53
|
+
// One authoritative snapshot for the current visible page; never retain it
|
|
54
|
+
// in discovery cursors. This is switch capability, not delivery or approval.
|
|
55
|
+
statuses: (sourceId, targetIds) => serial(table => {
|
|
56
|
+
const source = read(table, sourceId);
|
|
57
|
+
const checkedAt = Date.now();
|
|
58
|
+
return targetIds.map(targetId => {
|
|
59
|
+
const target = read(table, targetId);
|
|
60
|
+
const reason = !source.send && !target.receive ? 'both_disabled'
|
|
61
|
+
: !source.send ? 'sender_send_disabled' : !target.receive ? 'target_receive_disabled' : 'switches_allow';
|
|
62
|
+
return { state: source.send && target.receive ? 'allowed' : 'blocked', reason,
|
|
63
|
+
senderSend: source.send, targetReceive: target.receive, checkedAt };
|
|
64
|
+
});
|
|
65
|
+
}),
|
|
66
|
+
set: (id, patch, expectedRevision) => serial(async table => {
|
|
67
|
+
const parsed = recordSchema.parse({ ...patch, revision: expectedRevision });
|
|
68
|
+
const current = read(table, id);
|
|
69
|
+
if (current.revision !== expectedRevision) return { status: 'conflict', current };
|
|
70
|
+
if (current.revision === Number.MAX_SAFE_INTEGER) throw new Error('Permission revision exhausted');
|
|
71
|
+
const next = { send: parsed.send, receive: parsed.receive, revision: current.revision + 1 };
|
|
72
|
+
await table.put(sessionKey(id), next);
|
|
73
|
+
return { status: 'saved', current: { ...next } };
|
|
74
|
+
}),
|
|
75
|
+
// No await between the final synchronous read/check and followup callback.
|
|
76
|
+
admit: (sourceId, targetId, exec, followup) => serial(table => {
|
|
77
|
+
exec.signal?.throwIfAborted();
|
|
78
|
+
check(table, sourceId, targetId);
|
|
79
|
+
return followup();
|
|
80
|
+
}),
|
|
81
|
+
};
|
|
82
|
+
states.set(identity, state);
|
|
83
|
+
return state;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Explicit unknown never invents open defaults when identity/storage is unavailable.
|
|
87
|
+
export const unknownCommunication = () => ({ state: 'unknown', reason: 'unavailable', checkedAt: Date.now() });
|
|
88
|
+
export const communicationStatusSchema = {
|
|
89
|
+
type: 'object', additionalProperties: false,
|
|
90
|
+
properties: {
|
|
91
|
+
state: { type: 'string', required: true, enum: ['allowed', 'blocked', 'unknown'] },
|
|
92
|
+
reason: { type: 'string', required: true, enum: ['switches_allow', 'sender_send_disabled', 'target_receive_disabled', 'both_disabled', 'unavailable'] },
|
|
93
|
+
senderSend: { type: 'boolean' }, targetReceive: { type: 'boolean' },
|
|
94
|
+
checkedAt: { type: 'number', required: true },
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
export function communicationStatusText(status) {
|
|
98
|
+
return ({ switches_allow: '通信开关允许', sender_send_disabled: '当前会话已关闭发送',
|
|
99
|
+
target_receive_disabled: '目标已关闭接收', both_disabled: '当前会话已关闭发送,目标已关闭接收',
|
|
100
|
+
unavailable: '通信状态无法确认' })[status.reason] ?? '通信状态无法确认';
|
|
101
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { symbols } from '@deepseek-ai/cordis';
|
|
2
|
+
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { communicationPermissions, sessionIdentitySchema } from './communication-permissions.js';
|
|
5
|
+
|
|
6
|
+
const sessionId = sessionIdentitySchema;
|
|
7
|
+
const getSchema = z.object({ sessionId }).strict();
|
|
8
|
+
const setSchema = z.object({ sessionId, send: z.boolean(), receive: z.boolean(), expectedRevision: z.number().int().nonnegative().safe() }).strict();
|
|
9
|
+
const recordSchema = z.object({ send: z.boolean(), receive: z.boolean(), revision: z.number().int().nonnegative().safe() }).strict();
|
|
10
|
+
const setResultSchema = z.object({ status: z.enum(['saved', 'conflict']), current: recordSchema }).strict();
|
|
11
|
+
export const communicationRemote = {
|
|
12
|
+
package: '@ryuu-64/dsh-session-tools',
|
|
13
|
+
descriptors: ['get', 'set'].map(method => ({
|
|
14
|
+
id: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}`,
|
|
15
|
+
service: 'sessionCommunication', namespace: 'sessionCommunication', method,
|
|
16
|
+
invocation: { kind: 'direct' },
|
|
17
|
+
parameters: [{ name: 'request', wire: 'request', source: 'json', codec: {
|
|
18
|
+
mode: 'strict', typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:request`,
|
|
19
|
+
create: () => method === 'get' ? getSchema : setSchema,
|
|
20
|
+
} }],
|
|
21
|
+
result: {
|
|
22
|
+
mode: 'strict', typeSymbol: `@ryuu-64/dsh-session-tools:sessionCommunication.${method}:result`,
|
|
23
|
+
create: () => method === 'get' ? recordSchema : setResultSchema,
|
|
24
|
+
},
|
|
25
|
+
})),
|
|
26
|
+
};
|
|
27
|
+
const initializers = [];
|
|
28
|
+
const original = value => value?.[symbols.original] ?? value;
|
|
29
|
+
/** A Remote UI surface only. No corresponding model tool is registered. */
|
|
30
|
+
export class CommunicationRemote extends TypertRemoteService {
|
|
31
|
+
static inject = ['typert', 'connection', 'storageDomain'];
|
|
32
|
+
constructor(ctx) {
|
|
33
|
+
super(ctx, 'sessionCommunication');
|
|
34
|
+
for (const initialize of initializers) initialize.call(this);
|
|
35
|
+
ctx.typert.register({
|
|
36
|
+
package: communicationRemote.package, face: 'host', schemas: [],
|
|
37
|
+
model: { services: [], events: [], objects: [] },
|
|
38
|
+
invocations: communicationRemote.descriptors,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
authorize() {
|
|
42
|
+
const invocation = this.ctx.invocation;
|
|
43
|
+
const operator = this.ctx.connection.operator;
|
|
44
|
+
if (!invocation || !operator || original(invocation.peer) !== original(operator)) {
|
|
45
|
+
throw new RemoteError('gateway/bad-request', 'Only the authenticated host operator can read or change communication permissions.', {});
|
|
46
|
+
}
|
|
47
|
+
invocation.signal.throwIfAborted();
|
|
48
|
+
}
|
|
49
|
+
async get(request) {
|
|
50
|
+
this.authorize();
|
|
51
|
+
const parsed = getSchema.parse(request);
|
|
52
|
+
return await communicationPermissions(this.ctx).get(parsed.sessionId);
|
|
53
|
+
}
|
|
54
|
+
async set(request) {
|
|
55
|
+
this.authorize();
|
|
56
|
+
const parsed = setSchema.parse(request);
|
|
57
|
+
return await communicationPermissions(this.ctx).set(parsed.sessionId, { send: parsed.send, receive: parsed.receive }, parsed.expectedRevision);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// Apply the official standard-decorator initialization contract in plain JS.
|
|
61
|
+
for (const method of ['get', 'set']) Remote(CommunicationRemote.prototype[method], {
|
|
62
|
+
kind: 'method', name: method, static: false, private: false,
|
|
63
|
+
addInitializer: initialize => initializers.push(initialize),
|
|
64
|
+
});
|