@gotcos/glasses-server 7.0.18 → 7.0.29

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.
@@ -0,0 +1,305 @@
1
+ /**
2
+ * The session organizer (Sessions chat-style layout, step 2a; contract
3
+ * operations/personal/wk46_2026/sessions_chat_layout/S1_CONTRACT_step2a.md).
4
+ *
5
+ * COS's own folders, COS pins and renamed titles for agent sessions, shared by Control Web and the Mac app. It only
6
+ * ADDS: nothing an agent wrote is changed (a COS pin is not a Claude star), and a list without this store is today's.
7
+ *
8
+ * - One file, data/session-organizer.json, 0600, written durably (temp file, fsync, rename) on every change.
9
+ * - Keyed `<provider>:<canonical id>`, lowercase. The caller canonicalizes (Claude Desktop ids map to their CLI id)
10
+ * BEFORE it reaches this module, so this module never guesses identity.
11
+ * - One change per call, applied in memory and written at once; `rev` rises by one per change. Nothing takes a whole
12
+ * store, so two devices editing different things never overwrite each other.
13
+ * - Folder names and titles never reach a log line: logs carry counts and reason codes only.
14
+ * - A file that exists but cannot be READ makes the store unavailable (no writes), so a transient read error can
15
+ * never be followed by a write that replaces real data with an empty store. A file that reads but does not parse,
16
+ * or has the wrong shape, is moved aside as `.corrupt-<time>` and the store starts empty.
17
+ */
18
+ import { existsSync, mkdirSync, readFileSync, renameSync } from 'node:fs'
19
+ import { randomBytes } from 'node:crypto'
20
+ import { dirname } from 'node:path'
21
+ import { durableAtomicWriteFileSync } from './atomic-fs.js'
22
+ import { dataPath } from './data-dir.js'
23
+
24
+ export const ORGANIZER_FILE = 'session-organizer.json'
25
+ export const ORGANIZER_LIMITS = { folders: 200, entries: 5_000, folderName: 60, title: 120 } as const
26
+ export type OrganizerProvider = 'claude' | 'codex' | 'cursor'
27
+ const PROVIDERS: ReadonlySet<string> = new Set(['claude', 'codex', 'cursor'])
28
+ const FOLDER_ID_RE = /^f_[0-9a-f]{16}$/
29
+
30
+ export interface OrganizerFolder { name: string; created_at: string }
31
+ /** `desktop_id`: for a Claude session, the Claude Desktop id it was written under when one is known (Q1 FIX 2). A row
32
+ * matches an entry by its key OR by this id, so an entry survives the Desktop alias appearing or changing. */
33
+ export interface OrganizerEntry { folder_id?: string; cos_pinned?: true; title?: string; desktop_id?: string; updated_at: string }
34
+ interface OrganizerFile {
35
+ version: 1
36
+ rev: number
37
+ folders: Record<string, OrganizerFolder>
38
+ sessions: Record<string, OrganizerEntry>
39
+ }
40
+
41
+ export class OrganizerError extends Error {
42
+ constructor(readonly status: number, readonly reason: string) { super(reason) }
43
+ }
44
+
45
+ /** What a list row or search hit carries from the store (each omitted when absent). */
46
+ export interface OrganizerRowFields { folder_id?: string; cos_pinned?: true; title_override?: string }
47
+
48
+ /** Trim, drop control characters and line breaks, collapse inner whitespace. Empty means refused. */
49
+ export function cleanOrganizerText(value: unknown, max: number): string | null {
50
+ if (typeof value !== 'string') return null
51
+ // eslint-disable-next-line no-control-regex
52
+ const cleaned = value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, ' ').replace(/\s+/g, ' ').trim()
53
+ if (!cleaned || [...cleaned].length > max) return null
54
+ return cleaned
55
+ }
56
+
57
+ export function organizerKey(provider: string, sessionId: string): string {
58
+ return `${provider}:${sessionId.trim().toLowerCase()}`
59
+ }
60
+
61
+ function emptyFile(): OrganizerFile { return { version: 1, rev: 0, folders: {}, sessions: {} } }
62
+
63
+ function validShape(value: unknown): value is OrganizerFile {
64
+ if (!value || typeof value !== 'object') return false
65
+ const v = value as Partial<OrganizerFile>
66
+ if (v.version !== 1 || typeof v.rev !== 'number' || !Number.isInteger(v.rev) || v.rev < 0) return false
67
+ if (!v.folders || typeof v.folders !== 'object' || Array.isArray(v.folders)) return false
68
+ if (!v.sessions || typeof v.sessions !== 'object' || Array.isArray(v.sessions)) return false
69
+ for (const [id, folder] of Object.entries(v.folders)) {
70
+ if (!FOLDER_ID_RE.test(id) || !folder || typeof folder.name !== 'string' || typeof folder.created_at !== 'string') return false
71
+ }
72
+ for (const [key, entry] of Object.entries(v.sessions)) {
73
+ const provider = key.split(':', 1)[0]
74
+ if (!PROVIDERS.has(provider) || key.length <= provider.length + 1 || !entry || typeof entry.updated_at !== 'string') return false
75
+ if (entry.folder_id !== undefined && (typeof entry.folder_id !== 'string' || !v.folders[entry.folder_id])) return false
76
+ if (entry.cos_pinned !== undefined && entry.cos_pinned !== true) return false
77
+ if (entry.title !== undefined && typeof entry.title !== 'string') return false
78
+ if (entry.desktop_id !== undefined && typeof entry.desktop_id !== 'string') return false
79
+ }
80
+ return true
81
+ }
82
+
83
+ export type OrganizerLog = (line: string) => void
84
+
85
+ export class SessionOrganizer {
86
+ private state: OrganizerFile = emptyFile()
87
+ private available = true
88
+
89
+ constructor(private readonly path: string = dataPath(ORGANIZER_FILE), private readonly log: OrganizerLog = line => console.warn(line),
90
+ private readonly now: () => Date = () => new Date()) {
91
+ this.load()
92
+ }
93
+
94
+ private load(): void {
95
+ if (!existsSync(this.path)) return
96
+ let raw: string
97
+ try {
98
+ raw = readFileSync(this.path, 'utf8')
99
+ } catch (error) {
100
+ // Exists but unreadable (permission, I/O): never write over it.
101
+ this.available = false
102
+ this.log(`[session-organizer] unavailable: the store exists but could not be read (${(error as NodeJS.ErrnoException)?.code ?? 'error'})`)
103
+ return
104
+ }
105
+ let parsed: unknown
106
+ try { parsed = JSON.parse(raw) } catch { parsed = undefined }
107
+ if (validShape(parsed)) { this.state = parsed; return }
108
+ const aside = `${this.path}.corrupt-${Date.now()}`
109
+ try {
110
+ renameSync(this.path, aside)
111
+ this.log('[session-organizer] the store did not parse; moved aside and started empty (reason=corrupt_store)')
112
+ } catch {
113
+ this.available = false
114
+ this.log('[session-organizer] unavailable: the store did not parse and could not be moved aside (reason=corrupt_store)')
115
+ }
116
+ }
117
+
118
+ isAvailable(): boolean { return this.available }
119
+ rev(): number { return this.state.rev }
120
+ isEmpty(): boolean { return Object.keys(this.state.folders).length === 0 && Object.keys(this.state.sessions).length === 0 }
121
+
122
+ private requireAvailable(): void {
123
+ if (!this.available) throw new OrganizerError(503, 'organizer_unavailable')
124
+ }
125
+
126
+ private commit(next: OrganizerFile): void {
127
+ next.rev = this.state.rev + 1
128
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })
129
+ durableAtomicWriteFileSync(this.path, JSON.stringify(next), { mode: 0o600 })
130
+ this.state = next
131
+ }
132
+
133
+ private clone(): OrganizerFile { return structuredClone(this.state) }
134
+
135
+ private counts(): Map<string, number> {
136
+ const counts = new Map<string, number>()
137
+ for (const entry of Object.values(this.state.sessions)) {
138
+ if (entry.folder_id) counts.set(entry.folder_id, (counts.get(entry.folder_id) ?? 0) + 1)
139
+ }
140
+ return counts
141
+ }
142
+
143
+ listFolders(): Array<{ id: string; name: string; created_at: string; count: number }> {
144
+ const counts = this.counts()
145
+ return Object.entries(this.state.folders)
146
+ .map(([id, f]) => ({ id, name: f.name, created_at: f.created_at, count: counts.get(id) ?? 0 }))
147
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }) || a.id.localeCompare(b.id))
148
+ }
149
+
150
+ private nameTaken(name: string, except?: string): boolean {
151
+ const lower = name.toLocaleLowerCase()
152
+ return Object.entries(this.state.folders).some(([id, f]) => id !== except && f.name.toLocaleLowerCase() === lower)
153
+ }
154
+
155
+ createFolder(rawName: unknown): { id: string; name: string; created_at: string; count: number } {
156
+ this.requireAvailable()
157
+ const name = cleanOrganizerText(rawName, ORGANIZER_LIMITS.folderName)
158
+ if (!name) throw new OrganizerError(400, 'invalid_name')
159
+ if (Object.keys(this.state.folders).length >= ORGANIZER_LIMITS.folders) throw new OrganizerError(409, 'too_many_folders')
160
+ if (this.nameTaken(name)) throw new OrganizerError(409, 'folder_name_taken')
161
+ let id = ''
162
+ do { id = `f_${randomBytes(8).toString('hex')}` } while (this.state.folders[id])
163
+ const next = this.clone()
164
+ const created_at = this.now().toISOString()
165
+ next.folders[id] = { name, created_at }
166
+ this.commit(next)
167
+ return { id, name, created_at, count: 0 }
168
+ }
169
+
170
+ renameFolder(id: string, rawName: unknown): { id: string; name: string; created_at: string; count: number } {
171
+ this.requireAvailable()
172
+ const folder = this.state.folders[id]
173
+ if (!folder) throw new OrganizerError(404, 'folder_not_found')
174
+ const name = cleanOrganizerText(rawName, ORGANIZER_LIMITS.folderName)
175
+ if (!name) throw new OrganizerError(400, 'invalid_name')
176
+ if (this.nameTaken(name, id)) throw new OrganizerError(409, 'folder_name_taken')
177
+ const next = this.clone()
178
+ next.folders[id] = { ...folder, name }
179
+ this.commit(next)
180
+ return { id, name, created_at: folder.created_at, count: this.counts().get(id) ?? 0 }
181
+ }
182
+
183
+ /** Removes the folder. Its sessions leave it; no session is ever deleted. Returns how many left. */
184
+ deleteFolder(id: string): number {
185
+ this.requireAvailable()
186
+ if (!this.state.folders[id]) throw new OrganizerError(404, 'folder_not_found')
187
+ const next = this.clone()
188
+ delete next.folders[id]
189
+ let released = 0
190
+ const stamp = this.now().toISOString()
191
+ for (const [key, entry] of Object.entries(next.sessions)) {
192
+ if (entry.folder_id !== id) continue
193
+ released++
194
+ delete entry.folder_id
195
+ entry.updated_at = stamp
196
+ if (!entry.cos_pinned && entry.title === undefined) delete next.sessions[key]
197
+ }
198
+ this.commit(next)
199
+ return released
200
+ }
201
+
202
+ /**
203
+ * One session's change. `key` must already be canonical (organizerKey on the canonical id). Keys left out of
204
+ * `change` are untouched; `null` clears. An entry left with nothing in it is removed.
205
+ */
206
+ updateSession(key: string, change: { folder_id?: unknown; cos_pinned?: unknown; title?: unknown }, ids: { desktopId?: string } = {}): OrganizerRowFields {
207
+ this.requireAvailable()
208
+ const touchesFolder = Object.prototype.hasOwnProperty.call(change, 'folder_id')
209
+ const touchesPin = Object.prototype.hasOwnProperty.call(change, 'cos_pinned')
210
+ const touchesTitle = Object.prototype.hasOwnProperty.call(change, 'title')
211
+ if (!touchesFolder && !touchesPin && !touchesTitle) throw new OrganizerError(400, 'empty_change')
212
+ let folderId: string | null | undefined
213
+ if (touchesFolder) {
214
+ if (change.folder_id === null) folderId = null
215
+ else if (typeof change.folder_id === 'string' && this.state.folders[change.folder_id]) folderId = change.folder_id
216
+ else throw new OrganizerError(404, 'folder_not_found')
217
+ }
218
+ if (touchesPin && typeof change.cos_pinned !== 'boolean') throw new OrganizerError(400, 'invalid_pin')
219
+ let title: string | null | undefined
220
+ if (touchesTitle) {
221
+ if (change.title === null) title = null
222
+ else {
223
+ title = cleanOrganizerText(change.title, ORGANIZER_LIMITS.title)
224
+ if (!title) throw new OrganizerError(400, 'invalid_title')
225
+ }
226
+ }
227
+ const desktopId = ids.desktopId?.trim().toLowerCase() || undefined
228
+ // Q1 FIX 2: an entry written under the same Desktop id but another key (its CLI alias appeared or changed since)
229
+ // moves to this key, so one session never has two entries.
230
+ const movedFrom = !this.state.sessions[key] && desktopId
231
+ ? Object.keys(this.state.sessions).find(k => k.startsWith('claude:') && this.state.sessions[k].desktop_id === desktopId)
232
+ : undefined
233
+ const existing = this.state.sessions[key] ?? (movedFrom ? this.state.sessions[movedFrom] : undefined)
234
+ if (!existing && Object.keys(this.state.sessions).length >= ORGANIZER_LIMITS.entries) throw new OrganizerError(409, 'too_many_entries')
235
+ const next = this.clone()
236
+ const entry: OrganizerEntry = { ...(existing ? structuredClone(existing) : {}), updated_at: this.now().toISOString() }
237
+ if (movedFrom) delete next.sessions[movedFrom]
238
+ if (desktopId) entry.desktop_id = desktopId
239
+ if (folderId === null) delete entry.folder_id; else if (folderId) entry.folder_id = folderId
240
+ if (touchesPin) { if (change.cos_pinned === true) entry.cos_pinned = true; else delete entry.cos_pinned }
241
+ if (title === null) delete entry.title; else if (title) entry.title = title
242
+ if (!entry.folder_id && !entry.cos_pinned && entry.title === undefined) delete next.sessions[key]
243
+ else next.sessions[key] = entry
244
+ this.commit(next)
245
+ return this.fieldsFor(key)
246
+ }
247
+
248
+ /** The fields for the first of these keys that has an entry, or for an entry written under one of `desktopIds`. */
249
+ fieldsForAny(keys: readonly string[], desktopIds: readonly string[] = []): OrganizerRowFields {
250
+ for (const key of keys) if (this.state.sessions[key]) return this.fieldsFor(key)
251
+ if (desktopIds.length) {
252
+ const wanted = new Set(desktopIds.map(id => id.toLowerCase()))
253
+ for (const [key, entry] of Object.entries(this.state.sessions)) {
254
+ if (entry.desktop_id && key.startsWith('claude:') && wanted.has(entry.desktop_id)) return this.fieldsFor(key)
255
+ }
256
+ }
257
+ return {}
258
+ }
259
+
260
+ /** The fields a row for this canonical key carries (empty when none). */
261
+ fieldsFor(key: string): OrganizerRowFields {
262
+ const entry = this.state.sessions[key]
263
+ if (!entry) return {}
264
+ return {
265
+ ...(entry.folder_id ? { folder_id: entry.folder_id } : {}),
266
+ ...(entry.cos_pinned ? { cos_pinned: true as const } : {}),
267
+ ...(entry.title !== undefined ? { title_override: entry.title } : {}),
268
+ }
269
+ }
270
+
271
+ /** Canonical ids per provider that the list keeps at any age and outside its caps: COS pins and folder members. */
272
+ keptIds(): Record<OrganizerProvider, Set<string>> {
273
+ const kept: Record<OrganizerProvider, Set<string>> = { claude: new Set(), codex: new Set(), cursor: new Set() }
274
+ for (const [key, entry] of Object.entries(this.state.sessions)) {
275
+ if (!entry.cos_pinned && !entry.folder_id) continue
276
+ const at = key.indexOf(':')
277
+ kept[key.slice(0, at) as OrganizerProvider].add(key.slice(at + 1))
278
+ // The list maps a Desktop id to its current CLI id, so an entry follows its session when the alias changes.
279
+ if (entry.desktop_id) kept.claude.add(entry.desktop_id)
280
+ }
281
+ return kept
282
+ }
283
+
284
+ /** Keys whose renamed title contains `query` (case-insensitive), for search. */
285
+ titleMatches(query: string): Array<{ provider: OrganizerProvider; session_id: string }> {
286
+ const needle = query.trim().toLocaleLowerCase()
287
+ if (!needle) return []
288
+ const out: Array<{ provider: OrganizerProvider; session_id: string }> = []
289
+ for (const [key, entry] of Object.entries(this.state.sessions)) {
290
+ if (entry.title === undefined || !entry.title.toLocaleLowerCase().includes(needle)) continue
291
+ const at = key.indexOf(':')
292
+ out.push({ provider: key.slice(0, at) as OrganizerProvider, session_id: key.slice(at + 1) })
293
+ }
294
+ return out
295
+ }
296
+ }
297
+
298
+ let shared: SessionOrganizer | null = null
299
+ /** The server's one organizer, loaded on first use. */
300
+ export function sessionOrganizer(): SessionOrganizer {
301
+ if (!shared) shared = new SessionOrganizer()
302
+ return shared
303
+ }
304
+ /** Tests only. */
305
+ export function __resetSessionOrganizerForTests(next: SessionOrganizer | null = null): void { shared = next }
@@ -1354,6 +1354,16 @@ export function draftsFromLine(provider: SessionStreamProvider, line: string): S
1354
1354
  *
