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

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.
@@ -14,6 +14,34 @@ 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); }
33
+ /** Mirror of the engine's {{title}} fallback: first meaningful line of the raw
34
+ * text (skips the page-info stamp block and markdown decoration) — prefills the
35
+ * title input so the user sees and can edit what will be sent. */
36
+ function deriveTitleLocal(text) {
37
+ for (const raw of String(text || "").split("\n")) {
38
+ const line = raw.trim();
39
+ if (!line || /^>\s*\*\*[^*]+\*\*\s*:/.test(line)) continue;
40
+ const stripped = line.replace(/^#{1,6}\s+/, "").replace(/[*_`]+/g, "").trim();
41
+ if (stripped) return stripped.length > 80 ? stripped.slice(0, 80).trim() : stripped;
42
+ }
43
+ return "";
44
+ }
17
45
  function shareT(key, params) {
18
46
  if (!tFn) return key;
19
47
  try {
@@ -31,13 +59,33 @@ const state = {
31
59
  targets: [], history: [],
32
60
  payload: null, kind: "message", text: "", rawText: "", baseText: "", title: "", tags: "",
33
61
  // Which page-context fields get prepended to the shared content (multi-select).
34
- stamp: { os: true, browser: true, url: true, sessionId: false, sessionName: false },
62
+ stamp: { os: true, browser: true, url: false, sessionId: true, sessionName: true },
35
63
  targetId: null, meta: {}, redact: true, redactHits: [],
36
64
  result: null, busy: false, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", search: "", probe: [],
37
65
  editing: null, form: {},
66
+ /** Container picker (notebook/folder selection): per-target cache + pending pick.
67
+ * containersByTarget[id] = { containers: [{id,label,parent,path}], label } */
68
+ containersByTarget: {}, containerFor: "", containerOpen: false, containerFilter: "",
69
+ containerExpanded: {}, containersLoading: false, containerError: "",
70
+ /** Keyboard navigation index over the currently visible picker rows (-1 = none). */
71
+ kbIndex: -1,
72
+ /** Local favourite sinks (share-sink topic): { ok, message, action } of the last run. */
73
+ sinkResult: null, sinkBusy: "",
38
74
  };
39
75
  const listeners = new Set();
40
76
 
77
+ /** Host locale: window.__PI_LOCALE__ is set by the host layout ("en" | "zh-CN"/"zh-*"). */
78
+ function locale() {
79
+ try { return (typeof window !== "undefined" && String(window.__PI_LOCALE__ || "").startsWith("zh")) ? "zh" : "en"; }
80
+ catch { return "en"; }
81
+ }
82
+ /** Bilingual catalog data: note may be a {zh,en} pair (remote overlay) or a plain string. */
83
+ function noteText(note) {
84
+ if (!note) return "";
85
+ if (typeof note === "object") return String(note[locale()] || note.zh || note.en || "").trim();
86
+ return String(note);
87
+ }
88
+
41
89
  function api(path) {
42
90
  // Use the host's apiUrl() (basePath-aware, /dev-safe) when available; fall back
43
91
  // to the absolute extension API path otherwise.
@@ -79,10 +127,78 @@ function set(partial) { Object.assign(state, partial); emit(); }
79
127
  /** Pick a target for the pending share and return to the share dialog. */
80
128
  function chooseTarget(id) {
81
129
  recentAdd(id);
82
- set({ targetId: id, manager: false, editing: null, error: "", errorDetail: "" });
130
+ set({ targetId: id, manager: false, editing: null, error: "", errorDetail: "", containerOpen: false, containerFilter: "" });
131
+ syncContainerFor(id);
132
+ void ensureContainers(id);
83
133
  }
84
134
  function emit() { listeners.forEach((fn) => fn()); }
85
135
 
136
+ // ---------------------------------------------------------------------------
137
+ // Container selection (Joplin notebooks, Obsidian dirs, …): a tree picker with
138
+ // last-selection memory. The pick is recorded server-side immediately so
139
+ // headless/AI shares land in the same notebook. No polling — fetch on demand.
140
+
141
+ /** Selection follows the target's recorded last pick when the target switches. */
142
+ function syncContainerFor(id) {
143
+ const t = state.targets.find((x) => x.id === id);
144
+ set({ containerFor: t?.lastContainer || "" });
145
+ }
146
+
147
+ /** Fetch the container list for a target (cached per session; force bypasses). */
148
+ async function ensureContainers(targetId, force = false) {
149
+ const t = state.targets.find((x) => x.id === targetId);
150
+ if (!t || !t.supportsContainers) return;
151
+ if (state.containersByTarget[targetId] && !force) return;
152
+ set({ containersLoading: true, containerError: "" });
153
+ try {
154
+ const r = await getJSON("containers", { method: "POST", headers: { "content-type": "application/json" },
155
+ body: JSON.stringify({ targetId }) });
156
+ set({ containersLoading: false,
157
+ containersByTarget: { ...state.containersByTarget,
158
+ [targetId]: { containers: r.containers || [], label: r.containerLabel || null } } });
159
+ } catch (e) { set({ containersLoading: false, containerError: e.message }); }
160
+ }
161
+
162
+ /** Open/close the picker panel; expands the selection's ancestor chain by default. */
163
+ function toggleContainerPanel() {
164
+ if (state.containerOpen) { set({ containerOpen: false, containerFilter: "" }); return; }
165
+ const items = state.containersByTarget[state.targetId]?.containers || [];
166
+ const expanded = {};
167
+ // One visible level below the roots by default (children keep their own names),
168
+ // plus the full ancestor chain of the current selection.
169
+ for (const c of items) if (!c.parent) expanded[c.id] = true;
170
+ const byId = new Map(items.map((c) => [c.id, c]));
171
+ let cur = byId.get(state.containerFor);
172
+ while (cur?.parent) { expanded[cur.parent] = true; cur = byId.get(cur.parent); }
173
+ set({ containerOpen: true, containerFilter: "", containerExpanded: expanded, kbIndex: -1 });
174
+ }
175
+
176
+ /** Record the pick immediately (even the explicit "service default" pick). */
177
+ function pickContainer(c) {
178
+ const id = c ? c.id : "";
179
+ const pathLabel = c ? (c.path || c.label) : "";
180
+ set({ containerFor: id, containerOpen: false, containerFilter: "", kbIndex: -1 });
181
+ void getJSON("targets/last-container", { method: "POST", headers: { "content-type": "application/json" },
182
+ body: JSON.stringify({ id: state.targetId, container: id, label: pathLabel }) })
183
+ .then((r) => set({ targets: state.targets.map((x) => x.id === state.targetId && r?.target
184
+ ? { ...x, lastContainer: r.target.lastContainer, lastContainerLabel: r.target.lastContainerLabel,
185
+ recentContainers: r.target.recentContainers } : x) }))
186
+ .catch(() => {});
187
+ }
188
+
189
+ /** parent→children map for tree rendering; orphans without a resolvable parent fall back to root. */
190
+ function containerTree(items) {
191
+ const ids = new Set(items.map((c) => c.id));
192
+ const childrenOf = new Map();
193
+ for (const c of items) {
194
+ const k = (c.parent && ids.has(c.parent)) ? c.parent : "";
195
+ if (!childrenOf.has(k)) childrenOf.set(k, []);
196
+ childrenOf.get(k).push(c);
197
+ }
198
+ for (const arr of childrenOf.values()) arr.sort((a, b) => String(a.label).localeCompare(String(b.label)));
199
+ return childrenOf;
200
+ }
201
+
86
202
  // Content-kind labels resolved via shareT() at render time; status uses icons only.
87
203
  const STATUS_ICONS = { recent: "🕘", recommended: "★", dead: "⚠", legacy: "⚠" };
88
204
  const CFG_BADGE = {
@@ -90,6 +206,7 @@ const CFG_BADGE = {
90
206
  ready: { icon: "✓", key: "share.cfg.ready", color: "var(--accent, #4d8dff)" },
91
207
  "needs-setup": { icon: "🟠", key: "share.cfg.needs", color: "#d9a13c" },
92
208
  dead: { icon: "💀", key: "share.cfg.dead", color: "var(--text-muted, #8b909b)" },
209
+ legacy: { icon: "⚠", key: "share.cfg.legacy", color: "#d9a13c" },
93
210
  };
94
211
 
95
212
  const ICONS = {
@@ -130,10 +247,12 @@ function btn(label, onClick, opts = {}) {
130
247
  function openShare(payload = {}) {
131
248
  const kind = payload.kind || "message";
132
249
  const raw = payload.text || "";
250
+ primeSinks();
133
251
  set({ open: true, manager: false, payload, kind,
134
- text: raw, rawText: raw, baseText: raw, title: payload.title || "",
252
+ text: raw, rawText: raw, baseText: raw, title: payload.title || deriveTitleLocal(raw),
135
253
  tags: payload.tags || "", targetId: payload.targetId || null,
136
- result: null, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", redact: true, redactHits: [] });
254
+ result: null, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", redact: true, redactHits: [],
255
+ sinkResult: null, sinkBusy: "" });
137
256
  void refresh();
138
257
  // Compose from scratch so the page-info stamp reflects this dialog's context.
139
258
  void refreshPreview();
@@ -149,20 +268,26 @@ async function refresh(force = false) {
149
268
  const targets = catalog.targets || [];
150
269
  set({ targets, history: history.items || [], probe: probe.services || [], loading: false,
151
270
  targetId: state.targetId || targets.find((t) => t.recommended)?.id || targets[0]?.id });
271
+ syncContainerFor(state.targetId);
272
+ void ensureContainers(state.targetId);
152
273
  if (force) await getJSON("refresh", { method: "POST" }).catch(() => {});
153
274
  } catch (e) { set({ loading: false, error: e.message, errorDetail: e.detail || "catalog/history" }); }
154
275
  }
155
276
 
156
277
  function targetCard(target, selected, badge) {
157
- const disabled = target.status === "dead" || target.enabled === false;
278
+ const disabled = target.status === "dead" || target.status === "legacy" || target.enabled === false;
158
279
  return h("button", { type: "button", key: target.id, disabled,
159
- onClick: () => set({ targetId: target.id, error: "" }),
160
- title: target.note || target.name,
280
+ onClick: () => { set({ targetId: target.id, error: "", containerOpen: false, containerFilter: "" });
281
+ syncContainerFor(target.id); void ensureContainers(target.id); },
282
+ title: noteText(target.note) || target.name,
161
283
  style: { display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 9px",
162
284
  border: "1px solid " + (selected ? "var(--accent, #4d8dff)" : "var(--border, #34363c)"), borderRadius: 8,
163
285
  background: selected ? "rgba(77, 141, 255, 0.15)" : "var(--bg-hover, #25272c)", color: disabled ? "var(--text-muted, #8b909b)" : "var(--text, #d8dade)",
164
286
  fontSize: 12, cursor: "pointer", opacity: disabled ? 0.45 : 1 } },
165
- h("span", null, STATUS_ICONS[badge] || "🔗"),
287
+ h("span", null, target.icon || STATUS_ICONS[badge] || "🔗"),
288
+ // Provider glyph first; the source marker (recent/recommended) stays as a small secondary hint.
289
+ ...(target.icon && STATUS_ICONS[badge]
290
+ ? [h("span", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)" } }, STATUS_ICONS[badge])] : []),
166
291
  target.name || target.id,
167
292
  ...(target.kinds?.length ? [h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 10 } },
168
293
  target.kinds.map(kindLabel).join("/"))] : []),
@@ -170,14 +295,131 @@ function targetCard(target, selected, badge) {
170
295
  ? [h("span", { title: shareT(b.key), style: { fontSize: 10 } }, b.icon)] : []; })());
171
296
  }
172
297
 
298
+ /**
299
+ * Local "favourite" sinks — the second, semantically different provider family.
300
+ *
301
+ * Contract (owned here): other extensions publish to the `share-sink` topic:
302
+ * { id, order?, label, icon? { svg }, accepts?(payload), save(payload) → { ok, message?, action?: { label, run } } }
303
+ * Sinks store locally (no upload, no URL, no redaction) — unlike content-share *target*
304
+ * providers, which are upload destinations. payload.text is the UNREDACTED body on purpose.
305
+ *
306
+ * A built-in "copy" sink always exists, mirroring mobile share sheets where copy/save sit
307
+ * next to the network targets.
308
+ */
309
+ /** Fixed sink partners shipped with this product (commands + prompt snippets). Lazy clients
310
+ * register their sink only after materializing, so opening the dialog primes them once;
311
+ * any other provider that happens to be loaded is picked up by the topic read anyway. */
312
+ const SINK_PRIME_EXTS = ["aiti-cmd", "aiti-prompts"];
313
+ let sunkPrimed = false;
314
+ function primeSinks() {
315
+ if (sunkPrimed) return;
316
+ sunkPrimed = true;
317
+ const ensure = ctxRef?.ensureMaterialized;
318
+ if (typeof ensure !== "function") return;
319
+ for (const id of SINK_PRIME_EXTS) {
320
+ try { Promise.resolve(ensure(id)).then(() => emit()).catch(() => {}); } catch (e) { /* ignore */ }
321
+ }
322
+ }
323
+
324
+ function sinkItems() {
325
+ const items = [];
326
+ items.push({
327
+ id: "copy", order: -1000, builtin: true,
328
+ get label() { return shareT("share.sink.copy"); },
329
+ 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"/>' },
330
+ run: async () => {
331
+ try { await navigator.clipboard.writeText(state.text); return { ok: true, message: shareT("share.sink.copied") }; }
332
+ catch (e) { return { ok: false, message: String((e && e.message) || e) }; }
333
+ },
334
+ });
335
+ try {
336
+ for (const it of (ctxRef?.getTopicItems?.("share-sink") || [])) if (it && it.id) items.push(it);
337
+ } catch (e) { /* topic registry absent (old host) — copy only */ }
338
+ return items.sort((a, b) => (Number(a.order) || 100) - (Number(b.order) || 100));
339
+ }
340
+
341
+ /** Strip the "page info" stamp block (leading `> **Label**: value` lines) from a body. */
342
+ function stripStamp(text) {
343
+ const lines = String(text || "").split("\n");
344
+ let i = 0;
345
+ while (i < lines.length && /^>\s*\*\*[^*]+\*\*\s*:/.test(lines[i])) i++;
346
+ return lines.slice(i).join("\n").trim();
347
+ }
348
+
349
+ /** Sink payload: original body (unredacted, page-info stamp removed) + share metadata. */
350
+ function sinkPayload() {
351
+ // baseText is the unredacted body; when it is empty the textarea content is the only source
352
+ // (e.g. a session share fills the body server-side, so the preview holds the stamp only).
353
+ // Either way the stamp is metadata for external sharing — never part of a local favourite.
354
+ const raw = (typeof state.baseText === "string" && state.baseText.length) ? state.baseText : state.text;
355
+ return { ...(state.payload || {}), kind: state.kind, text: stripStamp(raw), title: state.title, tags: state.tags };
356
+ }
357
+
358
+ async function runSink(item) {
359
+ if (state.sinkBusy) return;
360
+ const payload = sinkPayload();
361
+ if (!item.builtin && typeof item.accepts === "function") {
362
+ let ok = false;
363
+ try { ok = !!item.accepts(payload); } catch (e) { ok = false; }
364
+ if (!ok) {
365
+ const empty = !String(payload.text || "").trim();
366
+ set({ sinkResult: { ok: false, message: empty ? shareT("share.sink.empty") : shareT("share.sink.unsupported") } });
367
+ return;
368
+ }
369
+ }
370
+ set({ sinkBusy: item.id, sinkResult: null });
371
+ try {
372
+ const r = item.builtin ? await item.run(payload) : await item.save(payload);
373
+ set({ sinkBusy: "", sinkResult: r || { ok: true } });
374
+ } catch (e) {
375
+ set({ sinkBusy: "", sinkResult: { ok: false, message: String((e && e.message) || e) } });
376
+ }
377
+ }
378
+
379
+ function sinkSection() {
380
+ const items = sinkItems();
381
+ if (!items.length) return null;
382
+ const res = state.sinkResult;
383
+ return h("div", null,
384
+ h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, marginBottom: 5 } }, shareT("share.sinks")),
385
+ h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6 } },
386
+ ...items.map((it) => {
387
+ const label = typeof it.label === "function" ? it.label() : (it.label || it.id);
388
+ const svg = it.icon && it.icon.svg;
389
+ return h("button", {
390
+ type: "button", key: it.id, disabled: !!state.sinkBusy,
391
+ onClick: () => { void runSink(it); },
392
+ title: label,
393
+ style: { display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 9px",
394
+ border: "1px solid var(--border, #34363c)", borderRadius: 8,
395
+ background: "var(--bg-hover, #25272c)", color: "var(--text, #d8dade)",
396
+ fontSize: 12, cursor: state.sinkBusy ? "default" : "pointer", opacity: state.sinkBusy && state.sinkBusy !== it.id ? 0.55 : 1 },
397
+ },
398
+ 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,
399
+ label,
400
+ state.sinkBusy === it.id ? h("span", { style: { fontSize: 10, opacity: 0.7 } }, "…") : null,
401
+ );
402
+ })),
403
+ res ? h("div", { style: { marginTop: 6, fontSize: 11, display: "flex", alignItems: "center", gap: 8,
404
+ color: res.ok ? "var(--ok, #4ade80)" : "#e05d5d", wordBreak: "break-word" } },
405
+ h("span", null, (res.ok ? "✓ " : "⚠ ") + (res.message || (res.ok ? shareT("share.sink.saved") : ""))),
406
+ res.ok && res.action && typeof res.action.run === "function"
407
+ ? h("button", { type: "button", onClick: () => { try { res.action.run(); } catch (e) {} },
408
+ style: { border: "1px solid var(--accent, #4d8dff)", background: "none", color: "var(--accent, #4d8dff)",
409
+ borderRadius: 6, padding: "1px 8px", fontSize: 11, cursor: "pointer" } }, res.action.label || "→")
410
+ : null) : null);
411
+ }
412
+
173
413
  function targetSection() {
174
414
  const recent = recentGet();
415
+ const kind = contentKind();
416
+ const compat = (x) => supportsKind(x, kind) && x.status !== "dead" && x.status !== "legacy";
175
417
  const t = state.targets;
176
418
  const byId = new Map(t.map((x) => [x.id, x]));
177
- const recentItems = recent.map((id) => byId.get(id)).filter(Boolean).slice(0, 5);
419
+ const recentItems = recent.map((id) => byId.get(id)).filter(Boolean).filter(compat).slice(0, 5);
178
420
  // 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);
421
+ const mine = t.filter((x) => x.custom && !recent.includes(x.id) && compat(x));
422
+ const recs = t.filter((x) => x.recommended && !recent.includes(x.id) && !x.custom && compat(x)).slice(0, 8);
181
423
  const shown = [];
182
424
  for (const item of recentItems) shown.push(targetCard(item, state.targetId === item.id, "recent"));
183
425
  for (const item of mine) shown.push(targetCard(item, state.targetId === item.id, null));
@@ -187,6 +429,10 @@ function targetSection() {
187
429
  if (sel && !recent.includes(sel.id) && !sel.custom && !sel.recommended) {
188
430
  shown.unshift(targetCard(sel, true, null));
189
431
  }
432
+ if (!recentItems.length && !mine.length && !recs.length) {
433
+ shown.push(h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, padding: "4px 2px" } },
434
+ shareT("share.noCompatible", { kind: kindLabel(kind) })));
435
+ }
190
436
  shown.push(h("button", { type: "button", onClick: () => set({ manager: true }),
191
437
  style: { border: "1px dashed var(--border, #34363c)", background: "none", color: "var(--text-muted, #8b909b)",
192
438
  borderRadius: 8, padding: "4px 10px", fontSize: 12, cursor: "pointer" } }, shareT("share.more")));
