agent-loft 0.2.127 → 0.2.129

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.
Files changed (41) hide show
  1. package/README.md +5 -2
  2. package/bin/cli.js +40 -19
  3. package/package.json +1 -1
  4. package/src/agents/claude/session.ts +8 -5
  5. package/src/agents/codex/session.ts +5 -4
  6. package/src/agents/dsh/session.ts +3 -1
  7. package/src/agents/pi/session.ts +4 -3
  8. package/src/agents/workbuddy/session.ts +6 -3
  9. package/src/channels/web/api.ts +10 -1
  10. package/src/channels/web/experts-api.ts +32 -8
  11. package/src/channels/web/memo-collab.ts +28 -0
  12. package/src/channels/web/memo-file.ts +30 -0
  13. package/src/channels/web/memo-storage.ts +15 -6
  14. package/src/channels/web/memos-api.ts +96 -37
  15. package/src/cli/service.ts +3 -1
  16. package/src/core/db.ts +12 -0
  17. package/src/core/expert-prompt.ts +2 -1
  18. package/src/core/experts.ts +2 -0
  19. package/src/core/hub.ts +13 -0
  20. package/src/core/mcp.ts +2 -2
  21. package/src/core/memo-index.ts +167 -0
  22. package/src/core/memo-sources.ts +113 -5
  23. package/src/core/memos-bridge.ts +69 -0
  24. package/src/core/tasks-bridge.ts +6 -0
  25. package/src/core/tasks-mcp.ts +7 -0
  26. package/src/core/types.ts +2 -0
  27. package/src/core/upgrade-health.ts +21 -0
  28. package/src/core/upgrade-launcher.ts +94 -0
  29. package/src/core/upgrade-releases.ts +103 -0
  30. package/src/core/upgrade.ts +54 -18
  31. package/src/main.ts +14 -0
  32. package/src/mcp/memo-tools.ts +26 -0
  33. package/src/mcp/tasks-server.ts +5 -4
  34. package/web/css/memos.css +3 -1
  35. package/web/lib/memo-access.js +28 -0
  36. package/web/settings/agent-defaults.js +4 -1
  37. package/web/settings/experts.js +7 -2
  38. package/web/settings/users.js +41 -15
  39. package/web/views/file-editor.js +2 -1
  40. package/web/views/memo-dialogs.js +88 -4
  41. package/web/views/memos.js +50 -15
@@ -1,5 +1,6 @@
1
1
  import { agentIcon, fill, h, icon, toast } from "../lib/dom.js";
2
2
  import { api } from "../lib/api.js";
3
+ import { expertMemoField } from "../lib/memo-access.js";
3
4
  import { confirmDialog, modal, showMenu } from "../lib/overlay.js";
4
5
  import { isAdmin, S } from "../state.js";
5
6
  import { openAgentDefaults } from "./agent-defaults.js";
@@ -205,18 +206,19 @@ function viewSharedExpert(e) {
205
206
  }
206
207
 
