@aiti-ai/aiti-msg-share 0.1.0 → 0.1.8

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 CHANGED
@@ -34,6 +34,39 @@ Sharing happens only when you say so, and the preview is always editable first.
34
34
 
35
35
  Every entry is a **host slot or extension topic** — this extension registers providers, other extensions render them. No hard-coded buttons.
36
36
 
37
+ ## Save-to (local favourite sinks)
38
+
39
+ Above the network targets the dialog always shows a **Save to** row — the same idea as a mobile
40
+ share sheet, where "Copy" and "Save to…" sit next to the upload targets:
41
+
42
+ | Sink | Provider | Effect |
43
+ | --- | --- | --- |
44
+ | Copy | built in | Copies the content to the clipboard |
45
+ | Save as command | `aiti-cmd` | Adds it to the saved-commands library (one click, editable later) |
46
+ | Save as prompt | `aiti-prompts` | Adds it to the prompt snippet library |
47
+
48
+ Sinks are a **different provider family** from targets: they store locally — no upload, no URL,
49
+ no redaction — and they never appear in the target manager.
50
+
51
+ ### Extension point (topic `share-sink`)
52
+
53
+ ```js
54
+ ctx.registerTopicItem("share-sink", {
55
+ id: "my-ext.thing", // unique
56
+ order: 30, // optional, lower = further left
57
+ label: "Save as thing", // string or () => string
58
+ icon: { svg: "<path .../>" }, // optional 24×24 inner markup
59
+ accepts: (payload) => true, // payload = { kind, text, title, tags, ...original }
60
+ async save(payload) {
61
+ return { ok: true, message: "Saved", action: { label: "Open", run() {} } };
62
+ },
63
+ });
64
+ ```
65
+
66
+ `payload.text` is the **unredacted** body with the page-info stamp removed (local storage is not an upload, and the stamp is sharing metadata — it must never end up inside a saved command). The consumer
67
+ (`aiti-msg-share`) renders the chips, shows the receipt and runs `action.run` on click.
68
+ Providers that are not loaded simply do not appear.
69
+
37
70
  ## Targets
38
71
 