@@ -195,6 +441,171 @@ function targetSection() {
195
441
  h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6 } }, ...shown));
196
442
  }
197
443
 
444
+ // --- Container picker UI (tree with named sub-items; search degrades to path list) ---
445
+
446
+ /** Visible picker rows in render order — keyboard navigation walks this list. */
447
+ let panelVisible = [];
448
+
449
+ function containerRow(c, depth, childCount, expanded, selected, highlighted, idx, kbActive) {
450
+ // Depth guides keep the hierarchy readable while every level keeps its own name.
451
+ const guides = [];
452
+ for (let i = 0; i < depth; i++) guides.push(h("span", { key: "g" + i,
453
+ style: { width: 14, textAlign: "center", flexShrink: 0, color: "var(--text-muted, #8b909b)", opacity: 0.45 } }, "│"));
454
+ return h("div", { key: c.id, "data-kb": String(idx), onClick: () => pickContainer(c), title: c.path || c.label,
455
+ style: { display: "flex", alignItems: "center", gap: 5, padding: "3px 6px", borderRadius: 6, cursor: "pointer", fontSize: 12,
456
+ background: selected ? "rgba(77, 141, 255, 0.18)" : kbActive ? "var(--bg-hover, #25272c)" : "transparent",
457
+ boxShadow: kbActive ? "inset 0 0 0 1px var(--accent, #4d8dff)" : undefined,
458
+ color: "var(--text, #d8dade)" } },
459
+ ...guides,
460
+ h("span", { onClick: (e) => { if (!childCount) return; e.stopPropagation();
461
+ set({ containerExpanded: { ...state.containerExpanded, [c.id]: !expanded } }); },
462
+ style: { width: 14, textAlign: "center", flexShrink: 0,
463
+ color: childCount ? "var(--text-muted, #8b909b)" : "transparent",
464
+ cursor: childCount ? "pointer" : "default" } }, expanded ? "▾" : "▸"),
465
+ h("span", { style: { flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
466
+ fontWeight: selected ? 600 : 400,
467
+ color: highlighted && !selected ? "var(--accent, #4d8dff)" : undefined } }, c.label),
468
+ selected ? h("span", { style: { color: "var(--accent, #4d8dff)", fontSize: 11, flexShrink: 0 } }, "✓") : null,
469
+ childCount && !expanded ? h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 10, flexShrink: 0 } }, childCount) : null);
470
+ }
471
+
472
+ /** Search keeps the tree: nodes matching by their own name + their ancestor chain.
473
+ * Each hit stays in context (named ancestors show WHERE it lives — real Joplin
474
+ * trees repeat names across roots), matches highlighted, branches force-expanded. */
475
+ function containerSearchState(items, query) {
476
+ const q = query.toLowerCase();
477
+ const match = new Set();
478
+ const ancestors = new Set();
479
+ const byId = new Map(items.map((c) => [c.id, c]));
480
+ for (const c of items) {
481
+ if (String(c.label).toLowerCase().includes(q)) {
482
+ match.add(c.id);
483
+ let cur = c;
484
+ while (cur?.parent && byId.has(cur.parent)) { ancestors.add(cur.parent); cur = byId.get(cur.parent); }
485
+ }
486
+ }
487
+ return { match, ancestors };
488
+ }
489
+
490
+ function renderContainerNodes(childrenOf, nodes, depth, search, flat) {
491
+ const out = [];
492
+ for (const c of nodes) {
493
+ if (search && !search.match.has(c.id) && !search.ancestors.has(c.id)) continue;
494
+ const kids = childrenOf.get(c.id) || [];
495
+ const expanded = search
496
+ ? search.ancestors.has(c.id) || kids.some((k) => search.match.has(k.id) || search.ancestors.has(k.id))
497
+ : !!state.containerExpanded[c.id];
498
+ const idx = flat.length;
499
+ flat.push(c);
500
+ out.push(containerRow(c, depth, kids.length, expanded, state.containerFor === c.id,
501
+ !!search && search.match.has(c.id), idx, state.kbIndex === idx));
502
+ if (kids.length && expanded) out.push(...renderContainerNodes(childrenOf, kids, depth + 1, search, flat));
503
+ }
504
+ return out;
505
+ }
506
+
507
+ /** Quick-pick chips from the target's recent-container history (≥2 entries to be useful). */
508
+ function containerQuickRow() {
509
+ const t = state.targets.find((x) => x.id === state.targetId);
510
+ const recents = (t?.recentContainers || []).filter((r) => r && r.id);
511
+ if (recents.length < 2) return null;
512
+ return h("div", { style: { display: "flex", flexWrap: "wrap", gap: 4, alignItems: "center", padding: "0 2px 4px" } },
513
+ h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 10, flexShrink: 0 } }, shareT("share.recent")),
514
+ ...recents.map((r) => {
515
+ const sel = state.containerFor === r.id;
516
+ return h("button", { type: "button", key: r.id, title: r.label, onClick: () => pickContainer({ id: r.id, label: r.label, path: r.label }),
517
+ style: { border: "1px solid " + (sel ? "var(--accent, #4d8dff)" : "var(--border, #34363c)"),
518
+ background: sel ? "rgba(77, 141, 255, 0.15)" : "var(--bg-hover, #25272c)",
519
+ color: "var(--text, #d8dade)", borderRadius: 6, padding: "2px 8px", fontSize: 11, cursor: "pointer",
520
+ maxWidth: 150, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, "🕘 " + r.label);
521
+ }));
522
+ }
523
+
524
+ function containerPanel(items) {
525
+ const filter = state.containerFilter.trim();
526
+ const childrenOf = containerTree(items);
527
+ const roots = childrenOf.get("") || [];
528
+ const empty = h("div", { style: { padding: "8px 6px", fontSize: 11, color: "var(--text-muted, #8b909b)" } },
529
+ shareT("share.container.empty"));
530
+ panelVisible = [];
531
+ const flat = panelVisible;
532
+ const search = filter ? containerSearchState(items, filter) : null;
533
+ const rows = renderContainerNodes(childrenOf, roots, 0, search, flat);
534
+ const kbMove = (delta) => {
535
+ if (!panelVisible.length) return;
536
+ const next = state.kbIndex < 0 ? (delta > 0 ? 0 : panelVisible.length - 1)
537
+ : Math.min(Math.max(state.kbIndex + delta, 0), panelVisible.length - 1);
538
+ set({ kbIndex: next });
539
+ setTimeout(() => { try { document.querySelector(`[data-ext-float] [data-kb="${next}"]`)?.scrollIntoView({ block: "nearest" }); } catch (e) {} }, 0);
540
+ };
541
+ return h("div", { style: { border: "1px solid var(--border, #34363c)", borderRadius: 7, marginTop: 5,
542
+ background: "var(--bg-panel, #1e2021)", maxHeight: 320, overflowY: "auto", padding: 4 } },
543
+ h("div", { style: { position: "sticky", top: -4, margin: -4, marginBottom: 0, padding: 4,
544
+ background: "var(--bg-panel, #1e2021)", zIndex: 1 } },
545
+ h("input", { value: state.containerFilter, placeholder: shareT("share.container.search"),
546
+ onInput: (e) => set({ containerFilter: e.target.value, kbIndex: -1 }),
547
+ onKeyDown: (e) => {
548
+ if (e.key === "Escape") { set({ containerOpen: false, containerFilter: "" }); return; }
549
+ if (e.key === "ArrowDown") { e.preventDefault(); kbMove(1); return; }
550
+ if (e.key === "ArrowUp") { e.preventDefault(); kbMove(-1); return; }
551
+ if (e.key === "Enter") { e.preventDefault(); const c = panelVisible[state.kbIndex]; if (c) pickContainer(c); return; }
552
+ const c = panelVisible[state.kbIndex];
553
+ if ((e.key === "ArrowRight" || e.key === "ArrowLeft") && c) {
554
+ e.preventDefault();
555
+ const kids = childrenOf.get(c.id) || [];
556
+ const expanded = filter ? true : !!state.containerExpanded[c.id];
557
+ if (e.key === "ArrowRight" && kids.length && !expanded) set({ containerExpanded: { ...state.containerExpanded, [c.id]: true } });
558
+ if (e.key === "ArrowLeft" && !filter && expanded) set({ containerExpanded: { ...state.containerExpanded, [c.id]: false } });
559
+ }
560
+ },
561
+ ref: (el) => { el?.focus?.(); },
562
+ style: { width: "100%", boxSizing: "border-box", background: "var(--bg-hover, #25272c)",
563
+ border: "1px solid var(--border, #34363c)", borderRadius: 6, padding: "4px 8px", fontSize: 12,
564
+ color: "var(--text, #d8dade)" } }),
565
+ filter && rows.length ? h("div", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)", marginTop: 3 } },
566
+ shareT("share.container.matches", { n: String(search.match.size) })) : null),
567
+ containerQuickRow(),
568
+ state.containersLoading ? h("div", { style: { padding: "6px", fontSize: 11, color: "var(--text-muted, #8b909b)" } }, "…") : null,
569
+ rows.length ? rows : empty);
570
+ }
571
+
572
+ /** Container selection row: hidden unless the current target supports containers. */
573
+ function containerSection() {
574
+ const t = state.targets.find((x) => x.id === state.targetId);
575
+ if (!t || !t.supportsContainers) return null;
576
+ const cache = state.containersByTarget[state.targetId];
577
+ const items = cache?.containers || [];
578
+ const selected = items.find((c) => c.id === state.containerFor);
579
+ const label = noteText(cache?.label) || noteText(t.containerLabel) || shareT("share.container.label");
580
+ const missing = state.containerFor && items.length && !selected;
581
+ const btnLabel = selected ? (selected.path || selected.label) : shareT("share.container.default");
582
+ return h("div", null,
583
+ h("div", { style: { display: "flex", alignItems: "center", gap: 6 } },
584
+ h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, flexShrink: 0 } },
585
+ "📓 " + label),
586
+ h("button", { type: "button", onClick: () => { void ensureContainers(state.targetId); toggleContainerPanel(); },
587
+ title: btnLabel,
588
+ style: { flex: 1, minWidth: 0, display: "flex", alignItems: "center", gap: 5, textAlign: "left",
589
+ border: "1px solid var(--border, #34363c)", background: "var(--bg-hover, #25272c)",
590
+ color: selected ? "var(--text, #d8dade)" : "var(--text-muted, #8b909b)", borderRadius: 7,
591
+ padding: "5px 9px", fontSize: 12, cursor: "pointer" } },
592
+ h("span", { style: { flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, btnLabel),
593
+ h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 10 } }, state.containerOpen ? "▴" : "▾")),
594
+ h("button", { type: "button", onClick: () => { void ensureContainers(state.targetId, true); },
595
+ title: shareT("share.container.refresh"),
596
+ style: { border: "1px solid var(--border, #34363c)", background: "none",
597
+ color: "var(--text-muted, #8b909b)", borderRadius: 7, padding: "5px 8px", fontSize: 12,
598
+ cursor: "pointer", flexShrink: 0 } }, "⟳")),
599
+ missing ? h("div", { style: { color: "#d9a13c", fontSize: 10, marginTop: 4 } }, shareT("share.container.missing")) : null,
600
+ state.containerOpen ? containerPanel(items) : null,
601
+ state.containerError ? h("div", { style: { display: "flex", alignItems: "center", gap: 8,
602
+ color: "#e05d5d", fontSize: 11, marginTop: 4 } },
603
+ shareT("share.container.fail", { detail: state.containerError }),
604
+ h("button", { type: "button", onClick: () => { void ensureContainers(state.targetId, true); },
605
+ style: { border: "none", background: "none", color: "var(--accent, #4d8dff)", cursor: "pointer", fontSize: 11 } },
606
+ shareT("share.container.refresh"))) : null);
607
+ }
608
+
198
609
  /** Collect page context for the optional "page info" stamp. */