1355
1355
  * Skipped: `isMeta` and `isCompactSummary` rows (injected context, not a prompt), tool
1356
1356
  * results, and the bookkeeping rows (`system`, `last-prompt`, `attachment`, `mode`...).
1357
+ *
1358
+ * ONLY `type: 'user'` AND `type: 'assistant'` ROWS ARE THE CONVERSATION (2026-11-11). Every
1359
+ * other row type is skipped, whatever its `message.role`. Claude Code 2.1.300 (first seen
1360
+ * 2026-10-14) writes `api-request-blob` rows: no timestamp, `message.role` user or assistant,
1361
+ * copies of earlier blocks, written AFTER the tool results they repeat. Read as a reply, a
1362
+ * copied `tool_use` re-opened a tool that had already answered, the tail read `tool_pending`,
1363
+ * and the queue held a turn parked for an idle Desktop session until 30 minutes of quiet
1364
+ * (S1, lanes/S1_queue_hold_diagnosis.md: 15 of 56 ended transcripts read open). An UNKNOWN
1365
+ * row type therefore never opens a turn: it fails toward "ended", and the hooks, the registry
1366
+ * and the gate still decide whether anything is sent.
1357
1367
  * Codex keeps its event rule (task_complete / turn_complete end, task_started opens).
1358
1368
  *