39
72
  161 built-in targets come from [`@aiti-ai/content-share`](https://www.npmjs.com/package/@aiti-ai/content-share):
@@ -14,6 +14,22 @@ const API = (path) => `/api/extensions/aiti-msg-share/${path}`;
14
14
  /** i18n lookup via host ctx.t (extman pattern); {param} interpolation. */
15
15
  let tFn = null;
16
16
  function kindLabel(k) { return shareT("share.kind." + k); }
17
+
18
+ /** Image/binary extension maps — must stay in sync with the server's classifyFile. */
19
+ const IMG_EXT = /\.(png|jpe?g|gif|webp|bmp|svg|ico|avif)$/i;
20
+ const BIN_EXT = /\.(pdf|zip|7z|rar|gz|tgz|tar|bz2|xz|mp3|wav|ogg|flac|mp4|mkv|webm|mov|avi|docx|doc|xlsx|xls|pptx|epub|bin|exe|dmg|iso|apk|psd|woff2?|ttf)$/i;
21
+
22
+ /** Content kind of the pending share: decides which targets are compatible. */
23
+ function contentKind() {
24
+ if (state.kind === "image") return "image";
25
+ if (state.kind === "file" && state.payload?.filePath) {
26
+ const f = state.payload.filePath;
27
+ if (IMG_EXT.test(f)) return "image";
28
+ if (BIN_EXT.test(f)) return "file";
29
+ }
30
+ return "text";
31
+ }
32
+ function supportsKind(t, kind) { return !(t.kinds || []).length || (t.kinds || []).includes(kind); }
17
33
  function shareT(key, params) {
18
34
  if (!tFn) return key;
19
35
  try {
@@ -31,13 +47,27 @@ const state = {
31
47
  targets: [], history: [],
32
48
  payload: null, kind: "message", text: "", rawText: "", baseText: "", title: "", tags: "",
33
49
  // Which page-context fields get prepended to the shared content (multi-select).
34
- stamp: { os: true, browser: true, url: true, sessionId: false, sessionName: false },
50
+ stamp: { os: true, browser: true, url: false, sessionId: true, sessionName: true },
35
51
  targetId: null, meta: {}, redact: true, redactHits: [],
36
52
  result: null, busy: false, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", search: "", probe: [],
37
53
  editing: null, form: {},
54
+ /** Local favourite sinks (share-sink topic): { ok, message, action } of the last run. */
55
+ sinkResult: null, sinkBusy: "",
38
56
  };
39
57
  const listeners = new Set();
40
58
 
59
+ /** Host locale: window.__PI_LOCALE__ is set by the host layout ("en" | "zh-CN"/"zh-*"). */
60
+ function locale() {
61
+ try { return (typeof window !== "undefined" && String(window.__PI_LOCALE__ || "").startsWith("zh")) ? "zh" : "en"; }
62
+ catch { return "en"; }
63
+ }
64
+ /** Bilingual catalog data: note may be a {zh,en} pair (remote overlay) or a plain string. */
65
+ function noteText(note) {
66
+ if (!note) return "";
67
+ if (typeof note === "object") return String(note[locale()] || note.zh || note.en || "").trim();
68
+ return String(note);
69
+ }
70
+
41
71
  function api(path) {
42
72
  // Use the host's apiUrl() (basePath-aware, /dev-safe) when available; fall back
43
73
  // to the absolute extension API path otherwise.
@@ -130,10 +160,12 @@ function btn(label, onClick, opts = {}) {
130
160
  function openShare(payload = {}) {
131
161
  const kind = payload.kind || "message";
132
162
  const raw = payload.text || "";
163
+ primeSinks();
133
164
  set({ open: true, manager: false, payload, kind,
134
165
  text: raw, rawText: raw, baseText: raw, title: payload.title || "",
135
166
  tags: payload.tags || "", targetId: payload.targetId || null,
136
- result: null, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", redact: true, redactHits: [] });
167
+ result: null, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", redact: true, redactHits: [],
168
+ sinkResult: null, sinkBusy: "" });
137
169
  void refresh();
138
170
  // Compose from scratch so the page-info stamp reflects this dialog's context.
139
171
  void refreshPreview();
@@ -157,7 +189,7 @@ function targetCard(target, selected, badge) {
157
189
  const disabled = target.status === "dead" || target.enabled === false;
158
190
  return h("button", { type: "button", key: target.id, disabled,
159
191
  onClick: () => set({ targetId: target.id, error: "" }),
160
- title: target.note || target.name,
192
+ title: noteText(target.note) || target.name,
161
193
  style: { display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 9px",
162
194
  border: "1px solid " + (selected ? "var(--accent, #4d8dff)" : "var(--border, #34363c)"), borderRadius: 8,
163
195
  background: selected ? "rgba(77, 141, 255, 0.15)" : "var(--bg-hover, #25272c)", color: disabled ? "var(--text-muted, #8b909b)" : "var(--text, #d8dade)",
@@ -170,14 +202,131 @@ function targetCard(target, selected, badge) {
170
202
  ? [h("span", { title: shareT(b.key), style: { fontSize: 10 } }, b.icon)] : []; })());
171
203
  }
172
204
 
205
+ /**
206
+ * Local "favourite" sinks — the second, semantically different provider family.
207
+ *
208
+ * Contract (owned here): other extensions publish to the `share-sink` topic:
209
+ * { id, order?, label, icon? { svg }, accepts?(payload), save(payload) → { ok, message?, action?: { label, run } } }
210
+ * Sinks store locally (no upload, no URL, no redaction) — unlike content-share *target*
211
+ * providers, which are upload destinations. payload.text is the UNREDACTED body on purpose.
212
+ *
213
+ * A built-in "copy" sink always exists, mirroring mobile share sheets where copy/save sit
214
+ * next to the network targets.
215
+ */
216
+ /** Fixed sink partners shipped with this product (commands + prompt snippets). Lazy clients
217
+ * register their sink only after materializing, so opening the dialog primes them once;
218
+ * any other provider that happens to be loaded is picked up by the topic read anyway. */
219
+ const SINK_PRIME_EXTS = ["aiti-cmd", "aiti-prompts"];
220
+ let sunkPrimed = false;
221
+ function primeSinks() {
222
+ if (sunkPrimed) return;
223
+ sunkPrimed = true;
224
+ const ensure = ctxRef?.ensureMaterialized;
225
+ if (typeof ensure !== "function") return;
226
+ for (const id of SINK_PRIME_EXTS) {
227
+ try { Promise.resolve(ensure(id)).then(() => emit()).catch(() => {}); } catch (e) { /* ignore */ }
228
+ }
229
+ }
230
+
231
+ function sinkItems() {
232
+ const items = [];
233
+ items.push({
234
+ id: "copy", order: -1000, builtin: true,
235
+ get label() { return shareT("share.sink.copy"); },
236
+ icon: { svg: '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>' },
237
+ run: async () => {
238
+ try { await navigator.clipboard.writeText(state.text); return { ok: true, message: shareT("share.sink.copied") }; }
239
+ catch (e) { return { ok: false, message: String((e && e.message) || e) }; }
240
+ },
241
+ });
242
+ try {
243
+ for (const it of (ctxRef?.getTopicItems?.("share-sink") || [])) if (it && it.id) items.push(it);
244
+ } catch (e) { /* topic registry absent (old host) — copy only */ }
245
+ return items.sort((a, b) => (Number(a.order) || 100) - (Number(b.order) || 100));
246
+ }
247
+
248
+ /** Strip the "page info" stamp block (leading `> **Label**: value` lines) from a body. */
249
+ function stripStamp(text) {
250
+ const lines = String(text || "").split("\n");
251
+ let i = 0;
252
+ while (i < lines.length && /^>\s*\*\*[^*]+\*\*\s*:/.test(lines[i])) i++;
253
+ return lines.slice(i).join("\n").trim();
254
+ }
255
+
256
+ /** Sink payload: original body (unredacted, page-info stamp removed) + share metadata. */
257
+ function sinkPayload() {
258
+ // baseText is the unredacted body; when it is empty the textarea content is the only source
259
+ // (e.g. a session share fills the body server-side, so the preview holds the stamp only).
260
+ // Either way the stamp is metadata for external sharing — never part of a local favourite.
261
+ const raw = (typeof state.baseText === "string" && state.baseText.length) ? state.baseText : state.text;
262
+ return { ...(state.payload || {}), kind: state.kind, text: stripStamp(raw), title: state.title, tags: state.tags };
263
+ }
264
+
265
+ async function runSink(item) {
266
+ if (state.sinkBusy) return;
267
+ const payload = sinkPayload();
268
+ if (!item.builtin && typeof item.accepts === "function") {
269
+ let ok = false;
270
+ try { ok = !!item.accepts(payload); } catch (e) { ok = false; }
271
+ if (!ok) {
272
+ const empty = !String(payload.text || "").trim();
273
+ set({ sinkResult: { ok: false, message: empty ? shareT("share.sink.empty") : shareT("share.sink.unsupported") } });
274
+ return;
275
+ }
276
+ }
277
+ set({ sinkBusy: item.id, sinkResult: null });
278
+ try {
279
+ const r = item.builtin ? await item.run(payload) : await item.save(payload);
280
+ set({ sinkBusy: "", sinkResult: r || { ok: true } });
281
+ } catch (e) {
282
+ set({ sinkBusy: "", sinkResult: { ok: false, message: String((e && e.message) || e) } });
283
+ }
284
+ }
285
+
286
+ function sinkSection() {
287
+ const items = sinkItems();
288
+ if (!items.length) return null;
289
+ const res = state.sinkResult;
290
+ return h("div", null,
291
+ h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, marginBottom: 5 } }, shareT("share.sinks")),
292
+ h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6 } },
293
+ ...items.map((it) => {
294
+ const label = typeof it.label === "function" ? it.label() : (it.label || it.id);
295
+ const svg = it.icon && it.icon.svg;
296
+ return h("button", {
297
+ type: "button", key: it.id, disabled: !!state.sinkBusy,
298
+ onClick: () => { void runSink(it); },
299
+ title: label,
300
+ style: { display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 9px",
301
+ border: "1px solid var(--border, #34363c)", borderRadius: 8,
302
+ background: "var(--bg-hover, #25272c)", color: "var(--text, #d8dade)",
303
+ fontSize: 12, cursor: state.sinkBusy ? "default" : "pointer", opacity: state.sinkBusy && state.sinkBusy !== it.id ? 0.55 : 1 },
304
+ },
305
+ svg ? h("span", { style: { display: "inline-flex" }, dangerouslySetInnerHTML: { __html: `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${svg}</svg>` } }) : null,
306
+ label,
307
+ state.sinkBusy === it.id ? h("span", { style: { fontSize: 10, opacity: 0.7 } }, "…") : null,
308
+ );
309
+ })),
310
+ res ? h("div", { style: { marginTop: 6, fontSize: 11, display: "flex", alignItems: "center", gap: 8,
311
+ color: res.ok ? "var(--ok, #4ade80)" : "#e05d5d", wordBreak: "break-word" } },
312
+ h("span", null, (res.ok ? "✓ " : "⚠ ") + (res.message || (res.ok ? shareT("share.sink.saved") : ""))),
313
+ res.ok && res.action && typeof res.action.run === "function"
314
+ ? h("button", { type: "button", onClick: () => { try { res.action.run(); } catch (e) {} },
315
+ style: { border: "1px solid var(--accent, #4d8dff)", background: "none", color: "var(--accent, #4d8dff)",
316
+ borderRadius: 6, padding: "1px 8px", fontSize: 11, cursor: "pointer" } }, res.action.label || "→")
317
+ : null) : null);
318
+ }
319
+
173
320
  function targetSection() {
174
321
  const recent = recentGet();
322
+ const kind = contentKind();
323
+ const compat = (x) => supportsKind(x, kind);
175
324
  const t = state.targets;
176
325
  const byId = new Map(t.map((x) => [x.id, x]));
177
- const recentItems = recent.map((id) => byId.get(id)).filter(Boolean).slice(0, 5);
326
+ const recentItems = recent.map((id) => byId.get(id)).filter(Boolean).filter(compat).slice(0, 5);
178
327
  // Targets the user has configured (saved) are always visible here.
179
- const mine = t.filter((x) => x.custom && !recent.includes(x.id));
180
- const recs = t.filter((x) => x.recommended && !recent.includes(x.id) && !x.custom).slice(0, 8);
328
+ const mine = t.filter((x) => x.custom && !recent.includes(x.id) && compat(x));
329
+ const recs = t.filter((x) => x.recommended && !recent.includes(x.id) && !x.custom && compat(x)).slice(0, 8);
181
330
  const shown = [];
182
331
  for (const item of recentItems) shown.push(targetCard(item, state.targetId === item.id, "recent"));
183
332
  for (const item of mine) shown.push(targetCard(item, state.targetId === item.id, null));
@@ -187,6 +336,10 @@ function targetSection() {
187
336
  if (sel && !recent.includes(sel.id) && !sel.custom && !sel.recommended) {
188
337
  shown.unshift(targetCard(sel, true, null));
189
338
  }
339
+ if (!recentItems.length && !mine.length && !recs.length) {
340
+ shown.push(h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, padding: "4px 2px" } },
341
+ shareT("share.noCompatible", { kind: kindLabel(kind) })));
342
+ }
190
343
  shown.push(h("button", { type: "button", onClick: () => set({ manager: true }),
191
344
  style: { border: "1px dashed var(--border, #34363c)", background: "none", color: "var(--text-muted, #8b909b)",
192
345
  borderRadius: 8, padding: "4px 10px", fontSize: 12, cursor: "pointer" } }, shareT("share.more")));