199
610
  function pageInfo() {
200
611
  const ua = (typeof navigator !== "undefined" && navigator.userAgent) || "";
@@ -214,10 +625,21 @@ function pageInfo() {
214
625
  if (!browser) b(/Version\/([\d.]+).*Safari/, "Safari");
215
626
  const svc = ctxRef?.getExtService?.("pi-web.session");
216
627
  const cur = (() => { try { return svc?.get?.() ?? svc; } catch { return null; } })();
217
- const sessionId = state.payload?.sessionId || cur?.requestedId || cur?.id
628
+ // Verified snapshot summary: name/firstMessage live under `session`, not on the snapshot itself.
629
+ const sum = cur?.session || null;
630
+ // A shared session row (session-manager menu payload) describes its own session and wins
631
+ // over the currently active one.
632
+ const rowSess = state.payload?.session;
633
+ // List title semantics (session-manager sessionTitle): name || first message || id prefix.
634
+ const listTitle = (s) => (s ? (s.name || s.firstMessage || String(s.id || "").slice(0, 12)) : "");
635
+ // Session ID is the raw canonical id, never the display title: row id → snapshot summary id
636
+ // → verified snapshot id → payload id → URL ?session=.
637
+ const sessionId = rowSess?.id || sum?.id || cur?.sessionId
638
+ || state.payload?.sessionId || state.payload?.sessionName
218
639
  || (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() : "");
640
+ // Session name follows the session list title so it stays meaningful even when the
641
+ // session has no explicit name (falls back to first message, then id prefix).
642
+ const sessionName = listTitle(rowSess) || listTitle(sum) || state.payload?.sessionName || "";
221
643
  return { os, browser, url: typeof location !== "undefined" ? location.href : "", sessionId, sessionName };
222
644
  }
223
645
 
@@ -254,7 +676,7 @@ function errorText() {
254
676
  disabled: "share.err.disabled", unknownTarget: "share.err.unknownTarget",
255
677
  noSession: "share.err.noSession", imageFetch: "share.err.imageFetch", endpoint: "share.err.endpoint",
256
678
  badRequest: "share.err.badRequest", badSxcu: "share.err.badSxcu", noProbe: "share.err.noProbe",
257
- forbidden: "share.err.forbidden",
679
+ forbidden: "share.err.forbidden", kind: "share.err.kind", containerFail: "share.container.fail",
258
680
  }[code];
259
681
  if (key) return shareT(key, { name, detail });
260
682
  return state.error || shareT("share.err.generic", { detail });
@@ -350,7 +772,23 @@ async function doShare() {
350
772
  // The textarea already shows the redacted text (preview-redact ran on load/toggle),
351
773
  // so upload exactly what the user sees; no second redaction on the server.
352
774
  const body = { ...(state.payload || {}), targetId: state.targetId, kind: state.kind,
353
- text: state.text, title: state.title, tags: state.tags, redact: false };
775
+ text: state.text, title: state.title, tags: state.tags, redact: false,
776
+ container: state.containerFor || "" };
777
+ // Images: load in the browser (same-origin /api/... or data: URLs — no CORS,
778
+ // no server-side fetch) and hand the server base64 bytes.
779
+ if (state.kind === "image" && body.imageSrc) {
780
+ const blob = await fetch(body.imageSrc).then((r) => { if (!r.ok) throw new Error("HTTP " + r.status); return r.blob(); })
781
+ .catch((e) => { throw Object.assign(new Error(shareT("share.err.imageFetch", { detail: e?.message || e })), { detail: String(e?.message || e) }); });
782
+ const dataUrl = await new Promise((res, rej) => {
783
+ const fr = new FileReader();
784
+ fr.onload = () => res(String(fr.result));
785
+ fr.onerror = () => rej(new Error("FileReader failed"));
786
+ fr.readAsDataURL(blob);
787
+ });
788
+ body.imageBase64 = dataUrl;
789
+ body.mime = blob.type || "image/png";
790
+ body.filename = body.filename || ("image." + (blob.type.split("/")[1] || "png").replace("jpeg", "jpg"));
791
+ }
354
792
  const r = await getJSON("share", { method: "POST", headers: { "content-type": "application/json" },
355
793
  body: JSON.stringify(body) });
356
794
  recentAdd(state.targetId);
@@ -392,7 +830,7 @@ function shareDialog() {
392
830
  style: { background: "none", border: "none", color: "var(--text-muted, #8b909b)", cursor: "pointer", fontSize: 14 } }, "✕"));
