heyquilt 0.3.147 → 0.3.149

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,443 @@
1
+ // Quilt's side of seam: live squares in a Quilt session. Seam (src/quilts/) never imports this.
2
+ // A person's held work lands by itself (Daniel, 2026-11-03). A folder's square holds the person's live
3
+ // work until someone commits and merges it, and when another merge changed the same lines it held a
4
+ // conflict too, waiting for a person nobody had asked (sq:09a100d0's RELEASES.md against main:1076).
5
+ // Agents' squares have their AI asked; a person's folder square had no one. Now, whatever how long the
6
+ // work was held, the person's app (as them, with their own Seam sign-in) lands it with no step of theirs:
7
+ //
8
+ // 1. Quiet for a moment (LAND_QUIET_MS after the last edit to the square, anyone's): the square's live
9
+ // work is committed with a message naming its files and merged onto its line, waiting for the
10
+ // line's required checks the way `seam merge --wait` does (merge-wait.js); the folder carries on
11
+ // in a new square (the relay's quilt-next).
12
+ // 2. A conflict in the square is settled without asking the person, in this order:
13
+ // a. what Seam offers by itself: a conflict's word-level suggestion, else its additive and
14
+ // whitespace steps (a changelog also its union step: bring-in.js isChangelog), else the work
15
+ // put onto main's copy when it was made on an older one (bring-in.js onOlderCopy);
16
+ // b. the person's own AI on their cloud machine, when they connected one: a task on the board for
17
+ // "<person>'s AI" (the relay wakes it, as for any task given to it; the same for every AI
18
+ // tool), with the file, both sides and what to do. AI_ATTEMPTS tries, as Seam gives an AI.
19
+ // AI sessions on the person's computer ARE the person, and are never handed this;
20
+ // c. else main's side stays in the file, and the person's version of each such file is kept in a
21
+ // square of its own, opened from their work and titled so they find it; the held square then
22
+ // merges, and the person is told once, in chat. Nothing is lost.
23
+ //
24
+ // Only the square's holder's app lands it; a writer's app does once the holder's has been quiet for
25
+ // HOLDER_WAIT_MS more (offline), the same turn as bringing main in (bring-in.js).
26
+ import { mergeWaiting } from '@heyquilt/seam/lib/quilts/merge-wait.js'
27
+ import { parseMarkers } from '@heyquilt/seam/lib/quilts/conflict-format.js'
28
+ import { blobId } from '@heyquilt/seam/lib/quilts/records.js'
29
+ import { squareShort } from '@heyquilt/seam/lib/quilts/errors.js'
30
+ import { isChangelog, onOlderCopy, olderTexts, unionMarked, HOLDER_WAIT_MS } from './bring-in.js'
31
+
32
+ const num = (v, d) => (Number(v) > 0 ? Number(v) : d)
33
+ // How long the square's work is left alone after its last edit before it lands.
34
+ export const LAND_QUIET_MS = num(process.env.QUILT_LAND_QUIET_MS, 90 * 1000)
35
+ // Seam's own number of tries an AI gets at one conflict (Seam's events.js AI_ATTEMPTS).
36
+ export const AI_ATTEMPTS = 2
37
+ // How long one try of the person's AI may take before it counts as failed.
38
+ export const AI_ATTEMPT_MS = num(process.env.QUILT_LAND_AI_MS, 15 * 60 * 1000)
39
+ // How long a merge waits for the line's required checks (seconds), as `seam merge --wait` would.
40
+ export const LAND_WAIT_S = num(process.env.QUILT_LAND_WAIT_S, 30 * 60)
41
+ // After a merge the line refused for something only a person can give (an approval, a red check), the next try.
42
+ export const REFUSED_RETRY_MS = 10 * 60 * 1000
43
+ // Seam's ladder steps a person never has to choose, tried on each conflict in turn (seam_resolve's rule).
44
+ export const RULES = ['additive', 'whitespace']
45
+
46
+ /**
47
+ * Whether held work lands by itself: on, unless QUILT_LAND=off or the person turned it off in their
48
+ * settings (autoLand: 'off'). Under node --test (Quilt's own tests) it is off unless a test sets
49
+ * QUILT_LAND=on: a square merging by itself after a quiet moment would change what other tests watch.
50
+ */
51
+ export function landOn ({ env = process.env, settings = {} } = {}) {
52
+ const v = String(env.QUILT_LAND || '').toLowerCase()
53
+ if (v === 'off') return false
54
+ if (v === 'on') return true
55
+ if (env.NODE_TEST_CONTEXT) return false
56
+ return settings.autoLand !== 'off'
57
+ }
58
+
59
+ const listed = (names) => `${names.slice(0, 5).join(', ')}${names.length > 5 ? ` and ${names.length - 5} more` : ''}`
60
+ const clock = (ts) => new Date(ts).toISOString().slice(11, 16) + ' UTC'
61
+
62
+ /** The commit message of work that lands by itself: its files, and that Quilt landed it. */
63
+ export function landMessage (paths) {
64
+ const names = [...new Set(paths)].sort()
65
+ return names.length ? `Work on ${listed(names)}, landed by Quilt once the folder went quiet` : 'Work landed by Quilt once the folder went quiet'
66
+ }
67
+
68
+ /** The square the person's version of files is kept in, titled so they find it. */
69
+ export function keptTitle (paths, at) {
70
+ const names = [...new Set(paths)].sort()
71
+ const what = names.length === 1 ? names[0] : `${names.length} files (${listed(names)})`
72
+ return `Your ${what} from ${clock(at)}, kept when main changed the same lines`.slice(0, 200)
73
+ }
74
+
75
+ /** The board task that asks the person's AI to settle a conflict: the file and the square, with the conflict's term so a retry is told apart. */
76
+ export function aiTaskTitle ({ paths, square, term }) {
77
+ return `Settle ${listed(paths)} in ${squareShort(square)}: main changed the same lines as the held work (conflict ${String(term || '').slice(0, 8)})`.slice(0, 200)
78
+ }
79
+
80
+ /** The one notice the person gets when their version was kept aside. */
81
+ export function keptNotice ({ paths, kept, line = 'main', patch = null }) {
82
+ return `Your held work${patch ? ` landed on ${line} as patch ${patch}` : ` is landing on ${line}`}, but ${listed(paths)} changed on ${line} in the same lines, so ${line}'s version stayed there. Your version is kept in square ${squareShort(kept)} ("Your … kept when main changed the same lines"): nothing was lost.`
83
+ }
84
+
85
+ /**
86
+ * The sides of a conflicted file as Seam writes it in its snapshot format (cat format snapshot):
87
+ * { ours, theirs, base } texts (null for a side that deleted it), or null when it is not one plain
88
+ * two-sided term (a name conflict, more sides, no markers).
89
+ */
90
+ export function sidesOf (text) {
91
+ let regions
92
+ try { regions = parseMarkers(text) } catch { return null }
93
+ const blocks = regions.filter((r) => !r.ok)
94
+ if (blocks.length !== 1 || blocks[0].format !== 'snapshot' || regions.some((r) => r.ok && r.ok.some((l) => l !== ''))) return null
95
+ const b = blocks[0]
96
+ if (!b.sides || b.sides.length !== 2) return null
97
+ const t = (s) => (s && !s.deleted && typeof s.text === 'string' ? s.text : null)
98
+ const bases = b.removes || []
99
+ return { ours: t(b.sides[0]), theirs: t(b.sides[1]), base: typeof bases[0] === 'string' ? bases[0] : (bases[0] && typeof bases[0].text === 'string' ? bases[0].text : '') }
100
+ }
101
+
102
+ /**
103
+ * Lands one folder's square. Everything it touches comes in `o`: `quilt`, `square`, `line`; `client()`
104
+ * (a Seam client as this member: square, diff, tree, cat, resolve, merge, events, openSquare, upload,
105
+ * commit, pathHistory, blobs, quilt); `block` (the folder's live block: status, commit, moveTo, block);
106
+ * `next()` (the relay moves the branch on to a new square after a merge); `catchUp()` (main brought
107
+ * in first); `hasAi()` (the person connected a cloud AI); `board` ({ list, add, comment, move }) as the
108
+ * person; `notify(text)` (one note to the person, in chat); `log`; `now`, `quietMs`, `aiMs`,
109
+ * `holderWaitMs`, `waitS` and `marked(path)` (a project's merge=union files).
110
+ */
111
+ export class Lander {
112
+ constructor (o) {
113
+ Object.assign(this, { quietMs: LAND_QUIET_MS, aiMs: AI_ATTEMPT_MS, holderWaitMs: HOLDER_WAIT_MS, waitS: LAND_WAIT_S, now: Date.now, log: () => {}, notify: () => {}, hasAi: () => false, catchUp: async () => null, marked: null }, o)
114
+ this.lastEdit = this.now()
115
+ this.busy = false
116
+ this.timer = null
117
+ this.stopped = false
118
+ this.refusedAt = 0
119
+ this.refusedHead = null
120
+ this.state = null // what it did last, for status: { landed } | { kept } | { asked } | { waiting }
121
+ }
122
+
123
+ /** An edit reached the square (anyone's): the quiet starts again, and a look is due once it lasts. A test run of older work stops. */
124
+ edited () {
125
+ this.lastEdit = this.now()
126
+ if (this.gateRun) this.gateRun.abort()
127
+ this.soon(this.quietMs + 50)
128
+ }
129
+
130
+ soon (ms) {
131
+ if (this.stopped) return
132
+ clearTimeout(this.timer)
133
+ this.timer = setTimeout(() => { this.timer = null; this.tick().catch(() => {}) }, ms)
134
+ this.timer.unref?.()
135
+ }
136
+
137
+ stop () { this.stopped = true; clearTimeout(this.timer) }
138
+
139
+ async me (c) {
140
+ if (this.memberId) return this.memberId
141
+ const q = await c.quilt(this.quilt).catch(() => null)
142
+ this.memberId = (q && q.you && q.you.member_id) || null
143
+ return this.memberId
144
+ }
145
+
146
+ /** One look: lands the square's work, or settles its conflict first. Answers what it did ({ did, ... }). */
147
+ async tick () {
148
+ if (this.busy || this.stopped) return { did: 'busy' }
149
+ this.busy = true
150
+ try { return await this.look() } catch (err) {
151
+ this.log(`couldn't land square ${squareShort(this.square)}'s work by itself (${String(err.message || err).slice(0, 300)}); Quilt tries again in a minute.`)
152
+ return { did: 'failed', error: err.message }
153
+ } finally { this.busy = false }
154
+ }
155
+
156
+ async look () {
157
+ const c = await this.client()
158
+ if (!c) return { did: 'no-client' }
159
+ let sq = await c.square(this.quilt, this.square)
160
+ if (!sq || sq.state !== 'open') return { did: 'closed' }
161
+ // Seam moved the square's head itself (someone settled a conflict there, the person's AI from its own
162
+ // folder): the live document follows first, so a commit of the live work is made on the right head.
163
+ const want = sq.head || sq.base
164
+ if (this.block.moveTo && this.block.head && want && this.block.head !== want) {
165
+ await this.block.moveTo(want, { base: !sq.head }).catch(() => null)
166
+ // Still moving (the relay brings main in this moment): the next look.
167
+ if (this.block.head !== want) { this.soon(15 * 1000); return { did: 'moving' } }
168
+ }
169
+ const work = this.block.status ? this.block.status() : []
170
+ if (!work.length && !sq.head) return { did: 'nothing' }
171
+ const me = await this.me(c)
172
+ const holder = !!me && me === sq.holder
173
+ const quiet = this.now() - this.lastEdit
174
+ const need = this.quietMs + (holder ? 0 : this.holderWaitMs)
175
+ if (quiet < need) { this.soon(need - quiet + 50); return { did: 'waiting', for: need - quiet } }
176
+ // Main first: the square takes main's newer patches (bring-in.js), and then this looks again.
177
+ if (sq.behind_by) {
178
+ await this.catchUp()
179
+ sq = await c.square(this.quilt, this.square)
180
+ if (!sq || sq.state !== 'open') return { did: 'closed' }
181
+ if (sq.behind_by) { this.soon(30 * 1000); return { did: 'behind' } }
182
+ }
183
+ if (sq.conflicted_paths) return this.settle(c, sq)
184
+ // Refused for something only a person gives: not again for a while, unless the square changed.
185
+ const headNow = sq.head || null
186
+ if (this.refusedAt && this.refusedHead === headNow && !work.length && this.now() - this.refusedAt < REFUSED_RETRY_MS) return { did: 'refused-wait' }
187
+ // The gate (land-gate.js): the project's fast tests pass on the work as it would land, or it stays held.
188
+ if (this.gate) {
189
+ const g = await this.tested(sq)
190
+ if (g) return g
191
+ }
192
+ let head = sq.head
193
+ if (work.length) {
194
+ const r = await this.block.commit({ message: landMessage(work.map((w) => w.path)) })
195
+ head = (r && r.square && r.square.head) || (this.block.block && this.block.block.head) || head
196
+ }
197
+ if (!head) return { did: 'nothing' }
198
+ return this.merge(c, sq, head)
199
+ }
200
+
201
+ /**
202
+ * Runs the gate on the work as it is now, at most one run at a time. Null when it passed (or is off);
203
+ * else what the look answers: held (red, or it can't run; one note per failure, not again until the
204
+ * work changes) or restarted (an edit came while it ran: tested again after the next quiet).
205
+ */
206
+ async tested (sq) {
207
+ const since = this.lastEdit
208
+ const key = `${since} ${sq.head || sq.base}`
209
+ if (this.gateHeld && this.gateHeld.key === key) return { did: 'held', ...this.gateHeld.why }
210
+ const ac = new AbortController()
211
+ this.gateRun = ac
212
+ const was = this.state
213
+ this.state = { testing: { at: this.now() } }
214
+ let r
215
+ try { r = await this.gate({ signal: ac.signal }) } finally { this.gateRun = null }
216
+ if (!r || r.off) { this.state = was; return null }
217
+ if (r.stopped || this.lastEdit !== since) {
218
+ this.state = was
219
+ this.log('new edits came while the tests ran: they run again once the folder is quiet.')
220
+ this.soon(Math.max(0, this.lastEdit + this.quietMs - this.now()) + 50)
221
+ return { did: 'restarted' }
222
+ }
223
+ if (r.missing || !r.ok) {
224
+ const why = r.missing ? { missing: r.missing } : { failing: r.failing || [], code: r.code, ...(r.timedOut ? { timedOut: true } : {}) }
225
+ this.gateHeld = { key, why }
226
+ this.state = { held: { ...why, command: r.command || '', at: this.now() } }
227
+ const ran = `in a copy of your folder${r.command ? ` (${r.command})` : ''}`
228
+ const tail = 'It stays held; Quilt tries again after your next change.'
229
+ const failing = why.failing || []
230
+ let said = `Your held work did not land: the fast tests failed ${ran}${failing.length ? `: ${listed(failing)}` : ` (exit ${r.code}, no test named)`}. ${tail}`
231
+ if (r.timedOut) said = `Your held work did not land: the fast tests did not finish ${ran} in ${Math.round((r.ms || 0) / 60000)} min, so Quilt stopped them${failing.length ? ` (failed so far: ${listed(failing)})` : ''}. ${tail}`
232
+ if (r.missing) said = `Your held work did not land: ${r.missing}.`
233
+ const sig = r.missing ? `missing ${r.missing}` : `failing ${failing.join('\n') || r.code}`
234
+ if (sig !== this.gateSaid) { this.gateSaid = sig; this.notify(said) }
235
+ this.log(said)
236
+ return { did: 'held', ...why }
237
+ }
238
+ this.gateHeld = null
239
+ this.gateSaid = null
240
+ this.state = was
241
+ this.log(`the fast tests passed on the held work${r.command ? ` (${r.command}` : ' ('}${r.ms ? `, ${Math.round(r.ms / 1000)} s` : ''}): it lands.`)
242
+ return null
243
+ }
244
+
245
+ async merge (c, sq, head) {
246
+ const line = sq.line || this.line || 'main'
247
+ const message = await this.title(c, sq).catch(() => null)
248
+ let r
249
+ try {
250
+ r = await mergeWaiting(c, this.quilt, line, { square: sq.id, expect_head: head, commit_live: false, ...(message ? { message } : {}) }, { wait: this.waitS, say: (t) => this.log(t) })
251
+ } catch (err) {
252
+ // An approval, a red check, a frozen line: a person's to give. Said once; tried again later.
253
+ this.refusedAt = this.now()
254
+ this.refusedHead = head
255
+ this.state = { waiting: String(err.message || err).split('\n')[0].slice(0, 300), at: this.now() }
256
+ this.log(`square ${squareShort(sq.id)}'s held work could not merge onto ${line} yet: ${this.state.waiting}`)
257
+ this.soon(REFUSED_RETRY_MS)
258
+ return { did: 'refused', error: err.message }
259
+ }
260
+ if (r && r.ok && r.merged) {
261
+ this.refusedAt = 0
262
+ const patch = r.merged.patch_no ?? null
263
+ this.state = { landed: { line, patch, at: this.now() } }
264
+ this.log(`landed square ${squareShort(sq.id)}'s held work on ${line}${patch != null ? ` as patch ${patch}` : ''}, with no step of yours.`)
265
+ this.closeAsks(sq, `Settled, and the held work landed on ${line}${patch != null ? ` as patch ${patch}` : ''}.`)
266
+ if (this.keptNote) { const n = this.keptNote; this.keptNote = null; this.notify(keptNotice({ ...n, line, patch })) }
267
+ try { await this.next() } catch (err) { this.log(`the folder's branch did not move to a new square yet (${err.message}); it does on the next look.`) }
268
+ return { did: 'landed', patch, line }
269
+ }
270
+ // A conflict: Seam rebased the square onto the line and kept it there (on_conflict rebase). The folder follows; settled next.
271
+ const to = (r && r.square && r.square.head) || (r && r.head) || null
272
+ if (to && this.block.moveTo) await this.block.moveTo(to).catch(() => {})
273
+ this.soon(1000)
274
+ return { did: 'conflict', terms: ((r && r.terms) || []).map((t) => t.path) }
275
+ }
276
+
277
+ /** The patch's title: the square's own commit messages (Seam would take the square's title, "Uncommitted work from …"). */
278
+ async title (c, sq) {
279
+ if (!c.log) return null
280
+ const log = await c.log(this.quilt, { rev: `sq:${sq.id}`, limit: 50 })
281
+ const own = ((log && log.commits) || []).filter((x) => x && x.square_id === sq.id && x.message).map((x) => String(x.message).split('\n')[0].trim()).filter(Boolean).reverse()
282
+ const uniq = [...new Set(own)]
283
+ if (!uniq.length) return null
284
+ if (uniq.length === 1) return uniq[0].slice(0, 200)
285
+ const all = `${uniq.length} commits: ${uniq.join('; ')}`
286
+ return all.length > 200 ? `${all.slice(0, 199)}…` : all
287
+ }
288
+
289
+ /** The square's conflicted files at its head: [{ path, term }]. */
290
+ async conflicts (c, sq) {
291
+ if (!sq.head) return []
292
+ const d = await c.diff(this.quilt, { from: `c:${sq.base}`, to: `c:${sq.head}`, format: 'names' })
293
+ const paths = ((d && d.files) || []).map((f) => f.path)
294
+ const out = []
295
+ for (let i = 0; i < paths.length; i += 100) {
296
+ const t = await c.tree(this.quilt, `c:${sq.head}`, paths.slice(i, i + 100))
297
+ for (const e of (t && t.entries) || []) if (e.mode === 'conflict') out.push({ path: e.path, term: e.term || '' })
298
+ }
299
+ return out
300
+ }
301
+
302
+ /** Settles the square's conflicts (2a, then 2b, then 2c at the top of this file), then looks again to merge. */
303
+ async settle (c, sq) {
304
+ const line = sq.line || this.line || 'main'
305
+ let head = sq.head
306
+ const resolve = async (path, entry) => {
307
+ const r = await c.resolve(this.quilt, sq.id, { expect_head: head, entries: [{ path, ...entry }] })
308
+ head = (r && r.square && r.square.head) || (r && r.result && r.result.id) || head
309
+ return r
310
+ }
311
+ let left = await this.conflicts(c, sq)
312
+ const settled = []
313
+ // Files the project marks merge=union (.gitattributes) are changelogs too.
314
+ if (!this.marked) this.marked = await unionMarked(c, this.quilt, line)
315
+ for (const x of left) {
316
+ // a. Seam's own answers: its suggestion, then its ladder steps; a changelog keeps both sides.
317
+ const tries = [{ choose: 'suggestion' }, ...RULES.map((rule) => ({ rule })), ...(isChangelog(x.path, this.marked) ? [{ rule: 'union' }] : [])]
318
+ let done = false
319
+ for (const t of tries) {
320
+ try { await resolve(x.path, t); done = true; settled.push({ path: x.path, how: t.choose || `rule:${t.rule}` }); break } catch (err) {
321
+ if (err.status === 409 && err.code !== 'conflict_taken') { head = (await c.square(this.quilt, sq.id)).head } else if (err.status && err.status >= 500) throw err
322
+ }
323
+ }
324
+ if (done) continue
325
+ // a. Work made on an older copy of main's file: its edits put onto main's copy.
326
+ const moved = await this.olderCopy(c, sq, line, x.path).catch(() => null)
327
+ if (moved) {
328
+ await c.upload(this.quilt, [{ kind: 'blob', id: moved.id, bytes: moved.bytes }])
329
+ try { await resolve(x.path, { choose: { blob: moved.id } }); settled.push({ path: x.path, how: 'older-copy' }); continue } catch {}
330
+ }
331
+ }
332
+ if (settled.length) {
333
+ this.log(`settled ${listed(settled.map((s) => s.path))} in square ${squareShort(sq.id)} as Seam offered (${[...new Set(settled.map((s) => s.how))].join(', ')}), with no step of yours.`)
334
+ if (this.block.moveTo && head) await this.block.moveTo(head).catch(() => {})
335
+ sq = await c.square(this.quilt, sq.id)
336
+ left = sq && sq.conflicted_paths ? await this.conflicts(c, sq) : []
337
+ }
338
+ if (!left.length) { this.closeAsks(sq); this.soon(settled.length ? 1000 : 30 * 1000); return { did: 'settled', settled } }
339
+ // b. The person's AI on their cloud machine, AI_ATTEMPTS tries.
340
+ if (this.hasAi() && this.board) {
341
+ const asked = this.ask(sq, left)
342
+ if (asked) return asked
343
+ }
344
+ // c. Main's side stays; the person's version is kept in a square of its own; the held work merges.
345
+ return this.keepAside(c, sq, left)
346
+ }
347
+
348
+ /** 2a's last step: the conflicted file's own side was made on an older copy of main's. { id, bytes } of the settled text, or null. */
349
+ async olderCopy (c, sq, line, path) {
350
+ const r = await c.cat(this.quilt, `c:${sq.head}`, path, { format: 'snapshot' })
351
+ if (!r || !r.conflict || !r.content) return null
352
+ const s = sidesOf(Buffer.from(r.content, 'base64').toString('utf8'))
353
+ if (!s || s.ours == null || s.theirs == null) return null
354
+ const union = isChangelog(path, this.marked)
355
+ const moved = onOlderCopy(s.ours, s.base, s.theirs, await olderTexts(c, this.quilt, path, line), { union })
356
+ if (!moved) return null
357
+ const bytes = Buffer.from(moved.text, 'utf8')
358
+ return { id: blobId(bytes), bytes }
359
+ }
360
+
361
+ /** The board's tasks this lander made for square `sq` (its marker in the title), and those for conflict `term`. */
362
+ asks (sq, term = null) {
363
+ let all = []
364
+ try { all = this.board.list() || [] } catch { return [] }
365
+ const mark = squareShort(sq.id)
366
+ return all.filter((t) => t && typeof t.title === 'string' && t.title.startsWith('Settle ') && t.title.includes(mark) && (!term || t.title.includes(`(conflict ${String(term).slice(0, 8)})`)))
367
+ }
368
+
369
+ /** 2b: a try of the person's AI is waiting, or a new one asked: { did }. Null once AI_ATTEMPTS tries failed. */
370
+ ask (sq, left) {
371
+ const term = left[0].term
372
+ const tries = this.asks(sq, term)
373
+ const open = tries.find((t) => !t.archived && t.column !== 'done' && t.column !== 'qa' && this.now() - (t.ts || 0) < this.aiMs)
374
+ if (open) { this.soon(Math.min(60 * 1000, this.aiMs)); return { did: 'asked', task: open.id, attempt: tries.length } }
375
+ if (tries.length >= AI_ATTEMPTS) return null
376
+ const paths = left.map((x) => x.path)
377
+ let task
378
+ // A board this member can't add to (a viewer's, say): straight to the rule, never a wait.
379
+ try { task = this.board.add({ title: aiTaskTitle({ paths, square: sq.id, term }), assignee: this.person, forAi: true }) } catch (err) { this.log(`couldn't ask ${this.person}'s AI on the board (${err.message})`); return null }
380
+ const id = task && (task.id || (task.task && task.task.id))
381
+ const line = sq.line || this.line || 'main'
382
+ const why = [
383
+ `${this.person}'s held work in square ${squareShort(sq.id)} and a newer patch on ${line} changed the same lines of ${listed(paths)}. This is try ${tries.length + 1} of ${AI_ATTEMPTS}.`,
384
+ `Read both sides with seam_square_status and seam_cat (rev sq:${squareShort(sq.id).slice(3)}, format git shows ours = the held work, theirs = ${line}'s). Keep what each side meant: settle each file with seam_resolve, or write the file without the markers, then seam_commit.`,
385
+ `Then move this task to Done. Quilt merges the square by itself once nothing in it is conflicted. If you can't settle it, say why in a comment and move it to Done: Quilt keeps ${line}'s side and keeps ${this.person}'s version in a square of its own.`
386
+ ].join('\n\n')
387
+ if (id) { try { this.board.comment(id, why) } catch {} }
388
+ this.state = { asked: { paths, attempt: tries.length + 1, at: this.now() } }
389
+ this.log(`asked ${this.person}'s AI to settle ${listed(paths)} in square ${squareShort(sq.id)} (try ${tries.length + 1} of ${AI_ATTEMPTS}).`)
390
+ this.soon(Math.min(60 * 1000, this.aiMs))
391
+ return { did: 'asked', task: id, attempt: tries.length + 1 }
392
+ }
393
+
394
+ /** Tasks asked of the AI for a square whose conflicts are all settled now: to Done, with a word. */
395
+ closeAsks (sq, words = 'Settled: nothing in the square is conflicted now, and Quilt merges it by itself.') {
396
+ if (!this.board || !sq) return
397
+ for (const t of this.asks(sq)) {
398
+ if (t.archived || t.column === 'done') continue
399
+ try { this.board.comment(t.id, words) } catch {}
400
+ try { this.board.move(t.id, 'done') } catch {}
401
+ }
402
+ }
403
+
404
+ /** 2c: main's side stays in each file; the person's version goes into a square of its own; the held work merges after. */
405
+ async keepAside (c, sq, left) {
406
+ const line = sq.line || this.line || 'main'
407
+ const at = this.now()
408
+ const mine = []
409
+ for (const x of left) {
410
+ const r = await c.cat(this.quilt, `c:${sq.head}`, x.path, { format: 'snapshot' })
411
+ const s = r && r.conflict && r.content ? sidesOf(Buffer.from(r.content, 'base64').toString('utf8')) : null
412
+ mine.push({ path: x.path, text: s ? s.ours : null, known: !!s })
413
+ }
414
+ const paths = left.map((x) => x.path)
415
+ const kept = await c.openSquare(this.quilt, { title: keptTitle(paths, at), line })
416
+ const changes = mine.filter((m) => m.known).map((m) => m.text == null ? { path: m.path, op: 'delete' } : { path: m.path, op: 'put', content: Buffer.from(m.text, 'utf8').toString('base64') })
417
+ if (changes.length) await c.commit(this.quilt, kept.id, { expect_head: null, message: `${keptTitle(paths, at)} (from square ${squareShort(sq.id)})`, changes })
418
+ let head = sq.head
419
+ for (const x of left) {
420
+ const r = await c.resolve(this.quilt, sq.id, { expect_head: head, entries: [{ path: x.path, choose: 'theirs' }], remember: false })
421
+ head = (r && r.square && r.square.head) || head
422
+ }
423
+ if (this.block.moveTo && head) await this.block.moveTo(head).catch(() => {})
424
+ this.closeAsks(sq, `Quilt kept ${line}'s side and put ${this.person}'s version in square ${squareShort(kept.id)}.`)
425
+ this.state = { kept: { paths, square: kept.id, title: keptTitle(paths, at), at } }
426
+ this.keptNote = { paths, kept: kept.id }
427
+ this.log(`kept ${line}'s side of ${listed(paths)} in square ${squareShort(sq.id)}; your version is in square ${squareShort(kept.id)} ("${keptTitle(paths, at)}").`)
428
+ // The held work merges now: no wait for quiet, the person did nothing since.
429
+ // The rest of the held work (anything still live, not committed) goes with it.
430
+ const now = await c.square(this.quilt, sq.id)
431
+ let r = null
432
+ if (now && !now.conflicted_paths) {
433
+ const work = this.block.status ? this.block.status() : []
434
+ let to = now.head
435
+ if (work.length) { const w = await this.block.commit({ message: landMessage(work.map((x) => x.path)) }); to = (w && w.square && w.square.head) || to }
436
+ if (to) r = await this.merge(c, now, to)
437
+ }
438
+ // Told once: with the patch when it landed now, else at once (it lands on a later look).
439
+ if (this.keptNote) { const n = this.keptNote; this.keptNote = null; this.notify(keptNotice({ ...n, line })) }
440
+ if (!r) this.soon(1000)
441
+ return { ...(r || { did: 'kept' }), kept: kept.id }
442
+ }
443
+ }
package/src/ui/app.css CHANGED
@@ -482,6 +482,8 @@ textarea.input { height: auto; padding: 10px 12px; resize: vertical; }
482
482
  .call-ai { position: absolute; right: -4px; top: -4px; width: 12px; height: 12px; display: grid; place-items: center; border-radius: 50%; background: var(--violet); color: #fff; box-shadow: 0 0 0 1.5px var(--panel); }
483
483
  .call-ai svg { width: 8px; height: 8px; }
484
484
  .call-face.agent.joining > :first-child { animation: call-joining 1.4s ease-in-out infinite; }
485
+ .call-face.agent.unheard > :first-child { opacity: .45; }
486
+ .cp-agents { padding-bottom: 8px; }
485
487
  @keyframes call-joining { 0%, 100% { box-shadow: 0 0 0 0 var(--violet); opacity: .55; } 50% { box-shadow: 0 0 0 3px var(--violet); opacity: 1; } }
486
488
  @media (prefers-reduced-motion: reduce) { .call-face.agent.joining > :first-child { animation: none; opacity: .6; box-shadow: 0 0 0 2px var(--violet); } }
487
489
  .call-tx { display: inline-flex; align-items: center; gap: 5px; height: 22px; padding: 0 8px; border: 1px solid var(--border); border-radius: 999px; background: none; color: var(--muted); font: 500 11.5px var(--sans); cursor: pointer; white-space: nowrap; }
@@ -73,10 +73,19 @@ export function catchUpWords (s) {
73
73
  if (stale.length) out.push(`${files(stale.length)} in this square ${stale.length === 1 ? 'was an older copy' : 'were older copies'} of main's, not anyone's edit: main's ${stale.length === 1 ? 'version stands' : 'versions stand'} (${listed(stale)}).`)
74
74
  }
75
75
  const n = s.conflicted ?? (b && b.conflicts ? b.conflicts.length : 0)
76
+ const l = s.landing || null
76
77
  if (n) {
77
78
  const named = b && b.conflicts && b.conflicts.length ? ` (${listed(b.conflicts)})` : ''
78
- out.push(`${files(n)} ${n === 1 ? 'conflicts' : 'conflict'} with main and ${n === 1 ? 'is' : 'are'} marked in this folder${named}: settle ${n === 1 ? 'it' : 'them'}, commit, and merge again.`)
79
+ // Held work lands by itself (source-live/land.js): the conflict is settled without the person.
80
+ if (s.lands) out.push(`${files(n)} ${n === 1 ? 'conflicts' : 'conflict'} with main and ${n === 1 ? 'is' : 'are'} marked in this folder${named}. Quilt settles ${n === 1 ? 'it' : 'them'} by itself: Seam's own merge if it has one, else your cloud AI if you connected one, else main's version stays and yours is kept in a square of its own. Then your work merges.`)
81
+ else out.push(`${files(n)} ${n === 1 ? 'conflicts' : 'conflict'} with main and ${n === 1 ? 'is' : 'are'} marked in this folder${named}: settle ${n === 1 ? 'it' : 'them'}, commit, and merge again.`)
79
82
  }
83
+ if (l && l.asked) out.push(`Your cloud AI is settling ${listed(l.asked.paths || [])} (try ${l.asked.attempt} of 2); your work merges once it is settled.`)
84
+ if (l && l.kept) out.push(`Main changed the same lines as your ${listed(l.kept.paths || [])}, so main's version stayed there; yours is kept in square sq:${String(l.kept.square || '').slice(-8)} ("${l.kept.title || ''}").`)
85
+ if (l && l.landed) out.push(`Your held work landed on ${l.landed.line || 'main'}${l.landed.patch != null ? ` as patch ${l.landed.patch}` : ''} at ${new Date(l.landed.at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}, with no step of yours.`)
86
+ if (l && l.waiting) out.push(`Your held work is waiting to merge: ${l.waiting}`)
87
+ if (l && l.testing) out.push('Your held work is being tested (the fast tests, in a copy of this folder) before it lands.')
88
+ if (l && l.held) out.push(l.held.missing ? `Your held work did not land: ${l.held.missing}.` : `Your held work did not land: the fast tests failed${(l.held.failing || []).length ? ` (${listed(l.held.failing)})` : ''}. It lands after your next change once they pass.`)
80
89
  return out
81
90
  }
82
91
 
@@ -47,6 +47,60 @@ export class VoiceCall {
47
47
  return this.spoken
48
48
  }
49
49
 
50
+ /**
51
+ * An agent's line as it renders (a fetch body of s16le PCM, mono, `rate` Hz), after any before it:
52
+ * each piece is scheduled straight after the last, so the line starts with its first sentence.
53
+ * The microphone is held the same way as in play().
54
+ */
55
+ playStream (name, body, rate = 24000) {
56
+ this.spoken = this.spoken.then(() => this.playStreamNow(name, body, rate)).catch((err) => console.warn('agent voice', err.message))
57
+ return this.spoken
58
+ }
59
+
60
+ async playStreamNow (name, body, rate) {
61
+ if (!this.in || !this.ctx) { body.cancel?.().catch(() => {}); return }
62
+ const reader = body.getReader()
63
+ const sources = []
64
+ let carry = null
65
+ let at = 0
66
+ let stopped = false
67
+ let wait = null
68
+ this.segmenter?.end()
69
+ this.agentTalking = name
70
+ this.onChange()
71
+ this.stopAgent = () => { stopped = true; for (const s of sources) { try { s.stop() } catch {} } reader.cancel().catch(() => {}); if (wait) wait() }
72
+ try {
73
+ while (!stopped) {
74
+ const { value, done } = await reader.read()
75
+ if (done || stopped) break
76
+ const bytes = carry ? concatBytes(carry, value) : value
77
+ const even = bytes.length - (bytes.length % 2)
78
+ carry = even < bytes.length ? bytes.slice(even) : null
79
+ if (!even || !this.in) continue
80
+ const view = new DataView(bytes.buffer, bytes.byteOffset, even)
81
+ const buf = this.ctx.createBuffer(1, even / 2, rate)
82
+ const ch = buf.getChannelData(0)
83
+ for (let i = 0; i < ch.length; i++) ch[i] = view.getInt16(i * 2, true) / 32768
84
+ const src = this.ctx.createBufferSource()
85
+ src.buffer = buf
86
+ src.connect(this.ctx.destination)
87
+ // A little lead on the first piece, so a slow second one doesn't leave a gap.
88
+ at = Math.max(at, this.ctx.currentTime + (sources.length ? 0.02 : 0.15))
89
+ src.start(at)
90
+ at += buf.duration
91
+ sources.push(src)
92
+ }
93
+ const left = at - (this.ctx ? this.ctx.currentTime : 0)
94
+ if (left > 0 && !stopped) await new Promise((resolve) => { wait = resolve; setTimeout(resolve, left * 1000) })
95
+ // The room's echo dies down before the microphone counts again.
96
+ await new Promise((resolve) => setTimeout(resolve, 300))
97
+ } finally {
98
+ this.stopAgent = null
99
+ this.agentTalking = null
100
+ this.onChange()
101
+ }
102
+ }
103
+
50
104
  async playNow (name, wav) {
51
105
  if (!this.in || !this.ctx) return
52
106
  const bytes = Uint8Array.from(atob(wav), (c) => c.charCodeAt(0))
@@ -338,3 +392,11 @@ function gathered (pc) {
338
392
  pc.addEventListener('icegatheringstatechange', check)
339
393
  })
340
394
  }
