heyquilt 0.3.174 → 0.3.176
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/RELEASES.md +30 -0
- package/bin/quilt.js +1 -75
- package/desktop/main.js +22 -9
- package/package.json +2 -3
- package/src/ai-vm.js +1 -1
- package/src/api/memory-store.js +1 -5
- package/src/api/server.js +4 -45
- package/src/api/supabase-store.js +0 -10
- package/src/autowork.js +7 -142
- package/src/base-pick.js +125 -12
- package/src/branch-view.js +1 -1
- package/src/connection.js +12 -37
- package/src/control.js +16 -93
- package/src/fsutil.js +1 -1
- package/src/git-aside.js +70 -0
- package/src/github-commit.js +1 -2
- package/src/gitstate.js +326 -0
- package/src/held.js +12 -53
- package/src/history.js +1 -25
- package/src/live-merge.js +42 -161
- package/src/mcp.js +6 -90
- package/src/merge3.js +21 -5
- package/src/pathrules.js +1 -1
- package/src/protocol.js +6 -11
- package/src/read-bases.js +3 -5
- package/src/relay-live-write.js +37 -44
- package/src/relay-mcp.js +30 -164
- package/src/relay-prune.js +3 -6
- package/src/relay-turn-sync.js +7 -11
- package/src/runner.js +2 -4
- package/src/server.js +61 -1717
- package/src/session.js +895 -844
- package/src/setup.js +11 -3
- package/src/status.js +2 -5
- package/src/swap-in.js +56 -13
- package/src/turn-sync-plan.js +2 -2
- package/src/turn-sync.js +1 -1
- package/src/ui/agent-guide.js +3 -1
- package/src/ui/app.css +4 -96
- package/src/ui/app.js +1 -1
- package/src/ui/chat.js +2 -6
- package/src/ui/cloud-ai-model.js +0 -13
- package/src/ui/cloud-ai.js +2 -10
- package/src/ui/connections.js +2 -1
- package/src/ui/fileview.js +7 -20
- package/src/ui/git-rule.js +2 -13
- package/src/ui/home.js +2 -8
- package/src/ui/session-words.js +27 -0
- package/src/ui/session.js +34 -407
- package/src/ui-server.js +7 -56
- package/src/api/routes/seam-connect.js +0 -103
- package/src/api/routes/session-migrate.js +0 -39
- package/src/force-date.js +0 -27
- package/src/quilt-default.js +0 -84
- package/src/quilt-history.js +0 -106
- package/src/quilt-remote.js +0 -78
- package/src/seam-access.js +0 -97
- package/src/seam-url.js +0 -15
- package/src/session-follow.js +0 -583
- package/src/session-layout3.js +0 -466
- package/src/session-migrate.js +0 -123
- package/src/session-quilt.js +0 -126
- package/src/session-seam.js +0 -312
- package/src/source-live/bring-in.js +0 -391
- package/src/source-live/land.js +0 -410
- package/src/source-live/live-block.js +0 -1166
- package/src/source-live/live-square.js +0 -116
- package/src/ui/force-words.js +0 -19
- package/src/ui/quiltview.js +0 -213
- package/src/ui/seam-model.js +0 -309
package/src/server.js
CHANGED
|
@@ -14,7 +14,6 @@
|
|
|
14
14
|
// editors change files, viewers only watch and chat, and agents can be
|
|
15
15
|
// limited to some folders. The relay enforces it by undoing file changes a
|
|
16
16
|
// member isn't allowed to make, before anyone else sees them.
|
|
17
|
-
import { quiltOf } from './session-seam.js'
|
|
18
17
|
import http from 'node:http'
|
|
19
18
|
import { makeChatLink, extendChatLink, pruneChatLinks, handleChatLink, fetchPublicFile } from './chat-links.js'
|
|
20
19
|
import fs from 'node:fs'
|
|
@@ -36,23 +35,8 @@ import {
|
|
|
36
35
|
ROOM_DOC, syncHeader,
|
|
37
36
|
syncStep1Message, updateMessage, awarenessMessage, bytesMessage, jsonMessage
|
|
38
37
|
} from './protocol.js'
|
|
39
|
-
import {
|
|
40
|
-
import { conflictsAhead, commitAhead, staleAhead, olderCopiesAhead, unionMarked, standHead, moveLive, lateEdits, sideReader, HOLDER_WAIT_MS } from './source-live/bring-in.js'
|
|
41
|
-
import { blobId } from '@heyquilt/seam/lib/quilts/records.js'
|
|
42
|
-
import { planSessionQuilt, quiltPlanRefusal, describeQuiltPlan, fileHash } from './session-quilt.js'
|
|
43
|
-
import { makeQuiltWithoutHistory, termsFor } from './session-migrate.js'
|
|
44
|
-
import { forceAtMs, forcedAction } from './force-date.js'
|
|
45
|
-
import { githubRepoOf, installationFor, remoteStage, mainGuarded, rulesetSteps, installSteps, stepsError } from './quilt-remote.js'
|
|
46
|
-
import { syncStoppedWords } from './ui/force-words.js'
|
|
47
|
-
import { historyQuilt, linkedHistory } from './quilt-history.js'
|
|
48
|
-
import { MAX_DIFF_CHARS } from './history.js'
|
|
49
|
-
import { LAYOUT_QUILT, copiedHead, treeIds, treeModes, branchFiles, binariesToUpload, bringsNew, forwardIntoLive, applyChecked, foldBack, writeFold, overlayFor, checkOverlay, copyIntoLive, carryLive, takeGitMeta, restoreGitMeta, squareBase, shareWithPeople, boxOntoHead, writeIntoLive } from './session-layout3.js'
|
|
50
|
-
import { readMerges } from './merges.js'
|
|
51
|
-
import { readTasks, updateTask, addTask } from './tasks.js'
|
|
38
|
+
import { readTasks, addTask } from './tasks.js'
|
|
52
39
|
import { HELD_MAP, readHeld, noteHeld, heldNoticesDue, heldTasksDue, nextHeldDue, heldNoticeText, heldTaskTitle, versionsOf, resolverOf, overBudget, HAND_MS, VERSIONS_MAP } from './held.js'
|
|
53
|
-
import { addComment } from './task-comments.js'
|
|
54
|
-
// Seam over HTTP through its client package (@heyquilt/seam), never Seam's code.
|
|
55
|
-
import { quiltClient } from '@heyquilt/seam/lib/quilts/client.js'
|
|
56
40
|
import { BranchStore, DEFAULT_KEY, BRANCH_IDLE_MS, DETACHED_TTL_MS, MAX_BRANCHES, validBranchKey, covers, splitLegacyDoc } from './branchdocs.js'
|
|
57
41
|
import { parsePublicKey, verifyChallenge } from './identity.js'
|
|
58
42
|
import { verifyPass, PASS_TTL_MS } from './passes.js'
|
|
@@ -73,12 +57,10 @@ import { asksRelay, relayAnswer } from './relay-ask.js'
|
|
|
73
57
|
import { DIFF, isDiff, hasEntry } from './branch-view.js'
|
|
74
58
|
import { inactiveBranches, pruneNotice, ARCHIVE_KEEP_MS } from './relay-prune.js'
|
|
75
59
|
import { RELAY_NAME as RELAY_BY, isRelay } from './ui/chat.js'
|
|
76
|
-
import { leaseKeeper, LEASE_HEARTBEAT_MS } from './relay-lease.js'
|
|
77
60
|
import { RoomMeter, roomDiskBytes, MachineMeter, machineLoad } from './relay-metrics.js'
|
|
78
61
|
import { clusterConfig, clusterProblems, Cluster, NOT_ROOMS, roomOfPath, replaySource, canReplay, displaceRoom, packRoom, unpackRoom, placeStaged, removeLocalRoom, MOVING, ELSEWHERE } from './relay-cluster.js'
|
|
79
62
|
import { joiningRoom, sessionArg } from './mcp-room.js'
|
|
80
63
|
import { nowSummary } from './now-summary.js'
|
|
81
|
-
import { squareShort } from '@heyquilt/seam/lib/quilts/errors.js'
|
|
82
64
|
|
|
83
65
|
const ROOM_RE = /^[A-Za-z0-9_-]{1,64}$/
|
|
84
66
|
const MAX_NAME = 64
|
|
@@ -112,17 +94,12 @@ const CLOUD_AI_GONE_MS = 5 * 60 * 1000
|
|
|
112
94
|
const BRANCH_SEEN_SAVE_MS = 60 * 60 * 1000
|
|
113
95
|
// A message to the relay older than this when it reaches the relay gets no answer (answerRelay).
|
|
114
96
|
const RELAY_ASK_MS = 10 * 60 * 1000
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
/** A file's path as Seam names it (forward slashes, no leading ./ or /), or '' when it is not one. */
|
|
122
|
-
const quiltFilePath = (p) => {
|
|
123
|
-
const s = typeof p === 'string' ? p.replace(/\\/g, '/').replace(/^(\.\/|\/)+/, '') : ''
|
|
124
|
-
return s && s.length <= 1000 && !s.split('/').includes('..') && !CONTROL_CHARS.test(s) ? s : ''
|
|
125
|
-
}
|
|
97
|
+
// What a room saved by an earlier version may still carry (Room.dropOldLayout): fields for files kept
|
|
98
|
+
// outside its branch documents, the documents that held them (named by an id, never a branch's name: an
|
|
99
|
+
// agent's task branch is quilt/<agent>/<task>), and git's bookkeeping, set aside while they were in use.
|
|
100
|
+
const OLD_META = ['quilt_id', 'quilt', 'quiltShadow', 'quiltImport', 'quiltMove', 'quiltLeftOver', 'syncStopped']
|
|
101
|
+
const OLD_DOC_KEY = /^quilt\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
102
|
+
const GIT_META = ['sync', 'upstreams', 'remoteBranches', 'viewBranches', 'ciPending', 'pullTold', 'githubToken', 'githubSync', 'largeToRelay', 'recreateDeleted']
|
|
126
103
|
const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
127
104
|
const LOGO = path.join(ROOT, 'assets', 'logo.svg')
|
|
128
105
|
const hash = (s) => crypto.createHash('sha256').update(String(s)).digest()
|
|
@@ -154,10 +131,6 @@ export function relayConfig (opts = {}) {
|
|
|
154
131
|
branchIdleMs: num(opts.branchIdleMs, BRANCH_IDLE_MS),
|
|
155
132
|
// A held conflict whose resolver's AI did nothing here this long goes to another AI (held.js HAND_MS); tests shorten it.
|
|
156
133
|
heldHandMs: num(opts.heldHandMs, undefined),
|
|
157
|
-
// The relay's leases (relay-lease.js: a layout move holds one per room); tests shorten them.
|
|
158
|
-
leaseTtlMs: num(opts.leaseTtlMs, undefined),
|
|
159
|
-
leaseMarginMs: num(opts.leaseMarginMs, undefined),
|
|
160
|
-
leaseHeartbeatMs: num(opts.leaseHeartbeatMs, undefined),
|
|
161
134
|
trustProxy: opts.trustProxy ?? /^(1|true|yes)$/i.test(env.QUILT_TRUST_PROXY || ''),
|
|
162
135
|
// Large files: Supabase Storage when both are set, otherwise the relay's own disk.
|
|
163
136
|
storageUrl: opts.storageUrl ?? env.QUILT_STORAGE_URL ?? '',
|
|
@@ -178,12 +151,6 @@ function loadedFor (stack) {
|
|
|
178
151
|
return frames.slice(0, 2).map((l) => l.replace(/\(?file:\/\/\/?[^)]*\/src\//, '(').replace(/:\d+\)?$/, ')')).join(' < ') || 'unknown'
|
|
179
152
|
}
|
|
180
153
|
|
|
181
|
-
// Seam (16, "How a session becomes a quilt"): a room's layout migration runs under a lease of its
|
|
182
|
-
// own, so two relay machines never move one room at once. Its holder is one attempt (`qm-<id>`),
|
|
183
|
-
// listed here while it runs.
|
|
184
|
-
const MIGRATION_LEASE = 'qm-'
|
|
185
|
-
const migrating = new Set()
|
|
186
|
-
|
|
187
154
|
class Room {
|
|
188
155
|
constructor (name, dataDir, cfg, log) {
|
|
189
156
|
this.name = name
|
|
@@ -235,9 +202,9 @@ class Room {
|
|
|
235
202
|
onSave: (e) => this.noteBranchSaved(e),
|
|
236
203
|
onDiskError: (err) => this.diskError(err)
|
|
237
204
|
})
|
|
205
|
+
this.dropOldLayout()
|
|
238
206
|
// A room saved before branch documents: its one document becomes the default branch's.
|
|
239
207
|
this.migrateLegacy()
|
|
240
|
-
this.recoverQuiltMove()
|
|
241
208
|
this.pruneBranches(Date.now(), { quiet: true }) // at load; the sweep says it in chat
|
|
242
209
|
this.awareness = new awarenessProtocol.Awareness(this.doc)
|
|
243
210
|
this.awareness.setLocalState(null)
|
|
@@ -327,7 +294,7 @@ class Room {
|
|
|
327
294
|
if (this.cloudAiWaker) this.cloudAiWaker.personActive(this, origin).catch(() => {}) // their cloud AI wakes while they work
|
|
328
295
|
}
|
|
329
296
|
const msg = updateMessage(update)
|
|
330
|
-
for (const ws of this.conns.keys()) if (ws !== origin
|
|
297
|
+
for (const ws of this.conns.keys()) if (ws !== origin) send(ws, msg)
|
|
331
298
|
this.bytes += update.length
|
|
332
299
|
if (!this.full && this.bytes > cfg.maxRoomBytes) {
|
|
333
300
|
this.full = true
|
|
@@ -346,7 +313,7 @@ class Room {
|
|
|
346
313
|
for (const id of added.concat(updated)) { const st = this.awareness.getStates().get(id); if (st && st.agent && st.agent.status === 'working') this.noteAi(this.names.get(origin)) }
|
|
347
314
|
}
|
|
348
315
|
const msg = awarenessMessage(this.awareness, changed)
|
|
349
|
-
for (const ws of this.conns.keys())
|
|
316
|
+
for (const ws of this.conns.keys()) send(ws, msg)
|
|
350
317
|
})
|
|
351
318
|
}
|
|
352
319
|
|
|
@@ -947,11 +914,7 @@ class Room {
|
|
|
947
914
|
onBranch (ws, rel) {
|
|
948
915
|
const e = ws.branch ? this.store.get(ws.branch) : null
|
|
949
916
|
// A diff branch leaves its unchanged files to git: a path it hasn't deleted counts as on it.
|
|
950
|
-
|
|
951
|
-
// At layout 3 the branch's work is in its square: a file new there (live-block.js) is on it too.
|
|
952
|
-
const lk = this.meta.layout === LAYOUT_QUILT && ws.branch && this.meta.quilt && (this.meta.quilt.live || {})[ws.branch]
|
|
953
|
-
const sq = isLiveKey(lk) ? this.store.load(lk) : null
|
|
954
|
-
return !!sq && (sq.files.has(rel) || sq.blobs.has(rel))
|
|
917
|
+
return !!e && (hasEntry(e, rel) || (isDiff(e) && !e.gone.has(rel)))
|
|
955
918
|
}
|
|
956
919
|
|
|
957
920
|
/** A branch document was saved: records it was used just now (see noteBranchSeen), and the
|
|
@@ -965,6 +928,29 @@ class Room {
|
|
|
965
928
|
this.saveMeta()
|
|
966
929
|
}
|
|
967
930
|
|
|
931
|
+
/**
|
|
932
|
+
* A room saved by an earlier version may carry what this relay no longer keeps: its files held
|
|
933
|
+
* outside its branch documents (layout 3) with git's bookkeeping set aside meanwhile, and the fields
|
|
934
|
+
* and documents that went with that. Once, at load: the room is back on its branch documents as
|
|
935
|
+
* they were kept (layout 2) with git's bookkeeping in place again, the fields are dropped, and the
|
|
936
|
+
* documents leave for the archive (kept ARCHIVE_KEEP_MS). A room with none of it is untouched.
|
|
937
|
+
*/
|
|
938
|
+
dropOldLayout () {
|
|
939
|
+
const m = this.meta
|
|
940
|
+
const docs = Object.keys(m.branches).filter((k) => OLD_DOC_KEY.test(k))
|
|
941
|
+
const fields = OLD_META.filter((k) => k in m)
|
|
942
|
+
if (m.layout !== 3 && !fields.length && !docs.length) return
|
|
943
|
+
const back = m.layout === 3
|
|
944
|
+
if (back) {
|
|
945
|
+
for (const [k, v] of Object.entries((m.quilt && m.quilt.kept) || {})) if (GIT_META.includes(k) || k.startsWith('agentCommits')) m[k] = v
|
|
946
|
+
m.layout = 2
|
|
947
|
+
}
|
|
948
|
+
for (const k of fields) delete m[k]
|
|
949
|
+
for (const k of docs) this.removeBranch(k, { save: false, archive: true })
|
|
950
|
+
this.log(`[${this.name}] saved by an earlier version: ${back ? 'back on its branch documents (layout 2), git bookkeeping restored; ' : ''}dropped ${[...fields, ...(docs.length ? [`${docs.length} document(s) that were not branches (archived)`] : [])].join(', ') || 'nothing else'}`)
|
|
951
|
+
this.saveMeta()
|
|
952
|
+
}
|
|
953
|
+
|
|
968
954
|
/**
|
|
969
955
|
* A room saved before branch documents kept everything in one document. That document
|
|
970
956
|
* becomes the default branch's as it is (every app's saved copy still matches it), and its
|
|
@@ -973,7 +959,7 @@ class Room {
|
|
|
973
959
|
* are never only in memory, and a crash part-way is finished at the next load.
|
|
974
960
|
*/
|
|
975
961
|
migrateLegacy () {
|
|
976
|
-
if (this.meta.layout === 2
|
|
962
|
+
if (this.meta.layout === 2) return
|
|
977
963
|
const legacy = this.doc
|
|
978
964
|
if (this.docFile && (legacy.getMap('files').size || legacy.getMap('blobs').size)) {
|
|
979
965
|
const stored = [...legacy.getMap('blobs').values()].filter((x) => x && x.stored && x.stored.id).map((x) => x.stored.id).sort()
|
|
@@ -1175,7 +1161,6 @@ class Room {
|
|
|
1175
1161
|
|
|
1176
1162
|
/** A room whose move to branch documents failed on the relay's disk (migrateLegacy) stays read-only: no branch document is used. */
|
|
1177
1163
|
assertMigrated () {
|
|
1178
|
-
if (this.meta.layout === LAYOUT_QUILT) throw new Error(`This session is the quilt ${(this.meta.quilt && this.meta.quilt.slug) || this.meta.quilt_id} now: its files are in its squares, not in branches. Use Seam (squares, commits, merges).`)
|
|
1179
1164
|
if (this.meta.layout !== 2) throw new Error("The relay couldn't finish updating how it stores this session (its disk refused), so the session is read-only until the relay is fixed.")
|
|
1180
1165
|
}
|
|
1181
1166
|
|
|
@@ -1193,57 +1178,10 @@ class Room {
|
|
|
1193
1178
|
broadcastAccess () { for (const [cws, a] of this.access) send(cws, jsonMessage(MSG_ACCESS, this.accessMessage(a))) }
|
|
1194
1179
|
|
|
1195
1180
|
/**
|
|
1196
|
-
* What every branch-list message carries: the list and
|
|
1197
|
-
*
|
|
1198
|
-
* app and agents can use Seam (Seam's plans/quilt-source-control/16); at layout 3 also `atTip`,
|
|
1199
|
-
* the branches whose squares the move started at main's tip for want of their own commit.
|
|
1200
|
-
*/
|
|
1201
|
-
branchesFields () {
|
|
1202
|
-
const q = this.meta.quilt_id && process.env.QUILT_SOURCE_URL ? { id: this.meta.quilt_id, slug: (this.meta.quilt || {}).slug || '', squares: (this.meta.quilt || {}).squares || {}, ...((this.meta.quilt || {}).at ? { at: this.meta.quilt.at } : {}), ...((this.meta.quilt || {}).history ? { history: true } : {}), ...(this.meta.layout === LAYOUT_QUILT ? { layout: LAYOUT_QUILT, live: this.meta.quilt.live || {}, ...(this.meta.quilt.adoption ? { adoption: this.meta.quilt.adoption } : {}), read: this.readTokenState(), ...((this.meta.quilt.basedAtTip || []).length ? { atTip: this.meta.quilt.basedAtTip.map((b) => b.from) } : {}) } : {}) } : null
|
|
1203
|
-
// 16 step 1: the quilt an import of the session's git remote fills while git is still the
|
|
1204
|
-
// authority. Its own field, so nothing that treats the session as a quilt (session-seam.js) moves.
|
|
1205
|
-
const sh = !q && this.meta.quiltShadow && process.env.QUILT_SOURCE_URL ? { id: this.meta.quiltShadow.id, slug: this.meta.quiltShadow.slug || '' } : null
|
|
1206
|
-
// The forced date (16 flag 9, force-date.js): when it is, live sync stopped, or the owner's app is to make the session a quilt now.
|
|
1207
|
-
const at = process.env.QUILT_SOURCE_URL ? forceAtMs() : null
|
|
1208
|
-
const act = this.meta.layout === LAYOUT_QUILT ? null : forcedAction({ at, layout: this.meta.layout, remote: this.hasGitRemote(), stopped: !!this.meta.syncStopped })
|
|
1209
|
-
const force = this.meta.syncStopped ? { stopped: { at: this.meta.syncStopped.at, why: syncStoppedWords(this.meta.syncStopped.at) } } : at != null && this.meta.layout !== LAYOUT_QUILT ? { at: new Date(at).toISOString(), remote: this.hasGitRemote(), ...(act === 'migrate' ? { migrate: true } : {}) } : null
|
|
1210
|
-
// "Make this a quilt" on a session with a git remote, while Seam imports it (quiltMakeWithRemote).
|
|
1211
|
-
const imp = !q && !sh && this.meta.quiltImport && process.env.QUILT_SOURCE_URL ? { slug: this.meta.quiltImport.slug || '', repo: this.meta.quiltImport.repo || '' } : null
|
|
1212
|
-
// writes: this relay takes a folder's live writes (relay-live-write.js), so apps send them instead of editing texts.
|
|
1213
|
-
return { branches: this.branchList(), writes: 1, ...(q ? { quilt: q } : {}), ...(sh ? { shadow: sh } : {}), ...(imp ? { importing: imp } : {}), ...(this.movingNow ? { moving: this.movingNow } : {}), ...(force ? { force } : {}) }
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
/** Whether the session has a git remote (16: a room with an upstream): it becomes a quilt only with its history. */
|
|
1217
|
-
hasGitRemote () { return Object.keys(this.meta.upstreams || {}).length > 0 }
|
|
1218
|
-
|
|
1219
|
-
/**
|
|
1220
|
-
* The forced date (16 flag 9): from QUILT_SOURCE_FORCE_AT on, a session with a git remote that is not
|
|
1221
|
-
* a quilt in its squares has its live file sync stopped, for good (meta.syncStopped): its branch
|
|
1222
|
-
* documents stay as they were at the date, the relay neither takes a member's file edits nor brings
|
|
1223
|
-
* GitHub in or pushes, and every member hears it in plain words. Chat, tasks, the feed and the audit
|
|
1224
|
-
* trail carry on. Nothing in git is touched. A session with no git remote is left to its owner's
|
|
1225
|
-
* next open (branchesFields `force.migrate`): only the owner's sign-in can make it a quilt.
|
|
1181
|
+
* What every branch-list message carries: the list, and `writes`: this relay takes a folder's live
|
|
1182
|
+
* writes (relay-live-write.js), so apps send them instead of editing texts.
|
|
1226
1183
|
*/
|
|
1227
|
-
|
|
1228
|
-
if (this.meta.syncStopped || this.meta.layout === LAYOUT_QUILT || this.quiltMoving || !this.exists || this.ended || this.destroyed) return false
|
|
1229
|
-
if (!process.env.QUILT_SOURCE_URL) return false
|
|
1230
|
-
if (forcedAction({ at: forceAtMs(), now, layout: this.meta.layout, remote: this.hasGitRemote() }) !== 'stop') return false
|
|
1231
|
-
const at = new Date(forceAtMs()).toISOString()
|
|
1232
|
-
this.meta.syncStopped = { at, since: new Date(now).toISOString() }
|
|
1233
|
-
this.saveMeta()
|
|
1234
|
-
this.log(`[${this.name}] the forced date (${at}) passed with a git remote and no cut-over: live file sync stopped`)
|
|
1235
|
-
try { this.postChat({ by: 'Quilt', text: syncStoppedWords(at), kind: 'note' }) } catch {}
|
|
1236
|
-
this.broadcastBranches()
|
|
1237
|
-
return true
|
|
1238
|
-
}
|
|
1239
|
-
|
|
1240
|
-
/** A member's write to a branch document after live sync stopped: not kept, and they hear why (at most once a minute a connection). */
|
|
1241
|
-
refusedSyncStopped (ws) {
|
|
1242
|
-
const now = Date.now()
|
|
1243
|
-
if (ws.syncStoppedToldAt && now - ws.syncStoppedToldAt < READ_ONLY_TELL_MS) return
|
|
1244
|
-
ws.syncStoppedToldAt = now
|
|
1245
|
-
send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields() }))
|
|
1246
|
-
}
|
|
1184
|
+
branchesFields () { return { branches: this.branchList(), writes: 1 } }
|
|
1247
1185
|
|
|
1248
1186
|
broadcastBranches () {
|
|
1249
1187
|
const msg = jsonMessage(MSG_BRANCHES, { ...this.branchesFields() })
|
|
@@ -1257,26 +1195,17 @@ class Room {
|
|
|
1257
1195
|
* app asks before it clears its folder for a switch).
|
|
1258
1196
|
*/
|
|
1259
1197
|
branchRequest (ws, req) {
|
|
1260
|
-
// Seam, behind QUILT_SOURCE_URL (Seam's plans/quilt-source-control/16): what making this session a
|
|
1261
|
-
// quilt would do, read only. The owner's (or, in a session without one, any editor's).
|
|
1262
|
-
if (req.op === 'quilt-plan') {
|
|
1263
|
-
if (!process.env.QUILT_SOURCE_URL) throw new Error('Seam is not on for this relay, so a session cannot become a quilt here yet')
|
|
1264
|
-
return { ok: true, plan: this.quiltPlan(this.access.get(ws), req.tip) }
|
|
1265
|
-
}
|
|
1266
1198
|
const key = String(req.branch ?? '')
|
|
1267
1199
|
if (!validBranchKey(key)) throw new Error(`"${key.slice(0, 60)}" isn't a branch name`)
|
|
1268
1200
|
if (req.op === 'join') {
|
|
1269
|
-
this.
|
|
1270
|
-
//
|
|
1271
|
-
//
|
|
1272
|
-
|
|
1273
|
-
const square = this.meta.layout === LAYOUT_QUILT && isLiveKey(key)
|
|
1274
|
-
const kept = this.meta.layout === LAYOUT_QUILT && !square && (ws.features || []).includes('quilt-folders') && !!this.meta.branches[this.resolveKey(key)]
|
|
1275
|
-
if (!square && !kept) this.assertMigrated()
|
|
1201
|
+
this.assertMigrated()
|
|
1202
|
+
// A document an earlier version kept beside the branches (dropOldLayout) is never a branch: an app
|
|
1203
|
+
// from then that still asks for one is refused, rather than starting a branch of that name.
|
|
1204
|
+
if (OLD_DOC_KEY.test(key)) throw new Error("That document isn't in this session any more: update Quilt")
|
|
1276
1205
|
// An app from before branch documents names the branch the old document was; else the first real branch takes ∅.
|
|
1277
1206
|
let adopted = false
|
|
1278
|
-
if (
|
|
1279
|
-
|
|
1207
|
+
if (validBranchKey(String(req.adopt || ''))) adopted = this.adoptDefault(String(req.adopt))
|
|
1208
|
+
adopted = this.adoptDefault(key) || adopted
|
|
1280
1209
|
const k = this.resolveKey(key)
|
|
1281
1210
|
const created = !this.meta.branches[k]
|
|
1282
1211
|
if (created) {
|
|
@@ -1323,16 +1252,6 @@ class Room {
|
|
|
1323
1252
|
if (!covers(Y.encodeStateVector(e.doc), want)) throw new Error(`not all of your changes on ${key} have reached the relay yet`)
|
|
1324
1253
|
return { ok: true, branch: k }
|
|
1325
1254
|
}
|
|
1326
|
-
// What the relay holds of the app's branch: its state vector, and its deletions (an update with
|
|
1327
|
-
// nothing past the vector). At layout 3 the app's own edits past them are ones the read-only
|
|
1328
|
-
// document refused, and its folder keeps them (Session.unsentPaths).
|
|
1329
|
-
if (req.op === 'state') {
|
|
1330
|
-
const k = this.resolveKey(key)
|
|
1331
|
-
const e = k === ws.branch ? this.store.get(k) : null
|
|
1332
|
-
if (!e) throw new Error(`you are not on ${key}`)
|
|
1333
|
-
const sv = Y.encodeStateVector(e.doc)
|
|
1334
|
-
return { ok: true, branch: k, sv: Buffer.from(sv).toString('base64'), deleted: Buffer.from(Y.encodeStateAsUpdate(e.doc, sv)).toString('base64') }
|
|
1335
|
-
}
|
|
1336
1255
|
if (req.op === 'remove') {
|
|
1337
1256
|
const a = this.access.get(ws)
|
|
1338
1257
|
if (!a || (this.controlled && !a.owner)) throw new Error('only the session owner can remove a branch')
|
|
@@ -1346,1450 +1265,11 @@ class Room {
|
|
|
1346
1265
|
}
|
|
1347
1266
|
// A folder's live write (relay-live-write.js): merged against the version it started from and applied here, at once.
|
|
1348
1267
|
if (req.op === 'live-write') return liveWrite(this, ws, req)
|
|
1349
|
-
// Quilt source control (src/source-live/live-square.js), behind QUILT_SOURCE, and always once the room is at layout 3: a square's live document's own ops.
|
|
1350
|
-
if ((req.op === 'seal' || req.op === 'start') && isLiveKey(key) && (process.env.QUILT_SOURCE || this.meta.layout === LAYOUT_QUILT)) {
|
|
1351
|
-
const k = this.resolveKey(key)
|
|
1352
|
-
const e = k === ws.branch ? this.store.get(k) : null
|
|
1353
|
-
if (!e) throw new Error(`you are not on ${key}`)
|
|
1354
|
-
return { branch: k, ...liveRequest(e.doc, req, this.names.get(ws) || '') }
|
|
1355
|
-
}
|
|
1356
1268
|
throw new Error('unknown branch request')
|
|
1357
1269
|
}
|
|
1358
1270
|
|
|
1359
|
-
/**
|
|
1360
|
-
* Tasks with a pull request, once the room is a quilt (16's table): one whose branch became a
|
|
1361
|
-
* square is kept in `meta.quilt.tasks` (task id -> square id); one whose branch did not loses
|
|
1362
|
-
* its `pr`, kept as a task comment. Returns the task id -> square id map.
|
|
1363
|
-
*/
|
|
1364
|
-
quiltTasks (squares) {
|
|
1365
|
-
const tasks = readTasks(this.tasks)
|
|
1366
|
-
const out = {}
|
|
1367
|
-
for (const t of tasks) {
|
|
1368
|
-
if (!t.pr) continue
|
|
1369
|
-
const sq = t.pr.branch && squares[t.pr.branch]
|
|
1370
|
-
if (sq) { out[t.id] = sq; continue }
|
|
1371
|
-
const which = `${t.pr.number ? ` #${t.pr.number}` : ''}${t.pr.url ? ` (${t.pr.url})` : ''}`
|
|
1372
|
-
updateTask(this.doc, this.tasks, { id: t.id, pr: null }, 'quilt-migrate')
|
|
1373
|
-
addComment(this.doc, this.taskComments, tasks, { taskId: t.id, by: 'Quilt', text: `This task's pull request${which} did not carry over when the session became a quilt: no square was made from its branch${t.pr.branch ? ` ${t.pr.branch}` : ''}.` }, 'quilt-migrate')
|
|
1374
|
-
}
|
|
1375
|
-
return out
|
|
1376
|
-
}
|
|
1377
|
-
|
|
1378
|
-
/**
|
|
1379
|
-
* Open commit requests have no replacement in a quilt (12): each becomes a comment on its task,
|
|
1380
|
-
* or a chat line when it has none, "Please get this into history: <paths>" with its square.
|
|
1381
|
-
*/
|
|
1382
|
-
quiltCommitRequests (squares) {
|
|
1383
|
-
const tasks = readTasks(this.tasks)
|
|
1384
|
-
for (const r of this.commitRequests.values()) {
|
|
1385
|
-
if (!r || r.state !== 'open') continue
|
|
1386
|
-
const sq = squares[r.branch || this.defaultKey]
|
|
1387
|
-
const text = `Please get this into history: ${(r.files || []).join(', ')}${sq ? ` (square ${squareShort(sq)})` : ''}. ${r.by || 'Someone'} asked for a commit ("${String(r.message || '').slice(0, 200)}") before the session became a quilt: commit it in Seam.`
|
|
1388
|
-
if (r.task && tasks.some((t) => t.id === r.task.id)) addComment(this.doc, this.taskComments, tasks, { taskId: r.task.id, by: 'Quilt', text }, 'quilt-migrate')
|
|
1389
|
-
else this.postChat({ by: 'Quilt', text, kind: 'note' })
|
|
1390
|
-
}
|
|
1391
|
-
}
|
|
1392
|
-
|
|
1393
|
-
/**
|
|
1394
|
-
* The owner's app asks to make the session a quilt (`op: 'quilt-migrate'`, `token`: their Seam
|
|
1395
|
-
* sign-in). Answered when it is done, on the branch channel like every branch request.
|
|
1396
|
-
*/
|
|
1397
|
-
quiltMigrateRequest (ws, req) {
|
|
1398
|
-
const answer = (fields) => send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields(), reply: { id: req.id, op: req.op, ...fields } }))
|
|
1399
|
-
const api = process.env.QUILT_SOURCE_URL
|
|
1400
|
-
if (!api) return answer({ ok: false, error: 'Seam is not on for this relay, so a session cannot become a quilt here yet' })
|
|
1401
|
-
if (!req.token || typeof req.token !== 'string') return answer({ ok: false, error: 'sign in to Seam first: making a session a quilt is done as its owner' })
|
|
1402
|
-
const seam = (this.seamClient || quiltClient)({ api, token: req.token })
|
|
1403
|
-
if (req.op === 'quilt-shadow') {
|
|
1404
|
-
return this.quiltShadowLink(this.access.get(ws), seam, req.quilt ?? null).then((r) => answer({ ok: true, ...r }), (err) => answer({ ok: false, error: err.message }))
|
|
1405
|
-
}
|
|
1406
|
-
if (req.op === 'quilt-unswitch') {
|
|
1407
|
-
return this.quiltUnswitch(this.access.get(ws), seam, { carried: req.carried || [] }).then((r) => answer({ ok: true, ...r }), (err) => answer({ ok: false, error: err.message, ...(err.open ? { open: err.open } : {}) }))
|
|
1408
|
-
}
|
|
1409
|
-
if (req.op === 'quilt-switch') {
|
|
1410
|
-
return this.quiltSwitch(this.access.get(ws), seam).then((r) => answer({ ok: true, ...r }), (err) => answer({ ok: false, error: err.message }))
|
|
1411
|
-
}
|
|
1412
|
-
if (req.op === 'quilt-make') {
|
|
1413
|
-
return this.quiltMake(this.access.get(ws), seam).then((r) => answer({ ok: true, quilt: r }), (err) => answer({ ok: false, error: err.message, ...(err.quilt_id ? { quilt_id: err.quilt_id } : {}), ...(err.steps ? { steps: err.steps } : {}) }))
|
|
1414
|
-
}
|
|
1415
|
-
if (req.op === 'quilt-next') {
|
|
1416
|
-
return this.quiltNext(this.access.get(ws), seam, req.branch).then((r) => answer({ ok: true, ...r }), (err) => answer({ ok: false, error: err.message }))
|
|
1417
|
-
}
|
|
1418
|
-
if (req.op === 'quilt-open') {
|
|
1419
|
-
return this.quiltOpen(this.access.get(ws), seam, req.branch ?? ws.branch).then((r) => answer({ ok: true, ...r }), (err) => answer({ ok: false, error: err.message }))
|
|
1420
|
-
}
|
|
1421
|
-
if (req.op === 'quilt-catch-up') {
|
|
1422
|
-
// An app that asks to bring main in follows a square whose base moves (0.3.133 on): its folder is no reason to wait (outdatedOn).
|
|
1423
|
-
if (!this.movesApps) this.movesApps = new Set()
|
|
1424
|
-
this.movesApps.add(appOf(ws, this.names.get(ws)))
|
|
1425
|
-
return this.quiltCatchUp(this.access.get(ws), seam, req.branch ?? ws.branch, { by: this.names.get(ws) || '' }).then((r) => answer({ ok: true, ...r }), (err) => answer({ ok: false, error: err.message }))
|
|
1426
|
-
}
|
|
1427
|
-
this.quiltMigrate(this.access.get(ws), seam).then(
|
|
1428
|
-
(r) => answer({ ok: true, quilt: r }),
|
|
1429
|
-
(err) => answer({ ok: false, error: err.message, ...(err.quilt_id ? { quilt_id: err.quilt_id } : {}) })
|
|
1430
|
-
)
|
|
1431
|
-
}
|
|
1432
|
-
|
|
1433
|
-
/**
|
|
1434
|
-
* 16 step 1 ("Shadow"), behind QUILT_SOURCE_URL: links the session to the quilt an import of its
|
|
1435
|
-
* git remote fills (`quilt`, its slug or id; null unlinks), as the owner with `seam` acting as
|
|
1436
|
-
* them. Nothing else changes: the session stays git-mode, agents keep their git path, and the
|
|
1437
|
-
* link only lets quilt_history (and the app) read the quilt's log. A read-only quilt token is
|
|
1438
|
-
* made for the room (`meta.quiltShadow.read`), so hosted agents read the log without anyone's
|
|
1439
|
-
* sign-in; making it needs admin on the quilt, which is how the owner proves the quilt is theirs.
|
|
1440
|
-
* The with-history migration (quiltMigrate) later turns this link into the session's quilt.
|
|
1441
|
-
*/
|
|
1442
|
-
async quiltShadowLink (a, seam, quilt) {
|
|
1443
|
-
const no = quiltPlanRefusal({ controlled: this.controlled, access: a })
|
|
1444
|
-
if (no) throw new Error(no.replace('see what making it a quilt would do', 'link it to a quilt'))
|
|
1445
|
-
if (this.meta.quilt_id) {
|
|
1446
|
-
const slug = (this.meta.quilt && this.meta.quilt.slug) || ''
|
|
1447
|
-
if (!quilt || (quilt !== this.meta.quilt_id && quilt !== slug && !String(quilt).endsWith(`/${slug}`))) throw new Error(`this session is already the quilt ${slug || this.meta.quilt_id}`)
|
|
1448
|
-
// Linking the session to its own quilt again makes the room's read token new when it is gone, ending or refused.
|
|
1449
|
-
const r = await this.freshReadToken(seam, this.meta.quilt_id, this.meta.quilt.read)
|
|
1450
|
-
if (r.renewed || this.meta.quilt.readRefusedAt) this.takeReadToken(r.read)
|
|
1451
|
-
return { shadow: { id: this.meta.quilt_id, slug }, read: { renewed: r.renewed, ...(r.read.expires_at ? { until: new Date(r.read.expires_at).toISOString() } : {}) } }
|
|
1452
|
-
}
|
|
1453
|
-
if (this.quiltMoving) throw new Error('this session is already being made a quilt')
|
|
1454
|
-
const was = this.meta.quiltShadow || null
|
|
1455
|
-
if (quilt === null || quilt === '') {
|
|
1456
|
-
if (!was) return { shadow: null }
|
|
1457
|
-
if (was.read && was.read.id && seam.revokeToken) await seam.revokeToken(was.id, was.read.id).catch(() => {})
|
|
1458
|
-
delete this.meta.quiltShadow
|
|
1459
|
-
this.saveMeta()
|
|
1460
|
-
this.broadcastBranches()
|
|
1461
|
-
return { shadow: null, was: { id: was.id, slug: was.slug } }
|
|
1462
|
-
}
|
|
1463
|
-
if (typeof quilt !== 'string' || quilt.length > 200) throw new Error('name the quilt to link (its slug or id)')
|
|
1464
|
-
this.quiltMoving = true
|
|
1465
|
-
try {
|
|
1466
|
-
const info = await seam.quilt(quilt)
|
|
1467
|
-
if (!info || !info.id) throw new Error(`Seam has no quilt ${quilt}`)
|
|
1468
|
-
if (!(info.lines || []).some((l) => l && l.name === 'main' && l.tip)) throw new Error(`${info.slug || quilt} has nothing on main yet: import the session's git remote into it first (seam import git ... --follow)`)
|
|
1469
|
-
let read
|
|
1470
|
-
try {
|
|
1471
|
-
const t = await seam.createToken(info.id, { name: `Quilt session ${this.name}`.slice(0, 100), level: 'read', expires_in_days: 365 })
|
|
1472
|
-
read = { token: t.token, id: t.id, ...(t.expires_at ? { expires_at: t.expires_at } : {}) }
|
|
1473
|
-
} catch (err) {
|
|
1474
|
-
throw new Error(err.status === 403 ? `only an admin of ${info.slug || quilt} can link a session to it` : `Seam did not make a read token for the session: ${err.message}`)
|
|
1475
|
-
}
|
|
1476
|
-
if (was && was.read && was.read.id && was.id !== info.id && seam.revokeToken) await seam.revokeToken(was.id, was.read.id).catch(() => {})
|
|
1477
|
-
this.meta.quiltShadow = { id: info.id, slug: info.slug || '', at: new Date().toISOString(), by: (a && (a.sub || a.key || a.name)) || '', read }
|
|
1478
|
-
this.saveMeta()
|
|
1479
|
-
this.broadcastBranches()
|
|
1480
|
-
return { shadow: { id: info.id, slug: info.slug || '' } }
|
|
1481
|
-
} finally {
|
|
1482
|
-
this.quiltMoving = false
|
|
1483
|
-
}
|
|
1484
|
-
}
|
|
1485
|
-
|
|
1486
|
-
/** A Seam client with the room's read token (shadow link or quilt), or null when it has none. */
|
|
1487
|
-
quiltReadClient () {
|
|
1488
|
-
const api = process.env.QUILT_SOURCE_URL
|
|
1489
|
-
const read = this.meta.quilt_id ? (this.meta.quilt || {}).read : (this.meta.quiltShadow || {}).read
|
|
1490
|
-
if (!api || !read || !read.token) return null
|
|
1491
|
-
if (read.expires_at && read.expires_at <= Date.now()) return null
|
|
1492
|
-
// No retries: Seam down falls back to the session's own record at once, with why.
|
|
1493
|
-
return (this.seamClient || quiltClient)({ api, token: read.token, retry: false })
|
|
1494
|
-
}
|
|
1495
|
-
|
|
1496
|
-
/**
|
|
1497
|
-
* The room's read token for quilt `q` (`read`, the one it has), as an admin `seam` checks it at a
|
|
1498
|
-
* move: kept while it has more than READ_TOKEN_RENEW_MS left and (`probe`) Seam still takes it;
|
|
1499
|
-
* else a new one is made and the old one revoked, so every member's folder can read its square.
|
|
1500
|
-
* { read, renewed: false | 'missing' | 'expiring' | 'refused' }; throws when Seam makes none.
|
|
1501
|
-
*/
|
|
1502
|
-
async freshReadToken (seam, q, read, { probe = true } = {}) {
|
|
1503
|
-
let why = !read || !read.token ? 'missing' : read.expires_at && read.expires_at - Date.now() < READ_TOKEN_RENEW_MS ? 'expiring' : ''
|
|
1504
|
-
if (!why && probe) {
|
|
1505
|
-
try { await (this.seamClient || quiltClient)({ api: process.env.QUILT_SOURCE_URL, token: read.token, retry: false }).quilt(q) } catch (err) {
|
|
1506
|
-
// Seam answers a token it no longer takes with 401, or 404 for a quilt it can't see (revoked).
|
|
1507
|
-
if (err.status === 401 || err.status === 403 || err.status === 404) why = 'refused'
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
if (!why) return { read, renewed: false }
|
|
1511
|
-
let t
|
|
1512
|
-
try { t = await seam.createToken(q, { name: `Quilt session ${this.name}`.slice(0, 100), level: 'read', expires_in_days: 365 }) } catch (err) {
|
|
1513
|
-
throw new Error(`the session's read token for its quilt is ${why === 'missing' ? 'missing' : why === 'expiring' ? 'about to end' : 'no longer taken by Seam'}, and Seam did not make a new one${err.status === 403 ? ' (only an admin of the quilt can)' : `: ${err.message}`}`)
|
|
1514
|
-
}
|
|
1515
|
-
if (read && read.id && seam.revokeToken) await seam.revokeToken(q, read.id).catch(() => {})
|
|
1516
|
-
return { read: { token: t.token, id: t.id, ...(t.expires_at ? { expires_at: t.expires_at } : {}) }, renewed: why }
|
|
1517
|
-
}
|
|
1518
|
-
|
|
1519
|
-
/**
|
|
1520
|
-
* What apps hear of the room's read token at layout 3 (never the token): when it ends, and
|
|
1521
|
-
* `renew` once it is missing, ends within READ_TOKEN_RENEW_MS or Seam refused it. The owner's app
|
|
1522
|
-
* renews it then, as the owner (Session.renewReadToken): the relay holds no credential that can.
|
|
1523
|
-
* Only an admin of the quilt makes a quilt token; the relay has the read token itself (read only)
|
|
1524
|
-
* and its accounts-API secret (not a Seam sign-in), and keeping the owner's sign-in on the relay
|
|
1525
|
-
* would let anyone with its disk act as them.
|
|
1526
|
-
*/
|
|
1527
|
-
readTokenState () {
|
|
1528
|
-
const read = (this.meta.quilt || {}).read
|
|
1529
|
-
const ends = read && read.expires_at ? Number(read.expires_at) : null
|
|
1530
|
-
const renew = !read || !read.token || !!this.meta.quilt.readRefusedAt || (ends !== null && ends - Date.now() < READ_TOKEN_RENEW_MS)
|
|
1531
|
-
return { ...(ends ? { ends } : {}), ...(renew ? { renew: true } : {}) }
|
|
1532
|
-
}
|
|
1533
|
-
|
|
1534
|
-
/** The room's read token is `read` from now on (made again by freshReadToken): kept, and apps hear it needs nothing. */
|
|
1535
|
-
takeReadToken (read) {
|
|
1536
|
-
this.meta.quilt.read = read
|
|
1537
|
-
delete this.meta.quilt.readRefusedAt
|
|
1538
|
-
this.saveMeta()
|
|
1539
|
-
this.broadcastBranches()
|
|
1540
|
-
}
|
|
1541
|
-
|
|
1542
|
-
/** Seam refused the room's read token (or it is gone): apps hear it, so the owner's renews it at once. */
|
|
1543
|
-
readTokenRefused () {
|
|
1544
|
-
if (!this.meta.quilt || this.meta.quilt.readRefusedAt) return
|
|
1545
|
-
this.meta.quilt.readRefusedAt = Date.now()
|
|
1546
|
-
this.saveMeta()
|
|
1547
|
-
this.broadcastBranches()
|
|
1548
|
-
}
|
|
1549
|
-
|
|
1550
|
-
/** The words for a room whose read token is gone or refused: what its owner does about it. */
|
|
1551
|
-
noReadToken () {
|
|
1552
|
-
const name = (this.meta.quilt && this.meta.quilt.slug) || this.meta.quilt_id || 'its quilt'
|
|
1553
|
-
return `the session's read token for ${name} is missing or has ended: its owner makes a new one with quilt session migrate --shadow ${name}`
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
/**
|
|
1557
|
-
* One read of the room's quilt for a member's block (live-block.js): `call` square, tree, blobs
|
|
1558
|
-
* or diff, always of this room's own quilt, with the room's read token. Only at layout 3.
|
|
1559
|
-
*/
|
|
1560
|
-
async quiltBlockRead ({ call, square, rev, paths, ids, from, to, file, format } = {}) {
|
|
1561
|
-
if (this.meta.layout !== LAYOUT_QUILT || !this.meta.quilt_id) throw new Error('this session\'s files are not in squares')
|
|
1562
|
-
const seam = this.quiltReadClient()
|
|
1563
|
-
if (!seam) { this.readTokenRefused(); throw new Error(this.noReadToken()) }
|
|
1564
|
-
const q = this.meta.quilt_id
|
|
1565
|
-
const list = (x, n) => Array.isArray(x) ? x.slice(0, n).map(String) : undefined
|
|
1566
|
-
const read = async () => {
|
|
1567
|
-
if (call === 'square') return { square: await seam.square(q, String(square || '')) }
|
|
1568
|
-
if (call === 'tree') return { tree: await seam.tree(q, String(rev || ''), list(paths, 100)) }
|
|
1569
|
-
if (call === 'blobs') {
|
|
1570
|
-
const want = (list(ids, 200) || []).filter((x) => /^[0-9a-f]{64}$/.test(x))
|
|
1571
|
-
return { blobs: want.length ? (await seam.blobs(q, want)).blobs : {} }
|
|
1572
|
-
}
|
|
1573
|
-
if (call === 'diff') return { diff: await seam.diff(q, { from: String(from || ''), to: String(to || ''), paths: list(paths, 100), format: 'names' }) }
|
|
1574
|
-
// A conflicted file has no bytes of its own: a folder writes it with its markers (live-block.js headFile).
|
|
1575
|
-
if (call === 'cat') return { cat: await seam.cat(q, String(rev || ''), String(file || ''), { format: format === 'git' ? 'git' : 'diff' }) }
|
|
1576
|
-
throw new Error('unknown read of the quilt')
|
|
1577
|
-
}
|
|
1578
|
-
// A token Seam no longer takes (revoked): 401, or a quilt it can't see; said with what the owner does.
|
|
1579
|
-
try { return await read() } catch (err) {
|
|
1580
|
-
if (err.status === 401 || (err.status === 404 && /no such quilt/i.test(String(err.message)))) { this.readTokenRefused(); throw new Error(this.noReadToken()) }
|
|
1581
|
-
throw err
|
|
1582
|
-
}
|
|
1583
|
-
}
|
|
1584
|
-
|
|
1585
|
-
/** The quilt this room's chronology reads (quilt-history.js historyQuilt) and a client to read it with. */
|
|
1586
|
-
quiltHistoryLink () {
|
|
1587
|
-
const quilt = historyQuilt(this.meta)
|
|
1588
|
-
return quilt ? { quilt, seam: this.quiltReadClient() } : null
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
/** The quilt's log for `query` (path, by, since, task, limit, with_diff), as chronology entries; null when the room has no link. */
|
|
1592
|
-
async quiltLog (query = {}) {
|
|
1593
|
-
const link = this.quiltHistoryLink()
|
|
1594
|
-
if (!link) return { ok: true, quilt: null, entries: [] }
|
|
1595
|
-
const r = await linkedHistory({ seam: link.seam, quilt: link.quilt, entries: [], query: { path: query.path || '', by: query.by, since: typeof query.since === 'number' ? query.since : undefined, task: query.task, limit: Math.min(Number(query.limit) || 30, 200), withDiff: !!query.with_diff } })
|
|
1596
|
-
return { ok: true, quilt: link.quilt, entries: r.list, ...(r.note ? { note: r.note } : {}) }
|
|
1597
|
-
}
|
|
1598
|
-
|
|
1599
|
-
/**
|
|
1600
|
-
* One read of the room's quilt for the app (blame, search, a patch), with the room's read token:
|
|
1601
|
-
* one request to Seam per `key` at a time, its answer kept a minute. Answers within `wait` ms,
|
|
1602
|
-
* else { working: true } and the app asks again: a first blame of a file is worked out by Seam
|
|
1603
|
-
* (202 "deriving"), which the client waits on at Seam's own pace. { quilt: null } when not linked.
|
|
1604
|
-
*/
|
|
1605
|
-
quiltRead (key, read, { wait = this.quiltReadWaitMs ?? QUILT_READ_WAIT_MS } = {}) {
|
|
1606
|
-
const link = this.quiltHistoryLink()
|
|
1607
|
-
if (!link) return Promise.resolve({ ok: true, quilt: null })
|
|
1608
|
-
if (!link.seam) return Promise.resolve({ ok: false, error: `the session has no read token for ${link.quilt.slug || link.quilt.id}: link it again` })
|
|
1609
|
-
const reads = this.quiltReads || (this.quiltReads = new Map())
|
|
1610
|
-
for (const [k, r] of reads) if (r.done && Date.now() - r.done > QUILT_READ_KEEP_MS) reads.delete(k)
|
|
1611
|
-
const k = `${link.quilt.id}\0${key}`
|
|
1612
|
-
let r = reads.get(k)
|
|
1613
|
-
if (!r) {
|
|
1614
|
-
r = { done: 0, answer: null }
|
|
1615
|
-
r.promise = read(link.seam, link.quilt.id)
|
|
1616
|
-
.then((v) => ({ ok: true, quilt: link.quilt, ...v }), (err) => ({ ok: false, error: `Seam: ${String(err.message || err).slice(0, 300)}` }))
|
|
1617
|
-
.then((ans) => { r.answer = ans; r.done = Date.now(); if (!ans.ok && reads.get(k) === r) reads.delete(k); return ans })
|
|
1618
|
-
reads.set(k, r)
|
|
1619
|
-
if (reads.size > 64) reads.delete(reads.keys().next().value)
|
|
1620
|
-
}
|
|
1621
|
-
if (r.done) return Promise.resolve(r.answer)
|
|
1622
|
-
return Promise.race([r.promise, new Promise((resolve) => { const t = setTimeout(() => resolve({ ok: true, quilt: link.quilt, working: true }), wait); t.unref?.() })])
|
|
1623
|
-
}
|
|
1624
|
-
|
|
1625
|
-
/**
|
|
1626
|
-
* Who wrote each line of `path` on main, from Seam's blame: { blame: { commit, who: [{ commit,
|
|
1627
|
-
* short, by, at, patch }], lines: [[text, index in who or -1]] } }, or { missing: true } when the
|
|
1628
|
-
* file is not on main (all of it is live work).
|
|
1629
|
-
*/
|
|
1630
|
-
quiltBlame (p) {
|
|
1631
|
-
const file = quiltFilePath(p)
|
|
1632
|
-
if (!file) return Promise.reject(new Error('name a file'))
|
|
1633
|
-
return this.quiltRead(`blame\0${file}`, async (seam, q) => {
|
|
1634
|
-
let b
|
|
1635
|
-
try { b = await seam.blame(q, 'main', file) } catch (err) { if (err.status === 404) return { missing: true }; throw err }
|
|
1636
|
-
const who = []
|
|
1637
|
-
const at = new Map()
|
|
1638
|
-
const lines = (b.lines || []).slice(0, QUILT_BLAME_MAX_LINES).map((l) => {
|
|
1639
|
-
if (!l.commit) return [String(l.text ?? ''), -1]
|
|
1640
|
-
if (!at.has(l.commit)) { at.set(l.commit, who.length); who.push({ commit: l.commit, short: l.short || l.commit.slice(0, 12), by: String(l.author || ''), at: Number(l.at) || 0, ...(l.patch && l.patch.patch_no != null ? { patch: l.patch.patch_no } : {}) }) }
|
|
1641
|
-
return [String(l.text ?? ''), at.get(l.commit)]
|
|
1642
|
-
})
|
|
1643
|
-
return { blame: { commit: b.commit || null, who, lines } }
|
|
1644
|
-
})
|
|
1645
|
-
}
|
|
1646
|
-
|
|
1647
|
-
/** Code search over main (Seam's /search): { search: { commit, counts, more, hits: [{ path, line, text, symbol }] } }. */
|
|
1648
|
-
quiltSearch (text) {
|
|
1649
|
-
const q = typeof text === 'string' ? text.trim() : ''
|
|
1650
|
-
if (!q || q.length > 300) return Promise.reject(new Error('search for some text (300 characters at most)'))
|
|
1651
|
-
return this.quiltRead(`search\0${q}`, async (seam, id) => {
|
|
1652
|
-
const r = await seam.searchCode(id, { q, rev: 'main', limit: 100 })
|
|
1653
|
-
const hits = ((r && r.results) || []).filter((x) => x && typeof x.path === 'string').map((x) => ({
|
|
1654
|
-
path: x.path,
|
|
1655
|
-
...(x.line ? { line: Number(x.line) } : {}),
|
|
1656
|
-
...(x.kind === 'content' ? { text: String(x.text || '').slice(0, 500) } : {}),
|
|
1657
|
-
...(x.kind === 'symbol' && x.symbol ? { symbol: `${x.symbol.kind || ''} ${x.symbol.name || ''}`.trim() } : {})
|
|
1658
|
-
}))
|
|
1659
|
-
return { search: { commit: (r && r.commit) || null, counts: (r && r.counts) || { files: 0, matches: 0 }, more: !!(r && (r.cursor || r.more)), hits } }
|
|
1660
|
-
})
|
|
1661
|
-
}
|
|
1662
|
-
|
|
1663
|
-
/** One patch (a commit of the log) for a file's History: { patch: { commit, files: [{ path, added, removed }], diff } }, the diff of `path` only. */
|
|
1664
|
-
quiltShow (commit, p) {
|
|
1665
|
-
if (typeof commit !== 'string' || !/^[0-9a-f]{12,64}$/.test(commit)) return Promise.reject(new Error('name a commit'))
|
|
1666
|
-
const file = quiltFilePath(p)
|
|
1667
|
-
return this.quiltRead(`show\0${commit}\0${file}`, async (seam, id) => {
|
|
1668
|
-
const s = await seam.show(id, commit, { format: 'unified' })
|
|
1669
|
-
const files = ((s && s.diff && s.diff.files) || []).map((f) => {
|
|
1670
|
-
let added = 0
|
|
1671
|
-
let removed = 0
|
|
1672
|
-
for (const l of String(f.patch || '').split('\n')) {
|
|
1673
|
-
if (l.startsWith('+') && !l.startsWith('+++')) added++
|
|
1674
|
-
else if (l.startsWith('-') && !l.startsWith('---')) removed++
|
|
1675
|
-
}
|
|
1676
|
-
return { path: String(f.path || ''), added, removed, ...(f.binary ? { binary: true } : {}), patch: String(f.patch || '') }
|
|
1677
|
-
})
|
|
1678
|
-
const mine = files.find((f) => f.path === file)
|
|
1679
|
-
const diff = mine ? mine.patch.split('\n').filter((l) => !l.startsWith('--- ') && !l.startsWith('+++ ')).join('\n') : ''
|
|
1680
|
-
return { patch: { commit, files: files.map(({ patch, ...f }) => f), diff: diff.length > MAX_DIFF_CHARS ? `${diff.slice(0, MAX_DIFF_CHARS)}\n… (diff truncated)` : diff } }
|
|
1681
|
-
})
|
|
1682
|
-
}
|
|
1683
|
-
|
|
1684
|
-
/** The dry run of making this session a quilt, for someone with access `a` (session-quilt.js). */
|
|
1685
|
-
quiltPlan (a, tip = null) {
|
|
1686
|
-
const no = quiltPlanRefusal({ controlled: this.controlled, access: a })
|
|
1687
|
-
if (no) throw new Error(no)
|
|
1688
|
-
this.assertMigrated()
|
|
1689
|
-
return planSessionQuilt(this.quiltSnapshot(), { tip: tip && typeof tip === 'object' ? tip : null })
|
|
1690
|
-
}
|
|
1691
|
-
|
|
1692
|
-
/**
|
|
1693
|
-
* The room as session-quilt.js's dry run reads it: each branch document's files (by hash),
|
|
1694
|
-
* history and merge records, tasks with pull requests, and commit requests.
|
|
1695
|
-
* Live square documents (quilt/<id>) are already Seam's and are left out.
|
|
1696
|
-
*/
|
|
1697
|
-
quiltSnapshot () {
|
|
1698
|
-
const branches = []
|
|
1699
|
-
for (const [key, b] of Object.entries(this.meta.branches || {})) {
|
|
1700
|
-
if (isLiveKey(key)) continue
|
|
1701
|
-
const e = this.store.load(key)
|
|
1702
|
-
if (!e) continue
|
|
1703
|
-
const files = {}
|
|
1704
|
-
for (const [p, t] of e.files) { const s = t.toString(); files[p] = { hash: fileHash(s), bytes: Buffer.byteLength(s) } }
|
|
1705
|
-
for (const [p, x] of e.blobs) if (x && !files[p]) files[p] = { hash: String(x.hash || x.sha256 || ''), bytes: Number(x.size) || 0 }
|
|
1706
|
-
const merges = [...e.doc.getMap('merges').values()].map((m) => ({ id: m && m.id, state: m && m.state }))
|
|
1707
|
-
branches.push({ key, by: b.by || '', files, history: e.doc.getArray('history').toArray(), merges })
|
|
1708
|
-
}
|
|
1709
|
-
const tasks = [...this.tasks.entries()].map(([id, t]) => ({ id, pr: t && typeof t.get === 'function' ? t.get('pr') : t && t.pr })).filter((t) => t.pr)
|
|
1710
|
-
return {
|
|
1711
|
-
room: this.name,
|
|
1712
|
-
owner: this.meta.ownerSub || this.meta.ownerName || this.meta.owner || '',
|
|
1713
|
-
defaultKey: this.defaultKey,
|
|
1714
|
-
hasRemote: Object.keys(this.meta.upstreams || {}).length > 0,
|
|
1715
|
-
branches,
|
|
1716
|
-
tasks,
|
|
1717
|
-
commitRequests: this.doc.getMap('commitRequests').size
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
|
|
1721
|
-
/**
|
|
1722
|
-
* Makes this session a quilt (Seam's plans/quilt-source-control/16, "Without history"), behind
|
|
1723
|
-
* QUILT_SOURCE_URL: the owner's (as quiltPlan), with `seam` a Seam client acting as them.
|
|
1724
|
-
* The room is linked (`meta.quilt_id`, `meta.quilt`) only when every step worked, so a
|
|
1725
|
-
* failure leaves it a git-mode session as before. A room with a git remote goes with history
|
|
1726
|
-
* (the import and the cut-over, 14 and 16 step 3), not here.
|
|
1727
|
-
*/
|
|
1728
|
-
async quiltMigrate (a, seam, { date = new Date() } = {}) {
|
|
1729
|
-
const no = quiltPlanRefusal({ controlled: this.controlled, access: a })
|
|
1730
|
-
if (no) throw new Error(no.replace('see what making it a quilt would do', 'make it a quilt'))
|
|
1731
|
-
this.assertMigrated()
|
|
1732
|
-
if (this.meta.quilt_id) throw new Error(`this session is already the quilt ${(this.meta.quilt && this.meta.quilt.slug) || this.meta.quilt_id}`)
|
|
1733
|
-
if (this.meta.quiltShadow) return this.quiltMigrateWithHistory(a, seam, { date })
|
|
1734
|
-
if (Object.keys(this.meta.upstreams || {}).length) throw new Error('this session has a git remote: it becomes a quilt with its history. Import the remote into a quilt with follow, link the session to it (quilt session migrate --shadow <quilt>), cut the import over, then migrate (docs/seam-cutover.md in the Seam repository)')
|
|
1735
|
-
return this.withMigrationLease(async () => {
|
|
1736
|
-
// Texts and small binaries (base64 in the document) go into the quilt; large files in storage are left out.
|
|
1737
|
-
const texts = (key) => {
|
|
1738
|
-
const e = this.store.load(key)
|
|
1739
|
-
const files = {}; const binaries = {}; const big = []; const modes = {}
|
|
1740
|
-
if (!e) return { files, binaries, modes, big, merges: [] }
|
|
1741
|
-
for (const [p, t] of e.files) files[p] = t.toString()
|
|
1742
|
-
for (const [p, x] of e.blobs) if (x && !(p in files)) { if (typeof x.data === 'string') binaries[p] = x.data; else big.push(p) }
|
|
1743
|
-
if (e.modes) for (const [p, m] of e.modes) if (m === 'x') modes[p] = 'x'
|
|
1744
|
-
return { files, binaries, modes, big, merges: e.doc ? readMerges(e.doc.getMap('merges')) : [] }
|
|
1745
|
-
}
|
|
1746
|
-
const def = texts(this.defaultKey)
|
|
1747
|
-
const leftOut = new Set(def.big)
|
|
1748
|
-
const branches = []
|
|
1749
|
-
for (const key of Object.keys(this.meta.branches || {})) {
|
|
1750
|
-
if (key === this.defaultKey || isLiveKey(key)) continue
|
|
1751
|
-
const t = texts(key)
|
|
1752
|
-
for (const p of t.big) leftOut.add(`${key}:${p}`)
|
|
1753
|
-
branches.push({ key, files: t.files, binaries: t.binaries, merges: t.merges })
|
|
1754
|
-
}
|
|
1755
|
-
const r = await makeQuiltWithoutHistory({ seam, room: this.name, defaultFiles: def.files, defaultBinaries: def.binaries, defaultModes: def.modes, defaultMerges: def.merges, branches, leftOut: [...leftOut], date })
|
|
1756
|
-
this.meta.quilt_id = r.quilt_id
|
|
1757
|
-
this.meta.quilt = { slug: r.slug, patch: r.patch, squares: Object.fromEntries(r.squares.map((s) => [s.from, s.id])), at: new Date(date).toISOString(), by: (a && (a.sub || a.key || a.name)) || '' }
|
|
1758
|
-
// Open merges now live in Seam as conflict terms; the ones with no text to carry are named.
|
|
1759
|
-
if (r.terms.length || r.merges_left.length) this.meta.quilt.merges = { terms: r.terms, left: r.merges_left }
|
|
1760
|
-
this.meta.quilt.tasks = this.quiltTasks(this.meta.quilt.squares)
|
|
1761
|
-
this.quiltCommitRequests(this.meta.quilt.squares)
|
|
1762
|
-
// A read token for the room, so hosted agents' quilt_history reads the quilt's log (best effort: without it they read the session's own record).
|
|
1763
|
-
if (seam.createToken) {
|
|
1764
|
-
try { const t = await seam.createToken(r.quilt_id, { name: `Quilt session ${this.name}`.slice(0, 100), level: 'read', expires_in_days: 365 }); if (t && t.token) this.meta.quilt.read = { token: t.token, id: t.id, ...(t.expires_at ? { expires_at: t.expires_at } : {}) } } catch {}
|
|
1765
|
-
}
|
|
1766
|
-
this.saveMeta()
|
|
1767
|
-
this.broadcastBranches()
|
|
1768
|
-
return { ...r, tasks: this.meta.quilt.tasks }
|
|
1769
|
-
}, seam)
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
/**
|
|
1773
|
-
* What a move into squares made so far, saved as it goes (`meta.quiltMove`): the squares it opened
|
|
1774
|
-
* in Seam and the square documents it made here. A relay that stops
|
|
1775
|
-
* part way (a deploy, a crash) finds it at load (recoverQuiltMove); done or undone, it goes.
|
|
1776
|
-
*/
|
|
1777
|
-
startQuiltMove (quilt) {
|
|
1778
|
-
this.meta.quiltMove = { quilt, at: Date.now(), opened: [], made: [], ...(this.migrationLease ? { lease: this.migrationLease } : {}) }
|
|
1779
|
-
this.saveMeta()
|
|
1780
|
-
return this.meta.quiltMove
|
|
1781
|
-
}
|
|
1782
|
-
|
|
1783
|
-
endQuiltMove () {
|
|
1784
|
-
if (!this.meta.quiltMove) return
|
|
1785
|
-
delete this.meta.quiltMove
|
|
1786
|
-
this.saveMeta()
|
|
1787
|
-
}
|
|
1788
|
-
|
|
1789
|
-
/**
|
|
1790
|
-
* At load: a move that never finished (layout 3 is written last, with the record's removal) is
|
|
1791
|
-
* undone here. The square documents it made leave, and what it opened in Seam is kept in
|
|
1792
|
-
* `meta.quiltLeftOver` for the owner's next move to abandon (only the owner's sign-in can). The
|
|
1793
|
-
* branch documents were never touched, so the session is as it was before the move.
|
|
1794
|
-
*/
|
|
1795
|
-
recoverQuiltMove () {
|
|
1796
|
-
const mv = this.meta.quiltMove
|
|
1797
|
-
if (!mv) return
|
|
1798
|
-
delete this.meta.quiltMove
|
|
1799
|
-
if (this.meta.layout !== LAYOUT_QUILT) {
|
|
1800
|
-
const live = new Set(Object.values((this.meta.quilt && this.meta.quilt.live) || {}))
|
|
1801
|
-
for (const lk of mv.made || []) if (isLiveKey(lk) && !live.has(lk) && this.meta.branches[lk]) this.removeBranch(lk, { save: false })
|
|
1802
|
-
const left = this.meta.quiltLeftOver || { quilt: mv.quilt, squares: [] }
|
|
1803
|
-
if (left.quilt === mv.quilt) {
|
|
1804
|
-
left.squares = [...new Set([...left.squares, ...(mv.opened || [])])]
|
|
1805
|
-
if (mv.lease) left.lease = mv.lease
|
|
1806
|
-
this.meta.quiltLeftOver = left
|
|
1807
|
-
}
|
|
1808
|
-
this.log(`[${this.name}] a move into squares stopped part way (the relay stopped): undone, the session is as it was; ${(mv.opened || []).length} square(s) it opened are abandoned at the next move`)
|
|
1809
|
-
}
|
|
1810
|
-
this.saveMeta()
|
|
1811
|
-
}
|
|
1812
|
-
|
|
1813
|
-
/** What a stopped move opened in Seam (recoverQuiltMove) is let go of, as the owner moving the session now. */
|
|
1814
|
-
async letGoOfStoppedMove (seam) {
|
|
1815
|
-
const left = this.meta.quiltLeftOver
|
|
1816
|
-
if (!left) return
|
|
1817
|
-
for (const id of left.squares || []) if (seam.abandon) await seam.abandon(left.quilt, id, { reason: 'a move of the session into the quilt stopped part way' }).catch(() => {})
|
|
1818
|
-
delete this.meta.quiltLeftOver
|
|
1819
|
-
this.saveMeta()
|
|
1820
|
-
}
|
|
1821
|
-
|
|
1822
|
-
/**
|
|
1823
|
-
* A move goes on only while the room is still this machine's: the cluster can hand it to another
|
|
1824
|
-
* machine (or the relay can stop) while the move waits on Seam, and this copy saves nothing after
|
|
1825
|
-
* that. Throws, so the move undoes what it made in Seam itself; the other machine undoes the rest
|
|
1826
|
-
* from the move's record (recoverQuiltMove).
|
|
1827
|
-
*/
|
|
1828
|
-
stillHere () {
|
|
1829
|
-
if (this.released || this.ended) throw new Error('the session left this relay machine during the move; move it again')
|
|
1830
|
-
if (this.moveLeaseLost) throw new Error('another relay machine took this session\'s move lease during the move; move it again')
|
|
1831
|
-
}
|
|
1832
|
-
|
|
1833
|
-
/**
|
|
1834
|
-
* Which git blob ids each of `paths` had in the default branch's history (the relay's git mirror,
|
|
1835
|
-
* up to the commit the session last knew main at): Map path -> Set, or null when the mirror can't
|
|
1836
|
-
* say (no git sync on this relay, no mirror, the commit out of reach).
|
|
1837
|
-
*/
|
|
1838
|
-
/**
|
|
1839
|
-
* Main's earlier versions of `file` from the history of `rev` in Seam (the move's square head), with
|
|
1840
|
-
* the head's own text (`headId`): { head, versions } for boxOntoHead, or null when they can't be read.
|
|
1841
|
-
*/
|
|
1842
|
-
async versionsOnLine (seam, q, rev, file, headId) {
|
|
1843
|
-
if (!seam.log || !seam.blobs) return null
|
|
1844
|
-
const log = await seam.log(q, { rev, paths: [file], limit: 50 })
|
|
1845
|
-
const ids = new Set([headId])
|
|
1846
|
-
for (const c of (log && log.commits) || []) {
|
|
1847
|
-
if (!c || !c.id) continue
|
|
1848
|
-
const t = await seam.tree(q, c.id, [file])
|
|
1849
|
-
for (const e of (t && t.entries) || []) if (e.path === file && e.blob) ids.add(e.blob)
|
|
1850
|
-
}
|
|
1851
|
-
const { blobs } = await seam.blobs(q, [...ids])
|
|
1852
|
-
const text = (id) => blobs && blobs[id] ? Buffer.from(blobs[id], 'base64').toString('utf8') : null
|
|
1853
|
-
const head = text(headId)
|
|
1854
|
-
return head === null ? null : { head, versions: [...ids].map(text).filter((x) => typeof x === 'string') }
|
|
1855
|
-
}
|
|
1856
|
-
|
|
1857
|
-
/**
|
|
1858
|
-
* One layout move of this room at a time, here and on every relay machine (a lease per room,
|
|
1859
|
-
* relay-lease.js). With `seam` (the owner's), what a move stopped part way left in Seam
|
|
1860
|
-
* (recoverQuiltMove) is let go of first.
|
|
1861
|
-
*/
|
|
1862
|
-
async withMigrationLease (fn, seam = null, kind = 'in') {
|
|
1863
|
-
if (this.quiltMoving) throw new Error('this session is already being moved')
|
|
1864
|
-
this.quiltMoving = true
|
|
1865
|
-
let done
|
|
1866
|
-
this.quiltMoved = new Promise((resolve) => { done = resolve })
|
|
1867
|
-
const keeper = this.leases
|
|
1868
|
-
const lease = keeper ? { repo: `relay.quilt/layout3/${crypto.createHash('sha256').update(this.name).digest('hex').slice(0, 40)}`, branch: 'migrate', room: `${MIGRATION_LEASE}${crypto.randomBytes(8).toString('hex')}` } : null
|
|
1869
|
-
let renew = null
|
|
1870
|
-
try {
|
|
1871
|
-
if (lease) {
|
|
1872
|
-
migrating.add(lease.room)
|
|
1873
|
-
let got = await keeper.ensure(lease)
|
|
1874
|
-
// The lease of a move that stopped with its relay (recoverQuiltMove): this relay lets go of it
|
|
1875
|
-
// when it still holds it, else it lapses within LEASE_TTL_MS of its last renewal.
|
|
1876
|
-
const stopped = this.meta.quiltLeftOver && this.meta.quiltLeftOver.lease
|
|
1877
|
-
if (!got.ok && stopped && got.room === stopped && await keeper.release({ ...lease, room: stopped })) got = await keeper.ensure(lease)
|
|
1878
|
-
if (!got.ok && stopped && got.room === stopped) throw new Error('a move of this session stopped part way when the relay restarted, and still holds its lease for up to two minutes; try again then')
|
|
1879
|
-
if (!got.ok) throw new Error(got.error ? `the relay could not take this session's migration lease (${got.error}); try again` : 'another relay machine is moving this session right now; try again in a few minutes')
|
|
1880
|
-
this.migrationLease = lease.room
|
|
1881
|
-
// The move keeps its own lease while it runs (minutes for a big session), whether or not this
|
|
1882
|
-
// relay renews live-sync leases; a lease it loses (another machine took it) stops it (stillHere).
|
|
1883
|
-
renew = setInterval(() => {
|
|
1884
|
-
keeper.ensure(lease).then((r) => { if (!r.ok && !r.error) this.moveLeaseLost = true }, () => {})
|
|
1885
|
-
}, this.cfg.leaseHeartbeatMs || LEASE_HEARTBEAT_MS)
|
|
1886
|
-
renew.unref?.()
|
|
1887
|
-
}
|
|
1888
|
-
// Every member hears the move is running (branchesFields `moving`): the app says so while it lasts.
|
|
1889
|
-
this.movingNow = { kind, since: Date.now() }
|
|
1890
|
-
this.broadcastBranches()
|
|
1891
|
-
if (seam) await this.letGoOfStoppedMove(seam)
|
|
1892
|
-
return await fn()
|
|
1893
|
-
} finally {
|
|
1894
|
-
clearInterval(renew)
|
|
1895
|
-
if (this.movingNow) { this.movingNow = null; if (!this.destroyed) this.broadcastBranches() }
|
|
1896
|
-
if (lease) { migrating.delete(lease.room); await keeper.release(lease).catch(() => {}) }
|
|
1897
|
-
this.moveLeaseLost = false
|
|
1898
|
-
this.migrationLease = null
|
|
1899
|
-
this.quiltMoving = false
|
|
1900
|
-
done()
|
|
1901
|
-
}
|
|
1902
|
-
}
|
|
1903
|
-
|
|
1904
|
-
/**
|
|
1905
|
-
* 16 "With history", in the cut-over sitting: a session with a git remote becomes the quilt its
|
|
1906
|
-
* import filled (the shadow link, quiltShadowLink), no new quilt. Only once the import is cut
|
|
1907
|
-
* over (main no longer frozen for the follow), because from now on Seam, not git, is the
|
|
1908
|
-
* authority. Each other branch document becomes a square based at its ref's imported commit
|
|
1909
|
-
* (`git:<sha>`), a detached `@sha` document at that commit, else at main's tip; open merges
|
|
1910
|
-
* become conflict terms in their square's first commit; then the layout-3 switch runs in the
|
|
1911
|
-
* same lease (the default document's difference from the imported tip is the adoption square).
|
|
1912
|
-
* If the switch fails, the link is undone too: the session is a git-mode session that shadows
|
|
1913
|
-
* the quilt, as before.
|
|
1914
|
-
*/
|
|
1915
|
-
async quiltMigrateWithHistory (a, seam, { date = new Date() } = {}) {
|
|
1916
|
-
// After the forced date stopped live sync, the branch documents are older than git: an adoption square made from
|
|
1917
|
-
// them would put back what the team committed since. Refused until the cut-over that skips them is built (NOT-DONE.md).
|
|
1918
|
-
if (this.meta.syncStopped) throw new Error(`live sync stopped on ${String(this.meta.syncStopped.at).slice(0, 10)}, so this session's branches are older than its git remote: moving it into its quilt with them would undo work committed since. That move is not built yet`)
|
|
1919
|
-
return this.withMigrationLease(async () => {
|
|
1920
|
-
const sh = this.meta.quiltShadow
|
|
1921
|
-
if (!sh) throw new Error('this session is no longer linked to a quilt')
|
|
1922
|
-
const info = await seam.quilt(sh.id)
|
|
1923
|
-
const main = ((info && info.lines) || []).find((l) => l && l.name === 'main')
|
|
1924
|
-
if (!main || !main.tip) throw new Error(`${sh.slug || sh.id} has nothing on main: import the session's git remote into it first`)
|
|
1925
|
-
if (main.frozen) throw new Error(`${sh.slug || sh.id}'s main is still frozen for the import's follow: cut the import over first (seam import cutover), then migrate`)
|
|
1926
|
-
const tip = { no: Number(main.patch_count) || null, commit: main.tip }
|
|
1927
|
-
// Every folder reads its square with the room's read token: checked (made again if need be) before anything moves.
|
|
1928
|
-
const rt = await this.freshReadToken(seam, sh.id, sh.read)
|
|
1929
|
-
const squares = []; const based = []; const terms = []; const mergesLeft = []
|
|
1930
|
-
// A failed move leaves no squares behind in the quilt: the ones it opened are abandoned.
|
|
1931
|
-
const abandonAll = async () => { for (const x of squares) if (seam.abandon) await seam.abandon(sh.id, x.id, { reason: 'the session\'s move into the quilt was undone' }).catch(() => {}) }
|
|
1932
|
-
const move = this.startQuiltMove(sh.id)
|
|
1933
|
-
try {
|
|
1934
|
-
for (const key of Object.keys(this.meta.branches || {})) {
|
|
1935
|
-
if (key === this.defaultKey || isLiveKey(key)) continue
|
|
1936
|
-
const want = squareBase(key, this.meta)
|
|
1937
|
-
// No commit names where the branch starts (the relay never fetched it from git): main's tip, said in the answer.
|
|
1938
|
-
if (!want) based.push({ from: key, wanted: '', why: 'unfetched' })
|
|
1939
|
-
let s
|
|
1940
|
-
try { s = await seam.openSquare(sh.id, { title: String(key).slice(0, 200), ...(want ? { base: want } : {}) }) } catch (err) {
|
|
1941
|
-
// Seam has no commit for that sha, or has it inside a square (a branch git merged into
|
|
1942
|
-
// main, imported as the merged square's own commit): main's tip, which holds it.
|
|
1943
|
-
const inSquare = /square's own commit, not a patch/.test(String(err && err.message))
|
|
1944
|
-
if (!want || (err.status !== 404 && !inSquare)) throw err
|
|
1945
|
-
s = await seam.openSquare(sh.id, { title: String(key).slice(0, 200) })
|
|
1946
|
-
based.push({ from: key, wanted: want, ...(inSquare ? { why: 'merged' } : {}) })
|
|
1947
|
-
}
|
|
1948
|
-
squares.push({ from: key, id: s.id })
|
|
1949
|
-
move.opened.push(s.id)
|
|
1950
|
-
this.stillHere()
|
|
1951
|
-
this.saveMeta()
|
|
1952
|
-
const e = this.store.load(key)
|
|
1953
|
-
const files = {}
|
|
1954
|
-
if (e) for (const [p, t] of e.files) files[p] = t.toString()
|
|
1955
|
-
const t = termsFor(e && e.doc ? readMerges(e.doc.getMap('merges')) : [], files, { square: s.id, patchSquare: null, patch: tip })
|
|
1956
|
-
for (const m of t.left) mergesLeft.push({ from: key, path: m.path, id: m.id })
|
|
1957
|
-
if (t.terms.length) {
|
|
1958
|
-
await seam.commit(sh.id, s.id, { expect_head: null, message: `Open merges from session ${this.name}: ${t.terms.map((x) => x.path).join(', ')}`.slice(0, 2000), changes: t.terms })
|
|
1959
|
-
this.stillHere()
|
|
1960
|
-
for (const x of t.terms) terms.push({ from: key, path: x.path, square: s.id })
|
|
1961
|
-
}
|
|
1962
|
-
}
|
|
1963
|
-
} catch (err) {
|
|
1964
|
-
await abandonAll()
|
|
1965
|
-
if (rt.renewed && this.meta.quiltShadow) this.meta.quiltShadow.read = rt.read
|
|
1966
|
-
this.endQuiltMove()
|
|
1967
|
-
throw err
|
|
1968
|
-
}
|
|
1969
|
-
const by = (a && (a.sub || a.key || a.name)) || ''
|
|
1970
|
-
// The room takes the quilt only as layout 3 is written (quiltSwitchNow): until then it is the
|
|
1971
|
-
// shadowing git-mode session it was, for its members, its agents, and a relay that stops.
|
|
1972
|
-
const quilt = { slug: sh.slug || info.slug || '', patch: tip, squares: Object.fromEntries(squares.map((x) => [x.from, x.id])), at: new Date(date).toISOString(), by, history: true, shadow: { ...sh, read: rt.read }, read: rt.read }
|
|
1973
|
-
if (terms.length || mergesLeft.length) quilt.merges = { terms, left: mergesLeft }
|
|
1974
|
-
if (based.length) quilt.basedAtTip = based
|
|
1975
|
-
let switched
|
|
1976
|
-
try {
|
|
1977
|
-
switched = await this.quiltSwitchNow(a, seam, { date, into: { id: sh.id, quilt } })
|
|
1978
|
-
} catch (err) {
|
|
1979
|
-
await abandonAll()
|
|
1980
|
-
// Still the shadowing session, with the read token as it is now (an old one was revoked for it).
|
|
1981
|
-
if (rt.renewed && this.meta.quiltShadow) { this.meta.quiltShadow.read = rt.read; this.saveMeta() }
|
|
1982
|
-
this.endQuiltMove()
|
|
1983
|
-
throw err
|
|
1984
|
-
}
|
|
1985
|
-
const tasks = this.meta.quilt.tasks = this.quiltTasks(this.meta.quilt.squares)
|
|
1986
|
-
this.quiltCommitRequests(this.meta.quilt.squares)
|
|
1987
|
-
this.saveMeta()
|
|
1988
|
-
this.broadcastBranches()
|
|
1989
|
-
return { quilt_id: sh.id, slug: this.meta.quilt.slug, patch: tip, squares, terms, merges_left: mergesLeft, left_out: [], history: true, based_at_tip: based, tasks, ...(rt.renewed ? { read_token: rt.renewed } : {}), ...switched }
|
|
1990
|
-
}, seam)
|
|
1991
|
-
}
|
|
1992
|
-
|
|
1993
|
-
/**
|
|
1994
|
-
* The layout-3 switch (16, "How a session becomes a quilt"), after quiltMigrate linked the
|
|
1995
|
-
* quilt: each branch document is copied into its square's live document on the relay
|
|
1996
|
-
* (`quilt/<square id>`, an overlay over the square's head), the default branch's difference
|
|
1997
|
-
* from `main` into an adoption square ("Uncommitted work from <room>"), every copy is checked
|
|
1998
|
-
* against its branch document, and only then `meta.layout = 3` is written. A failed check
|
|
1999
|
-
* removes the copies and leaves the room at layout 2. The branch documents are not touched: at
|
|
2000
|
-
* layout 3 they are read-only, and quiltUnswitch goes back to them. Apps without `quilts` are
|
|
2001
|
-
* sent away (supported). The owner's, with `seam` acting as them, behind QUILT_SOURCE_URL.
|
|
2002
|
-
*/
|
|
2003
|
-
async quiltSwitch (a, seam, { date = new Date() } = {}) {
|
|
2004
|
-
const no = quiltPlanRefusal({ controlled: this.controlled, access: a })
|
|
2005
|
-
if (no) throw new Error(no.replace('see what making it a quilt would do', 'move its files into its squares'))
|
|
2006
|
-
if (this.meta.layout === LAYOUT_QUILT) throw new Error('this session\'s files are already in its squares')
|
|
2007
|
-
this.assertMigrated()
|
|
2008
|
-
if (!this.meta.quilt_id || !this.meta.quilt) throw new Error('this session is not a quilt yet: make it one first (quilt session migrate)')
|
|
2009
|
-
return this.withMigrationLease(async () => {
|
|
2010
|
-
const rt = await this.freshReadToken(seam, this.meta.quilt_id, this.meta.quilt.read)
|
|
2011
|
-
if (rt.renewed) { this.meta.quilt.read = rt.read; this.saveMeta() }
|
|
2012
|
-
return { ...await this.quiltSwitchNow(a, seam, { date }), ...(rt.renewed ? { read_token: rt.renewed } : {}) }
|
|
2013
|
-
}, seam)
|
|
2014
|
-
}
|
|
2015
|
-
|
|
2016
|
-
/**
|
|
2017
|
-
* "Make this a quilt" (Seam's plans/quilt-source-control/16, flag 9): the owner's one step, from the
|
|
2018
|
-
* app's button, `quilt session migrate`, quilt_migrate_session or POST /v1/sessions/:room/migrate.
|
|
2019
|
-
* A room with no git remote becomes a quilt without history and its files go into its squares
|
|
2020
|
-
* (layout 3) in the same go; a room linked to the quilt its remote's import fills moves with history
|
|
2021
|
-
* (quiltMigrateWithHistory switches itself); a room already a quilt at layout 2 only switches. A
|
|
2022
|
-
* switch that fails leaves the room the layout-2 quilt it just became, every branch document as it
|
|
2023
|
-
* was (nobody's work moves until every copy is checked): the next click only switches.
|
|
2024
|
-
*/
|
|
2025
|
-
async quiltMake (a, seam, { date = new Date() } = {}) {
|
|
2026
|
-
if (this.meta.layout === LAYOUT_QUILT) throw new Error(`this session is already the quilt ${(this.meta.quilt && this.meta.quilt.slug) || this.meta.quilt_id}`)
|
|
2027
|
-
if (!this.meta.quilt_id && (this.hasGitRemote() || this.meta.quiltShadow || this.meta.quiltImport)) return this.quiltMakeWithRemote(a, seam, { date })
|
|
2028
|
-
let quilt = null
|
|
2029
|
-
if (!this.meta.quilt_id) {
|
|
2030
|
-
quilt = await this.quiltMigrate(a, seam, { date })
|
|
2031
|
-
if (this.meta.layout === LAYOUT_QUILT) return { ...quilt, layout: LAYOUT_QUILT }
|
|
2032
|
-
} else {
|
|
2033
|
-
const Q = this.meta.quilt || {}
|
|
2034
|
-
quilt = { quilt_id: this.meta.quilt_id, slug: Q.slug || '', patch: Q.patch || null, squares: Object.entries(Q.squares || {}).map(([from, id]) => ({ from, id })), terms: [], merges_left: [], left_out: [], tasks: Q.tasks || {} }
|
|
2035
|
-
}
|
|
2036
|
-
try {
|
|
2037
|
-
return { ...quilt, ...await this.quiltSwitch(a, seam, { date }) }
|
|
2038
|
-
} catch (err) {
|
|
2039
|
-
const e = new Error(`${err.message}. The session is the quilt ${quilt.slug} now, with its files still on its branches: make it a quilt again to move them into its squares`)
|
|
2040
|
-
e.quilt_id = quilt.quilt_id
|
|
2041
|
-
throw e
|
|
2042
|
-
}
|
|
2043
|
-
}
|
|
2044
|
-
|
|
2045
|
-
/**
|
|
2046
|
-
* "Make this a quilt" on a session with a git remote (quilt-remote.js): each click takes the next
|
|
2047
|
-
* step from where the session stands. Nothing moves in git but what Seam's own export pushes after
|
|
2048
|
-
* the cut-over, and the room stays a git-mode session until the move with history, which is
|
|
2049
|
-
* quiltMigrateWithHistory (its own checks undo it, back to layout 2, if it fails). What only the
|
|
2050
|
-
* repository's GitHub owner can do (install Seam's app, add the ruleset) is said as plain steps.
|
|
2051
|
-
*/
|
|
2052
|
-
async quiltMakeWithRemote (a, seam, { date = new Date() } = {}) {
|
|
2053
|
-
const no = quiltPlanRefusal({ controlled: this.controlled, access: a })
|
|
2054
|
-
if (no) throw new Error(no.replace('see what making it a quilt would do', 'make it a quilt'))
|
|
2055
|
-
const repo = (this.meta.quiltImport && this.meta.quiltImport.repo) || githubRepoOf(this.meta.upstreams, this.defaultKey)
|
|
2056
|
-
const stage = remoteStage(this.meta)
|
|
2057
|
-
if (stage === 'import') {
|
|
2058
|
-
if (!repo) throw new Error('this session\'s git remote is not on GitHub, so Seam cannot import it from here: import it with follow yourself (seam import git <url> --into <slug> --follow), then link the session to it (quilt session migrate --shadow <slug>) and click Make this a quilt again')
|
|
2059
|
-
const gh = seam.github ? await seam.github() : null
|
|
2060
|
-
if (!gh || gh.configured === false) throw new Error('Seam has no GitHub app set up, so it cannot import this session\'s repository yet')
|
|
2061
|
-
const inst = installationFor(gh, repo)
|
|
2062
|
-
if (!inst) throw stepsError(`Seam can't read ${repo} for you yet. To let it:`, installSteps(repo, gh.app && gh.app.install_url))
|
|
2063
|
-
if (this.quiltMoving) throw new Error('this session is already being moved')
|
|
2064
|
-
let r
|
|
2065
|
-
const name = repo.split('/')[1].toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'repo'
|
|
2066
|
-
try { r = await seam.importGithub({ installation_id: inst.id, repo, follow: true, slug: name }) } catch (err) {
|
|
2067
|
-
if (err.status !== 409) throw new Error(`Seam did not start importing ${repo}: ${err.message}`)
|
|
2068
|
-
r = await seam.importGithub({ installation_id: inst.id, repo, follow: true, slug: `${name}-${this.name.toLowerCase().replace(/[^a-z0-9-]/g, '-')}`.slice(0, 60) })
|
|
2069
|
-
}
|
|
2070
|
-
this.meta.quiltImport = { id: r.id, slug: r.slug || '', repo, installation: inst.id, at: new Date(date).toISOString(), by: (a && (a.sub || a.key || a.name)) || '' }
|
|
2071
|
-
this.saveMeta()
|
|
2072
|
-
this.broadcastBranches()
|
|
2073
|
-
return { stage: 'importing', import: { id: r.id, slug: r.slug || '', repo, state: r.state || 'reading' }, text: `Seam is importing ${repo} into the quilt ${r.slug || ''} and follows it from now on. Your git remote, clones and CI keep working as they are. Click Make this a quilt again once the import follows (a large repository takes a while).` }
|
|
2074
|
-
}
|
|
2075
|
-
if (stage === 'link') {
|
|
2076
|
-
const imp = this.meta.quiltImport
|
|
2077
|
-
const st = await seam.importStatus(imp.id)
|
|
2078
|
-
if (st.state === 'failed') {
|
|
2079
|
-
// A failed import is no use to the session: forgotten here, so the next click starts again.
|
|
2080
|
-
delete this.meta.quiltImport; this.saveMeta(); this.broadcastBranches()
|
|
2081
|
-
throw new Error(`Seam's import of ${imp.repo} failed (${st.error || 'no reason given'}). Click Make this a quilt again to start it over.`)
|
|
2082
|
-
}
|
|
2083
|
-
if (st.state !== 'following') return { stage: 'importing', import: { id: imp.id, slug: imp.slug, repo: imp.repo, state: st.state, commits: st.commits || 0 }, text: `Seam is still importing ${imp.repo} (${st.state}${st.commits ? `, ${st.commits} commits so far` : ''}). Click again in a while.` }
|
|
2084
|
-
await this.quiltShadowLink(a, seam, imp.id)
|
|
2085
|
-
return { stage: 'ready', import: { id: imp.id, slug: imp.slug, repo: imp.repo, state: st.state }, steps: rulesetSteps(imp.repo), text: [`Seam follows ${imp.repo} now, and this session reads its history from the quilt ${imp.slug}. Git stays the authority until you move the session in.`, `Before the move, only Seam may push to main on GitHub. ${imp.repo}'s GitHub owner does this once:`, ...rulesetSteps(imp.repo).map((x, i) => `${i + 1}. ${x}`)].join('\n') }
|
|
2086
|
-
}
|
|
2087
|
-
// The cut-over sitting (16 step 3): only after main takes pushes from Seam's export alone.
|
|
2088
|
-
const id = (this.meta.quiltImport && this.meta.quiltImport.id) || this.meta.quiltShadow.id
|
|
2089
|
-
const st = await seam.importStatus(id).catch((err) => { if (err.status === 404) return null; throw err })
|
|
2090
|
-
if (st && st.state === 'following') {
|
|
2091
|
-
if (repo) {
|
|
2092
|
-
const rules = await this.githubRulesOf(repo, 'main')
|
|
2093
|
-
if (rules === null) throw stepsError(`Quilt could not read ${repo}'s rules for main on GitHub, so it can't tell whether only Seam may push there. Check with the repository's GitHub owner:`, rulesetSteps(repo))
|
|
2094
|
-
if (!mainGuarded(rules)) throw stepsError(`Anyone can still push to main on ${repo}, so a push could land after the move and Seam's export would stop. ${repo}'s GitHub owner does this first:`, rulesetSteps(repo))
|
|
2095
|
-
}
|
|
2096
|
-
try { await seam.cutover(id, {}) } catch (err) {
|
|
2097
|
-
if (err.code === 'remote_moved' || /remote_moved|the remote's/.test(String(err.message))) throw new Error(`Someone pushed to ${repo || 'the remote'} since Seam last looked (${err.message}). Wait for the last pushes and CI to finish, then click Move into Seam now again.`)
|
|
2098
|
-
throw new Error(`Seam did not cut the import over: ${err.message}`)
|
|
2099
|
-
}
|
|
2100
|
-
} else if (st && st.state !== 'done') throw new Error(`Seam's import is ${st.state}, not following: ${st.error || 'see seam import status'}`)
|
|
2101
|
-
const moved = await this.quiltMigrateWithHistory(a, seam, { date })
|
|
2102
|
-
if (this.meta.quiltImport) { delete this.meta.quiltImport; this.saveMeta() }
|
|
2103
|
-
return { ...moved, cut_over: true }
|
|
2104
|
-
}
|
|
2105
|
-
|
|
2106
|
-
/**
|
|
2107
|
-
* GitHub's rules for `branch` of `repo` (owner/name): an array, or null when GitHub could not be
|
|
2108
|
-
* asked. Read without a token: Quilt no longer holds GitHub credentials, so a private repository's are not read (null).
|
|
2109
|
-
*/
|
|
2110
|
-
async githubRulesOf (repo, branch) {
|
|
2111
|
-
if (this.githubRules) return this.githubRules(repo, branch)
|
|
2112
|
-
try {
|
|
2113
|
-
const res = await globalThis.fetch(`https://api.github.com/repos/${repo}/rules/branches/${encodeURIComponent(branch)}`, { headers: { accept: 'application/vnd.github+json', 'user-agent': 'quilt-relay' } })
|
|
2114
|
-
if (!res.ok) return null
|
|
2115
|
-
const rules = await res.json()
|
|
2116
|
-
return Array.isArray(rules) ? rules : null
|
|
2117
|
-
} catch { return null }
|
|
2118
|
-
}
|
|
2119
|
-
|
|
2120
|
-
/**
|
|
2121
|
-
* quiltSwitch's work, inside the room's migration lease. `into` ({ id, quilt }): the quilt the
|
|
2122
|
-
* room becomes as layout 3 is written (the move with history), else the room's own.
|
|
2123
|
-
*/
|
|
2124
|
-
async quiltSwitchNow (a, seam, { date = new Date(), into = null } = {}) {
|
|
2125
|
-
const q = into ? into.id : this.meta.quilt_id
|
|
2126
|
-
const Q = into ? into.quilt : this.meta.quilt
|
|
2127
|
-
const move = this.meta.quiltMove || this.startQuiltMove(q)
|
|
2128
|
-
const made = []
|
|
2129
|
-
const unwatch = []
|
|
2130
|
-
let adoption = null
|
|
2131
|
-
const by = (a && (a.name || a.sub || a.key)) || ''
|
|
2132
|
-
try {
|
|
2133
|
-
// A branch's files over its square's head (branchFiles): binaries, and what the session never synced, are not deletions.
|
|
2134
|
-
// A square that starts at main's tip for want of the branch's commit keeps main's files the branch never had.
|
|
2135
|
-
const atTip = new Set((Q.basedAtTip || []).map((b) => b.from))
|
|
2136
|
-
const texts = (key, tree) => {
|
|
2137
|
-
const e = this.store.load(key)
|
|
2138
|
-
return e ? branchFiles(e.doc, tree, { diff: isDiff(e), unheld: atTip.has(key) }) : {}
|
|
2139
|
-
}
|
|
2140
|
-
// A full document's older copies of main's files were told apart by git's history of main, which the relay no longer keeps.
|
|
2141
|
-
const mainsOld = async (key, files) => files
|
|
2142
|
-
// Members keep writing their branch documents until layout 3 is written: an edit from now on
|
|
2143
|
-
// (before its files are read, or after) marks its branch, so the copy is made again from what
|
|
2144
|
-
// it holds then and checked with no wait between (the catch-up below). Watched from before any
|
|
2145
|
-
// read: an edit between a read and the copy once failed the check and undid the move.
|
|
2146
|
-
const edits = new Map()
|
|
2147
|
-
const watch = (key) => {
|
|
2148
|
-
if (edits.has(key)) return edits.get(key)
|
|
2149
|
-
const flag = { edited: false }
|
|
2150
|
-
edits.set(key, flag)
|
|
2151
|
-
const e = this.store.load(key)
|
|
2152
|
-
if (e && e.doc) { const mark = () => { flag.edited = true }; e.doc.on('update', mark); unwatch.push(() => e.doc.off('update', mark)) }
|
|
2153
|
-
return flag
|
|
2154
|
-
}
|
|
2155
|
-
for (const key of [this.defaultKey, ...Object.keys(Q.squares || {})]) if (this.meta.branches[key] && !isLiveKey(key)) watch(key)
|
|
2156
|
-
const held = (from) => new Set(((Q.merges && Q.merges.terms) || []).filter((t) => t.from === from).map((t) => t.path))
|
|
2157
|
-
const without = (o, skip) => Object.fromEntries(Object.entries(o).filter(([p]) => !skip.has(p)))
|
|
2158
|
-
const plan = []
|
|
2159
|
-
for (const [key, sq] of Object.entries(Q.squares || {})) {
|
|
2160
|
-
if (key === this.defaultKey || !this.meta.branches[key] || isLiveKey(key)) continue
|
|
2161
|
-
const s = await seam.square(q, sq)
|
|
2162
|
-
const head = s.head || s.base || null
|
|
2163
|
-
const skip = held(key)
|
|
2164
|
-
const t = head ? await seam.tree(q, head) : null
|
|
2165
|
-
plan.push({ key, sq, head, skip, answer: t, flag: watch(key), files: without(await mainsOld(key, texts(key, t), treeIds(t)), skip), tree: without(treeIds(t), skip), modes: treeModes(t) })
|
|
2166
|
-
}
|
|
2167
|
-
const mainTree = Q.patch ? await seam.tree(q, Q.patch.commit) : null
|
|
2168
|
-
const main = treeIds(mainTree)
|
|
2169
|
-
const def = texts(this.defaultKey, mainTree)
|
|
2170
|
-
const adopt = overlayFor(def, main)
|
|
2171
|
-
// A large file in the session's storage that main lacks: the folders that have it put it there.
|
|
2172
|
-
const defaultLarge = [...this.store.load(this.defaultKey).blobs].some(([p, x]) => x && typeof x.data !== 'string' && !x.blob && !main[p])
|
|
2173
|
-
if (Object.keys(adopt.puts).length || adopt.gone.length || defaultLarge) {
|
|
2174
|
-
const s = await seam.openSquare(q, { title: `Uncommitted work from ${this.name}`.slice(0, 200) })
|
|
2175
|
-
adoption = s.id
|
|
2176
|
-
move.opened.push(s.id)
|
|
2177
|
-
this.stillHere()
|
|
2178
|
-
this.saveMeta()
|
|
2179
|
-
plan.push({ key: this.defaultKey, sq: s.id, head: (Q.patch && Q.patch.commit) || null, skip: new Set(), answer: mainTree, flag: watch(this.defaultKey), files: def, tree: main, modes: treeModes(mainTree) })
|
|
2180
|
-
}
|
|
2181
|
-
// A boxed file (a member's unfinished work the session held while every other folder kept git's
|
|
2182
|
-
// copy) is the box holder's whole file, on the main they had: only its change goes onto the head.
|
|
2183
|
-
const rebased = []
|
|
2184
|
-
const boxesOnto = (p) => {
|
|
2185
|
-
const out = {}
|
|
2186
|
-
for (const [file, v] of Object.entries(p.boxes || {})) {
|
|
2187
|
-
const t = typeof p.files[file] === 'string' ? boxOntoHead(p.files[file], v.head, v.versions) : null
|
|
2188
|
-
if (t !== null) { out[file] = t; p.files[file] = t }
|
|
2189
|
-
}
|
|
2190
|
-
return out
|
|
2191
|
-
}
|
|
2192
|
-
for (const p of plan) {
|
|
2193
|
-
p.boxes = {}
|
|
2194
|
-
for (const c of Object.values(this.meta.boxes || {})) {
|
|
2195
|
-
const file = c && c.box && (this.branchOf(c) || this.defaultKey) === p.key ? String(c.pattern || '') : ''
|
|
2196
|
-
if (!file || /[*?[]/.test(file) || typeof p.files[file] !== 'string' || !p.head || !p.tree[file] || p.tree[file] === blobId(Buffer.from(p.files[file]))) continue
|
|
2197
|
-
const v = await this.versionsOnLine(seam, q, p.head, file, p.tree[file]).catch(() => null)
|
|
2198
|
-
if (v) p.boxes[file] = v
|
|
2199
|
-
}
|
|
2200
|
-
p.boxTexts = boxesOnto(p)
|
|
2201
|
-
for (const file of Object.keys(p.boxTexts)) rebased.push({ branch: p.key, path: file })
|
|
2202
|
-
}
|
|
2203
|
-
if (rebased.length) this.log(`[${this.name}] the move puts ${rebased.length} boxed file(s) onto main's newer copy as their change only: ${rebased.map((x) => x.path).slice(0, 10).join(', ')}`)
|
|
2204
|
-
// A small binary a branch changed goes to Seam first: its live entry names the blob.
|
|
2205
|
-
const uploaded = new Set()
|
|
2206
|
-
const upload = async (p) => {
|
|
2207
|
-
const up = binariesToUpload(p.files, p.tree).filter((b) => !uploaded.has(b.id))
|
|
2208
|
-
if (up.length) await seam.upload(q, up)
|
|
2209
|
-
for (const b of up) uploaded.add(b.id)
|
|
2210
|
-
return up.length
|
|
2211
|
-
}
|
|
2212
|
-
for (const p of plan) await upload(p)
|
|
2213
|
-
this.stillHere()
|
|
2214
|
-
for (const p of plan) {
|
|
2215
|
-
const lk = liveKey(p.sq)
|
|
2216
|
-
if (this.meta.branches[lk] && this.store.load(lk) && liveMaps(this.store.load(lk).doc).live.size) throw new Error(`square ${squareShort(p.sq)} already has a live document on the relay`)
|
|
2217
|
-
made.push(lk)
|
|
2218
|
-
move.made.push(lk)
|
|
2219
|
-
this.noteBranch(lk, { by })
|
|
2220
|
-
// A copy of the branch's Y.Doc, so the edit history inside it survives (16), made an overlay over the square's head.
|
|
2221
|
-
const from = this.store.load(p.key)
|
|
2222
|
-
copyIntoLive(this.store.load(lk).doc, from.doc, { files: p.files, head: p.tree, modes: p.modes, commit: p.head, by, skip: p.skip })
|
|
2223
|
-
writeIntoLive(this.store.load(lk).doc, p.boxTexts, p.tree, p.head)
|
|
2224
|
-
}
|
|
2225
|
-
const check = (p) => {
|
|
2226
|
-
const bad = checkOverlay(this.store.load(liveKey(p.sq)).doc, p.files, p.tree)
|
|
2227
|
-
if (bad) throw new Error(`the check after copying ${p.key === this.defaultKey ? 'the default branch' : p.key} failed: ${bad}`)
|
|
2228
|
-
}
|
|
2229
|
-
// A branch edited since its files were read is copied and checked again in the catch-up below.
|
|
2230
|
-
for (const p of plan) if (!p.flag.edited) check(p)
|
|
2231
|
-
// Every person in the session writes in every square, not only the holder who moved it, so their AIs (working for them) commit there too.
|
|
2232
|
-
const people = [...Object.entries(this.meta.members || {}).map(([key, m]) => ({ key, role: m && m.role })), ...(this.meta.ownerSub ? [{ key: this.meta.ownerSub, role: 'editor' }] : [])]
|
|
2233
|
-
const notShared = []
|
|
2234
|
-
if (seam.share) {
|
|
2235
|
-
for (const p of plan) {
|
|
2236
|
-
try { for (const x of await shareWithPeople(seam, q, p.sq, people)) notShared.push({ square: p.sq, ...x }) } catch (err) { notShared.push({ square: p.sq, member: '', why: String(err.message || err).slice(0, 200) }) }
|
|
2237
|
-
}
|
|
2238
|
-
}
|
|
2239
|
-
this.stillHere()
|
|
2240
|
-
// Edits that reached a branch document while the move waited on Seam go into its square too,
|
|
2241
|
-
// copied again and checked with no wait between the last copy and layout 3 (a new binary is
|
|
2242
|
-
// uploaded first, then the branches are looked at again).
|
|
2243
|
-
for (let round = 0; ; round++) {
|
|
2244
|
-
// `stale`: read again but not copied yet (a binary had to go to Seam first, or another edit came).
|
|
2245
|
-
const edited = plan.filter((p) => p.flag.edited || p.stale)
|
|
2246
|
-
if (!edited.length) break
|
|
2247
|
-
if (round >= MOVE_CATCH_UP_ROUNDS) throw new Error('edits kept arriving while the session moved; try again when it is quieter')
|
|
2248
|
-
let waited = 0
|
|
2249
|
-
for (const p of edited) { p.flag.edited = false; p.stale = true; p.files = without(await mainsOld(p.key, texts(p.key, p.answer), treeIds(p.answer)), p.skip); p.boxTexts = boxesOnto(p); waited += await upload(p) }
|
|
2250
|
-
this.stillHere()
|
|
2251
|
-
// Copied only from files read since the branch's last edit: an edit during the reads looks again.
|
|
2252
|
-
if (waited || edited.some((p) => p.flag.edited)) continue
|
|
2253
|
-
for (const p of edited) {
|
|
2254
|
-
copyIntoLive(this.store.load(liveKey(p.sq)).doc, this.store.load(p.key).doc, { files: p.files, head: p.tree, modes: p.modes, commit: p.head, by, skip: p.skip })
|
|
2255
|
-
writeIntoLive(this.store.load(liveKey(p.sq)).doc, p.boxTexts, p.tree, p.head)
|
|
2256
|
-
check(p)
|
|
2257
|
-
p.stale = false
|
|
2258
|
-
}
|
|
2259
|
-
}
|
|
2260
|
-
Q.live = Object.fromEntries(plan.map((p) => [p.key, liveKey(p.sq)]))
|
|
2261
|
-
// Large files in the session's storage that git's head lacks: the relay can't read their bytes,
|
|
2262
|
-
// so they are not in the squares yet; each folder that has them puts them in when it follows.
|
|
2263
|
-
const large = []
|
|
2264
|
-
for (const p of plan) {
|
|
2265
|
-
for (const [path, x] of this.store.load(p.key).blobs) if (x && typeof x.data !== 'string' && !x.blob && !p.tree[path] && !p.skip.has(path)) large.push({ branch: p.key, path, size: Number(x.size) || 0 })
|
|
2266
|
-
}
|
|
2267
|
-
if (large.length) Q.large = large
|
|
2268
|
-
if (adoption) Q.adoption = adoption
|
|
2269
|
-
Q.layoutAt = new Date(date).toISOString()
|
|
2270
|
-
// Git's bookkeeping leaves the room (16: dropped), kept for a rollback.
|
|
2271
|
-
Q.kept = takeGitMeta(this.meta)
|
|
2272
|
-
if (into) { this.meta.quilt_id = into.id; this.meta.quilt = Q; delete this.meta.quiltShadow }
|
|
2273
|
-
delete this.meta.quiltMove
|
|
2274
|
-
this.meta.layout = LAYOUT_QUILT // last
|
|
2275
|
-
this.saveMeta()
|
|
2276
|
-
for (const ws of [...this.conns.keys(), ...this.pending.keys()]) {
|
|
2277
|
-
if (!ws.hosted && !this.supported(ws)) { ws.endReason = 'needs_update'; ws.close(CLOSE_NEEDS_UPDATE, this.needsUpdate()) }
|
|
2278
|
-
}
|
|
2279
|
-
this.broadcastBranches()
|
|
2280
|
-
return { layout: LAYOUT_QUILT, live: Q.live, adoption, ...(rebased.length ? { rebased } : {}), ...(large.length ? { large } : {}), ...(notShared.length ? { not_shared: notShared } : {}) }
|
|
2281
|
-
} catch (err) {
|
|
2282
|
-
if (adoption && seam.abandon) await seam.abandon(q, adoption, { reason: 'the session\'s move into its squares was undone' }).catch(() => {})
|
|
2283
|
-
for (const lk of made) this.removeBranch(lk)
|
|
2284
|
-
if (made.length) this.broadcastBranches()
|
|
2285
|
-
if (!into) this.endQuiltMove()
|
|
2286
|
-
throw new Error(`Migration undone: ${err.message}. The session stays as it was.`)
|
|
2287
|
-
} finally {
|
|
2288
|
-
for (const off of unwatch) off()
|
|
2289
|
-
}
|
|
2290
|
-
}
|
|
2291
|
-
|
|
2292
|
-
/**
|
|
2293
|
-
* A branch's square merged, and Seam never changes a merged square again: the branch moves to a
|
|
2294
|
-
* new square on the same line, opened as the member asking (`seam` acting as them) and shared
|
|
2295
|
-
* with the merged one's holder and people writers, and its live document carries on from the old
|
|
2296
|
-
* one (carryLive: what the merge has leaves, later work stays), so every folder on the branch
|
|
2297
|
-
* keeps working. Any editor may ask; a square still open is left as it is. One move at a time.
|
|
2298
|
-
*/
|
|
2299
|
-
async quiltNext (a, seam, branch) {
|
|
2300
|
-
// A move running now (going back, say) settles first: a branch moves on from where it leaves the session.
|
|
2301
|
-
if (this.quiltMoving && this.quiltMoved) await this.quiltMoved
|
|
2302
|
-
if (this.meta.layout !== LAYOUT_QUILT) throw new Error('this session\'s files are not in squares')
|
|
2303
|
-
if (!a || a.role === 'viewer') throw new Error('only someone who may change files moves a branch to its next square')
|
|
2304
|
-
const key = String(branch || '')
|
|
2305
|
-
const run = async () => {
|
|
2306
|
-
if (this.meta.layout !== LAYOUT_QUILT) throw new Error('this session\'s files are not in squares')
|
|
2307
|
-
const q = this.meta.quilt_id
|
|
2308
|
-
// A read token gone or about to end is made again by whoever moves on, when Seam lets them (an admin).
|
|
2309
|
-
const rt = await this.freshReadToken(seam, q, this.meta.quilt.read, { probe: false }).catch(() => null)
|
|
2310
|
-
if (rt && rt.renewed) this.takeReadToken(rt.read)
|
|
2311
|
-
const lk = (this.meta.quilt.live || {})[key]
|
|
2312
|
-
if (!isLiveKey(lk)) throw new Error(`${key || 'that branch'} has no square in this session`)
|
|
2313
|
-
const old = lk.slice(liveKey('').length)
|
|
2314
|
-
const s = await seam.square(q, old)
|
|
2315
|
-
if (!s || s.state === 'open' || s.state === 'merging') return { square: old, moved: false }
|
|
2316
|
-
const n = await seam.openSquare(q, { title: String(s.title || `Work in ${this.name}`).replace(/^(Follow-up: )+/, '').slice(0, 200), line: (s.merged && s.merged.line) || s.line || 'main' })
|
|
2317
|
-
for (const m of new Set([s.holder, ...(s.writers || [])])) {
|
|
2318
|
-
if (m && m !== n.holder && String(m).startsWith('person:') && seam.share) await seam.share(q, n.id, { member: m }).catch(() => {})
|
|
2319
|
-
}
|
|
2320
|
-
const head = n.base || n.head || null
|
|
2321
|
-
let tree = {}
|
|
2322
|
-
try { if (head) tree = treeIds(await seam.tree(q, head)) } catch (err) { await this.abandonOpened(seam, q, n.id); throw err }
|
|
2323
|
-
// Going back started while this waited on Seam (quiltUnswitch waits for it): the square it opened goes.
|
|
2324
|
-
if (this.meta.layout !== LAYOUT_QUILT || this.quiltMoving) { await this.abandonOpened(seam, q, n.id); throw new Error('the session is going back to its branches') }
|
|
2325
|
-
const nk = liveKey(n.id)
|
|
2326
|
-
const by = (a && (a.name || a.sub || a.key)) || ''
|
|
2327
|
-
this.noteBranch(nk, { by })
|
|
2328
|
-
carryLive(this.store.load(nk).doc, this.store.load(lk).doc, { head: tree, commit: head, by })
|
|
2329
|
-
this.meta.quilt.live = { ...this.meta.quilt.live, [key]: nk }
|
|
2330
|
-
// A folder still on the old square for a moment (it has not heard yet) keeps typing there: its edits go on to this one (handle, movedOnTo).
|
|
2331
|
-
this.meta.quilt.next = Object.fromEntries([...Object.entries(this.meta.quilt.next || {}), [lk, nk]].slice(-MOVED_ON_KEPT))
|
|
2332
|
-
this.saveMeta()
|
|
2333
|
-
this.broadcastBranches()
|
|
2334
|
-
return { square: n.id, moved: true, from: old }
|
|
2335
|
-
}
|
|
2336
|
-
if (!this.quiltNexts) this.quiltNexts = new Map()
|
|
2337
|
-
const was = this.quiltNexts.get(key) || Promise.resolve()
|
|
2338
|
-
const p = was.catch(() => {}).then(run)
|
|
2339
|
-
this.quiltNexts.set(key, p)
|
|
2340
|
-
try { return await p } finally { if (this.quiltNexts.get(key) === p) this.quiltNexts.delete(key) }
|
|
2341
|
-
}
|
|
2342
|
-
|
|
2343
|
-
/**
|
|
2344
|
-
* Bringing main in (source-live/bring-in.js): a member's app asks, as that member (`seam`), each time
|
|
2345
|
-
* it checks its folder's square (session-follow.js catchUp). When main moved past the square's base,
|
|
2346
|
-
* the square takes main's new patches: Seam rebases its commits, and its live document moves onto the
|
|
2347
|
-
* new head with each file it changed combined three ways. Seam's server never moves a square by
|
|
2348
|
-
* itself (06): one of its members does, the holder first, and a writer once the holder's app has not
|
|
2349
|
-
* asked for a while (offline). One at a time per branch, with its moves (quiltNext). Answers
|
|
2350
|
-
* { square, behind, conflicted?, waiting?, brought? }.
|
|
2351
|
-
*/
|
|
2352
|
-
async quiltCatchUp (a, seam, branch, { by = '' } = {}) {
|
|
2353
|
-
if (this.meta.layout !== LAYOUT_QUILT) throw new Error('this session\'s files are not in squares')
|
|
2354
|
-
// Boxes the relay kept from before the session's files went into squares only showed people
|
|
2355
|
-
// holding files whose work had long landed (2026-11-05: 11 of Daniel's, handed on from Moss in October).
|
|
2356
|
-
const switched = Date.parse((this.meta.quilt || {}).layoutAt || '')
|
|
2357
|
-
if (switched && Object.values(this.meta.boxes || {}).some((c) => c && Number(c.ts) < switched)) {
|
|
2358
|
-
this.dropBoxes((c) => !!c && Number(c.ts) < switched)
|
|
2359
|
-
this.saveMeta()
|
|
2360
|
-
this.broadcastBoxes()
|
|
2361
|
-
}
|
|
2362
|
-
const key = String(branch || '')
|
|
2363
|
-
const lk = (this.meta.quilt.live || {})[key]
|
|
2364
|
-
if (!isLiveKey(lk)) throw new Error(`${key || 'that branch'} has no square in this session`)
|
|
2365
|
-
const id = lk.slice(liveKey('').length)
|
|
2366
|
-
const q = this.meta.quilt_id
|
|
2367
|
-
const sq = await seam.square(q, id)
|
|
2368
|
-
const answer = (more = {}) => ({ square: id, behind: (sq && sq.behind_by) || 0, ...(sq && sq.conflicted_paths ? { conflicted: sq.conflicted_paths } : {}), ...more })
|
|
2369
|
-
const e = this.store.load(lk)
|
|
2370
|
-
// A square merged from outside the folders (by hand in Seam, another tool, the website): the branch
|
|
2371
|
-
// moves on to its next square, as after a merge from the app (quiltNext), so every folder on it
|
|
2372
|
-
// follows main again (2026-11-05: a hand merge left three folders on a finished square).
|
|
2373
|
-
if (sq && (sq.state === 'merged' || sq.state === 'folded') && a && a.role !== 'viewer') {
|
|
2374
|
-
const n = await this.quiltNext(a, seam, key).catch(() => null)
|
|
2375
|
-
if (n && n.moved) return { square: n.square, behind: 0, moved: true, from: id }
|
|
2376
|
-
}
|
|
2377
|
-
if (!sq || sq.state !== 'open' || !e) return answer({ behind: 0 })
|
|
2378
|
-
if (!this.catchUps) this.catchUps = new Map()
|
|
2379
|
-
if (!sq.behind_by && liveHead(e.doc) === (sq.head || sq.base)) { this.catchUps.delete(id); return answer() }
|
|
2380
|
-
if (!a || a.role === 'viewer') return answer()
|
|
2381
|
-
let st = this.catchUps.get(id)
|
|
2382
|
-
if (!st) this.catchUps.set(id, (st = { since: Date.now() }))
|
|
2383
|
-
const me = await seam.quilt(q).then((x) => (x && x.you && x.you.member_id) || null, () => null)
|
|
2384
|
-
const holder = !!me && me === sq.holder
|
|
2385
|
-
const wait = this.catchUpWaitMs ?? HOLDER_WAIT_MS
|
|
2386
|
-
if (holder) st.holderAt = Date.now()
|
|
2387
|
-
else if (Date.now() - st.since < wait || (st.holderAt && Date.now() - st.holderAt < wait)) return answer({ waiting: sq.holder_name || sq.holder || 'its holder' })
|
|
2388
|
-
const run = () => this.bringMainIn(seam, q, key, lk, st, by)
|
|
2389
|
-
if (!this.quiltNexts) this.quiltNexts = new Map()
|
|
2390
|
-
const was = this.quiltNexts.get(key) || Promise.resolve()
|
|
2391
|
-
const p = was.catch(() => {}).then(run)
|
|
2392
|
-
this.quiltNexts.set(key, p)
|
|
2393
|
-
try { return await p } catch (err) {
|
|
2394
|
-
// The holder's app could not (its Seam sign-in, say): a writer's goes next time it asks.
|
|
2395
|
-
if (holder) st.holderAt = 0
|
|
2396
|
-
throw err
|
|
2397
|
-
} finally { if (this.quiltNexts.get(key) === p) this.quiltNexts.delete(key) }
|
|
2398
|
-
}
|
|
2399
|
-
|
|
2400
|
-
/**
|
|
2401
|
-
* The folders on square `lk` too old to follow its base moving (a Quilt before 0.3.133: it never
|
|
2402
|
-
* re-projected, nor said which head an edit was made on, so it would write the old base's files back
|
|
2403
|
-
* into the square): their people's names. A folder is known to follow a moving base by `quilt-moves`
|
|
2404
|
-
* (protocol.js), or by its app having asked to bring main in (0.3.133 and 0.3.134 do, every minute).
|
|
2405
|
-
*/
|
|
2406
|
-
outdatedOn (lk) {
|
|
2407
|
-
const out = new Set()
|
|
2408
|
-
for (const ws of this.conns.keys()) {
|
|
2409
|
-
if (ws.branch !== lk || (ws.features || []).includes('quilt-moves')) continue
|
|
2410
|
-
const name = this.names.get(ws) || ''
|
|
2411
|
-
if (this.movesApps && this.movesApps.has(appOf(ws, name))) continue
|
|
2412
|
-
out.add(name || 'someone')
|
|
2413
|
-
}
|
|
2414
|
-
return [...out].sort()
|
|
2415
|
-
}
|
|
2416
|
-
|
|
2417
|
-
/** quiltCatchUp's work, its turn come: the square read again, its live conflicts committed first, Seam's rebase, the live move. */
|
|
2418
|
-
async bringMainIn (seam, q, key, lk, st, by) {
|
|
2419
|
-
if (this.meta.layout !== LAYOUT_QUILT || (this.meta.quilt.live || {})[key] !== lk || this.quiltMoving) return { square: lk.slice(liveKey('').length), behind: 0 }
|
|
2420
|
-
const id = lk.slice(liveKey('').length)
|
|
2421
|
-
const sq = await seam.square(q, id)
|
|
2422
|
-
if (!sq || sq.state !== 'open') return { square: id, behind: 0 }
|
|
2423
|
-
// Main waits while a folder on the square can't follow its base moving: it would put the old base's
|
|
2424
|
-
// copies back as its edits (2026-11-01). It comes in once that app is updated, or leaves the square.
|
|
2425
|
-
const outdated = sq.behind_by ? this.outdatedOn(lk) : []
|
|
2426
|
-
if (outdated.length) return { square: id, behind: sq.behind_by, outdated }
|
|
2427
|
-
const doc = this.store.load(lk).doc
|
|
2428
|
-
const done = (more = {}) => ({ square: id, behind: 0, ...more })
|
|
2429
|
-
// The live document is not on the square's head (a commit's seal on its way, or lost with a relay
|
|
2430
|
-
// restart): given a moment, it moves onto it, combined, as after a rebase.
|
|
2431
|
-
if (liveHead(doc) !== (sq.head || sq.base)) {
|
|
2432
|
-
st.stale = st.stale || Date.now()
|
|
2433
|
-
if (Date.now() - st.stale < (this.catchUpWaitMs ?? HOLDER_WAIT_MS) / 5) return { square: id, behind: sq.behind_by || 0, waiting: 'a commit' }
|
|
2434
|
-
await this.moveSquareLive(seam, q, lk, doc, { prev: liveHead(doc), head: sq.head || sq.base, base: !sq.head, by })
|
|
2435
|
-
st.stale = 0
|
|
2436
|
-
}
|
|
2437
|
-
if (!sq.behind_by) { this.catchUps.delete(id); return done() }
|
|
2438
|
-
// An older copy of main's file in the live work is nobody's edit: main's stands, never a "conflict" with main.
|
|
2439
|
-
const stale = await staleAhead(seam, q, sq, doc, sq.line || 'main').catch((err) => { this.log(`[${this.name}] could not look for older copies of main's files in square ${squareShort(id)}: ${err.message}`); return [] })
|
|
2440
|
-
if (stale.length) {
|
|
2441
|
-
standHead(doc, stale, liveHead(doc))
|
|
2442
|
-
this.log(`[${this.name}] square ${squareShort(id)}: ${stale.length} live file(s) were older copies of main's, not edits; main's stand (${stale.slice(0, 5).join(', ')}${stale.length > 5 ? ', …' : ''})`)
|
|
2443
|
-
}
|
|
2444
|
-
// Work edited on an older copy of main's file is put onto the square's copy first: main's newer lines are nobody's deletion.
|
|
2445
|
-
// Files the project marks merge=union (its .gitattributes) combine like RELEASES.md: both sides stay.
|
|
2446
|
-
const marked = await unionMarked(seam, q, sq.line || 'main')
|
|
2447
|
-
const older = await olderCopiesAhead(seam, q, sq, doc, sq.line || 'main', { marked }).catch((err) => { this.log(`[${this.name}] could not look for work made on older copies of main's files in square ${squareShort(id)}: ${err.message}`); return [] })
|
|
2448
|
-
if (older.length) this.log(`[${this.name}] square ${squareShort(id)}: ${older.length} live file(s) were edited on an older copy of main's; their edits were put onto the square's copy (${older.slice(0, 5).join(', ')}${older.length > 5 ? ', …' : ''})`)
|
|
2449
|
-
const ahead = await conflictsAhead(seam, q, sq, doc, sq.line || 'main', { marked })
|
|
2450
|
-
const head = ahead.length ? await commitAhead(seam, q, sq, doc, ahead, by) : sq.head
|
|
2451
|
-
const r = await seam.rebase(q, id, { expect_head: head || null })
|
|
2452
|
-
if (r.noop || !r.square) { this.catchUps.delete(id); return done() }
|
|
2453
|
-
const to = r.square.head || r.square.base
|
|
2454
|
-
const terms = [...new Set([...(r.terms || []).map((t) => t.path), ...ahead])]
|
|
2455
|
-
const m = await this.moveSquareLive(seam, q, lk, doc, { prev: head || sq.base, head: to, base: !r.square.head, by, marked, brought: { patches: sq.behind_by, conflicts: terms, ...(stale.length ? { stale: stale.slice(0, 50) } : {}) } })
|
|
2456
|
-
this.catchUps.delete(id)
|
|
2457
|
-
this.log(`[${this.name}] brought ${sq.behind_by} patch(es) of ${sq.line || 'main'} into square ${squareShort(id)} as ${by || 'a member'}${m.combined.length ? `, combining ${m.combined.length} live file(s)` : ''}${terms.length ? `; ${terms.length} conflict(s) kept in the square` : ''}`)
|
|
2458
|
-
return done({ brought: { patches: sq.behind_by, combined: m.combined, conflicts: [...new Set([...terms, ...m.conflicts])], ...(stale.length ? { stale: stale.slice(0, 50) } : {}) }, ...(r.square.conflicted_paths ? { conflicted: r.square.conflicted_paths } : {}) })
|
|
2459
|
-
}
|
|
2460
|
-
|
|
2461
|
-
/**
|
|
2462
|
-
* A member's app tells its own person something Quilt did with their square's work by itself
|
|
2463
|
-
* (session-follow.js: their version of a file kept in a square of its own when main's change won
|
|
2464
|
-
* the same lines): a note from Quilt in chat, to them alone. Nobody else is told.
|
|
2465
|
-
*/
|
|
2466
|
-
quiltNote (ws, req) {
|
|
2467
|
-
const a = this.access.get(ws)
|
|
2468
|
-
const name = this.names.get(ws)
|
|
2469
|
-
if (!a || a.role === 'viewer' || (a.state && a.state !== 'approved') || !name) throw new Error('only a member who may change files is told about their square')
|
|
2470
|
-
const text = String(req.text || '').trim().slice(0, 1000)
|
|
2471
|
-
if (!text) throw new Error('a note needs its words')
|
|
2472
|
-
const m = this.postChat({ by: 'Quilt', to: name, text, kind: 'note' })
|
|
2473
|
-
return { ok: true, message: m.id }
|
|
2474
|
-
}
|
|
2475
|
-
|
|
2476
|
-
/** A square's live document moved onto `head` (bring-in.js moveLive), late edits made on the old head combined after (lateEdits). */
|
|
2477
|
-
async moveSquareLive (reader, q, lk, doc, opts) {
|
|
2478
|
-
const r = await moveLive(reader, q, doc, opts)
|
|
2479
|
-
if (!this.lateMoves) this.lateMoves = new Map()
|
|
2480
|
-
if (this.lateMoves.has(lk)) this.lateMoves.get(lk)()
|
|
2481
|
-
this.lateMoves.set(lk, lateEdits(doc, { from: opts.prev, to: opts.head, read: sideReader(this.quiltReadClient() || reader, q) }))
|
|
2482
|
-
return r
|
|
2483
|
-
}
|
|
2484
|
-
|
|
2485
|
-
/**
|
|
2486
|
-
* A folder's live block asks (live-block.js moveTo): Seam moved its square's head itself (seam_rebase,
|
|
2487
|
-
* a settled conflict, a merge that kept its conflict), and the live document follows, its files
|
|
2488
|
-
* combined with what the move changed, read with the room's read token.
|
|
2489
|
-
*/
|
|
2490
|
-
async liveMove (ws, req) {
|
|
2491
|
-
const key = this.resolveKey(String(req.branch || ''))
|
|
2492
|
-
if (!isLiveKey(key) || !(process.env.QUILT_SOURCE || this.meta.layout === LAYOUT_QUILT)) throw new Error('only a square\'s live document moves')
|
|
2493
|
-
const e = key === ws.branch ? this.store.get(key) : null
|
|
2494
|
-
if (!e) throw new Error(`you are not on ${req.branch}`)
|
|
2495
|
-
const a = this.access.get(ws)
|
|
2496
|
-
if (!a || a.role === 'viewer') throw new Error('only someone who may change files moves a square\'s live work')
|
|
2497
|
-
const head = String(req.head || '')
|
|
2498
|
-
if (!/^[0-9a-f]{64}$/.test(head)) throw new Error('move needs the square\'s new head')
|
|
2499
|
-
const prev = liveHead(e.doc)
|
|
2500
|
-
if (req.prev && req.prev !== prev) throw new Error(`the square's live head is ${String(prev || 'not set').slice(0, 12)}, not ${String(req.prev).slice(0, 12)}: read it again`)
|
|
2501
|
-
if (prev === head) return { head, moved: false }
|
|
2502
|
-
const by = this.names.get(ws) || ''
|
|
2503
|
-
// Squares in a session that is not a quilt (QUILT_SOURCE alone) have no read token to read the move with: the live work moves as it is.
|
|
2504
|
-
if (this.meta.layout !== LAYOUT_QUILT) { seal(e.doc, { prev, head, by }); if (req.base) liveMaps(e.doc).live.set('head', { commit: head, by, ts: Date.now(), base: true }); return { head, moved: true } }
|
|
2505
|
-
const reader = this.quiltReadClient()
|
|
2506
|
-
if (!reader) { this.readTokenRefused(); throw new Error(this.noReadToken()) }
|
|
2507
|
-
const r = await this.moveSquareLive(reader, this.meta.quilt_id, key, e.doc, { prev, head, base: !!req.base, by })
|
|
2508
|
-
return { head, moved: true, combined: r.combined, conflicts: r.conflicts }
|
|
2509
|
-
}
|
|
2510
|
-
|
|
2511
|
-
/** A square a branch move opened that the session no longer wants (it went back meanwhile), abandoned in Seam. */
|
|
2512
|
-
async abandonOpened (seam, q, id) {
|
|
2513
|
-
if (seam.abandon) await seam.abandon(q, id, { reason: 'the session went back to its branches while it opened' }).catch(() => {})
|
|
2514
|
-
}
|
|
2515
|
-
|
|
2516
|
-
/**
|
|
2517
|
-
* A branch with no square at layout 3 (the default branch when it equalled main's tip and held no
|
|
2518
|
-
* box, so the move opened no adoption square; a branch made after a quilt was made without
|
|
2519
|
-
* history; a branch checked out in git after the move, which the relay has no copy of): its folders' writes reach only its read-only document, so the first member who writes
|
|
2520
|
-
* there asks for one (`quilt-open`, the app's readOnly answer). It is opened as that member (its
|
|
2521
|
-
* holder), at the commit the branch document is of (the move's base for it: its ref's imported
|
|
2522
|
-
* commit, else the quilt's patch at the move, never main's tip now, which would undo what merged
|
|
2523
|
-
* since), the branch document copied into its live document and checked as the move does, and
|
|
2524
|
-
* every folder on the branch follows it; the asker's refused edits go in as theirs.
|
|
2525
|
-
*/
|
|
2526
|
-
async quiltOpen (a, seam, branch) {
|
|
2527
|
-
if (this.meta.layout !== LAYOUT_QUILT) throw new Error('this session\'s files are not in squares')
|
|
2528
|
-
if (!a || a.role === 'viewer') throw new Error('only someone who may change files opens a square for a branch')
|
|
2529
|
-
if (this.quiltMoving && this.quiltMoved) await this.quiltMoved
|
|
2530
|
-
if (this.meta.layout !== LAYOUT_QUILT) throw new Error('this session\'s files are not in squares')
|
|
2531
|
-
const key = this.resolveKey(String(branch || ''))
|
|
2532
|
-
if (!key || isLiveKey(key) || !validBranchKey(key)) throw new Error(`"${String(key).slice(0, 60)}" isn't a branch name`)
|
|
2533
|
-
const run = async () => {
|
|
2534
|
-
if (this.meta.layout !== LAYOUT_QUILT) throw new Error('this session\'s files are not in squares')
|
|
2535
|
-
const Q = this.meta.quilt
|
|
2536
|
-
const q = this.meta.quilt_id
|
|
2537
|
-
const rt = await this.freshReadToken(seam, q, Q.read, { probe: false }).catch(() => null)
|
|
2538
|
-
if (rt && rt.renewed) this.takeReadToken(rt.read)
|
|
2539
|
-
if ((Q.live || {})[key]) return { square: Q.live[key].slice(liveKey('').length), opened: false }
|
|
2540
|
-
// A branch the relay has no copy of (checked out in git after the move): a square at main's tip
|
|
2541
|
-
// with nothing in it, held by the asker; their app takes the folder in as it is (folderWins).
|
|
2542
|
-
if (!this.meta.branches[key]) {
|
|
2543
|
-
const s = await seam.openSquare(q, { title: `${key} in ${this.name}`.slice(0, 200) })
|
|
2544
|
-
if (this.meta.layout !== LAYOUT_QUILT || this.quiltMoving) { await this.abandonOpened(seam, q, s.id); throw new Error('the session is going back to its branches') }
|
|
2545
|
-
const by = (a && (a.name || a.sub || a.key)) || ''
|
|
2546
|
-
const lk = liveKey(s.id)
|
|
2547
|
-
this.noteBranch(lk, { by })
|
|
2548
|
-
startHead(this.store.load(lk).doc, s.head || s.base, by)
|
|
2549
|
-
Q.live = { ...Q.live, [key]: lk }
|
|
2550
|
-
Q.opened = [...(Q.opened || []), { from: key, id: s.id, by, at: new Date().toISOString(), fresh: true }]
|
|
2551
|
-
this.saveMeta()
|
|
2552
|
-
this.broadcastBranches()
|
|
2553
|
-
this.log(`[${this.name}] opened square ${squareShort(s.id)} at main's tip for ${key}, a branch the session had no copy of (asked by ${by || 'a member'})`)
|
|
2554
|
-
return { square: s.id, opened: true, fresh: true }
|
|
2555
|
-
}
|
|
2556
|
-
const want = squareBase(key, { ...this.meta, ...(Q.kept || {}) }) || (Q.patch && Q.patch.commit) || null
|
|
2557
|
-
let s
|
|
2558
|
-
try { s = await seam.openSquare(q, { title: (key === this.defaultKey ? `Work on ${key} in ${this.name}` : String(key)).slice(0, 200), ...(want ? { base: want } : {}) }) } catch (err) {
|
|
2559
|
-
if (!want || err.status !== 404) throw err
|
|
2560
|
-
s = await seam.openSquare(q, { title: String(key).slice(0, 200), ...(Q.patch && Q.patch.commit && want !== Q.patch.commit ? { base: Q.patch.commit } : {}) })
|
|
2561
|
-
}
|
|
2562
|
-
const head = s.head || s.base || null
|
|
2563
|
-
const by = (a && (a.name || a.sub || a.key)) || ''
|
|
2564
|
-
const lk = liveKey(s.id)
|
|
2565
|
-
try {
|
|
2566
|
-
const t = head ? await seam.tree(q, head) : null
|
|
2567
|
-
const e = this.store.load(key)
|
|
2568
|
-
const files = branchFiles(e.doc, t, { diff: isDiff(e) })
|
|
2569
|
-
const tree = treeIds(t)
|
|
2570
|
-
const up = binariesToUpload(files, tree)
|
|
2571
|
-
if (up.length) await seam.upload(q, up)
|
|
2572
|
-
if (this.meta.layout !== LAYOUT_QUILT || this.quiltMoving) throw new Error('the session is going back to its branches')
|
|
2573
|
-
this.noteBranch(lk, { by })
|
|
2574
|
-
copyIntoLive(this.store.load(lk).doc, e.doc, { files, head: tree, modes: treeModes(t), commit: head, by })
|
|
2575
|
-
const bad = checkOverlay(this.store.load(lk).doc, files, tree)
|
|
2576
|
-
if (bad) throw new Error(`the check after copying ${key} failed: ${bad}`)
|
|
2577
|
-
} catch (err) {
|
|
2578
|
-
if (this.meta.branches[lk]) this.removeBranch(lk)
|
|
2579
|
-
if (seam.abandon) await seam.abandon(q, s.id, { reason: 'opening it for the branch failed' }).catch(() => {})
|
|
2580
|
-
throw err
|
|
2581
|
-
}
|
|
2582
|
-
Q.live = { ...Q.live, [key]: lk }
|
|
2583
|
-
Q.opened = [...(Q.opened || []), { from: key, id: s.id, by, at: new Date().toISOString() }]
|
|
2584
|
-
this.saveMeta()
|
|
2585
|
-
this.broadcastBranches()
|
|
2586
|
-
this.log(`[${this.name}] opened square ${squareShort(s.id)} for ${key}, which had none (asked by ${by || 'a member'})`)
|
|
2587
|
-
return { square: s.id, opened: true }
|
|
2588
|
-
}
|
|
2589
|
-
// One square per branch: an ask while one opens waits for it, and finds it open.
|
|
2590
|
-
if (!this.quiltNexts) this.quiltNexts = new Map()
|
|
2591
|
-
const was = this.quiltNexts.get(key) || Promise.resolve()
|
|
2592
|
-
const p = was.catch(() => {}).then(run)
|
|
2593
|
-
this.quiltNexts.set(key, p)
|
|
2594
|
-
try { return await p } finally { if (this.quiltNexts.get(key) === p) this.quiltNexts.delete(key) }
|
|
2595
|
-
}
|
|
2596
|
-
|
|
2597
|
-
/**
|
|
2598
|
-
* Back to layout 2 from the kept branch documents (16's rollback before R3). The squares' live
|
|
2599
|
-
* documents stay. Refused while the quilt has open squares (16: export never includes squares),
|
|
2600
|
-
* unless each is named in `carried` (its work carried over by hand, `seam diff | git apply`);
|
|
2601
|
-
* merged and abandoned squares are no longer open. Git's bookkeeping comes back, and a session
|
|
2602
|
-
* that became its import's quilt (with history) is a git-mode session shadowing it again, so its
|
|
2603
|
-
* git-mode sync resumes and agents have their git path back.
|
|
2604
|
-
*/
|
|
2605
|
-
async quiltUnswitch (a, seam, { carried = [] } = {}) {
|
|
2606
|
-
const no = quiltPlanRefusal({ controlled: this.controlled, access: a })
|
|
2607
|
-
if (no) throw new Error(no.replace('see what making it a quilt would do', 'move it back to branches'))
|
|
2608
|
-
if (this.meta.layout !== LAYOUT_QUILT) throw new Error('this session\'s files are not in squares')
|
|
2609
|
-
if (!seam) throw new Error('sign in to Seam first: going back reads the quilt\'s open squares as its owner')
|
|
2610
|
-
return this.withMigrationLease(async () => {
|
|
2611
|
-
// A branch moving on to its next square, or opening one, finishes first: it sees the move and lets go of what it opened.
|
|
2612
|
-
await Promise.allSettled([...(this.quiltNexts || new Map()).values()])
|
|
2613
|
-
const q = this.meta.quilt_id
|
|
2614
|
-
// Squares carried at an earlier rollback (a session that went back and moved again) stay carried.
|
|
2615
|
-
const before = (this.meta.quilt.shadow && this.meta.quilt.shadow.rolledBack && this.meta.quilt.shadow.rolledBack.carried) || []
|
|
2616
|
-
const was = new Set([...before, ...(this.meta.quilt.carried || []), ...(Array.isArray(carried) ? carried.map(String) : [])])
|
|
2617
|
-
const open = ((await seam.squares(q, { state: 'open' })) || []).filter((s) => s && s.state !== 'merged' && s.state !== 'abandoned')
|
|
2618
|
-
// A square is named by its id, or as Seam names it (the end of its id, sq:<8 or more>), or by a
|
|
2619
|
-
// start of it (8 or more), when that names no other open square: squares opened together share their first 8.
|
|
2620
|
-
const bare = (id) => String(id).replace(/-/g, '').toLowerCase()
|
|
2621
|
-
const fits = (id, x) => { const y = bare(x); return y.length >= 8 && (bare(id).endsWith(y) || bare(id).startsWith(y)) }
|
|
2622
|
-
const names = (s) => was.has(s.id) || [...was].some((x) => fits(s.id, x) && open.filter((o) => fits(o.id, x)).length === 1)
|
|
2623
|
-
this.stillHere()
|
|
2624
|
-
const left = open.filter((s) => !names(s))
|
|
2625
|
-
if (left.length) {
|
|
2626
|
-
throw Object.assign(new Error(`${left.length} square${left.length === 1 ? ' is' : 's are'} still open in ${this.meta.quilt.slug || q}: ${left.slice(0, 10).map((s) => `${squareShort(s.id)} "${String(s.title || '').slice(0, 60)}"`).join(', ')}${left.length > 10 ? ', …' : ''}. Merge or abandon each, or carry its work over by hand (seam diff <square> | git apply) and name it as carried.`), { open: left.map((s) => ({ id: s.id, title: s.title || '' })) })
|
|
2627
|
-
}
|
|
2628
|
-
this.meta.quilt.carried = [...was]
|
|
2629
|
-
// A square no folder follows now (its folders are offline, or gone for good: a replaced cloud
|
|
2630
|
-
// AI machine) would keep its work only on the relay: it is committed in the square, which stays
|
|
2631
|
-
// readable in Seam, and copied into its branch document (foldSquareBack). A square a folder
|
|
2632
|
-
// follows comes back through that folder (Session.leaveSquare).
|
|
2633
|
-
const kept = []
|
|
2634
|
-
for (const [key, lk] of Object.entries(this.meta.quilt.live || {})) {
|
|
2635
|
-
const on = this.store.get(lk)
|
|
2636
|
-
if (on && on.conns.size) continue
|
|
2637
|
-
const r = await this.foldSquareBack(seam, q, key, lk).catch((err) => ({ branch: key, square: lk.slice(liveKey('').length), error: err.message }))
|
|
2638
|
-
this.stillHere()
|
|
2639
|
-
if (r && (r.error || r.copied.length || r.left.length || r.uncommitted)) kept.push(r)
|
|
2640
|
-
}
|
|
2641
|
-
// Nobody follows a carried square any more (its work is back in the branches): it is abandoned.
|
|
2642
|
-
for (const s of open) if (seam.abandon) await seam.abandon(q, s.id, { reason: 'carried back to the session\'s branches (quilt session migrate --back)' }).catch(() => {})
|
|
2643
|
-
restoreGitMeta(this.meta, this.meta.quilt.kept)
|
|
2644
|
-
delete this.meta.quilt.kept
|
|
2645
|
-
this.meta.layout = 2
|
|
2646
|
-
this.meta.quilt.unswitchedAt = new Date().toISOString()
|
|
2647
|
-
let shadow = null
|
|
2648
|
-
if (this.meta.quilt.history && this.meta.quilt.shadow) {
|
|
2649
|
-
shadow = this.meta.quilt.shadow
|
|
2650
|
-
this.meta.quiltShadow = { ...shadow, rolledBack: { at: this.meta.quilt.unswitchedAt, squares: this.meta.quilt.squares, adoption: this.meta.quilt.adoption || null, carried: this.meta.quilt.carried } }
|
|
2651
|
-
delete this.meta.quilt_id
|
|
2652
|
-
delete this.meta.quilt
|
|
2653
|
-
}
|
|
2654
|
-
this.saveMeta()
|
|
2655
|
-
this.broadcastBranches()
|
|
2656
|
-
return { layout: 2, ...(shadow ? { shadow: { id: shadow.id, slug: shadow.slug || '' } } : {}), ...(kept.length ? { kept, quilt: { slug: (shadow && shadow.slug) || (this.meta.quilt && this.meta.quilt.slug) || '', id: q } } : {}) }
|
|
2657
|
-
}, seam, 'back')
|
|
2658
|
-
}
|
|
2659
|
-
|
|
2660
|
-
/**
|
|
2661
|
-
* A square's work, at going back, when no folder follows it: its live work committed in the square
|
|
2662
|
-
* as the owner (`seam`), so all of it is in Seam and readable after the square is abandoned; then
|
|
2663
|
-
* what changed in the square since its base and its branch document lacks written there
|
|
2664
|
-
* (foldBack, writeFold).
|
|
2665
|
-
* { branch, square, commit, copied: [path], left: [{ path, why }], uncommitted? } or null.
|
|
2666
|
-
*/
|
|
2667
|
-
async foldSquareBack (seam, q, key, lk) {
|
|
2668
|
-
const sq = lk.slice(liveKey('').length)
|
|
2669
|
-
const live = this.store.load(lk)
|
|
2670
|
-
const e = this.store.load(key)
|
|
2671
|
-
if (!live || !e) return null
|
|
2672
|
-
const out = { branch: key, square: sq }
|
|
2673
|
-
let head = liveHead(live.doc)
|
|
2674
|
-
const row = await seam.square(q, sq)
|
|
2675
|
-
const list = overlay(live.doc)
|
|
2676
|
-
if (list.length) {
|
|
2677
|
-
try {
|
|
2678
|
-
const uploads = list.filter((x) => x.bytes).map((x) => ({ kind: 'blob', id: blobId(x.bytes), bytes: x.bytes }))
|
|
2679
|
-
if (uploads.length) await seam.upload(q, uploads)
|
|
2680
|
-
const changes = list.map((x) => x.op === 'delete' ? { path: x.path, op: 'delete' } : { path: x.path, op: 'put', blob: entryId(x), mode: x.mode })
|
|
2681
|
-
const r = await seam.commit(q, sq, { expect_head: (row && row.head) || null, message: `Work left in this square when session ${this.name} went back to its branches`, changes })
|
|
2682
|
-
seal(live.doc, { prev: head, head: r.square.head, sealed: Object.fromEntries(list.map((x) => [x.path, entryId(x)])), by: 'Quilt' })
|
|
2683
|
-
head = r.square.head
|
|
2684
|
-
} catch (err) { out.uncommitted = String(err.message || err).slice(0, 300) }
|
|
2685
|
-
}
|
|
2686
|
-
out.commit = head
|
|
2687
|
-
const tree = head ? await seam.tree(q, head) : null
|
|
2688
|
-
const square = {}
|
|
2689
|
-
for (const t of (tree && tree.entries) || []) square[t.path] = t.term ? { term: t.term } : { blob: t.blob || null, mode: t.mode }
|
|
2690
|
-
const bytes = {}
|
|
2691
|
-
// Not committed: the live work goes over the head as it is.
|
|
2692
|
-
if (out.uncommitted) for (const x of overlay(live.doc)) { if (x.op === 'delete') delete square[x.path]; else { square[x.path] = { blob: entryId(x), mode: x.mode }; if (x.bytes) bytes[entryId(x)] = x.bytes } }
|
|
2693
|
-
// The branch document over the square's base: what the session never syncs (links, ignored and
|
|
2694
|
-
// stored files) reads as it was there, so only what changed in the square since is looked at.
|
|
2695
|
-
const base = row && row.base ? (row.base === head ? tree : await seam.tree(q, row.base)) : tree
|
|
2696
|
-
const fold = foldBack(square, branchFiles(e.doc, base, { diff: isDiff(e) }))
|
|
2697
|
-
const need = [...new Set(fold.put.map((x) => x.blob))].filter((id) => id && !bytes[id])
|
|
2698
|
-
const fetch = async (ids) => { for (const [id, b64] of Object.entries((await seam.blobs(q, ids)).blobs || {})) bytes[id] = Buffer.from(b64, 'base64') }
|
|
2699
|
-
for (let i = 0; i < need.length; i += 100) {
|
|
2700
|
-
const ids = need.slice(i, i + 100)
|
|
2701
|
-
// One too large to read whole (413) is left, named; the others come one by one.
|
|
2702
|
-
try { await fetch(ids) } catch (err) { if (err.status !== 413) throw err; for (const id of ids) await fetch([id]).catch((x) => { if (x.status !== 413) throw x }) }
|
|
2703
|
-
}
|
|
2704
|
-
const w = writeFold(e, fold, bytes, 'Quilt')
|
|
2705
|
-
if (w.done.length) this.log(`[${this.name}] going back: copied ${w.done.length} file(s) of square ${squareShort(sq)}, which no folder follows, into ${key}`)
|
|
2706
|
-
return { ...out, copied: w.done, left: [...fold.skip, ...w.left] }
|
|
2707
|
-
}
|
|
2708
|
-
|
|
2709
|
-
/**
|
|
2710
|
-
* A write to a branch document at layout 3 reached the relay: it is not kept. Its member hears
|
|
2711
|
-
* so (MSG_BRANCHES `readOnly`, at most once a minute a connection), with where the work goes now.
|
|
2712
|
-
*/
|
|
2713
|
-
refusedReadOnly (ws, key, { binaries = [], moved = false } = {}) {
|
|
2714
|
-
const now = Date.now()
|
|
2715
|
-
if (!binaries.length && ws.readOnlyToldAt && now - ws.readOnlyToldAt < READ_ONLY_TELL_MS) return
|
|
2716
|
-
ws.readOnlyToldAt = now
|
|
2717
|
-
const q = this.meta.quilt || {}
|
|
2718
|
-
const live = (q.live || {})[key]
|
|
2719
|
-
const name = q.slug || this.meta.quilt_id || ''
|
|
2720
|
-
const branch = key === this.defaultKey ? 'the main branch' : key
|
|
2721
|
-
const movedOn = live && moved ? `This session is the quilt ${name} now: what your app wrote to ${branch}'s old copy did not go into its square ${squareShort(live.replace(/^quilt\//, ''))}, which has moved on since. Your edits stay in your folder, and go in when it follows the square.` : ''
|
|
2722
|
-
const why = movedOn || (live
|
|
2723
|
-
? `This session is the quilt ${name} now: ${binaries.slice(0, 5).join(', ')} did not reach ${branch}'s square ${squareShort(live.replace(/^quilt\//, ''))} from the old copy; your folder takes ${binaries.length === 1 ? 'it' : 'them'} in when it follows the square.`
|
|
2724
|
-
: `This session is the quilt ${name} now, and ${branch} has no square yet: your edits are kept, and your app opens a square for it that your folder follows, with them.`)
|
|
2725
|
-
this.log(`[${this.name}] ${live && moved ? 'did not forward a write (the square moved on since its copy) to the square of' : live ? 'could not forward binaries to the square of' : 'kept a write to'} ${key}, which ${live ? 'has one' : 'has no square'}, from ${this.names.get(ws) || 'someone'}`)
|
|
2726
|
-
send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields(), readOnly: { branch: key, ...(live ? { square: live.replace(/^quilt\//, '') } : { noSquare: true }), why } }))
|
|
2727
|
-
}
|
|
2728
|
-
|
|
2729
|
-
/**
|
|
2730
|
-
* The live document of the square a branch moved on to from square `key` (quiltNext), the last of
|
|
2731
|
-
* a chain of moves, or null. Each was carried from the one before with its whole history
|
|
2732
|
-
* (carryLive), so an update to an old one applies to it as it is.
|
|
2733
|
-
*/
|
|
2734
|
-
movedOnTo (key) {
|
|
2735
|
-
const next = this.meta.layout === LAYOUT_QUILT && this.meta.quilt && this.meta.quilt.next
|
|
2736
|
-
if (!next || !isLiveKey(key) || !next[key]) return null
|
|
2737
|
-
let to = key
|
|
2738
|
-
for (let i = 0; i < MOVED_ON_KEPT && next[to]; i++) to = next[to]
|
|
2739
|
-
return to === key ? null : this.store.load(to).doc
|
|
2740
|
-
}
|
|
2741
|
-
|
|
2742
|
-
/**
|
|
2743
|
-
* Which files `ws` may change in a late write the relay applies to a square's live document itself
|
|
2744
|
-
* (forwardToSquare, movedOnTo), where the guard (checkChange) never looks: none for a viewer,
|
|
2745
|
-
* only those inside their folders for a member limited to folders (session-access.js mayChange).
|
|
2746
|
-
*/
|
|
2747
|
-
forwardRule (ws) {
|
|
2748
|
-
const a = this.access.get(ws)
|
|
2749
|
-
return (p) => this.mayWrite(a, p)
|
|
2750
|
-
}
|
|
2751
|
-
|
|
2752
|
-
/**
|
|
2753
|
-
* A write to `key`'s kept document at layout 3, from an app that has not heard of its square yet:
|
|
2754
|
-
* it goes into the square's live document (forwardIntoLive). A file it deleted is gone from the
|
|
2755
|
-
* square when the square's head has it (read through the room's read token).
|
|
2756
|
-
*/
|
|
2757
|
-
forwardToSquare (ws, key, lk, update) {
|
|
2758
|
-
if (this.branchFull(lk)) { this.refusedReadOnly(ws, key, { binaries: ['your edits'] }); return }
|
|
2759
|
-
const e = this.store.load(lk)
|
|
2760
|
-
if (!e) return
|
|
2761
|
-
// Only while the square is still on the head its copy of the branch document was made over: once it
|
|
2762
|
-
// moved (main brought in, a commit, a rebase), the branch document's files are an older base's, and
|
|
2763
|
-
// a folder writing there (an app back with a stale folder) would put its older copies in as edits and
|
|
2764
|
-
// its missing files in as deletions (2026-11-01: 43 of them, from a folder at main:984). Not forwarded:
|
|
2765
|
-
// the folder's own block takes in what is its own when it follows the square (live-block.js adopt).
|
|
2766
|
-
if (copiedHead(e.doc) !== liveHead(e.doc)) { this.refusedReadOnly(ws, key, { moved: true }); return }
|
|
2767
|
-
const r = forwardIntoLive(e.doc, update, { may: this.forwardRule(ws) })
|
|
2768
|
-
if (r.refused.length) { this.log(`[${this.name}] did not take a write to ${r.refused.slice(0, 5).join(', ')} from ${this.names.get(ws) || 'someone'} into a square: not theirs to change`); return }
|
|
2769
|
-
this.log(`[${this.name}] a write to ${key} from ${this.names.get(ws) || 'someone'} went into its square ${squareShort(lk.slice(liveKey('').length))}`)
|
|
2770
|
-
if (r.binaries.length) this.refusedReadOnly(ws, key, { binaries: r.binaries })
|
|
2771
|
-
if (!r.deleted.length) return
|
|
2772
|
-
const head = liveHead(e.doc)
|
|
2773
|
-
if (!head) return
|
|
2774
|
-
this.quiltBlockRead({ call: 'tree', rev: head, paths: r.deleted }).then(({ tree }) => {
|
|
2775
|
-
const m = liveMaps(e.doc)
|
|
2776
|
-
const have = new Set(((tree && tree.entries) || []).map((x) => x.path))
|
|
2777
|
-
e.doc.transact(() => {
|
|
2778
|
-
for (const p of r.deleted) if (have.has(p) && !m.files.has(p) && !m.blobs.has(p)) { m.clean.delete(p); m.gone.set(p, { by: this.names.get(ws) || '', ts: Date.now() }) }
|
|
2779
|
-
}, 'relay-quilt')
|
|
2780
|
-
}, (err) => this.log(`[${this.name}] could not read ${squareShort(lk.slice(liveKey('').length))}'s head to delete ${r.deleted.join(', ')}: ${err.message}`))
|
|
2781
|
-
}
|
|
2782
|
-
|
|
2783
|
-
/** What an app this session can't take is told: why, and what to do (a WebSocket close reason, 123 bytes at most). */
|
|
2784
|
-
needsUpdate () { return this.meta.layout === LAYOUT_QUILT ? NEEDS_UPDATE_QUILT : NEEDS_UPDATE }
|
|
2785
|
-
|
|
2786
1271
|
/** Can this connection's app handle the session as it is now? */
|
|
2787
|
-
supported (ws) {
|
|
2788
|
-
const f = ws.features || []
|
|
2789
|
-
// At layout 3 an app's folder must follow its square (quilt-folders): 0.3.125 sent `quilts` but kept writing the read-only branch documents.
|
|
2790
|
-
if (this.meta.layout === LAYOUT_QUILT && !(f.includes('quilts') && f.includes('quilt-folders'))) return false
|
|
2791
|
-
return !this.meta.largeFiles || f.includes('large-files')
|
|
2792
|
-
}
|
|
1272
|
+
supported (ws) { return !this.meta.largeFiles || (ws.features || []).includes('large-files') }
|
|
2793
1273
|
|
|
2794
1274
|
/**
|
|
2795
1275
|
* The session now keeps large files in storage. Older apps would get
|
|
@@ -2799,7 +1279,7 @@ class Room {
|
|
|
2799
1279
|
if (this.meta.largeFiles) return
|
|
2800
1280
|
this.meta.largeFiles = true
|
|
2801
1281
|
for (const ws of [...this.conns.keys(), ...this.pending.keys()]) {
|
|
2802
|
-
if (!ws.hosted && !this.supported(ws)) { ws.endReason = 'needs_update'; ws.close(CLOSE_NEEDS_UPDATE,
|
|
1282
|
+
if (!ws.hosted && !this.supported(ws)) { ws.endReason = 'needs_update'; ws.close(CLOSE_NEEDS_UPDATE, NEEDS_UPDATE) }
|
|
2803
1283
|
}
|
|
2804
1284
|
}
|
|
2805
1285
|
|
|
@@ -3390,7 +1870,7 @@ class Room {
|
|
|
3390
1870
|
}
|
|
3391
1871
|
|
|
3392
1872
|
/**
|
|
3393
|
-
* Held conflicts nobody resolved (held.js;
|
|
1873
|
+
* Held conflicts nobody resolved (held.js; ruling 2026-10-30). Open 4 hours: the
|
|
3394
1874
|
* writer's person is told; 24: the session's owner too. Each once per record (`flagged4`, `flagged24`),
|
|
3395
1875
|
* by a direct message from Quilt, which waits in their inbox and chat until they are back. A record
|
|
3396
1876
|
* past the two-attempt budget becomes a task on the board (To do, assigned to the writer's person,
|
|
@@ -3581,8 +2061,6 @@ class Room {
|
|
|
3581
2061
|
let joined = false
|
|
3582
2062
|
let waiting = false
|
|
3583
2063
|
ws.meter = this.meter
|
|
3584
|
-
// The computer's key: an app's own connection and its folder's block share it (appOf).
|
|
3585
|
-
ws.appKey = publicKey || ''
|
|
3586
2064
|
ws.on('message', (data) => {
|
|
3587
2065
|
const buf = new Uint8Array(data)
|
|
3588
2066
|
this.meter.in(buf.length)
|
|
@@ -3611,7 +2089,7 @@ class Room {
|
|
|
3611
2089
|
// Its messages are the relay's own (relay-ask.js): nobody may write as it.
|
|
3612
2090
|
if (isRelay(name)) return ws.close(CLOSE_NAME_TAKEN, `"${RELAY_BY}" is the relay's own name; pick another name`)
|
|
3613
2091
|
// The session may have started storing files while this app signed in.
|
|
3614
|
-
if (!this.supported(ws)) return ws.close(CLOSE_NEEDS_UPDATE,
|
|
2092
|
+
if (!this.supported(ws)) return ws.close(CLOSE_NEEDS_UPDATE, NEEDS_UPDATE)
|
|
3615
2093
|
// With sign-in on, names come from accounts and can't be taken, so they aren't bound to keys.
|
|
3616
2094
|
if (!account) {
|
|
3617
2095
|
// Re-check: someone else may have taken the name while we waited.
|
|
@@ -3643,9 +2121,8 @@ class Room {
|
|
|
3643
2121
|
enter (ws, a) {
|
|
3644
2122
|
this.setAccess(ws, a)
|
|
3645
2123
|
this.noteTurns(ws, a)
|
|
3646
|
-
// Presence: an account's visit starts once it's let in (never while it waits for the owner).
|
|
3647
|
-
|
|
3648
|
-
if (ws.pass && this.presence && !ws.visit && !(ws.features || []).includes('quilt-block')) {
|
|
2124
|
+
// Presence: an account's visit starts once it's let in (never while it waits for the owner).
|
|
2125
|
+
if (ws.pass && this.presence && !ws.visit) {
|
|
3649
2126
|
ws.visit = this.presence.visitStart({ room: this.name, account: `${ws.pass.kind}:${ws.pass.sub}`, name: a.name, owner: !!a.owner, via: 'app', tool: ws.tool || '' })
|
|
3650
2127
|
// The accounts API learns who owns a session from this report, and only the owner may
|
|
3651
2128
|
// give people access there: tell it now rather than within the minute.
|
|
@@ -3670,12 +2147,10 @@ class Room {
|
|
|
3670
2147
|
join (ws, name) {
|
|
3671
2148
|
this.conns.set(ws, new Set())
|
|
3672
2149
|
this.names.set(ws, name)
|
|
3673
|
-
|
|
3674
|
-
ws.roomless = (ws.features || []).includes('quilt-block')
|
|
3675
|
-
if (!ws.roomless) send(ws, syncStep1Message(this.doc))
|
|
2150
|
+
send(ws, syncStep1Message(this.doc))
|
|
3676
2151
|
send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields() }))
|
|
3677
2152
|
const states = [...this.awareness.getStates().keys()]
|
|
3678
|
-
if (states.length
|
|
2153
|
+
if (states.length) send(ws, awarenessMessage(this.awareness, states))
|
|
3679
2154
|
send(ws, jsonMessage(MSG_CLAIMS, { claims: this.boxList(ws.branch) }))
|
|
3680
2155
|
this.touch()
|
|
3681
2156
|
}
|
|
@@ -3738,9 +2213,6 @@ class Room {
|
|
|
3738
2213
|
if (type === MSG_SYNC) {
|
|
3739
2214
|
const docId = decoding.readVarString(dec)
|
|
3740
2215
|
let doc = this.doc
|
|
3741
|
-
// A folder's live block (quilt-block) touches its square only: it may read the room's document
|
|
3742
|
-
// (its connection's sync asks), never write chat, tasks or activity there (it has no visit of its own).
|
|
3743
|
-
if (docId === ROOM_DOC && ws.roomless && decoding.peekVarUint(dec) !== syncProtocol.messageYjsSyncStep1) return
|
|
3744
2216
|
if (docId !== ROOM_DOC) {
|
|
3745
2217
|
// A connection syncs the room's document and the one branch it joined, nothing else.
|
|
3746
2218
|
// An edit it sent for the branch it just left, still in flight when the join landed
|
|
@@ -3752,20 +2224,6 @@ class Room {
|
|
|
3752
2224
|
// A branch over its size limit takes nothing new; the room and every other branch carry
|
|
3753
2225
|
// on, and nobody is disconnected for it (its members hear it in the branch list).
|
|
3754
2226
|
if (!this.unsavable && this.branchFull(k) && decoding.peekVarUint(dec) !== syncProtocol.messageYjsSyncStep1) return
|
|
3755
|
-
// Live sync stopped at the forced date (checkForcedDate): the branch documents stay as they were then. Read, never written.
|
|
3756
|
-
if (this.meta.syncStopped && !isLiveKey(k) && decoding.peekVarUint(dec) !== syncProtocol.messageYjsSyncStep1) { this.refusedSyncStopped(ws); return }
|
|
3757
|
-
// At layout 3 the work is in the squares (quiltSwitch); the branch documents are what going
|
|
3758
|
-
// back returns to. A write that still reaches one (an app that has not heard of its square
|
|
3759
|
-
// yet, or one back with edits made offline) goes into the branch's square, and stays in the
|
|
3760
|
-
// document too, so it is there on going back and every app's copy of it agrees with the
|
|
3761
|
-
// relay's. A branch with no square keeps it, and its member is told, so their app opens one
|
|
3762
|
-
// (quiltOpen copies the document, with it). Never dropped.
|
|
3763
|
-
if (this.meta.layout === LAYOUT_QUILT && !isLiveKey(k) && decoding.peekVarUint(dec) !== syncProtocol.messageYjsSyncStep1) {
|
|
3764
|
-
let update = null
|
|
3765
|
-
try { const d = decoding.clone(dec); decoding.readVarUint(d); update = decoding.readVarUint8Array(d) } catch {}
|
|
3766
|
-
const live = (this.meta.quilt && this.meta.quilt.live || {})[k]
|
|
3767
|
-
if (update && bringsNew(doc, update)) { if (live) this.forwardToSquare(ws, k, live, update); else this.refusedReadOnly(ws, k) }
|
|
3768
|
-
}
|
|
3769
2227
|
}
|
|
3770
2228
|
if (docId === ROOM_DOC ? this.full : this.unsavable) {
|
|
3771
2229
|
// Over quota: still answer "what do you have?" so people can read, but refuse new data.
|
|
@@ -3777,54 +2235,14 @@ class Room {
|
|
|
3777
2235
|
}
|
|
3778
2236
|
const enc = syncHeader(docId)
|
|
3779
2237
|
const header = encoding.length(enc)
|
|
3780
|
-
|
|
3781
|
-
const onto = docId === ROOM_DOC ? null : this.movedOnTo(this.resolveKey(docId))
|
|
3782
|
-
const took = []
|
|
3783
|
-
const take = (u) => took.push(u)
|
|
3784
|
-
if (onto) doc.on('update', take)
|
|
3785
|
-
try { syncProtocol.readSyncMessage(dec, enc, doc, ws) } finally { if (onto) doc.off('update', take) }
|
|
3786
|
-
for (const u of took) applyChecked(onto, u, this.forwardRule(ws), 'relay-quilt')
|
|
2238
|
+
syncProtocol.readSyncMessage(dec, enc, doc, ws)
|
|
3787
2239
|
if (encoding.length(enc) > header) send(ws, encoding.toUint8Array(enc))
|
|
3788
2240
|
} else if (type === MSG_BRANCH) {
|
|
3789
2241
|
let req = {}
|
|
3790
2242
|
let reply
|
|
3791
2243
|
try {
|
|
3792
2244
|
req = JSON.parse(decoding.readVarString(dec))
|
|
3793
|
-
|
|
3794
|
-
// A folder's live block whose square's head Seam moved (seam_rebase, a settled conflict): its live document follows, combined (bring-in.js moveLive).
|
|
3795
|
-
if (req.op === 'live-move') {
|
|
3796
|
-
const answer = (fields) => send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields(), reply: { id: req.id, op: req.op, ...fields } }))
|
|
3797
|
-
this.liveMove(ws, req).then((r) => answer({ ok: true, ...r }), (err) => answer({ ok: false, error: err.message }))
|
|
3798
|
-
return
|
|
3799
|
-
}
|
|
3800
|
-
// quilt_history from a folder with no Seam sign-in of its own: the quilt's log, read with the
|
|
3801
|
-
// room's read token (quiltReadClient). Any member may: the log is the session's own code.
|
|
3802
|
-
if (req.op === 'quilt-log') {
|
|
3803
|
-
const answer = (fields) => send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields(), reply: { id: req.id, op: req.op, ...fields } }))
|
|
3804
|
-
this.quiltLog(req.query && typeof req.query === 'object' ? req.query : {}).then(answer, (err) => answer({ ok: false, error: err.message }))
|
|
3805
|
-
return
|
|
3806
|
-
}
|
|
3807
|
-
// A member's folder that follows its square in place (session-follow.js) reads the square
|
|
3808
|
-
// through the relay with the same room read token, so no member needs Seam set up to follow.
|
|
3809
|
-
if (req.op === 'quilt-block') {
|
|
3810
|
-
const answer = (fields) => send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields(), reply: { id: req.id, op: req.op, ...fields } }))
|
|
3811
|
-
const a = this.access.get(ws)
|
|
3812
|
-
if (!a || (a.state && a.state !== 'approved')) return answer({ ok: false, error: 'not in this session' })
|
|
3813
|
-
// A slow or failed read is on the relay's log: a folder waiting to follow its square says only that it waits.
|
|
3814
|
-
const t0 = Date.now()
|
|
3815
|
-
this.quiltBlockRead(req).then((r) => { if (Date.now() - t0 > 5000) this.log(`[${this.name}] quilt-block ${req.call} took ${Date.now() - t0} ms`); answer({ ok: true, ...r }) }, (err) => { this.log(`[${this.name}] quilt-block ${req.call} failed after ${Date.now() - t0} ms: ${err.status ? `${err.status} ` : ''}${err.message}`); answer({ ok: false, error: err.message }) })
|
|
3816
|
-
return
|
|
3817
|
-
}
|
|
3818
|
-
// The app's History, Blame and search of a file in a linked session: the same room read token.
|
|
3819
|
-
if (req.op === 'quilt-blame' || req.op === 'quilt-search' || req.op === 'quilt-show') {
|
|
3820
|
-
const answer = (fields) => send(ws, jsonMessage(MSG_BRANCHES, { ...this.branchesFields(), reply: { id: req.id, op: req.op, ...fields } }))
|
|
3821
|
-
const a = this.access.get(ws)
|
|
3822
|
-
if (!a || (a.state && a.state !== 'approved')) return answer({ ok: false, error: 'not in this session' })
|
|
3823
|
-
const read = req.op === 'quilt-blame' ? this.quiltBlame(req.path) : req.op === 'quilt-search' ? this.quiltSearch(req.q) : this.quiltShow(req.commit, req.path)
|
|
3824
|
-
read.then(answer, (err) => answer({ ok: false, error: err.message }))
|
|
3825
|
-
return
|
|
3826
|
-
}
|
|
3827
|
-
reply = { id: req.id, op: req.op, ...(req.op === 'quilt-note' ? this.quiltNote(ws, req) : this.branchRequest(ws, req)) }
|
|
2245
|
+
reply = { id: req.id, op: req.op, ...this.branchRequest(ws, req) }
|
|
3828
2246
|
} catch (err) {
|
|
3829
2247
|
reply = { id: req.id, op: req.op, ok: false, error: err.message }
|
|
3830
2248
|
}
|
|
@@ -4015,8 +2433,6 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
4015
2433
|
// Without sign-in the limit is per address, and the message says so (as before).
|
|
4016
2434
|
const TOO_MANY = passKey ? 'too many new sessions; try again later' : 'too many new sessions from this address; try again later'
|
|
4017
2435
|
if (dataDir) fs.mkdirSync(dataDir, { recursive: true })
|
|
4018
|
-
// The relay's leases (relay-lease.js: one layout move per room): in the accounts API when this relay has one, else in this process.
|
|
4019
|
-
const leases = leaseKeeper({ apiUrl: cfg.apiUrl, secret: cfg.relayApiSecret, fetch: opts.apiFetch || globalThis.fetch, dataDir, log, ...(cfg.leaseTtlMs ? { ttlMs: cfg.leaseTtlMs } : {}), ...(cfg.leaseMarginMs !== undefined ? { marginMs: cfg.leaseMarginMs } : {}), holder: `relay:${cc.machineId || os.hostname()}:${process.pid}`.slice(0, 100) })
|
|
4020
2436
|
// Whether the accounts API has workspaces on, for hosted agents' library tools: asked in
|
|
4021
2437
|
// the background (never holding up the start) and again every 10 minutes.
|
|
4022
2438
|
const apiFetch = opts.apiFetch || globalThis.fetch
|
|
@@ -4113,7 +2529,6 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
4113
2529
|
if (tooBigToLoad(name)) return null
|
|
4114
2530
|
try {
|
|
4115
2531
|
room = new Room(name, dataDir, cfg, log)
|
|
4116
|
-
room.leases = leases
|
|
4117
2532
|
room.cluster = cluster
|
|
4118
2533
|
room.dataDirOf = dataDir
|
|
4119
2534
|
room.blobStore = store
|
|
@@ -4428,18 +2843,16 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
4428
2843
|
room.released = true // no save after this: the copy here is on its way to another machine
|
|
4429
2844
|
rooms.delete(name)
|
|
4430
2845
|
}
|
|
4431
|
-
/** The room is leaving this machine: refused from now on, saved, unloaded
|
|
2846
|
+
/** The room is leaving this machine: refused from now on, saved, unloaded. */
|
|
4432
2847
|
const letRoomGo = (name) => {
|
|
4433
2848
|
cluster.release(name)
|
|
4434
2849
|
unloadForMove(name)
|
|
4435
|
-
leases.forget(name)
|
|
4436
2850
|
if (hostedTimer) { clearTimeout(hostedTimer); writeHosted() }
|
|
4437
2851
|
log(`cluster: letting ${name} go to another machine`)
|
|
4438
2852
|
}
|
|
4439
2853
|
/** The room lives on `to` now: this machine's copy goes (never its large files in shared storage). */
|
|
4440
2854
|
const forgetRoomHere = (name, to) => {
|
|
4441
2855
|
unloadForMove(name)
|
|
4442
|
-
leases.forget(name)
|
|
4443
2856
|
removeLocalRoom(dataDir, name)
|
|
4444
2857
|
for (const h of hosted.values()) if (hostedIn(h, name)) delete h.rooms[name]
|
|
4445
2858
|
saveHosted()
|
|
@@ -4603,50 +3016,6 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
4603
3016
|
json(200, { sessions })
|
|
4604
3017
|
})
|
|
4605
3018
|
}
|
|
4606
|
-
// Making a session a quilt from the accounts API (POST /v1/sessions/:room/migrate, which checked the
|
|
4607
|
-
// owner's sign-in): { room, account, dry_run } plans it; { room, account, token } makes it, as the
|
|
4608
|
-
// owner, with their Seam sign-in. The room's own owner check still applies (Room.quiltPlan).
|
|
4609
|
-
if (url.pathname === '/quilt/migrate' && req.method === 'POST') {
|
|
4610
|
-
if (!fromApi(req)) return json(401, { error: 'only the accounts API may say this' })
|
|
4611
|
-
return readJson(req, 16 * 1024, (err, b) => {
|
|
4612
|
-
if (err || !b) return json(400, { error: 'send JSON' })
|
|
4613
|
-
const name = String(b.room || '')
|
|
4614
|
-
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) return json(400, { error: 'give the room' })
|
|
4615
|
-
if (!/^[a-z]+:[A-Za-z0-9_-]{1,64}$/.test(String(b.account || ''))) return json(400, { error: 'give the account' })
|
|
4616
|
-
const api = process.env.QUILT_SOURCE_URL
|
|
4617
|
-
if (!api) return json(409, { error: 'Seam is not on for this relay, so a session cannot become a quilt here yet' })
|
|
4618
|
-
const onDisk = dataDir && fs.existsSync(path.join(dataDir, `${name}.json`))
|
|
4619
|
-
if ((!rooms.has(name) && !onDisk) || roomEnded(name)) return json(404, { error: 'no such session' })
|
|
4620
|
-
const room = getRoom(name)
|
|
4621
|
-
if (!room) return json(409, { error: 'this session is not on this relay machine' })
|
|
4622
|
-
const access = { state: 'approved', role: 'editor', scopes: [], owner: !room.controlled || room.meta.ownerSub === b.account, sub: b.account }
|
|
4623
|
-
if (room.controlled && !access.owner) return json(403, { error: 'only the session\'s owner can make it a quilt' })
|
|
4624
|
-
if (b.dry_run === true) {
|
|
4625
|
-
try {
|
|
4626
|
-
const plan = room.quiltPlan(access, b.tip && typeof b.tip === 'object' ? b.tip : null)
|
|
4627
|
-
return json(200, { ok: true, plan, text: describeQuiltPlan(plan) })
|
|
4628
|
-
} catch (e) { return json(409, { error: e.message }) }
|
|
4629
|
-
}
|
|
4630
|
-
if (!b.token || typeof b.token !== 'string') return json(400, { error: 'sign in to Seam first: making a session a quilt is done as its owner' })
|
|
4631
|
-
const seam = (room.seamClient || quiltClient)({ api, token: b.token })
|
|
4632
|
-
if (b.step === 'unswitch') {
|
|
4633
|
-
return room.quiltUnswitch(access, seam, { carried: Array.isArray(b.carried) ? b.carried.slice(0, 200) : [] }).then((r) => json(200, { ok: true, ...r }), (e) => json(409, { error: e.message, ...(e.open ? { open: e.open } : {}) }))
|
|
4634
|
-
}
|
|
4635
|
-
if (b.step === 'switch') {
|
|
4636
|
-
return room.quiltSwitch(access, seam).then((r) => json(200, { ok: true, ...r }), (e) => json(409, { error: e.message }))
|
|
4637
|
-
}
|
|
4638
|
-
if (b.step === 'make') {
|
|
4639
|
-
return room.quiltMake(access, seam).then((quilt) => json(200, { ok: true, quilt }), (e) => json(409, { error: e.message, ...(e.quilt_id ? { quilt_id: e.quilt_id } : {}), ...(e.steps ? { steps: e.steps } : {}) }))
|
|
4640
|
-
}
|
|
4641
|
-
if (b.step === 'shadow') {
|
|
4642
|
-
return room.quiltShadowLink(access, seam, b.quilt ?? null).then((r) => json(200, { ok: true, ...r }), (e) => json(409, { error: e.message }))
|
|
4643
|
-
}
|
|
4644
|
-
room.quiltMigrate(access, seam).then(
|
|
4645
|
-
(quilt) => json(200, { ok: true, quilt }),
|
|
4646
|
-
(e) => json(409, { error: e.message, ...(e.quilt_id ? { quilt_id: e.quilt_id } : {}) })
|
|
4647
|
-
)
|
|
4648
|
-
})
|
|
4649
|
-
}
|
|
4650
3019
|
// Moving a room between machines (the accounts API runs it, src/api/relay-cluster.js): the source
|
|
4651
3020
|
// lets it go, the target copies it from the source, the source forgets its copy (or takes it back).
|
|
4652
3021
|
const cm = url.pathname.match(/^\/cluster\/rooms\/([A-Za-z0-9_-]{1,64})\/(release|export|fetch|forget|restore)$/)
|
|
@@ -4911,9 +3280,9 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
4911
3280
|
if (!publicKey) return reject(socket, 400, withUpdateSteps(NEEDS_UPDATE, { ascii: true }))
|
|
4912
3281
|
const key = parsePublicKey(publicKey)
|
|
4913
3282
|
if (!person || person.length > MAX_NAME || !key) return reject(socket, 400, 'Bad name or identity key')
|
|
4914
|
-
// An app that can't sync branch documents
|
|
4915
|
-
// `quilts
|
|
4916
|
-
//
|
|
3283
|
+
// An app that can't sync branch documents is told to update. Apps from 0.3.143 on say so with the
|
|
3284
|
+
// token `quilts`, older ones with `branches` (protocol.js FEATURES: both names are kept for the apps
|
|
3285
|
+
// already in use), so either one is enough.
|
|
4917
3286
|
const features = String(url.searchParams.get('features') || '').split(',')
|
|
4918
3287
|
if (!features.includes('branches') && !features.includes('quilts')) return reject(socket, 400, withUpdateSteps(NEEDS_UPDATE, { ascii: true }))
|
|
4919
3288
|
if (roomEnded(name)) return reject(socket, 410, ENDED_MESSAGE)
|
|
@@ -4937,10 +3306,9 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
4937
3306
|
return reject(socket, auth === 'need-key' ? 403 : 401, auth === 'need-key' ? 'Relay key required to create rooms' : secret ? 'Wrong room secret' : NOT_IN_SESSION)
|
|
4938
3307
|
}
|
|
4939
3308
|
// Checked after the secret, so only members learn what the session needs.
|
|
4940
|
-
|
|
4941
|
-
if ((room.meta.largeFiles && !features.includes('large-files')) || noQuilt) {
|
|
3309
|
+
if (room.meta.largeFiles && !features.includes('large-files')) {
|
|
4942
3310
|
if (!room.conns.size && room.onEmpty) room.onEmpty() // don't keep it in memory for nobody
|
|
4943
|
-
return reject(socket, 400, withUpdateSteps(
|
|
3311
|
+
return reject(socket, 400, withUpdateSteps(NEEDS_UPDATE, { ascii: true }))
|
|
4944
3312
|
}
|
|
4945
3313
|
if (!pass && !room.keyMatches(person, publicKey)) return reject(socket, 403, nameTaken(person))
|
|
4946
3314
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
@@ -5058,16 +3426,8 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
5058
3426
|
sweep()
|
|
5059
3427
|
const sweeper = setInterval(sweep, 6 * 60 * 60 * 1000)
|
|
5060
3428
|
sweeper.unref()
|
|
5061
|
-
// The relay's leases renewed, and let go of for sessions that ended (relay-lease.js).
|
|
5062
|
-
const leaseTicker = setInterval(() => {
|
|
5063
|
-
// A migration's lease (Room.withMigrationLease) is let go of once no migration here holds it (after a crash, at the next tick).
|
|
5064
|
-
leases.tick({ ended: (name) => { if (name.startsWith(MIGRATION_LEASE)) return !migrating.has(name); const r = rooms.get(name); return !!(r && r.ended) } }).then((lost) => {
|
|
5065
|
-
for (const l of lost) { const r = rooms.get(l.room); if (r && !r.ended) { r.log(`[${r.name}] lost the live-sync lease of ${l.branch} to ${l.to || 'nobody (lapsed)'}`); r.broadcastBranches() } }
|
|
5066
|
-
}).catch((err) => log(`lease tick: ${err.message}`))
|
|
5067
|
-
}, cfg.leaseHeartbeatMs || LEASE_HEARTBEAT_MS)
|
|
5068
|
-
leaseTicker.unref()
|
|
5069
3429
|
return new Promise((resolve, reject) => {
|
|
5070
|
-
httpServer.once('error', (err) => { clearInterval(heartbeat); clearInterval(sweeper);
|
|
3430
|
+
httpServer.once('error', (err) => { clearInterval(heartbeat); clearInterval(sweeper); features?.stop(); reject(err) })
|
|
5071
3431
|
httpServer.listen(port, host, () => {
|
|
5072
3432
|
const actualPort = httpServer.address().port
|
|
5073
3433
|
resolve({
|
|
@@ -5078,7 +3438,6 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
5078
3438
|
store, // exposed for tests
|
|
5079
3439
|
presence, // exposed for tests
|
|
5080
3440
|
hosted, // exposed for tests
|
|
5081
|
-
leases, // the live-sync leases (exposed for tests)
|
|
5082
3441
|
sweepHosted: () => sweepHosted && sweepHosted(), // exposed for tests: ends quiet hosted agents' visits now
|
|
5083
3442
|
wakeHeld: (now) => wakeHeld(now), // exposed for tests: escalates held conflicts in sessions nobody has open
|
|
5084
3443
|
features, // exposed for tests
|
|
@@ -5089,7 +3448,6 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
|
|
|
5089
3448
|
if (webhooks) webhooks.close()
|
|
5090
3449
|
machineMeter.stop()
|
|
5091
3450
|
if (cluster) cluster.stop()
|
|
5092
|
-
clearInterval(leaseTicker)
|
|
5093
3451
|
clearInterval(heartbeat)
|
|
5094
3452
|
clearInterval(sweeper)
|
|
5095
3453
|
features?.stop()
|
|
@@ -5240,24 +3598,10 @@ const ENDED_MESSAGE = 'The owner ended this session'
|
|
|
5240
3598
|
// Coming back by account (no invite link) to a session that doesn't let this account in, or isn't here.
|
|
5241
3599
|
const NOT_IN_SESSION = "You aren't in this session any more. Ask its owner for an invite link"
|
|
5242
3600
|
const NEEDS_UPDATE = needsUpdateWords()
|
|
5243
|
-
// How many of a branch's moves to its next square the relay remembers, to send a late edit on (movedOnTo).
|
|
5244
|
-
const MOVED_ON_KEPT = 50
|
|
5245
|
-
// A session whose code is in Seam (layout 3) takes apps whose folders follow their squares (quilt-folders, 0.3.127).
|
|
5246
|
-
// Only what to do: an AI told the session "moved into Seam" took Seam for a way to join it.
|
|
5247
|
-
const NEEDS_UPDATE_QUILT = needsUpdateWords('0.3.127')
|
|
5248
|
-
// How many times a move copies again the branches edited while it waited on Seam before it gives up (quiltSwitchNow).
|
|
5249
|
-
const MOVE_CATCH_UP_ROUNDS = 5
|
|
5250
|
-
// How often a member is told again that a write to a read-only branch document was not kept (refusedReadOnly).
|
|
5251
|
-
const READ_ONLY_TELL_MS = 60 * 1000
|
|
5252
|
-
// A room's read token with less than this left is made again at a move, or when a branch moves on to its next square (Room.freshReadToken).
|
|
5253
|
-
const READ_TOKEN_RENEW_MS = 30 * 86400e3
|
|
5254
3601
|
const SIGN_IN = 'Update Quilt and sign in to continue'
|
|
5255
3602
|
const NOT_LET_IN = "The session owner hasn't let you in yet."
|
|
5256
3603
|
const PASS_EXPIRED = 'Your sign-in expired. Reconnecting.'
|
|
5257
3604
|
|
|
5258
|
-
/** One app on one computer, as its connections say (an app's own and its folder's block share both). */
|
|
5259
|
-
const appOf = (ws, name) => `${ws.appKey || ''}\n${name || ''}`
|
|
5260
|
-
|
|
5261
3605
|
function reject (socket, code, message) {
|
|
5262
3606
|
socket.write(`HTTP/1.1 ${code} ${message}\r\nConnection: close\r\n\r\n`)
|
|
5263
3607
|
socket.destroy()
|