207
208
  function openTools(data, e, reload) {
209
+ const memos = expertMemoField(data.memoLibraries, e.id);
208
210
  const skills = checkList(data.skills.map((s) => ({ id: s.id, label: s.name, hint: s.description })), e.skills, "还没有启用的技能(设置 → 技能)");
209
211
  const machine = (data.machineMcp?.[e.engine] ?? []).map((name) => ({ id: `${data.machinePrefix}${name}`, label: `${name}(本机)` }));
210
212
  const mcp = checkList([...data.mcp.map((s) => ({ id: s.id, label: s.name, hint: s.description })), ...machine], e.mcp, "还没有 MCP(设置 → MCP)");
211
213
  const save = h("button", { class: "btn primary" }, "保存我的工具");
212
214
  const close = modal({ title: `${e.name} · 我的工具`, body: h("div", { class: "modal-body" },
213
215
  h("p", { class: "muted" }, "只影响你使用这个专家时加载的工具,网页和绑定账号后的飞书私聊共用。未选择时不加载技能或 MCP;记忆使用你自己的设置。子智能体的工具需在对应专家中单独配置。"),
214
- field("我的技能", skills.el), field("我的 MCP", mcp.el),
216
+ field("我的技能", skills.el), field("我的 MCP", mcp.el), memos.el,
215
217
  ), foot: h("div", { class: "modal-foot" }, save) });
216
218
  save.onclick = async () => {
217
219
  save.disabled = true;
218
220
  try {
219
- await api(`/api/experts/${e.id}/tools`, { method: "PUT", body: { skills: skills.value(), mcp: mcp.value() } });
221
+ await api(`/api/experts/${e.id}/tools`, { method: "PUT", body: { skills: skills.value(), mcp: mcp.value(), memoAccess: memos.changes() } });
220
222
  close();
221
223
  toast("已保存,你的对话下一条消息起使用新的工具");
222
224
  void reload();
@@ -296,6 +298,7 @@ function checkList(items, picked, empty) {
296
298
  /** e:编辑这个;preset:新建时预填(模板、复制) */
297
299
  function openEditor(data, e, reload, preset) {
298
300
  const src = e ?? preset ?? {};
301
+ const memos = expertMemoField(data.memoLibraries, e?.id);
299
302
  const name = h("input", { value: src.name ?? "", maxlength: "40", placeholder: "比如:证券观察员" });
300
303
  const avatar = avatarPicker(src, !e);
301
304
  const desc = h("input", { value: src.description ?? "", maxlength: "500", placeholder: "一句话说它是干什么的(选专家时、当子智能体时都看这句)" });
@@ -409,6 +412,7 @@ function openEditor(data, e, reload, preset) {
409
412
  section(
410
413
  "权限和能力",
411
414
  field("权限", perms.el, "改文件包含读文件,跑命令包含改文件。什么都不勾就是只能聊天"),
415
+ memos.el,
412
416
  cwdField,
413
417
  codexField,
414
418
  ),
@@ -454,6 +458,7 @@ function openEditor(data, e, reload, preset) {
454
458
  subagents: engine.value === "claude" ? subs.value() : [],
455
459
  codexTools: engine.value === "codex" ? codexTools.value() : [],
456
460
  memory: memory.checked,
461
+ memoAccess: memos.changes(),
457
462
  welcome: welcome.value,
458
463
  quickPrompts,
459
464
  };
@@ -348,28 +348,26 @@ export async function systemTab(cfg, page) {
348
348
  const render = () => {
349
349
  const recheck = h("button", { class: "btn small", disabled: checking }, checking ? "检查中…" : "检查更新");
350
350
  recheck.onclick = () => void checkVersion(true);
351
- const status = checking
352
- ? h("span", { class: "status-tag" }, "正在检查更新…")
353
- : !v
354
- ? null
355
- : v.updateAvailable
356
- ? h("span", { class: "status-tag ok" }, `有新版本 ${v.latest}`)
357
- : v.latest
358
- ? h("span", { class: "status-tag" }, "已是最新版本")
359
- : h("span", { class: "status-tag bad", title: v.latestError ?? "" }, "查不到最新版本");
360
- const upgradeBtn = v?.updateAvailable && v.canUpgrade && !checking ? h("button", { class: "btn small primary" }, `升级到 ${v.latest}`) : null;
351
+ let status = null;
352
+ if (checking) status = h("span", { class: "status-tag" }, "正在检查更新…");
353
+ else if (v?.upgrading) status = h("span", { class: "status-tag" }, "正在下载并检查新版…");
354
+ else if (v?.pendingVersion) {
355
+ const state = v.version === v.pendingVersion ? "正在验证" : "等待重启验证";
356
+ status = h("span", { class: "status-tag" }, `${v.pendingVersion} ${state}`);
357
+ } else if (v?.updateAvailable) status = h("span", { class: "status-tag ok" }, `有新版本 ${v.latest}`);
358
+ else if (v?.latest) status = h("span", { class: "status-tag" }, "已是最新版本");
359
+ else if (v) status = h("span", { class: "status-tag bad", title: v.latestError ?? "" }, "查不到最新版本");
360
+ const upgradeBtn = v?.updateAvailable && v.canUpgrade && !v.upgrading && !v.pendingVersion && !checking ? h("button", { class: "btn small primary" }, `升级到 ${v.latest}`) : null;
361
361
  if (upgradeBtn) {
362
362
  upgradeBtn.onclick = async () => {
363
363
  upgradeBtn.disabled = true;
364
364
  upgradeBtn.textContent = "正在升级…";
365
365
  try {
366
- const r = await api("/api/server/upgrade", { method: "POST" });
367
- toast(r.restarting ? `已升级到 ${r.to},服务正在重启,页面会自动重连` : `已升级到 ${r.to},重启 agent-loft 后生效`, 6000);
368
- void checkVersion(false);
366
+ await api("/api/server/upgrade?background=1", { method: "POST" });
367
+ await followUpgrade(v.latest);
369
368
  } catch (err) {
370
369
  toast(`升级失败:${err.message}`, 6000);
371
- upgradeBtn.disabled = false;
372
- upgradeBtn.textContent = `升级到 ${v.latest}`;
370
+ void checkVersion(false);
373
371
  }
374
372
  };
375
373
  }
@@ -378,6 +376,7 @@ export async function systemTab(cfg, page) {
378
376
  h("h4", {}, "服务端"),
379
377
  h("div", { class: "row" }, h("b", {}, `agent-loft ${v?.version ?? sys.version}`), status),
380
378
  h("div", { class: "muted" }, `Node ${sys.node} · 已运行 ${uptime(sys.uptimeMs)} · ${sys.underSystemd ? "以系统服务运行" : "前台运行(重启需要在终端里操作)"}`),
379
+ v?.upgradeError && !v.pendingVersion ? h("div", { class: "muted" }, v.upgradeError) : null,
381
380
  v && !checking && !v.latest && v.latestError ? h("div", { class: "muted" }, v.latestError) : null,
382
381
  v?.updateAvailable && !v.canUpgrade && v.reason ? h("div", { class: "muted" }, v.reason) : null,
383
382
  v?.updateAvailable && v.canUpgrade && !v.service ? h("div", { class: "muted" }, "agent-loft 是在前台手动运行的,升级后要自己重启一下。") : null,
@@ -404,6 +403,32 @@ export async function systemTab(cfg, page) {
404
403
  checking = false;
405
404
  if (sys) render();
406
405
  };
406
+ async function followUpgrade(target) {
407
+ let disconnectedAt = 0;
408
+ while (sysBox.isConnected) {
409
+ let progress;
410
+ try {
411
+ progress = await api("/api/server/upgrade");
412
+ disconnectedAt = 0;
413
+ } catch (err) {
414
+ if (err.status && err.status < 500) throw err;
415
+ // 服务重启时反向代理可能短暂返回 502,继续等新进程报告结果。
416
+ disconnectedAt ||= Date.now();
417
+ if (Date.now() - disconnectedAt > 150_000) {
418
+ toast("暂时连不上服务,恢复连接后可在设置里查看升级结果", 6000);
419
+ return;
420
+ }
421
+ }
422
+ if (progress?.error) throw new Error(progress.error);
423
+ if (progress && !progress.upgrading && (!progress.pendingVersion || !v?.service)) {
424
+ if (progress.pendingVersion) toast("新版已准备好,重启 agent-loft 后验证并启用", 6000);
425
+ else if (progress.version === target) toast(`已验证并启用 ${target}`, 6000);
426
+ await checkVersion(false);
427
+ return;
428
+ }
429
+ await new Promise(resolve => setTimeout(resolve, 2000));
430
+ }
431
+ }
407
432
  const versionDone = checkVersion(false);
408
433
  try {
409
434
  sys = await api("/api/system");
@@ -413,6 +438,7 @@ export async function systemTab(cfg, page) {
413
438
  }
414
439
  render();
415
440
  await versionDone;
441
+ if (v?.upgrading || (v?.pendingVersion && v.service)) void followUpgrade(v.pendingVersion || v.latest).catch(err => { toast(err.message); void checkVersion(false); });
416
442
  }
417
443
 
418
444
  /** 运行了多久:分钟 / 小时 / 天 */
@@ -88,7 +88,7 @@ function languageFor(name, CM) {
88
88
  * 在 parent 里建一个编辑器。onChange:内容变了;onSave:按了 Ctrl / ⌘ + S。
89
89
  * 返回 { text, setText, focus, measure, destroy };text() 给的是还原了换行符、可以直接存的内容
90
90
  */
91
- export async function createEditor({ parent, text, name, onChange, onSave, collaboration }) {
91
+ export async function createEditor({ parent, text, name, onChange, onSave, collaboration, readOnly = false }) {
92
92
  const CM = await loadCodeMirror();
93
93
  const dark = matchMedia("(prefers-color-scheme: dark)");
94
94
  const theme = new CM.Compartment();
@@ -117,6 +117,7 @@ export async function createEditor({ parent, text, name, onChange, onSave, colla
117
117
  CM.indentWithTab,
118
118
  ]),
119
119
  ...(collaboration ? [CM.collab(collaboration)] : []),
120
+ ...(readOnly ? [CM.EditorState.readOnly.of(true), CM.EditorView.editable.of(false)] : []),
120
121
  CM.basicSetup,
121
122
  CM.EditorView.lineWrapping,
122
123
  theme.of(themeOf()),
@@ -1,6 +1,90 @@
1
- import { h } from "../lib/dom.js";
1
+ import { h, toast } from "../lib/dom.js";
2
2
  import { modal } from "../lib/overlay.js";
3
3
  import { api } from "../lib/api.js";
4
+ import { memoAccessSelect } from "../lib/memo-access.js";
5
+
6
+ function memoAccessField() {
7
+ const select = memoAccessSelect("智能体访问", "off");
8
+ select.name = "access";
9
+ const hint = h("small", {}, "授权后,Agent Loft 会在服务器建立本库的全文索引。");
10
+ const update = () => { hint.hidden = select.value === "off"; };
11
+ select.addEventListener("change", update);
12
+ update();
13
+ return { select, field: h("label", {}, "智能体访问", select, hint) };
14
+ }
15
+
16
+ export async function memoAccessSettings(source) {
17
+ const url = action => "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id });
18
+ Object.assign(source, await api(url("access")));
19
+ const select = memoAccessSelect("默认权限", source.access ?? "off");
20
+ const status = h("p", { role: "status" });
21
+ const refresh = h("button", { class: "btn", type: "button" }, "立即刷新索引");
22
+ const save = h("button", { class: "btn primary", type: "submit" }, "保存权限");
23
+ const form = h("form", { class: "modal-body memo-fields" },
24
+ h("label", {}, "默认权限", select),
25
+ h("small", {}, "专家默认沿用此权限。可在「设置 → 专家」中为指定专家单独设置。"),
26
+ h("small", {}, "授权后会建立全文索引。在专家对话里直接说「帮我搜笔记」或「把这段记到笔记里」即可。"),
27
+ status, refresh, save);
28
+ let timer, sequence = 0;
29
+ async function load(method = "GET") {
30
+ clearTimeout(timer);
31
+ const request = ++sequence;
32
+ refresh.hidden = ![source.access, ...Object.values(source.expertAccess ?? {})].some(a => a === "read" || a === "write");
33
+ if (refresh.hidden) { status.textContent = ""; return; }
34
+ try {
35
+ const index = await api(url("index"), { method });
36
+ if (!form.isConnected || sequence !== request) return;
37
+ const last = index.success ? "最近成功:" + new Date(index.success).toLocaleString() : "首次索引尚未完成";
38
+ status.textContent = [index.running ? "正在扫描,已检查 " + index.scanned + " 份文本" : "", index.error, last].filter(Boolean).join(" · ");
39
+ refresh.disabled = index.running;
40
+ if (index.running) timer = setTimeout(load, 1500);
41
+ } catch (err) { if (sequence === request) status.textContent = err.message; }
42
+ }
43
+ modal({ title: source.name + " · 智能体访问", body: form, beforeClose: () => { if (save.disabled) return false; clearTimeout(timer); ++sequence; } });
44
+ refresh.onclick = () => void load("POST");
45
+ form.onsubmit = async e => {
46
+ e.preventDefault();
47
+ if (save.disabled) return;
48
+ save.disabled = true;
49
+ try {
50
+ Object.assign(source, await api(url("access"), { method: "PUT", body: { access: select.value, defaultOnly: true } }));
51
+ await load();
52
+ } catch (err) { status.textContent = err.message; }
53
+ finally { save.disabled = false; }
54
+ };
55
+ void load();
56
+ }
57
+
58
+ export async function shareMemoSource(source) {
59
+ const url = "/api/memos/sharing?" + new URLSearchParams({ source: source.id });
60
+ const members = await api(url);
61
+ const fields = members.map(member => {
62
+ const select = memoAccessSelect(member.name, member.access);
63
+ if (member.disabled) for (const option of select.options) option.disabled = option.value !== "off" && option.value !== member.access;
64
+ return { member, select };
65
+ });
66
+ const error = h("div", { class: "memo-error", role: "alert" });
67
+ const save = h("button", { class: "btn primary", type: "submit", disabled: !fields.length }, "保存共享");
68
+ const form = h("form", { class: "modal-body memo-fields" },
69
+ h("small", {}, "成员可在自己的备忘录里打开整个笔记库,包括文件和版本历史。共享给成员不会同时授权给对方的专家。"),
70
+ fields.length ? fields.map(({ member, select }) => h("label", { class: "memo-expert-access" },
71
+ member.name + (member.disabled ? "(已停用)" : ""), select)) : h("p", {}, "还没有其他可共享的账号。"), error, save);
72
+ let saving = false;
73
+ const close = modal({ title: source.name + " · 共享给成员", body: form, beforeClose: () => !saving });
74
+ form.onsubmit = async e => {
75
+ e.preventDefault();
76
+ if (saving) return;
77
+ saving = save.disabled = true;
78
+ try {
79
+ const changes = Object.fromEntries(fields.filter(({ member, select }) => member.access !== select.value)
80
+ .map(({ member, select }) => [member.id, select.value]));
81
+ await api(url, { method: "PUT", body: { changes } });
82
+ close();
83
+ toast("共享设置已保存");
84
+ } catch (err) { error.textContent = err.message; }
85
+ finally { saving = save.disabled = false; }
86
+ };
87
+ }
4
88
 
5
89
  export function connectSource(onConnect) {
6
90
  const kind = h("select", { class: "input" }, h("option", { value: "webdav" }, "WebDAV"), h("option", { value: "s3" }, "S3 / 兼容存储"));
@@ -25,7 +109,7 @@ export function connectSource(onConnect) {
25
109
  name.required = true;
26
110
  const error = h("div", { class: "memo-error", role: "alert" });
27
111
  const submit = h("button", { class: "btn primary", type: "submit" }, "连接笔记库");
28
- const form = h("form", { class: "modal-body memo-fields" }, label("名称", name), label("数据源", kind), label("服务地址", endpoint), s3, label(userLabel, username), label(secretLabel, secret), error, submit);
112
+ const form = h("form", { class: "modal-body memo-fields" }, label("名称", name), label("数据源", kind), label("服务地址", endpoint), s3, label(userLabel, username), label(secretLabel, secret), memoAccessField().field, error, submit);
29
113
  const close = modal({ title: "连接笔记库", body: form, beforeClose: () => !submit.disabled });
30
114
  form.onsubmit = async e => {
31
115
  e.preventDefault();
@@ -70,7 +154,7 @@ export function askMemoName(title, initial, directory) {
70
154
  }
71
155
 
72
156
  /** Only fetch the selected snapshot. Restoring returns its text to the normal conditional save path. */
73
- export async function chooseMemoVersion(url) {
157
+ export async function chooseMemoVersion(url, readOnly = false) {
74
158
  const versions = await api(url);
75
159
  return new Promise(resolve => {
76
160
  let request = 0, selected = null;
@@ -79,7 +163,7 @@ export async function chooseMemoVersion(url) {
79
163
  const preview = h("pre", { class: "memo-snapshot", "aria-label": "版本正文" });
80
164
  const apply = h("button", { class: "btn primary", disabled: true, onclick: () => { close(); resolve(selected); } }, "恢复此版本");
81
165
  const body = h("div", { class: "modal-body memo-fields" },
82
- versions.length ? [select, preview, apply] : h("p", {}, "还没有历史版本。下次保存修改时,会保留修改前的正文。"));
166
+ versions.length ? [select, preview, readOnly ? null : apply] : h("p", {}, "还没有历史版本。下次保存修改时,会保留修改前的正文。"));
83
167
  const close = modal({ title: "版本历史", body, beforeClose: () => { resolve(null); } });
84
168
  async function load() {
85
169
  const seq = ++request;
@@ -5,7 +5,7 @@ import { confirmDialog } from "../lib/overlay.js";
5
5
  import { WS } from "../lib/ws.js";
6
6
  import { S, setContentHash, ui } from "../state.js";
7
7
  import { createEditor } from "./file-editor.js";
8
- import { askMemoName, chooseMemoVersion, connectSource } from "./memo-dialogs.js";
8
+ import { askMemoName, chooseMemoVersion, connectSource, memoAccessSettings, shareMemoSource } from "./memo-dialogs.js";
9
9
  import { closeSide, renderSidebar } from "./sidebar.js";
10
10
  import { renderTopbar } from "./topbar.js";
11
11
 
@@ -78,8 +78,15 @@ function notebook() {
78
78
  const side = h("aside", { class: "memo-side" });
79
79
  const pathLabel = h("strong", { class: "memo-path" });
80
80
  const entryButton = button("连接笔记库", () => addSource());
81
+ const accessButton = h("button", { class: "btn", onclick: () => run(() => memoAccessSettings(source)) }, icon("gear"), "智能体访问");
82
+ const shareButton = button("共享给成员", () => run(() => shareMemoSource(source)));
83
+ const disconnectButton = button("断开笔记库", () => run(disconnect), "unplug");
84
+ const newNote = button("新建笔记", () => run(() => create(false)));
85
+ const newFolder = button("新建文件夹", () => run(() => create(true)), "folder");
86
+ const readOnly = () => source?.permission === "read";
81
87
  function endpoint(action, file = "", cursor = "") {
82
- return "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id, path: file, ...(action === "file" ? { collab: "1" } : {}), ...(cursor ? { cursor } : {}) });
88
+ return "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id, path: file,
89
+ ...(source.sharedBy ? { owner: source.sharedBy.id } : {}), ...(action === "file" ? { collab: "1" } : {}), ...(cursor ? { cursor } : {}) });
83
90
  }
84
91
  function sync() {
85
92
  retryButton.hidden = !saveError || conflict;
@@ -87,9 +94,10 @@ function notebook() {
87
94
  status.title = saveError;
88
95
  toggle.disabled = busy;
89
96
  choose.disabled = busy;
90
- copyButton.hidden = !conflict;
97
+ shareButton.disabled = accessButton.disabled = busy;
98
+ copyButton.hidden = !conflict || readOnly();
91
99
  status.textContent = conflict ? "远端已更改" : saving ? "正在保存…" : saveError ? "保存失败" :
92
- busy ? "处理中…" : dirty ? "待自动保存" : editor ? "已保存" : "";
100
+ busy ? "处理中…" : dirty ? "待自动保存" : readOnly() ? "只读" : editor ? "已保存" : "";
93
101
  }
94
102
  async function run(fn) {
95
103
  if (busy) return;
@@ -147,17 +155,35 @@ function notebook() {
147
155
  expanded = new Set();
148
156
  root.classList.add("show-tree");
149
157
  if (s) localStorage.setItem(chooseKey, s.id);
150
- fill(choose, ...sources.map(item => h("option", { value: item.id }, item.name)));
158
+ fillChoices();
151
159
  if (s) choose.value = s.id;
160
+ accessButton.hidden = shareButton.hidden = disconnectButton.hidden = !!s?.sharedBy;
161
+ toggle.hidden = newNote.hidden = newFolder.hidden = readOnly();
152
162
  side.hidden = !s;
153
163
  root.classList.toggle("no-source", !s);
154
164
  if (!s) {
155
165
  fill(pane, h("div", { class: "memo-empty" }, icon("clipboard"), h("h2", {}, "连接你的笔记库"), h("p", {}, "从 WebDAV 目录或 S3 存储桶打开笔记。"), entryButton));
156
166
  return;
157
167
  }
158
- fill(pane, h("div", { class: "memo-blankbar" }, toggleTree), h("div", { class: "memo-empty" }, icon("file"), h("p", {}, "选择文件,或在当前目录新建笔记。")));
168
+ fill(pane, h("div", { class: "memo-blankbar" }, toggleTree), h("div", { class: "memo-empty" }, icon("file"), h("p", {}, readOnly() ? "选择文件查看。" : "选择文件,或在当前目录新建笔记。")));
159
169
  refreshTree();
160
170
  }
171
+ function fillChoices() {
172
+ fill(choose, sources.map(item => h("option", { value: item.id }, item.sharedBy
173
+ ? item.name + " · " + item.sharedBy.name + "共享(" + (item.permission === "read" ? "只读" : "读写") + ")" : item.name)));
174
+ }
175
+ async function reloadSources() {
176
+ const list = await api("/api/memos/sources");
177
+ if (busy || dirty || saving) return;
178
+ sources = list;
179
+ const latest = sources.find(s => s.id === source?.id);
180
+ if (!latest || latest.permission !== source.permission) select(latest ?? sources[0]);
181
+ else {
182
+ Object.assign(source, latest);
183
+ fillChoices();
184
+ choose.value = latest.id;
185
+ }
186
+ }
161
187
  function addSource() {
162
188
  void run(async () => {
163
189
  if (!(await discardable())) return;
@@ -166,9 +192,9 @@ function notebook() {
166
192
  }
167
193
  async function disconnect() {
168
194
  if (!(await discardable())) return;
169
- if (!(await confirmDialog({ title: "断开笔记库?", message: `将移除「${source.name}」在此账号的连接。远端文件和本地版本历史会保留。${dirty ? "当前草稿尚未保存。" : ""}`, confirmText: "断开连接" }))) return;
195
+ if (!(await confirmDialog({ title: "断开笔记库?", message: `将移除「${source.name}」的连接,并撤回这个库的所有共享。远端文件和本地版本历史会保留。${dirty ? "当前草稿尚未保存。" : ""}`, confirmText: "断开连接" }))) return;
170
196
  await api(endpoint("sources"), { method: "DELETE" });
171
- sources = sources.filter(s => s !== source);
197
+ sources = sources.filter(s => s.id !== source.id);
172
198
  select(sources[0]);
173
199
  }
174
200
 
@@ -279,7 +305,7 @@ function notebook() {
279
305
  fill(toolbar, toggleTree, pathLabel, status, toggle, historyButton, copyButton, retryButton);
280
306
  fill(pane, toolbar, editorHost, reading);
281
307
  session = conflict ? null : data.collab;
282
- editor = await createEditor({ parent: editorHost, collaboration: session, text: session ? original : draft?.text ?? original, name: file, onSave: () => void saveNow().catch(err => toast(err.message)), onChange: () => {
308
+ editor = await createEditor({ parent: editorHost, readOnly: readOnly(), collaboration: session, text: session ? original : draft?.text ?? original, name: file, onSave: () => void saveNow().catch(err => toast(err.message)), onChange: () => {
283
309
  if (receiving) return;
284
310
  dirty = editor.collaboration ? !!editor.collaboration.pending() : editor.text() !== original;
285
311
  if (!conflict) { saveError = ""; retryMs = 0; }
@@ -341,10 +367,18 @@ function notebook() {
341
367
  const packet = await api(changesURL(current.collaboration.revision()), { headers, signal: controller.signal });
342
368
  if (controller.signal.aborted) break;
343
369
  applyPacket(current, packet);
370
+ if (source.sharedBy && packet.permission !== source.permission && !dirty && !saving && !busy) {
371
+ await reloadSources();
372
+ if (current !== editor) break;
373
+ }
344
374
  retry = 1000;
345
375
  } catch (err) {
346
376
  if (controller.signal.aborted) break;
347
377
  if ([401, 403, 404, 409].includes(err.status)) {
378
+ if (source.sharedBy && (err.status === 403 || err.status === 404) && !dirty && !saving && !busy) {
379
+ await reloadSources().catch(error => toast(error.message));
380
+ if (current !== editor) break;
381
+ }
348
382
  if (!dirty && !saving && !busy && err.status === 409) {
349
383
  await run(async () => {
350
384
  const fresh = await api(endpoint("file", path));
@@ -431,7 +465,7 @@ function notebook() {
431
465
  async function openHistory() {
432
466
  if (saving) await saving.catch(() => {});
433
467
  if (dirty && !conflict) await saveNow();
434
- const text = await chooseMemoVersion(endpoint("history", path));
468
+ const text = await chooseMemoVersion(endpoint("history", path), readOnly());
435
469
  if (text === null) return;
436
470
  if (conflict) throw new Error("请先另存草稿并重新打开文件,再恢复旧版");
437
471
  editor.setText(text);
@@ -478,8 +512,8 @@ function notebook() {
478
512
  refreshTree();
479
513
  });
480
514
  }, true);
481
- fill(side, h("div", { class: "memo-sources" }, choose, button("连接其他笔记库", addSource, "plus"), button("断开笔记库", () => run(disconnect), "unplug")),
482
- h("div", { class: "memo-tree-tools" }, button("新建笔记", () => run(() => create(false))), button("新建文件夹", () => run(() => create(true)), "folder"), button("刷新目录", refreshTree, "refresh"), h("button", { class: "btn memo-return", onclick: () => root.classList.remove("show-tree") }, "返回文件")), tree);
515
+ fill(side, h("div", { class: "memo-sources" }, choose, accessButton, shareButton, button("连接其他笔记库", addSource, "plus"), disconnectButton),
516
+ h("div", { class: "memo-tree-tools" }, newNote, newFolder, button("刷新目录", refreshTree, "refresh"), h("button", { class: "btn memo-return", onclick: () => root.classList.remove("show-tree") }, "返回文件")), tree);
483
517
  fill(root, side, pane);
484
518
  async function init() {
485
519
  fill(pane, h("div", { class: "memo-empty" }, "正在读取笔记库…"));
@@ -487,11 +521,11 @@ function notebook() {
487
521
  sources = await api("/api/memos/sources");
488
522
  const draft = savedDraft();
489
523
  select(sources.find(s => s.id === (draft?.source ?? localStorage.getItem(chooseKey))) ?? sources[0]);
490
- if (source && draft?.source === source.id && typeof draft.text === "string") {
524
+ if (source && !readOnly() && draft?.source === source.id && typeof draft.text === "string") {
491
525
  await run(async () => {
492
526
  let data;
493
527
  try { data = await api(endpoint("file", draft.path)); }
494
- catch { data = { text: null, version: null }; }
528
+ catch (err) { if (source.sharedBy) throw err; data = { text: null, version: null }; }
495
529
  for (let p = parent(draft.path); p; p = parent(p)) expanded.add(p);
496
530
  await showText(draft.path, data, true, draft);
497
531
  refreshTree();
@@ -502,7 +536,7 @@ function notebook() {
502
536
  }
503
537
  side.hidden = true;
504
538
  void init();
505
- return { owner, root, persistDraft, pausePoll, resumePoll, flush: () => {
539
+ return { owner, root, reloadSources, persistDraft, pausePoll, resumePoll, flush: () => {
506
540
  if (!busy && !conflict) void saveNow().catch(() => {});
507
541
  }, pending: () => dirty || busy || !!saving, destroy: resetDocument, measure: () => editor?.measure() };
508
542
  }
@@ -531,6 +565,7 @@ export function openMemos() {
531
565
  renderTopbar();
532
566
  renderSidebar();
533
567
  if (page?.owner !== S.user.id) { page?.destroy(); page = notebook(); }
568
+ else void page.reloadSources().catch(err => toast(err.message));
534
569
  fill(ui.msgInner, page.root);
535
570
  page.measure();
536
571
  page.resumePoll();