395
+
396
+ /** Two byte arrays as one. */
397
+ function concatBytes (a, b) {
398
+ const out = new Uint8Array(a.length + b.length)
399
+ out.set(a, 0)
400
+ out.set(b, a.length)
401
+ return out
402
+ }
package/src/ui/voice.js CHANGED
@@ -248,11 +248,17 @@ function speakAgents (id, view) {
248
248
  heard.ids.add(l.id)
249
249
  if (l.ts < heard.since - 2000) continue
250
250
  const call = live.call
251
- api('GET', `/api/sessions/${id}/voice/speech?line=${encodeURIComponent(l.id)}`).then((r) => {
252
- if (live && live.call === call && r && r.audio) call.play(l.by, r.audio)
253
- }, (err) => {
251
+ // Its speech plays as it renders (Fluxions' socket, on the API).
252
+ fetch(`/api/sessions/${id}/voice/speech-stream?line=${encodeURIComponent(l.id)}`, { headers: { 'x-quilt-token': TOKEN || '' } }).then(async (res) => {
253
+ if (!res.ok) {
254
+ const data = await res.json().catch(() => ({}))
255
+ throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status })
256
+ }
257
+ if (live && live.call === call && res.body) call.playStream(l.by, res.body)
258
+ else res.body?.cancel().catch(() => {})
259
+ }).catch((err) => {
254
260
  // Once a call: voices not set up, or the month's share heard.
255
- if (!heard.told && (err.status === 503 || err.status === 429 || err.status === 404)) { heard.told = true; toast(err.status === 404 ? "Agents' voices aren't on Quilt's servers yet: their lines show in the call." : err.message) }
261
+ if (!heard.told && (err.status === 503 || err.status === 429 || err.status === 404 || err.status === 502)) { heard.told = true; toast(err.status === 404 ? "Agents' voices aren't on Quilt's servers yet: their lines show in the call." : err.message) }
256
262
  })
257
263
  }