393
831
  const body = h("div", { ref: (el) => { dialogBodyEl = el; },
394
832
  style: { padding: "12px 14px", display: "flex", flexDirection: "column", gap: 12, flex: 1, minHeight: 0, overflowY: "auto" } },
395
- previewSection(), targetSection(),
833
+ previewSection(), sinkSection(), targetSection(), containerSection(),
396
834
  h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9 } },
397
835
  h("input", { value: state.title, placeholder: shareT("share.titleField"), onInput: (e) => set({ title: e.target.value }),
398
836
  style: { background: "var(--bg-hover, #25272c)", border: "1px solid var(--border, #34363c)", color: "var(--text, #d8dade)", borderRadius: 7, padding: "6px 9px", fontSize: 12 } }),
@@ -434,15 +872,21 @@ function managerDialog() {
434
872
  form: { ...((t.values && !Array.isArray(t.values)) ? t.values : {}) } }),
435
873
  style: { display: "flex", alignItems: "center", gap: 7, padding: "5px 8px", borderRadius: 7, cursor: "pointer",
436
874
  background: state.editing === t.id ? "rgba(77, 141, 255, 0.15)" : "none", opacity: t.status === "dead" ? 0.5 : 1 } },
437
- h("span", null, t.status === "dead" ? "💀" : t.category === "archive" ? "📓" : "🔗"),
875
+ h("span", null, t.status === "dead" ? "💀" : (t.icon || (t.category === "archive" ? "📓" : "🔗"))),
438
876
  h("div", { style: { flex: 1, minWidth: 0 } },
439
877
  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 : ""))),