1359
1369
  * PURE, like everything else here. The queue store reads the tail; this decides.
@@ -1400,7 +1410,9 @@ export function turnFromTail(provider: SessionStreamProvider, lines: readonly st
1400
1410
  const content = Array.isArray(message.content) ? message.content : typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : []
1401
1411
  const blocks = content.map(asRecord).filter((b): b is Record<string, unknown> => b !== null)
1402
1412
 
1403
- if (type === 'user' || message.role === 'user') {
1413
+ // The conversation is `user` and `assistant` rows only, by row TYPE, never by `message.role` (see the header:
1414
+ // an api-request-blob carries a role, and any row type this build does not know falls through both branches).
1415
+ if (type === 'user') {
1404
1416
  const results = blocks.filter(b => b.type === 'tool_result')
1405
1417
  if (results.length > 0) {
1406
1418
  for (const b of results) if (typeof b.tool_use_id === 'string') pendingToolUses.delete(b.tool_use_id)
@@ -1413,7 +1425,7 @@ export function turnFromTail(provider: SessionStreamProvider, lines: readonly st
1413
1425
  continue
1414
1426
  }
1415
1427
 
1416
- if (type === 'assistant' || message.role === 'assistant') {
1428
+ if (type === 'assistant') {
1417
1429
  for (const b of blocks) if (b.type === 'tool_use' && typeof b.id === 'string') pendingToolUses.add(b.id)
1418
1430
  const stop = typeof message.stop_reason === 'string' ? message.stop_reason : ''
1419
1431
  if (TERMINAL_STOP_REASONS.has(stop)) {
@@ -1,8 +1,9 @@
1
1
  // This Mac's own Tailscale MagicDNS name, for COS Control Web's origin checks.
2
2
  //
3
3
  // WHY NOT THE TAILSCALE CLI. Under the server's LaunchAgent the `tailscale status --json` call
4
- // the nudger makes does not answer (server.log: "trigger=boot dropped: Tailscale did not answer
5
- // for 120s"), so the nudger never learns Self.DNSName and a phone at
4
+ // the nudger makes fails: node passes its child no SHLVL, and the macOS CLI then answers "The
5
+ // Tailscale GUI failed to start" instead of the JSON (probe 2026-11-10; server.log's "Tailscale did
6
+ // not answer for 120s" is the event's age, not a hang). So the nudger never learns Self.DNSName and a phone at
6
7
  // http://<mac>.<tailnet>.ts.net:3141/control was refused by CORS on every write (6.99.1).
7
8
  // MagicDNS itself answers a reverse lookup of this Mac's own 100.x address at 100.100.100.100
8
9
  // in about a millisecond, with no CLI involved. The nudger's answer still wins when it has one.
@@ -10,6 +11,13 @@
10
11
  // EXACT NAME ONLY. The answer is normalised by normalizeTailscaleDnsName (lowercase, one
11
12
  // trailing dot dropped, must end in .ts.net) and compared for equality; never a suffix match.
12
13
  // No answer means no name: the tailnet NAME is refused and the tailnet IP URL keeps working.
14
+ //
15
+ // A MISS IS NOT FINAL (7.0.14). The boot lookup can miss (a startup race), and readers that only
16
+ // call currentSelfDnsName() then saw null forever: /api/web-key/status answered `origin: null` (COS
17
+ // Control hid Phone approvals) and the 3144 signer refused every phone write `origin_refused`, until
18
+ // some other route happened to call refresh(). refreshIfMissing() is for exactly those readers: with
19
+ // a name known it returns it and looks nothing up; with none it joins the lookup in flight or starts
20
+ // ONE, at most once per TAILNET_NAME_ON_DEMAND_MIN_MS, and waits at most a bounded time.
13
21
 
14
22
  import { Resolver } from 'node:dns/promises'
15
23
  import { networkInterfaces } from 'node:os'
@@ -18,6 +26,10 @@ import { normalizeTailscaleDnsName, reachableIpv4Addresses } from './network-pol
18
26
  export const TAILNET_NAME_HIT_TTL_MS = 10 * 60_000
19
27
  export const TAILNET_NAME_MISS_TTL_MS = 60_000
20
28
  export const TAILNET_REVERSE_TIMEOUT_MS = 1_500
29
+ /** refreshIfMissing(): while the name is unknown, at most one lookup it starts per this window. */
30
+ export const TAILNET_NAME_ON_DEMAND_MIN_MS = 30_000
31
+ /** refreshIfMissing(): the longest a request waits for that lookup (the lookup itself is bounded by the resolver timeout). */
32
+ export const TAILNET_NAME_ON_DEMAND_WAIT_MS = 2_000
21
33
  const MAGIC_DNS_RESOLVER = '100.100.100.100'
22
34
 
23
35
  export interface TailnetSelfNameDeps {
@@ -37,6 +49,13 @@ export interface TailnetSelfName {
37
49
  refresh(): Promise<string | null>
38
50
  /** `SelfDnsSource` for isAllowedCorsOrigin: same as refresh(). */
39
51
  queryStatus(): Promise<string | null>
52
+ /**
53
+ * For a request that must not act on a stale miss (7.0.14). A name known now: that name, no lookup.
54
+ * None: joins the lookup in flight, or starts one unless this method started one in the last
55
+ * TAILNET_NAME_ON_DEMAND_MIN_MS (then null at once). Waits at most `waitMs`; a slower lookup keeps
56
+ * running and caches its answer for the next reader. Never throws.
57
+ */
58
+ refreshIfMissing(waitMs?: number): Promise<string | null>
40
59
  }
41
60
 
42
61
  function defaultTailscaleIpv4(): string | null {
@@ -62,13 +81,8 @@ export function createTailnetSelfName(deps: TailnetSelfNameDeps = {}): TailnetSe
62
81
 
63
82
  const currentSelfDnsName = (): string | null => fromNudger() ?? cached?.name ?? null
64
83
 
65
- const refresh = (): Promise<string | null> => {
66
- const known = fromNudger()
67
- if (known) return Promise.resolve(known)
68
- const at = now()
69
- if (cached && at - cached.at < (cached.name ? TAILNET_NAME_HIT_TTL_MS : TAILNET_NAME_MISS_TTL_MS)) {
70
- return Promise.resolve(cached.name)
71
- }
84
+ // The one lookup (single-flight): every caller below shares the promise in flight.
85
+ const lookup = (): Promise<string | null> => {
72
86
  if (inflight) return inflight
73
87
  inflight = (async () => {
74
88
  let name: string | null = null
@@ -88,7 +102,40 @@ export function createTailnetSelfName(deps: TailnetSelfNameDeps = {}): TailnetSe
88
102
  return inflight
89
103
  }
90
104
 
91
- return { currentSelfDnsName, refresh, queryStatus: refresh }
105
+ const refresh = (): Promise<string | null> => {
106
+ const known = fromNudger()
107
+ if (known) return Promise.resolve(known)
108
+ const at = now()
109
+ if (cached && at - cached.at < (cached.name ? TAILNET_NAME_HIT_TTL_MS : TAILNET_NAME_MISS_TTL_MS)) {
110
+ return Promise.resolve(cached.name)
111
+ }
112
+ return lookup()
113
+ }
114
+
115
+ // When refreshIfMissing() last STARTED a lookup. Its own clock: the boot lookup and refresh()'s TTL
116
+ // do not count, so the first reader after a boot miss looks again at once.
117
+ let onDemandAt: number | null = null
118
+ const refreshIfMissing = (waitMs: number = TAILNET_NAME_ON_DEMAND_WAIT_MS): Promise<string | null> => {
119
+ const known = currentSelfDnsName()
120
+ if (known) return Promise.resolve(known)
121
+ let pending: Promise<string | null>
122
+ if (inflight) {
123
+ pending = inflight
124
+ } else {
125
+ const at = now()
126
+ if (onDemandAt !== null && at - onDemandAt < TAILNET_NAME_ON_DEMAND_MIN_MS) return Promise.resolve(null)
127
+ onDemandAt = at
128
+ pending = lookup()
129
+ }
130
+ const wait = Math.max(0, waitMs)
131
+ return new Promise<string | null>(resolve => {
132
+ const timer = setTimeout(() => resolve(null), wait)
133
+ timer.unref?.()
134
+ pending.then(name => { clearTimeout(timer); resolve(name) }, () => { clearTimeout(timer); resolve(null) })
135
+ })
136
+ }
137
+
138
+ return { currentSelfDnsName, refresh, queryStatus: refresh, refreshIfMissing }
92
139
  }
93
140
 
94
141
  let singleton: TailnetSelfName | null = null
@@ -122,6 +122,14 @@ export interface QueuedThreadTurn {
122
122
  * the words alone, so the pending row and its preview never show a path. Absent on a turn without files.
123
123
  */
124
124
  attachmentIds?: string[]
125
+ /**
126
+ * 2026-11-11 (S1, Miles's note held 08:01): WHY a `waiting` row is held, as a short code the drain decided, and
127
+ * since when that code has held (epoch ms). Written only when the code CHANGES, never per sweep, so a held row
128
+ * costs no extra writes. Additive: an older server or client ignores both. Codes only, never text
129
+ * (`holdReasonFor`, `HOLD_REASON_CODE`).
130
+ */
131
+ holdReason?: string
132
+ holdSince?: number
125
133
  }
126
134
 
127
135
  // ------------------------------------------------------------------- 6.78.0 flags
@@ -376,6 +384,22 @@ export function drainDecision(
376
384
  return seen.activity === 'idle' ? 'deliver' : 'hold'
377
385
  }
378
386
 
387
+ /** A hold reason is a short code: lowercase letters, digits and underscores. Anything else reads `gate_closed`. */
388
+ export const HOLD_REASON_CODE = /^[a-z0-9_]{1,48}$/
389
+
390
+ /**
391
+ * Why `drainDecision` held this row, as a code (2026-11-11). Same order as the decision, so the code names the
392
+ * branch that held: a cancel hold, then the gate (its own reason), then an open turn, then a turn not yet ended.
393
+ * Only meaningful for a row the decision held; `files_wait_for_turn_end` is set by the drain itself, when the
394
+ * row's files are the only thing that kept it from going into the running turn.
395
+ */
396
+ export function holdReasonFor(seen: DrainObservation, now: number): string {
397
+ if (typeof seen.cancelHoldUntil === 'number' && Number.isFinite(seen.cancelHoldUntil) && now < seen.cancelHoldUntil) return 'cancel_hold'
398
+ if (!seen.attachable) return typeof seen.reason === 'string' && HOLD_REASON_CODE.test(seen.reason) ? seen.reason : 'gate_closed'
399
+ if (seen.turnOpen === true) return 'turn_open'
400
+ return 'turn_not_ended'
401
+ }
402
+
379
403
  /**
380
404
  * Admit a turn to the queue, or say why not.
381
405
  *
@@ -92,6 +92,13 @@ export interface WebKeySignerDeps {
92
92
  api: (req: IncomingMessage, res: ServerResponse) => void
93
93
  /** `https://<MagicDNS name>:3144` (lib/web-key-origin.ts), or null when unknown. */
94
94
  origin: () => string | null
95
+ /**
96
+ * 7.0.14: called (and awaited) only when origin() is null on an /api request, before the origin
97
+ * check, so a boot-time miss of the tailnet name does not refuse the phone `origin_refused` until
98
+ * something else refreshes it (lib/tailnet-self-name.ts refreshIfMissing: bounded, single-flight,
99
+ * rate-limited). Absent: the null origin stands, as before.
100
+ */
101
+ refreshOrigin?: () => Promise<unknown>
95
102
  /** How often the signer's files are re-checked. 0: never on a timer (tests call integrity.check()). */
96
103
  recheckMs?: number
97
104
  }
@@ -128,13 +135,25 @@ export function createWebKeySignerHandler(deps: WebKeySignerDeps): ((req: Incomi
128
135
  const method = String(req.method ?? 'GET').toUpperCase()
129
136
 
130
137
  if (pathname === '/api' || pathname.startsWith('/api/')) {
138
+ const decide = (expected: string | null): void => {
139
+ const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined
140
+ // Another origin's page never drives this one. A write must name this origin outright.
141
+ if (origin !== undefined && origin !== expected) { json(res, 403, { ok: false, error: 'origin_refused' }); return }
142
+ if (method !== 'GET' && method !== 'HEAD' && (expected === null || origin !== expected)) { json(res, 403, { ok: false, error: 'origin_refused' }); return }
143
+ if (!signerApiAllowed(method === 'HEAD' ? 'GET' : method, pathname)) { json(res, 404, { ok: false, error: 'not_found' }); return }
144
+ deps.api(req, res)
145
+ }
131
146
  const expected = deps.origin()
132
- const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined
133
- // Another origin's page never drives this one. A write must name this origin outright.
134
- if (origin !== undefined && origin !== expected) { json(res, 403, { ok: false, error: 'origin_refused' }); return }
135
- if (method !== 'GET' && method !== 'HEAD' && (expected === null || origin !== expected)) { json(res, 403, { ok: false, error: 'origin_refused' }); return }
136
- if (!signerApiAllowed(method === 'HEAD' ? 'GET' : method, pathname)) { json(res, 404, { ok: false, error: 'not_found' }); return }
137
- deps.api(req, res)
147
+ if (expected !== null || !deps.refreshOrigin) { decide(expected); return }
148
+ // Name unknown: one bounded lookup, then the same checks against whatever it found (null still refuses).
149
+ let refreshing: Promise<unknown>
150
+ try { refreshing = Promise.resolve(deps.refreshOrigin()) } catch { refreshing = Promise.resolve() }
151
+ const after = (): void => {
152
+ let found: string | null = null
153
+ try { found = deps.origin() } catch { found = null }
154
+ decide(found)
155
+ }
156
+ void refreshing.then(after, after)
138
157
  return
139
158
  }
140
159