@vibelord/lanes 1.7.2 → 1.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/package.json +1 -1
- package/payload/lanes/VERSION +1 -1
- package/payload/lanes/bin/lanes +97 -17
- package/payload/lanes/bin/lanes-site-serve +15 -0
- package/payload/lanes/bin-rs/BINARIES.json +5 -0
- package/payload/lanes/container/lane-mcp +105 -5
- package/payload/lanes/container/lane_core.py +110 -0
- package/payload/lanes/container/throttle-pulse +159 -14
- package/payload/lanes/docs/ARCHITECTURE.md +108 -11
- package/payload/lanes/docs/DESIGN.md +10 -8
- package/payload/lanes/docs/INSTALL.md +1 -1
- package/payload/lanes/docs/RUNBOOK.md +297 -5
- package/payload/lanes/docs/USERGUIDE.md +11 -6
- package/payload/lanes/install/host-install.sh +14 -3
- package/payload/lanes/libexec/adopt.py +325 -0
- package/payload/lanes/libexec/cutover.py +656 -0
- package/payload/lanes/libexec/docsd.py +12 -8
- package/payload/lanes/libexec/doctor_lanes2.py +213 -0
- package/payload/lanes/libexec/economy_poll.py +87 -2
- package/payload/lanes/libexec/lanes_lib.py +465 -2
- package/payload/lanes/libexec/native.sh +38 -0
- package/payload/lanes/libexec/native_bin.py +668 -0
- package/payload/lanes/libexec/shadow.py +1311 -0
- package/payload/lanes/libexec/sidebar.py +269 -28
- package/payload/lanes/libexec/sidebar_status.py +373 -25
- package/payload/lanes/libexec/statusd.py +67 -3
- package/payload/lanes/libexec/tokens.py +99 -131
- package/payload/lanes/libexec/tokens.sh +1 -1
- package/payload/lanes/libexec/update.py +48 -5
- package/payload/lanes/libexec/users.py +282 -0
- package/payload/lanes/site/README.md +9 -0
- package/payload/lanes/site/conformance.py +280 -0
- package/payload/lanes/site/protocol.py +368 -0
- package/payload/lanes/site/server.py +314 -0
- package/payload/lanes/tokens/README.md +156 -0
- package/payload/lanes/tokens/generate.py +930 -0
- package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
- package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
- package/payload/lanes/tokens/tokens.v1.json +763 -0
- package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
- package/payload/lanes/web/README.md +132 -4
- package/payload/lanes/web/directory.css +95 -0
- package/payload/lanes/web/directory.js +951 -0
- package/payload/lanes/web/generated/README.md +107 -0
- package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
- package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
- package/payload/lanes/web/mobile.js +17 -21
- package/payload/lanes/web/tokens.css +137 -0
- package/payload/manifest.json +7 -4
|
@@ -0,0 +1,951 @@
|
|
|
1
|
+
// The Lanes 2.0 lane directory in the browser (fan-out lane F3; integrated cockpit §5.1; witnesses A24-A27). Loaded
|
|
2
|
+
// on demand: mobile.js appends this file only when the page's fragment is `#lanes` or a resume link `#lane=<identity>`,
|
|
3
|
+
// on a phone, a tablet and a desktop alike; index.html never lists it. Two halves share one renderer. laneDirectory()
|
|
4
|
+
// is the conformance kit's evaluation (lanes/tests/conformance), which the node suite replays. The page draws the
|
|
5
|
+
// owner's LaneDirectoryProjection (crates/lanes-protocol; docs/contracts/lanes2/schema) as delivered: it never derives
|
|
6
|
+
// sections, order or action reasons of its own, and it writes the frozen PreferencesUpdate and Command documents.
|
|
7
|
+
// Design notes and the Day-0 gaps: web/README.md, "Lane directory".
|
|
8
|
+
|
|
9
|
+
/** @typedef {{status: (string|null), since: number, stable_since: number}} AgentFact */
|
|
10
|
+
/** @typedef {{connection: string, connection_kind: ('direct'|'relay'), authority: string, host_instance: string,
|
|
11
|
+
* workspace: string, lane: string, name: string, registration: ('declared'|'registered_session'|'unregistered'),
|
|
12
|
+
* declared_in?: string, closable?: boolean, source_revision: number, native_generation: string,
|
|
13
|
+
* agent: (AgentFact|null)}} Observation */
|
|
14
|
+
/** @typedef {{revision: number, pins: string[], hidden: string[], seen_done: Object<string, number>,
|
|
15
|
+
* board_order?: string[], theme?: {id: string, revision: number}}} Preferences */
|
|
16
|
+
/** @typedef {{authority: string, workspace: string, label: string}} Filter */
|
|
17
|
+
/** @typedef {{principal: string, device_owner: boolean, filter: (Filter|null), preferences: Preferences,
|
|
18
|
+
* preference_updates?: Preferences[], observations: Observation[]}} DirectoryInput */
|
|
19
|
+
/** @typedef {{available: boolean, reason: (string|null)}} Action */
|
|
20
|
+
|
|
21
|
+
// A projection of lanes/tokens/tokens.v1.json (theme lanes/3): glyph, ASCII twin, tone role and the phone's label per
|
|
22
|
+
// agent state, and the marks the directory draws. tests/web/directory.test.mjs compares it with the JSON.
|
|
23
|
+
const LANES_DIRECTORY_TOKENS = {
|
|
24
|
+
theme: {id: 'lanes', revision: 3},
|
|
25
|
+
agent: {
|
|
26
|
+
needs_approval: ['◆', '!', 'tone-urgent', 'Needs approval'], needs_input: ['◇', '?', 'tone-attention', 'Needs you'],
|
|
27
|
+
working: ['▸', '>', 'tone-working', 'Working'], done: ['✓', 'v', 'tone-done', 'Done'],
|
|
28
|
+
errored: ['✗', 'X', 'tone-urgent', 'Error'], shell: ['_', '_', 'ink-dim', 'Shell'], idle: ['·', '.', 'ink-dim', 'Idle'],
|
|
29
|
+
},
|
|
30
|
+
marks: {pinned: ['▲', '^', 'accent'], stale: ['?', '?', 'ink-dim'], sep: ['·', '-', 'ink-dim']},
|
|
31
|
+
};
|
|
32
|
+
const SECTIONS = ['needs', 'working', 'done', 'rest', 'unregistered'];
|
|
33
|
+
// The attention queue of lanes/libexec/sidebar.py (ATTENTION, ALWAYS_DRAWN) and statusd's section table.
|
|
34
|
+
const ATTENTION = [['needs', 'Needs you', ['needs_approval', 'errored', 'needs_input']], ['working', 'Working', ['working']],
|
|
35
|
+
['done', 'Done', ['done']]];
|
|
36
|
+
const ALWAYS_DRAWN = ['needs', 'working'];
|
|
37
|
+
const SECTION_OF = {needs_approval: 'needs', errored: 'needs', needs_input: 'needs', working: 'working', done: 'done'};
|
|
38
|
+
const NEEDS_RANK = {needs_approval: 0, errored: 1, needs_input: 2};
|
|
39
|
+
const CONNECTION_FIELDS = ['connection', 'connection_kind'];
|
|
40
|
+
const ALL_LANES = 'All lanes';
|
|
41
|
+
// Unavailable-reason codes (the kit's) and the words a person reads for them.
|
|
42
|
+
const REASON_TEXT = {
|
|
43
|
+
not_registered: 'Only a registered lane can be pinned or hidden', no_owner_profile: 'This device has no owner: lanes device claim',
|
|
44
|
+
registered_unregister_first: 'Registered: unregister it first', not_closable: 'Nothing to close',
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
class DirectoryError extends Error {}
|
|
48
|
+
|
|
49
|
+
const identityOf = o => `${o.authority}/${o.workspace}/${o.lane}`;
|
|
50
|
+
const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
51
|
+
const has = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
52
|
+
const num = value => (typeof value === 'number' ? value : null);
|
|
53
|
+
// Python's json.dumps(sort_keys=True), which the kit runner compares documents by.
|
|
54
|
+
const canonical = value => Array.isArray(value) ? `[${value.map(canonical).join(',')}]`
|
|
55
|
+
: value && typeof value === 'object'
|
|
56
|
+
? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`
|
|
57
|
+
: JSON.stringify(value);
|
|
58
|
+
const compare = (a, b) => {
|
|
59
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
|
|
60
|
+
return a.length - b.length;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// The document with the highest revision. Every revision is grouped before the choice, so two different documents at
|
|
64
|
+
// one revision are refused in any arrival order, also below the winning revision.
|
|
65
|
+
function newest(docs, what, key, skip = []) {
|
|
66
|
+
const byRevision = new Map();
|
|
67
|
+
for (const doc of docs) {
|
|
68
|
+
const content = canonical(Object.fromEntries(Object.entries(doc).filter(([field]) => !skip.includes(field))));
|
|
69
|
+
if (!byRevision.has(doc[key])) byRevision.set(doc[key], new Set());
|
|
70
|
+
byRevision.get(doc[key]).add(content);
|
|
71
|
+
}
|
|
72
|
+
for (const [revision, contents] of [...byRevision].sort((a, b) => a[0] - b[0])) {
|
|
73
|
+
if (contents.size > 1) throw new DirectoryError(`${what}: two different documents at revision ${revision}`);
|
|
74
|
+
}
|
|
75
|
+
const top = Math.max(...byRevision.keys());
|
|
76
|
+
return docs.find(doc => doc[key] === top);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// {identity: {obs, through}}: one row per authority-qualified identity, never per name, address, port or session id;
|
|
80
|
+
// relayed copies collapse with direct ones to the newest source revision.
|
|
81
|
+
function merge(observations) {
|
|
82
|
+
const groups = new Map();
|
|
83
|
+
for (const obs of observations) {
|
|
84
|
+
const id = identityOf(obs);
|
|
85
|
+
if (!groups.has(id)) groups.set(id, []);
|
|
86
|
+
groups.get(id).push(obs);
|
|
87
|
+
}
|
|
88
|
+
const merged = new Map();
|
|
89
|
+
for (const [id, members] of groups) {
|
|
90
|
+
merged.set(id, {obs: newest(members, id, 'source_revision', CONNECTION_FIELDS),
|
|
91
|
+
through: [...new Set(members.map(obs => obs.connection))].sort()});
|
|
92
|
+
}
|
|
93
|
+
return merged;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The principal's preferences this device applies: the highest revision, or null on a device without an owner.
|
|
97
|
+
function appliedPreferences(input, themes) {
|
|
98
|
+
if (!(has(input, 'device_owner') ? input.device_owner : true)) return null;
|
|
99
|
+
const prefs = newest([input.preferences, ...(input.preference_updates || [])], 'preferences', 'revision');
|
|
100
|
+
const theme = prefs.theme;
|
|
101
|
+
if (theme != null && !(has(themes, theme.id) && themes[theme.id].includes(theme.revision))) {
|
|
102
|
+
throw new DirectoryError(`preferences: theme ${theme.id}/${theme.revision} is not in tokens.v1.json`);
|
|
103
|
+
}
|
|
104
|
+
return prefs;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The directory every client shows for one input (the kit's evaluation; sections, order, labels, counts and action
|
|
109
|
+
* reasons as lanes/libexec/sidebar.py draws them), run once over the whole filtered directory, never per workspace.
|
|
110
|
+
* @param {DirectoryInput} input
|
|
111
|
+
* @param {{themes?: Object<string, number[]>, stale?: Set<string>}} [options] the theme revisions the token source
|
|
112
|
+
* records; the authorities whose rows are kept stale (known, authorized, not refreshed)
|
|
113
|
+
*/
|
|
114
|
+
function laneDirectory(input, {themes = {lanes: [LANES_DIRECTORY_TOKENS.theme.revision]}, stale = new Set()} = {}) {
|
|
115
|
+
const observations = input.observations;
|
|
116
|
+
const scope = input.filter && Object.keys(input.filter).length ? input.filter : null;
|
|
117
|
+
const kept = scope ? observations.filter(o => o.authority === scope.authority && o.workspace === scope.workspace)
|
|
118
|
+
: observations.slice();
|
|
119
|
+
const label = scope ? scope.label : ALL_LANES;
|
|
120
|
+
const merged = merge(kept);
|
|
121
|
+
const prefs = appliedPreferences(input, themes);
|
|
122
|
+
const p = prefs || {};
|
|
123
|
+
const pins = new Set(p.pins || []), hidden = new Set(p.hidden || []), seen = p.seen_done || {};
|
|
124
|
+
const entries = [...merged].map(([id, {obs}]) => ({id, obs})).sort(byId);
|
|
125
|
+
const registered = entries.filter(e => e.obs.registration !== 'unregistered');
|
|
126
|
+
const unregistered = entries.filter(e => e.obs.registration === 'unregistered');
|
|
127
|
+
const shown = hidden.size ? registered.filter(e => !hidden.has(e.id)) : registered;
|
|
128
|
+
const known = new Set(registered.map(e => e.id));
|
|
129
|
+
|
|
130
|
+
const fact = e => {
|
|
131
|
+
const agent = e.obs.agent && typeof e.obs.agent === 'object' ? e.obs.agent : {};
|
|
132
|
+
const status = has(LANES_DIRECTORY_TOKENS.agent, agent.status) ? agent.status : null;
|
|
133
|
+
if (status === null) return {status, entered: null, key: null};
|
|
134
|
+
const since = num(agent.since), entered = num(agent.stable_since);
|
|
135
|
+
let key = SECTION_OF[status] || null;
|
|
136
|
+
if (key === 'done' && has(seen, e.id) && (since || 0) <= seen[e.id]) key = null; // viewed since it finished
|
|
137
|
+
return {status, entered: entered === null ? since : entered, key};
|
|
138
|
+
};
|
|
139
|
+
const facts = shown.map(e => ({e, ...fact(e)}));
|
|
140
|
+
let agents = false, rest = [];
|
|
141
|
+
const buckets = {needs: [], working: [], done: []};
|
|
142
|
+
facts.forEach((f, index) => {
|
|
143
|
+
agents = agents || (f.status !== null && f.status !== 'shell');
|
|
144
|
+
if (f.key === null) return void rest.push(f.e);
|
|
145
|
+
const stamp = f.entered === null ? Infinity : f.entered;
|
|
146
|
+
const order = pins.has(f.e.id) ? [0, index] : f.key === 'needs' ? [1, NEEDS_RANK[f.status], stamp, index]
|
|
147
|
+
: f.key === 'working' ? [1, stamp, index] : [1, f.entered === null ? Infinity : -f.entered, index];
|
|
148
|
+
buckets[f.key].push({order, e: f.e});
|
|
149
|
+
});
|
|
150
|
+
if (pins.size) rest = [...rest.filter(e => pins.has(e.id)), ...rest.filter(e => !pins.has(e.id))];
|
|
151
|
+
const listed = [];
|
|
152
|
+
if (!agents) listed.push(...rest);
|
|
153
|
+
else {
|
|
154
|
+
for (const [key, title] of ATTENTION) {
|
|
155
|
+
const bucket = buckets[key].sort((a, b) => compare(a.order, b.order));
|
|
156
|
+
if (bucket.length || ALWAYS_DRAWN.includes(key)) {
|
|
157
|
+
listed.push({divider: key, name: `${title} (${bucket.length})`}, ...bucket.map(b => b.e));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (rest.length) listed.push({divider: 'rest', name: `${label} (${rest.length})`}, ...rest);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const ok = () => ({available: true, reason: null}), no = reason => ({available: false, reason});
|
|
164
|
+
const actions = ({id, obs}) => {
|
|
165
|
+
const arrange = () => (known.has(id) ? (prefs ? ok() : no('no_owner_profile')) : no('not_registered'));
|
|
166
|
+
const close = obs.closable ? ok() : ['declared', 'registered_session'].includes(obs.registration)
|
|
167
|
+
? no('registered_unregister_first') : no('not_closable');
|
|
168
|
+
return {pin: arrange(), hide: arrange(), close};
|
|
169
|
+
};
|
|
170
|
+
const rows = [], sections = [], position = {};
|
|
171
|
+
const add = (section, e) => {
|
|
172
|
+
const index = position[section] || 0, {obs} = e;
|
|
173
|
+
position[section] = index + 1;
|
|
174
|
+
rows.push({identity: e.id, section, order_key: [SECTIONS.indexOf(section), index], label: obs.name,
|
|
175
|
+
status: (obs.agent || {}).status ?? null, host_instance: obs.host_instance, native_generation: obs.native_generation,
|
|
176
|
+
observed_through: merged.get(e.id).through, actions: actions(e), authority: obs.authority, workspace: obs.workspace,
|
|
177
|
+
pinned: pins.has(e.id), stale: stale.has(obs.authority)});
|
|
178
|
+
};
|
|
179
|
+
let section = 'rest';
|
|
180
|
+
for (const item of listed) {
|
|
181
|
+
if (item.divider) sections.push({section: (section = item.divider), label: item.name, count: 0});
|
|
182
|
+
else add(section, item);
|
|
183
|
+
}
|
|
184
|
+
if (unregistered.length) {
|
|
185
|
+
sections.push({section: 'unregistered', label: `Unregistered (${unregistered.length})`, count: 0});
|
|
186
|
+
unregistered.forEach(e => add('unregistered', e));
|
|
187
|
+
}
|
|
188
|
+
for (const item of sections) item.count = position[item.section] || 0;
|
|
189
|
+
let needs = 0, working = 0, running = 0;
|
|
190
|
+
for (const e of shown) {
|
|
191
|
+
const f = fact(e);
|
|
192
|
+
needs += f.key === 'needs';
|
|
193
|
+
working += f.key === 'working';
|
|
194
|
+
running += f.status !== null && f.status !== 'shell';
|
|
195
|
+
}
|
|
196
|
+
return {directory_label: label, preferences_revision: prefs ? prefs.revision : null, theme: p.theme ?? null, rows,
|
|
197
|
+
sections, counts: {needs, working, agents: running, shells: shown.length - running, rows: rows.length,
|
|
198
|
+
observations: observations.length, filtered_out: observations.length - kept.length,
|
|
199
|
+
collapsed: kept.length - merged.size, hidden: registered.length - shown.length}};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ------------------------------------------------------------------------------------------------- identities and links
|
|
203
|
+
// The authority-qualified identity `authority/workspace/lane` in lanes-core's grammar (crates/lanes-core
|
|
204
|
+
// src/ident/grammar.rs): the authority a token of at most 64 bytes (`[A-Za-z0-9_][A-Za-z0-9_.:-]*`, the Day-0 row's
|
|
205
|
+
// bound), workspace and lane Lanes identifiers (`[A-Za-z0-9_][A-Za-z0-9_.-]*`) of at most 128 bytes, the legacy bound.
|
|
206
|
+
const IDENTITY = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,63}\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/;
|
|
207
|
+
const keyOf = lane => `${lane.authority}/${lane.workspace_id}/${lane.lane_id}`;
|
|
208
|
+
const laneOf = identity => { const [authority, workspace_id, lane_id] = identity.split('/'); return {authority, workspace_id, lane_id}; };
|
|
209
|
+
const linkFor = identity => `#lane=${encodeURIComponent(identity)}`;
|
|
210
|
+
// The words for an unavailable reason: a kit code's sentence, or the owner's own words as delivered.
|
|
211
|
+
const reasonText = reason => (has(REASON_TEXT, reason) ? REASON_TEXT[reason] : reason);
|
|
212
|
+
/** @returns {null|{open: true, identity: (string|null)}} what a fragment asks for */
|
|
213
|
+
function parseLink(hash) {
|
|
214
|
+
const text = String(hash || '');
|
|
215
|
+
if (text === '#lanes') return {open: true, identity: null};
|
|
216
|
+
if (!text.startsWith('#lane=')) return null;
|
|
217
|
+
let identity;
|
|
218
|
+
try { identity = decodeURIComponent(text.slice(6)); } catch { return {open: true, identity: null}; }
|
|
219
|
+
return {open: true, identity: IDENTITY.test(identity) ? identity : null};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ------------------------------------------------------------------------------------------------- device-local
|
|
223
|
+
// What this device keeps for itself (integrated cockpit §5.1): never part of the shared preference record, never
|
|
224
|
+
// broadcast, never authority. Appearance overrides are device-wide; the place in the directory is per principal.
|
|
225
|
+
const DEVICE_KEYS = {density: ['comfortable', 'compact'], glyphs: ['unicode', 'ascii']};
|
|
226
|
+
const PLACE_KEYS = ['filter', 'selection', 'scroll'];
|
|
227
|
+
const PREFIX = 'lanes:directory:';
|
|
228
|
+
function deviceLocal(storage) {
|
|
229
|
+
const keys = () => { try { return Array.from({length: storage.length}, (_, i) => storage.key(i)); } catch { return []; } };
|
|
230
|
+
const place = (principal, field) => `${PREFIX}${encodeURIComponent(principal)}:${field}`;
|
|
231
|
+
const read = key => { try { return storage ? storage.getItem(key) : null; } catch { return null; } };
|
|
232
|
+
const write = (key, value) => {
|
|
233
|
+
try { if (value == null) storage.removeItem(key); else storage.setItem(key, value); } catch {}
|
|
234
|
+
};
|
|
235
|
+
// `lanes:directory:<principal>:<field>`: a principal is URI-encoded, so it holds no `:`
|
|
236
|
+
const isPlace = key => typeof key === 'string' && key.startsWith(PREFIX) && key.slice(PREFIX.length).split(':').length === 2
|
|
237
|
+
&& PLACE_KEYS.includes(key.slice(key.lastIndexOf(':') + 1));
|
|
238
|
+
return {
|
|
239
|
+
device: field => { const value = read(PREFIX + field); return DEVICE_KEYS[field].includes(value) ? value : DEVICE_KEYS[field][0]; },
|
|
240
|
+
setDevice: (field, value) => DEVICE_KEYS[field].includes(value) && write(PREFIX + field, value),
|
|
241
|
+
place: (principal, field) => { try { return JSON.parse(read(place(principal, field))); } catch { return null; } },
|
|
242
|
+
setPlace: (principal, field, value) => PLACE_KEYS.includes(field) && write(place(principal, field), value == null ? null : JSON.stringify(value)),
|
|
243
|
+
// an account change: drop what this device kept about a principal's place
|
|
244
|
+
purge: principal => keys().filter(key => isPlace(key) && key.startsWith(place(principal, ''))).forEach(key => write(key, null)),
|
|
245
|
+
// a page's first principal: drop every other principal's place (a re-login that reloaded the page)
|
|
246
|
+
purgeOthers: principal => keys().filter(key => isPlace(key) && !key.startsWith(place(principal, ''))).forEach(key => write(key, null)),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ------------------------------------------------------------------------------------------------- Day-0 documents
|
|
251
|
+
// What the page reads of a Day-0 frame, checked as the generated decoder will check it (the shape, and the cross-field
|
|
252
|
+
// rules that decide what is drawn). Anything else is a malformed delivery that replaces nothing.
|
|
253
|
+
const WIRE_SECTION = {needs_you: 'needs', working: 'working', done_unseen: 'done', remaining: 'rest', unregistered: 'unregistered'};
|
|
254
|
+
const FRESHNESS = ['fresh', 'stale', 'unknown'];
|
|
255
|
+
const REMOVAL = ['removed', 'access_revoked', 'left_filter'];
|
|
256
|
+
const RESYNC = ['delivery_gap', 'cursor_expired', 'subscription_epoch_changed', 'protocol_epoch_changed',
|
|
257
|
+
'authorization_changed', 'filter_changed', 'lagged', 'resume_token_invalid'];
|
|
258
|
+
// The common activity projection read as a token state when the row's style_token names none (its vocabulary is not
|
|
259
|
+
// frozen yet; the Day-0 goldens use `lane.attention.approval`): an explicit question, approval or error first.
|
|
260
|
+
const ATTENTION_STATE = {approval: 'needs_approval', actionable_error: 'errored', input: 'needs_input'};
|
|
261
|
+
const ACTIVITY_STATE = {working: 'working', delegating: 'working', waiting_build: 'working', waiting_capacity: 'working',
|
|
262
|
+
finished: 'done'};
|
|
263
|
+
const isInt = value => Number.isSafeInteger(value) && value >= 0;
|
|
264
|
+
const isText = value => typeof value === 'string' && value.length > 0;
|
|
265
|
+
const bad = what => { throw new DirectoryError(what); };
|
|
266
|
+
const laneId = lane => (lane && typeof lane === 'object' && IDENTITY.test(keyOf(lane)) ? keyOf(lane)
|
|
267
|
+
: bad('a lane identity outside the identity grammar'));
|
|
268
|
+
|
|
269
|
+
/** One LaneDirectoryRow: {identity, row, actions: {name: {available, reason}}}. */
|
|
270
|
+
function decodeRow(row) {
|
|
271
|
+
if (!row || row.v !== 1) bad('a directory row without v 1');
|
|
272
|
+
const identity = laneId(row.lane);
|
|
273
|
+
if (!isText(row.label) || !has(WIRE_SECTION, row.section) || !Array.isArray(row.actions) || !Array.isArray(row.memberships)
|
|
274
|
+
|| !row.source || !FRESHNESS.includes(row.source.freshness) || !isInt(row.source.revision)) bad(`${identity}: a row the page cannot read`);
|
|
275
|
+
if (!row.memberships.some(m => m && m.workspace_id === row.lane.workspace_id)) bad(`${identity}: not a member of its own workspace`);
|
|
276
|
+
if (row.section === 'needs_you' && row.attention === 'none') bad(`${identity}: Needs you without a question, approval or error`);
|
|
277
|
+
const nb = row.native_binding;
|
|
278
|
+
if (nb != null && !(isText(nb.runtime_instance_id) && isText(nb.native_generation))) bad(`${identity}: a native binding without its generation`);
|
|
279
|
+
const actions = {};
|
|
280
|
+
for (const a of row.actions) {
|
|
281
|
+
if (!a || !isText(a.action) || has(actions, a.action) || !isText(a.availability)) bad(`${identity}: an action unnamed or listed twice`);
|
|
282
|
+
const available = a.availability === 'available';
|
|
283
|
+
if (!available && !isText(a.reason)) bad(`${identity}: an unavailable action must say why`);
|
|
284
|
+
actions[a.action] = {available, reason: available ? null : a.reason};
|
|
285
|
+
}
|
|
286
|
+
return {identity, row, actions};
|
|
287
|
+
}
|
|
288
|
+
/** One snapshot page: its rows, after its envelope and directory header. */
|
|
289
|
+
function decodeSnapshot(s) {
|
|
290
|
+
const d = s && s.directory;
|
|
291
|
+
if (!s || s.v !== 1 || !isText(s.request_id) || !isText(s.subscription_stream_id) || !isInt(s.subscription_epoch)
|
|
292
|
+
|| !isText(s.source_cursor) || !isInt(s.delivery_sequence) || !isInt(s.page_index) || !d || d.v !== 1 || !d.scope
|
|
293
|
+
|| !isText(d.scope.principal_id) || !isInt(d.scope.authorization_epoch) || !isText(d.scope.runtime_instance_id)
|
|
294
|
+
|| !isInt(d.schema_revision) || !Array.isArray(d.sources) || !Array.isArray(d.rows) || !d.counts || !isInt(d.counts.total)
|
|
295
|
+
|| !['complete', 'incomplete'].includes(d.completeness)) bad('a snapshot page the page cannot read');
|
|
296
|
+
if (d.sources.some(source => !source || !FRESHNESS.includes(source.freshness))) bad('a source without a known freshness');
|
|
297
|
+
if (d.completeness === 'complete' && d.sources.some(source => source.freshness !== 'fresh')) {
|
|
298
|
+
bad('a projection with a stale or unknown source cannot claim completeness');
|
|
299
|
+
}
|
|
300
|
+
const entries = d.rows.map(decodeRow), ids = new Set(entries.map(e => e.identity));
|
|
301
|
+
if (ids.size !== entries.length) bad('a lane appears twice in one page');
|
|
302
|
+
return entries;
|
|
303
|
+
}
|
|
304
|
+
/** PrincipalPresentationPreferences: the document and its pinned and hidden identities. */
|
|
305
|
+
function decodePreferences(p) {
|
|
306
|
+
if (!p || p.v !== 1 || !isText(p.principal_id) || !isInt(p.revision) || !p.theme || !Array.isArray(p.pinned)
|
|
307
|
+
|| !Array.isArray(p.hidden) || !Array.isArray(p.viewed_done) || !Array.isArray(p.board_order)) bad('a preference document the page cannot read');
|
|
308
|
+
const pinned = p.pinned.map(laneId), hidden = p.hidden.map(laneId);
|
|
309
|
+
if (new Set(pinned).size !== pinned.length || new Set(hidden).size !== hidden.length || pinned.some(id => hidden.includes(id))) {
|
|
310
|
+
bad('a preference set lists a lane twice, or pinned and hidden');
|
|
311
|
+
}
|
|
312
|
+
return {doc: p, pinned: new Set(pinned), hidden: new Set(hidden)};
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* The frozen PreferencesUpdate (preferences_update.schema.json): `v`, the revision it expects, and the whole current
|
|
316
|
+
* content (pinned, hidden, viewed_done, board_order, theme, resume) with one list toggled. A lane is never pinned and
|
|
317
|
+
* hidden at once, so hiding a pinned lane also unpins it.
|
|
318
|
+
*/
|
|
319
|
+
function preferencesUpdate(prefs, identity, verb) {
|
|
320
|
+
const {doc} = prefs, without = list => list.filter(lane => keyOf(lane) !== identity);
|
|
321
|
+
const content = {pinned: doc.pinned, hidden: doc.hidden, viewed_done: doc.viewed_done, board_order: doc.board_order, theme: doc.theme};
|
|
322
|
+
if (doc.resume) content.resume = doc.resume;
|
|
323
|
+
if (verb === 'pin') content.pinned = prefs.pinned.has(identity) ? without(doc.pinned) : [...doc.pinned, laneOf(identity)];
|
|
324
|
+
else if (prefs.hidden.has(identity)) content.hidden = without(doc.hidden);
|
|
325
|
+
else Object.assign(content, {hidden: [...doc.hidden, laneOf(identity)], pinned: without(doc.pinned)});
|
|
326
|
+
return {v: 1, expected_revision: doc.revision, preferences: content};
|
|
327
|
+
}
|
|
328
|
+
let minted = 0;
|
|
329
|
+
const mint = prefix => `${prefix}-${globalThis.crypto?.randomUUID?.() || `${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 10)}`}.${++minted}`;
|
|
330
|
+
const DEADLINE_MS = 15000;
|
|
331
|
+
/**
|
|
332
|
+
* The frozen Command envelope (command.schema.json) for a native action on one row: a fresh operation id, the
|
|
333
|
+
* transport's protocol and retry epochs, the target identity, the owner epoch and native generation it was issued
|
|
334
|
+
* against and the row revision the person saw (D06). The payload kind is the row's action name, which Day-0's
|
|
335
|
+
* CommandPayload does not list yet (an integrator request in the README).
|
|
336
|
+
*/
|
|
337
|
+
function commandFor(epochs, row, action, ownerEpoch) {
|
|
338
|
+
return {v: 1, request_id: mint('req'), operation_id: mint('op'), retry_epoch: epochs.retry_epoch,
|
|
339
|
+
protocol_epoch: epochs.protocol_epoch, target: laneOf(row.identity), expected_owner_epoch: ownerEpoch,
|
|
340
|
+
expected_native_generation: row.native_generation, expected_revision: row.revision, remaining_deadline_ms: DEADLINE_MS,
|
|
341
|
+
payload: {kind: action, args: {}}};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// ------------------------------------------------------------------------------------------------- controller
|
|
345
|
+
// The verbs a row offers, and the action name each reads on the owner's row (the Day-0 goldens name opening `attach`).
|
|
346
|
+
const VERBS = {open: 'attach', pin: 'pin', hide: 'hide', close: 'close'};
|
|
347
|
+
/**
|
|
348
|
+
* The directory's state under one authority. Source port (wired by the host's directory gateway, E7; absent in
|
|
349
|
+
* Lanes 2.0 Round 1, so the page says it is not connected): `subscribe(onFrame) -> cancel` delivering Day-0 frames
|
|
350
|
+
* `{frame: 'snapshot'|'event'|'resync'|'refused', body}` and the provisional `{frame: 'preferences', body:
|
|
351
|
+
* PrincipalPresentationPreferences}` and `{frame: 'read_horizon', body: {authorization_epoch, read_until_unix_ms}}`;
|
|
352
|
+
* `updatePreferences(PreferencesUpdate)` and `command(Command)`, each answering a frame; and the transport's
|
|
353
|
+
* negotiated `protocol_epoch` and `retry_epoch`. Subscription callbacks are bound to the subscription they were
|
|
354
|
+
* issued under, action answers to the authority (principal, authorization epoch, runtime, schema) and to the one
|
|
355
|
+
* request: anything older is dropped unread (A27).
|
|
356
|
+
*/
|
|
357
|
+
function createDirectory({source = null, storage = null, now = () => Date.now(), onChange = () => {},
|
|
358
|
+
timers = {set: (fn, ms) => (typeof globalThis.setTimeout === 'function' ? globalThis.setTimeout(fn, ms) : null),
|
|
359
|
+
clear: id => typeof globalThis.clearTimeout === 'function' && globalThis.clearTimeout(id)}} = {}) {
|
|
360
|
+
const local = deviceLocal(storage);
|
|
361
|
+
const st = {scope: null, cut: null, previous: null, prefs: null, refused: null, malformed: false, waiting: false,
|
|
362
|
+
horizon: null, owners: new Map(), revoked: new Set(), filter: null, selection: null, selectedLabel: '', tombstone: null, notice: '',
|
|
363
|
+
pending: {}, armed: null, showHidden: false, stream: 0, authority: 0, issued: 0, dropped: 0, cancel: null, timer: null};
|
|
364
|
+
const principal = () => st.scope && st.scope.principal_id;
|
|
365
|
+
const prefsNow = () => (st.prefs && principal() === st.prefs.doc.principal_id ? st.prefs : null);
|
|
366
|
+
const boardsOf = ({row}) => [...new Set([row.lane.workspace_id, ...row.memberships.map(m => m.workspace_id)])]
|
|
367
|
+
.map(workspace => `${row.lane.authority}/${workspace}`);
|
|
368
|
+
const staleRow = e => st.waiting || st.malformed || e.row.source.freshness !== 'fresh';
|
|
369
|
+
// The read authority of the rows on screen lapsed: non-fresh rows are no longer retained (IC §5.1).
|
|
370
|
+
const lapsed = at => !!(st.horizon && st.scope && st.horizon.authorization_epoch === st.scope.authorization_epoch
|
|
371
|
+
&& at > st.horizon.read_until_unix_ms);
|
|
372
|
+
const changed = () => { arm(); onChange(api); return api; };
|
|
373
|
+
// One directory-wide timer, never one per lane: a redraw when the read horizon of the stale rows passes.
|
|
374
|
+
function arm() {
|
|
375
|
+
if (st.timer != null) { try { timers.clear(st.timer); } catch {} st.timer = null; }
|
|
376
|
+
const h = st.horizon, at = now();
|
|
377
|
+
if (!h || !st.cut || !st.scope || h.authorization_epoch !== st.scope.authorization_epoch || at > h.read_until_unix_ms
|
|
378
|
+
|| !st.cut.entries.some(staleRow)) return;
|
|
379
|
+
st.timer = timers.set(() => { st.timer = null; changed(); }, h.read_until_unix_ms - at + 1);
|
|
380
|
+
}
|
|
381
|
+
// A new authority (account, authorization epoch, runtime or schema): every pending answer and armed close is void.
|
|
382
|
+
function newAuthority() {
|
|
383
|
+
st.authority++;
|
|
384
|
+
st.pending = {};
|
|
385
|
+
st.armed = null;
|
|
386
|
+
st.owners = new Map();
|
|
387
|
+
}
|
|
388
|
+
// A fresh subscription; a callback of an earlier one is dropped. Safe when the source delivers inside subscribe().
|
|
389
|
+
function resubscribe() {
|
|
390
|
+
const stream = ++st.stream;
|
|
391
|
+
if (st.cancel) { const cancel = st.cancel; st.cancel = null; try { cancel(); } catch {} }
|
|
392
|
+
if (!source) return;
|
|
393
|
+
const cancel = source.subscribe(frame => (stream === st.stream ? receive(frame) : void st.dropped++));
|
|
394
|
+
if (stream === st.stream) st.cancel = typeof cancel === 'function' ? cancel : null;
|
|
395
|
+
else if (typeof cancel === 'function') try { cancel(); } catch {}
|
|
396
|
+
}
|
|
397
|
+
const forget = (what, identity) => {
|
|
398
|
+
const who = principal();
|
|
399
|
+
if (st.selection === identity) { st.selection = null; st.selectedLabel = ''; }
|
|
400
|
+
if (who && local.place(who, what) === identity) local.setPlace(who, what, null);
|
|
401
|
+
};
|
|
402
|
+
// Identities and boards the principal could read before an authority change and cannot now are revoked, not lost:
|
|
403
|
+
// no tombstone names them, and no filter, selection, saved place or answer survives (A27).
|
|
404
|
+
function purgeRevoked(previous) {
|
|
405
|
+
const ids = new Set(st.cut.entries.map(e => e.identity)), boards = new Set(st.cut.entries.flatMap(boardsOf));
|
|
406
|
+
let gone = false;
|
|
407
|
+
for (const id of previous.ids) if (!ids.has(id)) { gone = true; st.revoked.add(id); forget('selection', id); }
|
|
408
|
+
const who = principal(), saved = who && local.place(who, 'filter');
|
|
409
|
+
for (const filter of [st.filter, saved]) {
|
|
410
|
+
if (filter && previous.boards.has(`${filter.authority}/${filter.workspace}`) && !boards.has(`${filter.authority}/${filter.workspace}`)) {
|
|
411
|
+
gone = true;
|
|
412
|
+
if (filter === st.filter) st.filter = null;
|
|
413
|
+
if (who) local.setPlace(who, 'filter', null);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
st.tombstone = null;
|
|
417
|
+
st.notice = gone ? 'A workspace is no longer available' : '';
|
|
418
|
+
}
|
|
419
|
+
const idsOf = cut => ({ids: new Set(cut.entries.map(e => e.identity)), boards: new Set(cut.entries.flatMap(boardsOf))});
|
|
420
|
+
|
|
421
|
+
function snapshot(s) {
|
|
422
|
+
const entries = decodeSnapshot(s), d = s.directory, scope = {...d.scope, schema_revision: d.schema_revision};
|
|
423
|
+
const current = st.scope, cut = st.cut;
|
|
424
|
+
const same = current && scope.principal_id === current.principal_id && scope.runtime_instance_id === current.runtime_instance_id
|
|
425
|
+
&& scope.schema_revision === current.schema_revision;
|
|
426
|
+
if (same && scope.authorization_epoch < current.authorization_epoch) { st.dropped++; return api; } // before a newer authority
|
|
427
|
+
const next = s.page_index > 0 && cut ? [...cut.entries, ...entries] : entries;
|
|
428
|
+
let renew = false;
|
|
429
|
+
if (s.page_index > 0 && (!cut || cut.complete || cut.stream !== s.subscription_stream_id || cut.request !== s.request_id
|
|
430
|
+
|| cut.epoch !== s.subscription_epoch || cut.cursor !== s.source_cursor || s.page_index !== cut.pages
|
|
431
|
+
|| s.delivery_sequence !== cut.sequence + 1 || !same || scope.authorization_epoch !== current.authorization_epoch
|
|
432
|
+
|| new Set(next.map(e => e.identity)).size !== next.length)) return gap(); // a page of no cut in hand: start again
|
|
433
|
+
if (!d.next_page && d.counts.total !== next.length) bad('a snapshot whose rows disagree with its counts');
|
|
434
|
+
if (s.page_index > 0) {
|
|
435
|
+
Object.assign(cut, {entries: next, pages: cut.pages + 1, sequence: s.delivery_sequence, header: d, complete: !d.next_page});
|
|
436
|
+
} else {
|
|
437
|
+
if (!current || scope.principal_id !== current.principal_id) { // an account change: nothing of the old one stays
|
|
438
|
+
if (current) local.purge(current.principal_id); else local.purgeOthers(scope.principal_id);
|
|
439
|
+
renew = !!current; // a fresh subscription: the old principal's deliveries in flight go unheard
|
|
440
|
+
newAuthority();
|
|
441
|
+
const link = !current && st.selection;
|
|
442
|
+
const filter = local.place(scope.principal_id, 'filter'), saved = local.place(scope.principal_id, 'selection');
|
|
443
|
+
Object.assign(st, {previous: null, tombstone: null, notice: '', horizon: null, selectedLabel: '', revoked: new Set(),
|
|
444
|
+
filter: filter && isText(filter.authority) && isText(filter.workspace) ? filter : null});
|
|
445
|
+
if (!link) st.selection = typeof saved === 'string' && IDENTITY.test(saved) ? saved : null;
|
|
446
|
+
} else if (!same || scope.authorization_epoch !== current.authorization_epoch) { // a new authority
|
|
447
|
+
if (!st.previous && cut && cut.complete) st.previous = idsOf(cut);
|
|
448
|
+
newAuthority();
|
|
449
|
+
}
|
|
450
|
+
st.cut = {stream: s.subscription_stream_id, request: s.request_id, epoch: s.subscription_epoch, cursor: s.source_cursor,
|
|
451
|
+
pages: 1, sequence: s.delivery_sequence, header: d, entries, complete: !d.next_page};
|
|
452
|
+
}
|
|
453
|
+
st.scope = scope;
|
|
454
|
+
st.refused = null;
|
|
455
|
+
st.malformed = false;
|
|
456
|
+
if (st.cut.complete) {
|
|
457
|
+
st.waiting = false;
|
|
458
|
+
if (st.previous) { purgeRevoked(st.previous); st.previous = null; }
|
|
459
|
+
}
|
|
460
|
+
if (renew) resubscribe();
|
|
461
|
+
return changed();
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function event(e) {
|
|
465
|
+
if (!e || e.v !== 1 || !isText(e.subscription_stream_id) || !isInt(e.delivery_sequence) || !isInt(e.owner_epoch)
|
|
466
|
+
|| !e.payload || !isText(e.payload.kind)) bad('an event the page cannot read');
|
|
467
|
+
const cut = st.cut;
|
|
468
|
+
if (!cut || !cut.complete || e.subscription_stream_id !== cut.stream) return gap(); // never a suffix without its prefix
|
|
469
|
+
if (e.delivery_sequence <= cut.sequence) { st.dropped++; return api; } // a harmless duplicate
|
|
470
|
+
if (e.delivery_sequence !== cut.sequence + 1) return gap();
|
|
471
|
+
const {kind, data} = e.payload;
|
|
472
|
+
if (kind === 'directory_row') {
|
|
473
|
+
const entry = decodeRow(data), at = cut.entries.findIndex(f => f.identity === entry.identity);
|
|
474
|
+
if (at < 0) cut.entries.push(entry); else cut.entries[at] = entry; // in place: the next snapshot orders it
|
|
475
|
+
st.revoked.delete(entry.identity);
|
|
476
|
+
st.owners.set(entry.identity, e.owner_epoch);
|
|
477
|
+
} else if (kind === 'directory_row_removed') {
|
|
478
|
+
const identity = laneId(data && data.lane);
|
|
479
|
+
if (!REMOVAL.includes(data.reason)) bad('a removal without a known reason');
|
|
480
|
+
cut.entries = cut.entries.filter(f => f.identity !== identity);
|
|
481
|
+
st.owners.delete(identity);
|
|
482
|
+
if (data.reason === 'access_revoked') revokeLane(identity);
|
|
483
|
+
}
|
|
484
|
+
cut.sequence = e.delivery_sequence;
|
|
485
|
+
return changed();
|
|
486
|
+
}
|
|
487
|
+
// One lane's read access ended: no tombstone, no selection, saved place, filter or answer of it stays.
|
|
488
|
+
function revokeLane(identity) {
|
|
489
|
+
st.revoked.add(identity);
|
|
490
|
+
const pending = {...st.pending};
|
|
491
|
+
delete pending[identity];
|
|
492
|
+
st.pending = pending;
|
|
493
|
+
if (st.armed && st.armed.identity === identity) st.armed = null;
|
|
494
|
+
if (st.tombstone && st.tombstone.identity === identity) st.tombstone = null;
|
|
495
|
+
forget('selection', identity);
|
|
496
|
+
const board = identity.split('/').slice(0, 2).join('/'), who = principal();
|
|
497
|
+
const empty = filter => filter && `${filter.authority}/${filter.workspace}` === board && !st.cut.entries.some(e => boardsOf(e).includes(board));
|
|
498
|
+
if (empty(st.filter)) st.filter = null;
|
|
499
|
+
if (who && empty(local.place(who, 'filter'))) local.setPlace(who, 'filter', null);
|
|
500
|
+
st.notice = 'A lane is no longer available';
|
|
501
|
+
}
|
|
502
|
+
// A delivery the stream cannot continue from: a fresh subscription; the rows stay, stale, until its snapshot.
|
|
503
|
+
function gap() {
|
|
504
|
+
st.waiting = true;
|
|
505
|
+
resubscribe();
|
|
506
|
+
return changed();
|
|
507
|
+
}
|
|
508
|
+
function resync(r) {
|
|
509
|
+
if (!r || r.v !== 1 || !RESYNC.includes(r.reason)) bad('a resync the page cannot read');
|
|
510
|
+
if (r.reason !== 'authorization_changed') return gap();
|
|
511
|
+
// nothing of the old authority stays on screen; what it could read is compared with the next complete snapshot
|
|
512
|
+
if (!st.previous && st.cut && st.cut.complete) st.previous = idsOf(st.cut);
|
|
513
|
+
newAuthority();
|
|
514
|
+
st.cut = null;
|
|
515
|
+
st.waiting = false;
|
|
516
|
+
resubscribe();
|
|
517
|
+
return changed();
|
|
518
|
+
}
|
|
519
|
+
function preferences(p) {
|
|
520
|
+
const next = decodePreferences(p), cur = st.prefs;
|
|
521
|
+
if (cur && cur.doc.principal_id === p.principal_id && p.revision <= cur.doc.revision) {
|
|
522
|
+
if (p.revision === cur.doc.revision && canonical(p) !== canonical(cur.doc)) bad('preferences: two different documents at one revision');
|
|
523
|
+
st.dropped += p.revision < cur.doc.revision;
|
|
524
|
+
return api;
|
|
525
|
+
}
|
|
526
|
+
st.prefs = next;
|
|
527
|
+
return changed();
|
|
528
|
+
}
|
|
529
|
+
function receive(frame) {
|
|
530
|
+
try {
|
|
531
|
+
const body = frame && frame.body;
|
|
532
|
+
switch (frame && frame.frame) {
|
|
533
|
+
case 'snapshot': return snapshot(body);
|
|
534
|
+
case 'event': return event(body);
|
|
535
|
+
case 'resync': return resync(body);
|
|
536
|
+
case 'preferences': return preferences(body);
|
|
537
|
+
case 'refused': st.refused = isText(body && body.reason) ? body.reason : 'no reason given'; return changed();
|
|
538
|
+
case 'read_horizon':
|
|
539
|
+
if (!body || !isInt(body.authorization_epoch) || !isInt(body.read_until_unix_ms)) bad('a read horizon the page cannot read');
|
|
540
|
+
st.horizon = {authorization_epoch: body.authorization_epoch, read_until_unix_ms: body.read_until_unix_ms};
|
|
541
|
+
return changed();
|
|
542
|
+
default: return bad('a frame the page does not know');
|
|
543
|
+
}
|
|
544
|
+
} catch (error) {
|
|
545
|
+
if (!(error instanceof DirectoryError)) throw error;
|
|
546
|
+
st.malformed = true;
|
|
547
|
+
return changed();
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function connect(next) {
|
|
552
|
+
source = next || null;
|
|
553
|
+
newAuthority();
|
|
554
|
+
st.cut = null;
|
|
555
|
+
resubscribe();
|
|
556
|
+
return changed();
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// The rows a person may see now, in the shape renderDirectory draws: the owner's rows in the owner's order and
|
|
560
|
+
// sections, narrowed by the visible filter, without the principal's hidden lanes unless they are shown.
|
|
561
|
+
function view() {
|
|
562
|
+
if (!source) return {state: 'unavailable'};
|
|
563
|
+
if (st.refused) return {state: 'refused', reason: st.refused};
|
|
564
|
+
const cut = st.cut;
|
|
565
|
+
if (!cut) return {state: st.malformed ? 'malformed' : 'loading'};
|
|
566
|
+
const at = now(), expired = lapsed(at), prefs = prefsNow();
|
|
567
|
+
// past the read horizon a stale row is no longer authorized: never kept, also not after a malformed delivery
|
|
568
|
+
const live = cut.entries.filter(e => !(expired && staleRow(e)));
|
|
569
|
+
const boards = new Map();
|
|
570
|
+
for (const e of live) for (const board of boardsOf(e)) boards.set(board, {authority: e.row.lane.authority, workspace: board.slice(board.indexOf('/') + 1)});
|
|
571
|
+
const names = [...boards.values()].map(b => b.workspace);
|
|
572
|
+
const options = [...boards].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([, b]) => ({...b,
|
|
573
|
+
label: names.indexOf(b.workspace) !== names.lastIndexOf(b.workspace) ? `${b.workspace} · ${b.authority}` : b.workspace}));
|
|
574
|
+
const filter = (st.filter && options.find(o => o.authority === st.filter.authority && o.workspace === st.filter.workspace)) || null;
|
|
575
|
+
const inFilter = e => !filter || boardsOf(e).includes(`${filter.authority}/${filter.workspace}`);
|
|
576
|
+
const kept = live.filter(inFilter), hidden = prefs ? prefs.hidden : new Set();
|
|
577
|
+
const isHidden = e => e.row.section !== 'unregistered' && hidden.has(e.identity);
|
|
578
|
+
// hidden lanes the owner left out of the rows: by identity alone, only on a board this directory shows and never
|
|
579
|
+
// one whose access was revoked
|
|
580
|
+
const orphans = [...hidden].filter(id => !kept.some(e => e.identity === id) && !st.revoked.has(id) && boards.has(id.split('/').slice(0, 2).join('/'))
|
|
581
|
+
&& (!filter || id.startsWith(`${filter.authority}/${filter.workspace}/`))).sort();
|
|
582
|
+
const hiddenCount = kept.filter(isHidden).length + orphans.length;
|
|
583
|
+
const label = filter ? filter.label : ALL_LANES;
|
|
584
|
+
const resolvable = cut.complete && cut.header.completeness === 'complete' && !st.waiting && !st.malformed && !expired;
|
|
585
|
+
const rowOf = e => {
|
|
586
|
+
const {row} = e, nb = row.native_binding || null, owner = st.owners.get(e.identity), hid = isHidden(e);
|
|
587
|
+
const action = verb => {
|
|
588
|
+
const offered = e.actions[VERBS[verb]] || (verb === 'open' && nb ? {available: true, reason: null}
|
|
589
|
+
: {available: false, reason: verb === 'open' ? 'No native session to open' : 'Not offered for this lane'});
|
|
590
|
+
if (!offered.available) return offered;
|
|
591
|
+
if (verb === 'pin' && hid) return {available: false, reason: 'Hidden: unhide it first'};
|
|
592
|
+
if ((verb === 'pin' || verb === 'hide') && !prefs) return {available: false, reason: 'Your preferences have not arrived'};
|
|
593
|
+
if ((verb === 'open' || verb === 'close') && !nb) return {available: false, reason: 'No native session'};
|
|
594
|
+
if ((verb === 'open' || verb === 'close') && owner === undefined) return {available: false, reason: "Waiting for this lane's owner"};
|
|
595
|
+
return offered;
|
|
596
|
+
};
|
|
597
|
+
return {identity: e.identity, section: WIRE_SECTION[row.section], label: row.label,
|
|
598
|
+
status: has(LANES_DIRECTORY_TOKENS.agent, row.style_token) ? row.style_token : ATTENTION_STATE[row.attention] || ACTIVITY_STATE[row.activity] || null,
|
|
599
|
+
host_instance: nb ? nb.runtime_instance_id : null, native_generation: nb ? nb.native_generation : null,
|
|
600
|
+
observed_through: [row.source.owner], revision: row.source.revision, authority: row.lane.authority,
|
|
601
|
+
workspace: row.lane.workspace_id, pinned: !!prefs && prefs.pinned.has(e.identity), hidden: hid, stale: staleRow(e),
|
|
602
|
+
actions: {open: action('open'), pin: action('pin'), hide: action('hide'), close: action('close')}};
|
|
603
|
+
};
|
|
604
|
+
const rows = kept.filter(e => !isHidden(e) || st.showHidden).map(rowOf);
|
|
605
|
+
for (const id of st.showHidden ? orphans : []) {
|
|
606
|
+
const lane = laneOf(id), hide = prefs ? {available: true, reason: null} : {available: false, reason: 'Your preferences have not arrived'};
|
|
607
|
+
const no = {available: false, reason: 'Unhide it to see it'};
|
|
608
|
+
rows.push({identity: id, section: 'hidden', label: lane.lane_id, status: null, host_instance: null, native_generation: null,
|
|
609
|
+
observed_through: [], revision: null, authority: lane.authority, workspace: lane.workspace_id, pinned: false, hidden: true,
|
|
610
|
+
stale: false, actions: {open: no, pin: no, hide, close: no}});
|
|
611
|
+
}
|
|
612
|
+
const shown = rows.filter(r => !r.hidden);
|
|
613
|
+
const tally = key => rows.filter(r => r.section === key).length;
|
|
614
|
+
const agents = shown.some(r => r.section !== 'unregistered' && r.status !== null && r.status !== 'shell');
|
|
615
|
+
const sections = [];
|
|
616
|
+
if (agents) {
|
|
617
|
+
for (const [key, title] of ATTENTION) if (tally(key) || ALWAYS_DRAWN.includes(key)) sections.push({section: key, label: `${title} (${tally(key)})`, count: tally(key)});
|
|
618
|
+
if (tally('rest')) sections.push({section: 'rest', label: `${label} (${tally('rest')})`, count: tally('rest')});
|
|
619
|
+
}
|
|
620
|
+
if (tally('unregistered')) sections.push({section: 'unregistered', label: `Unregistered (${tally('unregistered')})`, count: tally('unregistered')});
|
|
621
|
+
if (tally('hidden')) sections.push({section: 'hidden', label: `Hidden (${tally('hidden')})`, count: tally('hidden')});
|
|
622
|
+
const count = key => shown.filter(r => r.section === key).length;
|
|
623
|
+
const model = {directory_label: label, preferences_revision: prefs ? prefs.doc.revision : null, rows, sections,
|
|
624
|
+
counts: {rows: shown.length, needs: count('needs'), working: count('working'), hidden: hiddenCount, total: cut.header.counts.total}};
|
|
625
|
+
|
|
626
|
+
// A selection resolves only against a complete directory: an incomplete one does not prove a lane is gone.
|
|
627
|
+
const found = st.selection ? live.find(e => e.identity === st.selection) : null;
|
|
628
|
+
let notice = st.notice, pending = null;
|
|
629
|
+
if (st.selection && hidden.has(st.selection) && !st.showHidden) {
|
|
630
|
+
forget('selection', st.selection); // as in the sidebar, a hidden lane leaves the list
|
|
631
|
+
notice = st.notice = 'Hidden on every device: Show hidden brings it back';
|
|
632
|
+
} else if (st.selection && !found && !orphans.includes(st.selection)) {
|
|
633
|
+
if (!resolvable) pending = st.selection;
|
|
634
|
+
else {
|
|
635
|
+
if (st.selectedLabel) st.tombstone = {identity: st.selection, label: st.selectedLabel};
|
|
636
|
+
else notice = 'That lane is not available here';
|
|
637
|
+
forget('selection', st.selection);
|
|
638
|
+
}
|
|
639
|
+
} else if (found) {
|
|
640
|
+
st.selectedLabel = found.row.label;
|
|
641
|
+
if (principal() && local.place(principal(), 'selection') !== found.identity) local.setPlace(principal(), 'selection', found.identity);
|
|
642
|
+
}
|
|
643
|
+
if (st.armed && !rows.some(r => r.identity === st.armed.identity && r.native_generation === st.armed.native_generation)) st.armed = null;
|
|
644
|
+
return {state: 'ready', model, options, filter, malformed: st.malformed, waiting: st.waiting, expired,
|
|
645
|
+
incomplete: !resolvable, selection: st.selection, pendingSelection: pending, tombstone: st.tombstone, notice,
|
|
646
|
+
pending: Object.fromEntries(Object.entries(st.pending).map(([id, p]) => [id, p.verb])), armed: st.armed,
|
|
647
|
+
showHidden: st.showHidden, owner: !!prefs};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function setFilter(target) {
|
|
651
|
+
st.filter = target ? {authority: target.authority, workspace: target.workspace} : null;
|
|
652
|
+
if (principal()) local.setPlace(principal(), 'filter', st.filter);
|
|
653
|
+
st.notice = '';
|
|
654
|
+
return changed();
|
|
655
|
+
}
|
|
656
|
+
// Selecting a row is local: it moves no other device's focus, opens nothing and asks for no write or resize authority.
|
|
657
|
+
// It is kept once the lane is found; a link that arrives before the directory waits for it.
|
|
658
|
+
function select(identity) {
|
|
659
|
+
st.tombstone = null;
|
|
660
|
+
st.notice = '';
|
|
661
|
+
st.armed = null;
|
|
662
|
+
if (st.selection !== identity) st.selectedLabel = '';
|
|
663
|
+
st.selection = identity;
|
|
664
|
+
return changed();
|
|
665
|
+
}
|
|
666
|
+
const say = text => { st.notice = text; return changed(); };
|
|
667
|
+
const dismiss = () => { st.tombstone = null; return changed(); };
|
|
668
|
+
const toggleHidden = () => { st.showHidden = !st.showHidden; return changed(); };
|
|
669
|
+
const setScroll = top => principal() && local.setPlace(principal(), 'scroll', Math.max(0, Math.round(top) || 0));
|
|
670
|
+
const scroll = () => (principal() && local.place(principal(), 'scroll')) || 0;
|
|
671
|
+
|
|
672
|
+
// What an answer frame says to the person: nothing when it took, the owner's words when it did not.
|
|
673
|
+
function answerText(answer, request) {
|
|
674
|
+
const body = answer && answer.body;
|
|
675
|
+
if (!body) return '';
|
|
676
|
+
if (answer.frame === 'refused') return isText(body.reason) ? body.reason : 'Refused';
|
|
677
|
+
if (answer.frame === 'receipt') {
|
|
678
|
+
if (body.state === 'refused') return (body.outcome && body.outcome.detail && body.outcome.detail.reason) || 'Refused';
|
|
679
|
+
return body.state === 'outcome_unknown' ? 'The outcome is not known yet: check the lane before trying again' : '';
|
|
680
|
+
}
|
|
681
|
+
if (answer.frame === 'preferences') {
|
|
682
|
+
// the owner answers with its current document; one that does not carry the request was changed elsewhere
|
|
683
|
+
try { preferences(body); } catch (error) { if (!(error instanceof DirectoryError)) throw error; st.malformed = true; return ''; }
|
|
684
|
+
const took = ['pinned', 'hidden'].every(field => canonical(body[field].map(keyOf).sort()) === canonical(request.preferences[field].map(keyOf).sort()));
|
|
685
|
+
return took ? '' : 'Changed on another device: try again';
|
|
686
|
+
}
|
|
687
|
+
return '';
|
|
688
|
+
}
|
|
689
|
+
// A shared preference change goes to the preference owner as the frozen PreferencesUpdate, a native action to the
|
|
690
|
+
// lane's owner as the frozen Command; only the answer, and the next document or snapshot, change the rows.
|
|
691
|
+
function act(identity, verb) {
|
|
692
|
+
const v = view();
|
|
693
|
+
const row = v.state === 'ready' && !v.malformed && !v.waiting ? v.model.rows.find(r => r.identity === identity) : null;
|
|
694
|
+
if (verb !== 'close') st.armed = null;
|
|
695
|
+
if (!row) return say('That lane is not available here');
|
|
696
|
+
if (st.pending[identity]) return say('Still waiting for the last answer');
|
|
697
|
+
const action = row.actions[verb] || {available: false, reason: 'Not offered for this lane'};
|
|
698
|
+
if (!action.available) return say(reasonText(action.reason));
|
|
699
|
+
let request, call;
|
|
700
|
+
if (verb === 'open' || verb === 'close') {
|
|
701
|
+
if (verb === 'close' && !(st.armed && st.armed.identity === identity && st.armed.native_generation === row.native_generation)) {
|
|
702
|
+
st.armed = {identity, native_generation: row.native_generation}; // the first press only asks, for this generation
|
|
703
|
+
return say('');
|
|
704
|
+
}
|
|
705
|
+
if (typeof source.command !== 'function' || !isInt(source.protocol_epoch) || !isInt(source.retry_epoch)) return say('This connection cannot do that');
|
|
706
|
+
request = commandFor(source, row, VERBS[verb], st.owners.get(identity));
|
|
707
|
+
call = () => source.command(request);
|
|
708
|
+
} else {
|
|
709
|
+
if (typeof source.updatePreferences !== 'function') return say('This connection cannot do that');
|
|
710
|
+
request = preferencesUpdate(prefsNow(), identity, verb);
|
|
711
|
+
call = () => source.updatePreferences(request);
|
|
712
|
+
}
|
|
713
|
+
st.armed = null;
|
|
714
|
+
st.notice = '';
|
|
715
|
+
const token = ++st.issued, authority = st.authority;
|
|
716
|
+
st.pending = {...st.pending, [identity]: {verb, token}};
|
|
717
|
+
const done = answer => {
|
|
718
|
+
if (authority !== st.authority || !st.pending[identity] || st.pending[identity].token !== token) { st.dropped++; return undefined; }
|
|
719
|
+
const rest = {...st.pending};
|
|
720
|
+
delete rest[identity];
|
|
721
|
+
st.pending = rest;
|
|
722
|
+
const text = answerText(answer, request);
|
|
723
|
+
return text ? say(text) : changed();
|
|
724
|
+
};
|
|
725
|
+
Promise.resolve().then(call).then(done, error => done({frame: 'refused', body: {reason: (error && error.message) || 'Refused'}}));
|
|
726
|
+
return changed();
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
const api = {state: st, receive, connect, view, setFilter, select, dismiss, act, say, setScroll, scroll, toggleHidden,
|
|
730
|
+
device: local.device, setDevice: (field, value) => { local.setDevice(field, value); return changed(); }};
|
|
731
|
+
return api;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// ------------------------------------------------------------------------------------------------- rendering
|
|
735
|
+
const DRAWN = [...SECTIONS, 'hidden'];
|
|
736
|
+
/**
|
|
737
|
+
* Draw a view into `root` (the directory's own element): the same rows, sections, labels, actions and reasons in the
|
|
738
|
+
* phone picker, the tablet panel and the desktop overlay; the mode changes only the geometry (directory.css).
|
|
739
|
+
* Returns the drawn controls by their `data-focus` key, so the page can keep the keyboard on the same control.
|
|
740
|
+
*/
|
|
741
|
+
function renderDirectory(doc, root, view, ui, {glyphs = 'unicode'} = {}) {
|
|
742
|
+
const focus = new Map();
|
|
743
|
+
const el = (tag, cls, text) => {
|
|
744
|
+
const node = doc.createElement(tag);
|
|
745
|
+
if (cls) node.className = cls;
|
|
746
|
+
if (text !== undefined) node.textContent = text;
|
|
747
|
+
return node;
|
|
748
|
+
};
|
|
749
|
+
const keyed = (node, key) => { node.setAttribute('data-focus', key); focus.set(key, node); return node; };
|
|
750
|
+
const glyph = (table, key) => LANES_DIRECTORY_TOKENS[table][key][glyphs === 'ascii' ? 1 : 0];
|
|
751
|
+
const buttonOf = (cls, text, label, action, key) => {
|
|
752
|
+
const b = el('button', cls, text);
|
|
753
|
+
b.type = 'button';
|
|
754
|
+
if (label) b.setAttribute('aria-label', label);
|
|
755
|
+
b.addEventListener('click', action);
|
|
756
|
+
return keyed(b, key);
|
|
757
|
+
};
|
|
758
|
+
const head = el('header', 'lanes-directory-head');
|
|
759
|
+
const title = el('h2', '', view.state === 'ready' ? view.model.directory_label : 'Lanes');
|
|
760
|
+
title.id = 'lanes-directory-title';
|
|
761
|
+
const count = el('p', 'lanes-directory-count');
|
|
762
|
+
if (view.state === 'ready') {
|
|
763
|
+
const c = view.model.counts;
|
|
764
|
+
count.textContent = `${c.rows} ${c.rows === 1 ? 'lane' : 'lanes'}${c.needs ? ` · ${c.needs} need you` : ''}${c.working ? ` · ${c.working} working` : ''}${c.hidden ? ` · ${c.hidden} hidden` : ''}`;
|
|
765
|
+
}
|
|
766
|
+
head.append(title, count, buttonOf('lanes-directory-close', '×', 'Close lanes', () => ui.close(), 'close'));
|
|
767
|
+
const parts = [head];
|
|
768
|
+
|
|
769
|
+
if (view.options) {
|
|
770
|
+
const bar = el('div', 'lanes-directory-filter');
|
|
771
|
+
const pick = keyed(el('select', 'lanes-directory-pick'), 'filter');
|
|
772
|
+
pick.setAttribute('aria-label', 'Show lanes from');
|
|
773
|
+
const options = [{label: ALL_LANES, value: ''}, ...view.options.map(o => ({label: o.label, value: `${o.authority}/${o.workspace}`}))];
|
|
774
|
+
const current = view.filter ? `${view.filter.authority}/${view.filter.workspace}` : '';
|
|
775
|
+
for (const o of options) {
|
|
776
|
+
const option = el('option', '', o.label);
|
|
777
|
+
option.value = o.value;
|
|
778
|
+
option.selected = o.value === current;
|
|
779
|
+
pick.append(option);
|
|
780
|
+
}
|
|
781
|
+
pick.addEventListener('change', () => {
|
|
782
|
+
const [authority, workspace] = pick.value ? pick.value.split('/') : [];
|
|
783
|
+
ui.setFilter(pick.value ? {authority, workspace} : null);
|
|
784
|
+
});
|
|
785
|
+
bar.append(pick);
|
|
786
|
+
if (view.filter) {
|
|
787
|
+
bar.append(el('span', 'lanes-directory-chip', `Filtered: ${view.filter.label}`),
|
|
788
|
+
buttonOf('lanes-directory-clear', 'Clear filter', 'Clear the filter and show All lanes', () => ui.setFilter(null), 'clear'));
|
|
789
|
+
}
|
|
790
|
+
parts.push(bar);
|
|
791
|
+
}
|
|
792
|
+
const say = (cls, text) => { const p = el('p', cls, text); p.setAttribute('role', 'status'); parts.push(p); };
|
|
793
|
+
const EMPTY = {
|
|
794
|
+
unavailable: 'Not connected: this host does not serve the lane directory yet.',
|
|
795
|
+
loading: 'Loading lanes…', malformed: 'The directory could not be read. Nothing was changed.',
|
|
796
|
+
refused: `The host refused the lane directory: ${view.reason}`,
|
|
797
|
+
};
|
|
798
|
+
if (view.state !== 'ready') {
|
|
799
|
+
say(`lanes-directory-empty is-${view.state}`, EMPTY[view.state]);
|
|
800
|
+
} else {
|
|
801
|
+
if (view.malformed) say('lanes-directory-notice is-stale', 'The latest update could not be read: showing what was read before, marked stale.');
|
|
802
|
+
else if (view.waiting) say('lanes-directory-notice is-stale', 'Reconnecting: the lanes below are marked stale until the directory answers.');
|
|
803
|
+
if (view.expired) say('lanes-directory-notice is-stale', 'Read access to some lanes lapsed while they could not be refreshed: they are not shown.');
|
|
804
|
+
else if (view.incomplete && !view.malformed && !view.waiting) say('lanes-directory-notice is-stale', 'Some sources did not answer: their lanes are marked stale.');
|
|
805
|
+
if (view.pendingSelection) say('lanes-directory-notice', 'Waiting for the directory to find the linked lane.');
|
|
806
|
+
if (view.notice) say('lanes-directory-notice', view.notice);
|
|
807
|
+
if (view.tombstone) {
|
|
808
|
+
const t = el('p', 'lanes-directory-notice is-tombstone', `‘${view.tombstone.label}’ is no longer in the directory. `);
|
|
809
|
+
t.append(buttonOf('lanes-directory-dismiss', 'Dismiss', 'Dismiss this notice', () => ui.dismiss(), 'dismiss'));
|
|
810
|
+
parts.push(t);
|
|
811
|
+
}
|
|
812
|
+
const list = el('div', 'lanes-directory-list');
|
|
813
|
+
list.setAttribute('role', 'list');
|
|
814
|
+
list.setAttribute('aria-labelledby', 'lanes-directory-title');
|
|
815
|
+
// Section by section in the owner's order: a header where the model draws one (an empty Working (0) too), and the
|
|
816
|
+
// rows of a directory without agents, which has no header, all the same.
|
|
817
|
+
const headers = new Map(view.model.sections.map(item => [item.section, item.label]));
|
|
818
|
+
for (const key of DRAWN) {
|
|
819
|
+
if (headers.has(key)) list.append(el('h3', `lanes-directory-section is-${key}`, headers.get(key)));
|
|
820
|
+
for (const row of view.model.rows) if (row.section === key) list.append(rowNode(row));
|
|
821
|
+
}
|
|
822
|
+
if (!view.model.rows.length) {
|
|
823
|
+
if (view.filter) {
|
|
824
|
+
const p = el('p', 'lanes-directory-empty is-filtered', `No lanes in ${view.model.directory_label}. `);
|
|
825
|
+
p.append(buttonOf('lanes-directory-clear', 'Show All lanes', 'Clear the filter and show All lanes', () => ui.setFilter(null), 'clear'));
|
|
826
|
+
list.append(p);
|
|
827
|
+
} else list.append(el('p', 'lanes-directory-empty is-empty', 'No lanes yet.'));
|
|
828
|
+
}
|
|
829
|
+
parts.push(list);
|
|
830
|
+
}
|
|
831
|
+
const foot = el('footer', 'lanes-directory-foot');
|
|
832
|
+
foot.append(el('span', '', 'This device only:'),
|
|
833
|
+
buttonOf('lanes-directory-toggle', ui.device('density') === 'compact' ? 'Comfortable rows' : 'Compact rows', '',
|
|
834
|
+
() => ui.setDevice('density', ui.device('density') === 'compact' ? 'comfortable' : 'compact'), 'density'),
|
|
835
|
+
buttonOf('lanes-directory-toggle', glyphs === 'ascii' ? 'Unicode glyphs' : 'ASCII glyphs', '',
|
|
836
|
+
() => ui.setDevice('glyphs', glyphs === 'ascii' ? 'unicode' : 'ascii'), 'glyphs'));
|
|
837
|
+
if (view.state === 'ready' && (view.model.counts.hidden || view.showHidden)) {
|
|
838
|
+
foot.append(buttonOf('lanes-directory-toggle', view.showHidden ? 'Leave hidden lanes out' : `Show hidden (${view.model.counts.hidden})`, '',
|
|
839
|
+
() => ui.toggleHidden(), 'hidden'));
|
|
840
|
+
}
|
|
841
|
+
parts.push(foot);
|
|
842
|
+
root.setAttribute('data-density', ui.device('density'));
|
|
843
|
+
root.replaceChildren(...parts);
|
|
844
|
+
return focus;
|
|
845
|
+
|
|
846
|
+
function rowNode(row) {
|
|
847
|
+
const status = has(LANES_DIRECTORY_TOKENS.agent, row.status) ? row.status : null;
|
|
848
|
+
const tone = status ? LANES_DIRECTORY_TOKENS.agent[status][2] : 'ink-dim';
|
|
849
|
+
const where = `${row.workspace} · ${row.authority}`;
|
|
850
|
+
const item = el('div', `lanes-directory-row${row.identity === view.selection ? ' is-selected' : ''}${row.stale ? ' is-stale' : ''}${row.hidden ? ' is-hidden' : ''}`);
|
|
851
|
+
item.setAttribute('role', 'listitem');
|
|
852
|
+
item.setAttribute('data-identity', row.identity);
|
|
853
|
+
item.setAttribute('data-tone', tone);
|
|
854
|
+
const word = status ? LANES_DIRECTORY_TOKENS.agent[status][3] : 'No agent';
|
|
855
|
+
const pick = buttonOf('lanes-directory-pick-row', '', `${row.label}, ${word}, ${where}${row.stale ? ', stale' : ''}${row.hidden ? ', hidden' : ''}`,
|
|
856
|
+
() => ui.select(row.identity), `row:${row.identity}`);
|
|
857
|
+
if (!focus.has('first')) focus.set('first', pick);
|
|
858
|
+
if (row.identity === view.selection) pick.setAttribute('aria-current', 'true');
|
|
859
|
+
const g = el('span', 'lanes-directory-glyph', status ? glyph('agent', status) : ' ');
|
|
860
|
+
g.setAttribute('aria-hidden', 'true');
|
|
861
|
+
pick.append(g, el('span', 'lanes-directory-name', row.label), el('span', 'lanes-directory-where', where),
|
|
862
|
+
el('span', 'lanes-directory-state', row.hidden ? 'Hidden' : word));
|
|
863
|
+
if (row.pinned) pick.append(el('span', 'lanes-directory-mark is-pinned', glyph('marks', 'pinned')));
|
|
864
|
+
if (row.stale) pick.append(el('span', 'lanes-directory-mark is-stale', glyph('marks', 'stale')));
|
|
865
|
+
item.append(pick);
|
|
866
|
+
if (row.identity === view.selection) item.append(detail(row, where));
|
|
867
|
+
return item;
|
|
868
|
+
}
|
|
869
|
+
function detail(row, where) {
|
|
870
|
+
const box = el('div', 'lanes-directory-detail');
|
|
871
|
+
const link = keyed(el('a', 'lanes-directory-link', 'Link to this lane'), `link:${row.identity}`);
|
|
872
|
+
link.href = linkFor(row.identity);
|
|
873
|
+
const facts = el('p', 'lanes-directory-facts', `${row.identity}${row.host_instance ? ` · ${row.host_instance}` : ''}${row.native_generation ? ` · generation ${row.native_generation}` : ''}${row.observed_through.length ? ` · from ${row.observed_through.join(', ')}` : ''}`);
|
|
874
|
+
const actions = el('div', 'lanes-directory-actions');
|
|
875
|
+
const pending = view.pending[row.identity];
|
|
876
|
+
const armed = view.armed && view.armed.identity === row.identity;
|
|
877
|
+
const verbs = row.hidden ? [['open', 'Open', row.actions.open], ['hide', 'Unhide', row.actions.hide]]
|
|
878
|
+
: [['open', 'Open', row.actions.open], ['pin', row.pinned ? 'Unpin' : 'Pin', row.actions.pin], ['hide', 'Hide', row.actions.hide],
|
|
879
|
+
['close', armed ? 'Confirm close' : 'Close', row.actions.close]];
|
|
880
|
+
for (const [verb, text, action] of verbs) {
|
|
881
|
+
const b = buttonOf(`lanes-directory-act is-${verb}`, pending === verb ? `${text}…` : text, `${text} ${row.label} (${where})`,
|
|
882
|
+
() => ui.act(row.identity, verb), `act:${row.identity}:${verb}`);
|
|
883
|
+
if (!action.available) {
|
|
884
|
+
b.disabled = true;
|
|
885
|
+
b.setAttribute('title', reasonText(action.reason));
|
|
886
|
+
actions.append(b, el('small', 'lanes-directory-reason', reasonText(action.reason)));
|
|
887
|
+
} else actions.append(b);
|
|
888
|
+
}
|
|
889
|
+
box.append(facts, link, actions);
|
|
890
|
+
return box;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
if (typeof module === 'object') {
|
|
895
|
+
module.exports = {LANES_DIRECTORY_TOKENS, DirectoryError, laneDirectory, parseLink, linkFor, deviceLocal, createDirectory,
|
|
896
|
+
renderDirectory, REASON_TEXT, preferencesUpdate, commandFor, decodeSnapshot};
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// ------------------------------------------------------------------------------------------------- the page
|
|
900
|
+
(() => {
|
|
901
|
+
const w = globalThis;
|
|
902
|
+
if (!w.document || w.lanesDirectory) return;
|
|
903
|
+
const doc = w.document, mode = doc.documentElement.dataset.lanesShell || 'desktop';
|
|
904
|
+
let storage = null, top = null, drawn = new Map();
|
|
905
|
+
try { storage = w.localStorage; } catch {}
|
|
906
|
+
doc.head.append(Object.assign(doc.createElement('link'), {rel: 'stylesheet', href: '/lanes-assets/directory.css'}));
|
|
907
|
+
const root = Object.assign(doc.createElement('section'), {className: `lanes-directory lanes-directory-${mode}`, hidden: true});
|
|
908
|
+
root.setAttribute('role', 'dialog');
|
|
909
|
+
root.setAttribute('aria-modal', 'true');
|
|
910
|
+
root.setAttribute('aria-labelledby', 'lanes-directory-title');
|
|
911
|
+
doc.body.append(root);
|
|
912
|
+
const list = () => root.querySelector('.lanes-directory-list');
|
|
913
|
+
// Back (or closing and opening again) restores this device's filter, selection and scroll; a redraw keeps the
|
|
914
|
+
// scroll, and the keyboard on the control it was on (or inside the dialog, on its close button).
|
|
915
|
+
const draw = () => {
|
|
916
|
+
if (root.hidden) return;
|
|
917
|
+
const active = doc.activeElement, key = active && root.contains(active) ? active.getAttribute('data-focus') : null;
|
|
918
|
+
if (list()) top = list().scrollTop;
|
|
919
|
+
drawn = renderDirectory(doc, root, ui.view(), ui, {glyphs: ui.device('glyphs')});
|
|
920
|
+
if (list()) list().scrollTop = top ?? ui.scroll();
|
|
921
|
+
if (key) (drawn.get(key) || drawn.get('close')).focus();
|
|
922
|
+
};
|
|
923
|
+
const ui = createDirectory({storage, onChange: draw});
|
|
924
|
+
const hide = () => {
|
|
925
|
+
if (!root.hidden && list()) ui.setScroll(list().scrollTop);
|
|
926
|
+
root.hidden = true;
|
|
927
|
+
top = null;
|
|
928
|
+
};
|
|
929
|
+
// Opening takes the keyboard into the dialog on a tablet or a desktop, where the terminal had it; a phone's picker
|
|
930
|
+
// fills the screen and opens no keyboard. A resume link moves no other device's focus.
|
|
931
|
+
const route = () => {
|
|
932
|
+
const link = parseLink(w.location.hash);
|
|
933
|
+
if (!link) return hide();
|
|
934
|
+
const opening = root.hidden;
|
|
935
|
+
root.hidden = false;
|
|
936
|
+
if (link.identity) ui.select(link.identity);
|
|
937
|
+
else if (w.location.hash !== '#lanes') ui.say('That link does not name a lane');
|
|
938
|
+
else draw();
|
|
939
|
+
if (opening && mode !== 'phone') (drawn.get(`row:${ui.state.selection}`) || drawn.get('first') || drawn.get('close')).focus();
|
|
940
|
+
};
|
|
941
|
+
ui.close = () => {
|
|
942
|
+
hide();
|
|
943
|
+
try { w.history.replaceState(null, '', w.location.pathname + w.location.search); } catch {}
|
|
944
|
+
if (mode === 'desktop') w.term?.focus();
|
|
945
|
+
};
|
|
946
|
+
root.addEventListener('keydown', ev => ev.key === 'Escape' && ui.close());
|
|
947
|
+
w.lanesDirectory = ui;
|
|
948
|
+
w.addEventListener('hashchange', route);
|
|
949
|
+
ui.connect(w.lanesDirectorySource);
|
|
950
|
+
route();
|
|
951
|
+
})();
|