@coda-console/friends 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/view/app.mjs CHANGED
@@ -3,12 +3,11 @@
3
3
  // Accord 的读写(coda/accord@1)都在这里按交互发起;「共享」(授给好友的、好友授给本机的远程执行、最近的操作)只经模块读写各台本机。
4
4
  // 网络节点(friendNodes / removeFriendNode,试用):分节标题行的入口打开抽屉,列出入了网却没完成互认的残留节点,删除由客户端弹确认框;
5
5
  // 移除好友后留在网络里的节点(status.networkRemovals)显示在分节里,用户点「重试」才读、才删,页面不会自己调用。
6
- // 昵称、头像都由 Accord 公钥推出(nickname.mjs、avatar.mjs),没有可编辑的名片;
6
+ // 昵称、头像都由 Accord 公钥推出(WebView 标准库 coda-view://lib/v1/accord.js、avatar.mjs),没有可编辑的名片;
7
7
  // 节点名等外来数据一律用 textContent / DOM API 渲染,从不拼 HTML 字符串。
8
8
  import { accordStatusSummary, resolveAvatar } from '../lib/avatar.mjs';
9
9
  import { checked, parseInvite } from '../lib/friends.mjs';
10
- import { identityTitle } from '../lib/nickname.mjs';
11
- import { friendSections, identities, listMembers } from '../lib/view-members.mjs';
10
+ import { friendSections, identities, listMembers, memberTitles } from '../lib/view-members.mjs';
12
11
  import { fill, h, identiconSvg, svg } from './dom.mjs';
13
12
 
14
13
  const ACCORD = 'coda/accord@1', LOCAL = { kind: ACCORD, id: 'local' };
@@ -21,6 +20,8 @@ const RECOVER_MS = 3000;
21
20
  const REVOKE_RETRIES = 3;
22
21
  // 结果不明的授予:连续读到这么多遍有效列表、里面都没有这条授权,就回滚这一行,允许重试(持有方对同一目标的授予幂等)。
23
22
  const GRANT_CONFIRMS = 3;
23
+ // 仅限目录的授予、改范围要先到目标机探测(持有方最长等 30 秒):页面多等一会儿再算没有回应。
24
+ const PROBE_WAIT_MS = 45_000;
24
25
 
25
26
  // 视图里的每台电脑(成员在页面生命周期内不变)各存一份数据;读不到的(unreachable)也在,只是不发请求。
26
27
  // 节点的名字、忙碌、错误、已收回按(电脑, 控制服务器节点 ID)记在 m.fn 里,不与好友行的 state.busy / state.notice 混用(那两个按 Accord 的 node 记)。
@@ -37,24 +38,24 @@ function say(target, text, kind = 'hint') { target.className = kind; target.text
37
38
  const pendingReplies = new Map();
38
39
  let counter = 0;
39
40
  // `late`:等不到回应时也不丢这条回复,晚到了就交给它(授予这类不能重发的写操作用)。
40
- function ask(m, type, input = {}, late) {
41
+ function ask(m, type, input = {}, late, wait = 10_000) {
41
42
  const rid = `n${++counter}`;
42
43
  return new Promise((resolve, reject) => {
43
44
  const settle = fn => v => { clearTimeout(timer); pendingReplies.delete(rid); fn(v); };
44
45
  const timer = setTimeout(() => {
45
46
  if (late) pendingReplies.get(rid).late = late; else pendingReplies.delete(rid);
46
47
  reject(new Error('模块没有回应'));
47
- }, 10_000);
48
+ }, wait);
48
49
  pendingReplies.set(rid, { machine: m.id, resolve: settle(resolve), reject: settle(reject) });
49
50
  Promise.resolve().then(() => coda.postMessage({ type, rid, ...input }, via(m))).catch(error => pendingReplies.get(rid)?.reject(Object.assign(new Error(`发送失败:${error?.message ?? error}`), { refused: true })));
50
51
  });
51
52
  }
52
53
  addEventListener('message', event => {
53
- const { type, rid, ok, value, error, effects } = event.data ?? {};
54
+ const { type, rid, ok, value, error, effects, code } = event.data ?? {};
54
55
  const wait = type === 'reply' ? pendingReplies.get(rid) : null;
55
56
  if (!wait || (event.machine?.id && event.machine.id !== wait.machine)) return;
56
57
  // refused:确认什么也没写——模块明确回了错误且 effects 为 none,或消息根本没发出去(postMessage 抛错);别的错误、超时都是结果不明。
57
- const failure = Object.assign(new Error(error), { refused: effects === 'none' });
58
+ const failure = Object.assign(new Error(error), { refused: effects === 'none', code });
58
59
  if (wait.late) { pendingReplies.delete(rid); wait.late(ok ? { value } : { failure }); } else if (ok) wait.resolve(value); else wait.reject(failure);
59
60
  });
60
61
 
@@ -110,7 +111,7 @@ function closeDialog() {
110
111
  // Escape 一次收一层:授予选择框,再是行尾菜单,再是弹层。
111
112
  addEventListener('keydown', e => {
112
113
  if (e.key !== 'Escape') return;
113
- if (picker.ctx) closePicker();
114
+ if (picker.ctx) cancelPicker();
114
115
  else if (state.menu) { state.menu = null; draw(); }
115
116
  else if (openDialog) closeDialog();
116
117
  });
@@ -139,12 +140,12 @@ function statusTiles(m, rows) {
139
140
  conflict || pending ? null : total ? '全部已互认' : '还没有好友')),
140
141
  tile('身份', cert.text, h('span', { class: 'tile-s' }, sub), cert.dot));
141
142
  }
