vine-context 0.0.0-stage → 0.1.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.
Files changed (34) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +280 -2
  3. package/dist/apps/shell.html +134 -0
  4. package/dist/apps/views.html +124 -0
  5. package/dist/cli.js +7865 -0
  6. package/dist/cli.js.map +1 -0
  7. package/examples/data/graphs/party/.cypherlite/schema/schema.cypher +5 -0
  8. package/examples/data/graphs/party/.cypherlite.lock +1 -0
  9. package/examples/data/graphs/party/.cypherlite.writer +0 -0
  10. package/examples/data/graphs/party/manifest.json +215 -0
  11. package/examples/data/graphs/party/nodes/0-262144-7987dd27c85668d4810609133f705907.parquet +0 -0
  12. package/examples/data/graphs/party/wal/.cypherlite.lock +1 -0
  13. package/examples/data/graphs/party/wal/.cypherlite.writer +0 -0
  14. package/examples/data/graphs/party/wal/00000002.log +0 -0
  15. package/examples/data/hosts/party/changes.jsonl +19 -0
  16. package/examples/data/hosts/party/group.json +5 -0
  17. package/examples/data/hosts/party/sharing.json +1 -0
  18. package/examples/data/identity.json +4 -0
  19. package/models/temporal-claims/instructions.md +78 -0
  20. package/models/temporal-claims/model.yaml +99 -0
  21. package/models/temporal-claims/tools.yaml +348 -0
  22. package/package.json +79 -4
  23. package/plugin/.claude-plugin/plugin.json +8 -0
  24. package/plugin/.codex-plugin/plugin.json +17 -0
  25. package/plugin/.mcp.json +8 -0
  26. package/plugin/codex/hooks.json +11 -0
  27. package/plugin/commands/join.md +22 -0
  28. package/plugin/hooks/hooks.json +11 -0
  29. package/plugin/hooks/register.tsx +2310 -0
  30. package/plugin/hooks/vine-hook.mjs +25 -0
  31. package/plugin/skills/join-context-graph/SKILL.md +36 -0
  32. package/plugin/skills/vine-context/SKILL.md +232 -0
  33. package/plugin/tests/context-graph.test.tsx +830 -0
  34. package/plugin/types/index.d.ts +165 -0