@@ -214,10 +367,21 @@ function pageInfo() {
214
367
  if (!browser) b(/Version\/([\d.]+).*Safari/, "Safari");
215
368
  const svc = ctxRef?.getExtService?.("pi-web.session");
216
369
  const cur = (() => { try { return svc?.get?.() ?? svc; } catch { return null; } })();
217
- const sessionId = state.payload?.sessionId || cur?.requestedId || cur?.id
370
+ // Verified snapshot summary: name/firstMessage live under `session`, not on the snapshot itself.
371
+ const sum = cur?.session || null;
372
+ // A shared session row (session-manager menu payload) describes its own session and wins
373
+ // over the currently active one.
374
+ const rowSess = state.payload?.session;
375
+ // List title semantics (session-manager sessionTitle): name || first message || id prefix.
376
+ const listTitle = (s) => (s ? (s.name || s.firstMessage || String(s.id || "").slice(0, 12)) : "");
377
+ // Session ID is the raw canonical id, never the display title: row id → snapshot summary id
378
+ // → verified snapshot id → payload id → URL ?session=.
379
+ const sessionId = rowSess?.id || sum?.id || cur?.sessionId
380
+ || state.payload?.sessionId || state.payload?.sessionName
218
381
  || (typeof location !== "undefined" ? new URL(location.href).searchParams.get("session") : "") || "";
219
- const sessionName = cur?.name || state.payload?.sessionName || state.payload?.title
220
- || (typeof document !== "undefined" ? String(document.title || "").replace(/\s*[·|-]\s*Pi Web.*$/i, "").trim() : "");
382
+ // Session name follows the session list title so it stays meaningful even when the
383
+ // session has no explicit name (falls back to first message, then id prefix).
384
+ const sessionName = listTitle(rowSess) || listTitle(sum) || state.payload?.sessionName || "";
221
385
  return { os, browser, url: typeof location !== "undefined" ? location.href : "", sessionId, sessionName };
222
386
  }
223
387
 
@@ -254,7 +418,7 @@ function errorText() {
254
418
  disabled: "share.err.disabled", unknownTarget: "share.err.unknownTarget",
255
419
  noSession: "share.err.noSession", imageFetch: "share.err.imageFetch", endpoint: "share.err.endpoint",
256
420
  badRequest: "share.err.badRequest", badSxcu: "share.err.badSxcu", noProbe: "share.err.noProbe",
257
- forbidden: "share.err.forbidden",
421
+ forbidden: "share.err.forbidden", kind: "share.err.kind",
258
422
  }[code];
259
423
  if (key) return shareT(key, { name, detail });
260
424
  return state.error || shareT("share.err.generic", { detail });
@@ -351,6 +515,21 @@ async function doShare() {
351
515
  // so upload exactly what the user sees; no second redaction on the server.
352
516
  const body = { ...(state.payload || {}), targetId: state.targetId, kind: state.kind,
353
517
  text: state.text, title: state.title, tags: state.tags, redact: false };
518
+ // Images: load in the browser (same-origin /api/... or data: URLs — no CORS,
519
+ // no server-side fetch) and hand the server base64 bytes.
520
+ if (state.kind === "image" && body.imageSrc) {
521
+ const blob = await fetch(body.imageSrc).then((r) => { if (!r.ok) throw new Error("HTTP " + r.status); return r.blob(); })
522
+ .catch((e) => { throw Object.assign(new Error(shareT("share.err.imageFetch", { detail: e?.message || e })), { detail: String(e?.message || e) }); });
523
+ const dataUrl = await new Promise((res, rej) => {
524
+ const fr = new FileReader();
525
+ fr.onload = () => res(String(fr.result));
526
+ fr.onerror = () => rej(new Error("FileReader failed"));
527
+ fr.readAsDataURL(blob);
528
+ });
529
+ body.imageBase64 = dataUrl;
530
+ body.mime = blob.type || "image/png";
531
+ body.filename = body.filename || ("image." + (blob.type.split("/")[1] || "png").replace("jpeg", "jpg"));
532
+ }
354
533
  const r = await getJSON("share", { method: "POST", headers: { "content-type": "application/json" },
355
534
  body: JSON.stringify(body) });
356
535
  recentAdd(state.targetId);
@@ -392,7 +571,7 @@ function shareDialog() {
392
571
  style: { background: "none", border: "none", color: "var(--text-muted, #8b909b)", cursor: "pointer", fontSize: 14 } }, "✕"));
393
572
  const body = h("div", { ref: (el) => { dialogBodyEl = el; },
394
573
  style: { padding: "12px 14px", display: "flex", flexDirection: "column", gap: 12, flex: 1, minHeight: 0, overflowY: "auto" } },
395
- previewSection(), targetSection(),
574
+ previewSection(), sinkSection(), targetSection(),
396
575
  h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9 } },
397
576
  h("input", { value: state.title, placeholder: shareT("share.titleField"), onInput: (e) => set({ title: e.target.value }),
398
577
  style: { background: "var(--bg-hover, #25272c)", border: "1px solid var(--border, #34363c)", color: "var(--text, #d8dade)", borderRadius: 7, padding: "6px 9px", fontSize: 12 } }),