142
- function drawHero(id, sections) {
143
+ function drawHero(id, sections, titles) {
143
144
  const { author, signer } = id, ready = Boolean(signer);
144
145
  const summary = accordStatusSummary(signer?.entry, []);
145
146
  const notice = state.heroNotice.get(author ?? '');
146
147
  const settled = members.every(m => m.loaded || m.unreachable || m.accordProblem);
147
- const name = author ? identityTitle(author) : !settled ? '读取中…' : ready ? '未建身份' : '读不到身份';
148
+ const name = author ? titles.get(author) : !settled ? '读取中…' : ready ? '未建身份' : '读不到身份';
148
149
  const single = !multi && sections[0];
149
150
  return h('section', { class: 'hero' },
150
151
  h('div', { class: 'banner' }, h('div', { class: 'banner-acts' },
@@ -315,7 +316,7 @@ async function submitInvite() {
315
316
 
316
317
  // ---- 好友详情:重新互认、移除都发给这一行所在的电脑 ----
317
318
  // 不同电脑上的 node 可能相同,忙碌与提示按(电脑, node)记。
318
- const sectionRows = m => friendSections([m])[0].rows;
319
+ let drawn = []; // 最近一次 draw 的分节,详情按它找当前行
319
320
 
320
321
  async function handshake(m, row) {
321
322
  const key = rowKey(m, row.node);
@@ -348,7 +349,7 @@ const detail = {
348
349
  notice: h('div'),
349
350
  };
350
351
  detail.dialog.body.append(h('div', { class: 'stack' }, detail.card, detail.info, detail.share, detail.actions, detail.notice));
351
- const detailRow = () => state.detail && sectionRows(state.detail.member).find(row => row.node === state.detail.node);
352
+ const detailRow = () => state.detail && drawn.find(section => section.member === state.detail.member).rows.find(row => row.node === state.detail.node);
352
353
  function openDetail(m, row) {
353
354
  state.detail = { member: m, node: row.node, key: rowKey(m, row.node) }; state.removing = null; state.menu = null;
354
355
  shareOf(m).opsOpen = false;
@@ -397,16 +398,19 @@ const SHARE_STATUS = {
397
398
  available: ['可用', 'bound'], target_off: ['目标已关闭', 'pending'], target_missing: ['目标不在了', 'pending'], target_offline: ['目标离线', 'pending'], target_unreachable: ['读不到目标', 'pending'], no_identity: ['读不出本机身份', 'pending'],
398
399
  granting: ['授予中', 'busy'], revoking: ['撤销中', 'busy'], machine_changed: ['已停用', 'pending'], grantee_changed: ['已停用', 'pending'],
399
400
  };
401
+ const PENDING = ['待确认', 'busy'];
400
402
  const PROXY_STATUS = {
401
403
  available: ['可用', 'bound'], off: ['TA 那边没开远程执行', 'pending'], channel: ['和 TA 的通道断了', 'pending'],
402
404
  author: ['本机身份变了,请 TA 重新授予', 'pending'], sign: ['本机没有可用的签名证书', 'pending'],
403
405
  };
404
406
  // 授出的范围不让选,由对方的身份决定:个人身份授给他名下的机器,机器身份只授给那一台;基座还没给 certified 时不写。
405
407
  const scopeNote = certified => (certified === true ? '授给这个人名下的机器' : certified === false ? '只授给对方那一台机器' : null);
406
- const shareOf = m => (m.share ??= { grants: null, problem: null, corrupt: null, clock: 0, writes: 0, touched: 0, reread: false, pending: [], revoking: new Map(), theirs: new Map(), ops: new Map(), targets: null, targetsProblem: null, opsOpen: false, timer: null });
408
+ const shareOf = m => (m.share ??= { grants: null, problem: null, corrupt: null, clock: 0, writes: 0, touched: 0, reread: false, pending: [], revoking: new Map(), theirs: new Map(), ops: new Map(), targets: null, targetsProblem: null, opsOpen: false, scopeOpen: new Set(), rescoping: new Map(), timer: null });
407
409
  const certifiedOf = (m, row) => m.friends.find(friend => friend.node === row.node)?.certified;
408
410
  const mergeGrant = (sh, made) => { const all = sh.grants ?? []; sh.grants = all.some(g => g.grant === made.grant) ? all.map(g => (g.grant === made.grant ? made : g)) : [...all, made]; };
409
411
  // 已撤的不显示;撤销中的(名下的调用还在取消)显示。
412
+ // 能改范围的:还在用的授权(已撤销、已失效、目标不在了的不行)。
413
+ const EDITABLE = new Set(['available', 'target_off', 'target_offline', 'target_unreachable']);
410
414
  const visibleGrant = g => g.status === 'revoking' || (g.status !== 'revoked' && g.revokedAt === undefined);
411
415
 
412
416
  function loadShare(m, row) {
@@ -445,6 +449,13 @@ async function readGrants(m, round = false) {
445
449
  if (p.state !== 'granting' || !p.unknown || (p.misses = (p.misses ?? 0) + 1) < GRANT_CONFIRMS) continue;
446
450
  Object.assign(p, { state: 'denied', reason: '没有确认授予成功,请重试', unknown: false, expired: true });
447
451
  }
452
+ // 结果不明的改范围:列表里是想改成的范围(或授权已不在了)就是核对完了;连续读到上限遍都不是,就写明没确认,回到原范围可再改。
453
+ for (const [grant, one] of sh.rescoping) {
454
+ if (!one.unknown) continue;
455
+ const found = read.grants.find(g => g.grant === grant);
456
+ if (!found || found.revokedAt !== undefined || JSON.stringify(found.restrict ?? null) === JSON.stringify(one.restrict)) sh.rescoping.delete(grant);
457
+ else if ((one.misses = (one.misses ?? 0) + 1) >= GRANT_CONFIRMS) sh.rescoping.set(grant, { error: '没有确认范围改成功,仍是原来的范围,可以再改一次' });
458
+ }
448
459
  // 结果不明的撤销:读到已撤或在撤销中就是核对完了,留下的是仍可用的,由恢复循环再发一次。
449
460
  for (const [grant, one] of sh.revoking) if (one.unknown && !read.grants.some(g => g.grant === grant && visibleGrant(g) && g.status !== 'revoking')) sh.revoking.delete(grant);
450
461
  }
@@ -468,7 +479,7 @@ async function readOps(m, row) {
468
479
  // 对应的授权仍可用,才重发;读和重发都结束了才排下一轮(所以同一授权的撤销不会有两个在途重试)。
469
480
  function recover(m) {
470
481
  const sh = shareOf(m);
471
- const need = sh.pending.some(p => p.unknown) || [...sh.revoking.values()].some(r => r.unknown) || (sh.grants ?? []).some(g => g.status === 'revoking');
482
+ const need = sh.pending.some(p => p.unknown) || [...sh.revoking.values()].some(r => r.unknown) || [...sh.rescoping.values()].some(r => r.unknown) || (sh.grants ?? []).some(g => g.status === 'revoking');
472
483
  if (!need || sh.timer) return;
473
484
  sh.timer = setTimeout(async () => {
474
485
  if (await readGrants(m, true)) {
@@ -526,32 +537,44 @@ async function grantTo(m, row, target) {
526
537
  const dots = () => svg('svg', { viewBox: '0 0 24 24', width: 18, height: 18, fill: 'currentColor', 'aria-hidden': 'true' },
527
538
  svg('circle', { cx: 5, cy: 12, r: 2 }), svg('circle', { cx: 12, cy: 12, r: 2 }), svg('circle', { cx: 19, cy: 12, r: 2 }));
528
539
  const emptyRow = text => h('li', { class: 'empty g-empty' }, text);
540
+ const ACCESS = { rw: '读写', ro: '只读' };
541
+ // 授权的范围:整台机器,或第一条目录加「等 N 个」,点开看全部目录与各自的读写;short 是操作记录里的简短标记(整台机器的不标)。展开与否按 key 记着,重画不丢。
542
+ function scopeView(sh, key, restrict, short) {
543
+ if (!restrict) return short ? null : h('span', { class: 'g-sub truncate' }, '整台机器');
544
+ const { dirs } = restrict, [first] = dirs;
545
+ return h('details', { class: 'scope', open: sh.scopeOpen.has(key), ontoggle: e => { if (e.target.open) sh.scopeOpen.add(key); else sh.scopeOpen.delete(key); } },
546
+ // 长路径在摘要里截断,读写标记与「等 N 个」留在后面不被截掉。
547
+ h('summary', { class: 'g-sub' }, short ? `仅限目录 · ${dirs.length} 个` : [h('span', { class: 'sum-main' }, `仅限目录 · ${first.path}`), h('span', { class: 'sum-tail' }, `(${ACCESS[first.access]})${dirs.length > 1 ? `等 ${dirs.length} 个` : ''}`)]),
548
+ h('ul', { class: 'dirs' }, dirs.map(dir => h('li', {}, h('span', { class: 'tag' }, ACCESS[dir.access]), h('span', { class: 'mono selectable' }, dir.path)))));
549
+ }
529
550
  // 一行:名称与说明、状态、行尾只有一个菜单按钮(没有菜单的行也留着这个槽,列对得齐)。
530
- function shareRow({ key, name, sub, subKind, badge, busy, menu }) {
551
+ function shareRow({ key, name, sub, subKind, scope, badge, busy, menu }) {
531
552
  const open = state.menu === key;
532
553
  return h('li', { class: 'g-row', 'aria-busy': busy ? 'true' : null },
533
- h('div', { class: 'g-info' }, h('span', { class: 'g-name truncate' }, name), sub ? h('span', { class: `g-sub truncate${subKind === 'error' ? ' error' : ''}` }, sub) : null),
554
+ h('div', { class: 'g-info' }, h('span', { class: 'g-name truncate' }, name), sub ? h('span', { class: `g-sub truncate${subKind === 'error' ? ' error' : ''}` }, sub) : null, scope),
534
555
  h('span', { class: `badge ${badge[1]}` }, badge[0]),
535
556
  menu ? h('button', { class: 'kebab', type: 'button', 'aria-label': `更多操作:${name}`, 'aria-haspopup': 'menu', 'aria-expanded': String(open), disabled: busy,
536
557
  onclick: e => { e.stopPropagation?.(); state.menu = open ? null : key; draw(); } }, dots()) : h('span', { class: 'kebab-slot', 'aria-hidden': 'true' }),
537
- open && menu ? h('div', { class: 'menu', role: 'menu' }, h('button', { type: 'button', role: 'menuitem', class: menu.danger ? 'danger' : '',
538
- onclick: e => { e.stopPropagation?.(); menu.run(); } }, menu.label, menu.note ? h('span', { class: 'menu-note' }, menu.note) : null)) : null);
558
+ open && menu ? h('div', { class: 'menu', role: 'menu' }, menu.map(item => h('button', { type: 'button', role: 'menuitem', class: item.danger ? 'danger' : '',
559
+ onclick: e => { e.stopPropagation?.(); item.run(); } }, item.label, item.note ? h('span', { class: 'menu-note' }, item.note) : null))) : null);
539
560
  }
540
561
  function drawShare(m, row) {
541
562
  const sh = shareOf(m), scope = scopeNote(certifiedOf(m, row));
542
563
  const mine = [
543
564
  ...(sh.grants ?? []).filter(g => g.friend === row.author && visibleGrant(g)).map(g => {
544
- const local = sh.revoking.get(g.grant), busy = g.status === 'revoking' || (local && !local.error);
545
- return shareRow({ key: `g:${g.grant}`, name: g.target.name ?? g.target.id, sub: local?.error ?? scope, subKind: local?.error ? 'error' : null,
546
- badge: busy ? SHARE_STATUS.revoking : SHARE_STATUS[g.status] ?? ['已失效', 'pending'], busy,
547
- menu: { label: '撤销', note: '同时取消对方正在跑的调用', danger: true, run: () => revokeGrant(m, g) } });
565
+ const local = sh.revoking.get(g.grant), re = sh.rescoping.get(g.grant), waiting = re?.unknown, failed = local?.error ?? re?.error;
566
+ const busy = g.status === 'revoking' || (local && !local.error) || waiting;
567
+ return shareRow({ key: `g:${g.grant}`, name: g.target.name ?? g.target.id, sub: failed ?? (waiting ? '范围改动待确认:下面还是原来的范围' : scope), subKind: failed ? 'error' : null, scope: scopeView(sh, `g:${g.grant}`, g.restrict),
568
+ badge: waiting ? PENDING : busy ? SHARE_STATUS.revoking : SHARE_STATUS[g.status] ?? ['已失效', 'pending'], busy,
569
+ menu: [...(EDITABLE.has(g.status) ? [{ label: '修改范围…', run: () => openScope(m, row, g) }] : []),
570
+ { label: '撤销', note: '同时取消对方正在跑的调用', danger: true, run: () => revokeGrant(m, g) }] });
548
571
  }),
549
- ...sh.pending.filter(p => p.friend === row.author).map(p => shareRow({ key: `p:${p.target.id}`, name: p.target.name, sub: p.state === 'denied' ? p.reason : scope, subKind: p.state === 'denied' ? 'error' : null,
550
- badge: p.state === 'denied' ? ['未授予', 'conflict'] : SHARE_STATUS.granting, busy: p.state === 'granting',
551
- menu: { label: '移除', run: () => { sh.pending = sh.pending.filter(one => one !== p); state.menu = null; draw(); } } })),
572
+ ...sh.pending.filter(p => p.friend === row.author).map(p => shareRow({ key: `p:${p.target.id}`, name: p.target.name, sub: p.state === 'denied' ? p.reason : p.restrict && p.unknown ? '授予待确认:正在核对列表' : scope, subKind: p.state === 'denied' ? 'error' : null, scope: scopeView(sh, `p:${p.target.id}`, p.restrict ?? null),
573
+ badge: p.state === 'denied' ? ['未授予', 'conflict'] : p.restrict && p.unknown ? PENDING : SHARE_STATUS.granting, busy: p.state === 'granting',
574
+ menu: [{ label: '移除', run: () => { sh.pending = sh.pending.filter(one => one !== p); state.menu = null; draw(); } }] })),
552
575
  ];
553
576
  const their = sh.theirs.get(row.author);
554
- const theirRows = (their?.rows ?? []).map(proxy => shareRow({ key: `t:${proxy.key}`, name: proxy.name, badge: PROXY_STATUS[proxy.status] ?? ['不可用', 'pending'] }));
577
+ const theirRows = (their?.rows ?? []).map(proxy => shareRow({ key: `t:${proxy.key}`, name: proxy.name, scope: scopeView(sh, `t:${proxy.key}`, proxy.restrict), badge: PROXY_STATUS[proxy.status] ?? ['不可用', 'pending'] }));
555
578
  const ops = sh.ops.get(row.author);
556
579
  const canGrant = row.status === 'bound' && Boolean(row.author) && sh.grants !== null && !sh.corrupt;
557
580
  fill(detail.share,
@@ -568,7 +591,7 @@ function drawShare(m, row) {
568
591
  if (sh.opsOpen && row.author) readOps(m, row);
569
592
  } }, h('summary', {}, '最近的操作'),
570
593
  h('div', { class: 'ops-list' }, ops?.problem ? h('p', { class: 'error' }, ops.problem) : !ops ? h('p', { class: 'empty' }, row.author ? '正在读取…' : '还没有操作记录')
571
- : ops.rows.length ? [...ops.rows.map(opRow), h('p', { class: 'hint' }, '完整记录:coda self ledger.list')] : h('p', { class: 'empty' }, '还没有操作记录'))));
594
+ : ops.rows.length ? [...ops.rows.map(one => opRow(sh, one)), h('p', { class: 'hint' }, '完整记录:coda self ledger.list')] : h('p', { class: 'empty' }, '还没有操作记录'))));
572
595
  }
573
596
  // 操作记录的摘要:时间、操作、命令摘要、结局、耗时。
574
597
  const duration = ms => (ms < 10_000 ? `${(ms / 1000).toFixed(1)} 秒` : ms < 60_000 ? `${Math.round(ms / 1000)} 秒` : `${Math.round(ms / 60_000)} 分钟`);
@@ -579,19 +602,23 @@ function outcomeOf(row) {
579
602
  if (row.exitCode === undefined || row.exitCode === 0) return ['成功', 'bound'];
580
603
  return [row.exitCode === null ? '失败' : `失败(退出码 ${row.exitCode})`, 'conflict'];
581
604
  }
582
- function opRow(row) {
605
+ function opRow(sh, row) {
583
606
  const [label, kind] = outcomeOf(row), rejected = row.outcome === 'rejected';
584
607
  return h('div', { class: 'op' },
585
608
  h('div', { class: 'op-top' }, h('span', { class: 'op-time' }, formatTime(row.at)), h('span', { class: 'tag' }, rejected ? '请求' : '执行'), h('span', { class: 'spacer' }),
586
609
  h('span', { class: `badge ${kind}` }, label), h('span', { class: 'dur' }, rejected ? '—' : duration(row.ms))),
587
- h('div', { class: 'op-cmd truncate selectable' }, rejected ? `${row.code}${row.count > 1 ? ` × ${row.count}` : ''}` : row.command.summary));
610
+ h('div', { class: 'op-cmd truncate selectable' }, rejected ? `${row.code}${row.count > 1 ? ` × ${row.count}` : ''}` : row.command.summary),
611
+ scopeView(sh, `o:${row.request}`, row.restrict, true));
588
612
  }
589
613
 
590
- // 授予选择框:叠在好友详情上,只选要授出的记录,不选范围;每行下面的小字是对方身份决定的范围。
591
- const picker = { dialog: makeDialog({ title: '授予远程执行', close: '取消', cancel: () => closePicker() }), ctx: null, list: h('ul', { class: 'glist' }) };
592
- picker.dialog.body.append(picker.list);
614
+ // 授予与修改范围用同一张表单,叠在好友详情上:授予先在列表里选机器、选定后出范围;修改范围直接是表单(机器固定)。
615
+ // 表单里的输入框不随页面的整体重画重建(否则打字时会丢焦点):只有结构变化(切范围、加删行、出错)才重画表单。
616
+ const MAX_DIRS = 50, MAX_PATH_BYTES = 1024;
617
+ const picker = { dialog: makeDialog({ title: '授予远程执行', close: '取消', cancel: () => cancelPicker() }), ctx: null, list: h('ul', { class: 'glist' }) };
593
618
  function openPicker(m, row) {
594
- picker.ctx = { m, row };
619
+ picker.ctx = { m, row, stage: 'list' };
620
+ picker.dialog.heading.textContent = '授予远程执行';
621
+ fill(picker.dialog.body, picker.list);
595
622
  picker.dialog.scrim.hidden = false;
596
623
  drawPicker();
597
624
  const sh = shareOf(m);
@@ -601,18 +628,174 @@ function closePicker() {
601
628
  picker.ctx = null;
602
629
  picker.dialog.scrim.hidden = true;
603
630
  }
631
+ // 探测在途时不能关:结果要落在这张表单上。
632
+ function cancelPicker() { if (!picker.ctx?.busy) closePicker(); }
604
633
  function drawPicker() {
605
- if (!picker.ctx) return;
634
+ if (picker.ctx?.stage !== 'list') return;
606
635
  const { m, row } = picker.ctx, sh = shareOf(m), scope = scopeNote(certifiedOf(m, row));
607
636
  const taken = new Set([...(sh.grants ?? []).filter(g => g.friend === row.author && visibleGrant(g)).map(g => g.target.id), ...sh.pending.filter(p => p.friend === row.author && p.state !== 'denied').map(p => p.target.id)]);
608
637
  fill(picker.list, sh.targetsProblem ? h('li', { class: 'error g-empty' }, sh.targetsProblem) : sh.targets === null ? emptyRow('正在读取…')
609
638
  : sh.targets.length ? sh.targets.map(target => {
610
639
  const why = sh.corrupt ? '持有方出了故障' : !target.available ? '远程执行没打开' : taken.has(target.id) ? '已授给 TA' : '';
611
- return h('li', {}, h('button', { class: 'pick', type: 'button', disabled: Boolean(why), onclick: () => { if (!why) grantTo(m, row, target); } },
640
+ return h('li', {}, h('button', { class: 'pick', type: 'button', disabled: Boolean(why), onclick: () => { if (!why) chooseTarget(target); } },
612
641
  h('span', { class: 'g-info' }, h('span', { class: 'g-name truncate' }, target.name), h('span', { class: 'g-sub truncate' }, `${target.os} · ${target.user}`), scope ? h('span', { class: 'g-sub truncate' }, scope) : null),
613
642
  why ? h('span', { class: 'why' }, why) : null));
614
643
  }) : emptyRow('没有可授出的远程执行记录'));
615
644
  }
645
+ const blankDir = access => ({ path: '', access });
646
+ // 选定机器:范围回到「整台机器」,目录清空(换机器重选时也一样)。
647
+ function chooseTarget(target) {
648
+ if (!picker.ctx) return;
649
+ Object.assign(picker.ctx, { stage: 'form', target, mode: 'whole', dirs: [blankDir('rw')], problem: null, busy: false });
650
+ drawForm();
651
+ }
652
+ function openScope(m, row, g) {
653
+ state.menu = null;
654
+ const sh = shareOf(m), target = sh.targets?.find(t => t.id === g.target.id) ?? { id: g.target.id, name: g.target.name ?? g.target.id };
655
+ const ctx = picker.ctx = { m, row, stage: 'form', grant: g, target, mode: g.restrict ? 'dirs' : 'whole', dirs: g.restrict?.dirs.map(dir => ({ ...dir })) ?? [blankDir('rw')], problem: null, busy: false };
656
+ picker.dialog.scrim.hidden = false;
657
+ drawForm();
658
+ // 目标机的系统(能不能选仅限目录)取自可授出的记录;读到了与已有的不同才重画。
659
+ ask(m, 'grants.targets').then(targets => {
660
+ sh.targets = targets;
661
+ const found = targets.find(t => t.id === g.target.id);
662
+ if (found && picker.ctx === ctx && !ctx.busy && found.restrictHint !== ctx.target.restrictHint) { ctx.target = found; drawForm(); }
663
+ }, () => {});
664
+ }
665
+ // 允许目录互相重叠的字面部分,与目标机同一套规则:规范掉 `.`、`..`、多余斜杠与结尾斜杠,相同或一条在另一条里面就算。经链接、大小写的真实路径层面以目标机为准。
666
+ const OVERLAP = '允许目录之间不能互相包含或重复,请去掉其中一条';
667
+ const normalPath = path => {
668
+ const parts = [];
669
+ for (const part of path.split('/')) { if (part === '..') parts.pop(); else if (part && part !== '.') parts.push(part); }
670
+ return `/${parts.join('/')}`;
671
+ };
672
+ const within = (path, parent) => path === parent || path.startsWith(parent === '/' ? '/' : `${parent}/`);
673
+ // 表单上方的校验:不合规就给出缺什么(第一处),确认按钮不可用,不发请求。
674
+ function scopeProblem(dirs) {
675
+ if (!dirs.length) return '至少要有一个目录';
676
+ if (dirs.length > MAX_DIRS) return `最多 ${MAX_DIRS} 个目录,现在有 ${dirs.length} 个`;
677
+ for (const [i, { path }] of dirs.entries()) {
678
+ if (!path) return `第 ${i + 1} 行还没填路径`;
679
+ if (!path.startsWith('/')) return `第 ${i + 1} 行:要填目标机上的绝对路径,以 / 开头`;
680
+ if (new TextEncoder().encode(path).length > MAX_PATH_BYTES) return `第 ${i + 1} 行:路径太长(至多 ${MAX_PATH_BYTES} 字节)`;
681
+ }
682
+ const flat = dirs.map(dir => normalPath(dir.path));
683
+ for (const [i, one] of flat.entries()) {
684
+ const j = flat.findIndex((other, at) => at > i && (within(one, other) || within(other, one)));
685
+ if (j >= 0) return `第 ${i + 1} 行(${dirs[i].path})与第 ${j + 1} 行(${dirs[j].path})重叠:${OVERLAP}`;
686
+ }
687
+ if (!dirs.some(dir => dir.access === 'rw')) return '至少要有一个「读写」的目录';
688
+ return null;
689
+ }
690
+ // 失败按持有方给的稳定错误码说明;后端的原话作补充。目录类的错误尽量指到是哪一行(持有方的原话里带路径,取路径最长的那行)。
691
+ const FAIL_TEXT = {
692
+ sandbox_unsupported: '这台机器不能用「仅限目录」:目标机要是 macOS,并且有 /usr/bin/sandbox-exec',
693
+ restrict_unsupported: '这台机器上的「远程执行」版本太旧,不认识「仅限目录」:到那台机器上升到 0.2.0 及以上再试',
694
+ restrict_dir_not_found: ['目录在目标机上不存在', '有目录在目标机上不存在'],
695
+ restrict_dir_not_a_directory: ['这个路径在目标机上不是目录', '有路径在目标机上不是目录'],
696
+ restrict_protected: ['与目标机上受保护的位置重叠:目录不能包含、也不能落在 Coda 的状态目录或 ~/.ssh 里面(整个家目录因为包含 ~/.ssh 也不行):请选与它们不重叠的目录', '有目录与目标机上受保护的位置重叠:目录不能包含、也不能落在 Coda 的状态目录或 ~/.ssh 里面(整个家目录因为包含 ~/.ssh 也不行):请选与它们不重叠的目录'],
697
+ sandbox_failed: '目标机上的沙箱起不来,没有授出',
698
+ target_offline: '目标机现在离线,没法探测:等它回来再试',
699
+ target_unreachable: '读不到目标机(可能被移出了空间):等它回到空间再试',
700
+ target_missing: '目标机上的远程执行记录不在了:先让那台机器重新打开远程执行',
701
+ target_changed: '目标已经不是授权时的那台机器的记录了:关掉这张表单重新选',
702
+ timeout: '目标机 30 秒内没有回应,没有授出:确认它在线、远程执行已打开,再试一次',
703
+ restrict_overlap: OVERLAP,
704
+ restrict_too_large: '范围太大,签不出授权记录:减少目录,或缩短路径',
705
+ already_granted: '已经授给 TA 一条范围不同的授权:到「我授给 TA」里那一行的菜单选「修改范围…」',
706
+ disabled: '目标机上的远程执行没打开',
707
+ invalid_input: '范围的格式不对:检查每一行的路径和读写',
708
+ invalid_state: '这条授权已撤销或已失效,不能再改范围',
709
+ not_found: '这条授权或目标记录已经不在了:关掉这张表单刷新一下',
710
+ };
711
+ function problemOf(c, e) {
712
+ if (!e.code) return { text: e.refused ? `没有发出:${e.message}` : '没有收到目标机的回应,不能确定有没有成功:先看「我授给 TA」里有没有这一条,再决定要不要重试' };
713
+ if (e.code === 'restrict_overlap') {
714
+ // 目标机的消息里是「第 N 条(原写法)与第 M 条(原写法)」,序号就是表单的行号;两条的原写法都对得上才指到行,对不上就只给说明。
715
+ const [, a, p, b, q] = /第 (\d+) 条((.*))与第 (\d+) 条((.*?)),同一目录/s.exec(e.message) ?? [];
716
+ const rows = a && c.dirs[a - 1]?.path === p && c.dirs[b - 1]?.path === q ? [c.dirs[a - 1], c.dirs[b - 1]] : [];
717
+ return { text: rows.length ? `第 ${a} 行(${p})与第 ${b} 行(${q}):${OVERLAP}` : OVERLAP, detail: e.message, rows };
718
+ }
719
+ const text = FAIL_TEXT[e.code], [one, any] = Array.isArray(text) ? text : [text, text];
720
+ const hit = Array.isArray(text) ? c.dirs.filter(dir => dir.path && e.message.includes(dir.path)).sort((a, b) => b.path.length - a.path.length)[0] : null;
721
+ return { text: hit ? `第 ${c.dirs.indexOf(hit) + 1} 行(${hit.path}):${one}` : (any ?? `没有成功(${e.code})`), detail: e.message, rows: hit ? [hit] : [] };
722
+ }
723
+ async function confirmScope() {
724
+ const c = picker.ctx;
725
+ if (!c || c.busy || (c.mode === 'dirs' && scopeProblem(c.dirs))) return;
726
+ if (!c.grant && c.mode === 'whole') return grantTo(c.m, c.row, c.target);
727
+ const { m, grant, row, target } = c, sh = shareOf(m), restrict = c.mode === 'dirs' ? { dirs: c.dirs.map(({ path, access }) => ({ path, access })) } : null;
728
+ c.busy = true; c.problem = null;
729
+ drawForm();
730
+ // 记着这次写:回应超时了才登记(授予是一行待确认的授权,改范围是授权行上的待确认)。晚到的回应、列表核对都按它收尾。
731
+ const unknown = grant ? { restrict, unknown: true } : { friend: row.author, target: { id: target.id, name: target.name }, state: 'granting', restrict, unknown: true };
732
+ const kept = () => (grant ? sh.rescoping.get(grant.grant) === unknown : sh.pending.includes(unknown));
733
+ const lose = text => { if (grant) sh.rescoping.set(grant.grant, { error: text }); else Object.assign(unknown, { state: 'denied', reason: text, unknown: false }); };
734
+ const late = reply => {
735
+ if (!kept()) return;
736
+ beginWrite(sh);
737
+ if (reply.value) { mergeGrant(sh, reply.value); if (grant) sh.rescoping.delete(grant.grant); else sh.pending = sh.pending.filter(p => p !== unknown); } else lose(problemOf({ dirs: c.dirs }, reply.failure).text);
738
+ endWrite(m);
739
+ readGrants(m);
740
+ draw();
741
+ };
742
+ if (grant) sh.rescoping.delete(grant.grant);
743
+ beginWrite(sh);
744
+ let made, failure;
745
+ try { made = await ask(m, grant ? 'grants.restrict' : 'grants.grant', grant ? { grant: grant.grant, restrict } : { friend: row.author, target: { kind: MACHINE_KIND, id: target.id }, restrict }, late, PROBE_WAIT_MS); } catch (e) { failure = e; }
746
+ endWrite(m);
747
+ c.busy = false;
748
+ if (made) mergeGrant(sh, made);
749
+ if (failure && !failure.code && !failure.refused) {
750
+ // 没有回应:不知道有没有写成。表单关掉,那一行显示待确认;晚到的回应与后台读列表谁先有结果听谁的。
751
+ if (grant) sh.rescoping.set(grant.grant, unknown); else sh.pending = [...sh.pending.filter(p => !(p.friend === unknown.friend && p.target.id === target.id)), unknown];
752
+ if (picker.ctx === c) closePicker();
753
+ recover(m);
754
+ } else if (picker.ctx === c) { if (made) closePicker(); else { c.problem = problemOf(c, failure); drawForm(); } }
755
+ draw();
756
+ }
757
+ function noticeOf(c) {
758
+ if (c.busy) return h('p', { class: 'progress' }, c.mode === 'dirs' ? '正在目标机上探测这些目录,最多约 30 秒,请稍候…' : '正在保存…');
759
+ return c.problem ? h('div', { class: 'warn-box', role: 'alert' }, h('div', {}, c.problem.text), c.problem.detail && c.problem.detail !== c.problem.text ? h('div', { class: 'detail selectable' }, c.problem.detail) : null) : null;
760
+ }
761
+ // 输入时只更新校验说明与确认按钮,不重建输入框。
762
+ function refreshForm() {
763
+ const c = picker.ctx, bad = c.mode === 'dirs' ? scopeProblem(c.dirs) : null;
764
+ if (c.form.hint) { c.form.hint.textContent = bad ?? ''; c.form.hint.hidden = !bad; }
765
+ c.form.confirm.disabled = c.busy || Boolean(bad);
766
+ c.form.confirm.textContent = c.busy ? (c.mode === 'dirs' ? '正在探测…' : '正在保存…') : c.grant ? '保存范围' : '授予';
767
+ fill(c.form.notice, noticeOf(c));
768
+ }
769
+ function dirRow(c, dir, i) {
770
+ const path = h('input', { type: 'text', class: 'mono', placeholder: '目标机上的绝对路径,如 /Users/me/work', autocomplete: 'off', spellcheck: 'false', 'aria-label': `第 ${i + 1} 行的路径`, disabled: c.busy,
771
+ oninput: e => { dir.path = e.target.value; refreshForm(); } });
772
+ path.value = dir.path;
773
+ const access = h('select', { 'aria-label': `第 ${i + 1} 行的权限`, disabled: c.busy, onchange: e => { dir.access = e.target.value; refreshForm(); } },
774
+ h('option', { value: 'rw' }, ACCESS.rw), h('option', { value: 'ro' }, ACCESS.ro));
775
+ access.value = dir.access;
776
+ return h('li', { class: `dir-row${c.problem?.rows?.includes(dir) ? ' bad' : ''}` }, path, access,
777
+ h('button', { class: 'btn quiet small', type: 'button', 'aria-label': `删除第 ${i + 1} 行`, disabled: c.busy, onclick: () => { c.dirs.splice(c.dirs.indexOf(dir), 1); c.problem = null; drawForm(); } }, '删除'));
778
+ }
779
+ function drawForm() {
780
+ const c = picker.ctx, { m, row, target } = c, modify = Boolean(c.grant), dirsMode = c.mode === 'dirs', scope = scopeNote(certifiedOf(m, row));
781
+ const option = (mode, label, note, off) => h('label', { class: `opt${c.mode === mode ? ' on' : ''}${off ? ' off' : ''}` },
782
+ h('input', { type: 'radio', name: 'scope', checked: c.mode === mode, disabled: off || c.busy, onchange: () => { c.mode = mode; c.problem = null; drawForm(); } }),
783
+ h('span', { class: 'g-info' }, h('span', { class: 'g-name' }, label), h('span', { class: 'g-sub' }, note)));
784
+ // 仅限目录只有 macOS 的目标机能用;已经是仅限目录的授权,选项不灰(灰了就没法留在原范围)。
785
+ const off = target.restrictHint !== true && !dirsMode;
786
+ c.form = { hint: dirsMode ? h('p', { class: 'hint', role: 'status' }) : null, notice: h('div', { 'aria-live': 'polite' }), confirm: h('button', { class: 'btn', type: 'button', onclick: confirmScope }) };
787
+ picker.dialog.heading.textContent = modify ? '修改范围' : '授予远程执行';
788
+ fill(picker.dialog.body, h('div', { class: 'stack scope-form' },
789
+ h('div', { class: 'target-box' }, h('span', { class: 'g-name truncate' }, target.name), target.os ? h('span', { class: 'g-sub truncate' }, `${target.os} · ${target.user}`) : null, scope ? h('span', { class: 'g-sub truncate' }, scope) : null),
790
+ h('div', { class: 'opts', role: 'radiogroup', 'aria-label': '范围' },
791
+ option('whole', '整台机器', '等同于登录这台机器上的这个账号'),
792
+ option('dirs', '仅限目录', off ? `第一期只支持 macOS 的机器${target.os ? `(这台是 ${target.os})` : ''}` : 'TA 的命令只能读写下面列出的目录(外加系统运行所需的只读路径和本次专用的临时目录);家目录里其余文件的内容、~/.ssh、Coda 数据读写不到', off)),
793
+ dirsMode ? h('div', { class: 'dirs-edit' }, h('ul', { class: 'glist' }, c.dirs.map((dir, i) => dirRow(c, dir, i))),
794
+ h('button', { class: 'btn quiet small', type: 'button', disabled: c.busy, onclick: () => { c.dirs.push(blankDir('ro')); c.problem = null; drawForm(); } }, '添加目录'), c.form.hint) : null,
795
+ c.form.notice,
796
+ h('div', { class: 'actions' }, c.form.confirm, modify ? null : h('button', { class: 'btn quiet', type: 'button', disabled: c.busy, onclick: () => { c.stage = 'list'; fill(picker.dialog.body, picker.list); picker.dialog.heading.textContent = '授予远程执行'; drawPicker(); } }, '换一台机器'))));
797
+ refreshForm();
798
+ }
616
799
 
617
800
  // ---- 网络节点 ----
618
801
  const canNet = () => typeof coda.friendNodes === 'function';
@@ -772,10 +955,11 @@ function drawSection({ member: m, title, unreachable, rows }) {
772
955
 
773
956
  const page = h('div', { class: 'page' });
774
957
  function draw() {
775
- const sections = friendSections(members);
958
+ const titles = memberTitles(members), sections = friendSections(members, titles);
959
+ drawn = sections;
776
960
  const ids = identities(live);
777
961
  if (!ids.length) ids.push({ author: null, signer: null, members: [] });
778
- fill(page, ids.map(id => drawHero(id, sections)), sections.map(drawSection));
962
+ fill(page, ids.map(id => drawHero(id, sections, titles)), sections.map(drawSection));
779
963
  if (state.detail) { if (detailRow()) drawDetail(); else closeDialog(); }
780
964
  drawPicker();
781
965
  if (netView) drawNet();
package/view/style.css CHANGED
@@ -188,6 +188,32 @@ details[open] > summary { margin-bottom: 10px; }
188
188
  .pick { width: 100%; display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line); background: var(--card); text-align: left; }
189
189
  .pick .why { font-size: .85em; color: var(--orange); }
190
190
 
191
+ /* 授予、修改范围的表单;授权行、代理记录、操作记录里的范围(长路径折行、点开看全部) */
192
+ .target-box { display: flex; flex-direction: column; min-width: 0; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line); background: var(--card); }
193
+ .opts { display: flex; flex-direction: column; gap: 8px; }
194
+ .opt { display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line); background: var(--card); }
195
+ .opt.on { border-color: var(--accent); }
196
+ .opt.off { opacity: .65; }
197
+ .opt input { flex: none; width: auto; margin-top: 3px; }
198
+ .dirs-edit { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; }
199
+ .dirs-edit > .glist { width: 100%; }
200
+ .dir-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
201
+ .dir-row input { flex: 1 1 100%; }
202
+ .dir-row select { flex: none; padding: 7px 8px; border-radius: var(--coda-radius, 9px); border: 1px solid var(--line); background: var(--bg); color: var(--fg); }
203
+ .dir-row.bad input { border-color: var(--red); }
204
+ .warn-box .detail { margin-top: 4px; font-size: .9em; opacity: .85; overflow-wrap: anywhere; }
205
+ .scope > summary { display: flex; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
206
+ .scope > summary::after { content: "\00a0▾"; flex: none; }
207
+ .scope .sum-main { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
208
+ .scope .sum-tail { flex: none; }
209
+ .scope[open] > summary { display: block; margin-bottom: 4px; white-space: normal; }
210
+ .scope[open] .sum-main { display: inline; overflow: visible; overflow-wrap: anywhere; }
211
+ .scope[open] > summary::after { content: "\00a0▴"; }
212
+ .dirs { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: .85em; }
213
+ .dirs li { display: flex; align-items: flex-start; gap: 8px; min-width: 0; }
214
+ .dirs .tag { flex: none; }
215
+ .dirs .mono { min-width: 0; overflow-wrap: anywhere; }
216
+
191
217
  /* 网络节点:分节标题行右端的图标按钮、抽屉里的分组与行、待移除块 */
192
218
  .sec .kebab { margin: -6px -6px -6px 0; }
193
219
  .page > section > .netblock { margin-top: 16px; }
package/lib/nickname.mjs DELETED
@@ -1,43 +0,0 @@
1
- // 由 Accord 公钥派生展示昵称(算法见 coda#3040):浏览器与 Node 通用,只用纯 JS 与 Uint8Array,不碰 Buffer 或 node:*。
2
-
3
- const AUTHOR = /^ed25519:([0-9a-f]{64})$/;
4
- const GROUPS = 36;
5
-
6
- /** 密钥的短码:`ed25519:` 之后的前 8 位(没有就空串)。 */
7
- export function shortAuthor(author) {
8
- const match = AUTHOR.exec(author ?? '');
9
- return match ? match[1].slice(0, 8) : '';
10
- }
11
-
12
- /**
13
- * 32 字节公钥的昵称:256 位从第 0 字节最高位起每 7 位一组,至多 36 组。0–77 是字母(v % 26),78–87 是数字,
14
- * 88–127 是结束符:已有不足 2 位时跳过,够 2 位就结束。读完仍不足 2 位给空串。
15
- */
16
- export function nicknameOf(key) {
17
- let name = '';
18
- for (let group = 0; group < GROUPS; group++) {
19
- let v = 0;
20
- for (let bit = group * 7; bit < group * 7 + 7; bit++) v = (v << 1) | ((key[bit >> 3] >> (7 - (bit & 7))) & 1);
21
- if (v < 78) name += String.fromCharCode(97 + (v % 26));
22
- else if (v < 88) name += String(v - 78);
23
- else if (name.length >= 2) return name;
24
- }
25
- return name.length >= 2 ? name : '';
26
- }
27
-
28
- /** 32 字节公钥按大端无符号整数转成十进制,左侧补零到 78 位。 */
29
- export const tailOf = key => BigInt(`0x${[...key].map(byte => byte.toString(16).padStart(2, '0')).join('')}`).toString().padStart(78, '0');
30
-
31
- /**
32
- * 好友与本机身份的展示名:合法公钥且解得出昵称给 `昵称 #尾号`(尾号是 tail 的末 4 位);合法公钥解不出昵称给公钥短码;
33
- * 没有合法公钥(如待互认的好友)给 fallbackNode。
34
- */
35
- export function identityTitle(author, fallbackNode = '') {
36
- const hex = AUTHOR.exec(author ?? '')?.[1];
37
- if (hex) {
38
- const key = Uint8Array.from({ length: 32 }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16));
39
- const name = nicknameOf(key);
40
- return name ? `${name} #${tailOf(key).slice(-4)}` : shortAuthor(author);
41
- }
42
- return fallbackNode;
43
- }