@unieai/rabi-session-log-export 0.2.1-rc.3 → 0.2.2-rc.5
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 +1 -1
- package/lib/client.js +1 -315
- package/lib/index.js +434 -19
- package/lib/types/client/CopyToast.d.ts +21 -0
- package/lib/types/client/Dialog.d.ts +8 -7
- package/lib/types/client/controller.d.ts +7 -3
- package/lib/types/client/copy-controller.d.ts +76 -0
- package/lib/types/client/index.d.ts +3 -2
- package/lib/types/client/locales.d.ts +108 -2
- package/lib/types/index.d.ts +3 -2
- package/lib/types/markdown.d.ts +22 -0
- package/lib/types/routes.d.ts +6 -2
- package/locale/de.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/package.json +14 -10
- package/src/archive.ts +706 -0
- package/src/client/CopyToast.tsx +40 -0
- package/src/client/Dialog.tsx +55 -0
- package/src/client/controller.ts +139 -0
- package/src/client/copy-controller.ts +201 -0
- package/src/client/index.ts +105 -0
- package/src/client/locales.ts +149 -0
- package/src/index.ts +234 -0
- package/src/markdown.ts +367 -0
- package/src/routes.ts +17 -0
- package/lib/types/client/HeaderAction.d.ts +0 -26
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @unieai/rabi-session-log-export
|
|
2
2
|
|
|
3
|
-
Web Session-log export
|
|
3
|
+
Web Session-log ZIP export and Session Markdown copy
|
|
4
4
|
|
|
5
5
|
Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
|
|
6
6
|
not meant to be used on its own.
|
package/lib/client.js
CHANGED
|
@@ -1,316 +1,2 @@
|
|
|
1
|
-
window.__ModuleLoader__.load({
|
|
2
|
-
id: "@unieai/rabi-session-log-export",
|
|
3
|
-
factory: (require) => {
|
|
4
|
-
var module = { exports: {} };
|
|
5
|
-
var exports = module.exports;
|
|
6
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
7
|
-
let _unieai_rabi_client_store = require("@unieai/rabi-client-store");
|
|
8
|
-
let react_jsx_runtime = require("react/jsx-runtime");
|
|
9
|
-
let react = require("react");
|
|
10
|
-
let _unieai_rabi_client_ui_primitives = require("@unieai/rabi-client-ui-primitives");
|
|
11
|
-
/** Browser-relative form of {@link SESSION_LOG_EXPORT_PATH}. */
|
|
12
|
-
const SESSION_LOG_EXPORT_ROUTE = "/api/session.export".slice(1);
|
|
13
|
-
//#endregion
|
|
14
|
-
//#region lib/types/client/controller.js
|
|
15
|
-
/** Browser download state shared by the Session Header button and `/export`. */
|
|
16
|
-
const INITIAL = { bySession: {} };
|
|
17
|
-
/**
|
|
18
|
-
* Collapse an untrusted Session id into the filename convention owned by the host endpoint.
|
|
19
|
-
* @param sessionId - Session whose archive is downloaded.
|
|
20
|
-
* @returns one safe browser download filename.
|
|
21
|
-
*/
|
|
22
|
-
function sessionLogZipFilename(sessionId) {
|
|
23
|
-
return `rabi-session-${String(sessionId).replace(/[^A-Za-z0-9_-]/g, "_")}.zip`;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Hand a Host download route to the browser download manager, which resolves it
|
|
27
|
-
* against the document's own base.
|
|
28
|
-
* @param url - document-relative Host download route.
|
|
29
|
-
* @param filename - browser download filename.
|
|
30
|
-
*/
|
|
31
|
-
function downloadUrl(url, filename) {
|
|
32
|
-
const anchor = document.createElement("a");
|
|
33
|
-
anchor.href = url;
|
|
34
|
-
anchor.download = filename;
|
|
35
|
-
anchor.click();
|
|
36
|
-
}
|
|
37
|
-
function messageOf(error) {
|
|
38
|
-
return error instanceof Error ? error.message : String(error);
|
|
39
|
-
}
|
|
40
|
-
/** Owns one in-flight browser download per Session and publishes modal state. */
|
|
41
|
-
var SessionLogDownloadController = class {
|
|
42
|
-
fetcher;
|
|
43
|
-
save;
|
|
44
|
-
/** uSES-safe state source shared by every Session-scoped modal contribution. */
|
|
45
|
-
store = (0, _unieai_rabi_client_store.createSnapshotStore)(INITIAL);
|
|
46
|
-
active = /* @__PURE__ */ new Map();
|
|
47
|
-
disposed = false;
|
|
48
|
-
/**
|
|
49
|
-
* @param fetcher - HTTP carrier used to read the host-streamed ZIP.
|
|
50
|
-
* @param save - browser save operation.
|
|
51
|
-
*/
|
|
52
|
-
constructor(fetcher = (input, init) => fetch(input, init), save = downloadUrl) {
|
|
53
|
-
this.fetcher = fetcher;
|
|
54
|
-
this.save = save;
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Download one Session tree; concurrent gestures for the same Session share one operation.
|
|
58
|
-
* @param sessionId - root Session whose ZIP includes descendants and attachments.
|
|
59
|
-
* @returns after the browser save starts, an error state is published, or a late post-disposal request is ignored.
|
|
60
|
-
*/
|
|
61
|
-
download(sessionId) {
|
|
62
|
-
const existing = this.active.get(sessionId);
|
|
63
|
-
if (existing !== void 0) return existing.done;
|
|
64
|
-
if (this.disposed) return Promise.resolve();
|
|
65
|
-
const abort = new AbortController();
|
|
66
|
-
const done = this.run(sessionId, abort.signal).finally(() => {
|
|
67
|
-
this.active.delete(sessionId);
|
|
68
|
-
});
|
|
69
|
-
this.active.set(sessionId, {
|
|
70
|
-
abort,
|
|
71
|
-
done
|
|
72
|
-
});
|
|
73
|
-
return done;
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Close one Session's dialog without cancelling an in-flight browser download.
|
|
77
|
-
* @param sessionId - Session whose modal closes.
|
|
78
|
-
*/
|
|
79
|
-
dismiss(sessionId) {
|
|
80
|
-
const current = this.store.getSnapshot().bySession[String(sessionId)];
|
|
81
|
-
if (current === void 0 || !current.open) return;
|
|
82
|
-
this.publish(sessionId, {
|
|
83
|
-
...current,
|
|
84
|
-
open: false
|
|
85
|
-
});
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Abort active fetches and reach quiescence.
|
|
89
|
-
* @returns after every active operation settles.
|
|
90
|
-
*/
|
|
91
|
-
async dispose() {
|
|
92
|
-
this.disposed = true;
|
|
93
|
-
const active = [...this.active.values()];
|
|
94
|
-
for (const operation of active) operation.abort.abort();
|
|
95
|
-
await Promise.allSettled(active.map((operation) => operation.done));
|
|
96
|
-
}
|
|
97
|
-
async run(sessionId, signal) {
|
|
98
|
-
this.publish(sessionId, {
|
|
99
|
-
open: true,
|
|
100
|
-
status: "downloading",
|
|
101
|
-
error: null
|
|
102
|
-
});
|
|
103
|
-
try {
|
|
104
|
-
const route = `${SESSION_LOG_EXPORT_ROUTE}?${new URLSearchParams({
|
|
105
|
-
sessionId,
|
|
106
|
-
includeDescendants: "true"
|
|
107
|
-
}).toString()}`;
|
|
108
|
-
const response = await this.fetcher(route, {
|
|
109
|
-
method: "HEAD",
|
|
110
|
-
signal
|
|
111
|
-
});
|
|
112
|
-
if (!response.ok) {
|
|
113
|
-
const detail = await response.text().catch(() => "");
|
|
114
|
-
throw new Error(`Export failed: HTTP ${response.status}${detail === "" ? "" : ` ${detail}`}`);
|
|
115
|
-
}
|
|
116
|
-
this.save(route, sessionLogZipFilename(sessionId));
|
|
117
|
-
const open = this.store.getSnapshot().bySession[String(sessionId)]?.open ?? true;
|
|
118
|
-
this.publish(sessionId, {
|
|
119
|
-
open,
|
|
120
|
-
status: "success",
|
|
121
|
-
error: null
|
|
122
|
-
});
|
|
123
|
-
} catch (error) {
|
|
124
|
-
if (signal.aborted) return;
|
|
125
|
-
const open = this.store.getSnapshot().bySession[String(sessionId)]?.open ?? true;
|
|
126
|
-
this.publish(sessionId, {
|
|
127
|
-
open,
|
|
128
|
-
status: "error",
|
|
129
|
-
error: messageOf(error)
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
publish(sessionId, entry) {
|
|
134
|
-
this.store.update((state) => {
|
|
135
|
-
state.bySession = {
|
|
136
|
-
...state.bySession,
|
|
137
|
-
[String(sessionId)]: entry
|
|
138
|
-
};
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
//#endregion
|
|
143
|
-
//#region lib/types/client/Dialog.js
|
|
144
|
-
/**
|
|
145
|
-
* Modal shared by the Session Header download menu item and this browser's `/export` command.
|
|
146
|
-
* @param props - Session runtime, bound controller state, actions, and localized copy.
|
|
147
|
-
* @returns the modal portal contribution.
|
|
148
|
-
*/
|
|
149
|
-
function SessionLogDownloadDialog({ sessionId, useSessionLogDownload, dismiss, t }) {
|
|
150
|
-
const entry = useSessionLogDownload((state) => state.bySession[String(sessionId)]);
|
|
151
|
-
const status = entry?.status;
|
|
152
|
-
const open = entry?.open === true;
|
|
153
|
-
const error = status === "error" ? entry?.error || t("dialog.commandFailed") : null;
|
|
154
|
-
return (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Modal, {
|
|
155
|
-
open,
|
|
156
|
-
onClose: () => {
|
|
157
|
-
dismiss(sessionId);
|
|
158
|
-
},
|
|
159
|
-
title: status === "downloading" ? t("dialog.preparingTitle") : status === "success" ? t("dialog.successTitle") : t("dialog.errorTitle"),
|
|
160
|
-
description: status === "downloading" ? t("dialog.preparingDescription") : status === "success" ? t("dialog.successDescription") : error ?? t("dialog.commandFailed"),
|
|
161
|
-
closeLabel: t("dialog.close"),
|
|
162
|
-
footer: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Button, {
|
|
163
|
-
variant: "primary",
|
|
164
|
-
onClick: () => {
|
|
165
|
-
dismiss(sessionId);
|
|
166
|
-
},
|
|
167
|
-
children: t("dialog.close")
|
|
168
|
-
})
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
//#endregion
|
|
172
|
-
//#region \0rabi-css:/home/runner/work/rabi-harness/rabi-harness/packages/session-query/session-log-export/src/client/HeaderAction.module.css.mjs
|
|
173
|
-
const css = ".nL4_yW_moreButton{width:28px;color:var(--dsw-alias-label-secondary);flex:none;padding:0}.nL4_yW_moreButton svg{width:15px;height:15px}";
|
|
174
|
-
const tagId = "@unieai/rabi-session-log-export/HeaderAction.module.css";
|
|
175
|
-
if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
|
|
176
|
-
const tag = document.createElement("style");
|
|
177
|
-
tag.dataset.plugin = "@unieai/rabi-session-log-export";
|
|
178
|
-
tag.dataset.pluginCss = tagId;
|
|
179
|
-
tag.textContent = css;
|
|
180
|
-
document.head.appendChild(tag);
|
|
181
|
-
}
|
|
182
|
-
var HeaderAction_module_css_default = { "moreButton": "nL4_yW_moreButton" };
|
|
183
|
-
//#endregion
|
|
184
|
-
//#region lib/types/client/HeaderAction.js
|
|
185
|
-
/**
|
|
186
|
-
* Render the Session Header menu with download and optional feedback actions.
|
|
187
|
-
* @param props - Session runtime, download controller, and localized copy.
|
|
188
|
-
* @returns the persistent Header action and Session-scoped dialog.
|
|
189
|
-
*/
|
|
190
|
-
function SessionLogDownloadHeaderAction(props) {
|
|
191
|
-
const { sessionId, useSessionLogDownload, useFeedbackAvailable, request, openFeedback, t } = props;
|
|
192
|
-
const feedbackAvailable = useFeedbackAvailable((value) => value);
|
|
193
|
-
const busy = useSessionLogDownload((state) => state.bySession[String(sessionId)])?.status === "downloading";
|
|
194
|
-
const [open, setOpen] = (0, react.useState)(false);
|
|
195
|
-
return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Menu, {
|
|
196
|
-
open,
|
|
197
|
-
align: "end",
|
|
198
|
-
dense: true,
|
|
199
|
-
onClose: () => {
|
|
200
|
-
setOpen(false);
|
|
201
|
-
},
|
|
202
|
-
items: [{
|
|
203
|
-
id: "download",
|
|
204
|
-
label: t("menu.download"),
|
|
205
|
-
icon: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconDownloadOutlineRegular, {}),
|
|
206
|
-
disabled: busy
|
|
207
|
-
}, ...feedbackAvailable ? [{
|
|
208
|
-
id: "feedback",
|
|
209
|
-
label: t("menu.feedback"),
|
|
210
|
-
icon: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconPaperPlaneOutlineRegular, {})
|
|
211
|
-
}] : []],
|
|
212
|
-
onSelect: (id) => {
|
|
213
|
-
setOpen(false);
|
|
214
|
-
if (id === "feedback") openFeedback(sessionId);
|
|
215
|
-
else request(sessionId);
|
|
216
|
-
},
|
|
217
|
-
anchor: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Button, {
|
|
218
|
-
size: "sm",
|
|
219
|
-
className: HeaderAction_module_css_default.moreButton,
|
|
220
|
-
"aria-label": t("header.more"),
|
|
221
|
-
"aria-haspopup": "menu",
|
|
222
|
-
"aria-expanded": open,
|
|
223
|
-
"aria-busy": busy,
|
|
224
|
-
onClick: () => {
|
|
225
|
-
setOpen((value) => !value);
|
|
226
|
-
},
|
|
227
|
-
children: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconEllipsisOutlineRegular, {})
|
|
228
|
-
})
|
|
229
|
-
}), (0, react_jsx_runtime.jsx)(SessionLogDownloadDialog, { ...props })] });
|
|
230
|
-
}
|
|
231
|
-
//#endregion
|
|
232
|
-
//#region lib/types/client/locales.js
|
|
233
|
-
/** Locale namespace owned by Session export browser feedback. */
|
|
234
|
-
const NS = "session-log-download";
|
|
235
|
-
/** Simplified-Chinese Session export strings. */
|
|
236
|
-
const zh = {
|
|
237
|
-
"header.more": "更多操作",
|
|
238
|
-
"menu.download": "下载 Session 日志",
|
|
239
|
-
"menu.feedback": "反馈",
|
|
240
|
-
"dialog.preparingTitle": "正在导出 Session",
|
|
241
|
-
"dialog.preparingDescription": "正在准备包含当前 Session、子 Session 和附件的 ZIP 文件。",
|
|
242
|
-
"dialog.successTitle": "Session 导出已开始下载",
|
|
243
|
-
"dialog.successDescription": "浏览器正在下载 Session ZIP 文件。",
|
|
244
|
-
"dialog.errorTitle": "Session 导出失败",
|
|
245
|
-
"dialog.close": "关闭",
|
|
246
|
-
"dialog.commandFailed": "无法启动 Session 导出。"
|
|
247
|
-
};
|
|
248
|
-
/** English Session export strings. */
|
|
249
|
-
const en = {
|
|
250
|
-
"header.more": "More actions",
|
|
251
|
-
"menu.download": "Download session log",
|
|
252
|
-
"menu.feedback": "Feedback",
|
|
253
|
-
"dialog.preparingTitle": "Exporting Session",
|
|
254
|
-
"dialog.preparingDescription": "Preparing a ZIP containing this Session, its sub-Sessions, and attachments.",
|
|
255
|
-
"dialog.successTitle": "Session download started",
|
|
256
|
-
"dialog.successDescription": "The browser is downloading the Session ZIP.",
|
|
257
|
-
"dialog.errorTitle": "Session export failed",
|
|
258
|
-
"dialog.close": "Close",
|
|
259
|
-
"dialog.commandFailed": "Could not start the Session export."
|
|
260
|
-
};
|
|
261
|
-
//#endregion
|
|
262
|
-
//#region lib/types/client/index.js
|
|
263
|
-
/** Browser plugin owning Session export download state and its shared modal. */
|
|
264
|
-
const inject = ["slots", "locale"];
|
|
265
|
-
/**
|
|
266
|
-
* Provide the download controller and mount its modal into the Session Header.
|
|
267
|
-
* @param ctx - browser context carrying slots and locale services.
|
|
268
|
-
*/
|
|
269
|
-
function apply(ctx) {
|
|
270
|
-
const controller = new SessionLogDownloadController();
|
|
271
|
-
ctx.provide("sessionLogDownload", controller);
|
|
272
|
-
ctx.effect(() => async () => {
|
|
273
|
-
await controller.dispose();
|
|
274
|
-
}, "session-log-download: browser download lifecycle");
|
|
275
|
-
ctx.effect(() => ctx.locale.register(NS, {
|
|
276
|
-
zh,
|
|
277
|
-
en
|
|
278
|
-
}), "session-log-download: browser dictionaries");
|
|
279
|
-
const feedbackAvailable = (0, _unieai_rabi_client_store.createSnapshotStore)(false);
|
|
280
|
-
ctx.inject(["feedbackUi"], (scope) => {
|
|
281
|
-
scope.effect(() => {
|
|
282
|
-
feedbackAvailable.set(true);
|
|
283
|
-
return () => {
|
|
284
|
-
feedbackAvailable.set(false);
|
|
285
|
-
};
|
|
286
|
-
}, "session-log-download: feedback availability");
|
|
287
|
-
});
|
|
288
|
-
ctx.on("command/executed", (sessionId, commandName, result) => {
|
|
289
|
-
if (commandName === "export" && result.kind === "success") controller.download(sessionId);
|
|
290
|
-
});
|
|
291
|
-
ctx.slots.inject("conversation.session.header.utilities", () => ctx.slots.register({
|
|
292
|
-
name: "conversation.session.header.utilities",
|
|
293
|
-
id: "session-log-download",
|
|
294
|
-
locale: NS,
|
|
295
|
-
inject: () => ({
|
|
296
|
-
hooks: {
|
|
297
|
-
sessionLogDownload: controller.store,
|
|
298
|
-
feedbackAvailable
|
|
299
|
-
},
|
|
300
|
-
request: (sessionId) => controller.download(sessionId),
|
|
301
|
-
dismiss: (sessionId) => {
|
|
302
|
-
controller.dismiss(sessionId);
|
|
303
|
-
},
|
|
304
|
-
openFeedback: (sessionId) => {
|
|
305
|
-
ctx.get("feedbackUi")?.openSession(sessionId);
|
|
306
|
-
}
|
|
307
|
-
})
|
|
308
|
-
}, SessionLogDownloadHeaderAction));
|
|
309
|
-
}
|
|
310
|
-
//#endregion
|
|
311
|
-
exports.apply = apply;
|
|
312
|
-
exports.inject = inject;
|
|
313
|
-
return module.exports;
|
|
314
|
-
}
|
|
315
|
-
});
|
|
316
1
|
|
|
2
|
+
window.__ModuleLoader__.load({id:`@unieai/rabi-session-log-export`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _unieai_rabi_client_store=require("@unieai/rabi-client-store");let _unieai_rabi_client_ui_primitives=require("@unieai/rabi-client-ui-primitives");let react_jsx_runtime=require("react/jsx-runtime");const SESSION_LOG_EXPORT_PATH=`/api/session.export`;const SESSION_LOG_EXPORT_ROUTE=SESSION_LOG_EXPORT_PATH.slice(1);const SESSION_MARKDOWN_EXPORT_PATH=`/api/session.markdown`;const SESSION_MARKDOWN_EXPORT_ROUTE=SESSION_MARKDOWN_EXPORT_PATH.slice(1);const INITIAL$1={bySession:{}};function sessionLogZipFilename(sessionId){return`rabi-session-${String(sessionId).replace(/[^A-Za-z0-9_-]/g,`_`)}.zip`}function downloadUrl(url,filename){const anchor=document.createElement(`a`);anchor.href=url;anchor.download=filename;anchor.click()}function messageOf(error){return error instanceof Error?error.message:String(error)}var SessionLogDownloadController=class{fetcher;save;store=(0,_unieai_rabi_client_store.createSnapshotStore)(INITIAL$1);active=new Map;disposed=false;nextOrder=0;constructor(fetcher=(input,init)=>fetch(input,init),save=downloadUrl){this.fetcher=fetcher;this.save=save}download(sessionId){const existing=this.active.get(sessionId);if(existing!==void 0)return existing.done;if(this.disposed)return Promise.resolve();const abort=new AbortController;const done=this.run(sessionId,abort.signal,this.nextOrder++).finally(()=>{this.active.delete(sessionId)});this.active.set(sessionId,{abort,done});return done}dismiss(sessionId){const current=this.store.getSnapshot().bySession[String(sessionId)];if(current===void 0||!current.open)return;this.publish(sessionId,{...current,open:false})}async dispose(){this.disposed=true;const active=[...this.active.values()];for(const operation of active)operation.abort.abort();await Promise.allSettled(active.map(operation=>operation.done))}async run(sessionId,signal,order){this.publish(sessionId,{order,open:true,status:`downloading`,error:null});try{const route=`${SESSION_LOG_EXPORT_ROUTE}?${new URLSearchParams({sessionId,includeDescendants:`true`}).toString()}`;const response=await this.fetcher(route,{method:`HEAD`,signal});if(!response.ok){const detail=await response.text().catch(()=>``);throw new Error(`Export failed: HTTP ${response.status}${detail===``?``:` ${detail}`}`)}if(signal.aborted)return;this.save(route,sessionLogZipFilename(sessionId));const open=this.store.getSnapshot().bySession[String(sessionId)]?.open??true;this.publish(sessionId,{order,open,status:`success`,error:null})}catch(error){if(signal.aborted)return;const open=this.store.getSnapshot().bySession[String(sessionId)]?.open??true;this.publish(sessionId,{order,open,status:`error`,error:messageOf(error)})}}publish(sessionId,entry){this.store.update(state=>{state.bySession={...state.bySession,[String(sessionId)]:entry}})}};const INITIAL={copying:false,notice:null};const browserClipboard={supportsDeferredWrite(){const clipboard=Reflect.get(navigator,`clipboard`);return typeof globalThis.ClipboardItem===`function`&&typeof clipboard===`object`&&clipboard!==null&&typeof Reflect.get(clipboard,`write`)===`function`},writeDeferred(data){return navigator.clipboard.write([new ClipboardItem({"text/plain":data})])},writeText:_unieai_rabi_client_ui_primitives.writeClipboard};function startWrite(start){try{return start()}catch(error){return Promise.reject(new Error(`clipboard write could not start`,{cause:error}))}}var SessionMarkdownCopyController=class{fetcher;clipboard;store=(0,_unieai_rabi_client_store.createSnapshotStore)(INITIAL);pending;disposed=false;noticeSeq=0;constructor(fetcher=(input,init)=>fetch(input,init),clipboard=browserClipboard){this.fetcher=fetcher;this.clipboard=clipboard}copy(sessionId){if(this.disposed)return Promise.resolve();if(this.pending!==void 0)return this.pending.done;const abort=new AbortController;const done=this.run(sessionId,abort.signal).finally(()=>{this.pending=void 0});this.pending={abort,done};return done}dismiss(){if(this.store.getSnapshot().notice===null)return;this.store.update(state=>{state.notice=null})}async dispose(){this.disposed=true;const pending=this.pending;pending?.abort.abort();await pending?.done;this.store.set(INITIAL)}run(sessionId,signal){this.store.update(state=>{state.copying=true});const preparation=this.prepare(sessionId,signal);if(this.clipboard.supportsDeferredWrite()){const data=preparation.then(markdown=>{if(this.isCancelled()||signal.aborted)throw new Error(`Session Markdown copy cancelled`);return new Blob([markdown],{type:`text/plain`})});const write=startWrite(()=>this.clipboard.writeDeferred(data));return this.settleDeferred(preparation,data,write)}return this.settleFallback(preparation)}async prepare(sessionId,signal){const route=`${SESSION_MARKDOWN_EXPORT_ROUTE}?${new URLSearchParams({sessionId}).toString()}`;const response=await this.fetcher(route,{signal});if(!response.ok)throw new Error(`Session Markdown request failed: HTTP ${String(response.status)}`);return response.text()}async settleDeferred(preparation,data,write){try{const[prepared,blob,written]=await Promise.allSettled([preparation,data,write]);if(this.isCancelled())return;if(prepared.status===`rejected`||blob.status===`rejected`){this.publishNotice(`preparationFailed`);return}if(written.status===`rejected`){this.publishNotice(`clipboardFailed`);return}this.publishNotice(`success`)}finally{this.store.update(state=>{state.copying=false})}}async settleFallback(preparation){try{let markdown;try{markdown=await preparation}catch{if(!this.isCancelled())this.publishNotice(`preparationFailed`);return}if(this.isCancelled())return;let accepted=false;try{accepted=await this.clipboard.writeText(markdown)}catch{accepted=false}if(this.isCancelled())return;this.publishNotice(accepted?`success`:`clipboardFailed`)}finally{this.store.update(state=>{state.copying=false})}}isCancelled(){return this.disposed}publishNotice(kind){this.store.update(state=>{state.notice={kind,seq:++this.noticeSeq}})}};function SessionMarkdownCopyToast({useSessionMarkdownCopy,dismiss,t}){const notice=useSessionMarkdownCopy(state=>state.notice);if(notice===null)return null;return notice.kind===`success`?(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Toast,{text:t(`toast.copied`),tone:`success`,onDone:dismiss},notice.seq):(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Toast,{text:t(notice.kind===`preparationFailed`?`toast.preparationFailed`:`toast.clipboardFailed`),icon:(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconWarningOutlineRegular,{}),onDone:dismiss},notice.seq)}function SessionLogDownloadDialog({useSessionLogDownload,dismiss,t}){const bySession=useSessionLogDownload(state=>state.bySession);const pending=Object.entries(bySession).filter(pair=>pair[1]?.open===true).sort((a,b)=>a[1].order-b[1].order)[0];if(pending===void 0)return null;const[id,entry]=pending;const sessionId=id;const{status}=entry;const title=status===`downloading`?t(`dialog.preparingTitle`):status===`success`?t(`dialog.successTitle`):t(`dialog.errorTitle`);const description=status===`downloading`?t(`dialog.preparingDescription`):status===`success`?t(`dialog.successDescription`):entry.error||t(`dialog.commandFailed`);return(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Modal,{open:true,onClose:()=>{dismiss(sessionId)},title,description:`${t(`dialog.session`,{sessionId})} ${description}`,closeLabel:t(`dialog.close`),footer:(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Button,{variant:`primary`,onClick:()=>{dismiss(sessionId)},children:t(`dialog.close`)})})}const NS=`session-log-download`;const zh={"menu.copyMarkdown":`复制会话为 Markdown`,"menu.download":`下载 Session 日志`,"menu.feedback":`反馈`,"toast.copied":`Session 已复制为 Markdown`,"toast.preparationFailed":`无法读取 Session 进行复制,请重试`,"toast.clipboardFailed":`无法写入剪贴板,请检查剪贴板权限后重试`,"dialog.session":`Session:{sessionId}`,"dialog.preparingTitle":`正在导出 Session`,"dialog.preparingDescription":`正在准备包含指定 Session、子 Session 和附件的 ZIP 文件`,"dialog.successTitle":`Session 导出已开始下载`,"dialog.successDescription":`浏览器正在下载 Session ZIP 文件。`,"dialog.errorTitle":`Session 导出失败`,"dialog.close":`关闭`,"dialog.commandFailed":`无法启动 Session 导出。`};const en={"menu.copyMarkdown":`Copy Session as Markdown`,"menu.download":`Download session log`,"menu.feedback":`Feedback`,"toast.copied":`Session copied as Markdown.`,"toast.preparationFailed":`Could not read the Session for copying. Try again.`,"toast.clipboardFailed":`Could not write to the clipboard. Check clipboard permission and try again.`,"dialog.session":`Session: {sessionId}`,"dialog.preparingTitle":`Exporting Session`,"dialog.preparingDescription":`Preparing a ZIP containing the selected Session, its sub-Sessions, and attachments.`,"dialog.successTitle":`Session download started`,"dialog.successDescription":`The browser is downloading the Session ZIP.`,"dialog.errorTitle":`Session export failed`,"dialog.close":`Close`,"dialog.commandFailed":`Could not start the Session export.`};const ja={"menu.copyMarkdown":`セッションを Markdown としてコピー`,"menu.download":`セッションログをダウンロード`,"menu.feedback":`フィードバック`,"toast.copied":`セッションを Markdown としてコピーしました`,"toast.preparationFailed":`コピーするセッションを読み取れませんでした。再試行してください。`,"toast.clipboardFailed":`クリップボードに書き込めませんでした。クリップボードの権限を確認して再試行してください。`,"dialog.session":`セッション: {sessionId}`,"dialog.preparingTitle":`セッションをエクスポート中`,"dialog.preparingDescription":`指定のセッション、そのサブセッション、添付ファイルを含むZIPを準備しています。`,"dialog.successTitle":`セッションのダウンロードを開始しました`,"dialog.successDescription":`ブラウザがセッションZIPをダウンロードしています。`,"dialog.errorTitle":`セッションのエクスポートに失敗しました`,"dialog.close":`閉じる`,"dialog.commandFailed":`セッションのエクスポートを開始できませんでした。`};const es={"menu.copyMarkdown":`Copiar sesión como Markdown`,"menu.download":`Descargar registro de sesión`,"menu.feedback":`Comentarios`,"toast.copied":`Sesión copiada como Markdown.`,"toast.preparationFailed":`No se pudo leer la sesión para copiarla. Intentar otra vez.`,"toast.clipboardFailed":`No se pudo escribir en el portapapeles. Verifique los permisos del portapapeles e inténtelo nuevamente.`,"dialog.session":`Sesión: {sessionId}`,"dialog.preparingTitle":`Sesión de exportación`,"dialog.preparingDescription":`Preparar un ZIP que contenga la sesión seleccionada, sus subsesiones y archivos adjuntos.`,"dialog.successTitle":`Descarga de sesión iniciada`,"dialog.successDescription":`El navegador está descargando el ZIP de la sesión.`,"dialog.errorTitle":`Error al exportar la sesión`,"dialog.close":`Cerrar`,"dialog.commandFailed":`No se pudo iniciar la exportación de la sesión.`};const fr={"menu.copyMarkdown":`Copier la session sous Markdown`,"menu.download":`Télécharger le journal de session`,"menu.feedback":`Commentaires`,"toast.copied":`Session copiée sous le nom Markdown.`,"toast.preparationFailed":`Impossible de lire la session pour la copier. Essayer à nouveau.`,"toast.clipboardFailed":`Impossible d'écrire dans le presse-papiers. Vérifiez l'autorisation du presse-papiers et réessayez.`,"dialog.session":`Session : {sessionId}`,"dialog.preparingTitle":`Session d'exportation`,"dialog.preparingDescription":`Préparation d'un ZIP contenant la session sélectionnée, ses sous-sessions et les pièces jointes.`,"dialog.successTitle":`Le téléchargement de la session a commencé`,"dialog.successDescription":`Le navigateur télécharge le ZIP de la session.`,"dialog.errorTitle":`Échec de l'exportation de la session`,"dialog.close":`Fermer`,"dialog.commandFailed":`Impossible de démarrer l'exportation de session.`};const de={"menu.copyMarkdown":`Kopieren Sie die Sitzung als Markdown`,"menu.download":`Sitzungsprotokoll herunterladen`,"menu.feedback":`Rückmeldung`,"toast.copied":`Sitzung als Markdown kopiert.`,"toast.preparationFailed":`Die Sitzung zum Kopieren konnte nicht gelesen werden. Versuchen Sie es erneut.`,"toast.clipboardFailed":`Es konnte nicht in die Zwischenablage geschrieben werden. Überprüfen Sie die Berechtigung für die Zwischenablage und versuchen Sie es erneut.`,"dialog.session":`Sitzung: {sessionId}`,"dialog.preparingTitle":`Sitzung exportieren`,"dialog.preparingDescription":`Vorbereiten einer ZIP-Datei mit der ausgewählten Sitzung, ihren Untersitzungen und Anhängen.`,"dialog.successTitle":`Sitzungsdownload gestartet`,"dialog.successDescription":`Der Browser lädt die Sitzungs-ZIP herunter.`,"dialog.errorTitle":`Der Sitzungsexport ist fehlgeschlagen`,"dialog.close":`Schließen`,"dialog.commandFailed":`Der Sitzungsexport konnte nicht gestartet werden.`};const ru={"menu.copyMarkdown":`Скопировать сеанс как Markdown`,"menu.download":`Скачать журнал сеанса`,"menu.feedback":`Обратная связь`,"toast.copied":`Сессия скопирована как Markdown.`,"toast.preparationFailed":`Не удалось прочитать сеанс для копирования. Попробуйте еще раз.`,"toast.clipboardFailed":`Не удалось записать в буфер обмена. Проверьте разрешение буфера обмена и повторите попытку.`,"dialog.session":`Сеанс: {sessionId}`,"dialog.preparingTitle":`Экспорт сеанса`,"dialog.preparingDescription":`Подготовка ZIP-файла, содержащего выбранный сеанс, его подсеансы и вложения.`,"dialog.successTitle":`Загрузка сеанса началась`,"dialog.successDescription":`Браузер загружает ZIP-файл сеанса.`,"dialog.errorTitle":`Экспорт сеанса не удался`,"dialog.close":`Закрыть`,"dialog.commandFailed":`Не удалось начать экспорт сеанса.`};const pt={"menu.copyMarkdown":`Copiar sessão como Markdown`,"menu.download":`Baixar registro da sessão`,"menu.feedback":`Comentários`,"toast.copied":`Sessão copiada como Markdown.`,"toast.preparationFailed":`Não foi possível ler a sessão para cópia. Tente novamente.`,"toast.clipboardFailed":`Não foi possível gravar na área de transferência. Verifique a permissão da área de transferência e tente novamente.`,"dialog.session":`Sessão: {sessionId}`,"dialog.preparingTitle":`Exportando Sessão`,"dialog.preparingDescription":`Preparando um ZIP contendo a sessão selecionada, suas subsessões e anexos.`,"dialog.successTitle":`Download da sessão iniciado`,"dialog.successDescription":`O navegador está baixando o ZIP da sessão.`,"dialog.errorTitle":`Falha na exportação da sessão`,"dialog.close":`Fechar`,"dialog.commandFailed":`Não foi possível iniciar a exportação da sessão.`};const inject=[`slots`,`locale`,`contextMenus`];function apply(ctx){const controller=new SessionLogDownloadController;const copyController=new SessionMarkdownCopyController;ctx.provide(`sessionLogDownload`,controller);ctx.effect(()=>async()=>{await controller.dispose()},`session-log-download: browser download lifecycle`);ctx.effect(()=>async()=>{await copyController.dispose()},`session-log-download: browser Markdown copy lifecycle`);ctx.effect(()=>ctx.locale.register(NS,{zh,en,ja,es,fr,de,ru,pt}),`session-log-download: browser dictionaries`);const feedbackAvailable=(0,_unieai_rabi_client_store.createSnapshotStore)(false);ctx.inject([`feedbackUi`],scope=>{scope.effect(()=>{feedbackAvailable.set(true);return()=>{feedbackAvailable.set(false)}},`session-log-download: feedback availability`)});const t=ctx.locale.bind(NS);ctx.slots.inject(`contextMenu.icon`,function*(){for(const[key,Icon]of Object.entries({"session-log-download.copy":_unieai_rabi_client_ui_primitives.IconCopyOutlineRegular,"session-log-download.download":_unieai_rabi_client_ui_primitives.IconDownloadOutlineRegular,"session-log-download.feedback":_unieai_rabi_client_ui_primitives.IconPaperPlaneOutlineRegular}))yield ctx.slots.register({name:`contextMenu.icon`,key},Icon)});ctx.effect(()=>ctx.contextMenus.register({id:`session-log-download.export`,target:`sessionHeader`,order:100,observe:()=>[controller.store,copyController.store,ctx.locale],resolve:({sessionId})=>[{id:`copy`,label:t(`menu.copyMarkdown`),icon:{key:`session-log-download.copy`},disabled:copyController.store.getSnapshot().copying,run:()=>copyController.copy(sessionId)},{id:`download`,label:t(`menu.download`),icon:{key:`session-log-download.download`},disabled:controller.store.getSnapshot().bySession[sessionId]?.status===`downloading`,run:()=>controller.download(sessionId)}]}),`session-log-download: Header exports`);ctx.effect(()=>ctx.contextMenus.register({id:`session-log-download.feedback`,target:`sessionHeader`,order:600,observe:()=>[feedbackAvailable,ctx.locale],resolve:({sessionId})=>feedbackAvailable.getSnapshot()?[{id:`feedback`,label:t(`menu.feedback`),icon:{key:`session-log-download.feedback`},separatorBefore:true,run:()=>{ctx.get(`feedbackUi`)?.openSession(sessionId)}}]:[]}),`session-log-download: Header feedback`);ctx.on(`command/executed`,(sessionId,commandName,result)=>{if(commandName===`export`&&result.kind===`success`)controller.download(sessionId)});ctx.slots.inject(`shell.overlay`,()=>ctx.slots.register({name:`shell.overlay`,id:`session-log-download.copy-toast`,locale:NS,inject:()=>({hooks:{sessionMarkdownCopy:copyController.store},dismiss:()=>{copyController.dismiss()}})},SessionMarkdownCopyToast));ctx.slots.inject(`shell.overlay`,()=>ctx.slots.register({name:`shell.overlay`,id:`session-log-download`,locale:NS,inject:()=>({hooks:{sessionLogDownload:controller.store},dismiss:sessionId=>{controller.dismiss(sessionId)}})},SessionLogDownloadDialog))}exports.apply=apply;exports.inject=inject;return module.exports}});
|