258
264
  }
@@ -262,7 +268,7 @@ const face = (key, name, color, muted) => `<span class="call-face" data-face="${
262
268
  // An agent in the call: like a person, with the agent mark, muted unless it is speaking; its ring
263
269
  // lights while its line plays. One just named shows joining (a pulsing ring) until it comes.
264
270
  const agentFace = (a, color, now) => {
265
- if (a.state === 'joining') return `<span class="call-face agent joining" data-face="agent:${esc(a.name)}" title="${esc(a.name)}, an agent: joining (someone said its name)">${avatar(a.name, color)}<span class="call-ai" aria-hidden="true">${I.bot}</span></span>`
271
+ if (a.state === 'joining') return `<span class="call-face agent ${a.hears === 'no' ? 'unheard' : 'joining'}" data-face="agent:${esc(a.name)}" title="${esc(a.name)}, an agent: ${a.hears === 'no' ? "can't hear you (Quilt can't wake it)" : 'joining (someone said its name)'}">${avatar(a.name, color)}<span class="call-ai" aria-hidden="true">${I.bot}</span>${a.hears === 'no' ? `<span class="call-muted">${I.micOff}</span>` : ''}</span>`
266
272
  const muted = !(a.until > now)
267
273
  return `<span class="call-face agent" data-face="agent:${esc(a.name)}" title="${esc(a.name)}, an agent: ${muted ? 'in the call, muted' : 'speaking'}">${avatar(a.name, color)}<span class="call-ai" aria-hidden="true">${I.bot}</span>${muted ? `<span class="call-muted">${I.micOff}</span>` : ''}</span>`
268
274
  }
@@ -321,10 +327,17 @@ export function renderCall () {
321
327
  const agents = view.agents || []
322
328
  redrawWhenMuted(agents, now)
323
329
  const agentFaces = agents.map((a) => agentFace(a, colorOf(a.name), now)).join('')
324
- const key = JSON.stringify([id, here, joining, asking, options, owner, elsewhere, view.transcribe, others.map((p) => [p.id, p.name, p.color, p.muted, p.transcribing, p.sharing]), agents.map((a) => [a.name, a.until > now]), me.name, me.color, c && [c.muted, c.transcribing, c.sharing], selfClosed, showing, minutes(view.since || Date.now())])
330
+ const key = JSON.stringify([id, here, joining, asking, options, owner, elsewhere, view.transcribe, others.map((p) => [p.id, p.name, p.color, p.muted, p.transcribing, p.sharing]), agents.map((a) => [a.name, a.state, a.hears, a.until > now]), me.name, me.color, c && [c.muted, c.transcribing, c.sharing], selfClosed, showing, minutes(view.since || Date.now())])
325
331
  if (key === drawn && (pin.hidden || pin.childElementCount)) { paintLines(pin, lines); paintTalk(); return }
326
332
  drawn = key
327
333
  linesDrawn = null
334
+ // A named agent that can't hear its name, or will hear it only later: say so, so nobody waits on it.
335
+ const unheard = agents.filter((a) => a.state === 'joining' && a.hears === 'no').map((a) => a.name)
336
+ const later = agents.filter((a) => a.state === 'joining' && a.hears === 'later').map((a) => a.name)
337
+ const agentNote = [
338
+ unheard.length ? `<p class="cp-note cp-agents">${esc(names(unheard))} can't hear you: Quilt can't wake ${unheard.length === 1 ? 'it' : 'them'} until ${unheard.length === 1 ? 'it picks' : 'they pick'} a way with quilt_wake.</p>` : '',
339
+ later.length ? `<p class="cp-note cp-agents">${esc(names(later))} ${later.length === 1 ? 'checks' : 'check'} in now and then, so ${later.length === 1 ? 'its' : 'their'} answer may take a while.</p>` : ''
340
+ ].join('')
328
341
  if (pin.hidden) { pin.innerHTML = ''; return }
329
342
  const dur = view.since ? minutes(view.since) : ''
330
343
  if (joining) {
@@ -353,6 +366,7 @@ export function renderCall () {
353
366
  <button type="button" class="call-ic" data-call-mute aria-pressed="${c.muted}" title="${c.muted ? 'Unmute' : 'Mute'}" aria-label="${c.muted ? 'Unmute' : 'Mute'}">${c.muted ? I.micOff : I.mic}</button>
354
367
  <button type="button" class="call-ic bad" data-call-leave title="Leave the call" aria-label="Leave the call">${I.hangUp}</button></div>
355
368
  <div class="cp-row"><span class="call-faces">${face('me', me.name, me.color, c.muted)}${others.map((p) => face(p.id, p.name, p.color, p.muted)).join('')}${agentFaces}</span>${tag}</div>
369
+ ${agentNote}
356
370
  ${options ? `<div class="cp-opts">${myChoice}${ownerChoice}</div>` : ''}
357
371
  ${c.sharing ? `<div class="cp-share">${I.screenShare}<span class="cp-says">Sharing your screen</span>${selfClosed ? '<button type="button" class="btn sm ghost" data-self-share="open" title="Show what you share, in the corner">Show</button>' : ''}<button type="button" class="btn sm" data-call-share>Stop sharing</button></div>` : ''}
358
372
  ${others.filter((p) => p.sharing).map((p) => `<div class="cp-share">${I.screenShare}<span class="cp-says">${esc(p.name)} is sharing a screen</span>${p.id === showing ? '<span class="call-sub">in the middle</span>' : `<button type="button" class="btn sm" data-screen-show="${p.id}">Show</button>`}</div>`).join('')}