878
+ h("div", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } },
879
+ (t.kinds || []).map(kindLabel).join("/")
880
+ + (() => { const n = noteText(t.note); return n ? " · " + n : ""; })()
881
+ + (t.supportsContainers && t.lastContainerLabel ? " · 📓 " + t.lastContainerLabel : ""))),
441
882
  (() => { const b = CFG_BADGE[t.configState]; return b ? h("span", { title: shareT(b.key),
442
883
  style: { color: b.color, fontSize: 9, whiteSpace: "nowrap", flexShrink: 0 } }, b.icon) : null; })(),
443
884
  t.recommended ? h("span", { style: { color: "var(--accent, #4d8dff)", fontSize: 10 } }, "★") : null,
444
885
  // "Use" closes the loop: pick this target for the pending share and return to it.
445
- t.status !== "dead" && t.configState !== "needs-setup"
886
+ !supportsKind(t, contentKind())
887
+ ? h("span", { title: shareT("share.notCompatible", { kind: kindLabel(contentKind()) }),
888
+ style: { color: "var(--text-muted, #8b909b)", fontSize: 9, whiteSpace: "nowrap", flexShrink: 0 } }, "∅")
889
+ : t.status !== "dead" && t.status !== "legacy" && t.configState !== "needs-setup"
446
890
  ? h("button", { type: "button", title: shareT("share.useTarget"),
447
891
  onClick: (e) => { e.stopPropagation(); chooseTarget(t.id); },
448
892
  style: { border: "1px solid var(--accent, #4d8dff)", background: state.targetId === t.id ? "var(--accent, #4d8dff)" : "none",
@@ -457,7 +901,7 @@ function managerDialog() {
457
901
  const fields = edit?.fields || [];
458
902
  const form = edit ? h("div", { style: { flex: 1, padding: 14, display: "flex", flexDirection: "column", gap: 12, overflowY: "auto" } },
459
903
  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,
904
+ (() => { const n = noteText(edit.note); return n ? h("div", { style: { fontSize: 11, color: "var(--text-muted, #8b909b)" } }, n) : null; })(),
461
905
  ...fields.map((f) => {
462
906
  const key = typeof f === "string" ? f : f.key;
463
907
  const label = typeof f === "string" ? f : (f.label || f.key);
@@ -549,12 +993,15 @@ export default function register(ctx) {
549
993
  style: { display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 8px", height: 22,
550
994
  border: "none", background: "none", borderRadius: 5, color: "var(--text-dim, #8b909b)", cursor: "pointer", fontSize: 11 },
551
995
  }, icon("share", 12), label);
552
- ctx.registerItems("userMessageActions", [{ id: "aiti-msg-share-user", render: shareAction(shareT("share.action")) }]);
996
+ // meta.order: 1 pins Share right after the host's built-in Copy button,
997
+ // ahead of unordered slot items (git-trace badge, quote, bookmark — manifest
998
+ // order would otherwise put aiti-git-trace first).
999
+ ctx.registerItems("userMessageActions", [{ id: "aiti-msg-share-user", render: shareAction(shareT("share.action")), meta: { order: 1 } }]);
553
1000
  // Assistant messages mount the same share button at both ends (meta.placement):
554
1001
  // long replies put one end off-screen, so top (meta row) + bottom carry identical buttons.
555
1002
  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" } },
1003
+ { id: "aiti-msg-share-assistant", render: shareAction(shareT("share.action")), meta: { order: 1 } },
1004
+ { id: "aiti-msg-share-assistant-top", render: shareAction(shareT("share.action")), meta: { placement: "top", order: 1 } },
558
1005
  ]);
559
1006
  // Session row share lives in session-manager's ⋯ more-menu, not as a bare row
560
1007
  // button (too many row actions). Registered via that extension's topic contract.
@@ -595,12 +1042,15 @@ export default function register(ctx) {
595
1042
  session: sess, title: sess?.name || sess?.title || "" }),
596
1043
  });
597
1044
  // File card's first-row action (file recognition).
1045
+ // `order` follows the msg-smart row order: built-in Open = 10, external = 20,
1046
+ // Reveal = 30 — so Share sits right after Open and before Reveal.
598
1047
  ctx.registerTopicItem("msg-file-action", {
599
1048
  id: "aiti-msg-share-file",
600
1049
  label: shareT("share.action"),
601
1050
  title: shareT("share.fileTip"),
602
1051
  icon: SHARE_ICON,
603
1052
  type: "share",
1053
+ order: 20,
604
1054
  match: (abs, isDir) => !isDir,
605
1055
  onClick: (abs) => openShare({ kind: "file", filePath: abs, filename: abs.split("/").pop() }),
606
1056
  });