@@ -0,0 +1,2310 @@
1
+ // The vine-context mod: this chat's shared contexts inside Claude Code's own UI.
2
+ //
3
+ // - A band above the prompt, in every chat: the chat's context (usually one),
4
+ // who's online and the latest news. The context's name opens the panel's
5
+ // Contexts view, where contexts are turned on and off for the chat.
6
+ // - A status line entry, and a toast when someone else's change or a digest arrives.
7
+ // - A panel (/contexts) with five tabs: an Overview (what needs you, what
8
+ // changed, recent activity), the context's Questions with their threads, its
9
+ // Claims (with conflicts and history), its People, and its Settings (this
10
+ // chat's use of it, sharing, what it holds, deleting it). Whether it's
11
+ // syncing, with a link to go online or offline, sits in the header. Long or
12
+ // secondary lists show their first few behind an underlined "N more ▾". An
13
+ // item opens on its own, with everything linked to it. Anything being edited
14
+ // (the description, an invite, a new context, the chat's contexts, the page
15
+ // of a context that's off for this chat, a deletion being confirmed) takes
16
+ // the whole panel until it's done or cancelled. An answer or a correction is
17
+ // written in the prompt box.
18
+ //
19
+ // Agents write; people steer. The panel never writes a claim itself: "Answer
20
+ // with this", "Keep this one", Look into it, Catch me up and "Save what this
21
+ // chat learned" hand the person's choice to the agent as a prompt, and the
22
+ // agent records it (see `prompts`). Answering a question and correcting a claim
23
+ // start a prompt in the prompt box instead (see `drafts`): the person writes
24
+ // their answer or correction on its last line and sends it themselves.
25
+ //
26
+ // It reads through the vine-context MCP server's `context_activity` tool,
27
+ // which never uses up the join notices meant for the agent, and acts through
28
+ // the server's ordinary tools. It polls, so there's nothing to refresh.
29
+
30
+ import { atom, read, update } from 'claude-code'
31
+ import type { EngineInterface, Register, UiPressArgument } from 'claude-code'
32
+
33
+ import type { Activity, Change, ContextDetails, Filters, Found, GraphEdge, GraphNode, Invite, Latest, Person, Tab } from '../types'
34
+
35
+ const PANE = 'context-graph'
36
+ const POLL_MS = 4000
37
+ const TICK_MS = 400
38
+ const NOTICE_MS = 6000
39
+ /** How many items a list shows before "Show more". */
40
+ const PAGE = 20
41
+ /** How many recent changes the Overview shows before "N more". */
42
+ const RECENT = 5
43
+ /** Below this many cells across the pane's body, a row's text and its buttons stack. */
44
+ const NARROW = 46
45
+ /** From this many cells across, the Overview sets its two halves side by side. */
46
+ const WIDE = 100
47
+
48
+ /**
49
+ * How the pane lays itself out for the room it has: `glance` for the desktop
50
+ * app's minimized widget (clicks may not reach it), else by the body's width.
51
+ * Height isn't used: a change of height alone doesn't redraw the pane, so the
52
+ * body scrolls instead.
53
+ */
54
+ export type Fit = 'glance' | 'narrow' | 'regular' | 'wide'
55
+ export const paneFit = (p: { bodyColumns?: number; placement?: string }): Fit => {
56
+ if (p.placement === 'widget') return 'glance'
57
+ const cols = p.bodyColumns ?? 80
58
+ return cols < NARROW ? 'narrow' : cols >= WIDE ? 'wide' : 'regular'
59
+ }
60
+
61
+ // The header names at most this many members (you, then who's online); the People tab has everyone.
62
+ const HEADER_PEOPLE = 6
63
+ const SERVERS = ['plugin_vine-context_vine-context', 'plugin:vine-context:vine-context', 'vine-context']
64
+ const NAME_RE = /^[a-z0-9][a-z0-9-]{0,62}$/
65
+
66
+ const activity = atom({ plugin: 'vine-context', key: 'activity' } as const, null, { shape: 'activity-3' })
67
+ const latest = atom({ plugin: 'vine-context', key: 'latest' } as const, null)
68
+ const tab = atom({ plugin: 'vine-context', key: 'tab' } as const, 'overview', { shape: 'tab-3' })
69
+ const code = atom({ plugin: 'vine-context', key: 'code' } as const, null)
70
+ const notice = atom({ plugin: 'vine-context', key: 'notice' } as const, null)
71
+ const error = atom({ plugin: 'vine-context', key: 'error' } as const, null)
72
+ const confirmRemove = atom({ plugin: 'vine-context', key: 'confirmRemove' } as const, null)
73
+ const creating = atom({ plugin: 'vine-context', key: 'creating' } as const, null)
74
+ const managing = atom({ plugin: 'vine-context', key: 'managing' } as const, null)
75
+ const details = atom({ plugin: 'vine-context', key: 'details' } as const, null)
76
+ const deleting = atom({ plugin: 'vine-context', key: 'deleting' } as const, null)
77
+ /** The context whose description is being edited. */
78
+ const editing = atom({ plugin: 'vine-context', key: 'editing' } as const, false as string | boolean)
79
+ /** The context being renamed. */
80
+ const renamingContext = atom({ plugin: 'vine-context', key: 'renamingContext' } as const, null as null | string)
81
+ const switching = atom({ plugin: 'vine-context', key: 'switching' } as const, false)
82
+ const detail = atom({ plugin: 'vine-context', key: 'detail' } as const, null)
83
+ const renaming = atom({ plugin: 'vine-context', key: 'renaming' } as const, false)
84
+ const filters = atom({ plugin: 'vine-context', key: 'filters' } as const, { text: '', claims: 'current', questions: 'open' })
85
+ const found = atom({ plugin: 'vine-context', key: 'found' } as const, null)
86
+ const more = atom({ plugin: 'vine-context', key: 'more' } as const, 0)
87
+ const unattached = atom({ plugin: 'vine-context', key: 'unattached' } as const, null)
88
+ const viewing = atom({ plugin: 'vine-context', key: 'viewing' } as const, null)
89
+ const tick = atom({ plugin: 'vine-context', key: 'tick' } as const, 0)
90
+ /** The context a join code is being made for, and the role it gives. */
91
+ const inviting = atom({ plugin: 'vine-context', key: 'inviting' } as const, null as null | { name: string; role: Invite['role'] })
92
+ const folds = atom({ plugin: 'vine-context', key: 'folds' } as const, [] as string[])
93
+
94
+ type Engine = EngineInterface
95
+
96
+ /** What's typed in the new invite's note, for its Make button (the field's own submit works too). */
97
+ let inviteNote = ''
98
+ /** What's typed in the new context's two fields, for its Create button. */
99
+ let newName = ''
100
+ let newDescription = ''
101
+ /** What's typed to confirm a deletion, for its Delete button. */
102
+ let deleteText = ''
103
+ /** What's typed as a context's new name, for its Rename button. */
104
+ let renameText = ''
105
+ /** The join code just made for a context that's off for this chat: its page shows it, since it has no People tab. */
106
+ let madeCode: { name: string; id: string; send: string; label: string | null; role: string } | null = null
107
+
108
+ /** The tabs, each with its icon. */
109
+ const TABS: { tab: Tab; icon: string; label: string }[] = [
110
+ { tab: 'overview', icon: '🏠', label: 'Overview' },
111
+ { tab: 'questions', icon: '❓', label: 'Questions' },
112
+ { tab: 'claims', icon: '📌', label: 'Claims' },
113
+ { tab: 'people', icon: '👥', label: 'People' },
114
+ { tab: 'settings', icon: '⚙', label: 'Settings' },
115
+ ]
116
+
117
+ const short = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
118
+ /** A path cut from the front, so its last folders (the telling part) stay. */
119
+ export const tail = (s: string, n: number) => (s.length > n ? `…${s.slice(s.length - n + 1)}` : s)
120
+ const ago = (iso: string, now: number) => {
121
+ const s = Math.max(0, (now - Date.parse(iso)) / 1000)
122
+ if (s < 60) return 'just now'
123
+ if (s < 3600) return `${Math.round(s / 60)}m ago`
124
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`
125
+ return `${Math.round(s / 86400)}d ago`
126
+ }
127
+ const prop = (n: GraphNode, k: string) => (typeof n.props[k] === 'string' ? (n.props[k] as string) : '')
128
+
129
+ /** A question with its thread and the claims that answer it, from the snapshot. */
130
+ export type Thread = { q: GraphNode; replies: GraphNode[]; answers: GraphNode[] }
131
+
132
+ /** Builds the questions' threads and the current claims from a snapshot. */
133
+ export function threads(nodes: GraphNode[], edges: GraphEdge[]): { open: Thread[]; answered: Thread[]; claims: GraphNode[]; withdrawn: number } {
134
+ const byId = new Map(nodes.map(n => [n.id, n]))
135
+ const live = (n: GraphNode | undefined): n is GraphNode => !!n && !n.ended
136
+ // A claim is current unless withdrawn or replaced by a current claim.
137
+ const replaced = new Set(edges.filter(e => e.type === 'REPLACES' && live(byId.get(e.source))).map(e => e.target))
138
+ const current = (n: GraphNode | undefined): n is GraphNode => live(n) && n.label === 'Claim' && !replaced.has(n.id)
139
+ const all: Thread[] = nodes
140
+ .filter(n => n.label === 'Question' && !n.ended)
141
+ .map(q => ({
142
+ q,
143
+ replies: edges
144
+ .filter(e => e.type === 'REPLIES_TO' && e.target === q.id)
145
+ .map(e => byId.get(e.source))
146
+ .filter(live)
147
+ .sort((a, b) => Date.parse(prop(a, 'recorded_at')) - Date.parse(prop(b, 'recorded_at'))),
148
+ answers: edges
149
+ .filter(e => e.type === 'ANSWERS' && e.target === q.id)
150
+ .map(e => byId.get(e.source))
151
+ .filter(current),
152
+ }))
153
+ return {
154
+ open: all.filter(t => !t.answers.length),
155
+ answered: all.filter(t => t.answers.length),
156
+ claims: nodes.filter(current),
157
+ withdrawn: nodes.filter(n => n.ended).length,
158
+ }
159
+ }
160
+
161
+ /** How a snapshot's items relate: what replaced what, what contradicts what, and each item's links. */
162
+ export function relations(nodes: GraphNode[], edges: GraphEdge[]) {
163
+ const byId = new Map(nodes.map(n => [n.id, n]))
164
+ const byKey = new Map(nodes.map(n => [n.key, n]))
165
+ const live = (n: GraphNode | undefined): n is GraphNode => !!n && !n.ended
166
+ /** A claim's newer version, where a claim that still stands replaced it. */
167
+ const replacedBy = new Map<string, GraphNode>()
168
+ for (const e of edges) {
169
+ const by = byId.get(e.source)
170
+ if (e.type === 'REPLACES' && live(by)) replacedBy.set(e.target, by)
171
+ }
172
+ const current = (n: GraphNode | undefined): n is GraphNode => live(n) && n.label === 'Claim' && !replacedBy.has(n.id)
173
+ const linked = (id: string, type: string, dir: 'out' | 'in') =>
174
+ edges
175
+ .filter(e => e.type === type && (dir === 'out' ? e.source : e.target) === id)
176
+ .map(e => byId.get(dir === 'out' ? e.target : e.source))
177
+ .filter((n): n is GraphNode => !!n)
178
+ // Pairs of claims that both still stand and can't both be true, each pair once.
179
+ const pairs = new Map<string, [GraphNode, GraphNode]>()
180
+ for (const e of edges) {
181
+ if (e.type !== 'CONTRADICTS') continue
182
+ const a = byId.get(e.source)
183
+ const b = byId.get(e.target)
184
+ if (current(a) && current(b)) pairs.set([a.id, b.id].sort().join('|'), [a, b])
185
+ }
186
+ const conflicts = [...pairs.values()]
187
+ const inConflict = new Set(conflicts.flatMap(([a, b]) => [a.id, b.id]))
188
+ /** Claims that no longer stand: replaced or withdrawn. */
189
+ const history = nodes.filter(n => n.label === 'Claim' && !current(n))
190
+ return { byId, byKey, replacedBy, current, linked, conflicts, inConflict, history }
191
+ }
192
+
193
+ /** Whether an item matches the filter's words: all of them, anywhere in its text, author, source or id. */
194
+ export function matches(n: GraphNode, text: string): boolean {
195
+ const words = text.toLowerCase().split(/\s+/).filter(Boolean)
196
+ if (!words.length) return true
197
+ const hay = `${n.title} ${prop(n, 'recorded_by')} ${prop(n, 'source')} ${n.key}`.toLowerCase()
198
+ return words.every(w => hay.includes(w))
199
+ }
200
+
201
+ /** How many items a filter adds because they're close in meaning, past those that share its words. */
202
+ export const RELATED = 5
203
+
204
+ /**
205
+ * A list under the filter: the items that match its words, then up to RELATED
206
+ * more that the search found close in meaning (`near`, best first), which are
207
+ * marked so the list can say so.
208
+ */
209
+ export function filtered<T>(items: T[], key: (x: T) => string, words: (x: T) => boolean, near: string[] | null | undefined): { list: T[]; byMeaning: Set<string> } {
210
+ const list = items.filter(words)
211
+ const byMeaning = new Set<string>()
212
+ if (!near?.length) return { list, byMeaning }
213
+ const shown = new Set(list.map(key))
214
+ const byKey = new Map(items.map(x => [key(x), x] as const))
215
+ for (const id of near) {
216
+ if (byMeaning.size >= RELATED) break
217
+ const x = byKey.get(id)
218
+ if (x !== undefined && !shown.has(id)) {
219
+ byMeaning.add(id)
220
+ list.push(x)
221
+ }
222
+ }
223
+ return { list, byMeaning }
224
+ }
225
+
226
+ /**
227
+ * Asks the server's search for what the filter's text is close to, in the
228
+ * context the panel shows, ended items included so History can use it too.
229
+ * A server from before `include_ended` is asked again without it.
230
+ */
231
+ async function findRelated($: Engine, text: string, context: string, ctx: Record<string, unknown>) {
232
+ if (!text) return update($, found, () => null)
233
+ await update($, found, () => ({ text, context, ids: null }))
234
+ const ask = { query: text, kind: 'any', limit: 50, ...ctx }
235
+ const settle = (next: Found) => update($, found, (v: Found | null) => (v?.text === text && v.context === context ? next : v))
236
+ try {
237
+ const rows = await call($, 'search', { ...ask, include_ended: true }).catch(() => call($, 'search', ask))
238
+ const ids = (Array.isArray(rows) ? rows : []).map((r: any) => r?.id).filter((id: unknown): id is string => typeof id === 'string')
239
+ await settle({ text, context, ids })
240
+ } catch {
241
+ await settle({ text, context, ids: [], failed: true })
242
+ }
243
+ }
244
+
245
+ /** What the agent is asked from the panel's other buttons: the person steers, the agent records. */
246
+ export const prompts = {
247
+ catchUp: (context: string) =>
248
+ `Catch me up on the context '${context}': what changed lately and who changed it, which questions are still open, and any claims that contradict each other. Keep it short, and end with what needs me.`,
249
+ saveChat: (context: string) =>
250
+ `Record what we've learned in this chat in the context '${context}'. Search it first, so you link to what's already there instead of repeating it. Add a claim for each finding and a question for each thing we still don't know, then tell me what you recorded, with the ids.`,
251
+ investigate: (q: GraphNode, context?: string) =>
252
+ `Look into the open question ${q.key} ("${short(q.title, 200)}")${context ? ` in the context '${context}'` : ''}. Search the context for what's already known about it, find out what you can, and reply on its thread with what you find. If that settles it, record a claim that answers it.`,
253
+ settle: (keep: GraphNode, drop: GraphNode, context?: string) =>
254
+ `The claims ${keep.key} ("${short(keep.title, 200)}") and ${drop.key} ("${short(drop.title, 200)}") contradict each other${context ? ` in the context '${context}'` : ''}. ${keep.key} is the one that's right.\n\n` +
255
+ `Settle it so only one stands: withdraw ${drop.key} with that as the reason if you may, otherwise record a claim that replaces it (replaces: [${drop.key}])${context ? ` (context: ${context})` : ''}. Then tell me what you did.`,
256
+ }
257
+
258
+ /**
259
+ * What the prompt box is started with to answer a question or correct a claim:
260
+ * what the agent is to do, the item, and a last line for the person to finish
261
+ * in their own words before they send it.
262
+ */
263
+ export const drafts = {
264
+ answer: (q: GraphNode, context?: string) =>
265
+ `Record my answer to the open question ${q.key}${context ? ` in the context '${context}'` : ''}: paraphrase it as a claim that stands alone, with answers: [${q.key}].\n` +
266
+ `Q: ${short(q.title, 300)}\nA: `,
267
+ correct: (claim: GraphNode, context?: string) =>
268
+ `The claim ${claim.key}${context ? ` in the context '${context}'` : ''} is wrong or out of date. Record what's right: paraphrase it as a claim that stands alone, with replaces: [${claim.key}].\n` +
269
+ `Was: ${short(claim.title, 300)}\nNow: `,
270
+ }
271
+
272
+ /** What the agent is asked when the person picks a reply as a question's answer. */
273
+ export function answerPrompt(q: GraphNode, answer: { reply: GraphNode }, context?: string): string {
274
+ const question = `the open question ${q.key} ("${short(q.title, 200)}")${context ? ` in the context '${context}'` : ''}`
275
+ const where = context ? ` (context: ${context})` : ''
276
+ const r = answer.reply
277
+ return (
278
+ `Answer ${question} with ${prop(r, 'recorded_by') || 'its'}'s reply ${r.key}: "${short(r.title, 400)}"\n\n` +
279
+ `Paraphrase it as a claim that stands alone and record it with answers: [${q.key}], with source "reply ${r.key}"${where}.`
280
+ )
281
+ }
282
+
283
+ // Module state: starts over on a reload (the values in $.state stay).
284
+ let server: string | undefined
285
+ let poll: { cancel(): void } | undefined
286
+ let loading: { cancel(): void } | undefined
287
+ let seen: Set<string> | undefined
288
+ let seenDigest: string | undefined
289
+ let wantSnapshot = false
290
+ /** How many times in a row the server hasn't answered: after a few, the band stops saying "loading". */
291
+ let failures = 0
292
+ const GIVE_UP_AFTER = 3
293
+ let noticeTimer: { cancel(): void } | undefined
294
+ /** The items opened one after another, so Back returns to the one before. */
295
+ let trail: string[] = []
296
+
297
+ /** Calls a tool on the vine-context server, finding its name on first use. */
298
+ async function call($: Engine, tool: string, args: Record<string, unknown> = {}): Promise<any> {
299
+ const names = server ? [server] : SERVERS
300
+ let last: unknown
301
+ for (const name of names) {
302
+ try {
303
+ const r = await $.mcp.call(name, tool, args)
304
+ server = name
305
+ const text = r.content.map(c => ('text' in c && typeof c.text === 'string' ? c.text : '')).find(t => t && !t.startsWith('News: ')) ?? ''
306
+ if (r.isError) throw new Error(text || `${tool} failed`)
307
+ if (r.structuredContent !== undefined) return r.structuredContent
308
+ try {
309
+ return JSON.parse(text)
310
+ } catch {
311
+ return text
312
+ }
313
+ } catch (e) {
314
+ last = e
315
+ if (server) throw e
316
+ }
317
+ }
318
+ throw last instanceof Error ? last : new Error('The vine-context MCP server is not connected.')
319
+ }
320
+
321
+ /**
322
+ * Whether the error showing came from the poll (the server not answering). The
323
+ * next answer clears only that kind: an error from something the person did
324
+ * stays until they dismiss it or their next action works.
325
+ */
326
+ let errorFromPoll = false
327
+
328
+ /** Shows an error in the panel (and, from the poll while nothing has loaded, the band). */
329
+ async function fail($: Engine, message: string, fromPoll = false) {
330
+ errorFromPoll = fromPoll
331
+ await update($, error, () => message)
332
+ }
333
+
334
+ /** Clears the error showing. */
335
+ async function clearError($: Engine) {
336
+ errorFromPoll = false
337
+ await update($, error, () => null)
338
+ }
339
+
340
+ /** Why the server didn't answer, in words that say what to do about it. */
341
+ export function trouble(message: string): string {
342
+ if (/context_activity|context_details|delete_context|unknown tool|not found|no such tool/i.test(message))
343
+ return 'This chat is still running an older vine-context server. Start a new chat (or restart this one) to pick up the new one.'
344
+ if (/not connected|no server|disconnected|closed/i.test(message)) return 'The vine-context server isn’t connected in this chat. Check it’s enabled, then start a new chat.'
345
+ return message
346
+ }
347
+
348
+ /** The server answered, or clearly won't: the band's "loading…" stops. */
349
+ function loaded() {
350
+ loading?.cancel()
351
+ loading = undefined
352
+ }
353
+
354
+ async function refresh($: Engine) {
355
+ try {
356
+ const which = await read($, viewing)
357
+ const r = (await call($, 'context_activity', { limit: 40, snapshot: wantSnapshot, ...(which ? { context: which } : {}) })) as Activity | { context: null; your_contexts: string[] }
358
+ loaded()
359
+ failures = 0
360
+ if (errorFromPoll) await clearError($)
361
+ if (r.context === null) {
362
+ // No context in this chat (there's no default): the band and panel offer to choose one.
363
+ await update($, unattached, () => r.your_contexts)
364
+ await update($, activity, () => null)
365
+ await update($, latest, () => null)
366
+ await update($, viewing, () => null)
367
+ $.ui.status('no context')
368
+ return
369
+ }
370
+ const a = r as Activity
371
+ await update($, unattached, () => null)
372
+ await update($, activity, () => a)
373
+ if (which && which !== a.context) await update($, viewing, () => null) // it was taken out of the chat
374
+ const others = a.recent.filter(c => !c.mine && !c.held)
375
+ if (seen) {
376
+ const fresh = others.filter(c => !seen!.has(c.id) && ['claim', 'question', 'reply', 'add_member', 'withdraw', 'remove_member'].includes(c.kind))
377
+ for (const c of fresh.slice(0, 3)) $.ui.toast(`${c.by} ${short(c.summary, 90)}`)
378
+ }
379
+ seen = new Set(a.recent.map(c => c.id))
380
+ // What others' changes meant for you (the sync digest): its first line as a toast.
381
+ const d = a.digest?.at(-1)
382
+ if (d && seenDigest !== undefined && d.at !== seenDigest && d.lines[0]) $.ui.toast(`${a.context}: ${short(d.lines[0], 110)}`)
383
+ seenDigest = d?.at ?? ''
384
+ const top = others.find(c => c.kind !== 'create')
385
+ await update($, latest, (): Latest | null => (top ? { by: top.by, summary: top.summary, at: top.at } : null))
386
+ const away = a.members - 1
387
+ const more = a.contexts.length > 1 ? ` +${a.contexts.length - 1}` : ''
388
+ $.ui.status(`context ${a.contexts.find(c => c.writes_here)?.name ?? a.context}${more}${a.sharing ? (away ? ` · ${a.online.length}/${away} online` : '') : ' · offline'}`)
389
+ } catch (e) {
390
+ // A new chat's server takes a moment to connect, so the first failures still read as loading.
391
+ if (++failures >= GIVE_UP_AFTER) loaded()
392
+ await fail($, trouble((e as Error).message), true)
393
+ }
394
+ }
395
+
396
+ /** Shows a line in the panel for a few seconds (or clears it). */
397
+ async function say($: Engine, text: string | null) {
398
+ noticeTimer?.cancel()
399
+ noticeTimer = undefined
400
+ await update($, notice, () => text)
401
+ if (text) noticeTimer = $.clock.after(NOTICE_MS, () => void update($, notice, () => null))
402
+ }
403
+
404
+ /** Opens an item on its own (a claim or a question), remembering where from. */
405
+ async function openItem($: Engine, key: string | null) {
406
+ if (key) trail.push(key)
407
+ else trail = []
408
+ await update($, detail, () => key)
409
+ }
410
+
411
+ /** A way out of a step (Cancel, Done, Back) leads with a ‹ caret, so it reads as going back. */
412
+ const caret = (label: string) => (label.startsWith('‹') ? label : `‹ ${label}`)
413
+
414
+ /** Back from an item: to the one opened before it, else to the list. */
415
+ async function backItem($: Engine) {
416
+ trail.pop()
417
+ await update($, detail, () => trail.at(-1) ?? null)
418
+ }
419
+
420
+ /** Runs a tool from a button or field, then refreshes; errors show in the panel. */
421
+ async function act($: Engine, tool: string, args: Record<string, unknown>, done?: string) {
422
+ try {
423
+ const r = await call($, tool, args)
424
+ await clearError($)
425
+ await say($, done ?? null)
426
+ // A new join code (from Invite): marked in the People tab's list.
427
+ const made = r && typeof r === 'object' ? (r as { invite?: { id?: string } }).invite?.id : undefined
428
+ if (made) await update($, code, () => made)
429
+ const inv = r as { context?: string; code?: string; invite?: { id: string; label?: string; role?: string } } | null
430
+ if (inv?.code && inv.context && inv.invite)
431
+ madeCode = { name: inv.context, id: inv.invite.id, send: `Join my context graph: /vine-context:join ${inv.code}`, label: inv.invite.label ?? null, role: inv.invite.role ?? 'contributor' }
432
+ } catch (e) {
433
+ await fail($, (e as Error).message)
434
+ }
435
+ await refresh($)
436
+ await loadDetails($)
437
+ }
438
+
439
+ /** Renames a context on this machine; the panel follows it to its new name. */
440
+ async function renameContext($: Engine, from: string, to: string) {
441
+ try {
442
+ await call($, 'rename_context', { name: from, to })
443
+ await clearError($)
444
+ await say($, `Renamed to '${to}' on this machine. Other members keep their own name for it.`)
445
+ if ((await read($, managing)) === from) await update($, managing, () => to)
446
+ if ((await read($, viewing)) === from) await update($, viewing, () => to)
447
+ if (madeCode?.name === from) madeCode = { ...madeCode, name: to }
448
+ } catch (e) {
449
+ await fail($, (e as Error).message)
450
+ }
451
+ await refresh($)
452
+ await loadDetails($)
453
+ }
454
+
455
+ /** The context whose details the panel shows: an off context's page, else the open context's Settings tab. */
456
+ async function detailsOf($: Engine): Promise<string | null> {
457
+ const m = await read($, managing)
458
+ if (m) return m
459
+ if ((await read($, tab)) !== 'settings' || (await read($, switching))) return null
460
+ return (await read($, activity))?.context ?? null
461
+ }
462
+
463
+ /** The context whose details were last asked for by drawing the Settings tab, so a failing read isn't asked again on every redraw. */
464
+ let askedDetails: string | undefined
465
+
466
+ /** Reads the details of the context being shown (again, after a change). */
467
+ async function loadDetails($: Engine) {
468
+ const name = await detailsOf($)
469
+ if (!name) return
470
+ try {
471
+ const d = (await call($, 'context_details', { name })) as ContextDetails
472
+ if ((await detailsOf($)) === name) await update($, details, () => d)
473
+ } catch (e) {
474
+ await fail($, trouble((e as Error).message))
475
+ }
476
+ }
477
+
478
+ /** Opens the page of a context that's off for this chat (or, with null, goes back to the list). */
479
+ async function manage($: Engine, name: string | null) {
480
+ await update($, details, () => null)
481
+ await update($, managing, () => name)
482
+ if (name) await loadDetails($)
483
+ }
484
+
485
+ /** What's wrong with a new context's name and description, or null. */
486
+ export function newContextProblem(name: string, description: string, existing: string[]): string | null {
487
+ if (!name) return 'Give it a name.'
488
+ if (!NAME_RE.test(name)) return 'A context name is lower-case letters, digits and dashes, such as "checkout-incident".'
489
+ if (existing.includes(name)) return `There's already a context '${name}' on this machine: turn it on in the list.`
490
+ if (!description.trim()) return 'Say what it’s for: every member’s agent reads that to decide what belongs there.'
491
+ return null
492
+ }
493
+
494
+ /**
495
+ * Starts a prompt in the prompt box for the person to finish and send: what they
496
+ * had typed stays, above it. The panel stays on the item, to read while writing.
497
+ */
498
+ async function draft($: Engine, text: string, what: string) {
499
+ try {
500
+ const box = await $.prompt.read()
501
+ const kept = box.text.replace(/\s+$/, '')
502
+ const r = await $.prompt.fill({ text: kept ? `${kept}\n\n${text}` : text })
503
+ if (r.isFilled) await clearError($).then(() => say($, `Your ${what} is started in the prompt box: finish its last line, then press Enter to send it to your agent.`))
504
+ else await fail($, r.refusal === 'dialog' ? 'Close the open dialog first: the prompt box can’t take text while it’s up.' : 'The prompt box couldn’t take the text here.')
505
+ } catch (e) {
506
+ await fail($, (e as Error).message)
507
+ }
508
+ }
509
+
510
+ /** Hands the person's words to the agent, as their own prompt: it shows in the chat, so the panel says nothing more. */
511
+ async function ask($: Engine, text: string) {
512
+ await openItem($, null)
513
+ await say($, null)
514
+ try {
515
+ await $.prompt.submit({ text, asUser: true })
516
+ } catch (e) {
517
+ await fail($, (e as Error).message)
518
+ }
519
+ }
520
+
521
+ /** Opens the panel: on the chat's contexts (to turn them on and off), or on a context. */
522
+ async function openPane($: Engine, contexts = false) {
523
+ wantSnapshot = true
524
+ await update($, switching, () => contexts)
525
+ // The panel opens on the list or the context, never on a step left half done.
526
+ await update($, creating, () => null)
527
+ await update($, deleting, () => null)
528
+ await update($, folds, () => [])
529
+ askedDetails = undefined
530
+ await manage($, null)
531
+ if (contexts) await openItem($, null)
532
+ await refresh($)
533
+ // `focus` also brings the panel's tab to the front when it's already open behind another.
534
+ return $.ui.open({ id: PANE, title: 'Context', focus: true, closeOnEscape: true })
535
+ }
536
+
537
+ export const register: Register = on => {
538
+ on('session.start', async ($, e, next) => {
539
+ await $.command.register({ name: 'contexts', description: "Open this chat's context: what needs you, its questions and threads, claims, people, and the chat's contexts" })
540
+ poll?.cancel()
541
+ loading?.cancel()
542
+ seen = undefined
543
+ failures = 0
544
+ await clearError($) // a reload forgets where the last error came from, so it starts clear
545
+ await update($, tick, () => 0)
546
+ // "loading." "loading.." "loading..." until the server first answers.
547
+ loading = $.clock.every(TICK_MS, () => void update($, tick, n => (n + 1) % 3))
548
+ poll = $.clock.every(POLL_MS, () => void refresh($))
549
+ void refresh($)
550
+ return next(e)
551
+ })
552
+
553
+ on('command.run', { command: 'contexts' }, async $ => {
554
+ const r = await openPane($)
555
+ return { text: r.isPlaced ? 'Context panel opened.' : `The panel couldn't open here: ${r.reason}` }
556
+ })
557
+
558
+ // The band above the prompt: always there.
559
+ on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
560
+ if (e.props.hasSurvey) return next(e)
561
+ const { Box, Text, Button } = $.ui.resolve(e)
562
+ const none = await read($, unattached)
563
+ const a = await read($, activity)
564
+ if (!none && !a) {
565
+ // The MCP server hasn't answered yet: a new chat's first seconds.
566
+ const n = await read($, tick)
567
+ const err = await read($, error)
568
+ if (failures < GIVE_UP_AFTER || !err)
569
+ return (
570
+ <Box flexDirection="row" gap={1}>
571
+ <Text dimColor>○ loading{'.'.repeat(n + 1)}</Text>
572
+ </Box>
573
+ )
574
+ return (
575
+ <Box flexDirection="row" gap={1} alignItems="center">
576
+ <Text color="warning">○</Text>
577
+ <Text dimColor>{short(err, 150)}</Text>
578
+ <Button key="retry" label="Retry" onPress={() => void refresh($)} />
579
+ </Box>
580
+ )
581
+ }
582
+ if (!a)
583
+ return (
584
+ <Box flexDirection="row" gap={1} alignItems="center">
585
+ <Text dimColor>○</Text>
586
+ <Text>
587
+ No context
588
+ <Text dimColor> · your agent will ask which this chat is for</Text>
589
+ </Text>
590
+ <Button key="choose-context" label="Choose" onPress={() => void openPane($, true)} />
591
+ </Box>
592
+ )
593
+ const l = await read($, latest)
594
+ const now = await $.clock.now()
595
+ const away = a.members - 1
596
+ const d = a.digest?.at(-1)
597
+ const main = a.contexts.find(c => c.writes_here)?.name ?? a.context
598
+ // The latest news: what others' changes meant for you if that's newest, else the latest change from someone else.
599
+ const news = d && (!l || d.at >= l.at) ? `${short(d.lines[0] ?? '', 70)} (${ago(d.at, now)})` : l ? `${l.by} ${short(l.summary, 60)} (${ago(l.at, now)})` : ''
600
+ const more = a.contexts.filter(c => c.name !== main).map(c => ` +${c.name}`).join('')
601
+ return (
602
+ <Box flexDirection="row" gap={1} alignItems="center" width="100%">
603
+ <Text color={a.sharing ? 'green' : undefined} dimColor={!a.sharing}>
604
+ ●
605
+ </Text>
606
+ <Button key="band-contexts" label={`${main}${more}`} plain onPress={() => void openPane($, true)} />
607
+ {/* The news takes the free room, so who's here and the open arrow sit at the right end. */}
608
+ <Box flexGrow={1} flexShrink={1}>
609
+ <Text dimColor wrap="truncate-end">
610
+ {news ? `· ${news}` : ''}
611
+ </Text>
612
+ </Box>
613
+ <Text dimColor>{a.sharing ? (away ? `${a.online.length}/${away} online` : 'just you') : 'offline'}</Text>
614
+ <Button key="open-context" label="❯" onPress={() => void openPane($)} />
615
+ </Box>
616
+ )
617
+ })
618
+
619
+
620
+ // The panel.
621
+ on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
622
+ const els = $.ui.resolve(e) as Record<string, any>
623
+ const { Box, Text, Button, Input, Select, Code } = els
624
+ const a = await read($, activity)
625
+ const err = await read($, error)
626
+ // The terminal draws borders as box characters: cards there would be heavy, so it gets plain rows.
627
+ const graphical = e.surface !== 'terminal'
628
+ const cols = e.props.bodyColumns ?? 80
629
+ const fit = paneFit(e.props)
630
+ const narrow = fit === 'narrow'
631
+ /**
632
+ * Text with its buttons beside it, at the right; stacked under it when the
633
+ * pane is narrow, so neither is squeezed to a sliver.
634
+ */
635
+ /** A line of text with a quiet copy button at its end, shown only while the pointer is on the line. */
636
+ const copyable = (key: string, content: unknown, text: string, what: string) => (
637
+ <Box key={key} flexDirection="row" gap={1} alignItems="center">
638
+ <Box flexShrink={1}>{content}</Box>
639
+ <Box display="none" hover={{ display: 'flex' }} flexShrink={0}>
640
+ <Button
641
+ key={`${key}-copy`}
642
+ label="⧉"
643
+ plain
644
+ dimColor
645
+ onPress={(press: UiPressArgument) =>
646
+ $.ui.copy({ text, surface: press.surface }).then(r => $.ui.toast(r.isCopied ? `Copied the ${what}: ${text}` : `Couldn’t copy the ${what}.`))
647
+ }
648
+ />
649
+ </Box>
650
+ </Box>
651
+ )
652
+
653
+ const split = (key: string, main: unknown, side: unknown, align: 'center' | 'flex-start' = 'flex-start') => {
654
+ const actions = [side].flat().filter(Boolean)
655
+ const buttons = actions.length > 0 && (
656
+ <Box flexDirection="row" gap="xs" flexWrap="wrap" flexShrink={0} alignItems="center">
657
+ {actions}
658
+ </Box>
659
+ )
660
+ return narrow ? (
661
+ <Box key={key} flexDirection="column" gap="xs">
662
+ <Box flexDirection="column">{main}</Box>
663
+ {buttons}
664
+ </Box>
665
+ ) : (
666
+ <Box key={key} flexDirection="row" gap={1} justifyContent="space-between" alignItems={align}>
667
+ <Box flexDirection="column" flexShrink={1}>
668
+ {main}
669
+ </Box>
670
+ {buttons}
671
+ </Box>
672
+ )
673
+ }
674
+ const card = (key: string, children: unknown, tone?: string) =>
675
+ graphical ? (
676
+ <Box key={key} flexDirection="column" borderStyle="round" borderColor={tone ?? 'subtle'} paddingX={1} paddingY="xs" gap="xs">
677
+ {children}
678
+ </Box>
679
+ ) : (
680
+ <Box key={key} flexDirection="column">
681
+ {children}
682
+ </Box>
683
+ )
684
+ const heading = (text: string, count?: number | string) => (
685
+ <Text size="heading" weight="semibold" bold>
686
+ {text}
687
+ {count !== undefined && <Text dimColor weight="regular"> {count}</Text>}
688
+ </Text>
689
+ )
690
+ const meta = (text: string) => (
691
+ <Text size="footnote" dimColor wrap="wrap">
692
+ {text}
693
+ </Text>
694
+ )
695
+ /**
696
+ * One of a row of choices: the chosen one stands out. On a graphical surface its filled colour says so, and
697
+ * nothing is added to its label, so the row doesn't shift as the choice moves. A terminal may have no colour
698
+ * to go by, so there the chosen one is marked with ▸ as well.
699
+ */
700
+ const chip = (key: string, label: string, active: boolean, onPress: () => void) => (
701
+ <Button key={key} label={`${active && !graphical ? '▸ ' : ''}${label}`} variant={active ? 'primary' : 'secondary'} dimColor={!active} onPress={onPress} />
702
+ )
703
+ const note = await read($, notice)
704
+ const made = await read($, code)
705
+ const none = await read($, unattached)
706
+
707
+ // Minimized to a widget on the desktop app: what reads at a glance, with
708
+ // nothing to press, since clicks may not reach it. Expanding it brings back
709
+ // whatever view was open.
710
+ if (fit === 'glance') {
711
+ const s = a?.snapshot
712
+ const th = s ? threads(s.nodes, s.edges) : undefined
713
+ const rl = s ? relations(s.nodes, s.edges) : undefined
714
+ const unsent = a ? a.recent.filter((c: Change) => c.held && c.mine).length : 0
715
+ const others = a ? a.people.filter((p: Person) => p.role && p.online && !p.you).length : 0
716
+ const facts = a
717
+ ? [
718
+ a.sharing ? `${others} other${others === 1 ? '' : 's'} online` : 'Offline',
719
+ th && th.open.length ? `❓ ${th.open.length} open` : '',
720
+ rl && rl.conflicts.length ? `⚡ ${rl.conflicts.length} conflict${rl.conflicts.length === 1 ? '' : 's'}` : '',
721
+ unsent ? `${unsent} not sent yet` : '',
722
+ ].filter(Boolean)
723
+ : []
724
+ const last = a?.recent[0]
725
+ return (
726
+ <Box key="glance" flexDirection="column" gap="xs" paddingX={graphical ? 1 : 0}>
727
+ <Text weight="semibold" bold wrap="wrap">
728
+ <Text color={none || !a ? undefined : a.sharing ? 'success' : 'warning'}>● </Text>
729
+ {none ? 'No context in this chat' : (a?.context ?? 'Context')}
730
+ </Text>
731
+ <Text size="footnote" dimColor wrap="wrap">
732
+ {none ? 'Open the panel to turn one on.' : a ? facts.join(' · ') : (err ?? 'Loading…')}
733
+ </Text>
734
+ {!none && last && (
735
+ <Box key="glance-latest">
736
+ <Text size="footnote" wrap="wrap">
737
+ <Text weight="semibold" bold>
738
+ {last.mine ? 'you' : last.by}
739
+ </Text>{' '}
740
+ {short(last.summary, 80)}
741
+ </Text>
742
+ </Box>
743
+ )}
744
+ </Box>
745
+ )
746
+ }
747
+ const dismiss = () => void clearError($).then(() => say($, null))
748
+ const messages =
749
+ err || note
750
+ ? card(
751
+ err ? 'error' : 'notice',
752
+ <Box flexDirection="row" gap={1} justifyContent="space-between" alignItems="flex-start">
753
+ <Box flexShrink={1}>
754
+ <Text color={err ? 'error' : 'success'} wrap="wrap">
755
+ {err ?? note}
756
+ </Text>
757
+ </Box>
758
+ <Button key="dismiss-message" label="×" plain dimColor onPress={dismiss} />
759
+ </Box>,
760
+ err ? 'error' : 'success',
761
+ )
762
+ : null
763
+ /** A view that takes the whole panel: a title, what it's about, its body, and a way out. */
764
+ const modal = (key: string, title: string, about: string | null, body: unknown, close?: { label: string; onPress: () => void }) => (
765
+ <Box key={key} flexDirection="column" gap="md" paddingX={graphical ? 1 : 0}>
766
+ <Box flexDirection="column" gap="xs">
767
+ <Box flexDirection="row" gap={1} justifyContent="space-between" alignItems="flex-start">
768
+ <Box flexShrink={1}>
769
+ <Text size="title" weight="semibold" bold wrap="wrap">
770
+ {title}
771
+ </Text>
772
+ </Box>
773
+ {close && <Button key={`close-${key}`} label={caret(close.label)} variant="secondary" dimColor onPress={close.onPress} />}
774
+ </Box>
775
+ {about && <Text wrap="wrap">{about}</Text>}
776
+ </Box>
777
+ {messages}
778
+ {body}
779
+ </Box>
780
+ )
781
+
782
+ /** A label over a field as wide as the panel, with a line of help under it. */
783
+ const field = (label: string, input: unknown, help?: string) => (
784
+ <Box flexDirection="column" gap="xs" width="100%" alignItems="stretch">
785
+ <Text weight="semibold" bold>
786
+ {label}
787
+ </Text>
788
+ {input}
789
+ {help && meta(help)}
790
+ </Box>
791
+ )
792
+ const opened: string[] = await read($, folds)
793
+ const flip = (id: string) => void update($, folds, (v: string[]) => (v.includes(id) ? v.filter(x => x !== id) : [...v, id]))
794
+ /** An underlined link that opens and closes what it's about. */
795
+ const foldLink = (id: string, open: boolean, label: string) => (
796
+ <Box key={`fold-row-${id}`} flexDirection="row">
797
+ <Button key={`fold-${id}`} plain dimColor onPress={() => flip(id)}>
798
+ <Text underline>{label}</Text>
799
+ {open ? ' ▴' : ' ▾'}
800
+ </Button>
801
+ </Box>
802
+ )
803
+ /**
804
+ * A list that shows only its first few items, with a link for the rest (and
805
+ * one to fold them away again). With `latest`, the few are the last ones and
806
+ * the link comes first, as for the earlier replies in a thread.
807
+ */
808
+ const folded = <T,>(id: string, list: T[], first: number, what: string, one: string, render: (x: T, i: number) => unknown, latest = false) => {
809
+ const hidden = list.length - first
810
+ if (hidden <= 0) return list.map(render)
811
+ const open = opened.includes(id)
812
+ const shown = open ? list : latest ? list.slice(-first) : list.slice(0, first)
813
+ const link = foldLink(id, open, open ? `Show fewer ${what}` : `${hidden} ${latest ? 'earlier' : 'more'} ${hidden === 1 ? one : what}`)
814
+ return latest ? [link, ...shown.map(render)] : [...shown.map(render), link]
815
+ }
816
+ /** Extra detail behind an underlined link, closed until asked for. */
817
+ const reveal = (id: string, label: string, hide: string, body: unknown) =>
818
+ opened.includes(id) ? (
819
+ <Box key={`reveal-${id}`} flexDirection="column" gap="xs">
820
+ {foldLink(id, true, hide)}
821
+ {body}
822
+ </Box>
823
+ ) : (
824
+ foldLink(id, false, label)
825
+ )
826
+ const here = none ?? a?.your_contexts ?? []
827
+ const using = a?.contexts ?? []
828
+ const inChat = (n: string) => using.find(c => c.name === n)
829
+ const loadedDetails = await read($, details)
830
+ /** Shows one of the chat's contexts: the panel leaves the list for it. */
831
+ const show = (n: string) =>
832
+ update($, viewing, () => n)
833
+ .then(() => refresh($))
834
+ .then(() => manage($, null))
835
+ .then(() => update($, switching, () => false))
836
+ /** Opens one of the chat's contexts on its Settings tab. */
837
+ const settingsTab = (n: string) =>
838
+ show(n)
839
+ .then(() => update($, more, () => 0))
840
+ .then(() => update($, tab, () => 'settings' as Tab))
841
+ .then(() => {
842
+ askedDetails = n
843
+ return loadDetails($)
844
+ })
845
+ /** Turns a context on or off for this chat. */
846
+ const toggle = (n: string) =>
847
+ void (inChat(n)
848
+ ? act($, 'remove_context', { name: n }, `'${n}' is off for this chat. It stays on this machine.`)
849
+ : act($, using.length ? 'add_context' : 'use_context', { name: n }, `'${n}' is on for this chat.`))
850
+ /** Starts the join-code step for one of the chat's contexts: the panel moves to it, and the code lands in its People tab. */
851
+ const share = (n: string) => {
852
+ inviteNote = ''
853
+ return show(n).then(() => update($, inviting, () => ({ name: n, role: 'contributor' as Invite['role'] })))
854
+ }
855
+ const writeHere = (n: string) => void act($, 'add_context', { name: n, write_here: true }, `New items go to '${n}' unless another fits better.`)
856
+
857
+ /** A context's pin: whether new chats started in this chat's folder (or below it) start with it. */
858
+ const pin = (n: string, where: string) => {
859
+ const f = a?.folder
860
+ if (!f) return null
861
+ const pinned = (f.pinned ?? []).includes(n)
862
+ return (
863
+ <Button
864
+ key={`pin-${where}${n}`}
865
+ plain
866
+ dimColor={!pinned}
867
+ onPress={() =>
868
+ void act($, 'link_folder', pinned ? { name: n, off: true } : { name: n }, pinned ? `New chats in this folder no longer start with '${n}'.` : `New chats in this folder start with '${n}'.`)
869
+ }
870
+ >
871
+ {pinned ? '📌 On for new chats in ' : '📌 Turn on for new chats in '}
872
+ {/* The folder's end is what tells folders apart, so a long path loses its start. Desktop always
873
+ cuts a Text at its end, so the cut is made here; it leaves more room there for the wider font. */}
874
+ <Text size="footnote" dimColor wrap="truncate-start">
875
+ {tail(f.folder, Math.max(12, Math.min(48, cols - (graphical ? 22 : 18))))}
876
+ </Text>
877
+ </Button>
878
+ )
879
+ }
880
+
881
+ /**
882
+ * A context's settings: how this chat uses it, its sharing, what it holds,
883
+ * and deleting it. The open context's Settings tab, and the page of one
884
+ * that's off for this chat (`inTab` false), where only some of it can be changed.
885
+ */
886
+ const settings = (n: string, inTab: boolean) => {
887
+ const c = inChat(n)
888
+ const d = loadedDetails && loadedDetails.name === n ? loadedDetails : null
889
+ const isAdmin = (d?.role ?? c?.role) === 'admin'
890
+ const severalOn = using.length > 1
891
+ const sharing = d?.sharing ?? (inTab ? a?.sharing : undefined)
892
+ const relays = inTab ? a?.relays_up : undefined
893
+ // A label column beside its value; narrow, the label sits over it instead.
894
+ const row = (label: string, value: unknown) =>
895
+ narrow ? (
896
+ <Box key={`detail-${label}`} flexDirection="column">
897
+ <Text size="footnote" dimColor>
898
+ {label}
899
+ </Text>
900
+ <Text wrap="wrap">{value}</Text>
901
+ </Box>
902
+ ) : (
903
+ <Box key={`detail-${label}`} flexDirection="row" gap={1} alignItems="flex-start">
904
+ <Box width={10} flexShrink={0}>
905
+ <Text dimColor>{label}</Text>
906
+ </Box>
907
+ <Box flexShrink={1} flexGrow={1}>
908
+ <Text wrap="wrap">{value}</Text>
909
+ </Box>
910
+ </Box>
911
+ )
912
+ const count = (k: string, one: string, plural: string) => `${d?.items[k] ?? 0} ${(d?.items[k] ?? 0) === 1 ? one : plural}`
913
+ const description = d ? d.description : descriptionOf(n)
914
+ const fresh = !inTab && madeCode?.name === n ? madeCode : null
915
+ /** No one else has joined, so there is nobody to sync with. */
916
+ const alone = d?.members === 1
917
+ return (
918
+ <Box key={`settings-${n}`} flexDirection="column" gap="md">
919
+ <Box flexDirection="column" gap="xs">
920
+ {heading('Name')}
921
+ {/* The id every member shares sits right under this machine's name for it, with nothing between. */}
922
+ {split(
923
+ `name-row-${n}`,
924
+ [
925
+ copyable(
926
+ `context-name-${n}`,
927
+ <Text weight="semibold" bold wrap="wrap">
928
+ {n}
929
+ </Text>,
930
+ n,
931
+ 'name',
932
+ ),
933
+ d?.id &&
934
+ copyable(
935
+ `context-id-${n}`,
936
+ <Text size="footnote" dimColor mono wrap="wrap">
937
+ {d.id}
938
+ </Text>,
939
+ d.id,
940
+ 'id',
941
+ ),
942
+ ],
943
+ <Button key={`rename-context-${n}`} label="✎ Rename" variant="secondary" dimColor onPress={() => ((renameText = ''), void update($, renamingContext, () => n))} />,
944
+ 'center',
945
+ )}
946
+ </Box>
947
+ <Box flexDirection="column" gap="xs">
948
+ {heading('What it’s for')}
949
+ {split(
950
+ `description-row-${n}`,
951
+ description ? (
952
+ <Text wrap="wrap">{description}</Text>
953
+ ) : (
954
+ <Text italic dimColor wrap="wrap">
955
+ No description yet, so agents won’t know what belongs here.
956
+ </Text>
957
+ ),
958
+ isAdmin && <Button key={`describe-${n}`} label={description ? '✎ Edit' : 'Describe'} variant={description ? 'secondary' : 'primary'} dimColor={!!description} onPress={() => void update($, editing, () => n)} />,
959
+ )}
960
+ {!isAdmin && (d?.role ?? c?.role) && meta('Only an admin can change it.')}
961
+ </Box>
962
+ <Box flexDirection="column" gap="xs">
963
+ {heading('This chat')}
964
+ <Box flexDirection="row" gap="xs" justifyContent="space-between" alignItems="center">
965
+ <Box flexDirection="row" gap="xs" flexWrap="wrap" alignItems="center">
966
+ <Button key={`detail-toggle-${n}`} label={c ? '◉ On' : '○ Off'} variant={c ? 'primary' : 'secondary'} dimColor={!c} onPress={() => toggle(n)} />
967
+ {c && severalOn && !c.writes_here && <Button key={`detail-write-${n}`} label="✎ Write here" variant="secondary" onPress={() => writeHere(n)} />}
968
+ </Box>
969
+ {c && !inTab && <Button key={`detail-open-${n}`} label="Open ›" variant="secondary" onPress={() => void show(n)} />}
970
+ </Box>
971
+ {meta(
972
+ c
973
+ ? severalOn
974
+ ? c.writes_here
975
+ ? 'Your agent looks things up in this context, and records new items in it unless another context clearly fits better.'
976
+ : 'Your agent looks things up in this context, and records a new item in it only when the item fits its description.'
977
+ : 'This chat uses this context: your agent looks things up in it and records new claims and questions in it. Turning it off only affects this chat. Your copy stays on this machine.'
978
+ : 'This chat isn’t using this context. Turn it on to open it here, share it or change its settings.',
979
+ )}
980
+ {pin(n, 'detail-')}
981
+ </Box>
982
+ <Box flexDirection="column" gap="xs">
983
+ {heading('Sharing')}
984
+ {sharing === undefined ? (
985
+ <Text dimColor>Loading…</Text>
986
+ ) : (
987
+ <Text wrap="wrap">
988
+ <Text color={sharing ? 'success' : 'warning'}>● </Text>
989
+ {!sharing ? 'Offline' : alone ? 'Only you so far' : 'Syncing'}
990
+ <Text dimColor>
991
+ {!sharing && alone ? ' · only you so far' : ''}
992
+ {d && !alone ? ` · ${d.members} members · ${d.online} of the others online now` : ''}
993
+ {d?.open_invites ? ` · ${d.open_invites} join code${d.open_invites === 1 ? '' : 's'} not used yet` : ''}
994
+ </Text>
995
+ </Text>
996
+ )}
997
+ {/* Said only when something is off, or there's no one to sync with yet: the usual state needs no explaining. */}
998
+ {sharing === false
999
+ ? meta('Your copy keeps working. What you write is sent when you’re back online.')
1000
+ : relays === 0
1001
+ ? meta('This machine can’t reach the servers that help members find each other, so nothing syncs right now.')
1002
+ : alone
1003
+ ? meta(d?.open_invites ? 'Nobody has joined yet. Syncing starts when someone uses a join code you sent.' : 'Nobody else is in this context yet. Invite someone to share it with them.')
1004
+ : null}
1005
+ {(
1006
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1007
+ {isAdmin && (
1008
+ <Button
1009
+ key={`detail-invite-${n}`}
1010
+ label="+ Invite someone"
1011
+ variant="primary"
1012
+ onPress={() => {
1013
+ inviteNote = ''
1014
+ return update($, inviting, () => ({ name: n, role: 'contributor' as Invite['role'] }))
1015
+ }}
1016
+ />
1017
+ )}
1018
+ {/* The open context's header already has this switch. */}
1019
+ {!inTab &&
1020
+ sharing !== undefined &&
1021
+ (sharing ? (
1022
+ <Button key={`detail-offline-${n}`} label="Go offline" variant="secondary" dimColor onPress={() => void act($, 'stop_sharing', { context: n }, `'${n}' is offline: not syncing until you go online again.`)} />
1023
+ ) : (
1024
+ <Button key={`detail-online-${n}`} label="Go online" variant="secondary" onPress={() => void act($, 'start_sharing', { context: n }, `'${n}' is back online: syncing with the other members.`)} />
1025
+ ))}
1026
+ </Box>
1027
+ )}
1028
+ {!isAdmin && (d?.role ?? c?.role) && meta('Only an admin can invite people.')}
1029
+ {fresh && (
1030
+ <Box key={`made-${n}`} flexDirection="column" gap="xs">
1031
+ {split(
1032
+ `made-row-${n}`,
1033
+ <Text wrap="wrap">
1034
+ <Text weight="semibold" bold>
1035
+ {fresh.label ? `For ${fresh.label.replace(/^for\s+/i, '')}` : 'No note'}
1036
+ </Text>
1037
+ <Text dimColor> · {fresh.role}</Text>
1038
+ <Text color="success"> · new: send it now</Text>
1039
+ </Text>,
1040
+ <Button
1041
+ key={`copy-made-${n}`}
1042
+ label="Copy"
1043
+ variant="secondary"
1044
+ onPress={(press: UiPressArgument) => void $.ui.copy({ text: fresh.send, surface: press.surface }).then(r => r.isCopied && $.ui.toast('Copied: send it privately, to that one person.'))}
1045
+ />,
1046
+ 'center',
1047
+ )}
1048
+ {Code ? <Code source={fresh.send} /> : <Text>{fresh.send}</Text>}
1049
+ {meta('Turn it on and open its People tab to see or cancel its codes.')}
1050
+ </Box>
1051
+ )}
1052
+ </Box>
1053
+ <Box flexDirection="column" gap="xs">
1054
+ {heading('About')}
1055
+ {d ? (
1056
+ <Box flexDirection="column" gap="xs">
1057
+ <Box flexDirection="column">
1058
+ {row('Your role', d.role ?? 'removed (you keep your copy to read)')}
1059
+ {row('Made by', d.yours ? 'you' : (d.created_by ?? 'unknown'))}
1060
+ {row('Holds', `${count('Claim', 'claim', 'claims')} · ${count('Question', 'question', 'questions')} · ${count('Reply', 'reply', 'replies')}`)}
1061
+ {d.held > 0 && row('Not yet sent', `${d.held} just written, still only on this machine`)}
1062
+ </Box>
1063
+ {reveal(
1064
+ `about-${n}`,
1065
+ 'Storage and history',
1066
+ 'Hide storage and history',
1067
+ <Box key={`about-more-${n}`} flexDirection="column">
1068
+ {row('Changes', `${d.changes} in all, withdrawn items included`)}
1069
+ {row('Stored at', d.stored_at)}
1070
+ </Box>,
1071
+ )}
1072
+ </Box>
1073
+ ) : (
1074
+ <Text dimColor>{err ? 'Couldn’t read its details.' : 'Loading…'}</Text>
1075
+ )}
1076
+ </Box>
1077
+ <Box flexDirection="column" gap="xs">
1078
+ {heading('Delete')}
1079
+ {meta('Deletes this machine’s copy for good. Other members keep theirs. You’ll be asked to confirm.')}
1080
+ <Box flexDirection="row">
1081
+ <Button
1082
+ key={`ask-delete-${n}`}
1083
+ label="Delete from this machine…"
1084
+ variant="secondary"
1085
+ dimColor
1086
+ onPress={() => {
1087
+ deleteText = ''
1088
+ return update($, deleting, () => ({ name: n, error: null }))
1089
+ }}
1090
+ />
1091
+ </Box>
1092
+ </Box>
1093
+ </Box>
1094
+ )
1095
+ }
1096
+
1097
+ /** A context's description as best known: its details, else the chat's list, else the open context. */
1098
+ const descriptionOf = (n: string) =>
1099
+ (loadedDetails && loadedDetails.name === n ? loadedDetails.description : null) ?? inChat(n)?.description ?? (a?.context === n ? a.description : null) ?? null
1100
+
1101
+ // Editing a context's description, from its Settings or the open context's header: only that.
1102
+ const describingNow = await read($, editing)
1103
+ if (typeof describingNow === 'string' && here.includes(describingNow)) {
1104
+ const n = describingNow
1105
+ const before = descriptionOf(n)
1106
+ const close = () => void update($, editing, () => false)
1107
+ return modal(
1108
+ 'describe-step',
1109
+ `Describe ${n}`,
1110
+ 'What goes in it, and what doesn’t. It syncs to every member, and their agents use it to decide what belongs here.',
1111
+ field(
1112
+ `What is '${n}' for?`,
1113
+ <Input
1114
+ key="describe"
1115
+ value={before ?? ''}
1116
+ placeholder="What goes in it, in a sentence or two"
1117
+ submitLabel="Save"
1118
+ rows={4}
1119
+ autoFocus
1120
+ onSubmit={(v: string) => {
1121
+ close()
1122
+ if (v.trim() && v.trim() !== before) void act($, 'describe_context', { description: v.trim(), context: n }, 'Saved. Every member’s agent sees it.')
1123
+ }}
1124
+ />,
1125
+ ),
1126
+ { label: 'Cancel', onPress: close },
1127
+ )
1128
+ }
1129
+
1130
+ // Renaming a context on this machine: only that.
1131
+ const renamingNow = await read($, renamingContext)
1132
+ if (renamingNow && here.includes(renamingNow)) {
1133
+ const n = renamingNow
1134
+ const close = () => {
1135
+ renameText = ''
1136
+ void update($, renamingContext, () => null)
1137
+ }
1138
+ const rename = (typed: string) => {
1139
+ const to = typed.trim().toLowerCase().replace(/\s+/g, '-')
1140
+ if (!to || to === n) return close()
1141
+ if (!NAME_RE.test(to)) return void fail($, 'A context name is lower-case letters, digits and dashes, such as "checkout-incident".')
1142
+ if (here.includes(to)) return void fail($, `There's already a context '${to}' on this machine.`)
1143
+ close()
1144
+ void renameContext($, n, to)
1145
+ }
1146
+ return modal(
1147
+ 'rename-context-step',
1148
+ `Rename ${n}`,
1149
+ 'The name is this machine’s label for it. Other members keep their own name for it, and every chat and folder here that uses it follows the new one.',
1150
+ <Box flexDirection="column" gap="sm">
1151
+ <Input
1152
+ key={`rename-context-${n}`}
1153
+ label="New name"
1154
+ value={n}
1155
+ placeholder="lower-case letters, digits and dashes"
1156
+ submitLabel="Rename"
1157
+ autoFocus
1158
+ onInput={(v: string) => (renameText = v)}
1159
+ onSubmit={rename}
1160
+ />
1161
+ <Box flexDirection="row">
1162
+ <Button key="do-rename-context" label="Rename" variant="primary" onPress={() => rename(renameText || n)} />
1163
+ </Box>
1164
+ </Box>,
1165
+ { label: 'Cancel', onPress: close },
1166
+ )
1167
+ }
1168
+
1169
+ // Making a join code for a context, on or off for this chat: who it's for and their role. An open
1170
+ // context's code waits in its People tab; an off one's shows on its page.
1171
+ const invitingNow = await read($, inviting)
1172
+ const managedNow = await read($, managing)
1173
+ if (invitingNow && typeof invitingNow === 'object' && here.includes(invitingNow.name)) {
1174
+ const { name: n, role } = invitingNow
1175
+ const close = () => void update($, inviting, () => null)
1176
+ const make = (text: string) => {
1177
+ inviteNote = ''
1178
+ close()
1179
+ if (inChat(n) && a?.context === n && !(managedNow === n)) void update($, tab, () => 'people' as Tab)
1180
+ void act($, 'share_context', { ...(text.trim() ? { label: text.trim() } : {}), ...(role !== 'contributor' ? { role } : {}), context: n }, 'Join code made. Copy it and send it privately, to that one person.')
1181
+ }
1182
+ return modal(
1183
+ 'invite-step',
1184
+ `Invite someone to ${n}`,
1185
+ 'A join code lets one person in: whoever uses it first. Send it to them privately. It expires in 24 hours if no one uses it.',
1186
+ <Box flexDirection="column" gap="sm">
1187
+ {Select && (
1188
+ <Select
1189
+ key="invite-role"
1190
+ label="They can"
1191
+ value={role}
1192
+ options={[
1193
+ { key: 'contributor', value: 'contributor', label: 'Read and add (contributor)' },
1194
+ { key: 'reader', value: 'reader', label: 'Only read (reader)' },
1195
+ { key: 'admin', value: 'admin', label: 'Read, add and invite (admin)' },
1196
+ ]}
1197
+ onSelect={(r: string) => void update($, inviting, () => ({ name: n, role: r as Invite['role'] }))}
1198
+ />
1199
+ )}
1200
+ {field(
1201
+ 'Who is it for? (optional)',
1202
+ <Input
1203
+ key="invite-note"
1204
+ placeholder="e.g. Sam: shown when they join, so a code used by someone else stands out"
1205
+ autoFocus
1206
+ onInput={(v: string) => (inviteNote = v)}
1207
+ onSubmit={make}
1208
+ />,
1209
+ )}
1210
+ <Box flexDirection="row">
1211
+ <Button key="make-code" label="Make join code" variant="primary" onPress={() => make(inviteNote)} />
1212
+ </Box>
1213
+ {meta('This machine answers the code, so it must be online when they use it. Everyone in the context is told who joined.')}
1214
+ </Box>,
1215
+ { label: 'Cancel', onPress: close },
1216
+ )
1217
+ }
1218
+
1219
+ // Confirming a deletion, from the Settings tab or an off context's page:
1220
+ // only that. Nothing goes until the name is typed.
1221
+ const doomed = await read($, deleting)
1222
+ if (doomed && here.includes(doomed.name)) {
1223
+ const n = doomed.name
1224
+ const known = loadedDetails && loadedDetails.name === n ? loadedDetails : null
1225
+ const close = () => {
1226
+ deleteText = ''
1227
+ void update($, deleting, () => null)
1228
+ }
1229
+ const confirm = (typed: string) => {
1230
+ if (typed.trim() !== n) return update($, deleting, () => ({ name: n, error: `Type ${n} exactly to delete it. Nothing was deleted.` }))
1231
+ deleteText = ''
1232
+ return update($, deleting, () => null)
1233
+ .then(() => manage($, null))
1234
+ .then(() => update($, viewing, () => null))
1235
+ .then(() => update($, tab, () => 'overview' as Tab))
1236
+ .then(() => act($, 'delete_context', { name: n, confirm: n }, `'${n}' was deleted from this machine.`))
1237
+ }
1238
+ const items = known ? Object.values(known.items).reduce((x, y) => x + y, 0) : null
1239
+ const others = known ? known.members - (known.role ? 1 : 0) : null
1240
+ return modal(
1241
+ 'delete-step',
1242
+ `Delete ${n}?`,
1243
+ `This permanently deletes this machine’s copy of '${n}'${items !== null ? `: its ${items} item${items === 1 ? '' : 's'}, their history` : ': its claims, questions and replies, their history'}, the join codes made here, and every chat’s and folder’s link to it. It can’t be undone.`,
1244
+ <Box flexDirection="column" gap="md">
1245
+ {card(
1246
+ 'delete-effects',
1247
+ <Box flexDirection="column" gap="xs">
1248
+ {others === null ? (
1249
+ <Text wrap="wrap">Other members keep their own copies. If you’re its only member, it’s gone for good.</Text>
1250
+ ) : others > 0 ? (
1251
+ <Text wrap="wrap">
1252
+ {others} other member{others === 1 ? ' keeps their' : 's keep their'} own copy, and nothing is deleted for them. To get it back you’d need a new join code from one of its admins.
1253
+ </Text>
1254
+ ) : (
1255
+ <Text color="warning" wrap="wrap">
1256
+ You’re its only member, so this is the only copy: once deleted, it’s gone for good.
1257
+ </Text>
1258
+ )}
1259
+ {known?.yours && others !== null && others > 0 && (
1260
+ <Text color="warning" wrap="wrap">
1261
+ You made this context. The other members keep syncing with each other, but the join codes you made stop working.
1262
+ </Text>
1263
+ )}
1264
+ {inChat(n) && meta('To only stop using it in this chat, turn it off instead: it stays on this machine.')}
1265
+ </Box>,
1266
+ 'warning',
1267
+ )}
1268
+ {field(
1269
+ `Type ${n} to confirm`,
1270
+ <Input key={`delete-confirm-${n}`} placeholder={n} autoFocus onInput={(v: string) => (deleteText = v)} onSubmit={(v: string) => confirm(v)} />,
1271
+ )}
1272
+ {doomed.error && (
1273
+ <Text color="error" wrap="wrap">
1274
+ {doomed.error}
1275
+ </Text>
1276
+ )}
1277
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1278
+ <Button key="keep-context" label="Keep it" variant="primary" onPress={close} />
1279
+ <Button key={`delete-${n}`} label="Delete permanently" variant="secondary" onPress={() => confirm(deleteText)} />
1280
+ </Box>
1281
+ </Box>,
1282
+ { label: 'Cancel', onPress: close },
1283
+ )
1284
+ }
1285
+
1286
+ // A new context: its name and what it's for, together. Only that.
1287
+ const creatingNow = await read($, creating)
1288
+ if (creatingNow) {
1289
+ const close = () => void update($, creating, () => null)
1290
+ const create = () => {
1291
+ const name = newName.trim().toLowerCase().replace(/\s+/g, '-')
1292
+ const description = newDescription.trim()
1293
+ const problem = newContextProblem(name, description, here)
1294
+ if (problem) return update($, creating, () => ({ error: problem }))
1295
+ newName = ''
1296
+ newDescription = ''
1297
+ return update($, creating, () => null)
1298
+ .then(() => update($, switching, () => false))
1299
+ .then(() => update($, viewing, () => name))
1300
+ .then(() => act($, a ? 'add_context' : 'use_context', { name, description }, `Created '${name}'${a ? ' and added it to this chat' : ''}. No one is invited yet: use Invite someone when you want to let a person in.`))
1301
+ }
1302
+ return modal(
1303
+ 'new-context-step',
1304
+ 'Create a new context',
1305
+ 'A context holds what a group knows, as claims and questions, shared with the people you invite.',
1306
+ <Box flexDirection="column" gap="md">
1307
+ {field(
1308
+ 'Name',
1309
+ <Input
1310
+ key="new-name"
1311
+ placeholder="e.g. checkout-incident"
1312
+ autoFocus
1313
+ onInput={(v: string) => (newName = v)}
1314
+ onSubmit={(v: string) => {
1315
+ newName = v
1316
+ return create()
1317
+ }}
1318
+ />,
1319
+ 'Short: lower-case letters, digits and dashes.',
1320
+ )}
1321
+ {field(
1322
+ 'What is it for?',
1323
+ <Input
1324
+ key="new-description"
1325
+ placeholder="What goes in it, in a sentence or two"
1326
+ rows={4}
1327
+ onInput={(v: string) => (newDescription = v)}
1328
+ onSubmit={(v: string) => {
1329
+ newDescription = v
1330
+ return create()
1331
+ }}
1332
+ />,
1333
+ 'Every member’s agent reads this to decide what belongs there. You can change it later.',
1334
+ )}
1335
+ {creatingNow.error && (
1336
+ <Text color="error" wrap="wrap">
1337
+ {creatingNow.error}
1338
+ </Text>
1339
+ )}
1340
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1341
+ <Button key="create-context" label="Create" variant="primary" onPress={() => create()} />
1342
+ <Button key="cancel-create" label="‹ Cancel" variant="secondary" dimColor onPress={close} />
1343
+ </Box>
1344
+ {meta('It’s yours: you’re its admin, and it’s added to this chat. Invite people from its People tab, or with Share in the list.')}
1345
+ </Box>,
1346
+ { label: 'Cancel', onPress: close },
1347
+ )
1348
+ }
1349
+
1350
+ // The chat's contexts, each with a switch: on means this chat uses it.
1351
+ if (none !== null || (await read($, switching))) {
1352
+ const many = using.length > 1
1353
+
1354
+ // A context that's off for this chat: what it's for and its settings. One
1355
+ // that's on opens instead, with these on its Settings tab.
1356
+ const managed = await read($, managing)
1357
+ if (managed && here.includes(managed)) {
1358
+ const n = managed
1359
+ return modal(
1360
+ 'context-details',
1361
+ n,
1362
+ null,
1363
+ settings(n, false),
1364
+ { label: '‹ Contexts', onPress: () => void manage($, null) },
1365
+ )
1366
+ }
1367
+
1368
+ return modal(
1369
+ 'contexts',
1370
+ 'Contexts in this chat',
1371
+ none
1372
+ ? here.length
1373
+ ? 'This chat has no context yet, so your agent will ask which it’s for. Turn one on, or create one.'
1374
+ : 'A context holds what a group knows, as claims and questions, shared with the people you invite. Create one for this chat, or join one with a code someone sent you.'
1375
+ : many
1376
+ ? 'Your agent reads all of these, and puts each new item in the one whose description fits. ✎ marks where it writes when none clearly does.'
1377
+ : 'Most chats use one context. Turn another on to use it too: your agent then picks the right one for each item.',
1378
+ <Box flexDirection="column" gap="sm">
1379
+ <Box flexDirection="column" gap="xs">
1380
+ <Box flexDirection="row">
1381
+ <Button
1382
+ key="create-new-context"
1383
+ label="+ Create new context"
1384
+ variant="primary"
1385
+ onPress={() => {
1386
+ newName = ''
1387
+ newDescription = ''
1388
+ return update($, creating, () => ({ error: null }))
1389
+ }}
1390
+ />
1391
+ </Box>
1392
+ {meta('Got a join code? Paste it to your agent, or run /vine-context:join with it.')}
1393
+ </Box>
1394
+ {here.map(n => {
1395
+ const c = inChat(n)
1396
+ return card(
1397
+ `ctx-${n}`,
1398
+ <Box flexDirection="column" gap="xs">
1399
+ {/* Wraps so a long name pushes the toggle onto its own line instead of past the card's edge. */}
1400
+ <Box key={`ctx-head-${n}`} flexDirection="row" gap={1} justifyContent="space-between" alignItems="center" flexWrap="wrap">
1401
+ <Box flexDirection="row" gap="xs" alignItems="center" flexShrink={1} flexWrap="wrap">
1402
+ <Button key={`name-${n}`} label={n} plain onPress={() => (c ? show(n) : manage($, n))} />
1403
+ <Text>
1404
+ {c && <Text dimColor>· {c.role ?? 'removed'}</Text>}
1405
+ {c && many && c.writes_here ? <Text color="suggestion"> ✎ writes here</Text> : ''}
1406
+ </Text>
1407
+ </Box>
1408
+ <Button key={`toggle-${n}`} label={c ? '◉ On' : '○ Off'} variant={c ? 'primary' : 'secondary'} dimColor={!c} onPress={() => toggle(n)} />
1409
+ </Box>
1410
+ {c && (
1411
+ <Text size="footnote" dimColor italic={!c.description} wrap="wrap">
1412
+ {c.description ?? 'No description yet'}
1413
+ </Text>
1414
+ )}
1415
+ <Box flexDirection="row" gap="xs" justifyContent="space-between" alignItems="center">
1416
+ <Box flexDirection="row" gap="xs" flexWrap="wrap" alignItems="center">
1417
+ <Button key={`settings-${n}`} label="Settings" variant="secondary" dimColor onPress={() => (c ? settingsTab(n) : manage($, n))} />
1418
+ {c?.role === 'admin' && <Button key={`share-${n}`} label="Share" variant="secondary" dimColor onPress={() => share(n)} />}
1419
+ {c && many && !c.writes_here && <Button key={`write-${n}`} label="✎ Write here" variant="secondary" dimColor onPress={() => writeHere(n)} />}
1420
+ </Box>
1421
+ {c && <Button key={`open-${n}`} label="Open ›" variant="secondary" onPress={() => show(n)} />}
1422
+ </Box>
1423
+ {pin(n, '')}
1424
+ </Box>,
1425
+ c ? 'suggestion' : undefined,
1426
+ )
1427
+ })}
1428
+ {a?.folder && here.length > 0 && meta('📌 A pinned context is on in every new chat started in that folder, or below it. It’s kept on this machine: nothing is written into the folder.')}
1429
+ </Box>,
1430
+ none ? undefined : { label: 'Done', onPress: () => void update($, switching, () => false) },
1431
+ )
1432
+ }
1433
+
1434
+ if (!a)
1435
+ return (
1436
+ <Box flexDirection="column" padding={1} gap="sm">
1437
+ <Text bold>Context</Text>
1438
+ <Text dimColor wrap="wrap">
1439
+ {err ?? 'Loading the context…'}
1440
+ </Text>
1441
+ </Box>
1442
+ )
1443
+ const many = a.contexts.length > 1
1444
+ /** The context a panel action is about: named only when the chat has several (the tools take `context` then). */
1445
+ const ctx = many ? { context: a.context } : {}
1446
+ const named = many ? a.context : undefined
1447
+ const admin = a.you.role === 'admin'
1448
+ const invites: Invite[] = admin ? (a.invites ?? []) : []
1449
+ const canWrite = a.you.role === 'admin' || a.you.role === 'contributor'
1450
+ const snap = a.snapshot
1451
+ const t = snap ? threads(snap.nodes, snap.edges) : undefined
1452
+ const rel = snap ? relations(snap.nodes, snap.edges) : undefined
1453
+ const now = await $.clock.now()
1454
+ const heldByNode = new Map(a.recent.filter((c: Change) => c.held && c.node).map((c: Change) => [c.node!, c]))
1455
+ const isMine = (n: GraphNode) => prop(n, 'recorded_by') === a.you.name
1456
+ const byline = (n: GraphNode) => {
1457
+ const by = prop(n, 'recorded_by') || '?'
1458
+ const at = prop(n, 'recorded_at')
1459
+ return `${by === a.you.name ? 'you' : by}${at ? ` · ${ago(at, now)}` : ''}`
1460
+ }
1461
+ const held = (n: GraphNode) => (heldByNode.has(n.key) ? <Text color="warning"> · still only on this machine</Text> : '')
1462
+ const undo = (n: GraphNode) => {
1463
+ const change = heldByNode.get(n.key)
1464
+ return change ? <Button key={`undo-${n.key}`} label="Undo" variant="primary" onPress={() => void act($, 'take_back', { id: change.id, ...ctx }, 'Taken back. It never left this machine.')} /> : null
1465
+ }
1466
+ /** Withdraw, for its author or an admin, once it has been shared (before that, Undo). */
1467
+ const withdraw = (n: GraphNode) =>
1468
+ !heldByNode.has(n.key) && !n.ended && canWrite && (isMine(n) || admin) ? (
1469
+ <Button
1470
+ key={`withdraw-${n.key}`}
1471
+ label="Withdraw"
1472
+ variant="secondary"
1473
+ dimColor
1474
+ onPress={() => void openItem($, null).then(() => act($, 'withdraw', { id: n.key, ...ctx }, 'Withdrawn. It stays in the history.'))}
1475
+ />
1476
+ ) : null
1477
+
1478
+ // Changing your name: only that.
1479
+ if (await read($, renaming))
1480
+ return modal(
1481
+ 'rename-step',
1482
+ 'Your name',
1483
+ `Everyone sees you as ${a.you.name}. Each person names themselves: the name travels with your key, to every context on this machine, and every member sees the change.`,
1484
+ <Input
1485
+ key="my-name"
1486
+ label="The name you’d like others to see"
1487
+ value={a.you.name}
1488
+ submitLabel="Rename"
1489
+ autoFocus
1490
+ onSubmit={(v: string) => {
1491
+ void update($, renaming, () => false)
1492
+ if (v.trim() && v.trim() !== a.you.name) void act($, 'set_my_name', { name: v.trim() }, `You're now ${v.trim()} in every context on this machine.`)
1493
+ }}
1494
+ />,
1495
+ { label: 'Cancel', onPress: () => void update($, renaming, () => false) },
1496
+ )
1497
+
1498
+ // Confirming a removal: only that.
1499
+ const pending = await read($, confirmRemove)
1500
+ const leaving = pending ? a.people.find((p: Person) => p.fingerprint === pending) : undefined
1501
+ if (leaving)
1502
+ return modal(
1503
+ 'remove-step',
1504
+ `Remove ${leaving.name}?`,
1505
+ `Every member’s machine stops syncing with ${leaving.name} and refuses their later changes. What they wrote stays, and they keep the copy they already had.`,
1506
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1507
+ <Button
1508
+ key={`confirm-${leaving.fingerprint}`}
1509
+ label={`Remove ${leaving.name}`}
1510
+ variant="primary"
1511
+ onPress={() => {
1512
+ void update($, confirmRemove, () => null)
1513
+ void act($, 'remove_peer', { name: leaving.name, ...ctx }, `${leaving.name} was removed. They keep the copy they already had.`)
1514
+ }}
1515
+ />
1516
+ </Box>,
1517
+ { label: 'Cancel', onPress: () => void update($, confirmRemove, () => null) },
1518
+ )
1519
+
1520
+ // One item on its own: a question with its thread, or a claim with everything linked to it.
1521
+ const openKey = await read($, detail)
1522
+ const item = openKey && rel ? rel.byKey.get(openKey) : undefined
1523
+ if (item && rel && t) {
1524
+ const back = { label: trail.length > 1 ? '‹ Back' : '‹ Back to the list', onPress: () => void backItem($) }
1525
+ /** A linked item: its text, who and when, and a way to open it. */
1526
+ const related = (label: string, tone: string | undefined, n: GraphNode) =>
1527
+ split(
1528
+ `rel-${label}-${n.key}`,
1529
+ <>
1530
+ <Text wrap="wrap" strikethrough={n.label === 'Claim' && !rel.current(n)} dimColor={n.ended}>
1531
+ <Text color={tone} dimColor={!tone}>
1532
+ {label}{' '}
1533
+ </Text>
1534
+ {short(n.title, 300)}
1535
+ </Text>
1536
+ <Text size="footnote" dimColor>
1537
+ {byline(n)} · {n.key}
1538
+ </Text>
1539
+ </>,
1540
+ <Button key={`open-${n.key}`} label="Open ›" variant="secondary" dimColor onPress={() => void openItem($, n.key)} />,
1541
+ )
1542
+ const group = (title: string, label: string, tone: string | undefined, list: GraphNode[]) =>
1543
+ list.length > 0 && (
1544
+ <Box key={`group-${title}`} flexDirection="column" gap="xs">
1545
+ {heading(title, list.length)}
1546
+ {list.map(n => related(label, tone, n))}
1547
+ </Box>
1548
+ )
1549
+ const copy = (text: string) => (press: UiPressArgument) => void $.ui.copy({ text, surface: press.surface }).then(r => r.isCopied && $.ui.toast('Copied.'))
1550
+
1551
+ if (item.label === 'Question') {
1552
+ const th = [...t.open, ...t.answered].find(x => x.q.id === item.id)
1553
+ const answered = !!th?.answers.length
1554
+ const about = rel.linked(item.id, 'ABOUT', 'out')
1555
+ const asked = rel.linked(item.id, 'ABOUT', 'in')
1556
+ return modal(
1557
+ 'question-view',
1558
+ item.ended ? 'Withdrawn question' : answered ? 'Answered question' : 'Open question',
1559
+ item.title,
1560
+ <Box flexDirection="column" gap="sm">
1561
+ <Text size="footnote" dimColor>
1562
+ asked by {byline(item)} · {item.key}
1563
+ {held(item)}
1564
+ </Text>
1565
+ {group('It’s about', '→', undefined, about)}
1566
+ {th && th.replies.length > 0 && (
1567
+ <Box flexDirection="column" gap="xs">
1568
+ {heading('Thread', th.replies.length)}
1569
+ {th.replies.map(r =>
1570
+ split(
1571
+ `ar-${r.key}`,
1572
+ <>
1573
+ <Text wrap="wrap">
1574
+ <Text dimColor>↳ </Text>
1575
+ {short(r.title, 600)}
1576
+ </Text>
1577
+ <Text size="footnote" dimColor>
1578
+ {byline(r)}
1579
+ {held(r)}
1580
+ </Text>
1581
+ </>,
1582
+ [
1583
+ undo(r),
1584
+ !answered && !item.ended && canWrite && (
1585
+ <Button key={`answer-with-${r.key}`} label="Answer with this" variant="secondary" dimColor onPress={() => void ask($, answerPrompt(item, { reply: r }, named))} />
1586
+ ),
1587
+ ],
1588
+ ),
1589
+ )}
1590
+ </Box>
1591
+ )}
1592
+ {th && group('Answer', '✓', 'success', th.answers)}
1593
+ {group('Questions about this one', '?', 'warning', asked)}
1594
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1595
+ {!answered && !item.ended && canWrite && <Button key={`answer-in-chat-${item.key}`} label="✎ Answer in the chat" variant="primary" onPress={() => draft($, drafts.answer(item, named), 'answer')} />}
1596
+ {!answered && !item.ended && canWrite && <Button key={`investigate-${item.key}`} label="Ask my agent to look into it" variant="secondary" onPress={() => void ask($, prompts.investigate(item, named))} />}
1597
+ <Button key={`copy-${item.key}`} label="Copy" variant="secondary" dimColor onPress={copy(`${item.title} (${item.key})`)} />
1598
+ {undo(item)}
1599
+ {withdraw(item)}
1600
+ </Box>
1601
+ {!answered && !item.ended && meta('Agents reply on the thread. Answer in the chat starts your answer in the prompt box: finish it and send it, and your agent records it as a claim that answers the question.')}
1602
+ </Box>,
1603
+ back,
1604
+ )
1605
+ }
1606
+
1607
+ const newer = rel.replacedBy.get(item.id)
1608
+ const state = item.ended ? 'Withdrawn claim' : newer ? 'Replaced claim' : rel.inConflict.has(item.id) ? 'Claim in conflict' : 'Claim'
1609
+ const from = prop(item, 'about_from')
1610
+ const to = prop(item, 'about_to')
1611
+ const contradicts = [...rel.linked(item.id, 'CONTRADICTS', 'out'), ...rel.linked(item.id, 'CONTRADICTS', 'in')].filter((n, i, all) => all.findIndex(x => x.id === n.id) === i)
1612
+ return modal(
1613
+ 'claim-view',
1614
+ state,
1615
+ null,
1616
+ <Box flexDirection="column" gap="sm">
1617
+ <Text wrap="wrap" strikethrough={!rel.current(item)}>
1618
+ {item.title}
1619
+ </Text>
1620
+ <Box flexDirection="column">
1621
+ <Text size="footnote" dimColor>
1622
+ recorded by {byline(item)} · {item.key}
1623
+ {held(item)}
1624
+ </Text>
1625
+ {prop(item, 'source') && meta(`Source: ${prop(item, 'source')}`)}
1626
+ {(from || to) && meta(`About ${from && to ? `${from.slice(0, 10)} to ${to.slice(0, 10)}` : from ? `${from.slice(0, 10)} onwards` : `up to ${to.slice(0, 10)}`}`)}
1627
+ {item.ended && (
1628
+ <Text size="footnote" color="warning" wrap="wrap">
1629
+ Withdrawn{prop(item, 'withdrawn_by') ? ` by ${prop(item, 'withdrawn_by')}` : ''}
1630
+ {prop(item, 'withdrawn_at') ? ` · ${ago(prop(item, 'withdrawn_at'), now)}` : ''}
1631
+ {prop(item, 'withdraw_reason') ? `: ${prop(item, 'withdraw_reason')}` : ''}
1632
+ </Text>
1633
+ )}
1634
+ </Box>
1635
+ {newer && group('Replaced by', '↑', 'success', [newer])}
1636
+ {group('Can’t be true alongside', '⚡', 'warning', contradicts)}
1637
+ {group('Answers', '?', undefined, rel.linked(item.id, 'ANSWERS', 'out'))}
1638
+ {group('Evidence for it', '+', 'success', rel.linked(item.id, 'SUPPORTS', 'in'))}
1639
+ {group('It’s evidence for', '→', undefined, rel.linked(item.id, 'SUPPORTS', 'out'))}
1640
+ {group('Earlier versions', '↓', undefined, rel.linked(item.id, 'REPLACES', 'out'))}
1641
+ {group('Questions about it', '?', 'warning', rel.linked(item.id, 'ABOUT', 'in'))}
1642
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1643
+ {rel.current(item) && canWrite && !heldByNode.has(item.key) && (
1644
+ <Button key={`correct-${item.key}`} label="✎ Correct it in the chat" variant="primary" onPress={() => draft($, drafts.correct(item, named), 'correction')} />
1645
+ )}
1646
+ <Button key={`copy-${item.key}`} label="Copy" variant="secondary" dimColor onPress={copy(`${item.title} (${item.key})`)} />
1647
+ {undo(item)}
1648
+ {withdraw(item)}
1649
+ </Box>
1650
+ {rel.current(item) && canWrite && meta('Correct it when it’s wrong or out of date: it starts in the prompt box, and once you send it the new claim replaces this one, which stays in the history. Withdraw it when it should never have been recorded.')}
1651
+ </Box>,
1652
+ back,
1653
+ )
1654
+ }
1655
+
1656
+ const stored = await read($, tab)
1657
+ const current: Tab = TABS.some(x => x.tab === stored) ? stored : 'overview'
1658
+ const f: Filters = await read($, filters)
1659
+ const extra = await read($, more)
1660
+ /** Another tab starts from the top, without the last tab's filter words. */
1661
+ const setTab = (x: Tab) =>
1662
+ void update($, more, () => 0)
1663
+ .then(() => {
1664
+ if (x === 'settings') askedDetails = undefined
1665
+ })
1666
+ .then(() => (x === current ? undefined : update($, filters, (v: Filters): Filters => ({ ...v, text: '' }))))
1667
+ .then(() => update($, tab, () => x))
1668
+ // Returned, so whoever presses waits for the search too.
1669
+ const setFilter = (patch: Partial<Filters>) =>
1670
+ update($, more, () => 0)
1671
+ .then(() => update($, filters, (v: Filters): Filters => ({ ...v, ...patch })))
1672
+ .then(() => (patch.text !== undefined ? findRelated($, patch.text, a.context, ctx) : undefined))
1673
+ const members = a.people.filter((p: Person) => p.role)
1674
+ const rank = (p: Person) => (p.you ? 0 : p.online ? 1 : 2)
1675
+ const shown = [...members].sort((x, y) => rank(x) - rank(y)).slice(0, HEADER_PEOPLE)
1676
+ const unshown = members.length - shown.length
1677
+ const unshownOnline = members.filter((p: Person) => p.online).length - shown.filter((p: Person) => p.online).length
1678
+ const counts: Record<Tab, number | undefined> = { overview: undefined, questions: t?.open.length, claims: t?.claims.length, people: members.length, settings: undefined }
1679
+ const goOnline = <Button key="go-online" label="Go online" variant="primary" onPress={() => void act($, 'start_sharing', { ...ctx }, 'Back online: syncing with the other members.')} />
1680
+
1681
+ const header = (
1682
+ <Box flexDirection="column" gap="xs">
1683
+ <Box flexDirection="row" justifyContent="space-between" alignItems="center" gap={1} flexWrap="wrap">
1684
+ {/* Whether it's syncing, with the way to change it: who's online is listed under the description. */}
1685
+ <Box flexDirection="row" gap={1} alignItems="center" flexShrink={1} flexWrap="wrap">
1686
+ <Text size="footnote" color={a.sharing ? 'success' : 'warning'}>
1687
+ {a.sharing ? '⇅ Syncing' : '● Offline'}
1688
+ {a.sharing && a.relays_up === 0 ? <Text color="warning"> · no relay reachable</Text> : ''}
1689
+ </Text>
1690
+ <Button
1691
+ key="sync-toggle"
1692
+ plain
1693
+ dimColor
1694
+ onPress={() =>
1695
+ void act($, a.sharing ? 'stop_sharing' : 'start_sharing', { ...ctx }, a.sharing ? 'Offline: not syncing until you go online again.' : 'Back online: syncing with the other members.')
1696
+ }
1697
+ >
1698
+ <Text size="footnote" underline>
1699
+ {a.sharing ? 'Go offline' : 'Go online'}
1700
+ </Text>
1701
+ </Button>
1702
+ </Box>
1703
+ <Button key="switch" label={many ? `⇄ ${a.contexts.length} contexts` : '⇄ Contexts'} plain dimColor onPress={() => void update($, switching, () => true)} />
1704
+ </Box>
1705
+ <Text size="title" weight="semibold" bold wrap="wrap">
1706
+ {a.context}
1707
+ </Text>
1708
+ {many && (
1709
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1710
+ {a.contexts.map(c => (
1711
+ <Button
1712
+ key={`view-${c.name}`}
1713
+ label={`${c.name}${c.writes_here ? ' ✎' : ''}`}
1714
+ variant={c.name === a.context ? 'primary' : 'secondary'}
1715
+ dimColor={c.name !== a.context}
1716
+ onPress={() => void update($, viewing, () => c.name).then(() => refresh($))}
1717
+ />
1718
+ ))}
1719
+ </Box>
1720
+ )}
1721
+ {/* What it's for is written out once: in full on the overview, and in Settings under its own heading
1722
+ (where it's edited). The other tabs keep a line of it, so the lists start higher. */}
1723
+ {current === 'settings' ? null : !a.description ? (
1724
+ <Box flexDirection="row" gap="xs" alignItems="flex-start">
1725
+ <Box flexShrink={1}>
1726
+ <Text italic dimColor wrap="wrap">
1727
+ No description yet{admin ? '' : ': an admin can add one'}, so agents won’t know what belongs here.
1728
+ </Text>
1729
+ </Box>
1730
+ {admin && <Button key="edit-description" label="✎" plain dimColor onPress={() => void update($, editing, () => a.context)} />}
1731
+ </Box>
1732
+ ) : current === 'overview' ? (
1733
+ <Box flexDirection="row" gap="xs" alignItems="flex-start">
1734
+ <Box flexShrink={1}>
1735
+ <Text wrap="wrap">{a.description}</Text>
1736
+ </Box>
1737
+ {admin && <Button key="edit-description" label="✎" plain dimColor onPress={() => void update($, editing, () => a.context)} />}
1738
+ </Box>
1739
+ ) : (
1740
+ <Text key="description-line" size="footnote" dimColor wrap="truncate-end">
1741
+ {a.description}
1742
+ </Text>
1743
+ )}
1744
+ {/* Who's in it: the People tab lists them in full, so not above it too. */}
1745
+ <Box flexDirection="row" gap="sm" flexWrap="wrap" alignItems="center" display={current === 'people' ? 'none' : 'flex'}>
1746
+ {shown.map((p: Person) => (
1747
+ <Box key={`who-${p.fingerprint}`} hover={{ scope: `who-${p.fingerprint}` }}>
1748
+ <Text size="footnote" dimColor={!p.online} hover={{ underline: true }}>
1749
+ <Text color={p.online ? 'success' : undefined}>●</Text> {p.name}
1750
+ {p.you ? ' (you)' : ''}
1751
+ {!graphical ? ` ${p.role}` : ''}
1752
+ </Text>
1753
+ </Box>
1754
+ ))}
1755
+ {unshown > 0 && <Button key="who-more" label={`+${unshown} more${unshownOnline ? ` · ${unshownOnline} online` : ''}`} plain dimColor onPress={() => setTab('people')} />}
1756
+ </Box>
1757
+ {graphical &&
1758
+ current !== 'people' &&
1759
+ shown.map((p: Person) => (
1760
+ <Box key={`who-card-${p.fingerprint}`} display="none" hover={{ scope: `who-${p.fingerprint}`, display: 'flex' }}>
1761
+ <Text size="footnote" dimColor>
1762
+ {p.name} · {p.role}
1763
+ {p.creator ? ' · made this context' : ''} · {p.online ? 'online now' : 'offline'} · key {p.fingerprint}
1764
+ {p.agent ? ` · ${p.agent}` : ''}
1765
+ {p.platform ? ` · ${p.platform}` : ''}
1766
+ </Text>
1767
+ </Box>
1768
+ ))}
1769
+ <Box flexDirection="row" gap="xs" marginTop="sm" flexWrap="wrap">
1770
+ {TABS.map(x => chip(`tab-${x.tab}`, `${x.icon} ${x.label}${counts[x.tab] !== undefined ? ` ${counts[x.tab]}` : ''}`, current === x.tab, () => setTab(x.tab)))}
1771
+ </Box>
1772
+ {messages}
1773
+ </Box>
1774
+ )
1775
+
1776
+ /** The search behind the filter's text, once it has answered for this text in this context. */
1777
+ const search = f.text ? await read($, found) : null
1778
+ const near = search && search.text === f.text && search.context === a.context ? search : null
1779
+ /** The filter box above a list, and what it's filtering by: its words, and how many more are close in meaning. */
1780
+ const filterBox = (what: string, byMeaning: number) => (
1781
+ <Box flexDirection="column" gap="xs" width="100%" alignItems="stretch">
1782
+ <Input key="filter" value={f.text} placeholder={`Search ${what} by meaning, words, a person or an id`} submitLabel="Search" onSubmit={(v: string) => setFilter({ text: v.trim() })} />
1783
+ {f.text && (
1784
+ <Box flexDirection="row" gap="xs" alignItems="center" flexWrap="wrap">
1785
+ <Text size="footnote" dimColor wrap="wrap">
1786
+ Showing {what} matching “{short(f.text, 40)}”
1787
+ {!near || near.ids === null
1788
+ ? ' · looking for ones close in meaning…'
1789
+ : near.failed
1790
+ ? ' · search by meaning isn’t available, so only words match'
1791
+ : byMeaning
1792
+ ? `, then ${byMeaning} close in meaning`
1793
+ : ''}
1794
+ </Text>
1795
+ <Button key="clear-filter" label="× Clear" plain dimColor onPress={() => setFilter({ text: '' })} />
1796
+ </Box>
1797
+ )}
1798
+ </Box>
1799
+ )
1800
+ /** The first page of a list, and a button for the rest. */
1801
+ const paged = <T,>(list: T[]) => list.slice(0, PAGE + extra)
1802
+ const showMore = (total: number) =>
1803
+ total > PAGE + extra && (
1804
+ <Box key="show-more-row" flexDirection="row">
1805
+ <Button key="show-more" plain dimColor onPress={() => void update($, more, (n: number) => n + PAGE)}>
1806
+ <Text underline>{`Show ${Math.min(PAGE, total - PAGE - extra)} more of ${total}`}</Text>
1807
+ </Button>
1808
+ </Box>
1809
+ )
1810
+
1811
+ let body
1812
+ if (current === 'settings') {
1813
+ // The open context's details, read when the tab is first drawn for it (and again after each change).
1814
+ if ((!loadedDetails || loadedDetails.name !== a.context) && askedDetails !== a.context) {
1815
+ askedDetails = a.context
1816
+ void loadDetails($)
1817
+ }
1818
+ body = settings(a.context, true)
1819
+ } else if (!snap || !t || !rel) body = <Text dimColor>Loading…</Text>
1820
+ else if (current === 'overview') {
1821
+ const heldMine = a.recent.filter((c: Change) => c.held && c.mine)
1822
+ const waiting = t.open.filter(th => th.replies.length)
1823
+ const mineOpen = t.open.filter(th => isMine(th.q) && th.replies.length)
1824
+ const digest = a.digest?.at(-1)
1825
+ const feed = a.recent
1826
+ // The "you claimed:" part of an activity line is who-did-what metadata: drawn dim so the claim itself reads first.
1827
+ const lead = (c: Change) => {
1828
+ const i = /^(claim|question|reply|describe)$/.test(c.kind) ? c.summary.indexOf(': ') : -1
1829
+ return i < 0 ? { head: '', body: c.summary } : { head: c.summary.slice(0, i + 2), body: c.summary.slice(i + 2) }
1830
+ }
1831
+ const ICON: Record<string, string> = { claim: '📌', question: '❓', reply: '↳', link: '🔗', withdraw: '✕', add_member: '👋', remove_member: '🚪', set_role: '🔑', rename: '✎', describe: '✎', create: '✦' }
1832
+ const need = (key: string, tone: string, text: unknown, button: unknown) => card(`need-${key}`, split(`need-row-${key}`, <Text wrap="wrap">{text}</Text>, button, 'center'), tone)
1833
+ const needs = [
1834
+ !a.sharing && need('offline', 'warning', 'You’re offline: what you write stays on this machine, and you don’t see what others add, until you’re back.', goOnline),
1835
+ a.sharing && a.relays_up === 0 && need('relays', 'warning', 'No signalling relay is reachable, so the other members can’t find this machine right now.', null),
1836
+ rel.conflicts.length > 0 &&
1837
+ need(
1838
+ 'conflicts',
1839
+ 'warning',
1840
+ `⚡ ${rel.conflicts.length} pair${rel.conflicts.length === 1 ? '' : 's'} of claims can’t both be true. Someone needs to say which stands.`,
1841
+ <Button key="see-conflicts" label="Settle" variant="primary" onPress={() => void update($, filters, (v: Filters): Filters => ({ ...v, text: '', claims: 'conflicts' })).then(() => setTab('claims'))} />,
1842
+ ),
1843
+ mineOpen.length > 0 &&
1844
+ need(
1845
+ 'replies',
1846
+ 'suggestion',
1847
+ `↳ ${mineOpen.length} of your questions ${mineOpen.length === 1 ? 'has' : 'have'} replies: ${short(mineOpen[0]!.q.title, 80)}`,
1848
+ <Button key="see-replies" label="Read" variant="primary" onPress={() => void openItem($, mineOpen[0]!.q.key)} />,
1849
+ ),
1850
+ t.open.length > 0 &&
1851
+ need(
1852
+ 'questions',
1853
+ 'subtle',
1854
+ `❓ ${t.open.length} open question${t.open.length === 1 ? '' : 's'}${waiting.length ? `, ${waiting.length} with replies` : ''}.`,
1855
+ <Button key="see-questions" label="See" variant="secondary" onPress={() => void update($, filters, (v: Filters): Filters => ({ ...v, text: '', questions: 'open' })).then(() => setTab('questions'))} />,
1856
+ ),
1857
+ admin && !a.description && need('describe', 'suggestion', 'This context has no description, so agents can’t tell what belongs in it.', <Button key="need-describe" label="Describe" variant="primary" onPress={() => void update($, editing, () => a.context)} />),
1858
+ admin &&
1859
+ members.length === 1 &&
1860
+ !invites.length &&
1861
+ need(
1862
+ 'alone',
1863
+ 'suggestion',
1864
+ 'It’s just you here so far.',
1865
+ <Button key="need-invite" label="Invite someone" variant="primary" onPress={() => ((inviteNote = ''), void update($, inviting, () => ({ name: a.context, role: 'contributor' as Invite['role'] })))} />,
1866
+ ),
1867
+ invites.length > 0 && need('invites', 'subtle', `${invites.length} join code${invites.length === 1 ? ' is' : 's are'} waiting to be used.`, <Button key="see-invites" label="See" variant="secondary" onPress={() => setTab('people')} />),
1868
+ ].filter(Boolean)
1869
+ const attention = (
1870
+ <Box key="overview-now" flexDirection="column" gap="sm" {...(fit === 'wide' ? { width: '50%', flexGrow: 1, flexShrink: 1 } : {})}>
1871
+ {heldMine.length > 0 &&
1872
+ card(
1873
+ 'held',
1874
+ <Box flexDirection="column" gap="xs">
1875
+ <Text color="warning">Just written, still only on this machine:</Text>
1876
+ {heldMine.map((c: Change) =>
1877
+ split(
1878
+ `held-${c.id}`,
1879
+ <Text wrap="wrap">{short(c.summary, 140)}</Text>,
1880
+ <Button key={`undo-change-${c.id}`} label="Undo" variant="primary" onPress={() => void act($, 'take_back', { id: c.id, ...ctx }, 'Taken back. It never left this machine.')} />,
1881
+ 'center',
1882
+ ),
1883
+ )}
1884
+ </Box>,
1885
+ 'warning',
1886
+ )}
1887
+ {heading('Needs you', needs.length || undefined)}
1888
+ {needs.length ? folded('needs', needs, 3, 'things', 'thing', x => x) : card('all-clear', <Text color="success">✓ Nothing needs you right now.</Text>, 'success')}
1889
+ {digest && digest.lines.length > 0 && (
1890
+ <Box flexDirection="column" gap="xs">
1891
+ {heading('What changed for you')}
1892
+ {card(
1893
+ 'digest',
1894
+ <Box flexDirection="column" gap="xs">
1895
+ {folded('digest', digest.lines, 3, 'changes', 'change', (line, i) => (
1896
+ <Text key={`digest-${i}`} wrap="wrap">
1897
+ {line}
1898
+ </Text>
1899
+ ))}
1900
+ {meta(ago(digest.at, now))}
1901
+ </Box>,
1902
+ 'suggestion',
1903
+ )}
1904
+ </Box>
1905
+ )}
1906
+ {heading('Ask your agent')}
1907
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
1908
+ <Button key="catch-up" label="Catch me up" variant="secondary" onPress={() => void ask($, prompts.catchUp(a.context))} />
1909
+ {canWrite && <Button key="save-chat" label="Save what this chat learned" variant="secondary" onPress={() => void ask($, prompts.saveChat(a.context))} />}
1910
+ </Box>
1911
+ </Box>
1912
+ )
1913
+ const happened = (
1914
+ <Box key="overview-recent" flexDirection="column" gap="sm" {...(fit === 'wide' ? { width: '50%', flexGrow: 1, flexShrink: 1 } : {})}>
1915
+ {heading('Recent activity')}
1916
+ {!feed.length && meta('Nothing yet. What your agent and the other members’ agents record shows up here.')}
1917
+ {folded('recent', feed, RECENT, 'changes', 'change', (c: Change) =>
1918
+ split(
1919
+ `act-${c.id}`,
1920
+ <>
1921
+ <Text wrap="wrap">
1922
+ <Text dimColor>
1923
+ {ICON[c.kind] ?? '·'} {c.mine ? 'you' : c.by} {lead(c).head}
1924
+ </Text>
1925
+ {short(lead(c).body, 200)}
1926
+ </Text>
1927
+ <Text size="footnote" dimColor>
1928
+ {ago(c.at, now)}
1929
+ {c.held ? <Text color="warning"> · still only on this machine</Text> : ''}
1930
+ </Text>
1931
+ </>,
1932
+ c.node && rel.byKey.has(c.node) && <Button key={`open-change-${c.id}`} label="Open ›" variant="secondary" dimColor onPress={() => void openItem($, c.node)} />,
1933
+ ),
1934
+ )}
1935
+ {meta(
1936
+ `${t.claims.length} claim${t.claims.length === 1 ? '' : 's'} · ${t.open.length} open and ${t.answered.length} answered question${t.answered.length === 1 ? '' : 's'} · ${rel.history.length} replaced or withdrawn · ${a.changes} changes in all${snap.truncated ? ' · showing the latest items only' : ''}`,
1937
+ )}
1938
+ </Box>
1939
+ )
1940
+ // Wide, what needs you sits beside what happened; otherwise one above the other.
1941
+ body =
1942
+ fit === 'wide' ? (
1943
+ <Box key="overview" flexDirection="row" gap={2} alignItems="flex-start">
1944
+ {attention}
1945
+ {happened}
1946
+ </Box>
1947
+ ) : (
1948
+ <Box key="overview" flexDirection="column" gap="sm">
1949
+ {attention}
1950
+ {happened}
1951
+ </Box>
1952
+ )
1953
+ } else if (current === 'questions') {
1954
+ const scopes = {
1955
+ open: t.open,
1956
+ answered: t.answered,
1957
+ mine: [...t.open, ...t.answered].filter(th => isMine(th.q)),
1958
+ }
1959
+ const scope = f.questions in scopes ? f.questions : 'open'
1960
+ const { list, byMeaning } = filtered(
1961
+ scopes[scope],
1962
+ th => th.q.key,
1963
+ th => matches(th.q, f.text) || th.replies.some(r => matches(r, f.text)) || th.answers.some(c => matches(c, f.text)),
1964
+ near?.ids,
1965
+ )
1966
+ const question = (th: Thread) => {
1967
+ const q = th.q
1968
+ const answered = th.answers.length > 0
1969
+ return card(
1970
+ `q-${q.key}`,
1971
+ <Box flexDirection="column" gap="xs">
1972
+ {split(
1973
+ `q-row-${q.key}`,
1974
+ <>
1975
+ <Text wrap="wrap" weight="semibold" bold>
1976
+ {!graphical && <Text color="warning">? </Text>}
1977
+ {short(q.title, 300)}
1978
+ </Text>
1979
+ <Text size="footnote" dimColor>
1980
+ asked by {byline(q)}
1981
+ {th.replies.length ? ` · ${th.replies.length} repl${th.replies.length === 1 ? 'y' : 'ies'}` : ''}
1982
+ {byMeaning.has(q.key) ? ' · close in meaning' : ''}
1983
+ {held(q)}
1984
+ </Text>
1985
+ </>,
1986
+ [
1987
+ undo(q),
1988
+ answered || !canWrite ? (
1989
+ <Button key={`open-${q.key}`} label="Open ›" variant="secondary" dimColor onPress={() => void openItem($, q.key)} />
1990
+ ) : (
1991
+ <Button key={`answer-${q.key}`} label="Answer" variant="primary" onPress={() => void openItem($, q.key)} />
1992
+ ),
1993
+ ],
1994
+ )}
1995
+ {folded(
1996
+ `replies-${q.key}`,
1997
+ th.replies,
1998
+ 2,
1999
+ 'replies',
2000
+ 'reply',
2001
+ r => (
2002
+ <Box key={`r-${r.key}`} flexDirection="column" paddingLeft={2}>
2003
+ <Text wrap="wrap">
2004
+ <Text dimColor>↳ </Text>
2005
+ {short(r.title, 240)}
2006
+ </Text>
2007
+ <Text size="footnote" dimColor>
2008
+ {byline(r)}
2009
+ {held(r)}
2010
+ </Text>
2011
+ </Box>
2012
+ ),
2013
+ true,
2014
+ )}
2015
+ {th.answers.map(c => (
2016
+ <Box key={`a-${c.key}`} flexDirection="column" paddingLeft={2}>
2017
+ <Text wrap="wrap">
2018
+ <Text color="success">✓ </Text>
2019
+ {short(c.title, 300)}
2020
+ </Text>
2021
+ <Text size="footnote" dimColor>
2022
+ answered by {byline(c)}
2023
+ </Text>
2024
+ </Box>
2025
+ ))}
2026
+ </Box>,
2027
+ heldByNode.has(q.key) ? 'warning' : answered ? 'success' : undefined,
2028
+ )
2029
+ }
2030
+ body = (
2031
+ <Box flexDirection="column" gap="sm">
2032
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
2033
+ {chip('scope-open', `Open ${t.open.length}`, scope === 'open', () => setFilter({ questions: 'open' }))}
2034
+ {chip('scope-answered', `Answered ${t.answered.length}`, scope === 'answered', () => setFilter({ questions: 'answered' }))}
2035
+ {chip('scope-mine', `Mine ${scopes.mine.length}`, scope === 'mine', () => setFilter({ questions: 'mine' }))}
2036
+ </Box>
2037
+ {filterBox('questions', byMeaning.size)}
2038
+ {!list.length &&
2039
+ card(
2040
+ 'empty',
2041
+ <Text dimColor wrap="wrap">
2042
+ {f.text
2043
+ ? 'No questions match.'
2044
+ : scope === 'open'
2045
+ ? t.answered.length
2046
+ ? '✓ Every question has an answer.'
2047
+ : 'No questions yet. When your agent records something the group needs to find out, it shows up here with its thread.'
2048
+ : scope === 'answered'
2049
+ ? 'No question has been answered yet.'
2050
+ : 'You haven’t asked anything here yet.'}
2051
+ </Text>,
2052
+ )}
2053
+ {paged(list).map(question)}
2054
+ {showMore(list.length)}
2055
+ {meta('Agents ask and reply. Answer gives your agent your answer, and it records it as a claim.')}
2056
+ </Box>
2057
+ )
2058
+ } else if (current === 'claims') {
2059
+ const scopes = {
2060
+ current: t.claims,
2061
+ mine: t.claims.filter(isMine),
2062
+ conflicts: t.claims.filter(n => rel.inConflict.has(n.id)),
2063
+ history: rel.history,
2064
+ }
2065
+ const scope = f.claims in scopes ? f.claims : 'current'
2066
+ const { list, byMeaning } = filtered(scopes[scope], n => n.key, n => matches(n, f.text), near?.ids)
2067
+ const pairs = scope === 'history' ? [] : rel.conflicts.filter(([x, y]) => matches(x, f.text) || matches(y, f.text))
2068
+ const side = (keep: GraphNode, drop: GraphNode) =>
2069
+ split(
2070
+ `side-${keep.key}`,
2071
+ <>
2072
+ <Text wrap="wrap">{short(keep.title, 300)}</Text>
2073
+ <Text size="footnote" dimColor>
2074
+ {byline(keep)} · {keep.key}
2075
+ </Text>
2076
+ </>,
2077
+ [
2078
+ canWrite && <Button key={`keep-${keep.key}-over-${drop.key}`} label="Keep this one" variant="secondary" onPress={() => void ask($, prompts.settle(keep, drop, named))} />,
2079
+ <Button key={`open-${keep.key}-vs-${drop.key}`} label="Open ›" variant="secondary" dimColor onPress={() => void openItem($, keep.key)} />,
2080
+ ],
2081
+ )
2082
+ const badges = (n: GraphNode) => {
2083
+ const evidence = rel.linked(n.id, 'SUPPORTS', 'in').filter(rel.current).length
2084
+ return [
2085
+ rel.linked(n.id, 'ANSWERS', 'out').length ? 'answers a question' : '',
2086
+ evidence ? `${evidence} in support` : '',
2087
+ rel.linked(n.id, 'REPLACES', 'out').length ? 'updated' : '',
2088
+ prop(n, 'source') ? short(prop(n, 'source'), 50) : '',
2089
+ ]
2090
+ .filter(Boolean)
2091
+ .map(x => ` · ${x}`)
2092
+ .join('')
2093
+ }
2094
+ body = (
2095
+ <Box flexDirection="column" gap="sm">
2096
+ <Box flexDirection="row" gap="xs" flexWrap="wrap">
2097
+ {chip('scope-current', `Current ${t.claims.length}`, scope === 'current', () => setFilter({ claims: 'current' }))}
2098
+ {chip('scope-mine', `Mine ${scopes.mine.length}`, scope === 'mine', () => setFilter({ claims: 'mine' }))}
2099
+ {(rel.conflicts.length > 0 || scope === 'conflicts') && chip('scope-conflicts', `⚡ Conflicts ${rel.conflicts.length}`, scope === 'conflicts', () => setFilter({ claims: 'conflicts' }))}
2100
+ {chip('scope-history', `History ${rel.history.length}`, scope === 'history', () => setFilter({ claims: 'history' }))}
2101
+ </Box>
2102
+ {filterBox('claims', byMeaning.size)}
2103
+ {pairs.map(([x, y]) =>
2104
+ card(
2105
+ `conflict-${x.key}-${y.key}`,
2106
+ <Box flexDirection="column" gap="xs">
2107
+ <Text color="warning" weight="semibold" bold>
2108
+ ⚡ These can’t both be true
2109
+ </Text>
2110
+ {side(x, y)}
2111
+ <Text size="footnote" dimColor>
2112
+ — or —
2113
+ </Text>
2114
+ {side(y, x)}
2115
+ </Box>,
2116
+ 'warning',
2117
+ ),
2118
+ )}
2119
+ {scope === 'conflicts' && !pairs.length && card('empty', <Text color="success">✓ No claims contradict each other.</Text>, 'success')}
2120
+ {scope !== 'conflicts' &&
2121
+ !list.length &&
2122
+ card(
2123
+ 'empty',
2124
+ <Text dimColor wrap="wrap">
2125
+ {f.text
2126
+ ? 'No claims match.'
2127
+ : scope === 'current'
2128
+ ? 'No claims yet. What your agent records as true shows up here. Try “Save what this chat learned” on the Overview.'
2129
+ : scope === 'mine'
2130
+ ? 'None of the current claims are yours.'
2131
+ : 'Nothing has been replaced or withdrawn.'}
2132
+ </Text>,
2133
+ )}
2134
+ {scope !== 'conflicts' &&
2135
+ paged(list).map(n => {
2136
+ const newer = rel.replacedBy.get(n.id)
2137
+ return card(
2138
+ `c-${n.key}`,
2139
+ split(
2140
+ `c-row-${n.key}`,
2141
+ <>
2142
+ <Text wrap="wrap" strikethrough={scope === 'history'} dimColor={scope === 'history'}>
2143
+ {!graphical && <Text color="suggestion">• </Text>}
2144
+ {rel.inConflict.has(n.id) && <Text color="warning">⚡ </Text>}
2145
+ {short(n.title, 300)}
2146
+ </Text>
2147
+ <Text size="footnote" dimColor wrap="wrap">
2148
+ {byline(n)}
2149
+ {byMeaning.has(n.key) ? ' · close in meaning' : ''}
2150
+ {scope === 'history'
2151
+ ? n.ended
2152
+ ? ` · withdrawn${prop(n, 'withdrawn_by') ? ` by ${prop(n, 'withdrawn_by')}` : ''}${prop(n, 'withdraw_reason') ? `: ${short(prop(n, 'withdraw_reason'), 80)}` : ''}`
2153
+ : newer
2154
+ ? ` · replaced by ${newer.key}: ${short(newer.title, 80)}`
2155
+ : ''
2156
+ : badges(n)}
2157
+ {held(n)}
2158
+ </Text>
2159
+ </>,
2160
+ [undo(n), <Button key={`open-${n.key}`} label="Open ›" variant="secondary" dimColor onPress={() => void openItem($, n.key)} />],
2161
+ ),
2162
+ heldByNode.has(n.key) ? 'warning' : rel.inConflict.has(n.id) ? 'warning' : undefined,
2163
+ )
2164
+ })}
2165
+ {scope !== 'conflicts' && showMore(list.length)}
2166
+ {scope === 'history' && meta('Nothing is deleted: replaced and withdrawn claims stay, so anyone can see what the group believed before.')}
2167
+ </Box>
2168
+ )
2169
+ } else {
2170
+ const gone = a.people.filter((p: Person) => !p.role)
2171
+ const wrote = (p: Person) => {
2172
+ const mine = snap.nodes.filter(n => !n.ended && prop(n, 'recorded_by') === p.name)
2173
+ const n = (label: string) => mine.filter(x => x.label === label).length
2174
+ const parts = [
2175
+ [n('Claim'), 'claim'],
2176
+ [n('Question'), 'question'],
2177
+ [n('Reply'), 'repl'],
2178
+ ]
2179
+ .filter(([count]) => count)
2180
+ .map(([count, word]) => `${count} ${word}${word === 'repl' ? (count === 1 ? 'y' : 'ies') : count === 1 ? '' : 's'}`)
2181
+ const last = a.recent.find((c: Change) => c.by === p.name)
2182
+ return `${p.joined_at ? `joined ${ago(p.joined_at, now)}` : ''}${parts.length ? ` · ${parts.join(', ')}` : ' · nothing recorded yet'}${last ? ` · active ${ago(last.at, now)}` : ''}`.replace(/^ · /, '')
2183
+ }
2184
+ const person = (p: Person) =>
2185
+ card(
2186
+ `person-${p.fingerprint}`,
2187
+ split(
2188
+ `person-row-${p.fingerprint}`,
2189
+ <>
2190
+ <Text wrap="wrap">
2191
+ <Text color={p.online ? 'success' : undefined} dimColor={!p.online}>
2192
+ ●
2193
+ </Text>{' '}
2194
+ <Text weight="semibold" bold dimColor={!p.role}>
2195
+ {p.name}
2196
+ </Text>
2197
+ <Text dimColor>
2198
+ {p.you ? ' (you)' : ''} · {p.role ?? 'removed'}
2199
+ {p.creator ? ' · made this context' : ''}
2200
+ {p.role ? (p.online ? ' · online' : ' · offline') : ''}
2201
+ </Text>
2202
+ </Text>
2203
+ {meta(wrote(p))}
2204
+ {reveal(
2205
+ `key-${p.fingerprint}`,
2206
+ 'Key and agent',
2207
+ 'Hide key and agent',
2208
+ <Text key={`key-text-${p.fingerprint}`} size="footnote" dimColor mono wrap="wrap">
2209
+ {p.fingerprint}
2210
+ {p.agent ? ` · ${p.agent}` : ''}
2211
+ {p.platform ? ` · ${p.platform}` : ''}
2212
+ </Text>,
2213
+ )}
2214
+ </>,
2215
+ [
2216
+ p.you && <Button key="rename" label="✎ Rename" variant="secondary" dimColor onPress={() => void update($, renaming, () => true)} />,
2217
+ admin && !p.creator && !p.you && p.role && Select && (
2218
+ <Select
2219
+ key={`role-${p.fingerprint}`}
2220
+ value={p.role}
2221
+ options={['reader', 'contributor', 'admin'].map(r => ({ key: r, value: r, label: r }))}
2222
+ onSelect={(r: string) => r !== p.role && void act($, 'set_peer_role', { name: p.name, role: r, ...ctx }, `${p.name} is now ${r}.`)}
2223
+ />
2224
+ ),
2225
+ admin && !p.creator && !p.you && p.role && (
2226
+ <Button key={`remove-${p.fingerprint}`} label="Remove" variant="secondary" dimColor onPress={() => void update($, confirmRemove, () => p.fingerprint)} />
2227
+ ),
2228
+ ],
2229
+ 'center',
2230
+ ),
2231
+ p.you ? 'suggestion' : undefined,
2232
+ )
2233
+ body = (
2234
+ <Box flexDirection="column" gap="sm">
2235
+ {heading('Members', members.length)}
2236
+ {members.map(person)}
2237
+ {admin &&
2238
+ card(
2239
+ 'invite-card',
2240
+ <Box flexDirection="column" gap="sm">
2241
+ {split(
2242
+ 'invite-head',
2243
+ <Text weight="semibold" bold>
2244
+ Join codes
2245
+ <Text dimColor weight="regular"> {invites.length ? `${invites.length} waiting` : 'none waiting'}</Text>
2246
+ </Text>,
2247
+ <Button
2248
+ key="invite"
2249
+ label="+ Invite someone"
2250
+ variant="primary"
2251
+ onPress={() => {
2252
+ inviteNote = ''
2253
+ void update($, inviting, () => ({ name: a.context, role: 'contributor' as Invite['role'] }))
2254
+ }}
2255
+ />,
2256
+ 'center',
2257
+ )}
2258
+ {invites.length === 0
2259
+ ? meta('Each code lets one person in: whoever uses it first. Codes stay here until they’re used, cancelled or expire.')
2260
+ : invites.map((i: Invite) => {
2261
+ const send = `Join my context graph: /vine-context:join ${i.code}`
2262
+ const left = Math.max(0, Date.parse(i.expires_at) - now)
2263
+ const hours = Math.round(left / 3600_000)
2264
+ return (
2265
+ <Box key={`inv-${i.id}`} flexDirection="column" gap="xs">
2266
+ {split(
2267
+ `inv-row-${i.id}`,
2268
+ <Text wrap="wrap">
2269
+ <Text weight="semibold" bold>
2270
+ {i.label ? `For ${i.label.replace(/^for\s+/i, '')}` : 'No note'}
2271
+ </Text>
2272
+ <Text dimColor>
2273
+ {' '}
2274
+ · {i.role} · {hours >= 1 ? `expires in ${hours}h` : 'expires soon'}
2275
+ </Text>
2276
+ {i.id === made && <Text color="success"> · new: send it now</Text>}
2277
+ </Text>,
2278
+ [
2279
+ <Button
2280
+ key={`copy-${i.id}`}
2281
+ label="Copy"
2282
+ variant="secondary"
2283
+ onPress={(press: UiPressArgument) => void $.ui.copy({ text: send, surface: press.surface }).then(r => r.isCopied && $.ui.toast('Copied: send it privately, to that one person.'))}
2284
+ />,
2285
+ <Button key={`cancel-${i.id}`} label="Cancel" variant="secondary" dimColor onPress={() => void act($, 'revoke_invite', { id: i.id, ...ctx }, 'Cancelled: that code no longer works.')} />,
2286
+ ],
2287
+ 'center',
2288
+ )}
2289
+ {Code ? <Code source={send} /> : <Text>{send}</Text>}
2290
+ </Box>
2291
+ )
2292
+ })}
2293
+ {!a.sharing && invites.length > 0 && <Text color="warning">You’re offline, so these codes won’t work until you go online.</Text>}
2294
+ </Box>,
2295
+ 'suggestion',
2296
+ )}
2297
+ {gone.length > 0 && heading('Removed', gone.length)}
2298
+ {gone.map(person)}
2299
+ </Box>
2300
+ )
2301
+ }
2302
+
2303
+ return (
2304
+ <Box flexDirection="column" gap="md" paddingX={graphical ? 1 : 0}>
2305
+ {header}
2306
+ {body}
2307
+ </Box>
2308
+ )
2309
+ })
2310
+ }