@@ -437,12 +616,15 @@ function managerDialog() {
437
616
  h("span", null, t.status === "dead" ? "💀" : t.category === "archive" ? "📓" : "🔗"),
438
617
  h("div", { style: { flex: 1, minWidth: 0 } },
439
618
  h("div", { style: { fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, t.name || t.id),
440
- h("div", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)" } }, (t.kinds || []).map(kindLabel).join("/") + (t.note ? " · " + t.note : ""))),
619
+ h("div", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)" } }, (t.kinds || []).map(kindLabel).join("/") + (() => { const n = noteText(t.note); return n ? " · " + n : ""; })())),
441
620
  (() => { const b = CFG_BADGE[t.configState]; return b ? h("span", { title: shareT(b.key),
442
621
  style: { color: b.color, fontSize: 9, whiteSpace: "nowrap", flexShrink: 0 } }, b.icon) : null; })(),
443
622
  t.recommended ? h("span", { style: { color: "var(--accent, #4d8dff)", fontSize: 10 } }, "★") : null,
444
623
  // "Use" closes the loop: pick this target for the pending share and return to it.
445
- t.status !== "dead" && t.configState !== "needs-setup"
624
+ !supportsKind(t, contentKind())
625
+ ? h("span", { title: shareT("share.notCompatible", { kind: kindLabel(contentKind()) }),
626
+ style: { color: "var(--text-muted, #8b909b)", fontSize: 9, whiteSpace: "nowrap", flexShrink: 0 } }, "∅")
627
+ : t.status !== "dead" && t.configState !== "needs-setup"
446
628
  ? h("button", { type: "button", title: shareT("share.useTarget"),
447
629
  onClick: (e) => { e.stopPropagation(); chooseTarget(t.id); },
448
630
  style: { border: "1px solid var(--accent, #4d8dff)", background: state.targetId === t.id ? "var(--accent, #4d8dff)" : "none",
@@ -457,7 +639,7 @@ function managerDialog() {
457
639
  const fields = edit?.fields || [];
458
640
  const form = edit ? h("div", { style: { flex: 1, padding: 14, display: "flex", flexDirection: "column", gap: 12, overflowY: "auto" } },
459
641
  h("div", { style: { fontWeight: 600 } }, edit.name || edit.id),
460
- edit.note ? h("div", { style: { fontSize: 11, color: "var(--text-muted, #8b909b)" } }, edit.note) : null,
642
+ (() => { const n = noteText(edit.note); return n ? h("div", { style: { fontSize: 11, color: "var(--text-muted, #8b909b)" } }, n) : null; })(),
461
643
  ...fields.map((f) => {
462
644
  const key = typeof f === "string" ? f : f.key;
463
645
  const label = typeof f === "string" ? f : (f.label || f.key);
@@ -549,12 +731,15 @@ export default function register(ctx) {
549
731
  style: { display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 8px", height: 22,
550
732
  border: "none", background: "none", borderRadius: 5, color: "var(--text-dim, #8b909b)", cursor: "pointer", fontSize: 11 },
551
733
  }, icon("share", 12), label);
552
- ctx.registerItems("userMessageActions", [{ id: "aiti-msg-share-user", render: shareAction(shareT("share.action")) }]);
734
+ // meta.order: 1 pins Share right after the host's built-in Copy button,
735
+ // ahead of unordered slot items (git-trace badge, quote, bookmark — manifest
736
+ // order would otherwise put aiti-git-trace first).
737
+ ctx.registerItems("userMessageActions", [{ id: "aiti-msg-share-user", render: shareAction(shareT("share.action")), meta: { order: 1 } }]);
553
738
  // Assistant messages mount the same share button at both ends (meta.placement):
554
739
  // long replies put one end off-screen, so top (meta row) + bottom carry identical buttons.
555
740
  ctx.registerItems("assistantMessageActions", [
556
- { id: "aiti-msg-share-assistant", render: shareAction(shareT("share.action")) },
557
- { id: "aiti-msg-share-assistant-top", render: shareAction(shareT("share.action")), meta: { placement: "top" } },
741
+ { id: "aiti-msg-share-assistant", render: shareAction(shareT("share.action")), meta: { order: 1 } },
742
+ { id: "aiti-msg-share-assistant-top", render: shareAction(shareT("share.action")), meta: { placement: "top", order: 1 } },
558
743
  ]);
559
744
  // Session row share lives in session-manager's ⋯ more-menu, not as a bare row
560
745
  // button (too many row actions). Registered via that extension's topic contract.
@@ -595,12 +780,15 @@ export default function register(ctx) {
595
780
  session: sess, title: sess?.name || sess?.title || "" }),
596
781
  });
597
782
  // File card's first-row action (file recognition).
783
+ // `order` follows the msg-smart row order: built-in Open = 10, external = 20,
784
+ // Reveal = 30 — so Share sits right after Open and before Reveal.
598
785
  ctx.registerTopicItem("msg-file-action", {
599
786
  id: "aiti-msg-share-file",
600
787
  label: shareT("share.action"),
601
788
  title: shareT("share.fileTip"),
602
789
  icon: SHARE_ICON,
603
790
  type: "share",
791
+ order: 20,
604
792
  match: (abs, isDir) => !isDir,
605
793
  onClick: (abs) => openShare({ kind: "file", filePath: abs, filename: abs.split("/").pop() }),
606
794
  });
@@ -2111,6 +2111,20 @@ var tFn = null;
2111
2111
  function kindLabel(k) {
2112
2112
  return shareT("share.kind." + k);
2113
2113
  }
2114
+ var IMG_EXT = /\.(png|jpe?g|gif|webp|bmp|svg|ico|avif)$/i;
2115
+ var BIN_EXT = /\.(pdf|zip|7z|rar|gz|tgz|tar|bz2|xz|mp3|wav|ogg|flac|mp4|mkv|webm|mov|avi|docx|doc|xlsx|xls|pptx|epub|bin|exe|dmg|iso|apk|psd|woff2?|ttf)$/i;
2116
+ function contentKind() {
2117
+ if (state.kind === "image") return "image";
2118
+ if (state.kind === "file" && state.payload?.filePath) {
2119
+ const f = state.payload.filePath;
2120
+ if (IMG_EXT.test(f)) return "image";
2121
+ if (BIN_EXT.test(f)) return "file";
2122
+ }
2123
+ return "text";
2124
+ }
2125
+ function supportsKind(t, kind) {
2126
+ return !(t.kinds || []).length || (t.kinds || []).includes(kind);
2127
+ }
2114
2128
  function shareT(key, params) {
2115
2129
  if (!tFn) return key;
2116
2130
  try {
@@ -2138,7 +2152,7 @@ var state = {
2138
2152
  title: "",
2139
2153
  tags: "",
2140
2154
  // Which page-context fields get prepended to the shared content (multi-select).
2141
- stamp: { os: true, browser: true, url: true, sessionId: false, sessionName: false },
2155
+ stamp: { os: true, browser: true, url: false, sessionId: true, sessionName: true },
2142
2156
  targetId: null,
2143
2157
  meta: {},
2144
2158
  redact: true,
@@ -2153,9 +2167,24 @@ var state = {
2153
2167
  search: "",
2154
2168
  probe: [],
2155
2169
  editing: null,
2156
- form: {}
2170
+ form: {},
2171
+ /** Local favourite sinks (share-sink topic): { ok, message, action } of the last run. */
2172
+ sinkResult: null,
2173
+ sinkBusy: ""
2157
2174
  };
2158
2175
  var listeners = /* @__PURE__ */ new Set();
2176
+ function locale() {
2177
+ try {
2178
+ return typeof window !== "undefined" && String(window.__PI_LOCALE__ || "").startsWith("zh") ? "zh" : "en";
2179
+ } catch {
2180
+ return "en";
2181
+ }
2182
+ }
2183
+ function noteText(note) {
2184
+ if (!note) return "";
2185
+ if (typeof note === "object") return String(note[locale()] || note.zh || note.en || "").trim();
2186
+ return String(note);
2187
+ }
2159
2188
  function api(path) {
2160
2189
  return apiUrlFn ? apiUrlFn(`/api/extensions/aiti-msg-share/${path}`) : API(path);
2161
2190
  }
@@ -2261,6 +2290,7 @@ function btn(label, onClick, opts = {}) {
2261
2290
  function openShare(payload = {}) {
2262
2291
  const kind = payload.kind || "message";
2263
2292
  const raw = payload.text || "";
2293
+ primeSinks();
2264
2294
  set({
2265
2295
  open: true,
2266
2296
  manager: false,
@@ -2279,7 +2309,9 @@ function openShare(payload = {}) {
2279
2309
  errorTarget: "",
2280
2310
  errorProvider: "",
2281
2311
  redact: true,
2282
- redactHits: []
2312
+ redactHits: [],
2313
+ sinkResult: null,
2314
+ sinkBusy: ""
2283
2315
  });
2284
2316
  void refresh();
2285
2317
  void refreshPreview();
@@ -2316,7 +2348,7 @@ function targetCard(target, selected, badge) {
2316
2348
  key: target.id,
2317
2349
  disabled,
2318
2350
  onClick: () => set({ targetId: target.id, error: "" }),
2319
- title: target.note || target.name,
2351
+ title: noteText(target.note) || target.name,
2320
2352
  style: {
2321
2353
  display: "inline-flex",
2322
2354
  alignItems: "center",
@@ -2344,13 +2376,166 @@ function targetCard(target, selected, badge) {
2344
2376
  })()
2345
2377
  );
2346
2378
  }
2379
+ var SINK_PRIME_EXTS = ["aiti-cmd", "aiti-prompts"];
2380
+ var sunkPrimed = false;
2381
+ function primeSinks() {
2382
+ if (sunkPrimed) return;
2383
+ sunkPrimed = true;
2384
+ const ensure = ctxRef?.ensureMaterialized;
2385
+ if (typeof ensure !== "function") return;
2386
+ for (const id of SINK_PRIME_EXTS) {
2387
+ try {
2388
+ Promise.resolve(ensure(id)).then(() => emit()).catch(() => {
2389
+ });
2390
+ } catch (e) {
2391
+ }
2392
+ }
2393
+ }
2394
+ function sinkItems() {
2395
+ const items = [];
2396
+ items.push({
2397
+ id: "copy",
2398
+ order: -1e3,
2399
+ builtin: true,
2400
+ get label() {
2401
+ return shareT("share.sink.copy");
2402
+ },
2403
+ icon: { svg: '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>' },
2404
+ run: async () => {
2405
+ try {
2406
+ await navigator.clipboard.writeText(state.text);
2407
+ return { ok: true, message: shareT("share.sink.copied") };
2408
+ } catch (e) {
2409
+ return { ok: false, message: String(e && e.message || e) };
2410
+ }
2411
+ }
2412
+ });
2413
+ try {
2414
+ for (const it of ctxRef?.getTopicItems?.("share-sink") || []) if (it && it.id) items.push(it);
2415
+ } catch (e) {
2416
+ }
2417
+ return items.sort((a, b) => (Number(a.order) || 100) - (Number(b.order) || 100));
2418
+ }
2419
+ function stripStamp(text) {
2420
+ const lines = String(text || "").split("\n");
2421
+ let i = 0;
2422
+ while (i < lines.length && /^>\s*\*\*[^*]+\*\*\s*:/.test(lines[i])) i++;
2423
+ return lines.slice(i).join("\n").trim();
2424
+ }
2425
+ function sinkPayload() {
2426
+ const raw = typeof state.baseText === "string" && state.baseText.length ? state.baseText : state.text;
2427
+ return { ...state.payload || {}, kind: state.kind, text: stripStamp(raw), title: state.title, tags: state.tags };
2428
+ }
2429
+ async function runSink(item) {
2430
+ if (state.sinkBusy) return;
2431
+ const payload = sinkPayload();
2432
+ if (!item.builtin && typeof item.accepts === "function") {
2433
+ let ok = false;
2434
+ try {
2435
+ ok = !!item.accepts(payload);
2436
+ } catch (e) {
2437
+ ok = false;
2438
+ }
2439
+ if (!ok) {
2440
+ const empty = !String(payload.text || "").trim();
2441
+ set({ sinkResult: { ok: false, message: empty ? shareT("share.sink.empty") : shareT("share.sink.unsupported") } });
2442
+ return;
2443
+ }
2444
+ }
2445
+ set({ sinkBusy: item.id, sinkResult: null });
2446
+ try {
2447
+ const r = item.builtin ? await item.run(payload) : await item.save(payload);
2448
+ set({ sinkBusy: "", sinkResult: r || { ok: true } });
2449
+ } catch (e) {
2450
+ set({ sinkBusy: "", sinkResult: { ok: false, message: String(e && e.message || e) } });
2451
+ }
2452
+ }
2453
+ function sinkSection() {
2454
+ const items = sinkItems();
2455
+ if (!items.length) return null;
2456
+ const res = state.sinkResult;
2457
+ return h(
2458
+ "div",
2459
+ null,
2460
+ h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, marginBottom: 5 } }, shareT("share.sinks")),
2461
+ h(
2462
+ "div",
2463
+ { style: { display: "flex", flexWrap: "wrap", gap: 6 } },
2464
+ ...items.map((it) => {
2465
+ const label = typeof it.label === "function" ? it.label() : it.label || it.id;
2466
+ const svg = it.icon && it.icon.svg;
2467
+ return h(
2468
+ "button",
2469
+ {
2470
+ type: "button",
2471
+ key: it.id,
2472
+ disabled: !!state.sinkBusy,
2473
+ onClick: () => {
2474
+ void runSink(it);
2475
+ },
2476
+ title: label,
2477
+ style: {
2478
+ display: "inline-flex",
2479
+ alignItems: "center",
2480
+ gap: 5,
2481
+ padding: "4px 9px",
2482
+ border: "1px solid var(--border, #34363c)",
2483
+ borderRadius: 8,
2484
+ background: "var(--bg-hover, #25272c)",
2485
+ color: "var(--text, #d8dade)",
2486
+ fontSize: 12,
2487
+ cursor: state.sinkBusy ? "default" : "pointer",
2488
+ opacity: state.sinkBusy && state.sinkBusy !== it.id ? 0.55 : 1
2489
+ }
2490
+ },
2491
+ svg ? h("span", { style: { display: "inline-flex" }, dangerouslySetInnerHTML: { __html: `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${svg}</svg>` } }) : null,
2492
+ label,
2493
+ state.sinkBusy === it.id ? h("span", { style: { fontSize: 10, opacity: 0.7 } }, "\u2026") : null
2494
+ );
2495
+ })
2496
+ ),
2497
+ res ? h(
2498
+ "div",
2499
+ { style: {
2500
+ marginTop: 6,
2501
+ fontSize: 11,
2502
+ display: "flex",
2503
+ alignItems: "center",
2504
+ gap: 8,
2505
+ color: res.ok ? "var(--ok, #4ade80)" : "#e05d5d",
2506
+ wordBreak: "break-word"
2507
+ } },
2508
+ h("span", null, (res.ok ? "\u2713 " : "\u26A0 ") + (res.message || (res.ok ? shareT("share.sink.saved") : ""))),
2509
+ res.ok && res.action && typeof res.action.run === "function" ? h("button", {
2510
+ type: "button",
2511
+ onClick: () => {
2512
+ try {
2513
+ res.action.run();
2514
+ } catch (e) {
2515
+ }
2516
+ },
2517
+ style: {
2518
+ border: "1px solid var(--accent, #4d8dff)",
2519
+ background: "none",
2520
+ color: "var(--accent, #4d8dff)",
2521
+ borderRadius: 6,
2522
+ padding: "1px 8px",
2523
+ fontSize: 11,
2524
+ cursor: "pointer"
2525
+ }
2526
+ }, res.action.label || "\u2192") : null
2527
+ ) : null
2528
+ );
2529
+ }
2347
2530
  function targetSection() {
2348
2531
  const recent = recentGet();
2532
+ const kind = contentKind();
2533
+ const compat = (x) => supportsKind(x, kind);
2349
2534
  const t = state.targets;
2350
2535
  const byId = new Map(t.map((x) => [x.id, x]));
2351
- const recentItems = recent.map((id) => byId.get(id)).filter(Boolean).slice(0, 5);
2352
- const mine = t.filter((x) => x.custom && !recent.includes(x.id));
2353
- const recs = t.filter((x) => x.recommended && !recent.includes(x.id) && !x.custom).slice(0, 8);
2536
+ const recentItems = recent.map((id) => byId.get(id)).filter(Boolean).filter(compat).slice(0, 5);
2537
+ const mine = t.filter((x) => x.custom && !recent.includes(x.id) && compat(x));
2538
+ const recs = t.filter((x) => x.recommended && !recent.includes(x.id) && !x.custom && compat(x)).slice(0, 8);
2354
2539
  const shown = [];
2355
2540
  for (const item of recentItems) shown.push(targetCard(item, state.targetId === item.id, "recent"));
2356
2541
  for (const item of mine) shown.push(targetCard(item, state.targetId === item.id, null));
@@ -2359,6 +2544,13 @@ function targetSection() {
2359
2544
  if (sel && !recent.includes(sel.id) && !sel.custom && !sel.recommended) {
2360
2545
  shown.unshift(targetCard(sel, true, null));
2361
2546
  }
2547
+ if (!recentItems.length && !mine.length && !recs.length) {
2548
+ shown.push(h(
2549
+ "span",
2550
+ { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, padding: "4px 2px" } },
2551
+ shareT("share.noCompatible", { kind: kindLabel(kind) })
2552
+ ));
2553
+ }
2362
2554
  shown.push(h("button", {
2363
2555
  type: "button",
2364
2556
  onClick: () => set({ manager: true }),
@@ -2406,8 +2598,11 @@ function pageInfo() {
2406
2598
  return null;
2407
2599
  }
2408
2600
  })();
2409
- const sessionId = state.payload?.sessionId || cur?.requestedId || cur?.id || (typeof location !== "undefined" ? new URL(location.href).searchParams.get("session") : "") || "";
2410
- const sessionName = cur?.name || state.payload?.sessionName || state.payload?.title || (typeof document !== "undefined" ? String(document.title || "").replace(/\s*[·|-]\s*Pi Web.*$/i, "").trim() : "");
2601
+ const sum = cur?.session || null;
2602
+ const rowSess = state.payload?.session;
2603
+ const listTitle = (s) => s ? s.name || s.firstMessage || String(s.id || "").slice(0, 12) : "";
2604
+ const sessionId = rowSess?.id || sum?.id || cur?.sessionId || state.payload?.sessionId || state.payload?.sessionName || (typeof location !== "undefined" ? new URL(location.href).searchParams.get("session") : "") || "";
2605
+ const sessionName = listTitle(rowSess) || listTitle(sum) || state.payload?.sessionName || "";
2411
2606
  return { os, browser, url: typeof location !== "undefined" ? location.href : "", sessionId, sessionName };
2412
2607
  }
2413
2608
  var STAMP_LABELS = { os: "share.pi.os", browser: "share.pi.browser", url: "share.pi.url", sessionId: "share.pi.sessionId", sessionName: "share.pi.sessionName" };
@@ -2445,7 +2640,8 @@ function errorText() {
2445
2640
  badRequest: "share.err.badRequest",
2446
2641
  badSxcu: "share.err.badSxcu",
2447
2642
  noProbe: "share.err.noProbe",
2448
- forbidden: "share.err.forbidden"
2643
+ forbidden: "share.err.forbidden",
2644
+ kind: "share.err.kind"
2449
2645
  }[code];
2450
2646
  if (key) return shareT(key, { name, detail });
2451
2647
  return state.error || shareT("share.err.generic", { detail });
@@ -2636,6 +2832,23 @@ async function doShare() {
2636
2832
  tags: state.tags,
2637
2833
  redact: false
2638
2834
  };
2835
+ if (state.kind === "image" && body.imageSrc) {
2836
+ const blob = await fetch(body.imageSrc).then((r2) => {
2837
+ if (!r2.ok) throw new Error("HTTP " + r2.status);
2838
+ return r2.blob();
2839
+ }).catch((e) => {
2840
+ throw Object.assign(new Error(shareT("share.err.imageFetch", { detail: e?.message || e })), { detail: String(e?.message || e) });
2841
+ });
2842
+ const dataUrl = await new Promise((res, rej) => {
2843
+ const fr = new FileReader();
2844
+ fr.onload = () => res(String(fr.result));
2845
+ fr.onerror = () => rej(new Error("FileReader failed"));
2846
+ fr.readAsDataURL(blob);
2847
+ });
2848
+ body.imageBase64 = dataUrl;
2849
+ body.mime = blob.type || "image/png";
2850
+ body.filename = body.filename || "image." + (blob.type.split("/")[1] || "png").replace("jpeg", "jpg");
2851
+ }
2639
2852
  const r = await getJSON("share", {
2640
2853
  method: "POST",
2641
2854
  headers: { "content-type": "application/json" },
@@ -2706,6 +2919,7 @@ function shareDialog() {
2706
2919
  style: { padding: "12px 14px", display: "flex", flexDirection: "column", gap: 12, flex: 1, minHeight: 0, overflowY: "auto" }
2707
2920
  },
2708
2921
  previewSection(),
2922
+ sinkSection(),
2709
2923
  targetSection(),
2710
2924
  h(
2711
2925
  "div",
@@ -2827,7 +3041,10 @@ function managerDialog() {
2827
3041
  "div",
2828
3042
  { style: { flex: 1, minWidth: 0 } },
2829
3043
  h("div", { style: { fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, t.name || t.id),
2830
- h("div", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)" } }, (t.kinds || []).map(kindLabel).join("/") + (t.note ? " \xB7 " + t.note : ""))
3044
+ h("div", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)" } }, (t.kinds || []).map(kindLabel).join("/") + (() => {
3045
+ const n = noteText(t.note);
3046
+ return n ? " \xB7 " + n : "";
3047
+ })())
2831
3048
  ),
2832
3049
  (() => {
2833
3050
  const b = CFG_BADGE[t.configState];
@@ -2838,7 +3055,10 @@ function managerDialog() {
2838
3055
  })(),
2839
3056
  t.recommended ? h("span", { style: { color: "var(--accent, #4d8dff)", fontSize: 10 } }, "\u2605") : null,
2840
3057
  // "Use" closes the loop: pick this target for the pending share and return to it.
2841
- t.status !== "dead" && t.configState !== "needs-setup" ? h("button", {
3058
+ !supportsKind(t, contentKind()) ? h("span", {
3059
+ title: shareT("share.notCompatible", { kind: kindLabel(contentKind()) }),
3060
+ style: { color: "var(--text-muted, #8b909b)", fontSize: 9, whiteSpace: "nowrap", flexShrink: 0 }
3061
+ }, "\u2205") : t.status !== "dead" && t.configState !== "needs-setup" ? h("button", {
2842
3062
  type: "button",
2843
3063
  title: shareT("share.useTarget"),
2844
3064
  onClick: (e) => {
@@ -2880,7 +3100,10 @@ function managerDialog() {
2880
3100
  "div",
2881
3101
  { style: { flex: 1, padding: 14, display: "flex", flexDirection: "column", gap: 12, overflowY: "auto" } },
2882
3102
  h("div", { style: { fontWeight: 600 } }, edit.name || edit.id),
2883
- edit.note ? h("div", { style: { fontSize: 11, color: "var(--text-muted, #8b909b)" } }, edit.note) : null,
3103
+ (() => {
3104
+ const n = noteText(edit.note);
3105
+ return n ? h("div", { style: { fontSize: 11, color: "var(--text-muted, #8b909b)" } }, n) : null;
3106
+ })(),
2884
3107
  ...fields.map((f) => {
2885
3108
  const key = typeof f === "string" ? f : f.key;
2886
3109
  const label = typeof f === "string" ? f : f.label || f.key;
@@ -3058,10 +3281,10 @@ function register(ctx) {
3058
3281
  fontSize: 11
3059
3282
  }
3060
3283
  }, icon("share", 12), label);
3061
- ctx.registerItems("userMessageActions", [{ id: "aiti-msg-share-user", render: shareAction(shareT("share.action")) }]);
3284
+ ctx.registerItems("userMessageActions", [{ id: "aiti-msg-share-user", render: shareAction(shareT("share.action")), meta: { order: 1 } }]);
3062
3285
  ctx.registerItems("assistantMessageActions", [
3063
- { id: "aiti-msg-share-assistant", render: shareAction(shareT("share.action")) },
3064
- { id: "aiti-msg-share-assistant-top", render: shareAction(shareT("share.action")), meta: { placement: "top" } }
3286
+ { id: "aiti-msg-share-assistant", render: shareAction(shareT("share.action")), meta: { order: 1 } },
3287
+ { id: "aiti-msg-share-assistant-top", render: shareAction(shareT("share.action")), meta: { placement: "top", order: 1 } }
3065
3288
  ]);
3066
3289
  ctx.registerItems("commands", [{
3067
3290
  id: "aiti-msg-share.center",
@@ -3103,6 +3326,7 @@ function register(ctx) {
3103
3326
  title: shareT("share.fileTip"),
3104
3327
  icon: SHARE_ICON,
3105
3328
  type: "share",
3329
+ order: 20,
3106
3330
  match: (abs, isDir) => !isDir,
3107
3331
  onClick: (abs) => openShare({ kind: "file", filePath: abs, filename: abs.split("/").pop() })
3108
3332
  });
package/index.ts CHANGED
@@ -7,25 +7,34 @@
7
7
  */
8
8
  import { join, dirname } from "node:path";
9
9
  // @ts-ignore pure JS core shared with tests
10
- import { ShareStore, makeRedactor, publicTarget, exportSessionMarkdown } from "./lib/share-core.mjs";
10
+ import { ShareStore, makeRedactor, publicTarget, exportSessionMarkdown, classifyFile, MAX_SHARE_FILE_BYTES } from "./lib/share-core.mjs";
11
11
 
12
12
  let configDir = "";
13
13
  let stateDir = "";
14
+ let cacheDir = "";
14
15
  let store;
15
16
  let registry = null;
16
17
  let redact = (t) => ({ text: t, hits: [] });
17
18
  let secretEngineReady = false;
18
19
 
20
+ /** Published audit catalog (dead markings + bilingual notes); overridable for tests/dev. */
21
+ const CATALOG_URL = process.env.AITI_SHARE_TARGETS_URL || "https://aiti.pw/share-targets.json";
22
+
19
23
  const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {
20
24
  status,
21
25
  headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
22
26
  });
23
27
 
24
- async function ensureRuntime() {
25
- if (registry) return registry;
28
+ async function ensureRuntime(force = false) {
29
+ if (registry && !force) return registry;
26
30
  const cs = await import("@aiti-ai/content-share");
27
- registry = new cs.Registry();
28
- await registry.init();
31
+ registry = new cs.Registry({
32
+ // Remote overlay: dead markings, bilingual notes and labels from the
33
+ // published audit doc; falls back to the bundled catalog when unreachable.
34
+ url: CATALOG_URL,
35
+ cacheDir: cacheDir || undefined,
36
+ });
37
+ await registry.init(force);
29
38
  const { customProvider } = cs;
30
39
  registry.register(customProvider());
31
40
  // Re-register user-imported .sxcu configs (persisted on the target record) —
@@ -126,6 +135,9 @@ export default {
126
135
  i18n: {
127
136
  "en": {
128
137
  "share.err.forbidden": "That path is outside the allowed roots — only session workspaces can be shared.",
138
+ "share.err.kind": "This target doesn't accept {kind} content ({detail}). Pick a target that supports it.",
139
+ "share.noCompatible": "No targets support {kind} — add one via \"Add more\".",
140
+ "share.notCompatible": "Doesn't accept {kind}",
129
141
  "share.err.endpoint": "「{name}」的 API 端点无响应或不支持该操作({detail})。该服务的 API 可能已变更,请在「管理目标」检查端点配置。",
130
142
  "share.err.network": "Cannot reach 「{name}」 (network unreachable / blocked / service down). Pick another target in Manage targets, or use local-link.",
131
143
  "share.err.timeout": "「{name}」 timed out.",
@@ -158,6 +170,12 @@ export default {
158
170
  "share.openInNewTab": "Open in new tab",
159
171
  "ext.displayName": "Message Share",
160
172
  "share.subtitle": "{kind} · {chars} chars",
173
+ "share.sinks": "Save to",
174
+ "share.sink.copy": "Copy",
175
+ "share.sink.copied": "Copied to clipboard",
176
+ "share.sink.saved": "Saved",
177
+ "share.sink.unsupported": "This content cannot be saved here",
178
+ "share.sink.empty": "Nothing to save — the dialog only carries the page-info header (edit the content or share a message/selection)",
161
179
  "share.targets": "Share targets",
162
180
  "share.more": "Add more…",
163
181
  "share.copy": "Copy link",
@@ -202,6 +220,9 @@ export default {
202
220
  },
203
221
  "zh-CN": {
204
222
  "share.err.forbidden": "该路径不在允许范围内——只能分享会话工作区内的文件。",
223
+ "share.err.kind": "该目标不支持{kind}内容({detail})。请换一个支持该类型的目标。",
224
+ "share.noCompatible": "没有支持{kind}的目标——可在「加更多…」里添加。",
225
+ "share.notCompatible": "不接受{kind}",
205
226
  "share.err.endpoint": "「{name}」的 API 端点无效或已变更({detail})。请在「管理目标」检查端点配置。",
206
227
  "share.err.network": "无法连接「{name}」的服务端(网络不可达 / 被拦截 / 服务宕机)。可在「管理目标」换一个服务,或用 local-link。",
207
228
  "share.err.timeout": "「{name}」响应超时。",
@@ -234,6 +255,12 @@ export default {
234
255
  "share.openInNewTab": "在新窗口打开",
235
256
  "ext.displayName": "消息分享",
236
257
  "share.subtitle": "{kind} · {chars} 字符",
258
+ "share.sinks": "收藏",
259
+ "share.sink.copy": "复制",
260
+ "share.sink.copied": "已复制到剪贴板",
261
+ "share.sink.saved": "已保存",
262
+ "share.sink.unsupported": "该内容不能收藏到这里",
263
+ "share.sink.empty": "没有可收藏的正文——当前只有页信息头(可先编辑正文,或改分享消息/选区)",
237
264
  "share.targets": "分享目标",
238
265
  "share.more": "加更多…",
239
266
  "share.copy": "复制链接",
@@ -278,6 +305,9 @@ export default {
278
305
  },
279
306
  "zh-TW": {
280
307
  "share.err.forbidden": "該路徑不在允許範圍內——只能分享工作階段工作區內的檔案。",
308
+ "share.err.kind": "該目標不支援{kind}內容({detail})。請換一個支援該類型的目標。",
309
+ "share.noCompatible": "沒有支援{kind}的目標——可在「加更多…」裡添加。",
310
+ "share.notCompatible": "不接受{kind}",
281
311
  "share.err.endpoint": "「{name}」的 API 端點無效或已變更({detail})。請在「管理目標」檢查端點設定。",
282
312
  "share.err.network": "無法連線「{name}」的伺服端(網路不可達 / 被封鎖 / 服務當機)。可在「管理目標」換一個服務,或用 local-link。",
283
313
  "share.err.timeout": "「{name}」回應逾時。",
@@ -310,6 +340,12 @@ export default {
310
340
  "share.openInNewTab": "在新視窗開啟",
311
341
  "ext.displayName": "訊息分享",
312
342
  "share.subtitle": "{kind} · {chars} 字元",
343
+ "share.sinks": "收藏",
344
+ "share.sink.copy": "複製",
345
+ "share.sink.copied": "已複製到剪貼簿",
346
+ "share.sink.saved": "已儲存",
347
+ "share.sink.unsupported": "此內容無法收藏到這裡",
348
+ "share.sink.empty": "沒有可收藏的正文——目前只有頁資訊標頭(可先編輯正文,或改分享訊息/選取區)",
313
349
  "share.targets": "分享目標",
314
350
  "share.more": "加更多…",
315
351
  "share.copy": "複製連結",
@@ -367,11 +403,18 @@ export default {
367
403
  if (!configDir) {
368
404
  configDir = ctx.configDir || "";
369
405
  stateDir = ctx.stateDir || join(dirname(configDir), "state", "aiti-msg-share");
406
+ cacheDir = ctx.cacheDir || join(dirname(configDir), "cache", "aiti-msg-share");
370
407
  store = new ShareStore(configDir, stateDir);
371
408
  }
372
409
  const reg = await ensureRuntime();
373
410
  await ensureSecretEngine();
374
411
 
412
+ // POST /refresh — force-reload the remote catalog overlay (bypasses TTL).
413
+ if (p[0] === "refresh" && req.method === "POST") {
414
+ const fresh = await ensureRuntime(true);
415
+ return json({ ok: true, count: fresh.catalog().length });
416
+ }
417
+
375
418
  // GET /catalog — all targets + metadata
376
419
  if (p[0] === "catalog" && req.method === "GET") {
377
420
  return json({ ok: true, targets: allTargets(reg), count: reg.catalog().length });
@@ -436,17 +479,29 @@ export default {
436
479
  const text = body.rawText || exportSessionMarkdown(session, { full: !!body.full, title: meta.title,
437
480
  tags: String(meta.tags).split(",").map((s) => s.trim()).filter(Boolean) });
438
481
  content = { text };
439
- } else if (body.imageSrc) {
440
- // Same-origin only: image previews are served by pi-web itself
441
- // (`/api/sessions/.../tool-result-image`). Blocks SSRF to arbitrary hosts.
442
- const url = new URL(body.imageSrc, "http://localhost");
443
- const sameOrigin = url.host === "localhost" || url.host === (typeof location !== "undefined" ? location.host : "")
444
- || url.hostname === "127.0.0.1";
445
- if (!sameOrigin) return json({ ok: false, errorCode: "badRequest",
446
- error: "imageSrc must be a pi-web relative path or 127.0.0.1 URL", detail: url.host }, 400);
447
- const r = await fetch(url);
448
- if (!r.ok) return json({ ok: false, error: `image fetch ${r.status}`, errorCode: "imageFetch", detail: String(r.status) }, 502);
449
- content = { buffer: new Uint8Array(await r.arrayBuffer()), filename: body.filename || "image.png", mime: r.headers.get("content-type") || "image/png" };
482
+ } else if (body.imageBase64 || body.imageSrc) {
483
+ // Preferred path: the browser already loaded the image (same-origin or
484
+ // data: URL) and sends base64 — no server-side fetch, no CORS, works for
485
+ // pasted data: URLs too.
486
+ if (body.imageBase64) {
487
+ const m = /^data:([^;,]+)?(;base64)?,([\s\S]*)$/.exec(String(body.imageBase64));
488
+ const b64 = (m ? m[3] : String(body.imageBase64)).trim();
489
+ if (!b64) return json({ ok: false, errorCode: "badRequest", error: "empty image payload" }, 400);
490
+ const mime = (m?.[1] || body.mime || "image/png").split(";")[0];
491
+ content = { buffer: Buffer.from(b64, "base64"), filename: body.filename || "image.png", mime };
492
+ } else {
493
+ // Fallback: relative /api/... paths resolved against THIS request's
494
+ // origin (the old "http://localhost" base hit port 80 / nginx → 404).
495
+ // Same-origin only: image previews are served by pi-web itself; blocks SSRF.
496
+ const origin = new URL(req.url).origin;
497
+ const url = new URL(String(body.imageSrc), origin);
498
+ const sameOrigin = url.origin === origin || url.hostname === "127.0.0.1" || url.hostname === "localhost";
499
+ if (!sameOrigin) return json({ ok: false, errorCode: "badRequest",
500
+ error: "imageSrc must be a pi-web relative path or same-origin URL", detail: url.host }, 400);
501
+ const r = await fetch(url);
502
+ if (!r.ok) return json({ ok: false, error: `image fetch ${r.status}`, errorCode: "imageFetch", detail: String(r.status) }, 502);
503
+ content = { buffer: Buffer.from(await r.arrayBuffer()), filename: body.filename || "image.png", mime: r.headers.get("content-type") || "image/png" };
504
+ }
450
505
  } else if (body.filePath) {
451
506
  // Respect pi-web allowed-roots (session cwds): never read arbitrary
452
507
  // server files on behalf of the caller.
@@ -457,13 +512,17 @@ export default {
457
512
  if (!allowed) return json({ ok: false, errorCode: "forbidden",
458
513
  error: "path is outside the allowed roots", detail: body.filePath }, 403);
459
514
  }
460
- const { readFile } = await import("node:fs/promises");
515
+ const { readFile, stat } = await import("node:fs/promises");
516
+ const st = await stat(body.filePath).catch(() => null);
517
+ if (!st?.isFile()) return json({ ok: false, errorCode: "badRequest", error: "file not found", detail: body.filePath }, 400);
518
+ if (st.size > MAX_SHARE_FILE_BYTES) return json({ ok: false, errorCode: "tooLarge",
519
+ error: `file too large: ${st.size} bytes`, detail: String(st.size) }, 413);
520
+ const name = body.filename || body.filePath.split("/").pop() || "file";
521
+ const cls = classifyFile(name);
461
522
  const buffer = await readFile(body.filePath);
462
- const ext = body.filePath.split(".").pop()?.toLowerCase() || "txt";
463
- const mime = ext === "png" ? "image/png" : ext === "jpg" || ext === "jpeg" ? "image/jpeg" : "text/plain";
464
- content = ext === "png" || ext === "jpg" || ext === "jpeg"
465
- ? { buffer, filename: body.filename || body.filePath.split("/").pop(), mime }
466
- : { text: buffer.toString("utf8"), filename: body.filename || body.filePath.split("/").pop() };
523
+ content = cls.kind === "text"
524
+ ? { text: buffer.toString("utf8"), filename: name }
525
+ : { buffer, filename: name, mime: cls.mime };
467
526
  } else {
468
527
  content = { text: body.text || "" };
469
528
  }
@@ -471,6 +530,15 @@ export default {
471
530
  const doRedact = body.redact !== false && "text" in content;
472
531
  const hooks = doRedact ? { transformText: redact } : undefined;
473
532
  const cs = await import("@aiti-ai/content-share");
533
+ // Kind guard (defense in depth — the pipeline checks too): an image buffer
534
+ // to a text-only target would silently produce garbage on the service.
535
+ const contentKind = "text" in content ? "text" : /^image\//i.test(content.mime) ? "image" : "file";
536
+ const kinds = (provider as any).kinds || [];
537
+ if (kinds.length && !kinds.includes(contentKind)) {
538
+ return json({ ok: false, errorCode: "kind", errorTarget: target.id, providerLabel: (provider as any).label,
539
+ error: `kind mismatch: ${contentKind} not in [${kinds.join("/")}]`,
540
+ detail: `${(provider as any).label} accepts: ${kinds.join(", ")}` }, 400);
541
+ }
474
542
  let result;
475
543
  try {
476
544
  result = await cs.share(provider, content,
@@ -10,6 +10,34 @@ import { join, dirname } from "node:path";
10
10
 
11
11
  const HISTORY_MAX = 200;
12
12
 
13
+ /** Files above this size are rejected before reading (provider limits are checked later). */
14
+ export const MAX_SHARE_FILE_BYTES = 200 * 1024 * 1024;
15
+
16
+ const IMAGE_MIME = {
17
+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif",
18
+ webp: "image/webp", bmp: "image/bmp", svg: "image/svg+xml", ico: "image/x-icon", avif: "image/avif",
19
+ };
20
+ const TEXT_EXT = new Set([
21
+ "txt", "md", "markdown", "json", "js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "rb", "go", "rs", "java",
22
+ "c", "h", "cpp", "hpp", "cs", "php", "sh", "bash", "zsh", "yml", "yaml", "toml", "ini", "cfg", "conf",
23
+ "csv", "tsv", "log", "html", "htm", "css", "scss", "xml", "sql", "env", "properties", "gradle", "vim",
24
+ "dockerfile", "makefile", "gitignore", "license",
25
+ ]);
26
+
27
+ /**
28
+ * Classify a shared file: image (binary, image/* mime), text (decoded as utf8),
29
+ * or binary (byte-exact buffer, application/octet-stream). Mirrors the client's
30
+ * kind filter so both ends agree on what the content is.
31
+ */
32
+ export function classifyFile(filename) {
33
+ const ext = String(filename || "").split(".").pop()?.toLowerCase() || "";
34
+ if (IMAGE_MIME[ext]) return { kind: "image", mime: IMAGE_MIME[ext] };
35
+ if (TEXT_EXT.has(ext)) return { kind: "text", mime: "text/plain" };
36
+ // Executables/scripts without extension sometimes carry a shebang — still treat
37
+ // unknown types as binary: byte-exact upload never corrupts, utf8 decode can.
38
+ return { kind: "binary", mime: "application/octet-stream" };
39
+ }
40
+
13
41
  /** Mask a secret for display: keep first 2 / last 4 chars only. */
14
42
  export function maskSecret(value) {
15
43
  if (!value || typeof value !== "string") return "";
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@aiti-ai/aiti-msg-share",
3
- "version": "0.1.0",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "description": "Share sessions, messages, selections, files and images through pluggable targets with secret redaction and QR codes",
6
6
  "license": "MIT",
7
7
  "aitiExtProtocol": "1.0",
8
8
  "soul": "分享出去,是为了让对话继续。",
9
9
  "dependencies": {
10
- "@aiti-ai/content-share": "^0.1.4",
10
+ "@aiti-ai/content-share": "^0.1.11",
11
11
  "@aiti-ai/secret-mask-core": "^0.1.0",
12
12
  "qrcode": "^1.5.4"
13
13
  },
@@ -27,5 +27,5 @@
27
27
  "bugs": {
28
28
  "url": "https://github.com/aiti-ai/aiti-ai/issues"
29
29
  },
30
- "contentHash": "b48cb29d594d7e75"
30
+ "contentHash": "603e2fa84e7f66a0"
31
31
  }
@@ -48,3 +48,14 @@ test("exportSessionMarkdown: role headers + folded tool output", () => {
48
48
  assert.ok(md.includes("## User\n\nhello"));
49
49
  assert.ok(md.includes("folded"));
50
50
  });
51
+
52
+ test("classifyFile: image / text / binary by extension", async () => {
53
+ const { classifyFile } = await import("../lib/share-core.mjs");
54
+ assert.deepEqual(classifyFile("shot.png"), { kind: "image", mime: "image/png" });
55
+ assert.deepEqual(classifyFile("photo.JPG"), { kind: "image", mime: "image/jpeg" });
56
+ assert.deepEqual(classifyFile("notes.md"), { kind: "text", mime: "text/plain" });
57
+ assert.deepEqual(classifyFile("data.json"), { kind: "text", mime: "text/plain" });
58
+ assert.deepEqual(classifyFile("report.pdf"), { kind: "binary", mime: "application/octet-stream" });
59
+ assert.deepEqual(classifyFile("archive.tar.gz"), { kind: "binary", mime: "application/octet-stream" });
60
+ assert.deepEqual(classifyFile("noext"), { kind: "binary", mime: "application/octet-stream" });
61
+ });