From dcac7fa1ce760e67b815298555f924948d5d070e Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:26:13 +0100 Subject: [PATCH 01/66] feat: sign in to MemSync and connect a local project to a shared one [skip ci] The runtime can now talk to MemSync, the service that is to replace the Team relay. Nothing is deployed, so the two addresses it needs are empty by default, and then none of this runs. - runtime/sharing/access.ts exchanges the beta session for a ten-minute access token at memtrace.io and renews it a minute before it expires. It waits for a refresh in flight and tries once more when the refresh token was rotated while the request travelled. The session is shown only to www.memtrace.io or to this computer. - runtime/sharing/memsync speaks gRPC over Node's own HTTP/2 with a small protobuf codec, so no package is added. A test checks the hand-written shapes against the copied projects.proto and against bytes from protoc. - Sharing lists my shared projects and invitations, accepts an invitation, and records which shared project a local project's board belongs to. The board itself is not synced yet. - Every rule name MemSync refuses by has a sentence in src/sharing-refusals.ts. The same scenarios run against a stand-in service and, when MEMSYNC_SERVER_BINARY and MEMSYNC_TEST_DATABASE_URL are set, against a real memsync-server on a database of its own. The Team feature is not changed. Co-Authored-By: Claude Fable 5.2 --- runtime/app.ts | 20 + runtime/beta.ts | 33 ++ runtime/sharing/access.ts | 200 ++++++++ runtime/sharing/addresses.ts | 65 +++ runtime/sharing/memsync/grpc.ts | 318 ++++++++++++ runtime/sharing/memsync/projects-api.ts | 221 +++++++++ runtime/sharing/memsync/projects-contract.ts | 61 +++ runtime/sharing/memsync/projects.proto | 122 +++++ runtime/sharing/memsync/wire.ts | 271 +++++++++++ runtime/sharing/problems.ts | 35 ++ runtime/sharing/routes.ts | 59 +++ runtime/sharing/sharing.ts | 248 ++++++++++ src/shared.ts | 4 + src/sharing-refusals.ts | 61 +++ src/sharing.ts | 67 +++ tests/beta-access.test.ts | 67 +++ tests/sharing-access.test.ts | 320 ++++++++++++ tests/sharing-addresses.test.ts | 95 ++++ tests/sharing-grpc.test.ts | 433 +++++++++++++++++ tests/sharing-projects-api.test.ts | 263 ++++++++++ tests/sharing-real-memsync.test.ts | 169 +++++++ tests/sharing-refusals.test.ts | 60 +++ tests/sharing-runtime.test.ts | 365 ++++++++++++++ tests/sharing-wire.test.ts | 257 ++++++++++ tests/sharing.test.ts | 483 +++++++++++++++++++ tests/support/beta-session.ts | 73 +++ tests/support/memsync-owner.ts | 78 +++ tests/support/memsync-stand-in.ts | 355 ++++++++++++++ tests/support/projects-api-scenarios.ts | 342 +++++++++++++ tests/support/real-memsync.ts | 169 +++++++ 30 files changed, 5314 insertions(+) create mode 100644 runtime/sharing/access.ts create mode 100644 runtime/sharing/addresses.ts create mode 100644 runtime/sharing/memsync/grpc.ts create mode 100644 runtime/sharing/memsync/projects-api.ts create mode 100644 runtime/sharing/memsync/projects-contract.ts create mode 100644 runtime/sharing/memsync/projects.proto create mode 100644 runtime/sharing/memsync/wire.ts create mode 100644 runtime/sharing/problems.ts create mode 100644 runtime/sharing/routes.ts create mode 100644 runtime/sharing/sharing.ts create mode 100644 src/sharing-refusals.ts create mode 100644 src/sharing.ts create mode 100644 tests/sharing-access.test.ts create mode 100644 tests/sharing-addresses.test.ts create mode 100644 tests/sharing-grpc.test.ts create mode 100644 tests/sharing-projects-api.test.ts create mode 100644 tests/sharing-real-memsync.test.ts create mode 100644 tests/sharing-refusals.test.ts create mode 100644 tests/sharing-runtime.test.ts create mode 100644 tests/sharing-wire.test.ts create mode 100644 tests/sharing.test.ts create mode 100644 tests/support/beta-session.ts create mode 100644 tests/support/memsync-owner.ts create mode 100644 tests/support/memsync-stand-in.ts create mode 100644 tests/support/projects-api-scenarios.ts create mode 100644 tests/support/real-memsync.ts diff --git a/runtime/app.ts b/runtime/app.ts index 2223095..a422297 100644 --- a/runtime/app.ts +++ b/runtime/app.ts @@ -80,6 +80,12 @@ import { createMemtraceIdentityProofProvider } from "./team-identity"; import { discoverOfficialTeamService } from "./team/discovery"; import { createBetaAuthorization } from "./beta-auth"; import { MemCodeBeta, nativeBetaStorage } from "./beta"; +import { Sharing } from "./sharing/sharing"; +import { + registerSharing, + sharingSettingsSchema, + sharingSettingsToKeep, +} from "./sharing/routes"; import { ManagedMemcodeEngine } from "./managed-engine"; import { ManagedRetrievalAssistant } from "./context/managed-assistant"; import { ProductTelemetry, observeTelemetryMutation } from "./telemetry"; @@ -747,6 +753,13 @@ export async function createRuntime( } }, }); + // Sharing shows memtrace.io the same session, and holds no credential of its own. + const sharing = new Sharing({ + state, + changed, + session: () => beta!.sessionProof(), + }); + registerSharing(register, sharing, host); register("beta:status", z.undefined(), () => beta!.status()); register("beta:connect", z.undefined(), () => beta!.connect()); register("beta:cancel", z.undefined(), () => beta!.cancel()); @@ -1301,6 +1314,7 @@ export async function createRuntime( workerPermissionDefaults: workerPermissionDefaults.optional(), handoffAttribution: handoffAttributionSchema.optional(), automaticUpdateDownloads: z.boolean().optional(), + sharing: sharingSettingsSchema.optional(), memtracePath: z.string().max(1000), speechEndpoint: z.string().max(1000), speech: speechSettingsSchema.optional(), @@ -1323,6 +1337,10 @@ export async function createRuntime( .strict(), async (settings) => { localURL(settings.speechEndpoint); + const sharingSettings = sharingSettingsToKeep( + settings.sharing, + store.state.settings.sharing, + ); if (settings.contextAssistant?.enabled) { const helper = settings.contextAssistant; if (!helper.model.trim()) @@ -1397,6 +1415,7 @@ export async function createRuntime( ...settings, dshProfile, speech: settings.speech ?? store.state.settings.speech, + sharing: sharingSettings, contextAssistant: settings.contextAssistant ?? store.state.settings.contextAssistant, workerPermissionDefaults: state().settings.workerPermissionDefaults, @@ -2047,6 +2066,7 @@ export async function createRuntime( teamIdentity.cancel(); await repositories.close(); await team?.close(); + sharing.close(); await speech.close(); await retrieval.close(); await connections.close(); diff --git a/runtime/beta.ts b/runtime/beta.ts index da332b8..4848161 100644 --- a/runtime/beta.ts +++ b/runtime/beta.ts @@ -26,6 +26,13 @@ export interface BetaCredentials extends BetaBinding { signedOut?: boolean; reauthRequired?: boolean; } +/** What memtrace.io checks a session by. It is a credential: show it to memtrace.io only. */ +export interface BetaSessionProof { + refreshToken: string; + deviceId: string; + sessionId: string; + accountId: string; +} export interface BetaStoredState { configured: boolean; signedOut?: boolean; @@ -618,6 +625,32 @@ export class MemCodeBeta { MEMTRACE_ENGINEER: record.account.id, }; } + /** + * The session as memtrace.io's other endpoints check it, once a rotation in + * flight has been saved. Null when there is no session to show. + */ + async sessionProof(): Promise { + await this.initialize(); + // Rotation spends the refresh token, so the old one is refused from then on. + await this.refreshing?.catch(() => {}); + const record = this.record; + if ( + this.changing || + this.closing || + this.signedOut || + !record || + record.signedOut || + record.reauthRequired || + Date.parse(record.refreshExpiresAt) <= this.clock() + ) + return null; + return { + refreshToken: record.refreshToken, + deviceId: record.deviceId, + sessionId: record.sessionId, + accountId: record.account.id, + }; + } clearTelemetryAuthorization() { this.telemetry = undefined; } diff --git a/runtime/sharing/access.ts b/runtime/sharing/access.ts new file mode 100644 index 0000000..be3bd87 --- /dev/null +++ b/runtime/sharing/access.ts @@ -0,0 +1,200 @@ +import { BetaRequestError, boundedBetaJSON } from "../beta-auth"; +import type { BetaSessionProof } from "../beta"; +import { SharingSignedOut, SharingUnavailable } from "./problems"; + +/** Proof of who is calling, for one call to the sharing service after another. */ +export interface AccessToken { + token: string; + /** The account the sharing service will answer for. */ + accountId: string; +} + +export interface SharingAccessOptions { + /** The Memtrace sign-in, once a rotation in flight has landed. Null: nobody is signed in. */ + session(): Promise; + tokenEndpoint(): URL; + fetcher?: typeof fetch; + now?: () => number; +} + +interface HeldToken extends AccessToken { + sessionId: string; + renewAt: number; +} + +const EXCHANGE_TIMEOUT_MS = 15_000, + RENEW_AHEAD_MS = 60_000, + // The sharing service refuses a token that lives longer than this. + LONGEST_LIFE_SECONDS = 900, + LONGEST_TOKEN = 16384, + LONGEST_ACCOUNT_ID = 200; +const tokenForm = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; + +const unexpectedReply = () => + new SharingUnavailable( + "The sign-in address for sharing did not answer with an access token. Check the address in Settings.", + ); + +function refusedExchange(status: number): Error { + if (status === 401) + return new SharingSignedOut( + "Your Memtrace sign-in has ended. Sign in again to see the projects you share.", + ); + if (status === 422) + return new SharingUnavailable( + "The name or email on your Memtrace account cannot be used for sharing. Change it at memtrace.io, then try again.", + ); + if (status === 503) + return new SharingUnavailable( + "Sharing is switched off or not set up at memtrace.io right now. Try again later.", + ); + return new SharingUnavailable( + `The sign-in address for sharing answered HTTP ${status}. Check the address in Settings, or try again later.`, + ); +} + +/** Who the token says it is for. Its signature is the sharing service's to check. */ +function accountNamedIn(token: string): string { + let account: unknown; + try { + account = JSON.parse( + Buffer.from(token.split(".")[1], "base64url").toString("utf8"), + )?.sub; + } catch { + throw unexpectedReply(); + } + if ( + typeof account !== "string" || + !account || + account.length > LONGEST_ACCOUNT_ID + ) + throw unexpectedReply(); + return account; +} + +function issuedToken( + reply: any, + sentAt: number, + session: BetaSessionProof, +): HeldToken { + const token = reply?.access_token, + lifeSeconds = reply?.expires_in; + if ( + typeof token !== "string" || + token.length > LONGEST_TOKEN || + !tokenForm.test(token) || + reply.token_type !== "Bearer" || + !Number.isInteger(lifeSeconds) || + lifeSeconds <= 0 || + lifeSeconds > LONGEST_LIFE_SECONDS + ) + throw unexpectedReply(); + const accountId = accountNamedIn(token); + if (accountId !== session.accountId) + throw new SharingUnavailable( + "memtrace.io answered for another account than the one signed in here. Sign out and in again.", + ); + const lifeMs = lifeSeconds * 1000; + return { + token, + accountId, + sessionId: session.sessionId, + renewAt: sentAt + lifeMs - Math.min(RENEW_AHEAD_MS, lifeMs / 2), + }; +} + +/** + * Gets an access token for the sharing service from memtrace.io and renews it + * before it expires. The token is kept in memory only. + */ +export class SharingAccess { + private held?: HeldToken; + private exchanging?: Promise; + private readonly fetcher: typeof fetch; + private readonly now: () => number; + constructor(private readonly options: SharingAccessOptions) { + this.fetcher = options.fetcher ?? fetch; + this.now = options.now ?? Date.now; + } + + async current(): Promise { + const session = await this.options.session(); + if (!session) { + this.held = undefined; + throw new SharingSignedOut(); + } + const held = this.held; + if ( + held && + held.sessionId === session.sessionId && + this.now() < held.renewAt + ) + return { token: held.token, accountId: held.accountId }; + const fresh = await (this.exchanging ??= this.exchange(session).finally( + () => (this.exchanging = undefined), + )); + // An exchange already under way may have been for the sign-in before this one. + if (fresh.sessionId !== session.sessionId) return this.current(); + this.held = fresh; + return { token: fresh.token, accountId: fresh.accountId }; + } + + /** Call when the sharing service would not take a token, so the next call asks for another. */ + forget(token: string) { + if (this.held?.token === token) this.held = undefined; + } + + private async exchange(session: BetaSessionProof): Promise { + try { + return await this.request(session); + } catch (problem) { + if (!(problem instanceof SharingSignedOut)) throw problem; + // MemCode's own refresh may have spent that refresh token while the request travelled. + const latest = await this.options.session(); + if (!latest || latest.refreshToken === session.refreshToken) + throw problem; + return this.request(latest); + } + } + + private async request(session: BetaSessionProof): Promise { + const sentAt = this.now(); + const response = await this.send(session); + return issuedToken(await replyOf(response), sentAt, session); + } + + private async send(session: BetaSessionProof): Promise { + try { + // memtrace.io refuses a request that holds anything but these three fields. + return await this.fetcher(this.options.tokenEndpoint(), { + method: "POST", + redirect: "error", + signal: AbortSignal.timeout(EXCHANGE_TIMEOUT_MS), + headers: { + "content-type": "application/json", + accept: "application/json", + }, + body: JSON.stringify({ + refresh_token: session.refreshToken, + device_id: session.deviceId, + session_id: session.sessionId, + }), + }); + } catch { + // The failure may quote the request, so none of it is passed on. + throw new SharingUnavailable( + "memtrace.io could not be reached to sign in to sharing. Check your connection and try again.", + ); + } + } +} + +async function replyOf(response: Response): Promise { + try { + return await boundedBetaJSON(response); + } catch (failure) { + throw failure instanceof BetaRequestError + ? refusedExchange(failure.status) + : unexpectedReply(); + } +} diff --git a/runtime/sharing/addresses.ts b/runtime/sharing/addresses.ts new file mode 100644 index 0000000..499689e --- /dev/null +++ b/runtime/sharing/addresses.ts @@ -0,0 +1,65 @@ +import type { SharingSettings } from "../../src/sharing"; +import { BETA_ORIGIN } from "../beta-auth"; + +/** The two places sharing talks to, checked and ready to use. */ +export interface SharingAddresses { + memsync: URL; + tokenEndpoint: URL; +} + +const thisComputer = ["localhost", "127.0.0.1", "[::1]"]; + +function webAddress(typed: string, what: string): URL { + let address: URL; + try { + address = new URL(typed); + } catch { + throw new Error(`${what} is not a web address. Start it with https://.`); + } + if ( + !["http:", "https:"].includes(address.protocol) || + address.username || + address.password || + address.search || + address.hash + ) + throw new Error( + `${what} must be a plain https:// address, without a sign-in, a question mark or a # part.`, + ); + return address; +} + +const encryptedOrLocal = (address: URL) => + address.protocol === "https:" || thisComputer.includes(address.hostname); + +/** + * Reads where sharing lives from the settings. Null means sharing is not set up. + * Throws a sentence for the person when an address cannot be used. + */ +export function sharingAddresses( + settings: SharingSettings | undefined, +): SharingAddresses | null { + const memsyncUrl = settings?.memsyncUrl.trim() ?? "", + tokenUrl = settings?.tokenUrl.trim() ?? ""; + if (!memsyncUrl && !tokenUrl) return null; + if (!memsyncUrl || !tokenUrl) + throw new Error( + "Sharing needs both addresses: the sharing service and the sign-in address. Enter both, or leave both empty.", + ); + const memsync = webAddress(memsyncUrl, "The sharing service address"); + // Every call carries an access token, and the service itself speaks unencrypted HTTP/2. + if (!encryptedOrLocal(memsync)) + throw new Error( + "The sharing service address must start with https://. Plain http:// works only for a service on this computer.", + ); + const tokenEndpoint = webAddress(tokenUrl, "The sign-in address for sharing"); + // The only sign-in MemCode holds is a memtrace.io one. It is shown to nobody else. + if ( + tokenEndpoint.origin !== BETA_ORIGIN && + !thisComputer.includes(tokenEndpoint.hostname) + ) + throw new Error( + `MemCode shows your Memtrace sign-in only to ${new URL(BETA_ORIGIN).host}. The sign-in address for sharing must be there, or on this computer.`, + ); + return { memsync, tokenEndpoint }; +} diff --git a/runtime/sharing/memsync/grpc.ts b/runtime/sharing/memsync/grpc.ts new file mode 100644 index 0000000..4a06c71 --- /dev/null +++ b/runtime/sharing/memsync/grpc.ts @@ -0,0 +1,318 @@ +import { + connect, + constants, + type ClientHttp2Session, + type IncomingHttpHeaders, +} from "node:http2"; + +/** gRPC's status codes, by the names the protocol gives them. */ +export const grpcStatus = { + OK: 0, + CANCELLED: 1, + UNKNOWN: 2, + INVALID_ARGUMENT: 3, + DEADLINE_EXCEEDED: 4, + NOT_FOUND: 5, + ALREADY_EXISTS: 6, + PERMISSION_DENIED: 7, + RESOURCE_EXHAUSTED: 8, + FAILED_PRECONDITION: 9, + ABORTED: 10, + OUT_OF_RANGE: 11, + UNIMPLEMENTED: 12, + INTERNAL: 13, + UNAVAILABLE: 14, + DATA_LOSS: 15, + UNAUTHENTICATED: 16, +} as const; + +/** A call that did not end in a reply: the service's own status, or one this client gave it. */ +export class GrpcFailure extends Error { + constructor( + readonly code: number, + message: string, + readonly metadata: Readonly> = {}, + ) { + super(message); + this.name = "GrpcFailure"; + } +} + +export interface GrpcCall { + /** `/package.Service/Method`. */ + path: string; + request: Uint8Array; + metadata?: Record; + timeoutMs?: number; +} +export interface GrpcChannel { + /** One request, one reply. */ + unary(call: GrpcCall): Promise; + close(): void; +} +export interface GrpcChannelOptions { + /** How long an unused connection is kept. A stale one is the usual way a call hangs. */ + idleMs?: number; + maxReplyBytes?: number; +} + +const FRAME_HEADER_BYTES = 5, + NOT_COMPRESSED = 0; +const DEFAULT_TIMEOUT_MS = 10_000, + DEFAULT_IDLE_MS = 10_000, + // What a gRPC server sends at most unless it is set up otherwise. + DEFAULT_MAX_REPLY_BYTES = 4 * 1024 * 1024; + +function frame(message: Uint8Array): Buffer { + const framed = Buffer.alloc(FRAME_HEADER_BYTES + message.length); + framed[0] = NOT_COMPRESSED; + framed.writeUInt32BE(message.length, 1); + framed.set(message, FRAME_HEADER_BYTES); + return framed; +} + +/** A reply to a unary call is exactly one uncompressed message. */ +function soleMessage(body: Buffer): Uint8Array | GrpcFailure { + const unreadable = (what: string) => + new GrpcFailure( + grpcStatus.INTERNAL, + `The sharing service sent a reply that ${what}.`, + ); + if (body.length < FRAME_HEADER_BYTES) return unreadable("holds no message"); + if (body[0] !== NOT_COMPRESSED) return unreadable("is compressed"); + const length = body.readUInt32BE(1); + if (body.length < FRAME_HEADER_BYTES + length) + return unreadable("is cut short"); + if (body.length > FRAME_HEADER_BYTES + length) + return unreadable("holds more than one message"); + return new Uint8Array(body.subarray(FRAME_HEADER_BYTES)); +} + +function metadataFrom(headers: IncomingHttpHeaders | undefined) { + const metadata: Record = {}; + for (const [name, value] of Object.entries(headers ?? {})) + if (!name.startsWith(":") && value !== undefined) + metadata[name] = Array.isArray(value) ? value.join(", ") : value; + return metadata; +} + +function reasonSent(encoded: string | undefined): string { + if (!encoded) return "The sharing service turned the call down."; + try { + return decodeURIComponent(encoded); + } catch { + return encoded; + } +} + +/** What a proxy means when it answers itself, as gRPC maps HTTP statuses. */ +function statusOfHttp(http: number): number { + if (http === 401) return grpcStatus.UNAUTHENTICATED; + if (http === 403) return grpcStatus.PERMISSION_DENIED; + if (http === 404) return grpcStatus.UNIMPLEMENTED; + if ([429, 502, 503, 504].includes(http)) return grpcStatus.UNAVAILABLE; + return grpcStatus.UNKNOWN; +} + +interface Received { + headers?: IncomingHttpHeaders; + trailers?: IncomingHttpHeaders; + body: Buffer[]; + bytes: number; +} + +function withoutStatus( + headers: IncomingHttpHeaders, + metadata: Record, +) { + const http = Number(headers[":status"]); + if (http !== 200) + return new GrpcFailure( + statusOfHttp(http), + `The address answered HTTP ${http} instead of a sharing reply.`, + metadata, + ); + if (!String(headers["content-type"] ?? "").startsWith("application/grpc")) + return new GrpcFailure( + grpcStatus.UNKNOWN, + "The address answered, but it is not a sharing service.", + metadata, + ); + return new GrpcFailure( + grpcStatus.UNAVAILABLE, + "The connection was cut before the sharing service finished its answer.", + metadata, + ); +} + +function outcome({ + headers, + trailers, + body, +}: Received): Uint8Array | GrpcFailure { + if (!headers) + return new GrpcFailure( + grpcStatus.UNAVAILABLE, + "The sharing service closed the connection before it answered.", + ); + // A call that is turned down at once carries its status in the first headers. + const metadata = { ...metadataFrom(headers), ...metadataFrom(trailers) }; + const status = metadata["grpc-status"]; + if (status === undefined) return withoutStatus(headers, metadata); + const code = Number(status); + if (code === grpcStatus.OK) return soleMessage(Buffer.concat(body)); + return new GrpcFailure( + Number.isInteger(code) ? code : grpcStatus.UNKNOWN, + reasonSent(metadata["grpc-message"]), + metadata, + ); +} + +const notReached = (error: unknown) => + new GrpcFailure( + grpcStatus.UNAVAILABLE, + `The sharing service could not be reached (${ + (error as NodeJS.ErrnoException).code ?? (error as Error).message + }).`, + ); + +function exchange( + session: ClientHttp2Session, + path: string, + call: GrpcCall, + maxReplyBytes: number, +): Promise { + const timeoutMs = call.timeoutMs ?? DEFAULT_TIMEOUT_MS; + return new Promise((resolve, reject) => { + const received: Received = { body: [], bytes: 0 }; + const stream = session.request({ + ...call.metadata, + ":method": "POST", + ":path": path, + "content-type": "application/grpc", + te: "trailers", + "grpc-timeout": `${timeoutMs}m`, + }); + let finished = false; + const finish = (result: Uint8Array | GrpcFailure) => { + if (finished) return; + finished = true; + clearTimeout(deadline); + if (!(result instanceof GrpcFailure)) return resolve(result); + stream.close(constants.NGHTTP2_CANCEL); + reject(result); + }; + const deadline = setTimeout( + () => + finish( + new GrpcFailure( + grpcStatus.DEADLINE_EXCEEDED, + "The sharing service did not answer in time.", + ), + ), + timeoutMs, + ); + stream.on("response", (headers) => (received.headers = headers)); + stream.on("trailers", (trailers) => (received.trailers = trailers)); + stream.on("data", (part: Buffer) => { + received.bytes += part.length; + if (received.bytes <= maxReplyBytes + FRAME_HEADER_BYTES) + return void received.body.push(part); + finish( + new GrpcFailure( + grpcStatus.RESOURCE_EXHAUSTED, + "The sharing service sent a larger reply than MemCode reads.", + ), + ); + }); + stream.on("error", (error) => finish(notReached(error))); + stream.on("close", () => finish(outcome(received))); + stream.end(frame(call.request)); + }); +} + +/** After one of these the connection itself is in doubt, so the next call opens another. */ +const connectionInDoubt = (failure: unknown) => + failure instanceof GrpcFailure && + ( + [ + grpcStatus.UNAVAILABLE, + grpcStatus.DEADLINE_EXCEEDED, + grpcStatus.INTERNAL, + grpcStatus.UNKNOWN, + ] as number[] + ).includes(failure.code); + +/** + * gRPC over Node's own HTTP/2: `http://` is unencrypted HTTP/2, `https://` is TLS. + * One connection is opened when first needed and kept while it is in use. + */ +export function grpcChannel( + address: URL, + options: GrpcChannelOptions = {}, +): GrpcChannel { + const pathPrefix = address.pathname.replace(/\/+$/, ""); + const idleMs = options.idleMs ?? DEFAULT_IDLE_MS, + maxReplyBytes = options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES; + let session: ClientHttp2Session | undefined, + idle: ReturnType | undefined, + callsInFlight = 0, + closed = false; + const retire = (retired: ClientHttp2Session) => { + if (session === retired) session = undefined; + }; + const connected = (): ClientHttp2Session => { + if (session && !session.closed && !session.destroyed) return session; + const opened = connect(address.origin); + // Each call reports what went wrong with it; the connection only steps aside. + opened.on("error", () => retire(opened)); + opened.on("goaway", () => retire(opened)); + opened.on("close", () => retire(opened)); + session = opened; + return opened; + }; + const restWhenUnused = () => { + if (--callsInFlight > 0 || !session) return; + const resting = session; + idle = setTimeout(() => { + retire(resting); + resting.close(); + }, idleMs); + idle.unref(); + }; + return { + async unary(call) { + if (closed) + throw new GrpcFailure( + grpcStatus.CANCELLED, + "Sharing was closed before the call was made.", + ); + clearTimeout(idle); + callsInFlight++; + let using: ClientHttp2Session | undefined; + try { + using = connected(); + return await exchange( + using, + pathPrefix + call.path, + call, + maxReplyBytes, + ); + } catch (failure) { + if (using && connectionInDoubt(failure)) { + retire(using); + using.close(); + } + throw failure instanceof GrpcFailure ? failure : notReached(failure); + } finally { + restWhenUnused(); + } + }, + close() { + closed = true; + clearTimeout(idle); + session?.close(); + session = undefined; + }, + }; +} diff --git a/runtime/sharing/memsync/projects-api.ts b/runtime/sharing/memsync/projects-api.ts new file mode 100644 index 0000000..25dbe0e --- /dev/null +++ b/runtime/sharing/memsync/projects-api.ts @@ -0,0 +1,221 @@ +import type { AccessToken } from "../access"; +import { refusalNamed, SharingUnavailable } from "../problems"; +import { GrpcFailure, grpcStatus, type GrpcChannel } from "./grpc"; +import { + projectsCalls, + projectsContract, + projectsService, + type ProjectsCall, +} from "./projects-contract"; +import { + decodeMessage, + encodeMessage, + WireError, + type WireMessage, +} from "./wire"; + +export interface PersonRecord { + accountId: string; + name: string; + /** Their verified address, when they have one. */ + email?: string; +} +export interface InvitationRecord { + id: string; + projectId: string; + projectName: string; + email: string; + /** Missing once the person who invited is no longer on the project. */ + invitedBy?: PersonRecord; + sentAt: string; + expiresAt: string; +} +export interface ProjectRecord { + id: string; + name: string; + owner: PersonRecord; + guests: PersonRecord[]; + openInvitations: InvitationRecord[]; + guestLimit: number; +} + +/** The sharing service's Projects API, as far as MemCode uses it. */ +export interface ProjectsApi { + listProjects(): Promise; + listInvitations(): Promise; + getProject(projectId: string): Promise; + acceptInvitation( + projectId: string, + invitationId: string, + ): Promise; +} + +/** Where access tokens come from, and where one the service refused is handed back. */ +export interface AccessTokens { + current(): Promise; + forget(token: string): void; +} + +const REFUSAL_HEADER = "memsync-refusal"; + +const unreadable = () => + new WireError("A reply lacks something it always holds."); +const isMessage = (value: unknown): value is WireMessage => + !!value && typeof value === "object" && !Array.isArray(value); +const messages = (value: unknown) => (Array.isArray(value) ? value : []); + +function person(sent: unknown): PersonRecord { + if (!isMessage(sent) || !sent.account_id) throw unreadable(); + return { + accountId: String(sent.account_id), + name: String(sent.name), + ...(sent.email ? { email: String(sent.email) } : {}), + }; +} + +function moment(sent: unknown): string { + if (!isMessage(sent)) throw unreadable(); + const at = new Date(Number(sent.seconds) * 1000 + Number(sent.nanos) / 1e6); + if (Number.isNaN(at.getTime())) throw unreadable(); + return at.toISOString(); +} + +function invitation(sent: WireMessage): InvitationRecord { + if (!sent.id || !sent.project_id) throw unreadable(); + return { + id: String(sent.id), + projectId: String(sent.project_id), + projectName: String(sent.project_name), + email: String(sent.email), + ...(sent.invited_by ? { invitedBy: person(sent.invited_by) } : {}), + sentAt: moment(sent.sent_at), + expiresAt: moment(sent.expires_at), + }; +} + +function project(sent: WireMessage): ProjectRecord { + if (!sent.id) throw unreadable(); + return { + id: String(sent.id), + name: String(sent.name), + owner: person(sent.owner), + guests: messages(sent.guests).map(person), + openInvitations: messages(sent.open_invitations).map(invitation), + guestLimit: Number(sent.guest_limit), + }; +} + +function unavailable(failure: GrpcFailure): SharingUnavailable { + const serviceAnswered = failure.metadata["grpc-status"] !== undefined; + let sentence = + "The sharing address did not answer as a sharing service. Check it in Settings."; + if (failure.code === grpcStatus.UNAUTHENTICATED) + sentence = + "The sharing service did not accept this sign-in. Try again in a few minutes."; + else if (failure.code === grpcStatus.DEADLINE_EXCEEDED) + sentence = + "The sharing service did not answer in time. Try again in a moment."; + else if (serviceAnswered) + sentence = + "The sharing service is having trouble right now. Try again in a few minutes."; + else if (failure.code === grpcStatus.UNAVAILABLE) + sentence = + "The sharing service could not be reached. Check your connection and try again."; + return new SharingUnavailable(sentence, { cause: failure }); +} + +/** What to tell the person about a call that did not end in a reply. */ +function problemWith(call: ProjectsCall, failure: unknown): Error { + if (failure instanceof WireError) + return new SharingUnavailable( + "The sharing service sent a reply MemCode could not read. Updating MemCode may help.", + { cause: failure }, + ); + if (!(failure instanceof GrpcFailure)) return failure as Error; + const rule = failure.metadata[REFUSAL_HEADER]; + const refusal = refusalNamed(rule); + if (refusal) return refusal; + // The log keeps what the sentence leaves out: which call, and the service's own words. + console.error( + `[sharing] ${call} failed: status ${failure.code}${rule ? `, rule ${rule}` : ""}: ${failure.message}`, + ); + if (rule) + return new SharingUnavailable( + "The sharing service turned this down for a reason this version of MemCode does not know. Updating MemCode may help.", + { cause: failure }, + ); + return unavailable(failure); +} + +const signInWasRefused = (failure: unknown) => + failure instanceof GrpcFailure && + failure.code === grpcStatus.UNAUTHENTICATED && + !failure.metadata[REFUSAL_HEADER]; + +/** The Projects API over gRPC, signed in with the caller's access token. */ +export class MemsyncProjects implements ProjectsApi { + constructor( + private readonly channel: GrpcChannel, + private readonly access: AccessTokens, + private readonly timeoutMs?: number, + ) {} + + async listProjects() { + const reply = await this.call("ListProjects", {}); + return messages(reply.projects).map(project); + } + async listInvitations() { + const reply = await this.call("ListInvitations", {}); + return messages(reply.invitations).map(invitation); + } + async getProject(projectId: string) { + return project(await this.call("GetProject", { project_id: projectId })); + } + async acceptInvitation(projectId: string, invitationId: string) { + return project( + await this.call("AcceptInvitation", { + project_id: projectId, + invitation_id: invitationId, + }), + ); + } + + private async call( + name: ProjectsCall, + request: WireMessage, + ): Promise { + // A token the service refuses is replaced once: its keys or the token may have just changed. + const first = await this.attempt(name, request); + if ("reply" in first) return first.reply; + const second = await this.attempt(name, request); + if ("reply" in second) return second.reply; + throw problemWith(name, second.signInRefused); + } + + private async attempt( + name: ProjectsCall, + request: WireMessage, + ): Promise<{ reply: WireMessage } | { signInRefused: GrpcFailure }> { + const { token } = await this.access.current(); + const shapes = projectsCalls[name]; + try { + const sent = await this.channel.unary({ + path: `/${projectsService}/${name}`, + request: encodeMessage(projectsContract, shapes.request, request), + metadata: { authorization: `Bearer ${token}` }, + timeoutMs: this.timeoutMs, + }); + return { reply: decodeMessage(projectsContract, shapes.reply, sent) }; + } catch (failure) { + if (signInWasRefused(failure)) { + this.access.forget(token); + return { signInRefused: failure as GrpcFailure }; + } + const problem = problemWith(name, failure); + // A newly verified address reaches the service only in a new token. + if ("rule" in problem && problem.rule === "email_not_verified") + this.access.forget(token); + throw problem; + } + } +} diff --git a/runtime/sharing/memsync/projects-contract.ts b/runtime/sharing/memsync/projects-contract.ts new file mode 100644 index 0000000..6b2a6d1 --- /dev/null +++ b/runtime/sharing/memsync/projects-contract.ts @@ -0,0 +1,61 @@ +import type { Contract } from "./wire"; + +/** + * The part of projects.proto MemCode uses, written out by hand. A test reads + * the .proto file beside this one and fails when the two disagree, so take a + * newer contract by copying the file and following what the test says. + */ +const text = (number: number) => ({ number, kind: "string" }) as const; +const one = (number: number, message: string) => + ({ number, kind: { message } }) as const; +const many = (number: number, message: string) => + ({ number, kind: { message }, repeated: true }) as const; +const moment = "google.protobuf.Timestamp"; + +export const projectsService = "memsync.v1.Projects"; + +export const projectsContract = { + [moment]: { + seconds: { number: 1, kind: "int64" }, + nanos: { number: 2, kind: "int32" }, + }, + Person: { account_id: text(1), name: text(2), email: text(3) }, + Project: { + id: text(1), + name: text(2), + owner: one(3, "Person"), + guests: many(4, "Person"), + open_invitations: many(5, "Invitation"), + guest_limit: { number: 6, kind: "uint32" }, + }, + Invitation: { + id: text(1), + project_id: text(2), + project_name: text(3), + email: text(4), + invited_by: one(5, "Person"), + sent_at: one(6, moment), + expires_at: one(7, moment), + }, + ListProjectsRequest: {}, + ListProjectsResponse: { projects: many(1, "Project") }, + GetProjectRequest: { project_id: text(1) }, + ListInvitationsRequest: {}, + ListInvitationsResponse: { invitations: many(1, "Invitation") }, + AcceptInvitationRequest: { project_id: text(1), invitation_id: text(2) }, +} satisfies Contract; + +/** The calls MemCode makes. Starting, renaming, deleting and inviting happen at memtrace.io. */ +export const projectsCalls = { + ListProjects: { + request: "ListProjectsRequest", + reply: "ListProjectsResponse", + }, + ListInvitations: { + request: "ListInvitationsRequest", + reply: "ListInvitationsResponse", + }, + GetProject: { request: "GetProjectRequest", reply: "Project" }, + AcceptInvitation: { request: "AcceptInvitationRequest", reply: "Project" }, +} as const; +export type ProjectsCall = keyof typeof projectsCalls; diff --git a/runtime/sharing/memsync/projects.proto b/runtime/sharing/memsync/projects.proto new file mode 100644 index 0000000..7c5316b --- /dev/null +++ b/runtime/sharing/memsync/projects.proto @@ -0,0 +1,122 @@ +syntax = "proto3"; + +package memsync.v1; + +import "google/protobuf/timestamp.proto"; + +// Projects and the people on them. +// +// Every call carries the caller's Memtrace access token as +// `authorization: Bearer `. A call that is turned down returns a gRPC +// status whose `memsync-refusal` metadata names the rule that turned it down, +// so MemCode and memtrace.io can show their own wording for it. +service Projects { + // Starts a personal project owned by the caller. + rpc StartProject(StartProjectRequest) returns (Project); + // Lists the projects the caller owns or is a guest on, by name. + rpc ListProjects(ListProjectsRequest) returns (ListProjectsResponse); + // Shows one project the caller is on. + rpc GetProject(GetProjectRequest) returns (Project); + // Invites a person by email address. Only the owner can invite. + rpc InvitePerson(InvitePersonRequest) returns (Invitation); + // Lists the open invitations sent to the caller's verified email address. + rpc ListInvitations(ListInvitationsRequest) returns (ListInvitationsResponse); + // Makes the caller a guest on the project that invited them. + rpc AcceptInvitation(AcceptInvitationRequest) returns (Project); + // Takes back an invitation nobody has accepted, open or expired. Only the owner can. + rpc CancelInvitation(CancelInvitationRequest) returns (Project); + // Takes a guest off the project. Only the owner can. + rpc RemoveGuest(RemoveGuestRequest) returns (Project); + // Takes the caller off a project they are a guest on. The owner cannot leave. + rpc LeaveProject(LeaveProjectRequest) returns (LeaveProjectResponse); + // Gives the project a new name. Only the owner can. + rpc RenameProject(RenameProjectRequest) returns (Project); + // Deletes the project for everyone on it, at once and for good. Only the owner can. + rpc DeleteProject(DeleteProjectRequest) returns (DeleteProjectResponse); +} + +message Person { + string account_id = 1; + string name = 2; + // Empty until the person has verified an address at memtrace.io. + string email = 3; +} + +message Project { + string id = 1; + string name = 2; + Person owner = 3; + repeated Person guests = 4; + // Invitations that can still be accepted. + repeated Invitation open_invitations = 5; + // How many guests and open invitations the project can hold together. + uint32 guest_limit = 6; +} + +message Invitation { + string id = 1; + string project_id = 2; + string project_name = 3; + string email = 4; + Person invited_by = 5; + google.protobuf.Timestamp sent_at = 6; + google.protobuf.Timestamp expires_at = 7; +} + +message StartProjectRequest { + string name = 1; +} + +message ListProjectsRequest {} + +message ListProjectsResponse { + repeated Project projects = 1; +} + +message GetProjectRequest { + string project_id = 1; +} + +message InvitePersonRequest { + string project_id = 1; + string email = 2; +} + +message ListInvitationsRequest {} + +message ListInvitationsResponse { + repeated Invitation invitations = 1; +} + +message AcceptInvitationRequest { + string project_id = 1; + string invitation_id = 2; +} + +message CancelInvitationRequest { + string project_id = 1; + string invitation_id = 2; +} + +message RemoveGuestRequest { + string project_id = 1; + // The guest's `Person.account_id`. + string account_id = 2; +} + +message LeaveProjectRequest { + string project_id = 1; +} + +message LeaveProjectResponse {} + +message RenameProjectRequest { + string project_id = 1; + string name = 2; +} + +message DeleteProjectRequest { + string project_id = 1; +} + +message DeleteProjectResponse {} diff --git a/runtime/sharing/memsync/wire.ts b/runtime/sharing/memsync/wire.ts new file mode 100644 index 0000000..ba27614 --- /dev/null +++ b/runtime/sharing/memsync/wire.ts @@ -0,0 +1,271 @@ +/** + * Protocol Buffers (proto3) on the wire, for the kinds of field the sharing + * service's contract uses. A message is described by its shape, so the shapes + * can be checked against the .proto file in a test. + */ +export type ScalarKind = + "string" | "bytes" | "uint32" | "uint64" | "int32" | "int64"; +/** Only messages are repeated in the contract, so only they can be. */ +export type FieldShape = + | { number: number; kind: ScalarKind } + | { number: number; kind: { message: string }; repeated?: boolean }; +export type MessageShape = Record; +/** Message shapes by name. */ +export type Contract = Record; +export type WireValue = + string | number | Uint8Array | WireMessage | WireMessage[]; +export interface WireMessage { + [field: string]: WireValue | undefined; +} + +/** Bytes that are not the message they were said to be, or a value that cannot be sent. */ +export class WireError extends Error {} + +const VARINT = 0, + FIXED64 = 1, + LENGTH_DELIMITED = 2, + FIXED32 = 5; +const WIRE_TYPE_BITS = 3, + LONGEST_VARINT = 10, + TWO_TO_64 = 1n << 64n; +const utf8 = new TextDecoder("utf-8", { fatal: true }); +const ranges = { + uint32: [0, 4294967295], + uint64: [0, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + int64: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], +} as const; +type NumberKind = keyof typeof ranges; +const isNumberKind = (kind: FieldShape["kind"]): kind is NumberKind => + typeof kind === "string" && kind in ranges; +const isRepeated = (field: FieldShape) => + "repeated" in field && !!field.repeated; + +function shapeOf(contract: Contract, name: string): MessageShape { + const shape = contract[name]; + if (!shape) throw new WireError(`No shape is known for ${name}.`); + return shape; +} + +class Writer { + private readonly parts: Uint8Array[] = []; + private varint(value: bigint) { + const bytes: number[] = []; + let rest = value; + do { + const low = Number(rest & 0x7fn); + rest >>= 7n; + bytes.push(rest ? low | 0x80 : low); + } while (rest); + this.parts.push(Uint8Array.from(bytes)); + } + private tag(field: number, wireType: number) { + this.varint(BigInt((field << WIRE_TYPE_BITS) | wireType)); + } + number(field: number, value: number) { + this.tag(field, VARINT); + // A negative number travels as its 64-bit two's complement. + this.varint(value < 0 ? TWO_TO_64 + BigInt(value) : BigInt(value)); + } + bytes(field: number, value: Uint8Array) { + this.tag(field, LENGTH_DELIMITED); + this.varint(BigInt(value.length)); + this.parts.push(value); + } + finish(): Uint8Array { + return new Uint8Array(Buffer.concat(this.parts)); + } +} + +function checkedNumber( + kind: NumberKind, + value: unknown, + field: string, +): number { + const [least, most] = ranges[kind]; + if ( + !Number.isInteger(value) || + (value as number) < least || + (value as number) > most + ) + throw new WireError(`${field} is not a ${kind}.`); + return value as number; +} + +function writeField( + writer: Writer, + contract: Contract, + name: string, + { number, kind }: FieldShape, + value: WireValue, +) { + if (typeof kind !== "string") { + if ( + typeof value !== "object" || + value instanceof Uint8Array || + Array.isArray(value) + ) + throw new WireError(`${name} is not a message.`); + writer.bytes(number, encodeMessage(contract, kind.message, value)); + } else if (isNumberKind(kind)) { + if (checkedNumber(kind, value, name) !== 0) + writer.number(number, value as number); + } else if (kind === "string") { + if (typeof value !== "string") throw new WireError(`${name} is not text.`); + if (value) writer.bytes(number, new TextEncoder().encode(value)); + } else { + if (!(value instanceof Uint8Array)) + throw new WireError(`${name} is not bytes.`); + if (value.length) writer.bytes(number, value); + } +} + +/** Writes a message as the reference implementation does: fields by number, defaults left out. */ +export function encodeMessage( + contract: Contract, + message: string, + value: WireMessage, +): Uint8Array { + const writer = new Writer(); + const fields = Object.entries(shapeOf(contract, message)).sort( + ([, left], [, right]) => left.number - right.number, + ); + for (const [name, shape] of fields) { + const given = value[name]; + if (given === undefined) continue; + if (!isRepeated(shape)) writeField(writer, contract, name, shape, given); + else if (!Array.isArray(given)) + throw new WireError(`${name} is not a list.`); + else + for (const item of given) writeField(writer, contract, name, shape, item); + } + return writer.finish(); +} + +class Reader { + private at = 0; + constructor(private readonly source: Uint8Array) {} + get done() { + return this.at >= this.source.length; + } + varint(): bigint { + let value = 0n; + for (let read = 0; read < LONGEST_VARINT; read++) { + if (this.done) throw new WireError("The message ends inside a number."); + const byte = this.source[this.at++]; + value |= BigInt(byte & 0x7f) << BigInt(7 * read); + if (!(byte & 0x80)) return BigInt.asUintN(64, value); + } + throw new WireError("A number in the message never ends."); + } + take(length: number): Uint8Array { + if (length > this.source.length - this.at) + throw new WireError("The message ends inside a field."); + const taken = this.source.subarray(this.at, this.at + length); + this.at += length; + return taken; + } + delimited(): Uint8Array { + const length = this.varint(); + if (length > BigInt(this.source.length)) + throw new WireError("The message ends inside a field."); + return this.take(Number(length)); + } + skip(wireType: number) { + if (wireType === VARINT) this.varint(); + else if (wireType === FIXED64) this.take(8); + else if (wireType === LENGTH_DELIMITED) this.delimited(); + else if (wireType === FIXED32) this.take(4); + else + throw new WireError( + "The message has a field of a kind proto3 does not have.", + ); + } +} + +function numberRead(kind: NumberKind, raw: bigint, field: string): number { + const value = + kind === "int32" || kind === "int64" ? BigInt.asIntN(64, raw) : raw; + const [least, most] = ranges[kind]; + if (value < BigInt(least) || value > BigInt(most)) + throw new WireError(`${field} is out of range for a ${kind}.`); + return Number(value); +} + +function readField( + reader: Reader, + contract: Contract, + name: string, + { kind }: FieldShape, + wireType: number, +): WireValue { + const expected = isNumberKind(kind) ? VARINT : LENGTH_DELIMITED; + if (wireType !== expected) + throw new WireError(`${name} was sent as another kind of field.`); + if (isNumberKind(kind)) return numberRead(kind, reader.varint(), name); + const bytes = reader.delimited(); + if (typeof kind !== "string") + return decodeMessage(contract, kind.message, bytes); + if (kind === "bytes") return new Uint8Array(bytes); + try { + return utf8.decode(bytes); + } catch { + throw new WireError(`${name} is not text.`); + } +} + +function emptyMessage(shape: MessageShape): WireMessage { + const empty: WireMessage = {}; + for (const [name, field] of Object.entries(shape)) { + const { kind } = field; + if (isRepeated(field)) empty[name] = []; + else if (kind === "string") empty[name] = ""; + else if (kind === "bytes") empty[name] = new Uint8Array(); + else if (isNumberKind(kind)) empty[name] = 0; + } + return empty; +} + +/** + * Reads a message. Fields that were not sent read as empty, a message that was + * not sent is left out, and fields this shape does not know are skipped. + * Throws WireError, and nothing else, for bytes that are not such a message. + */ +export function decodeMessage( + contract: Contract, + message: string, + bytes: Uint8Array, +): WireMessage { + const shape = shapeOf(contract, message); + const byNumber = new Map( + Object.entries(shape).map(([name, field]) => [ + field.number, + { name, field }, + ]), + ); + const read = emptyMessage(shape); + const reader = new Reader(bytes); + while (!reader.done) { + const tag = reader.varint(); + const number = Number(tag >> BigInt(WIRE_TYPE_BITS)), + wireType = Number(tag & 7n); + if (number < 1) + throw new WireError("The message has a field without a number."); + const known = byNumber.get(number); + if (!known) { + reader.skip(wireType); + continue; + } + const value = readField( + reader, + contract, + known.name, + known.field, + wireType, + ); + if (isRepeated(known.field)) + (read[known.name] as WireMessage[]).push(value as WireMessage); + else read[known.name] = value; + } + return read; +} diff --git a/runtime/sharing/problems.ts b/runtime/sharing/problems.ts new file mode 100644 index 0000000..9c857d1 --- /dev/null +++ b/runtime/sharing/problems.ts @@ -0,0 +1,35 @@ +import { + isRefusalRule, + refusalSentences, + type RefusalRule, +} from "../../src/sharing-refusals"; + +/** There is no Memtrace sign-in to show. The person has to sign in. */ +export class SharingSignedOut extends Error { + constructor(message = "Sign in to Memtrace to see the projects you share.") { + super(message); + this.name = "SharingSignedOut"; + } +} + +/** Sharing cannot be used right now. The message says what the person can do. */ +export class SharingUnavailable extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "SharingUnavailable"; + } +} + +/** One of the sharing service's rules turned the request down. The message is MemCode's sentence for it. */ +export class SharingRefused extends Error { + constructor(readonly rule: RefusalRule) { + super(refusalSentences[rule]); + this.name = "SharingRefused"; + } +} + +/** The refusal for a rule name the service sent, or nothing for a name MemCode does not know. */ +export const refusalNamed = (rule: string | undefined) => + rule !== undefined && isRefusalRule(rule) + ? new SharingRefused(rule) + : undefined; diff --git a/runtime/sharing/routes.ts b/runtime/sharing/routes.ts new file mode 100644 index 0000000..7023762 --- /dev/null +++ b/runtime/sharing/routes.ts @@ -0,0 +1,59 @@ +import { z } from "zod"; +import type { SharingSettings } from "../../src/sharing"; +import type { NativeHost } from "../host"; +import { sharingAddresses } from "./addresses"; +import type { Sharing } from "./sharing"; + +type Register = ( + method: string, + schema: z.ZodType, + handler: (input: any) => unknown, +) => void; + +const id = z.string().min(1).max(200); + +/** What the Settings dialog may save for sharing. The addresses are checked on save. */ +export const sharingSettingsSchema = z + .object({ memsyncUrl: z.string().max(2000), tokenUrl: z.string().max(2000) }) + .strict(); + +/** + * What a save of Settings leaves for sharing. A save that says nothing about + * sharing keeps what was there, and two empty addresses take sharing away. + * Throws a sentence for the person when an address cannot be used. + */ +export function sharingSettingsToKeep( + sent: SharingSettings | undefined, + kept: SharingSettings | undefined, +): SharingSettings | undefined { + if (!sent) return kept; + return sharingAddresses(sent) ? sent : undefined; +} + +/** What the app's window may ask of sharing. */ +export function registerSharing( + register: Register, + sharing: Sharing, + host: NativeHost, +) { + register("sharing:overview", z.undefined(), () => sharing.overview()); + register( + "sharing:accept-invitation", + z.object({ projectId: id, invitationId: id }).strict(), + (input) => sharing.acceptInvitation(input), + ); + register( + "sharing:connect", + z.object({ projectId: id, sharedProjectId: id }).strict(), + (input) => sharing.connect(input), + ); + register( + "sharing:disconnect", + z.object({ projectId: id }).strict(), + ({ projectId }) => sharing.disconnect(projectId), + ); + // Starting, renaming and deleting a project and inviting people happen at memtrace.io. + register("sharing:manage", z.undefined(), () => + host.call("open_memcode_projects", {}), + ); +} diff --git a/runtime/sharing/sharing.ts b/runtime/sharing/sharing.ts new file mode 100644 index 0000000..ad8c9ff --- /dev/null +++ b/runtime/sharing/sharing.ts @@ -0,0 +1,248 @@ +import type { AppState, Project } from "../../src/shared"; +import type { + PendingInvitation, + SharedPerson, + SharedProject, + SharedProjectLink, + SharingOverview, +} from "../../src/sharing"; +import type { BetaSessionProof } from "../beta"; +import { SharingAccess } from "./access"; +import { sharingAddresses } from "./addresses"; +import { grpcChannel, type GrpcChannel } from "./memsync/grpc"; +import { + MemsyncProjects, + type InvitationRecord, + type PersonRecord, + type ProjectRecord, + type ProjectsApi, +} from "./memsync/projects-api"; +import { + SharingRefused, + SharingSignedOut, + SharingUnavailable, +} from "./problems"; + +export interface SharingOptions { + state(): AppState; + /** Saves the workspace and tells the app's window. */ + changed(): Promise; + /** The Memtrace sign-in to show memtrace.io. Null: nobody is signed in. */ + session(): Promise; + fetcher?: typeof fetch; + now?: () => string; +} + +/** Everything that talks to one sharing service, built from one pair of addresses. */ +interface Service { + settingsKey: string; + address: string; + channel: GrpcChannel; + access: SharingAccess; + projects: ProjectsApi; +} + +const NOT_SET_UP = + "Sharing is not set up. Enter the sharing addresses in Settings first."; + +const shownPerson = ( + person: PersonRecord, + accountId: string, +): SharedPerson => ({ + name: person.name, + isYou: person.accountId === accountId, +}); +const shownProject = ( + project: ProjectRecord, + accountId: string, +): SharedProject => ({ + id: project.id, + name: project.name, + owner: shownPerson(project.owner, accountId), + guests: project.guests.map((guest) => shownPerson(guest, accountId)), + youAreOwner: project.owner.accountId === accountId, + openInvitations: project.openInvitations.length, + guestLimit: project.guestLimit, +}); +const shownInvitation = (invitation: InvitationRecord): PendingInvitation => ({ + id: invitation.id, + projectId: invitation.projectId, + projectName: invitation.projectName, + invitedBy: invitation.invitedBy?.name ?? "The project's owner", + expiresAt: invitation.expiresAt, +}); + +/** + * Sharing a project through the sharing service: who is signed in, the shared + * projects and invitations of that person, and which shared project each local + * project is connected to. The board itself is not synchronized here. + */ +export class Sharing { + private service?: Service; + private readonly now: () => string; + constructor(private readonly options: SharingOptions) { + this.now = options.now ?? (() => new Date().toISOString()); + } + + /** What the Sharing view shows. A problem is part of the answer, with what to do about it. */ + async overview(): Promise { + try { + const service = this.serviceInUse(); + if (!service) return { state: "not-set" }; + const [{ accountId }, projects, invitations] = await Promise.all([ + service.access.current(), + service.projects.listProjects(), + service.projects.listInvitations(), + ]); + return { + state: "ready", + accountId, + service: service.address, + projects: projects.map((project) => shownProject(project, accountId)), + invitations: invitations.map(shownInvitation), + }; + } catch (problem) { + if (problem instanceof SharingSignedOut) + return { state: "signed-out", detail: problem.message }; + if ( + problem instanceof SharingUnavailable || + problem instanceof SharingRefused + ) + return { state: "unavailable", detail: problem.message }; + throw problem; + } + } + + async acceptInvitation(input: { + projectId: string; + invitationId: string; + }): Promise { + await this.requiredService().projects.acceptInvitation( + input.projectId, + input.invitationId, + ); + return this.overview(); + } + + /** Records that a local project's board belongs to a shared project the person is on. */ + async connect(input: { + projectId: string; + sharedProjectId: string; + }): Promise { + const service = this.requiredService(); + this.assertFree(input, service); + const [{ accountId }, shared] = await Promise.all([ + service.access.current(), + service.projects.getProject(input.sharedProjectId), + ]); + // Another connect may have finished while the service was being asked. + this.assertFree(input, service); + const link: SharedProjectLink = { + projectId: input.projectId, + sharedProjectId: shared.id, + sharedProjectName: shared.name, + accountId, + service: service.address, + connectedAt: this.now(), + }; + (this.options.state().sharedProjectLinks ??= []).push(link); + await this.options.changed(); + return link; + } + + /** Forgets the link on this computer. The person stays on the shared project. */ + async disconnect(projectId: string): Promise { + const state = this.options.state(); + const kept = (state.sharedProjectLinks ?? []).filter( + (link) => link.projectId !== projectId, + ); + if (kept.length === (state.sharedProjectLinks ?? []).length) return; + state.sharedProjectLinks = kept; + await this.options.changed(); + } + + close() { + this.service?.channel.close(); + this.service = undefined; + } + + private assertFree( + input: { projectId: string; sharedProjectId: string }, + service: Service, + ) { + const state = this.options.state(); + const local = state.projects.find( + (project) => project.id === input.projectId, + ); + if (!local) throw new Error("Project not found."); + assertMayBeShared(local, state); + const links = state.sharedProjectLinks ?? []; + const existing = links.find((link) => link.projectId === local.id); + if (existing) + throw new Error( + `This project is already connected to “${existing.sharedProjectName}”. Disconnect it first.`, + ); + const taken = links.find( + (link) => + link.sharedProjectId === input.sharedProjectId && + link.service === service.address, + ); + const takenBy = + taken && state.projects.find((project) => project.id === taken.projectId); + if (taken && takenBy) + throw new Error( + `“${taken.sharedProjectName}” is already connected to “${takenBy.name}” on this computer.`, + ); + } + + private requiredService(): Service { + const service = this.serviceInUse(); + if (!service) throw new Error(NOT_SET_UP); + return service; + } + + /** The service for the addresses in Settings now. A changed address starts a new one. */ + private serviceInUse(): Service | null { + const settings = this.options.state().settings.sharing; + const settingsKey = JSON.stringify([ + settings?.memsyncUrl ?? "", + settings?.tokenUrl ?? "", + ]); + if (this.service?.settingsKey === settingsKey) return this.service; + this.close(); + let addresses: ReturnType; + try { + addresses = sharingAddresses(settings); + } catch (mistyped) { + throw new SharingUnavailable((mistyped as Error).message); + } + if (!addresses) return null; + const { memsync, tokenEndpoint } = addresses; + const channel = grpcChannel(memsync); + const access = new SharingAccess({ + session: this.options.session, + tokenEndpoint: () => tokenEndpoint, + fetcher: this.options.fetcher, + }); + this.service = { + settingsKey, + address: memsync.href, + channel, + access, + projects: new MemsyncProjects(channel, access), + }; + return this.service; + } +} + +function assertMayBeShared(local: Project, state: AppState) { + if (local.example) + throw new Error( + "The example project cannot be connected. Open one of your own projects first.", + ); + // Team Sync keeps its own copy of this board in step. Two services must not both do that. + if (state.team?.some((room) => room.projectId === local.id)) + throw new Error( + "This project is shared through Team Sync. Leave its team before connecting it to a shared project.", + ); +} diff --git a/src/shared.ts b/src/shared.ts index baa149c..b025f1c 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -338,6 +338,8 @@ export interface Project { example?: boolean; } export interface Settings { + /** Where projects are shared. Not set: sharing through the sharing service is absent. */ + sharing?: import("./sharing").SharingSettings; automaticUpdateDownloads?: boolean; workerPermissionDefaults?: Partial< Record @@ -413,6 +415,8 @@ export interface TeamInvite { expiresAt: string; } export interface AppState { + /** Which shared project each local project's board belongs to, on this computer. */ + sharedProjectLinks?: import("./sharing").SharedProjectLink[]; reviewWorkflows?: Record< string, import("./code-review").ReviewWorkflowBinding diff --git a/src/sharing-refusals.ts b/src/sharing-refusals.ts new file mode 100644 index 0000000..f7ca0bf --- /dev/null +++ b/src/sharing-refusals.ts @@ -0,0 +1,61 @@ +/** + * The rules the sharing service turns a request down by, and what MemCode tells + * the person for each. The names are a contract with the service: it sends one + * as `memsync-refusal` metadata. The wording is MemCode's own. + */ +export const refusalRules = [ + "no_such_project", + "no_such_invitation", + "no_such_guest", + "only_the_owner_invites", + "not_the_owner", + "the_owner_cannot_leave", + "guest_limit_reached", + "already_on_project", + "already_invited", + "invitation_expired", + "email_not_verified", + "invalid_project_name", + "invalid_email", + "invalid_update_id", + "empty_update", + "update_too_large", + "too_many_updates", +] as const; +export type RefusalRule = (typeof refusalRules)[number]; + +export const isRefusalRule = (name: string): name is RefusalRule => + (refusalRules as readonly string[]).includes(name); + +export const refusalSentences: Record = { + no_such_project: + "This shared project no longer exists, or you are no longer on it.", + no_such_invitation: + "That invitation is no longer open. Ask the owner of the project to invite you again.", + no_such_guest: "That person is not a guest on this project.", + only_the_owner_invites: + "Only the owner of a project can invite people to it.", + not_the_owner: "Only the owner of a project can change it.", + the_owner_cannot_leave: + "You own this project, so you cannot leave it. You can delete it at memtrace.io.", + guest_limit_reached: + "Every guest place on this project is taken. An invitation holds its place until it is accepted, cancelled or expires.", + already_on_project: "You are already on this project.", + already_invited: + "That email address already has an open invitation to this project.", + invitation_expired: + "This invitation has expired. Ask the owner of the project to send a new one.", + email_not_verified: + "Invitations go to a verified email address, and the one on your Memtrace account is not verified. Verify it at memtrace.io, then accept again.", + invalid_project_name: + "A project name is one line of text, at most 240 characters long.", + invalid_email: "That is not an email address. Check it and try again.", + invalid_update_id: + "MemCode sent a board change without a usable id. This is a fault in MemCode, not something you did.", + empty_update: + "MemCode sent an empty board change. This is a fault in MemCode, not something you did.", + update_too_large: + "One change to the board was too large to share. Shorten the text you just added and try again.", + too_many_updates: + "MemCode sent too many board changes at once. This is a fault in MemCode, not something you did.", +}; diff --git a/src/sharing.ts b/src/sharing.ts new file mode 100644 index 0000000..2502d4a --- /dev/null +++ b/src/sharing.ts @@ -0,0 +1,67 @@ +/** + * Sharing a project with your other computers and with guests. + * What the app shows of it; nothing here is a credential. + */ + +/** Where shared projects live. Both empty: sharing is absent from the app. */ +export interface SharingSettings { + /** The sharing service's address. */ + memsyncUrl: string; + /** Where MemCode exchanges its Memtrace sign-in for an access token. */ + tokenUrl: string; +} + +export const sharingIsSet = (settings: SharingSettings | undefined): boolean => + !!settings?.memsyncUrl.trim() && !!settings.tokenUrl.trim(); + +export interface SharedPerson { + name: string; + isYou: boolean; +} + +/** A project as the sharing service knows it: a name and the people on it. */ +export interface SharedProject { + id: string; + name: string; + owner: SharedPerson; + guests: SharedPerson[]; + youAreOwner: boolean; + /** Invitations nobody has accepted yet. Each holds a guest place. */ + openInvitations: number; + guestLimit: number; +} + +/** An invitation sent to the signed-in person's verified email address. */ +export interface PendingInvitation { + id: string; + projectId: string; + projectName: string; + invitedBy: string; + expiresAt: string; +} + +/** Which shared project the board of a local project belongs to. Kept on this computer. */ +export interface SharedProjectLink { + projectId: string; + sharedProjectId: string; + /** As it was when last seen, so it can be named while offline. */ + sharedProjectName: string; + /** The Memtrace account that connected it. */ + accountId: string; + /** The sharing service it lives on. */ + service: string; + connectedAt: string; +} + +export type SharingOverview = + | { state: "not-set" } + | { state: "signed-out"; detail: string } + | { state: "unavailable"; detail: string } + | { + state: "ready"; + /** The account the lists below belong to. */ + accountId: string; + service: string; + projects: SharedProject[]; + invitations: PendingInvitation[]; + }; diff --git a/tests/beta-access.test.ts b/tests/beta-access.test.ts index 8f15d71..80fad74 100644 --- a/tests/beta-access.test.ts +++ b/tests/beta-access.test.ts @@ -1056,3 +1056,70 @@ test("a rotated refresh is never published to the engine when OS credential pers f.manager.close(); } }); + +test("the session shown to memtrace.io's other endpoints waits for a rotation in flight", async () => { + const f = managerFixture(); + let releaseRefresh!: (value: BetaTokens) => void; + try { + assert.equal(await f.manager.sessionProof(), null); + await f.manager.connect(); + const connected = f.disk.state.credentials as BetaCredentials; + assert.deepEqual(await f.manager.sessionProof(), { + refreshToken: connected.refreshToken, + deviceId: connected.deviceId, + sessionId: connected.sessionId, + accountId: account.id, + }); + f.advance(14 * 60000); + f.authorization.refresh = async () => + new Promise((resolve) => (releaseRefresh = resolve)); + const refreshing = f.manager.refresh(); + await delay(); + let shown = false; + const proof = f.manager.sessionProof().then((value) => { + shown = true; + return value; + }); + await wait(40); + assert.equal(shown, false, "the spent refresh token must not be shown"); + const rotated = tokens(f.lastBinding!, f.now); + releaseRefresh(rotated); + await refreshing; + assert.equal((await proof)!.refreshToken, rotated.refresh_token); + assert.notEqual(rotated.refresh_token, connected.refreshToken); + } finally { + await f.manager.close(); + } +}); + +test("there is no session to show after sign-out, after revocation or once the refresh has expired", async () => { + const signedOut = managerFixture(); + try { + await signedOut.manager.connect(); + await signedOut.manager.signOut(); + assert.equal(await signedOut.manager.sessionProof(), null); + } finally { + await signedOut.manager.close(); + } + const revoked = managerFixture(); + try { + await revoked.manager.connect(); + revoked.advance(14 * 60000); + revoked.authorization.refresh = async () => { + throw new BetaRequestError(401); + }; + await revoked.manager.refresh(); + assert.equal(await revoked.manager.sessionProof(), null); + } finally { + await revoked.manager.close(); + } + const expired = managerFixture(); + try { + await expired.manager.connect(); + assert.ok(await expired.manager.sessionProof()); + expired.advance(31 * 86400000); + assert.equal(await expired.manager.sessionProof(), null); + } finally { + await expired.manager.close(); + } +}); diff --git a/tests/sharing-access.test.ts b/tests/sharing-access.test.ts new file mode 100644 index 0000000..b0efcf1 --- /dev/null +++ b/tests/sharing-access.test.ts @@ -0,0 +1,320 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { SharingAccess } from "../runtime/sharing/access"; +import { + SharingSignedOut, + SharingUnavailable, +} from "../runtime/sharing/problems"; +import type { BetaSessionProof } from "../runtime/beta"; + +const tokenEndpoint = new URL( + "https://www.memtrace.io/api/memcode/memsync/token", +); +const encoded = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); +/** Shaped like memtrace.io's token. MemCode never checks the signature; MemSync does. */ +const accessToken = (sub: unknown, serial = 0) => + [ + encoded({ alg: "EdDSA", typ: "JWT", kid: "test" }), + encoded({ sub, purpose: "memsync-access", serial }), + "c2lnbmF0dXJl", + ].join("."); +const session = ( + changes: Partial = {}, +): BetaSessionProof => ({ + refreshToken: "refresh-" + "r".repeat(40), + deviceId: "device-1234567890abcdef", + sessionId: "session-1234567890abcdef", + accountId: "acct-1", + ...changes, +}); + +function fixture() { + const start = Date.parse("2026-11-21T12:00:00Z"); + let serial = 0; + const state = { + now: start, + session: session() as BetaSessionProof | null, + requests: [] as Array<{ url: string; init: RequestInit; body: any }>, + answer: (async () => + Response.json({ + access_token: accessToken("acct-1", ++serial), + token_type: "Bearer", + expires_in: 600, + })) as (body: any) => Promise, + }; + const access = new SharingAccess({ + session: async () => state.session, + tokenEndpoint: () => tokenEndpoint, + now: () => state.now, + fetcher: (async (url, init) => { + const body = JSON.parse(String(init?.body)); + state.requests.push({ url: String(url), init: init!, body }); + return state.answer(body); + }) as typeof fetch, + }); + return { access, state, start }; +} + +test("the first call exchanges the Memtrace session for an access token", async () => { + const f = fixture(); + const access = await f.access.current(); + assert.equal(access.accountId, "acct-1"); + assert.equal(access.token, accessToken("acct-1", 1)); + assert.equal(f.state.requests.length, 1); + const [{ url, init, body }] = f.state.requests; + assert.equal(url, tokenEndpoint.href); + assert.equal(init.method, "POST"); + assert.equal(init.redirect, "error"); + assert.ok(init.signal, "the request is given up on after a while"); + assert.equal( + (init.headers as Record)["content-type"], + "application/json", + ); + // memtrace.io refuses a request with any other field in it. + assert.deepEqual(body, { + refresh_token: f.state.session!.refreshToken, + device_id: f.state.session!.deviceId, + session_id: f.state.session!.sessionId, + }); +}); + +test("a token is reused until a minute before it expires, then renewed", async () => { + const f = fixture(); + const first = await f.access.current(); + f.state.now = f.start + 8 * 60000 + 59000; + assert.equal((await f.access.current()).token, first.token); + assert.equal(f.state.requests.length, 1); + f.state.now = f.start + 9 * 60000 + 1000; + const renewed = await f.access.current(); + assert.notEqual(renewed.token, first.token); + assert.equal(f.state.requests.length, 2); +}); + +test("a token that lives under two minutes is renewed at half its life", async () => { + const f = fixture(); + f.state.answer = async () => + Response.json({ + access_token: accessToken("acct-1", f.state.requests.length), + token_type: "Bearer", + expires_in: 60, + }); + await f.access.current(); + f.state.now = f.start + 29000; + await f.access.current(); + assert.equal(f.state.requests.length, 1); + f.state.now = f.start + 31000; + await f.access.current(); + assert.equal(f.state.requests.length, 2); +}); + +test("calls made together ask memtrace.io once", async () => { + const f = fixture(); + let release!: () => void; + const held = new Promise((resolve) => (release = resolve)); + const answer = f.state.answer; + f.state.answer = async (body) => { + await held; + return answer(body); + }; + const together = [f.access.current(), f.access.current(), f.access.current()]; + await new Promise((resolve) => setImmediate(resolve)); + release(); + const tokens = await Promise.all(together); + assert.equal(f.state.requests.length, 1); + assert.equal(new Set(tokens.map((access) => access.token)).size, 1); +}); + +test("a token the sharing service would not take is forgotten, and only that one", async () => { + const f = fixture(); + const first = await f.access.current(); + f.access.forget("some other token"); + assert.equal((await f.access.current()).token, first.token); + f.access.forget(first.token); + assert.notEqual((await f.access.current()).token, first.token); + assert.equal(f.state.requests.length, 2); +}); + +test("without a Memtrace session nothing is sent and the person is told to sign in", async () => { + const f = fixture(); + f.state.session = null; + await assert.rejects(f.access.current(), SharingSignedOut); + assert.equal(f.state.requests.length, 0); +}); + +test("a token is never handed to another sign-in, or kept after signing out", async () => { + const f = fixture(); + const first = await f.access.current(); + f.state.session = session({ + sessionId: "session-of-someone-else-123", + accountId: "acct-2", + }); + f.state.answer = async () => + Response.json({ + access_token: accessToken("acct-2"), + token_type: "Bearer", + expires_in: 600, + }); + const second = await f.access.current(); + assert.equal(second.accountId, "acct-2"); + assert.notEqual(second.token, first.token); + f.state.session = null; + await assert.rejects(f.access.current(), SharingSignedOut); + assert.equal(f.state.requests.length, 2); +}); + +test("a call that joins an exchange begun for the sign-in before it asks again for its own", async () => { + const f = fixture(); + let release!: () => void; + const held = new Promise((resolve) => (release = resolve)); + f.state.answer = async (body) => { + await held; + return Response.json({ + access_token: accessToken( + body.session_id === session().sessionId ? "acct-1" : "acct-2", + ), + token_type: "Bearer", + expires_in: 600, + }); + }; + const before = f.access.current(); + await new Promise((resolve) => setImmediate(resolve)); + f.state.session = session({ + sessionId: "session-of-someone-else-123", + accountId: "acct-2", + }); + const after = f.access.current(); + await new Promise((resolve) => setImmediate(resolve)); + release(); + assert.equal((await after).accountId, "acct-2"); + assert.equal((await before).accountId, "acct-1"); +}); + +test("a refresh token that was rotated while the request travelled is replaced once", async () => { + const f = fixture(); + const rotated = "rotated-" + "n".repeat(40); + const answer = f.state.answer; + f.state.answer = async (body) => { + if (body.refresh_token === rotated) return answer(body); + f.state.session = session({ refreshToken: rotated }); + return Response.json({ error: "Session not found" }, { status: 401 }); + }; + const access = await f.access.current(); + assert.equal(access.accountId, "acct-1"); + assert.deepEqual( + f.state.requests.map((request) => request.body.refresh_token), + [session().refreshToken, rotated], + ); +}); + +test("a session memtrace.io no longer knows means signing in again, without asking twice", async () => { + const f = fixture(); + f.state.answer = async () => + Response.json({ error: "Session not found" }, { status: 401 }); + await assert.rejects(f.access.current(), SharingSignedOut); + assert.equal(f.state.requests.length, 1); +}); + +test("memtrace.io's other answers each say what the person can do", async () => { + const f = fixture(); + const cases: Array<[number, RegExp]> = [ + [422, /name or email/i], + [503, /switched off|not set up/i], + [400, /HTTP 400/], + [404, /HTTP 404/], + [429, /HTTP 429/], + [500, /HTTP 500/], + ]; + for (const [status, sentence] of cases) { + f.state.answer = async () => new Response("{}", { status }); + await assert.rejects(f.access.current(), (error) => { + assert.ok(error instanceof SharingUnavailable, `HTTP ${status}`); + assert.match(error.message, sentence); + return true; + }); + } + f.state.answer = async () => { + throw new TypeError("fetch failed"); + }; + await assert.rejects(f.access.current(), (error) => { + assert.ok(error instanceof SharingUnavailable); + assert.match(error.message, /could not be reached/); + return true; + }); +}); + +test("a reply that is not the token it should be is not used", async () => { + const f = fixture(); + const good = { + access_token: accessToken("acct-1"), + token_type: "Bearer", + expires_in: 600, + }; + const wrong: unknown[] = [ + { ...good, token_type: "MAC" }, + { ...good, expires_in: 0 }, + { ...good, expires_in: 901 }, + { ...good, expires_in: 1.5 }, + { ...good, expires_in: "600" }, + { ...good, access_token: undefined }, + { ...good, access_token: "not-a-token" }, + { ...good, access_token: "a.b" }, + { ...good, access_token: "a.!!.c" }, + { ...good, access_token: accessToken(undefined) }, + { ...good, access_token: accessToken("") }, + { ...good, access_token: accessToken(17) }, + { ...good, access_token: accessToken("x".repeat(201)) }, + { ...good, access_token: accessToken("acct-1") + "A".repeat(16384) }, + null, + [], + "token", + ]; + for (const reply of wrong) { + f.state.answer = async () => Response.json(reply); + await assert.rejects( + f.access.current(), + SharingUnavailable, + JSON.stringify(reply)?.slice(0, 80), + ); + } + f.state.answer = async () => + new Response("Memtrace", { + headers: { "content-type": "text/html" }, + }); + await assert.rejects(f.access.current(), SharingUnavailable); + f.state.answer = async () => new Response("x".repeat(40000)); + await assert.rejects(f.access.current(), SharingUnavailable); +}); + +test("the token belongs to the account that is signed in, or it is not used", async () => { + const f = fixture(); + f.state.answer = async () => + Response.json({ + access_token: accessToken("acct-of-someone-else"), + token_type: "Bearer", + expires_in: 600, + }); + await assert.rejects(f.access.current(), SharingUnavailable); +}); + +test("no failure repeats the refresh token", async () => { + const f = fixture(); + const secret = f.state.session!.refreshToken; + for (const answer of [ + async () => + new Response(JSON.stringify({ echoed: secret }), { status: 401 }), + async () => + new Response(JSON.stringify({ echoed: secret }), { status: 500 }), + async () => Response.json({ echoed: secret }), + async () => { + throw new Error("could not send " + secret); + }, + ]) { + f.state.answer = answer as () => Promise; + await assert.rejects(f.access.current(), (error: Error) => { + assert.ok(!error.message.includes(secret)); + assert.ok(!String(error.cause ?? "").includes(secret)); + return true; + }); + } +}); diff --git a/tests/sharing-addresses.test.ts b/tests/sharing-addresses.test.ts new file mode 100644 index 0000000..b9cce0a --- /dev/null +++ b/tests/sharing-addresses.test.ts @@ -0,0 +1,95 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { sharingAddresses } from "../runtime/sharing/addresses"; + +const hosted = { + memsyncUrl: "https://sync.memtrace.io", + tokenUrl: "https://www.memtrace.io/api/memcode/memsync/token", +}; + +test("sharing is absent until both addresses are set", () => { + assert.equal(sharingAddresses(undefined), null); + assert.equal(sharingAddresses({ memsyncUrl: "", tokenUrl: "" }), null); + assert.equal(sharingAddresses({ memsyncUrl: " ", tokenUrl: "\t" }), null); +}); + +test("one address without the other is a mistake, not a setting", () => { + for (const half of [ + { ...hosted, tokenUrl: "" }, + { ...hosted, memsyncUrl: " " }, + ]) + assert.throws(() => sharingAddresses(half), /both/); +}); + +test("a hosted sharing service and memtrace.io's token endpoint are accepted as typed", () => { + const addresses = sharingAddresses({ + memsyncUrl: " https://sync.memtrace.io ", + tokenUrl: hosted.tokenUrl, + })!; + assert.equal(addresses.memsync.href, "https://sync.memtrace.io/"); + assert.equal(addresses.tokenEndpoint.href, hosted.tokenUrl); +}); + +test("a sharing service behind a path keeps its path", () => { + const addresses = sharingAddresses({ + ...hosted, + memsyncUrl: "https://company.example/memsync/", + })!; + assert.equal(addresses.memsync.href, "https://company.example/memsync/"); +}); + +test("an unencrypted sharing service is accepted on this computer only", () => { + for (const local of [ + "http://127.0.0.1:50061", + "http://localhost:50061", + "http://[::1]:50061", + ]) + assert.ok(sharingAddresses({ ...hosted, memsyncUrl: local })); + for (const exposed of [ + "http://sync.memtrace.io", + "http://192.168.1.20:50061", + "http://localhost.example.com:50061", + ]) + assert.throws( + () => sharingAddresses({ ...hosted, memsyncUrl: exposed }), + /https:\/\//, + ); +}); + +test("an address that is not a plain web address is refused", () => { + for (const memsyncUrl of [ + "sync.memtrace.io", + "grpc://sync.memtrace.io", + "https://someone:secret@sync.memtrace.io", + "https://sync.memtrace.io/?token=1", + "https://sync.memtrace.io/#part", + "not an address", + ]) + assert.throws(() => sharingAddresses({ ...hosted, memsyncUrl }), Error); + for (const tokenUrl of [ + "www.memtrace.io/api/memcode/memsync/token", + "https://someone:secret@www.memtrace.io/api/memcode/memsync/token", + "https://www.memtrace.io/api/memcode/memsync/token?next=1", + ]) + assert.throws(() => sharingAddresses({ ...hosted, tokenUrl }), Error); +}); + +test("the Memtrace sign-in is shown to memtrace.io or to this computer, nobody else", () => { + for (const tokenUrl of [ + "https://www.memtrace.io/api/memcode/memsync/token", + "http://127.0.0.1:3000/api/memcode/memsync/token", + "http://localhost:3000/api/memcode/memsync/token", + ]) + assert.ok(sharingAddresses({ ...hosted, tokenUrl })); + for (const tokenUrl of [ + "https://tokens.example.com/api/memcode/memsync/token", + "https://www.memtrace.io.example.com/api/memcode/memsync/token", + "https://memtrace.io.evil.example/token", + "http://www.memtrace.io/api/memcode/memsync/token", + "https://www.memtrace.io:8443/api/memcode/memsync/token", + ]) + assert.throws( + () => sharingAddresses({ ...hosted, tokenUrl }), + /memtrace\.io/, + ); +}); diff --git a/tests/sharing-grpc.test.ts b/tests/sharing-grpc.test.ts new file mode 100644 index 0000000..bcef585 --- /dev/null +++ b/tests/sharing-grpc.test.ts @@ -0,0 +1,433 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + createServer, + type Http2Server, + type IncomingHttpHeaders, + type ServerHttp2Stream, +} from "node:http2"; +import { createServer as createPlainServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { + GrpcFailure, + grpcChannel, + grpcStatus, +} from "../runtime/sharing/memsync/grpc"; + +type Answer = ( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + request: Buffer, +) => void; + +const framed = (message: Uint8Array, compressed = 0) => { + const frame = Buffer.alloc(5 + message.length); + frame[0] = compressed; + frame.writeUInt32BE(message.length, 1); + frame.set(message, 5); + return frame; +}; +const reply = (stream: ServerHttp2Stream, message: Uint8Array) => { + stream.respond( + { ":status": 200, "content-type": "application/grpc" }, + { waitForTrailers: true }, + ); + stream.on("wantTrailers", () => stream.sendTrailers({ "grpc-status": "0" })); + stream.end(framed(message)); +}; +const refuse = ( + stream: ServerHttp2Stream, + status: number, + message: string, + metadata: Record = {}, +) => + stream.respond( + { + ":status": 200, + "content-type": "application/grpc", + "grpc-status": String(status), + "grpc-message": encodeURIComponent(message), + ...metadata, + }, + { endStream: true }, + ); + +async function listening(answer: Answer) { + const server: Http2Server = createServer(); + let sessions = 0; + const open = new Set(); + server.on("session", (session) => { + sessions++; + open.add(session); + session.on("close", () => open.delete(session)); + }); + server.on("stream", (stream, headers) => { + const parts: Buffer[] = []; + stream.on("error", () => {}); + stream.on("data", (part: Buffer) => parts.push(part)); + stream.on("end", () => + answer(stream as ServerHttp2Stream, headers, Buffer.concat(parts)), + ); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { + address: new URL(`http://127.0.0.1:${port}`), + get sessions() { + return sessions; + }, + hangUp: () => open.forEach((session) => session.destroy()), + close: async () => { + open.forEach((session) => session.destroy()); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +} +const failure = async (call: Promise) => { + try { + await call; + } catch (error) { + assert.ok(error instanceof GrpcFailure, String(error)); + return error; + } + assert.fail("The call was expected to fail."); +}; +const say = (text: string) => new Uint8Array(Buffer.from(text)); + +test("a call sends one framed message to the method's path and reads the framed reply", async () => { + let seen: IncomingHttpHeaders = {}; + const server = await listening((stream, headers, request) => { + seen = headers; + assert.equal(request[0], 0); + assert.equal(request.readUInt32BE(1), request.length - 5); + reply(stream, say(request.subarray(5).toString().toUpperCase())); + }); + const channel = grpcChannel(server.address); + try { + const answer = await channel.unary({ + path: "/memsync.v1.Projects/ListProjects", + request: say("hello"), + metadata: { authorization: "Bearer token-1" }, + timeoutMs: 2500, + }); + assert.equal(Buffer.from(answer).toString(), "HELLO"); + assert.equal(seen[":method"], "POST"); + assert.equal(seen[":path"], "/memsync.v1.Projects/ListProjects"); + assert.equal(seen["content-type"], "application/grpc"); + assert.equal(seen.te, "trailers"); + assert.equal(seen["grpc-timeout"], "2500m"); + assert.equal(seen.authorization, "Bearer token-1"); + } finally { + channel.close(); + await server.close(); + } +}); + +test("an empty request and an empty reply are both whole messages", async () => { + const server = await listening((stream, _headers, request) => { + assert.equal(request.length, 5); + reply(stream, new Uint8Array()); + }); + const channel = grpcChannel(server.address); + try { + const answer = await channel.unary({ + path: "/s/m", + request: new Uint8Array(), + }); + assert.equal(answer.length, 0); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a call that is turned down fails with its status, reason and metadata", async () => { + const server = await listening((stream) => + refuse(stream, grpcStatus.NOT_FOUND, "there is no such project — 100%", { + "memsync-refusal": "no_such_project", + }), + ); + const channel = grpcChannel(server.address); + try { + const refused = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(refused.code, grpcStatus.NOT_FOUND); + assert.equal(refused.message, "there is no such project — 100%"); + assert.equal(refused.metadata["memsync-refusal"], "no_such_project"); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a status sent after the reply still fails the call", async () => { + const server = await listening((stream) => { + stream.respond( + { ":status": 200, "content-type": "application/grpc" }, + { waitForTrailers: true }, + ); + stream.on("wantTrailers", () => + stream.sendTrailers({ + "grpc-status": String(grpcStatus.UNAVAILABLE), + "grpc-message": "the%20database%20is%20away", + }), + ); + stream.end(framed(say("half an answer"))); + }); + const channel = grpcChannel(server.address); + try { + const failed = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(failed.code, grpcStatus.UNAVAILABLE); + assert.equal(failed.message, "the database is away"); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a service that does not answer in time is given up on, and told so", async () => { + let cancelled!: () => void; + const serverSawCancel = new Promise((resolve) => (cancelled = resolve)); + const server = await listening((stream) => stream.on("close", cancelled)); + const channel = grpcChannel(server.address); + try { + const started = Date.now(); + const late = await failure( + channel.unary({ path: "/s/m", request: say(""), timeoutMs: 120 }), + ); + assert.equal(late.code, grpcStatus.DEADLINE_EXCEEDED); + assert.ok(Date.now() - started < 2000); + await serverSawCancel; + } finally { + channel.close(); + await server.close(); + } +}); + +test("nothing listening at the address reads as unavailable", async () => { + const server = await listening(() => {}); + const { address } = server; + await server.close(); + const channel = grpcChannel(address); + try { + const down = await failure( + channel.unary({ path: "/s/m", request: say(""), timeoutMs: 2000 }), + ); + assert.equal(down.code, grpcStatus.UNAVAILABLE); + } finally { + channel.close(); + } +}); + +test("a proxy's own answer is read by its HTTP status", async () => { + const expected: Array<[number, number]> = [ + [401, grpcStatus.UNAUTHENTICATED], + [403, grpcStatus.PERMISSION_DENIED], + [404, grpcStatus.UNIMPLEMENTED], + [502, grpcStatus.UNAVAILABLE], + [503, grpcStatus.UNAVAILABLE], + [504, grpcStatus.UNAVAILABLE], + [500, grpcStatus.UNKNOWN], + ]; + for (const [http, code] of expected) { + const server = await listening((stream) => { + stream.respond({ ":status": http, "content-type": "text/html" }); + stream.end("

Bad gateway

"); + }); + const channel = grpcChannel(server.address); + try { + const failed = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(failed.code, code, `HTTP ${http}`); + } finally { + channel.close(); + await server.close(); + } + } +}); + +test("a web page at the address is not mistaken for an answer", async () => { + const server = await listening((stream) => { + stream.respond({ ":status": 200, "content-type": "text/html" }); + stream.end("

Welcome

"); + }); + const channel = grpcChannel(server.address); + try { + const failed = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(failed.code, grpcStatus.UNKNOWN); + assert.match(failed.message, /not a sharing service/i); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a server that only speaks HTTP/1.1 reads as unavailable", async () => { + const server = createPlainServer((_request, response) => + response.end("hello"), + ); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + const channel = grpcChannel(new URL(`http://127.0.0.1:${port}`)); + try { + const failed = await failure( + channel.unary({ path: "/s/m", request: say(""), timeoutMs: 2000 }), + ); + assert.equal(failed.code, grpcStatus.UNAVAILABLE); + } finally { + channel.close(); + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +}); + +test("a reply that is cut short, compressed, doubled or missing is refused", async () => { + const broken: Array<[string, (stream: ServerHttp2Stream) => void]> = [ + ["cut short", (stream) => stream.end(framed(say("whole")).subarray(0, 7))], + ["compressed", (stream) => stream.end(framed(say("squeezed"), 1))], + [ + "doubled", + (stream) => + stream.end(Buffer.concat([framed(say("a")), framed(say("b"))])), + ], + ["missing", (stream) => stream.end()], + ]; + for (const [name, send] of broken) { + const server = await listening((stream) => { + stream.respond( + { ":status": 200, "content-type": "application/grpc" }, + { waitForTrailers: true }, + ); + stream.on("wantTrailers", () => + stream.sendTrailers({ "grpc-status": "0" }), + ); + send(stream); + }); + const channel = grpcChannel(server.address); + try { + const failed = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(failed.code, grpcStatus.INTERNAL, name); + } finally { + channel.close(); + await server.close(); + } + } +}); + +test("a reply larger than the limit is refused before it is all read", async () => { + const server = await listening((stream) => + reply(stream, new Uint8Array(70000)), + ); + const channel = grpcChannel(server.address, { maxReplyBytes: 4096 }); + try { + const failed = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(failed.code, grpcStatus.RESOURCE_EXHAUSTED); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a reply that ends without any status reads as unavailable", async () => { + const server = await listening((stream) => { + stream.respond({ ":status": 200, "content-type": "application/grpc" }); + stream.end(framed(say("no trailers follow"))); + }); + const channel = grpcChannel(server.address); + try { + const failed = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(failed.code, grpcStatus.UNAVAILABLE); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a path in the service's address goes in front of every call", async () => { + let path = ""; + const server = await listening((stream, headers) => { + path = String(headers[":path"]); + reply(stream, say("ok")); + }); + const behindProxy = new URL("/memsync/", server.address); + const channel = grpcChannel(behindProxy); + try { + await channel.unary({ + path: "/memsync.v1.Projects/GetProject", + request: say(""), + }); + assert.equal(path, "/memsync/memsync.v1.Projects/GetProject"); + } finally { + channel.close(); + await server.close(); + } +}); + +test("calls made together share a connection, and a lost connection is replaced", async () => { + const server = await listening((stream, _headers, request) => + reply(stream, request.subarray(5)), + ); + const channel = grpcChannel(server.address); + try { + const answers = await Promise.all( + ["one", "two", "three"].map((text) => + channel.unary({ path: "/s/m", request: say(text) }), + ), + ); + assert.deepEqual( + answers.map((answer) => Buffer.from(answer).toString()), + ["one", "two", "three"], + ); + assert.equal(server.sessions, 1); + server.hangUp(); + await new Promise((resolve) => setTimeout(resolve, 30)); + const again = await channel.unary({ path: "/s/m", request: say("four") }); + assert.equal(Buffer.from(again).toString(), "four"); + assert.equal(server.sessions, 2); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a connection nobody has used for a while is closed, and the next call opens another", async () => { + const server = await listening((stream) => reply(stream, say("ok"))); + const channel = grpcChannel(server.address, { idleMs: 40 }); + try { + await channel.unary({ path: "/s/m", request: say("") }); + await new Promise((resolve) => setTimeout(resolve, 150)); + await channel.unary({ path: "/s/m", request: say("") }); + assert.equal(server.sessions, 2); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a closed channel makes no more calls", async () => { + const server = await listening((stream) => reply(stream, say("ok"))); + const channel = grpcChannel(server.address); + try { + await channel.unary({ path: "/s/m", request: say("") }); + channel.close(); + const failed = await failure( + channel.unary({ path: "/s/m", request: say("") }), + ); + assert.equal(failed.code, grpcStatus.CANCELLED); + assert.equal(server.sessions, 1); + } finally { + await server.close(); + } +}); diff --git a/tests/sharing-projects-api.test.ts b/tests/sharing-projects-api.test.ts new file mode 100644 index 0000000..815d512 --- /dev/null +++ b/tests/sharing-projects-api.test.ts @@ -0,0 +1,263 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { grpcChannel, grpcStatus } from "../runtime/sharing/memsync/grpc"; +import { MemsyncProjects } from "../runtime/sharing/memsync/projects-api"; +import { + SharingRefused, + SharingSignedOut, + SharingUnavailable, +} from "../runtime/sharing/problems"; +import { refusalRules, refusalSentences } from "../src/sharing-refusals"; +import { startStandInMemsync } from "./support/memsync-stand-in"; +import { + cast, + projectsApiScenarios, + signedInTo, +} from "./support/projects-api-scenarios"; + +projectsApiScenarios("stand-in sharing service", startStandInMemsync); + +/** MemCode's client with access tokens the test hands out and takes back. */ +async function fixture(timeoutMs?: number) { + const service = await startStandInMemsync(); + const people = cast(); + const forgotten: string[] = []; + let issued = 0; + const channel = grpcChannel(service.address); + const state = { token: service.tokenFor(people.alex) }; + const projects = new MemsyncProjects( + channel, + { + current: async () => { + issued++; + return { token: state.token, accountId: people.alex.accountId }; + }, + forget: (token) => { + forgotten.push(token); + state.token = service.tokenFor(people.alex); + }, + }, + timeoutMs, + ); + return { + service, + people, + projects, + state, + forgotten, + get issued() { + return issued; + }, + close: async () => { + channel.close(); + await service.close(); + }, + }; +} +const unavailable = (sentence: RegExp) => (problem: unknown) => { + assert.ok(problem instanceof SharingUnavailable, String(problem)); + assert.match(problem.message, sentence); + return true; +}; +const quietly = async (context: test.TestContext, run: () => Promise) => { + const logged = context.mock.method(console, "error", () => {}); + try { + return { result: await run(), logged }; + } finally { + logged.mock.restore(); + } +}; + +test("every call carries the access token as a bearer token", async () => { + const f = await fixture(); + try { + await f.projects.listProjects(); + await f.projects.listInvitations(); + assert.deepEqual(f.service.calls, [ + { method: "ListProjects", token: f.state.token }, + { method: "ListInvitations", token: f.state.token }, + ]); + } finally { + await f.close(); + } +}); + +test("a token the service turns away is handed back and the call made once more with a new one", async () => { + const f = await fixture(); + try { + const first = f.state.token; + f.service.expire(first); + assert.deepEqual(await f.projects.listProjects(), []); + assert.deepEqual(f.forgotten, [first]); + assert.deepEqual( + f.service.calls.map((call) => call.token), + [first, f.state.token], + ); + } finally { + await f.close(); + } +}); + +test("a service that takes no token at all is unavailable, after two tries and no more", async (context) => { + const f = await fixture(); + try { + f.service.turnAwayNextCall(); + f.service.turnAwayNextCall(); + const { logged } = await quietly(context, () => + assert.rejects( + f.projects.listProjects(), + unavailable(/did not accept this sign-in/), + ), + ); + assert.equal(f.service.calls.length, 2); + assert.equal(f.forgotten.length, 2); + assert.equal(logged.mock.callCount(), 1); + } finally { + await f.close(); + } +}); + +test("each rule the service can name reaches the person as MemCode's sentence for it", async () => { + const f = await fixture(); + try { + for (const rule of refusalRules) { + f.service.refuseNextCallBy(rule); + await assert.rejects(f.projects.listProjects(), (problem) => { + assert.ok(problem instanceof SharingRefused, rule); + assert.equal(problem.rule, rule); + assert.equal(problem.message, refusalSentences[rule]); + return true; + }); + } + } finally { + await f.close(); + } +}); + +test("a rule from a newer service is said plainly and written to the log by name", async (context) => { + const f = await fixture(); + try { + f.service.refuseNextCallBy("project_is_archived"); + const { logged } = await quietly(context, () => + assert.rejects( + f.projects.listProjects(), + unavailable(/this version of MemCode does not know/), + ), + ); + assert.match( + String(logged.mock.calls[0].arguments[0]), + /project_is_archived/, + ); + assert.match(String(logged.mock.calls[0].arguments[0]), /ListProjects/); + } finally { + await f.close(); + } +}); + +test("a refusal for an unverified address hands the token back, so the next try carries the new address", async () => { + const f = await fixture(); + try { + const first = f.state.token; + f.service.refuseNextCallBy("email_not_verified"); + await assert.rejects(f.projects.listInvitations(), SharingRefused); + assert.deepEqual(f.forgotten, [first]); + f.service.refuseNextCallBy("no_such_project", grpcStatus.NOT_FOUND); + await assert.rejects(f.projects.listInvitations(), SharingRefused); + assert.deepEqual(f.forgotten, [first]); + } finally { + await f.close(); + } +}); + +test("a service in trouble, out of reach, too slow or unreadable is unavailable, each in its own words", async (context) => { + const f = await fixture(150); + try { + await quietly(context, async () => { + f.service.failNextCall(grpcStatus.UNAVAILABLE); + await assert.rejects( + f.projects.listProjects(), + unavailable(/having trouble/), + ); + f.service.failNextCall(grpcStatus.INTERNAL); + await assert.rejects( + f.projects.listProjects(), + unavailable(/having trouble/), + ); + f.service.stallNextCall(); + await assert.rejects(f.projects.listProjects(), unavailable(/in time/)); + f.service.garbleNextReply(); + await assert.rejects( + f.projects.listProjects(), + unavailable(/could not read/), + ); + await f.service.close(); + await assert.rejects( + f.projects.listProjects(), + unavailable(/could not be reached/), + ); + }); + } finally { + await f.close(); + } +}); + +test("a reply that lacks what it always holds is not passed on half read", async (context) => { + const f = await fixture(); + try { + const alex = signedInTo(f.service, f.people.alex); + const id = await alex.website.startProject("Launch plan"); + alex.close(); + // The same bytes read as an invitation have no project id, sender or dates. + const channel = grpcChannel(f.service.address); + context.after(() => channel.close()); + const asInvitation = new MemsyncProjects( + { + unary: (call) => + channel.unary({ + ...call, + path: call.path.replace("ListInvitations", "ListProjects"), + }), + close() {}, + }, + { + current: async () => ({ token: f.state.token, accountId: "" }), + forget() {}, + }, + ); + await quietly(context, () => + assert.rejects( + asInvitation.listInvitations(), + unavailable(/could not read/), + ), + ); + assert.equal((await f.projects.getProject(id)).name, "Launch plan"); + } finally { + await f.close(); + } +}); + +test("having no sign-in, or no way to get a token, stops the call before it is made", async () => { + const service = await startStandInMemsync(); + const channel = grpcChannel(service.address); + try { + for (const problem of [ + new SharingSignedOut(), + new SharingUnavailable("memtrace.io could not be reached."), + ]) { + const projects = new MemsyncProjects(channel, { + current: async () => { + throw problem; + }, + forget() {}, + }); + await assert.rejects( + projects.listProjects(), + (thrown) => thrown === problem, + ); + } + assert.equal(service.calls.length, 0); + } finally { + channel.close(); + await service.close(); + } +}); diff --git a/tests/sharing-real-memsync.test.ts b/tests/sharing-real-memsync.test.ts new file mode 100644 index 0000000..a63f530 --- /dev/null +++ b/tests/sharing-real-memsync.test.ts @@ -0,0 +1,169 @@ +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { grpcChannel } from "../runtime/sharing/memsync/grpc"; +import { MemsyncProjects } from "../runtime/sharing/memsync/projects-api"; +import { SharingUnavailable } from "../runtime/sharing/problems"; +import { refusalRules } from "../src/sharing-refusals"; +import { actingAs } from "./support/memsync-owner"; +import { + cast, + projectsApiScenarios, + signedInTo, +} from "./support/projects-api-scenarios"; +import { + realMemsyncMissing, + startRealMemsync, + worldOn, + type RealMemsync, + type TokenChanges, +} from "./support/real-memsync"; + +// MemCode's client against the real server: its wire format, its statuses and its rules. +// Skipped unless a built server and a PostgreSQL server for tests are named: +// MEMSYNC_SERVER_BINARY=/path/to/memsync-server \ +// MEMSYNC_TEST_DATABASE_URL=postgres://memsync@127.0.0.1:54329/postgres \ +// node --import tsx --test tests/sharing-real-memsync.test.ts +let started: Promise | undefined; +const server = () => (started ??= startRealMemsync()); +after(async () => { + await (await started)?.stop(); +}); + +projectsApiScenarios( + "real memsync-server", + async () => worldOn(await server()), + { + skip: realMemsyncMissing, + }, +); + +test( + "real memsync-server: a token it has no reason to trust is turned away", + { skip: realMemsyncMissing }, + async (context) => { + const real = await server(); + const { alex } = cast(); + const untrusted: Array<[string, TokenChanges]> = [ + ["signed with another key", { unknownKey: true }], + ["made for another service", { claims: { aud: "memcode-team" } }], + [ + "made for another purpose", + { claims: { purpose: "memcode-engine-beta" } }, + ], + ["from another issuer", { claims: { iss: "https://example.com" } }], + ["expired", { claims: { iat: 1700000000, exp: 1700000600 } }], + [ + "longer-lived than fifteen minutes", + { claims: { exp: Math.floor(Date.now() / 1000) + 3600 } }, + ], + ]; + context.mock.method(console, "error", () => {}); + for (const [what, changes] of untrusted) { + const channel = grpcChannel(real.address); + const forgotten: string[] = []; + const token = real.tokenFor(alex, changes); + const projects = new MemsyncProjects(channel, { + current: async () => ({ token, accountId: alex.accountId }), + forget: (refused) => forgotten.push(refused), + }); + try { + await assert.rejects( + projects.listProjects(), + (problem) => { + assert.ok(problem instanceof SharingUnavailable, what); + assert.match(problem.message, /did not accept this sign-in/); + return true; + }, + what, + ); + assert.deepEqual(forgotten, [token, token], what); + } finally { + channel.close(); + } + } + }, +); + +test( + "real memsync-server: every rule it names is one MemCode has a sentence for", + { skip: realMemsyncMissing }, + async () => { + const world = worldOn(await server()); + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo), + dana = signedInTo(world, people.dana); + const named: string[] = []; + const naming = async (attempt: Promise) => { + try { + await attempt; + assert.fail("expected the service to turn this down"); + } catch (problem) { + const rule = (problem as { metadata?: Record }) + .metadata?.["memsync-refusal"]; + assert.ok(rule, String(problem)); + named.push(rule); + } + }; + try { + const id = await alex.website.startProject("Rules"); + await naming(alex.website.startProject(" ")); + await naming(alex.website.invite(id, "not an address")); + await naming(alex.website.invite(id, people.alex.email!)); + const forBo = await alex.website.invite(id, people.bo.email!); + await naming(alex.website.invite(id, people.bo.email!)); + await bo.projects.acceptInvitation(id, forBo); + await naming(bo.website.invite(id, people.dana.email!)); + await naming(bo.website.deleteProject(id)); + await naming(alex.website.removeGuest(id, people.dana.accountId)); + await alex.website.invite(id, people.dana.email!); + await naming(alex.website.invite(id, "one.more@example.com")); + await naming(dana.website.deleteProject(id)); + await naming( + actingAs(world.address, dana.token).cancelInvitation(id, forBo), + ); + assert.deepEqual(named, [ + "invalid_project_name", + "invalid_email", + "already_on_project", + "already_invited", + "only_the_owner_invites", + "not_the_owner", + "no_such_guest", + "guest_limit_reached", + "no_such_project", + "no_such_project", + ]); + for (const rule of named) + assert.ok((refusalRules as readonly string[]).includes(rule), rule); + } finally { + for (const person of [alex, bo, dana]) person.close(); + } + }, +); + +test( + "real memsync-server: the same person signed in on two computers sees the same projects", + { skip: realMemsyncMissing }, + async () => { + const world = worldOn(await server()); + const { alex } = cast(); + const mac = signedInTo(world, alex), + windows = signedInTo(world, alex); + try { + const id = await mac.website.startProject("On both computers"); + const seen = await windows.projects.listProjects(); + assert.deepEqual( + seen.map((project) => project.id), + [id], + ); + assert.deepEqual(seen[0].guests, []); + // Nobody invited the second computer: signing in is all it took. + assert.deepEqual(await windows.projects.listInvitations(), []); + assert.deepEqual(seen[0].openInvitations, []); + } finally { + mac.close(); + windows.close(); + } + }, +); diff --git a/tests/sharing-refusals.test.ts b/tests/sharing-refusals.test.ts new file mode 100644 index 0000000..7600a5a --- /dev/null +++ b/tests/sharing-refusals.test.ts @@ -0,0 +1,60 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + isRefusalRule, + refusalRules, + refusalSentences, +} from "../src/sharing-refusals"; + +// The table in MemSync's docs/08_crosscutting_concepts.md, as of 21 November 2026. +const namedByMemsync = [ + "no_such_project", + "no_such_invitation", + "no_such_guest", + "only_the_owner_invites", + "not_the_owner", + "the_owner_cannot_leave", + "guest_limit_reached", + "already_on_project", + "already_invited", + "invitation_expired", + "email_not_verified", + "invalid_project_name", + "invalid_email", + "invalid_update_id", + "empty_update", + "update_too_large", + "too_many_updates", +]; + +test("every rule MemSync can refuse by is known by name", () => { + assert.deepEqual([...refusalRules].sort(), [...namedByMemsync].sort()); + for (const rule of namedByMemsync) assert.equal(isRefusalRule(rule), true); + assert.equal(isRefusalRule("a_rule_from_a_newer_memsync"), false); + assert.equal(isRefusalRule(""), false); +}); + +test("every rule has one plain sentence of its own", () => { + const sentences = refusalRules.map((rule) => refusalSentences[rule]); + assert.equal(new Set(sentences).size, refusalRules.length); + for (const sentence of sentences) { + assert.match(sentence, /^[A-Z].*\.$/s, sentence); + assert.doesNotMatch( + sentence, + /[a-z]_[a-z]/, + "no rule names in " + sentence, + ); + assert.doesNotMatch( + sentence, + /\b(gRPC|status|metadata|MemSync)\b/, + sentence, + ); + assert.ok(sentence.length <= 220, sentence); + } +}); + +test("the sentences keep to the words of the product", () => { + const all = Object.values(refusalSentences).join(" "); + assert.doesNotMatch(all, /\bteam\b/i); + assert.doesNotMatch(all, /\bPro\b|\bPro\+/); +}); diff --git a/tests/sharing-runtime.test.ts b/tests/sharing-runtime.test.ts new file mode 100644 index 0000000..76fe472 --- /dev/null +++ b/tests/sharing-runtime.test.ts @@ -0,0 +1,365 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createRuntime } from "../runtime/app"; +import type { BetaCredentials, BetaStoredState } from "../runtime/beta"; +import type { AppState, Project } from "../src/shared"; +import type { SharingOverview } from "../src/sharing"; +import { refusalSentences } from "../src/sharing-refusals"; +import { signedInBetaStore } from "./support/beta-session"; +import { actingAs } from "./support/memsync-owner"; +import { + startStandInMemsync, + type StandInPerson, +} from "./support/memsync-stand-in"; +import { cast } from "./support/projects-api-scenarios"; + +const encoded = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + +/** memtrace.io's token endpoint: the stored session's three values in, a token out. */ +async function tokenEndpointFor( + session: BetaCredentials, + issue: () => { token: string } | { status: number }, +) { + const requests: unknown[] = []; + const server = createServer((request, response) => { + let body = ""; + request.on("data", (part) => (body += part)); + request.on("end", () => { + const sent = JSON.parse(body); + requests.push(sent); + const known = + request.method === "POST" && + request.url === "/api/memcode/memsync/token" && + Object.keys(sent).sort().join() === + "device_id,refresh_token,session_id" && + sent.refresh_token === session.refreshToken && + sent.device_id === session.deviceId && + sent.session_id === session.sessionId; + const issued = known ? issue() : { status: 401 }; + response.writeHead("token" in issued ? 200 : issued.status, { + "content-type": "application/json", + }); + response.end( + "token" in issued + ? JSON.stringify({ + access_token: issued.token, + token_type: "Bearer", + expires_in: 600, + }) + : "{}", + ); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { + url: `http://127.0.0.1:${port}/api/memcode/memsync/token`, + requests, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +/** The whole local runtime, signed in to the beta, beside a stand-in memtrace.io and sharing service. */ +async function fixture(signedIn = true) { + const root = await mkdtemp(join(tmpdir(), "memcode-sharing-runtime-")); + const service = await startStandInMemsync(); + const people = cast(); + const me: StandInPerson = people.alex; + const stored: BetaStoredState = signedIn + ? signedInBetaStore( + { id: me.accountId, name: me.name, email: me.email }, + join(root, "access.jwt"), + ) + : { configured: false, credentials: null }; + let serial = 0; + const tokens = await tokenEndpointFor( + (stored.credentials ?? {}) as BetaCredentials, + () => { + const token = [ + encoded({ alg: "EdDSA", typ: "JWT" }), + encoded({ sub: me.accountId, serial: ++serial }), + "c2lnbmF0dXJl", + ].join("."); + service.admit(token, me); + return { token }; + }, + ); + const native: string[] = []; + const emitted: string[] = []; + const start = () => + createRuntime( + join(root, "profile"), + root, + { + async call(method: string): Promise { + native.push(method); + if (method === "beta_store_read") return structuredClone(stored) as T; + if (method === "open_memcode_projects") return null as T; + throw Error("Unexpected native operation " + method); + }, + }, + (event) => emitted.push(event), + ); + const runtime = { current: await start() }; + const project: Project = { + id: "local-web", + name: "website", + description: "", + path: join(root, "website"), + branch: "main", + analysis: "idle", + createdAt: "2026-11-21T12:00:00.000Z", + }; + runtime.current.store.state.projects.push(project); + const request = (method: string, input?: unknown) => + runtime.current.request(method, input) as Promise; + return { + root, + service, + people, + me, + tokens, + native, + emitted, + request, + state: () => runtime.current.store.state, + saveAddresses: (sharing: { memsyncUrl: string; tokenUrl: string }) => + request("settings:save", { + ...runtime.current.store.state.settings, + sharing, + }), + website: (person: StandInPerson) => + actingAs(service.address, service.tokenFor(person)), + async restart() { + await runtime.current.close(); + runtime.current = await start(); + }, + async close() { + await runtime.current.close(); + await tokens.close(); + await service.close(); + await rm(root, { recursive: true, force: true }); + }, + }; +} + +test("sharing is absent until its two addresses are saved in Settings", async () => { + const f = await fixture(); + try { + assert.deepEqual(await f.request("sharing:overview"), { state: "not-set" }); + assert.equal(f.state().settings.sharing, undefined); + await assert.rejects( + f.saveAddresses({ memsyncUrl: f.service.address.href, tokenUrl: "" }), + /both addresses/, + ); + await assert.rejects( + f.saveAddresses({ + memsyncUrl: "http://sync.example.com", + tokenUrl: f.tokens.url, + }), + /https:\/\//, + ); + await assert.rejects( + f.saveAddresses({ + memsyncUrl: f.service.address.href, + tokenUrl: "https://tokens.example.com/token", + }), + /only to www\.memtrace\.io/, + ); + assert.equal(f.state().settings.sharing, undefined); + assert.equal(f.tokens.requests.length, 0); + await f.saveAddresses({ + memsyncUrl: f.service.address.href, + tokenUrl: f.tokens.url, + }); + assert.equal( + (await f.request("sharing:overview")).state, + "ready", + ); + // Emptying both fields takes sharing away again, and a later save of other settings keeps that. + await f.saveAddresses({ memsyncUrl: " ", tokenUrl: "" }); + assert.equal(f.state().settings.sharing, undefined); + assert.deepEqual(await f.request("sharing:overview"), { state: "not-set" }); + } finally { + await f.close(); + } +}); + +test("a signed-in MemCode lists shared projects, accepts an invitation and connects the open project", async () => { + const f = await fixture(); + const { dana } = f.people; + try { + await f.saveAddresses({ + memsyncUrl: f.service.address.href, + tokenUrl: f.tokens.url, + }); + const mine = await f.website(f.me).startProject("Launch plan"); + const theirs = await f.website(dana).startProject("Website"); + const invitation = await f.website(dana).invite(theirs, f.me.email!); + + const before = await f.request("sharing:overview"); + assert.equal(before.state, "ready"); + if (before.state !== "ready") return; + assert.deepEqual( + before.projects.map((project) => project.name), + ["Launch plan"], + ); + assert.deepEqual( + before.invitations.map((waiting) => [ + waiting.projectName, + waiting.invitedBy, + ]), + [["Website", dana.name]], + ); + // One exchange served every call: the token is renewed, not asked for each time. + assert.equal(f.tokens.requests.length, 1); + + const after = await f.request( + "sharing:accept-invitation", + { + projectId: theirs, + invitationId: invitation, + }, + ); + assert.equal(after.state, "ready"); + if (after.state !== "ready") return; + assert.deepEqual( + after.projects.map((project) => [project.name, project.youAreOwner]), + [ + ["Launch plan", true], + ["Website", false], + ], + ); + assert.deepEqual(after.invitations, []); + + f.emitted.length = 0; + await f.request("sharing:connect", { + projectId: "local-web", + sharedProjectId: mine, + }); + assert.deepEqual( + f + .state() + .sharedProjectLinks?.map((link) => [ + link.projectId, + link.sharedProjectName, + ]), + [["local-web", "Launch plan"]], + ); + assert.ok( + f.emitted.includes("workspace:state"), + "the app's window hears of the link", + ); + const saved: AppState = JSON.parse( + await readFile(join(f.root, "profile", "workspace.json"), "utf8"), + ); + assert.equal(saved.sharedProjectLinks?.[0].sharedProjectId, mine); + assert.deepEqual(saved.settings.sharing, { + memsyncUrl: f.service.address.href, + tokenUrl: f.tokens.url, + }); + // Neither the session nor a token is written to the workspace file or sent to the window. + const session = (await f.tokens.requests[0]) as { refresh_token: string }; + assert.ok(!JSON.stringify(saved).includes(session.refresh_token)); + assert.ok(!JSON.stringify(saved).includes("c2lnbmF0dXJl")); + + await f.restart(); + assert.equal(f.state().sharedProjectLinks?.[0].sharedProjectId, mine); + assert.equal( + (await f.request("sharing:overview")).state, + "ready", + ); + + await assert.rejects( + f.request("sharing:connect", { + projectId: "local-web", + sharedProjectId: theirs, + }), + /already connected to “Launch plan”/, + ); + await f.request("sharing:disconnect", { projectId: "local-web" }); + assert.deepEqual(f.state().sharedProjectLinks, []); + await f.website(dana).deleteProject(theirs); + await assert.rejects( + f.request("sharing:connect", { + projectId: "local-web", + sharedProjectId: theirs, + }), + { message: refusalSentences.no_such_project }, + ); + } finally { + await f.close(); + } +}); + +test("without a beta sign-in, sharing asks the person to sign in and contacts nobody", async () => { + const f = await fixture(false); + try { + await f.saveAddresses({ + memsyncUrl: f.service.address.href, + tokenUrl: f.tokens.url, + }); + const overview = await f.request("sharing:overview"); + assert.equal(overview.state, "signed-out"); + assert.equal(f.tokens.requests.length, 0); + assert.equal(f.service.calls.length, 0); + } finally { + await f.close(); + } +}); + +test("managing projects opens memtrace.io in the browser, and requests are checked before they run", async () => { + const f = await fixture(); + try { + await f.request("sharing:manage"); + assert.ok(f.native.includes("open_memcode_projects")); + for (const [method, input] of [ + ["sharing:connect", { projectId: "local-web" }], + [ + "sharing:connect", + { projectId: "local-web", sharedProjectId: "x", extra: 1 }, + ], + ["sharing:accept-invitation", { projectId: "", invitationId: "x" }], + ["sharing:disconnect", {}], + ["sharing:overview", { anything: true }], + ] as const) + await assert.rejects( + f.request(method, input), + `${method} ${JSON.stringify(input)}`, + ); + } finally { + await f.close(); + } +}); + +test("connecting through sharing makes no Team room, and Team's own requests are still there", async () => { + const f = await fixture(); + try { + await f.saveAddresses({ + memsyncUrl: f.service.address.href, + tokenUrl: f.tokens.url, + }); + const mine = await f.website(f.me).startProject("Launch plan"); + await f.request("sharing:connect", { + projectId: "local-web", + sharedProjectId: mine, + }); + assert.equal( + await f.request("team:status", { projectId: "local-web" }), + null, + ); + assert.equal(f.state().team?.length ?? 0, 0); + } finally { + await f.close(); + } +}); diff --git a/tests/sharing-wire.test.ts b/tests/sharing-wire.test.ts new file mode 100644 index 0000000..adc34d0 --- /dev/null +++ b/tests/sharing-wire.test.ts @@ -0,0 +1,257 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { + decodeMessage, + encodeMessage, + WireError, + type Contract, +} from "../runtime/sharing/memsync/wire"; +import { + projectsCalls, + projectsContract, + projectsService, +} from "../runtime/sharing/memsync/projects-contract"; + +const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString("hex"); +const bytes = (text: string) => new Uint8Array(Buffer.from(text, "hex")); + +// Made by the reference implementation, so MemCode's own encoder never checks itself: +// protoc -I proto --encode=memsync.v1.Project memsync/v1/projects.proto +// from the text below (libprotoc 35.1, 21 November 2026). +const projectId = "0d3b6f0e-5a52-4c1e-9d3e-2f1f5f3a9c11", + invitationId = "7a1c8a52-0b1f-4a43-8a3b-0c5d7e9f1a22"; +const owner = { + account_id: "acct-owner", + name: "Alex Holm", + email: "alex@example.com", +}; +const project = { + id: projectId, + name: "Launch plan ✈", + owner, + guests: [ + { account_id: "acct-guest", name: "Bo Li", email: "" }, + { + account_id: "acct-second", + name: "Chidi Okafor", + email: "chidi@example.com", + }, + ], + open_invitations: [ + { + id: invitationId, + project_id: projectId, + project_name: "Launch plan ✈", + email: "dana@example.com", + invited_by: owner, + sent_at: { seconds: 1795300000, nanos: 123456789 }, + expires_at: { seconds: 1796509600, nanos: 0 }, + }, + ], + guest_limit: 2, +}; +const projectFromProtoc = + "0a2430643362366630652d356135322d346331652d396433652d326631663566336139633131120f4c61756e636820706c616e20e29c881a290a0a616363742d6f776e65721209416c657820486f6c6d1a10616c6578406578616d706c652e636f6d22130a0a616363742d67756573741205426f204c69222e0a0b616363742d7365636f6e64120c4368696469204f6b61666f721a116368696469406578616d706c652e636f6d2aaf010a2437613163386135322d306231662d346134332d386133622d306335643765396631613232122430643362366630652d356135322d346331652d396433652d3266316635663361396331311a0f4c61756e636820706c616e20e29c88221064616e61406578616d706c652e636f6d2a290a0a616363742d6f776e65721209416c657820486f6c6d1a10616c6578406578616d706c652e636f6d320b08a0b588d80610959aef3a3a0608a09fd2d8063002"; +const acceptFromProtoc = + "0a2430643362366630652d356135322d346331652d396433652d326631663566336139633131122437613163386135322d306231662d346134332d386133622d306335643765396631613232"; + +test("a project encoded by protoc is read field for field", () => { + assert.deepEqual( + decodeMessage(projectsContract, "Project", bytes(projectFromProtoc)), + project, + ); +}); + +test("requests are written byte for byte as protoc writes them", () => { + assert.equal( + hex( + encodeMessage(projectsContract, "AcceptInvitationRequest", { + project_id: projectId, + invitation_id: invitationId, + }), + ), + acceptFromProtoc, + ); + assert.equal( + hex(encodeMessage(projectsContract, "Project", project)), + projectFromProtoc, + ); + assert.equal( + hex(encodeMessage(projectsContract, "ListProjectsRequest", {})), + "", + ); +}); + +test("fields that were not sent read as empty, and an absent message as absent", () => { + assert.deepEqual(decodeMessage(projectsContract, "Project", bytes("")), { + id: "", + name: "", + guests: [], + open_invitations: [], + guest_limit: 0, + }); +}); + +test("a field from a newer contract is skipped, whatever its kind", () => { + const withUnknowns = bytes( + "0a0161" + // id: "a" + "7801" + // field 15, varint + "8201026869" + // field 16, two bytes + "8d0101000000" + // field 17, four fixed bytes + "91010100000000000000" + // field 18, eight fixed bytes + "3002", // guest_limit: 2 + ); + const read = decodeMessage(projectsContract, "Project", withUnknowns); + assert.equal(read.id, "a"); + assert.equal(read.guest_limit, 2); +}); + +test("damaged bytes are refused with one kind of error and never crash", () => { + const damaged = [ + "0a", // a length with nothing after it + "0aff", // a string longer than the message + "0a02c328", // a string that is not UTF-8 + "ffffffffffffffffffffff01", // a number that never ends + "0800", // a number where the id's text belongs + "32020800", // guest_limit sent as a nested message + "1a05ffffffff0f", // an owner whose own bytes are cut short + "0b", // a group, which proto3 no longer has + "00", // field number zero + ]; + for (const text of damaged) + assert.throws( + () => decodeMessage(projectsContract, "Project", bytes(text)), + WireError, + text, + ); + const whole = bytes(projectFromProtoc); + for (let cut = 0; cut < whole.length; cut++) { + try { + decodeMessage(projectsContract, "Project", whole.subarray(0, cut)); + } catch (error) { + assert.ok(error instanceof WireError, `cut at ${cut}: ${error}`); + } + } + for (let at = 0; at < whole.length; at++) { + const flipped = Uint8Array.from(whole); + flipped[at] ^= 0xff; + try { + decodeMessage(projectsContract, "Project", flipped); + } catch (error) { + assert.ok(error instanceof WireError, `flipped at ${at}: ${error}`); + } + } +}); + +test("numbers keep their value at the edges", () => { + const numbers = { + Numbers: { + small: { number: 1, kind: "uint32" }, + large: { number: 2, kind: "uint64" }, + signed: { number: 3, kind: "int64" }, + short: { number: 4, kind: "int32" }, + raw: { number: 5, kind: "bytes" }, + }, + } satisfies Contract; + for (const value of [ + { + small: 4294967295, + large: 9007199254740991, + signed: -1, + short: -2147483648, + }, + { small: 1, large: 300, signed: -62135596800, short: 999999999 }, + { small: 127, large: 128, signed: 253402300799, short: -1 }, + ]) { + const sent = { ...value, raw: new Uint8Array([0, 255, 7]) }; + assert.deepEqual( + decodeMessage( + numbers, + "Numbers", + encodeMessage(numbers, "Numbers", sent), + ), + sent, + ); + } + // 2^53 cannot be told from 2^53 + 1 in a JavaScript number. + assert.throws( + () => decodeMessage(numbers, "Numbers", bytes("1080808080808080" + "10")), + WireError, + ); + assert.throws( + () => encodeMessage(numbers, "Numbers", { small: -1 }), + WireError, + ); + assert.throws( + () => encodeMessage(numbers, "Numbers", { small: 1.5 }), + WireError, + ); +}); + +/** Reads the messages and calls out of a .proto file that has no nested messages. */ +function parseProto(source: string) { + const text = source.replace(/\/\/[^\n]*/g, ""); + const messages: Record< + string, + Record + > = {}; + for (const [, name, body] of text.matchAll( + /message\s+(\w+)\s*\{([^{}]*)\}/g, + )) { + messages[name] = {}; + for (const [, repeated, kind, field, number] of body.matchAll( + /(repeated\s+)?([\w.]+)\s+(\w+)\s*=\s*(\d+)\s*;/g, + )) + messages[name][field] = { + number: Number(number), + kind, + repeated: !!repeated, + }; + } + const calls: Record = {}; + for (const [, name, request, reply] of text.matchAll( + /rpc\s+(\w+)\s*\(\s*(\w+)\s*\)\s*returns\s*\(\s*(\w+)\s*\)/g, + )) + calls[name] = { request, reply }; + return { + package: /package\s+([\w.]+)\s*;/.exec(text)?.[1], + service: /service\s+(\w+)/.exec(text)?.[1], + messages, + calls, + }; +} + +test("what MemCode reads and writes is what the contract says", async () => { + const contract = parseProto( + await readFile( + new URL("../runtime/sharing/memsync/projects.proto", import.meta.url), + "utf8", + ), + ); + assert.equal(`${contract.package}.${contract.service}`, projectsService); + for (const [name, call] of Object.entries(projectsCalls)) + assert.deepEqual(contract.calls[name], call, `call ${name}`); + const shapes = projectsContract as Contract; + for (const [name, shape] of Object.entries(shapes)) { + if (name.startsWith("google.protobuf.")) continue; + const written = Object.fromEntries( + Object.entries(shape).map(([field, written]) => [ + field, + { + number: written.number, + kind: + typeof written.kind === "string" + ? written.kind + : written.kind.message, + repeated: "repeated" in written && !!written.repeated, + }, + ]), + ); + assert.deepEqual(written, contract.messages[name], `message ${name}`); + } + // Every message a call uses is one MemCode has a shape for. + for (const call of Object.values(projectsCalls)) + for (const used of [call.request, call.reply]) + assert.ok(shapes[used], `no shape for ${used}`); +}); diff --git a/tests/sharing.test.ts b/tests/sharing.test.ts new file mode 100644 index 0000000..2065bb4 --- /dev/null +++ b/tests/sharing.test.ts @@ -0,0 +1,483 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { initialState } from "../src/seed"; +import type { AppState, Project } from "../src/shared"; +import type { SharingOverview } from "../src/sharing"; +import { refusalSentences } from "../src/sharing-refusals"; +import { Sharing } from "../runtime/sharing/sharing"; +import { + startStandInMemsync, + type StandInMemsync, + type StandInPerson, +} from "./support/memsync-stand-in"; +import { actingAs } from "./support/memsync-owner"; +import { cast } from "./support/projects-api-scenarios"; + +const tokenUrl = "http://127.0.0.1:9/api/memcode/memsync/token"; +const at = "2026-11-21T12:00:00.000Z"; +const localProject = (id: string, name: string): Project => ({ + id, + name, + description: "", + path: `/work/${name}`, + branch: "main", + analysis: "idle", + createdAt: at, +}); +const encoded = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + +/** MemCode's sharing with a sign-in the test controls, a stand-in memtrace.io and a stand-in service. */ +async function fixture() { + const service = await startStandInMemsync(); + const people = cast(); + const state: AppState = initialState(); + state.projects.push( + localProject("local-web", "website"), + localProject("local-app", "app"), + ); + state.activeProjectId = "local-web"; + state.settings.sharing = { memsyncUrl: service.address.href, tokenUrl }; + const world = { + signedIn: people.alex as StandInPerson | null, + sessionId: "session-1234567890abcdef", + saves: 0, + exchanges: [] as string[], + tokenEndpointStatus: 200, + admitAt: service as StandInMemsync, + }; + let serial = 0; + const sharing = new Sharing({ + state: () => state, + changed: async () => void world.saves++, + session: async () => + world.signedIn && { + refreshToken: "refresh-" + "r".repeat(40), + deviceId: "device-1234567890abcdef", + sessionId: world.sessionId, + accountId: world.signedIn.accountId, + }, + now: () => at, + fetcher: (async (url) => { + world.exchanges.push(String(url)); + if (world.tokenEndpointStatus !== 200) + return new Response("{}", { status: world.tokenEndpointStatus }); + const token = [ + encoded({ alg: "EdDSA", typ: "JWT" }), + encoded({ sub: world.signedIn!.accountId, serial: ++serial }), + "c2lnbmF0dXJl", + ].join("."); + world.admitAt.admit(token, world.signedIn!); + return Response.json({ + access_token: token, + token_type: "Bearer", + expires_in: 600, + }); + }) as typeof fetch, + }); + const as = (person: StandInPerson) => + actingAs(service.address, service.tokenFor(person)); + return { + service, + people, + state, + world, + sharing, + as, + close: async () => { + sharing.close(); + await service.close(); + }, + }; +} +type Ready = Extract; +const ready = (overview: SharingOverview): Ready => { + assert.equal(overview.state, "ready", JSON.stringify(overview)); + return overview as Ready; +}; +const quiet = (context: test.TestContext) => + context.mock.method(console, "error", () => {}); + +test("sharing that is not set up is absent: nobody is asked anything", async () => { + const f = await fixture(); + try { + for (const unset of [undefined, { memsyncUrl: "", tokenUrl: "" }]) { + f.state.settings.sharing = unset; + assert.deepEqual(await f.sharing.overview(), { state: "not-set" }); + await assert.rejects( + f.sharing.connect({ projectId: "local-web", sharedProjectId: "any" }), + /not set up/, + ); + } + assert.equal(f.world.exchanges.length, 0); + assert.equal(f.service.calls.length, 0); + } finally { + await f.close(); + } +}); + +test("the overview lists my projects and the invitations waiting for me", async () => { + const f = await fixture(); + const { alex, bo, dana, chidiAddress } = f.people; + try { + const launch = await f.as(alex).startProject("Launch plan"); + await f.as(bo).startProject("Bo's own project"); + const forBo = await f.as(alex).invite(launch, bo.email!); + f.world.signedIn = bo; + f.world.sessionId = "session-bo-1234567890abcdef"; + await f.sharing.acceptInvitation({ + projectId: launch, + invitationId: forBo, + }); + f.world.signedIn = alex; + f.world.sessionId = "session-1234567890abcdef"; + await f.as(alex).invite(launch, chidiAddress); + const website = await f.as(dana).startProject("Website"); + const forAlex = await f.as(dana).invite(website, alex.email!); + + const mine = ready(await f.sharing.overview()); + assert.equal(mine.accountId, alex.accountId); + assert.equal(mine.service, f.service.address.href); + assert.deepEqual(mine.projects, [ + { + id: launch, + name: "Launch plan", + owner: { name: alex.name, isYou: true }, + guests: [{ name: bo.name, isYou: false }], + youAreOwner: true, + openInvitations: 1, + guestLimit: 2, + }, + ]); + assert.equal(mine.invitations.length, 1); + assert.deepEqual( + { ...mine.invitations[0], expiresAt: "" }, + { + id: forAlex, + projectId: website, + projectName: "Website", + invitedBy: dana.name, + expiresAt: "", + }, + ); + assert.ok(Date.parse(mine.invitations[0].expiresAt) > Date.parse(at)); + // Nothing about other people but their names reaches the app's window. + const shown = JSON.stringify(mine); + for (const hidden of [ + bo.accountId, + bo.email!, + dana.accountId, + dana.email!, + chidiAddress, + ]) + assert.ok(!shown.includes(hidden), hidden); + + f.world.signedIn = bo; + f.world.sessionId = "session-bo-1234567890abcdef"; + const asGuest = ready(await f.sharing.overview()); + assert.deepEqual( + asGuest.projects.map((project) => [project.name, project.youAreOwner]), + [ + ["Bo's own project", true], + ["Launch plan", false], + ], + ); + assert.deepEqual(asGuest.projects[1].guests, [ + { name: bo.name, isYou: true }, + ]); + assert.deepEqual(asGuest.projects[1].owner, { + name: alex.name, + isYou: false, + }); + } finally { + await f.close(); + } +}); + +test("accepting an invitation answers with the lists as they are now", async () => { + const f = await fixture(); + const { alex, dana } = f.people; + try { + const website = await f.as(dana).startProject("Website"); + const forAlex = await f.as(dana).invite(website, alex.email!); + const after = ready( + await f.sharing.acceptInvitation({ + projectId: website, + invitationId: forAlex, + }), + ); + assert.deepEqual(after.invitations, []); + assert.deepEqual( + after.projects.map((project) => [project.name, project.youAreOwner]), + [["Website", false]], + ); + } finally { + await f.close(); + } +}); + +test("a refusal reaches the person as the sentence for its rule", async () => { + const f = await fixture(); + const { alex, dana } = f.people; + try { + const website = await f.as(dana).startProject("Website"); + await assert.rejects( + f.sharing.acceptInvitation({ + projectId: website, + invitationId: "no-such-id", + }), + { message: refusalSentences.no_such_invitation }, + ); + await assert.rejects( + f.sharing.connect({ projectId: "local-web", sharedProjectId: website }), + { message: refusalSentences.no_such_project }, + ); + assert.equal(f.state.sharedProjectLinks, undefined); + assert.equal(alex.accountId.length > 0, true); + } finally { + await f.close(); + } +}); + +test("without a Memtrace sign-in the overview says so, and nothing is sent", async () => { + const f = await fixture(); + try { + f.world.signedIn = null; + const overview = await f.sharing.overview(); + assert.equal(overview.state, "signed-out"); + assert.match( + (overview as { detail: string }).detail, + /Sign in to Memtrace/, + ); + await assert.rejects( + f.sharing.acceptInvitation({ projectId: "p", invitationId: "i" }), + /Sign in to Memtrace/, + ); + assert.equal(f.world.exchanges.length, 0); + assert.equal(f.service.calls.length, 0); + } finally { + await f.close(); + } +}); + +test("a problem on the way is an overview that says what to do, never an exception", async (context) => { + quiet(context); + const f = await fixture(); + try { + f.world.tokenEndpointStatus = 503; + assert.deepEqual(await f.sharing.overview(), { + state: "unavailable", + detail: + "Sharing is switched off or not set up at memtrace.io right now. Try again later.", + }); + f.world.tokenEndpointStatus = 401; + assert.equal((await f.sharing.overview()).state, "signed-out"); + f.world.tokenEndpointStatus = 200; + f.service.refuseNextCallBy("no_such_project"); + assert.deepEqual(await f.sharing.overview(), { + state: "unavailable", + detail: refusalSentences.no_such_project, + }); + f.state.settings.sharing = { + memsyncUrl: "http://sync.example.com", + tokenUrl, + }; + const mistyped = await f.sharing.overview(); + assert.equal(mistyped.state, "unavailable"); + assert.match((mistyped as { detail: string }).detail, /https:\/\//); + f.state.settings.sharing = { memsyncUrl: f.service.address.href, tokenUrl }; + await f.service.close(); + const down = await f.sharing.overview(); + assert.equal(down.state, "unavailable"); + assert.match((down as { detail: string }).detail, /could not be reached/); + } finally { + await f.close(); + } +}); + +test("connecting records which shared project a local project's board belongs to", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + const launch = await f.as(alex).startProject("Launch plan"); + const link = await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: launch, + }); + assert.deepEqual(link, { + projectId: "local-web", + sharedProjectId: launch, + sharedProjectName: "Launch plan", + accountId: alex.accountId, + service: f.service.address.href, + connectedAt: at, + }); + assert.deepEqual(f.state.sharedProjectLinks, [link]); + assert.equal(f.world.saves, 1); + // Connecting asks the service only whether the person is on that project. + assert.deepEqual( + f.service.calls + .filter((call) => call.method !== "StartProject") + .map((call) => call.method), + ["GetProject"], + ); + } finally { + await f.close(); + } +}); + +test("a local project is connected to one shared project, and a shared project to one local project", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + const launch = await f.as(alex).startProject("Launch plan"), + website = await f.as(alex).startProject("Website"); + await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: launch, + }); + await assert.rejects( + f.sharing.connect({ projectId: "local-web", sharedProjectId: website }), + /already connected to “Launch plan”/, + ); + await assert.rejects( + f.sharing.connect({ projectId: "local-app", sharedProjectId: launch }), + /“Launch plan” is already connected to “website” on this computer/, + ); + assert.equal(f.state.sharedProjectLinks!.length, 1); + assert.equal(f.world.saves, 1); + await f.sharing.connect({ + projectId: "local-app", + sharedProjectId: website, + }); + assert.deepEqual( + f.state.sharedProjectLinks!.map((link) => [ + link.projectId, + link.sharedProjectName, + ]), + [ + ["local-web", "Launch plan"], + ["local-app", "Website"], + ], + ); + } finally { + await f.close(); + } +}); + +test("two connects for one project at the same moment leave one link", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + const launch = await f.as(alex).startProject("Launch plan"), + website = await f.as(alex).startProject("Website"); + const outcomes = await Promise.allSettled([ + f.sharing.connect({ projectId: "local-web", sharedProjectId: launch }), + f.sharing.connect({ projectId: "local-web", sharedProjectId: website }), + ]); + assert.deepEqual(outcomes.map((outcome) => outcome.status).sort(), [ + "fulfilled", + "rejected", + ]); + assert.equal(f.state.sharedProjectLinks!.length, 1); + } finally { + await f.close(); + } +}); + +test("the example project, a Team project and a project that is not there cannot be connected", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + const launch = await f.as(alex).startProject("Launch plan"); + await assert.rejects( + f.sharing.connect({ projectId: "example", sharedProjectId: launch }), + /example project/, + ); + f.state.team = [ + { projectId: "local-app" } as NonNullable[number], + ]; + await assert.rejects( + f.sharing.connect({ projectId: "local-app", sharedProjectId: launch }), + /Team Sync/, + ); + await assert.rejects( + f.sharing.connect({ projectId: "gone", sharedProjectId: launch }), + /Project not found/, + ); + assert.equal(f.state.sharedProjectLinks, undefined); + assert.equal(f.world.saves, 0); + assert.ok(!f.service.calls.some((call) => call.method === "GetProject")); + } finally { + await f.close(); + } +}); + +test("disconnecting forgets the link on this computer and asks the service nothing", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + const launch = await f.as(alex).startProject("Launch plan"), + website = await f.as(alex).startProject("Website"); + await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: launch, + }); + await f.sharing.connect({ + projectId: "local-app", + sharedProjectId: website, + }); + const asked = f.service.calls.length; + await f.sharing.disconnect("local-web"); + assert.deepEqual( + f.state.sharedProjectLinks!.map((link) => link.projectId), + ["local-app"], + ); + assert.equal(f.world.saves, 3); + await f.sharing.disconnect("local-web"); + assert.equal(f.world.saves, 3); + assert.equal(f.service.calls.length, asked); + // The person is still on the shared project, and can connect it again. + await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: launch, + }); + f.world.signedIn = null; + await f.sharing.disconnect("local-app"); + assert.deepEqual( + f.state.sharedProjectLinks!.map((link) => link.projectId), + ["local-web"], + ); + } finally { + await f.close(); + } +}); + +test("a new sharing address in Settings is used from the next call on", async () => { + const f = await fixture(); + const elsewhere = await startStandInMemsync(); + const { alex } = f.people; + try { + await f.as(alex).startProject("On the first service"); + await actingAs(elsewhere.address, elsewhere.tokenFor(alex)).startProject( + "On the second service", + ); + assert.deepEqual( + ready(await f.sharing.overview()).projects.map((project) => project.name), + ["On the first service"], + ); + f.state.settings.sharing = { memsyncUrl: elsewhere.address.href, tokenUrl }; + f.world.admitAt = elsewhere; + const moved = ready(await f.sharing.overview()); + assert.deepEqual( + moved.projects.map((project) => project.name), + ["On the second service"], + ); + assert.equal(moved.service, elsewhere.address.href); + // The token for the first service was not carried over to the second. + assert.equal(f.world.exchanges.length, 2); + } finally { + await f.close(); + await elsewhere.close(); + } +}); diff --git a/tests/support/beta-session.ts b/tests/support/beta-session.ts new file mode 100644 index 0000000..25ebb88 --- /dev/null +++ b/tests/support/beta-session.ts @@ -0,0 +1,73 @@ +import { generateKeyPairSync, randomBytes, sign } from "node:crypto"; +import { + BETA_PROGRAM, + BETA_TERMS, + type BetaPublicKey, +} from "../../runtime/beta-auth"; +import type { BetaCredentials, BetaStoredState } from "../../runtime/beta"; + +const encoded = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + +/** + * What the native credential store holds for someone who is signed in to the + * beta: their session and a current engine proof, signed by a key made here. + */ +export function signedInBetaStore( + account: { id: string; name: string; email?: string }, + accessFile: string, +): BetaStoredState { + const pair = generateKeyPairSync("ed25519"); + const publicKey = { + ...pair.publicKey.export({ format: "jwk" }), + kid: "memcode-test-session", + alg: "EdDSA", + use: "sig", + } as BetaPublicKey; + const deviceId = "device-" + randomBytes(12).toString("hex"), + sessionId = "session-" + randomBytes(12).toString("hex"), + issuedAt = Math.floor(Date.now() / 1000); + const unsigned = [ + encoded({ alg: "EdDSA", typ: "JWT", kid: publicKey.kid }), + encoded({ + iss: "https://memtrace.io", + aud: "memcode-engine-beta", + purpose: "memcode-engine-beta", + program: BETA_PROGRAM, + sub: account.id, + name: account.name, + ...(account.email ? { email: account.email } : {}), + device_id: deviceId, + session_id: sessionId, + terms_version: BETA_TERMS, + entitlements: { + local_engine: true, + graph_queries: "unlimited", + cortex: true, + improve: true, + external_memdb: false, + provider_credits: false, + }, + iat: issuedAt, + exp: issuedAt + 900, + jti: randomBytes(32).toString("base64url"), + }), + ].join("."); + const credentials: BetaCredentials = { + version: 1, + deviceId, + sessionId, + refreshToken: randomBytes(32).toString("base64url"), + refreshExpiresAt: new Date(Date.now() + 30 * 86400000).toISOString(), + account, + termsVersion: BETA_TERMS, + publicKey, + accessExpiresAt: new Date((issuedAt + 900) * 1000).toISOString(), + }; + return { + configured: true, + credentials, + accessToken: `${unsigned}.${sign(null, Buffer.from(unsigned), pair.privateKey).toString("base64url")}`, + accessFile, + }; +} diff --git a/tests/support/memsync-owner.ts b/tests/support/memsync-owner.ts new file mode 100644 index 0000000..01bf053 --- /dev/null +++ b/tests/support/memsync-owner.ts @@ -0,0 +1,78 @@ +import { + projectsCalls, + projectsContract, + projectsService, +} from "../../runtime/sharing/memsync/projects-contract"; +import { grpcChannel } from "../../runtime/sharing/memsync/grpc"; +import { + decodeMessage, + encodeMessage, + type Contract, + type WireMessage, +} from "../../runtime/sharing/memsync/wire"; + +/** + * What an owner does at memtrace.io, which MemCode itself never does: start a + * project, invite, cancel, remove, delete. Tests need these to set a scene. + * `sharing-wire.test.ts` checks these shapes against the .proto file too. + */ +const text = (number: number) => ({ number, kind: "string" }) as const; +export const ownerContract = { + ...projectsContract, + StartProjectRequest: { name: text(1) }, + InvitePersonRequest: { project_id: text(1), email: text(2) }, + CancelInvitationRequest: { project_id: text(1), invitation_id: text(2) }, + RemoveGuestRequest: { project_id: text(1), account_id: text(2) }, + DeleteProjectRequest: { project_id: text(1) }, + DeleteProjectResponse: {}, +} satisfies Contract; +export const ownerCalls = { + ...projectsCalls, + StartProject: { request: "StartProjectRequest", reply: "Project" }, + InvitePerson: { request: "InvitePersonRequest", reply: "Invitation" }, + CancelInvitation: { request: "CancelInvitationRequest", reply: "Project" }, + RemoveGuest: { request: "RemoveGuestRequest", reply: "Project" }, + DeleteProject: { + request: "DeleteProjectRequest", + reply: "DeleteProjectResponse", + }, +} as const; + +/** One signed-in person acting on the sharing service the way the website does. */ +export function actingAs(address: URL, token: string) { + const call = async ( + name: keyof typeof ownerCalls, + request: WireMessage, + ): Promise => { + const channel = grpcChannel(address); + try { + const reply = await channel.unary({ + path: `/${projectsService}/${name}`, + request: encodeMessage( + ownerContract, + ownerCalls[name].request, + request, + ), + metadata: { authorization: `Bearer ${token}` }, + }); + return decodeMessage(ownerContract, ownerCalls[name].reply, reply); + } finally { + channel.close(); + } + }; + return { + startProject: async (name: string) => + String((await call("StartProject", { name })).id), + invite: async (projectId: string, email: string) => + String((await call("InvitePerson", { project_id: projectId, email })).id), + cancelInvitation: (projectId: string, invitationId: string) => + call("CancelInvitation", { + project_id: projectId, + invitation_id: invitationId, + }), + removeGuest: (projectId: string, accountId: string) => + call("RemoveGuest", { project_id: projectId, account_id: accountId }), + deleteProject: (projectId: string) => + call("DeleteProject", { project_id: projectId }), + }; +} diff --git a/tests/support/memsync-stand-in.ts b/tests/support/memsync-stand-in.ts new file mode 100644 index 0000000..a17a704 --- /dev/null +++ b/tests/support/memsync-stand-in.ts @@ -0,0 +1,355 @@ +import { createServer, type ServerHttp2Stream } from "node:http2"; +import type { AddressInfo } from "node:net"; +import { randomBytes, randomUUID } from "node:crypto"; +import { + decodeMessage, + encodeMessage, + type WireMessage, +} from "../../runtime/sharing/memsync/wire"; +import { grpcStatus } from "../../runtime/sharing/memsync/grpc"; +import { ownerCalls, ownerContract } from "./memsync-owner"; + +/** Someone a token signs in. `email` is their verified address, if they have one. */ +export interface StandInPerson { + accountId: string; + name: string; + email?: string; +} +interface Invitation { + id: string; + email: string; + invitedBy: StandInPerson; + sentAt: number; +} +interface Project { + id: string; + name: string; + owner: StandInPerson; + guests: StandInPerson[]; + invitations: Invitation[]; +} + +// A field number that never ends, which no reader takes for a message. +const NEVER_A_MESSAGE = Buffer.alloc(24, 0xff); +const GUEST_LIMIT = 2, + INVITATION_LIFETIME_MS = 14 * 86400000; + +/** A refusal as MemSync sends it: a status, and the rule's name as metadata. */ +class Refused extends Error { + constructor( + readonly status: number, + readonly rule?: string, + ) { + super(rule ?? "refused"); + } +} +const refusals = { + no_such_project: grpcStatus.NOT_FOUND, + no_such_invitation: grpcStatus.NOT_FOUND, + no_such_guest: grpcStatus.NOT_FOUND, + only_the_owner_invites: grpcStatus.PERMISSION_DENIED, + not_the_owner: grpcStatus.PERMISSION_DENIED, + guest_limit_reached: grpcStatus.RESOURCE_EXHAUSTED, + already_on_project: grpcStatus.ALREADY_EXISTS, + already_invited: grpcStatus.ALREADY_EXISTS, + invitation_expired: grpcStatus.FAILED_PRECONDITION, + email_not_verified: grpcStatus.FAILED_PRECONDITION, + invalid_project_name: grpcStatus.INVALID_ARGUMENT, + invalid_email: grpcStatus.INVALID_ARGUMENT, +} as const; +const refuse = (rule: keyof typeof refusals): never => { + throw new Refused(refusals[rule], rule); +}; + +const moment = (ms: number) => ({ + seconds: Math.floor(ms / 1000), + nanos: (ms % 1000) * 1e6, +}); +const personMessage = (person: StandInPerson): WireMessage => ({ + account_id: person.accountId, + name: person.name, + email: person.email ?? "", +}); + +/** + * MemSync's Projects service with its rules for personal projects, kept in memory. + * It speaks the real wire format over HTTP/2, so MemCode's own client talks to it. + * `tests/sharing-real-memsync.test.ts` runs the same scenarios against the real server. + */ +export async function startStandInMemsync() { + const projects = new Map(); + const signedIn = new Map(); + const calls: Array<{ method: string; token: string }> = []; + let now = Date.parse("2026-11-21T12:00:00Z"); + let turnAway: Refused[] = []; + let garbleNext = false; + let stallNext = false; + + const isOn = (project: Project, person: StandInPerson) => + project.owner.accountId === person.accountId || + project.guests.some((guest) => guest.accountId === person.accountId); + const isOpen = (invitation: Invitation) => + now < invitation.sentAt + INVITATION_LIFETIME_MS; + const invitationMessage = (project: Project, invitation: Invitation) => ({ + id: invitation.id, + project_id: project.id, + project_name: project.name, + email: invitation.email, + invited_by: personMessage(invitation.invitedBy), + sent_at: moment(invitation.sentAt), + expires_at: moment(invitation.sentAt + INVITATION_LIFETIME_MS), + }); + const projectMessage = (project: Project): WireMessage => ({ + id: project.id, + name: project.name, + owner: personMessage(project.owner), + guests: project.guests.map(personMessage), + open_invitations: project.invitations + .filter(isOpen) + .map((invitation) => invitationMessage(project, invitation)), + guest_limit: GUEST_LIMIT, + }); + const found = (id: unknown) => + projects.get(String(id)) ?? refuse("no_such_project"); + const sharedWith = (id: unknown, person: StandInPerson) => { + const project = found(id); + return isOn(project, person) ? project : refuse("no_such_project"); + }; + const ownedBy = ( + id: unknown, + person: StandInPerson, + guestsAreTold: keyof typeof refusals, + ) => { + const project = sharedWith(id, person); + return project.owner.accountId === person.accountId + ? project + : refuse(guestsAreTold); + }; + + const handlers: Record< + keyof typeof ownerCalls, + (request: WireMessage, caller: StandInPerson) => WireMessage + > = { + StartProject({ name }, caller) { + const trimmed = String(name).trim(); + if (!trimmed || [...trimmed].length > 240 || /\p{Cc}/u.test(trimmed)) + refuse("invalid_project_name"); + const project: Project = { + id: randomUUID(), + name: trimmed, + owner: caller, + guests: [], + invitations: [], + }; + projects.set(project.id, project); + return projectMessage(project); + }, + ListProjects(_request, caller) { + const mine = [...projects.values()].filter((project) => + isOn(project, caller), + ); + mine.sort((left, right) => (left.name < right.name ? -1 : 1)); + return { projects: mine.map(projectMessage) }; + }, + GetProject({ project_id }, caller) { + return projectMessage(sharedWith(project_id, caller)); + }, + InvitePerson({ project_id, email }, caller) { + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(email))) + refuse("invalid_email"); + const project = ownedBy(project_id, caller, "only_the_owner_invites"); + const address = String(email).toLowerCase(); + if ( + [project.owner, ...project.guests].some( + (person) => person.email === address, + ) + ) + refuse("already_on_project"); + const open = project.invitations.filter(isOpen); + if (open.some((invitation) => invitation.email === address)) + refuse("already_invited"); + if (project.guests.length + open.length >= GUEST_LIMIT) + refuse("guest_limit_reached"); + const invitation: Invitation = { + id: randomUUID(), + email: address, + invitedBy: caller, + sentAt: now, + }; + project.invitations.push(invitation); + return invitationMessage(project, invitation); + }, + ListInvitations(_request, caller) { + const waiting = [...projects.values()].flatMap((project) => + project.invitations + .filter( + (invitation) => + isOpen(invitation) && invitation.email === caller.email, + ) + .map((invitation) => invitationMessage(project, invitation)), + ); + return { invitations: waiting }; + }, + AcceptInvitation({ project_id, invitation_id }, caller) { + const project = found(project_id); + const invitation = + project.invitations.find((sent) => sent.id === invitation_id) ?? + refuse("no_such_invitation"); + if (isOn(project, caller)) refuse("already_on_project"); + if (!isOpen(invitation)) refuse("invitation_expired"); + if (!caller.email) refuse("email_not_verified"); + if (caller.email !== invitation.email) refuse("no_such_invitation"); + project.invitations = project.invitations.filter( + (sent) => sent !== invitation, + ); + project.guests.push(caller); + return projectMessage(project); + }, + CancelInvitation({ project_id, invitation_id }, caller) { + const project = ownedBy(project_id, caller, "not_the_owner"); + if (!project.invitations.some((sent) => sent.id === invitation_id)) + refuse("no_such_invitation"); + project.invitations = project.invitations.filter( + (sent) => sent.id !== invitation_id, + ); + return projectMessage(project); + }, + RemoveGuest({ project_id, account_id }, caller) { + const project = ownedBy(project_id, caller, "not_the_owner"); + if (!project.guests.some((guest) => guest.accountId === account_id)) + refuse("no_such_guest"); + project.guests = project.guests.filter( + (guest) => guest.accountId !== account_id, + ); + return projectMessage(project); + }, + DeleteProject({ project_id }, caller) { + projects.delete(ownedBy(project_id, caller, "not_the_owner").id); + return {}; + }, + }; + + const framed = (message: Uint8Array) => { + const frame = Buffer.alloc(5 + message.length); + frame.writeUInt32BE(message.length, 1); + frame.set(message, 5); + return frame; + }; + const turnDown = (stream: ServerHttp2Stream, refused: Refused) => + stream.respond( + { + ":status": 200, + "content-type": "application/grpc", + "grpc-status": String(refused.status), + "grpc-message": encodeURIComponent(refused.message), + ...(refused.rule ? { "memsync-refusal": refused.rule } : {}), + }, + { endStream: true }, + ); + function answer( + stream: ServerHttp2Stream, + path: string, + bearer: string, + body: Buffer, + ) { + const method = path.split("/").at(-1) as keyof typeof ownerCalls; + const token = bearer.replace(/^Bearer /, ""); + calls.push({ method, token }); + if (stallNext) return void (stallNext = false); + try { + const forced = turnAway.shift(); + if (forced) throw forced; + const caller = signedIn.get(token); + if (!caller || !bearer.startsWith("Bearer ")) + throw new Refused(grpcStatus.UNAUTHENTICATED); + const call = ownerCalls[method]; + if (!call) throw new Refused(grpcStatus.UNIMPLEMENTED); + const reply = handlers[method]( + decodeMessage(ownerContract, call.request, body.subarray(5)), + caller, + ); + stream.respond( + { ":status": 200, "content-type": "application/grpc" }, + { waitForTrailers: true }, + ); + stream.on("wantTrailers", () => + stream.sendTrailers({ "grpc-status": "0" }), + ); + const sent = encodeMessage(ownerContract, call.reply, reply); + stream.end(framed(garbleNext ? NEVER_A_MESSAGE : sent)); + garbleNext = false; + } catch (problem) { + if (!(problem instanceof Refused)) throw problem; + turnDown(stream, problem); + } + } + + const server = createServer(); + const sessions = new Set(); + server.on("session", (session) => { + sessions.add(session); + session.on("close", () => sessions.delete(session)); + }); + server.on("stream", (stream, headers) => { + const parts: Buffer[] = []; + stream.on("error", () => {}); + stream.on("data", (part: Buffer) => parts.push(part)); + stream.on("end", () => + answer( + stream as ServerHttp2Stream, + String(headers[":path"]), + String(headers.authorization ?? ""), + Buffer.concat(parts), + ), + ); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + + return { + address: new URL(`http://127.0.0.1:${port}`), + calls, + /** A token that signs this person in. A person signed in twice has two tokens. */ + tokenFor(person: StandInPerson): string { + const token = randomBytes(24).toString("base64url"); + signedIn.set(token, person); + return token; + }, + /** Takes a token someone else issued as this person's, as MemSync takes memtrace.io's. */ + admit(token: string, person: StandInPerson) { + signedIn.set(token, person); + }, + expire(token: string) { + signedIn.delete(token); + }, + /** Days pass, which is how an invitation expires. */ + daysPass(days: number) { + now += days * 86400000; + }, + /** The next call is turned away as not signed in, whatever token it carries. */ + turnAwayNextCall() { + turnAway.push(new Refused(grpcStatus.UNAUTHENTICATED)); + }, + /** The next call is turned down by a rule, as a newer MemSync might. */ + refuseNextCallBy( + rule: string, + status: number = grpcStatus.FAILED_PRECONDITION, + ) { + turnAway.push(new Refused(status, rule)); + }, + failNextCall(status: number) { + turnAway.push(new Refused(status)); + }, + garbleNextReply() { + garbleNext = true; + }, + stallNextCall() { + stallNext = true; + }, + async close() { + sessions.forEach((session) => session.destroy()); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +} +export type StandInMemsync = Awaited>; diff --git a/tests/support/projects-api-scenarios.ts b/tests/support/projects-api-scenarios.ts new file mode 100644 index 0000000..f3e56bf --- /dev/null +++ b/tests/support/projects-api-scenarios.ts @@ -0,0 +1,342 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { grpcChannel } from "../../runtime/sharing/memsync/grpc"; +import { MemsyncProjects } from "../../runtime/sharing/memsync/projects-api"; +import { SharingRefused } from "../../runtime/sharing/problems"; +import type { RefusalRule } from "../../src/sharing-refusals"; +import { actingAs } from "./memsync-owner"; +import type { StandInPerson } from "./memsync-stand-in"; + +/** A sharing service to run a scenario against: the stand-in, or a real memsync-server. */ +export interface SharingWorld { + address: URL; + /** A token the service takes as this person. */ + tokenFor(person: StandInPerson): string; + /** Only a world that can move its clock has this. */ + daysPass?(days: number): void; + close(): Promise; +} + +/** People who are new in every scenario, so scenarios never see each other's projects. */ +export function cast() { + const unique = randomUUID().slice(0, 8); + const person = (name: string, verified = true): StandInPerson => ({ + accountId: `${name.toLowerCase()}-${unique}`, + name: `${name} Example`, + ...(verified + ? { email: `${name.toLowerCase()}.${unique}@example.com` } + : {}), + }); + return { + alex: person("Alex"), + bo: person("Bo"), + dana: person("Dana"), + /** Signed in, with no verified email address. */ + chidi: person("Chidi", false), + chidiAddress: `chidi.${unique}@example.com`, + }; +} + +export function signedInTo(world: SharingWorld, person: StandInPerson) { + const token = world.tokenFor(person); + const channel = grpcChannel(world.address); + return { + token, + /** MemCode's own client. */ + projects: new MemsyncProjects(channel, { + current: async () => ({ token, accountId: person.accountId }), + forget() {}, + }), + /** What the same person does at memtrace.io. */ + website: actingAs(world.address, token), + close: () => channel.close(), + }; +} + +export const refusedBy = (rule: RefusalRule) => (problem: unknown) => { + assert.ok(problem instanceof SharingRefused, String(problem)); + assert.equal(problem.rule, rule); + return true; +}; + +/** What MemCode's Projects client must do against any sharing service that follows the contract. */ +export function projectsApiScenarios( + where: string, + open: () => Promise, + options: { skip?: string | false } = {}, +) { + const scenario = ( + name: string, + run: (world: SharingWorld) => Promise, + needs?: "a clock to move", + ) => + test(`${where}: ${name}`, { skip: options.skip }, async (context) => { + const world = await open(); + try { + if (needs && !world.daysPass) + return context.skip("this sharing service's clock cannot be moved"); + await run(world); + } finally { + await world.close(); + } + }); + + scenario("someone new has no projects and no invitations", async (world) => { + const bo = signedInTo(world, cast().bo); + try { + assert.deepEqual(await bo.projects.listProjects(), []); + assert.deepEqual(await bo.projects.listInvitations(), []); + } finally { + bo.close(); + } + }); + + scenario( + "an owner sees their project with its open invitation", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex); + try { + const id = await alex.website.startProject(" Launch plan ✈ "); + const invitationId = await alex.website.invite(id, people.bo.email!); + const [listed] = await alex.projects.listProjects(); + assert.equal(listed.id, id); + assert.equal(listed.name, "Launch plan ✈"); + assert.deepEqual(listed.owner, people.alex); + assert.deepEqual(listed.guests, []); + assert.equal(listed.guestLimit, 2); + assert.equal(listed.openInvitations.length, 1); + const [open] = listed.openInvitations; + assert.equal(open.id, invitationId); + assert.equal(open.email, people.bo.email); + assert.deepEqual(open.invitedBy, people.alex); + const lifetimeDays = + (Date.parse(open.expiresAt) - Date.parse(open.sentAt)) / 86400000; + assert.equal(lifetimeDays, 14); + assert.deepEqual(await alex.projects.getProject(id), listed); + } finally { + alex.close(); + } + }, + ); + + scenario( + "an invited person finds the invitation, accepts it and is a guest", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo); + try { + const id = await alex.website.startProject("Launch plan"); + const invitationId = await alex.website.invite(id, people.bo.email!); + const waiting = await bo.projects.listInvitations(); + assert.equal(waiting.length, 1); + assert.equal(waiting[0].id, invitationId); + assert.equal(waiting[0].projectId, id); + assert.equal(waiting[0].projectName, "Launch plan"); + assert.equal(waiting[0].invitedBy?.name, people.alex.name); + assert.deepEqual(await bo.projects.listProjects(), []); + + const joined = await bo.projects.acceptInvitation(id, invitationId); + assert.deepEqual(joined.guests, [people.bo]); + assert.deepEqual(joined.openInvitations, []); + assert.deepEqual(await bo.projects.listInvitations(), []); + assert.deepEqual( + (await bo.projects.listProjects()).map((project) => project.id), + [id], + ); + assert.deepEqual((await alex.projects.getProject(id)).guests, [ + people.bo, + ]); + } finally { + alex.close(); + bo.close(); + } + }, + ); + + scenario("projects come listed by name", async (world) => { + const alex = signedInTo(world, cast().alex); + try { + for (const name of ["Website", "Android app", "Launch plan"]) + await alex.website.startProject(name); + assert.deepEqual( + (await alex.projects.listProjects()).map((project) => project.name), + ["Android app", "Launch plan", "Website"], + ); + } finally { + alex.close(); + } + }); + + scenario( + "a project someone is not on reads as no such project", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + dana = signedInTo(world, people.dana); + try { + const id = await alex.website.startProject("Private"); + for (const asked of [id, randomUUID(), "not-an-id", ""]) + await assert.rejects( + dana.projects.getProject(asked), + refusedBy("no_such_project"), + ); + } finally { + alex.close(); + dana.close(); + } + }, + ); + + scenario( + "an invitation cannot be accepted by someone it was not sent to", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo), + dana = signedInTo(world, people.dana), + chidi = signedInTo(world, people.chidi); + try { + const id = await alex.website.startProject("Launch plan"); + const forBo = await alex.website.invite(id, people.bo.email!); + await assert.rejects( + dana.projects.acceptInvitation(id, forBo), + refusedBy("no_such_invitation"), + ); + await assert.rejects( + bo.projects.acceptInvitation(id, randomUUID()), + refusedBy("no_such_invitation"), + ); + await assert.rejects( + bo.projects.acceptInvitation(randomUUID(), forBo), + refusedBy("no_such_project"), + ); + // Signed in, but with no verified address to match the invitation against. + const forChidi = await alex.website.invite(id, people.chidiAddress); + await assert.rejects( + chidi.projects.acceptInvitation(id, forChidi), + refusedBy("email_not_verified"), + ); + assert.deepEqual((await alex.projects.getProject(id)).guests, []); + } finally { + for (const person of [alex, bo, dana, chidi]) person.close(); + } + }, + ); + + scenario( + "accepting twice, or as someone already on the project, changes nothing", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo); + try { + const id = await alex.website.startProject("Launch plan"); + const forBo = await alex.website.invite(id, people.bo.email!); + await bo.projects.acceptInvitation(id, forBo); + await assert.rejects( + bo.projects.acceptInvitation(id, forBo), + refusedBy("no_such_invitation"), + ); + const forDana = await alex.website.invite(id, people.dana.email!); + await assert.rejects( + bo.projects.acceptInvitation(id, forDana), + refusedBy("already_on_project"), + ); + const now = await alex.projects.getProject(id); + assert.deepEqual(now.guests, [people.bo]); + assert.equal(now.openInvitations.length, 1); + } finally { + alex.close(); + bo.close(); + } + }, + ); + + scenario( + "a cancelled invitation is gone from the invited person's list", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo); + try { + const id = await alex.website.startProject("Launch plan"); + const forBo = await alex.website.invite(id, people.bo.email!); + await alex.website.cancelInvitation(id, forBo); + assert.deepEqual(await bo.projects.listInvitations(), []); + await assert.rejects( + bo.projects.acceptInvitation(id, forBo), + refusedBy("no_such_invitation"), + ); + } finally { + alex.close(); + bo.close(); + } + }, + ); + + scenario( + "a removed guest and a deleted project both read as no such project", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo); + try { + const kept = await alex.website.startProject("Kept"), + deleted = await alex.website.startProject("Deleted"); + for (const id of [kept, deleted]) + await bo.projects.acceptInvitation( + id, + await alex.website.invite(id, people.bo.email!), + ); + assert.equal((await bo.projects.listProjects()).length, 2); + await alex.website.removeGuest(kept, people.bo.accountId); + await alex.website.deleteProject(deleted); + assert.deepEqual(await bo.projects.listProjects(), []); + for (const id of [kept, deleted]) + await assert.rejects( + bo.projects.getProject(id), + refusedBy("no_such_project"), + ); + assert.deepEqual( + (await alex.projects.listProjects()).map((project) => project.id), + [kept], + ); + } finally { + alex.close(); + bo.close(); + } + }, + ); + + scenario( + "an invitation older than fourteen days is no longer listed and cannot be accepted", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo); + try { + const id = await alex.website.startProject("Launch plan"); + const forBo = await alex.website.invite(id, people.bo.email!); + world.daysPass!(13); + assert.equal((await bo.projects.listInvitations()).length, 1); + world.daysPass!(2); + assert.deepEqual(await bo.projects.listInvitations(), []); + await assert.rejects( + bo.projects.acceptInvitation(id, forBo), + refusedBy("invitation_expired"), + ); + assert.deepEqual( + (await alex.projects.getProject(id)).openInvitations, + [], + ); + } finally { + alex.close(); + bo.close(); + } + }, + "a clock to move", + ); +} diff --git a/tests/support/real-memsync.ts b/tests/support/real-memsync.ts new file mode 100644 index 0000000..03c8170 --- /dev/null +++ b/tests/support/real-memsync.ts @@ -0,0 +1,169 @@ +import { execFile, spawn } from "node:child_process"; +import { generateKeyPairSync, randomBytes, sign } from "node:crypto"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { createServer, type AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { + GrpcFailure, + grpcChannel, + grpcStatus, +} from "../../runtime/sharing/memsync/grpc"; +import type { StandInPerson } from "./memsync-stand-in"; +import type { SharingWorld } from "./projects-api-scenarios"; + +const BINARY = "MEMSYNC_SERVER_BINARY", + DATABASE_SERVER = "MEMSYNC_TEST_DATABASE_URL", + PSQL = "MEMSYNC_TEST_PSQL"; +const ISSUER = "https://memtrace.io", + AUDIENCE = "memsync", + KEY_ID = "memcode-tests"; + +/** Why the tests against a real memsync-server cannot run here, or nothing when they can. */ +export const realMemsyncMissing: string | false = + process.env[BINARY] && process.env[DATABASE_SERVER] + ? false + : `set ${BINARY} to a built memsync-server and ${DATABASE_SERVER} to a PostgreSQL server where tests may create databases`; + +const encoded = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); + +export interface TokenChanges { + claims?: Record; + /** Sign with a key the server was never told about. */ + unknownKey?: boolean; +} + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, "127.0.0.1", resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +async function answers(address: URL): Promise { + const channel = grpcChannel(address); + try { + await channel.unary({ + path: "/memsync.v1.Projects/ListProjects", + request: new Uint8Array(), + timeoutMs: 1000, + }); + return true; + } catch (failure) { + // Being asked who we are is an answer. Silence is not. + return ( + failure instanceof GrpcFailure && + failure.code === grpcStatus.UNAUTHENTICATED + ); + } finally { + channel.close(); + } +} + +/** + * Starts the real `memsync-server` on a database of its own, trusting a signing key + * made for this run. Stopping it drops the database, so nothing that was already + * on the PostgreSQL server is touched. + */ +export async function startRealMemsync() { + const psql = (sql: string) => + promisify(execFile)(process.env[PSQL] ?? "psql", [ + process.env[DATABASE_SERVER]!, + "-v", + "ON_ERROR_STOP=1", + "-qAtc", + sql, + ]); + const folder = await mkdtemp(join(tmpdir(), "memcode-real-memsync-")); + const database = `memcode_test_${randomBytes(6).toString("hex")}`; + const trusted = generateKeyPairSync("ed25519"), + stranger = generateKeyPairSync("ed25519"); + const keyFile = join(folder, "keys.json"); + await writeFile( + keyFile, + JSON.stringify({ + keys: [ + { + ...trusted.publicKey.export({ format: "jwk" }), + kid: KEY_ID, + alg: "EdDSA", + use: "sig", + }, + ], + }), + ); + await psql(`CREATE DATABASE "${database}"`); + const databaseUrl = new URL(process.env[DATABASE_SERVER]!); + databaseUrl.pathname = `/${database}`; + const address = new URL(`http://127.0.0.1:${await freePort()}`); + const output: string[] = []; + const server = spawn(process.env[BINARY]!, [], { + stdio: ["ignore", "pipe", "pipe"], + env: { + PATH: process.env.PATH, + MEMSYNC_DATABASE_URL: databaseUrl.href, + MEMSYNC_TOKEN_ISSUER: ISSUER, + MEMSYNC_TOKEN_AUDIENCE: AUDIENCE, + MEMSYNC_TOKEN_KEYS_FILE: keyFile, + MEMSYNC_LISTEN_ADDRESS: address.host, + }, + }); + server.stdout.on("data", (part) => output.push(String(part))); + server.stderr.on("data", (part) => output.push(String(part))); + const exited = new Promise((resolve) => + server.once("exit", () => resolve()), + ); + const stop = async () => { + server.kill("SIGTERM"); + await exited; + await psql(`DROP DATABASE IF EXISTS "${database}" WITH (FORCE)`).catch( + () => {}, + ); + await rm(folder, { recursive: true, force: true }); + }; + const deadline = Date.now() + 20000; + while (!(await answers(address))) { + if (server.exitCode !== null || Date.now() > deadline) { + await stop(); + throw new Error(`memsync-server did not start:\n${output.join("")}`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + + /** A token as memtrace.io issues it (MemSync's ADR-0010), signed for this run. */ + const tokenFor = ( + person: StandInPerson, + changes: TokenChanges = {}, + ): string => { + const issuedAt = Math.floor(Date.now() / 1000); + const unsigned = [ + encoded({ alg: "EdDSA", typ: "JWT", kid: KEY_ID }), + encoded({ + iss: ISSUER, + aud: AUDIENCE, + purpose: "memsync-access", + sub: person.accountId, + name: person.name, + ...(person.email ? { email: person.email } : {}), + email_verified: !!person.email, + iat: issuedAt, + exp: issuedAt + 600, + ...changes.claims, + }), + ].join("."); + const key = changes.unknownKey ? stranger.privateKey : trusted.privateKey; + return `${unsigned}.${sign(null, Buffer.from(unsigned), key).toString("base64url")}`; + }; + return { address, tokenFor, stop }; +} +export type RealMemsync = Awaited>; + +/** One scenario's view of a server that all scenarios share. Their people never overlap. */ +export const worldOn = (server: RealMemsync): SharingWorld => ({ + address: server.address, + tokenFor: (person) => server.tokenFor(person), + close: async () => {}, +}); From 3adb596857282e0b7b6218e5610104035078ffa1 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:39:18 +0100 Subject: [PATCH 02/66] feat: add a Sharing view for shared projects and invitations [skip ci] Once the two sharing addresses are saved under Account in Settings, the sidebar gets a Sharing entry. It lists the signed-in person's shared projects and the invitations waiting for them, accepts an invitation, and connects the open project to one shared project or disconnects it. With no addresses saved there is no entry, which is how every build starts. Starting, renaming and deleting a project and inviting people stay at memtrace.io. "Manage at memtrace.io" opens the MemCode tab of the account through a new native command with a fixed address. The view says that connecting only records where the board belongs and that the board does not sync yet. It asks again when the window regains focus, when the signed-in account changes and on request. A link is still shown, and can be undone, while the service cannot be reached. Co-Authored-By: Claude Fable 5.2 --- src-tauri/src/native.rs | 7 + src/App.tsx | 27 +- src/components/Dialogs.tsx | 7 + src/components/SharedProjects.tsx | 467 +++++++++++++++++++++++++++++ src/components/SharingSettings.tsx | 60 ++++ src/shared.ts | 13 + src/sharing.ts | 60 ++++ src/styles-sharing.css | 167 +++++++++++ src/tauri.ts | 6 + tests/sharing-view.test.ts | 406 +++++++++++++++++++++++++ 10 files changed, 1219 insertions(+), 1 deletion(-) create mode 100644 src/components/SharedProjects.tsx create mode 100644 src/components/SharingSettings.tsx create mode 100644 src/styles-sharing.css create mode 100644 tests/sharing-view.test.ts diff --git a/src-tauri/src/native.rs b/src-tauri/src/native.rs index 8712574..bcb61a7 100644 --- a/src-tauri/src/native.rs +++ b/src-tauri/src/native.rs @@ -182,6 +182,13 @@ pub async fn host_call(app: AppHandle, method: &str, input: Value) -> Result { + tauri::async_runtime::spawn_blocking(|| open_claim("https://www.memtrace.io/account?workspace=all§ion=memcode")) + .await + .map_err(|e| e.to_string())??; + Ok(Value::Null) + } "open_path" => { let path = input["path"] .as_str() diff --git a/src/App.tsx b/src/App.tsx index 49ea74b..e3c7285 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -24,6 +24,7 @@ import { Route, Search, Settings2, + Share2, ShieldCheck, Sparkles, Square, @@ -74,8 +75,11 @@ import { import type { GuideDestination } from "./guide-content"; import { WorkerConnections } from "./components/WorkerConnections"; import { TeamOnboarding } from "./components/TeamOnboarding"; +import { SharedProjects } from "./components/SharedProjects"; +import { sharingIsSet } from "./sharing"; import "./styles-team.css"; import "./styles-collaboration.css"; +import "./styles-sharing.css"; import { BetaAccess } from "./components/BetaAccess"; import { AppUpdateAction } from "./components/AppUpdates"; import { InstallationGuide } from "./components/InstallationGuide"; @@ -107,8 +111,14 @@ type View = | "artifacts" | "activity" | "docs" - | "team"; + | "team" + | "sharing"; const pageCopy: Record = { + sharing: [ + "SHARED PROJECTS", + "Projects you share.", + "Your shared projects and invitations, and the one this project belongs to.", + ], team: [ "BUILD WITH YOUR TEAM", "Better together. Still local.", @@ -609,6 +619,10 @@ export function App() { count: state.team?.find((item) => item.projectId === project.id) ?.unreadCount, }, + // Sharing has no service to talk to until its addresses are set, so it is not offered. + ...(sharingIsSet(state.settings.sharing) + ? [{ id: "sharing" as const, label: "Sharing", icon: Share2 }] + : []), { id: "docs", label: "Docs", icon: BookOpen }, ]; const projectGroups = new Map(); @@ -897,6 +911,17 @@ export function App() { }} /> )} + {view === "sharing" && ( + { + setSettingsSection("account"); + setDialog("settings"); + }} + /> + )} {view === "docs" && ( }> )} + {section === "account" && ( + setDraft((value) => ({ ...value, sharing }))} + /> + )} {section === "workers" && ( <> ; +type Ready = Extract; + +interface PanelProps { + /** Null while the first answer is on its way. */ + overview: SharingOverview | null; + state: Workspace; + project: Project; + /** Which action is running, so its button and the others wait. */ + busy: string; + error: string; + onRefresh(): void; + onManage(): void; + onAccount(): void; + onSettings(): void; + onAccept(invitation: PendingInvitation): void; + onConnect(shared: SharedProject): void; + onDisconnect(): void; +} + +const people = (shared: SharedProject) => { + const others = [shared.owner, ...shared.guests] + .filter((person) => !person.isYou) + .filter((person) => shared.youAreOwner || person !== shared.owner) + .map((person) => person.name); + const taken = shared.guests.length + shared.openInvitations; + return [ + shared.youAreOwner ? "You own it" : `Shared by ${shared.owner.name}`, + ...(others.length ? [`with ${others.join(", ")}`] : []), + `${taken} of ${shared.guestLimit} guest places taken`, + ].join(" · "); +}; + +/** What the open project's own line says, and whether it can be disconnected. */ +function OpenProject({ + project, + standing, + busy, + onDisconnect, +}: { + project: Project; + standing: ProjectSharing; + busy: string; + onDisconnect(): void; +}) { + const name = {project.name}; + const linked = + standing.kind === "connected" || + standing.kind === "gone" || + standing.kind === "elsewhere" || + standing.kind === "remembered"; + return ( +
+ + + +
+ {standing.kind === "free" && ( +

{name} is not connected to a shared project. Choose one below.

+ )} + {standing.kind === "example" && ( +

+ The example project cannot be connected. Open one of your own + projects first. +

+ )} + {standing.kind === "team" && ( +

+ {name} is shared through Team Sync, so it cannot be connected here + as well. +

+ )} + {standing.kind === "connected" && ( + <> +

+ {name} is connected to {standing.shared.name}. +

+ + Connecting records which shared project this board belongs to. The + board does not sync between computers yet. + + + )} + {standing.kind === "remembered" && ( +

+ {name} is connected to {standing.name}. +

+ )} + {standing.kind === "gone" && ( +

+ {name} was connected to {standing.name}, which no + longer exists, or you are no longer on it. +

+ )} + {standing.kind === "elsewhere" && ( +

+ {name} was connected to {standing.name} under + another Memtrace account or sharing service. +

+ )} +
+ {linked && ( + + )} +
+ ); +} + +function SharedProjectRow({ + shared, + connectedTo, + openProject, + mayConnect, + busy, + onConnect, +}: { + shared: SharedProject; + connectedTo: Project | undefined; + openProject: Project; + mayConnect: boolean; + busy: string; + onConnect(shared: SharedProject): void; +}) { + return ( +
  • +
    + {shared.name} + {people(shared)} +
    + {connectedTo?.id === openProject.id ? ( + + + Connected to this project + + ) : connectedTo ? ( + + Connected to {connectedTo.name} + + ) : ( + mayConnect && ( + + ) + )} +
  • + ); +} + +function Lists({ + overview, + state, + project, + busy, + onRefresh, + onManage, + onAccept, + onConnect, + onDisconnect, +}: PanelProps & { overview: Ready }) { + const standing = projectSharing(project, state, overview); + const links = state.sharedProjectLinks ?? []; + return ( + <> + +
    +

    Your shared projects

    + + + + +
    + {overview.projects.length ? ( +
      + {overview.projects.map((shared) => ( + + ))} +
    + ) : ( +

    + You have no shared projects yet. Start one at memtrace.io, where you + also invite people to it. +

    + )} +
    +

    Invitations for you

    +
    + {overview.invitations.length ? ( +
      + {overview.invitations.map((invitation) => ( +
    • + + + +
      + {invitation.projectName} + + From {invitation.invitedBy} · open until{" "} + {dateLabel(invitation.expiresAt.slice(0, 10), { + day: "numeric", + month: "long", + })} + +
      + +
    • + ))} +
    + ) : ( +

    No invitations are waiting for you.

    + )} +

    + Projects are started, renamed and deleted at memtrace.io, and people are + invited there. A personal project holds its owner and two guests. Your + own computers need no invitation: sign in to MemCode on each. +

    + + ); +} + +/** The Sharing view for one answer from the runtime. It decides nothing itself. */ +export function SharingPanel(props: PanelProps) { + const { overview, busy, error, onRefresh, onAccount, onSettings } = props; + // The link is kept on this computer, so it can be shown and undone without the service. + const remembered = + overview && overview.state !== "ready" + ? props.state.sharedProjectLinks?.find( + (link) => link.projectId === props.project.id, + ) + : undefined; + return ( +
    + {error && ( +

    + {error} +

    + )} + {!overview && ( +

    + + Looking up your shared projects… +

    + )} + {overview?.state === "ready" && } + {remembered && ( + + )} + {overview?.state === "signed-out" && ( +
    +

    {overview.detail}

    + +
    + )} + {overview?.state === "unavailable" && ( +
    +

    {overview.detail}

    + +
    + )} + {overview?.state === "not-set" && ( +
    +

    + Sharing is not set up. Enter the sharing addresses under Account in + Settings. +

    + +
    + )} +
    + ); +} + +/** Shared projects and invitations of the signed-in person, and the open project's link. */ +export function SharedProjects({ + state, + project, + notify, + onAccount, +}: { + state: AppState; + project: Project; + notify: (message: string) => void; + onAccount(): void; +}) { + const [overview, setOverview] = useState(null); + const [busy, setBusy] = useState(""); + const [error, setError] = useState(""); + const perform = useCallback( + async (key: string, action: () => Promise) => { + setBusy(key); + setError(""); + try { + await action(); + } catch (reason) { + setError(errorMessage(reason)); + } finally { + setBusy(""); + } + }, + [], + ); + const refresh = useCallback( + () => + perform("refresh", async () => + setOverview(await window.memcode.sharingOverview()), + ), + [perform], + ); + // The addresses are part of what is shown, so a change in Settings asks again. + const addresses = `${state.settings.sharing?.memsyncUrl}\n${state.settings.sharing?.tokenUrl}`; + useEffect(() => { + setOverview(null); + void refresh(); + }, [refresh, addresses]); + // Projects and invitations change at memtrace.io, so coming back to the window looks again. + useEffect(() => { + let lookedAt = Date.now(); + const lookAgain = () => { + if (Date.now() - lookedAt < REFRESH_ON_RETURN_MS) return; + lookedAt = Date.now(); + void refresh(); + }; + window.addEventListener("focus", lookAgain); + return () => window.removeEventListener("focus", lookAgain); + }, [refresh]); + // Signing in, signing out or switching account changes whose projects these are. + useEffect(() => { + let signedInAs: string | undefined | null = null; + return window.memcode.onBetaStatus((status) => { + const account = + status.state === "connected" ? status.account?.id : undefined; + if (signedInAs !== null && account !== signedInAs) void refresh(); + signedInAs = account; + }); + }, [refresh]); + return ( + void refresh()} + onManage={() => + void perform("manage", () => window.memcode.openSharedProjectsPage()) + } + onAccount={onAccount} + onSettings={onAccount} + onAccept={(invitation) => + void perform(`accept:${invitation.id}`, async () => { + setOverview( + await window.memcode.acceptSharedInvitation({ + projectId: invitation.projectId, + invitationId: invitation.id, + }), + ); + notify(`You are now a guest on ${invitation.projectName}`); + }) + } + onConnect={(shared) => + void perform(`connect:${shared.id}`, async () => { + await window.memcode.connectSharedProject({ + projectId: project.id, + sharedProjectId: shared.id, + }); + notify(`${project.name} is connected to ${shared.name}`); + }) + } + onDisconnect={() => + void perform("disconnect", async () => { + await window.memcode.disconnectSharedProject(project.id); + notify(`${project.name} is no longer connected`); + }) + } + /> + ); +} diff --git a/src/components/SharingSettings.tsx b/src/components/SharingSettings.tsx new file mode 100644 index 0000000..2a26da6 --- /dev/null +++ b/src/components/SharingSettings.tsx @@ -0,0 +1,60 @@ +import { Share2 } from "lucide-react"; +import type { SharingSettings as Addresses } from "../sharing"; + +const tokenAddressExample = "https://www.memtrace.io/api/memcode/memsync/token"; + +/** The two addresses sharing needs. Both empty keeps sharing out of the app. */ +export function SharingSettings({ + value, + change, +}: { + value: Addresses | undefined; + change: (value: Addresses) => void; +}) { + const addresses = value ?? { memsyncUrl: "", tokenUrl: "" }; + return ( +
    + Advanced · sharing service +
    +
    + + + Sharing service + + Where your shared projects live. Sharing appears in the sidebar + once both addresses are set. + + +
    +
    + + +

    + MemCode shows your Memtrace sign-in to the sign-in address, so it + must be at www.memtrace.io or on this computer. +

    +
    +
    +
    + ); +} diff --git a/src/shared.ts b/src/shared.ts index b025f1c..87c4223 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -535,6 +535,19 @@ export interface MemCodeAPI extends CodeReviewAPI { localAnalysisDiagnostics( projectId: string, ): Promise; + /** The signed-in person's shared projects and invitations, or why they cannot be shown. */ + sharingOverview(): Promise; + acceptSharedInvitation(input: { + projectId: string; + invitationId: string; + }): Promise; + connectSharedProject(input: { + projectId: string; + sharedProjectId: string; + }): Promise; + disconnectSharedProject(projectId: string): Promise; + /** Opens the page at memtrace.io where projects are started and people invited. */ + openSharedProjectsPage(): Promise; teamsList(): Promise; createTeamWorkspace(input: { name: string; diff --git a/src/sharing.ts b/src/sharing.ts index 2502d4a..2a4a633 100644 --- a/src/sharing.ts +++ b/src/sharing.ts @@ -65,3 +65,63 @@ export type SharingOverview = projects: SharedProject[]; invitations: PendingInvitation[]; }; + +type Workspace = Pick< + import("./shared").AppState, + "projects" | "team" | "sharedProjectLinks" +>; +type LocalProject = import("./shared").Project; +type Ready = Extract; + +/** How one local project stands with sharing, for the person signed in now. */ +export type ProjectSharing = + | { kind: "free" } + | { kind: "example" } + | { kind: "team" } + | { kind: "connected"; shared: SharedProject } + /** Connected, but the shared project is not among the person's projects any more. */ + | { kind: "gone"; name: string } + /** Connected under another Memtrace account, or on another sharing service. */ + | { kind: "elsewhere"; name: string } + /** Connected as far as this computer knows. The sharing service could not be asked. */ + | { kind: "remembered"; name: string }; + +export function projectSharing( + project: LocalProject, + workspace: Workspace, + overview: Ready, +): ProjectSharing { + const link = workspace.sharedProjectLinks?.find( + (candidate) => candidate.projectId === project.id, + ); + if (!link) { + if (project.example) return { kind: "example" }; + const inTeam = workspace.team?.some( + (room) => room.projectId === project.id, + ); + return inTeam ? { kind: "team" } : { kind: "free" }; + } + const madeHere = + link.accountId === overview.accountId && link.service === overview.service; + if (!madeHere) return { kind: "elsewhere", name: link.sharedProjectName }; + const shared = overview.projects.find( + (candidate) => candidate.id === link.sharedProjectId, + ); + return shared + ? { kind: "connected", shared } + : { kind: "gone", name: link.sharedProjectName }; +} + +/** The local project a shared project is connected to on this computer, if any. */ +export function localProjectOf( + shared: SharedProject, + links: SharedProjectLink[], + projects: LocalProject[], + service: string, +): LocalProject | undefined { + const link = links.find( + (candidate) => + candidate.sharedProjectId === shared.id && candidate.service === service, + ); + return link && projects.find((project) => project.id === link.projectId); +} diff --git a/src/styles-sharing.css b/src/styles-sharing.css new file mode 100644 index 0000000..432c43b --- /dev/null +++ b/src/styles-sharing.css @@ -0,0 +1,167 @@ +.sharing-home { + max-width: 880px; + margin: 0 auto; + color: var(--ink); + padding-bottom: 24px; +} +.sharing-home .button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + white-space: nowrap; +} +.sharing-open-project { + display: flex; + align-items: center; + gap: 15px; + padding: 19px 22px; + border: 1px solid #dce7df; + border-radius: 10px; + background: #f8fbf8; +} +.sharing-open-project > div { + flex: 1; + min-width: 0; +} +.sharing-open-project p { + margin: 0; + font-size: 13px; + line-height: 1.6; +} +.sharing-open-project strong, +.sharing-row strong { + font-weight: 550; +} +.sharing-open-project small { + display: block; + margin-top: 5px; + font-size: 11px; + line-height: 1.6; + color: var(--muted); +} +.sharing-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin: 30px 0 4px; +} +.sharing-heading h3 { + margin: 0; + font-size: 16px; + font-weight: 550; + letter-spacing: -0.02em; +} +.sharing-list { + list-style: none; + margin: 0; + padding: 0; +} +.sharing-row { + display: flex; + align-items: center; + gap: 13px; + padding: 15px 0; + border-bottom: 1px solid var(--line); +} +.sharing-row > div { + display: flex; + flex-direction: column; + gap: 5px; + flex: 1; + min-width: 0; +} +.sharing-row strong { + font-size: 13px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.sharing-row small { + font-size: 11px; + color: var(--muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.sharing-mark { + width: 29px; + height: 29px; + display: grid; + place-items: center; + border: 1px solid #e0ebdf; + border-radius: 50%; + background: #f0f6ec; + color: #718b69; +} +.sharing-connected { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 11px; + color: #498773; + white-space: nowrap; +} +.sharing-empty, +.sharing-footnote { + font-size: 12px; + line-height: 1.7; + color: var(--muted); + margin: 12px 0 0; +} +.sharing-footnote { + margin-top: 30px; + font-size: 11px; +} +.sharing-notice { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + padding: 18px 21px; + border: 1px solid #e1e6d7; + border-radius: 9px; + background: #f7f9f1; +} +.sharing-notice p { + margin: 0; + font-size: 12px; + line-height: 1.65; + color: #556352; +} +.sharing-problem { + margin: 0 0 16px; + padding: 12px 16px; + border: 1px solid #f0d9cf; + border-radius: 8px; + background: #fdf6f2; + color: #8a4a2f; + font-size: 12px; + line-height: 1.6; +} +.sharing-loading { + display: flex; + align-items: center; + gap: 10px; + padding: 30px 0; + color: var(--muted); + font-size: 12px; +} +.settings-sharing-fields { + display: grid; + gap: 12px; + margin-top: 12px; +} +.settings-sharing-fields p { + margin: 0; + line-height: 1.6; +} +.sharing-heading-actions { + display: inline-flex; + align-items: center; + gap: 8px; +} +.sharing-open-project + .sharing-notice { + margin-top: 14px; +} diff --git a/src/tauri.ts b/src/tauri.ts index b7c9274..f747099 100644 --- a/src/tauri.ts +++ b/src/tauri.ts @@ -203,6 +203,12 @@ export async function installNativeBridge(): Promise { }, localAnalysisDiagnostics: (projectId) => call("project:local-diagnostics", { projectId }), + sharingOverview: () => call("sharing:overview"), + acceptSharedInvitation: (input) => call("sharing:accept-invitation", input), + connectSharedProject: (input) => call("sharing:connect", input), + disconnectSharedProject: (projectId) => + call("sharing:disconnect", { projectId }), + openSharedProjectsPage: () => call("sharing:manage"), teamsList: () => call("team:list"), createTeamWorkspace: (input) => call("team:create-workspace", input), shareTeamProject: (input) => call("team:share-project", input), diff --git a/tests/sharing-view.test.ts b/tests/sharing-view.test.ts new file mode 100644 index 0000000..8cef2d5 --- /dev/null +++ b/tests/sharing-view.test.ts @@ -0,0 +1,406 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { SharingPanel } from "../src/components/SharedProjects"; +import { SharingSettings } from "../src/components/SharingSettings"; +import type { AppState, Project } from "../src/shared"; +import { + localProjectOf, + projectSharing, + sharingIsSet, + type SharedProject, + type SharedProjectLink, + type SharingOverview, +} from "../src/sharing"; + +const at = "2026-11-21T12:00:00.000Z"; +const local = ( + id: string, + name: string, + extra: Partial = {}, +): Project => ({ + id, + name, + description: "", + path: `/work/${name}`, + branch: "main", + analysis: "idle", + createdAt: at, + ...extra, +}); +const website = local("local-web", "website"), + app = local("local-app", "app"), + example = local("example", "Design preview", { example: true, path: null }); +const launch: SharedProject = { + id: "shared-launch", + name: "Launch plan", + owner: { name: "Alex Holm", isYou: true }, + guests: [{ name: "Bo Li", isYou: false }], + youAreOwner: true, + openInvitations: 1, + guestLimit: 2, +}; +const redesign: SharedProject = { + id: "shared-redesign", + name: "Website redesign", + owner: { name: "Dana Ek", isYou: false }, + guests: [{ name: "Alex Holm", isYou: true }], + youAreOwner: false, + openInvitations: 0, + guestLimit: 2, +}; +type Ready = Extract; +const ready = (changes: Partial = {}): Ready => ({ + state: "ready", + accountId: "acct-alex", + service: "https://sync.memtrace.io/", + projects: [launch, redesign], + invitations: [], + ...changes, +}); +const link = (changes: Partial = {}): SharedProjectLink => ({ + projectId: website.id, + sharedProjectId: launch.id, + sharedProjectName: "Launch plan", + accountId: "acct-alex", + service: "https://sync.memtrace.io/", + connectedAt: at, + ...changes, +}); +type Shown = Pick; +const shown = (changes: Partial = {}): Shown => ({ + projects: [example, website, app], + ...changes, +}); + +test("sharing is in the app only when both addresses are set", () => { + assert.equal(sharingIsSet(undefined), false); + assert.equal( + sharingIsSet({ memsyncUrl: "https://sync.memtrace.io", tokenUrl: "" }), + false, + ); + assert.equal( + sharingIsSet({ memsyncUrl: " ", tokenUrl: "https://www.memtrace.io/t" }), + false, + ); + assert.equal( + sharingIsSet({ + memsyncUrl: "https://sync.memtrace.io", + tokenUrl: "https://www.memtrace.io/t", + }), + true, + ); +}); + +test("the open project is free, connected, or says why it cannot be connected", () => { + assert.deepEqual(projectSharing(website, shown(), ready()), { kind: "free" }); + assert.deepEqual(projectSharing(example, shown(), ready()), { + kind: "example", + }); + assert.deepEqual( + projectSharing( + website, + shown({ + team: [ + { projectId: website.id } as NonNullable[number], + ], + }), + ready(), + ), + { kind: "team" }, + ); + assert.deepEqual( + projectSharing(website, shown({ sharedProjectLinks: [link()] }), ready()), + { kind: "connected", shared: launch }, + ); +}); + +test("a link whose shared project is gone, or that was made elsewhere, is told apart from a live one", () => { + const linked = shown({ sharedProjectLinks: [link()] }); + assert.deepEqual( + projectSharing(website, linked, ready({ projects: [redesign] })), + { + kind: "gone", + name: "Launch plan", + }, + ); + assert.deepEqual( + projectSharing(website, linked, ready({ accountId: "acct-other" })), + { + kind: "elsewhere", + name: "Launch plan", + }, + ); + assert.deepEqual( + projectSharing( + website, + linked, + ready({ service: "https://sync.company.example/" }), + ), + { kind: "elsewhere", name: "Launch plan" }, + ); +}); + +test("a shared project knows which local project it is connected to on this computer", () => { + const links = [link({ projectId: app.id })]; + const projects = [example, website, app]; + const service = "https://sync.memtrace.io/"; + assert.equal(localProjectOf(launch, links, projects, service), app); + assert.equal(localProjectOf(redesign, links, projects, service), undefined); + assert.equal( + localProjectOf(launch, links, projects, "https://other.example/"), + undefined, + ); + // A link to a local project that is no longer in the workspace holds nothing. + assert.equal( + localProjectOf(launch, links, [example, website], service), + undefined, + ); +}); + +const actions = { + onRefresh() {}, + onManage() {}, + onAccount() {}, + onSettings() {}, + onAccept() {}, + onConnect() {}, + onDisconnect() {}, +}; +const render = ( + overview: SharingOverview | null, + state: Shown = shown(), + project: Project = website, + extra: { busy?: string; error?: string } = {}, +) => + renderToStaticMarkup( + createElement(SharingPanel, { + overview, + state, + project, + busy: extra.busy ?? "", + error: extra.error ?? "", + ...actions, + }), + ); +const text = (markup: string) => + markup + .replace(/<[^>]+>/g, " ") + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, "&") + .replace(/\s+/g, " "); + +test("my shared projects are listed with who owns them, who is on them and a way to connect", () => { + const page = text(render(ready())); + assert.match( + page, + /Launch plan You own it · with Bo Li · 2 of 2 guest places taken/, + ); + assert.match( + page, + /Website redesign Shared by Dana Ek · 1 of 2 guest places taken/, + ); + assert.match(page, /website is not connected to a shared project/); + assert.equal((page.match(/Connect website/g) ?? []).length, 2); + assert.match(page, /Manage at memtrace\.io/); + assert.doesNotMatch(page, /\bteam\b/i); +}); + +test("a connected project says so, says the board does not sync yet, and offers to disconnect", () => { + const page = text(render(ready(), shown({ sharedProjectLinks: [link()] }))); + assert.match(page, /website is connected to Launch plan/); + assert.match(page, /does not sync between computers yet/); + assert.match(page, /Connected to this project/); + assert.match(page, /Disconnect/); + // A project that is connected is not offered a second shared project. + assert.doesNotMatch(page, /Connect website/); +}); + +test("a shared project connected to another local project says which, and cannot be taken twice", () => { + const page = text( + render( + ready(), + shown({ sharedProjectLinks: [link({ projectId: app.id })] }), + ), + ); + assert.match(page, /Launch plan .* Connected to app/); + assert.equal((page.match(/Connect website/g) ?? []).length, 1); +}); + +test("the example project and a Team project are told why they cannot be connected", () => { + const forExample = text(render(ready(), shown(), example)); + assert.match(forExample, /example project cannot be connected/); + assert.doesNotMatch(forExample, /Connect Design preview/); + const forTeam = text( + render( + ready(), + shown({ + team: [ + { projectId: website.id } as NonNullable[number], + ], + }), + ), + ); + assert.match(forTeam, /shared through Team Sync/); + assert.doesNotMatch(forTeam, /Connect website/); +}); + +test("a link that leads nowhere any more says so and can be disconnected", () => { + const gone = text( + render( + ready({ projects: [redesign] }), + shown({ sharedProjectLinks: [link()] }), + ), + ); + assert.match(gone, /no longer exists, or you are no longer on it/); + assert.match(gone, /Disconnect/); + const elsewhere = text( + render( + ready({ accountId: "acct-other" }), + shown({ sharedProjectLinks: [link()] }), + ), + ); + assert.match(elsewhere, /another Memtrace account or sharing service/); + assert.match(elsewhere, /Disconnect/); +}); + +test("invitations waiting for me say who sent them and until when, and can be accepted", () => { + const page = text( + render( + ready({ + projects: [], + invitations: [ + { + id: "invitation-1", + projectId: "shared-redesign", + projectName: "Website redesign", + invitedBy: "Dana Ek", + expiresAt: "2026-12-05T09:30:00.000Z", + }, + ], + }), + ), + ); + assert.match(page, /Invitations for you/); + assert.match(page, /Website redesign From Dana Ek · open until 5 December/); + assert.match(page, /Accept/); + assert.match(page, /You have no shared projects yet/); +}); + +test("the lists can be asked for again without leaving the page", () => { + assert.match(render(ready()), /]*aria-label="Look again"/); + assert.match( + render(ready(), shown(), website, { busy: "refresh" }), + /]*aria-label="Look again"[^>]*disabled=""/, + ); +}); + +test("with nothing waiting, the page says so instead of showing an empty list", () => { + const page = text(render(ready({ projects: [launch] }))); + assert.match(page, /No invitations are waiting for you/); +}); + +test("each state that is not a list says what to do next", () => { + assert.match(text(render(null)), /Looking up your shared projects/); + const signedOut = text( + render({ + state: "signed-out", + detail: "Sign in to Memtrace to see the projects you share.", + }), + ); + assert.match( + signedOut, + /Sign in to Memtrace to see the projects you share\./, + ); + assert.match(signedOut, /Open account settings/); + const unavailable = text( + render({ + state: "unavailable", + detail: "The sharing service could not be reached.", + }), + ); + assert.match(unavailable, /The sharing service could not be reached\./); + assert.match(unavailable, /Try again/); + const notSet = text(render({ state: "not-set" })); + assert.match(notSet, /Sharing is not set up/); + assert.match(notSet, /Open settings/); +}); + +test("a connected project is still named, and can be disconnected, while the service cannot be asked", () => { + const linked = shown({ sharedProjectLinks: [link()] }); + for (const overview of [ + { + state: "unavailable", + detail: "The sharing service could not be reached.", + }, + { + state: "signed-out", + detail: "Sign in to Memtrace to see the projects you share.", + }, + ] as const) { + const page = text(render(overview, linked)); + assert.match(page, /website is connected to Launch plan/); + assert.match(page, /Disconnect/); + assert.doesNotMatch(text(render(overview)), /is connected to|Disconnect/); + } + assert.doesNotMatch(text(render(null, linked)), /Disconnect/); +}); + +test("a refusal is shown where the person is looking, and buttons wait while one is working", () => { + const markup = render( + ready({ + invitations: [ + { + id: "invitation-1", + projectId: "shared-x", + projectName: "X", + invitedBy: "Dana Ek", + expiresAt: "2026-12-05T09:30:00.000Z", + }, + ], + }), + shown(), + website, + { busy: "accept:invitation-1", error: "This invitation has expired." }, + ); + assert.match(markup, /role="alert"[^>]*>[^<]*This invitation has expired\./); + assert.ok((markup.match(/disabled=""/g) ?? []).length >= 3); +}); + +test("names from the sharing service are shown as text, never as markup", () => { + const hostile: SharedProject = { + ...launch, + name: '', + guests: [{ name: "", isYou: false }], + }; + const markup = render(ready({ projects: [hostile] })); + assert.doesNotMatch(markup, / { + const fields = (value?: { memsyncUrl: string; tokenUrl: string }) => + [ + ...renderToStaticMarkup( + createElement(SharingSettings, { value, change() {} }), + ).matchAll(/]*value="([^"]*)"/g), + ].map(([, label, shown]) => [label, shown]); + assert.deepEqual(fields(), [ + ["Sharing service address", ""], + ["Sign-in address for sharing", ""], + ]); + assert.deepEqual( + fields({ + memsyncUrl: "https://sync.memtrace.io", + tokenUrl: "https://www.memtrace.io/api/memcode/memsync/token", + }), + [ + ["Sharing service address", "https://sync.memtrace.io"], + [ + "Sign-in address for sharing", + "https://www.memtrace.io/api/memcode/memsync/token", + ], + ], + ); +}); From debc7b29c7b3c7e864eb7e899447158d16bbae7b Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:39:18 +0100 Subject: [PATCH 03/66] test: run MemCode in a browser against a local memtrace.io [skip ci] scripts/shared-projects-local.mts starts the real runtime on a profile of its own and serves the real app window to a browser. It answers the native shell's calls itself, sends requests for www.memtrace.io to a site on this computer, and approves the beta sign-in with a session cookie it is given. The code engine is switched off, so nothing is downloaded and no installed Memtrace is touched. This is how sharing can be tried before memtrace.io issues MemSync tokens or a MemSync is deployed. Two runs on two ports are two computers. Co-Authored-By: Claude Fable 5.2 --- scripts/fixtures/browser-shell.ts | 58 +++++++ scripts/shared-projects-local.mts | 268 ++++++++++++++++++++++++++++++ 2 files changed, 326 insertions(+) create mode 100644 scripts/fixtures/browser-shell.ts create mode 100644 scripts/shared-projects-local.mts diff --git a/scripts/fixtures/browser-shell.ts b/scripts/fixtures/browser-shell.ts new file mode 100644 index 0000000..def64e3 --- /dev/null +++ b/scripts/fixtures/browser-shell.ts @@ -0,0 +1,58 @@ +// Stands in for the three @tauri-apps/api modules when the app window runs in an +// ordinary browser beside scripts/shared-projects-local.mts. Requests go to that +// script over HTTP instead of to the native shell. +type Listener = (event: { payload: unknown }) => void; + +const listeners = new Map>(); +let showWorkspace: ((state: unknown) => void) | undefined; +let events: EventSource | undefined; + +function listenToRuntime() { + if (events) return; + events = new EventSource("/events"); + events.onmessage = (message) => { + const { event, payload } = JSON.parse(message.data); + if (event === "workspace:state") showWorkspace?.(payload); + else listeners.get(event)?.forEach((listener) => listener({ payload })); + }; +} + +async function rpc(method: string, input: unknown): Promise { + const response = await fetch("/rpc", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ method, input }), + }); + const reply = await response.json(); + // The native shell rejects with a string, and src/tauri.ts expects that. + if (reply.error !== undefined) throw reply.error; + return reply.result; +} + +export const isTauri = () => true; + +export class Channel { + onmessage: (message: T) => void = () => {}; +} + +export async function invoke(command: string, args: any = {}): Promise { + if (command === "rpc") return rpc(args.method, args.input) as Promise; + if (command === "workspace_ack") return true as T; + if (command !== "workspace_connect") throw `Unknown command ${command}`; + let sequence = 0; + showWorkspace = (state) => + args.channel.onmessage({ sequence: ++sequence, token: args.token, state }); + listenToRuntime(); + const loaded = (await rpc("workspace:load", null)) as { state: unknown }; + showWorkspace(loaded.state); + return undefined as T; +} + +export async function listen(event: string, listener: Listener) { + if (!listeners.has(event)) listeners.set(event, new Set()); + listeners.get(event)!.add(listener); + listenToRuntime(); + return () => void listeners.get(event)!.delete(listener); +} + +export const getCurrentWindow = () => ({ startDragging: async () => {} }); diff --git a/scripts/shared-projects-local.mts b/scripts/shared-projects-local.mts new file mode 100644 index 0000000..de26f58 --- /dev/null +++ b/scripts/shared-projects-local.mts @@ -0,0 +1,268 @@ +// Runs the real MemCode runtime and the real app window in a browser, signed in +// through a memtrace.io you run on this computer, so sharing can be tried before +// anything is deployed. docs/shared-projects.md has the steps. +// +// What is real: the runtime, its beta sign-in and refresh, the token exchange, +// the gRPC calls to memsync-server and every pixel of the app. +// What stands in: the native shell (this script answers its calls), the person +// in the browser (the script approves the sign-in with the cookie you give it), +// and the code engine, which is switched off. +// +// MEMCODE_LOCAL_SITE=http://127.0.0.1:3000 \ +// MEMCODE_LOCAL_SITE_COOKIE= \ +// node --import tsx scripts/shared-projects-local.mts [--port 5310] [--profile ] +import react from "@vitejs/plugin-react"; +import { build } from "vite"; +import { createServer } from "node:http"; +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { extname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createRuntime } from "../runtime/app.ts"; +import { BETA_ORIGIN } from "../runtime/beta-auth.ts"; +import { ManagedMemcodeEngine } from "../runtime/managed-engine.ts"; +import { MemtraceEngine } from "../runtime/memtrace.ts"; +import { initialState } from "../src/seed.ts"; + +const root = resolve(fileURLToPath(new URL("..", import.meta.url))); +const option = (name: string) => { + const at = process.argv.indexOf(name); + return at < 0 ? undefined : process.argv[at + 1]; +}; +const site = new URL(process.env.MEMCODE_LOCAL_SITE ?? ""); +const cookie = process.env.MEMCODE_LOCAL_SITE_COOKIE; +if (!["localhost", "127.0.0.1", "[::1]"].includes(site.hostname) || !cookie) + throw new Error( + "Set MEMCODE_LOCAL_SITE to a memtrace.io on this computer and MEMCODE_LOCAL_SITE_COOKIE to a signed-in person's session cookie.", + ); +const port = Number(option("--port") ?? 5310); +const profile = resolve( + option("--profile") ?? + (await mkdtemp(join(tmpdir(), "memcode-local-profile-"))), +); +const built = join(profile, "window"); + +// MemCode only ever signs in at memtrace.io. Here, and only here, that name leads to the local site. +const sendToInternet = globalThis.fetch; +const sendToLocalSite: typeof fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : input); + if (url.origin !== BETA_ORIGIN) return sendToInternet(input, init); + return sendToInternet(new URL(url.pathname + url.search, site), init); +}; +globalThis.fetch = sendToLocalSite; + +// No code engine in this run: nothing is downloaded and no installed Memtrace is touched. +ManagedMemcodeEngine.prototype.prepare = async () => join(profile, "no-engine"); +MemtraceEngine.prototype.analyze = async () => { + throw new Error("The code engine is switched off in this local run."); +}; + +/** The person in the browser, approving MemCode's sign-in at the local site. */ +async function approveSignIn(authorizeUrl: string) { + const signedIn = { cookie: `better-auth.session_token=${cookie}` }; + const page = await sendToLocalSite(authorizeUrl, { headers: signedIn }); + const consent = /name="consent" value="([^"]+)"/.exec(await page.text())?.[1]; + if (!consent) + throw new Error( + `The local site showed no approval page (HTTP ${page.status}). Is the cookie for a signed-in, approved person?`, + ); + const approved = await sendToLocalSite( + new URL("/api/memcode/beta/authorize", BETA_ORIGIN), + { + method: "POST", + redirect: "manual", + headers: { + ...signedIn, + origin: BETA_ORIGIN, + "content-type": "application/x-www-form-urlencoded", + }, + body: new URLSearchParams({ + consent, + action: "approve", + accept_terms: "yes", + }), + }, + ); + const backToMemcode = approved.headers.get("location"); + if (!backToMemcode) + throw new Error( + `The local site did not approve (HTTP ${approved.status}).`, + ); + await sendToInternet(backToMemcode); +} + +/** The native shell's part: the credential store, and the pages it would open in a browser. */ +const stored: { + configured: boolean; + signedOut?: boolean; + credentials: unknown; + accessToken?: string; +} = { + configured: false, + credentials: null, +}; +const accessFile = join(profile, "engine-access.jwt"); +const host = { + async call(method: string, input?: any): Promise { + const done = null as T; + if (method === "beta_store_read") + return structuredClone({ + ...stored, + ...(stored.accessToken ? { accessFile } : {}), + }) as T; + if (method === "beta_store_write") { + Object.assign(stored, { + configured: true, + signedOut: false, + credentials: input.credentials, + }); + return done; + } + if (method === "beta_access_write") { + stored.accessToken = input.accessToken; + await writeFile(accessFile, input.accessToken, { mode: 0o600 }); + return { accessFile } as T; + } + if (method === "beta_access_clear") + return void (stored.accessToken = undefined) as T; + if (method === "beta_store_mark_signed_out") + return void Object.assign(stored, { + signedOut: true, + accessToken: undefined, + }) as T; + if (method === "beta_store_forget_session" || method === "beta_store_clear") + return void Object.assign(stored, { + credentials: null, + accessToken: undefined, + }) as T; + if (method === "open_memcode_beta") { + // The shell returns at once and the browser does its part afterwards. + void approveSignIn(input.url).catch((problem) => + console.error(String(problem)), + ); + return done; + } + if (method === "installation_status") + return { + state: "development", + needsInstall: false, + canUpdate: false, + } as T; + console.log( + `[shell] ${method}${method.startsWith("open_") ? " would open a page or folder" : ""}`, + ); + return done; + }, +}; + +// A workspace with one project of its own, so there is something to connect. +await mkdir(join(profile, "website"), { recursive: true }); +try { + await readFile(join(profile, "workspace.json")); +} catch { + const state = initialState(); + state.projects.push({ + id: "local-website", + name: "website", + description: "A local project for trying out sharing.", + path: join(profile, "website"), + branch: "main", + analysis: "idle", + createdAt: new Date().toISOString(), + }); + state.activeProjectId = "local-website"; + await writeFile(join(profile, "workspace.json"), JSON.stringify(state)); +} + +const watchers = new Set<(event: string, payload: unknown) => void>(); +const runtime = await createRuntime(profile, root, host, (event, payload) => + watchers.forEach((tell) => tell(event, payload)), +); + +// The app's own code, with the three Tauri modules replaced by ones that talk to this script. +await build({ + configFile: false, + root, + base: "./", + plugins: [react()], + logLevel: "warn", + resolve: { + alias: Object.fromEntries( + ["core", "event", "window"].map((part) => [ + `@tauri-apps/api/${part}`, + join(root, "scripts/fixtures/browser-shell.ts"), + ]), + ), + }, + build: { outDir: built, emptyOutDir: true, target: "es2023" }, +}); + +const types: Record = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript", + ".mjs": "text/javascript", + ".wasm": "application/wasm", + ".css": "text/css", + ".svg": "image/svg+xml", + ".png": "image/png", + ".woff2": "font/woff2", + ".json": "application/json", +}; +const origin = `http://127.0.0.1:${port}`; +createServer(async (request, response) => { + const url = new URL(request.url ?? "/", origin); + // Only this page may drive the runtime: no other site, and no request without JSON. + const fromHere = + request.headers.host === `127.0.0.1:${port}` && + (request.headers.origin ?? origin) === origin; + if (!fromHere) return void response.writeHead(403).end(); + if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const part of request) body += part; + const reply = await (async () => { + if ( + !String(request.headers["content-type"]).startsWith("application/json") + ) + return { error: "Send JSON." }; + try { + const { method, input } = JSON.parse(body); + return { + result: (await runtime.request(method, input ?? null)) ?? null, + }; + } catch (problem) { + return { error: (problem as Error).message }; + } + })(); + response.writeHead(200, { "content-type": "application/json" }); + return void response.end(JSON.stringify(reply)); + } + if (url.pathname === "/events") { + response.writeHead(200, { + "content-type": "text/event-stream", + "cache-control": "no-store", + }); + const tell = (event: string, payload: unknown) => + response.write(`data: ${JSON.stringify({ event, payload })}\n\n`); + watchers.add(tell); + return void request.on("close", () => watchers.delete(tell)); + } + const name = url.pathname === "/" ? "index.html" : url.pathname.slice(1); + try { + const file = resolve(built, name); + if (!file.startsWith(built)) throw new Error("outside the built window"); + const bytes = await readFile(file); + response.writeHead(200, { + "content-type": types[extname(file)] ?? "application/octet-stream", + }); + response.end(bytes); + } catch { + response.writeHead(404).end(); + } +}).listen(port, "127.0.0.1", () => + console.log( + `MemCode is at ${origin}\n profile: ${profile}\n signs in at: ${site.origin} (stands in for ${BETA_ORIGIN})\n` + + ` token address to enter in Settings: ${new URL("/api/memcode/memsync/token", site).href}`, + ), +); +for (const signal of ["SIGINT", "SIGTERM"] as const) + process.on(signal, () => void runtime.close().finally(() => process.exit(0))); From de1a59330dc73bb3c083d065dc94b09cd6c852af Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:51:11 +0100 Subject: [PATCH 04/66] fix: report a MemSync reply that lacks a required part as unreadable [skip ci] A project without an owner, a person without an account id or an invitation without its dates was read after the guarded part of the call, so it left the client as a bare decoding error with words meant for nobody. The reply is now read inside the call, and the person is told the service sent something MemCode could not read. Found by breaking the client on purpose: two of 38 breakages passed the tests. Both have a test now, the other being the order fields are written in. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/memsync/projects-api.ts | 51 ++++++++++---------- tests/sharing-projects-api.test.ts | 64 +++++++++++++++++++++++++ tests/sharing-wire.test.ts | 13 +++++ 3 files changed, 104 insertions(+), 24 deletions(-) diff --git a/runtime/sharing/memsync/projects-api.ts b/runtime/sharing/memsync/projects-api.ts index 25dbe0e..98e56c9 100644 --- a/runtime/sharing/memsync/projects-api.ts +++ b/runtime/sharing/memsync/projects-api.ts @@ -160,42 +160,43 @@ export class MemsyncProjects implements ProjectsApi { private readonly timeoutMs?: number, ) {} - async listProjects() { - const reply = await this.call("ListProjects", {}); - return messages(reply.projects).map(project); + listProjects() { + return this.call("ListProjects", {}, (reply) => + messages(reply.projects).map(project), + ); } - async listInvitations() { - const reply = await this.call("ListInvitations", {}); - return messages(reply.invitations).map(invitation); + listInvitations() { + return this.call("ListInvitations", {}, (reply) => + messages(reply.invitations).map(invitation), + ); } - async getProject(projectId: string) { - return project(await this.call("GetProject", { project_id: projectId })); + getProject(projectId: string) { + return this.call("GetProject", { project_id: projectId }, project); } - async acceptInvitation(projectId: string, invitationId: string) { - return project( - await this.call("AcceptInvitation", { - project_id: projectId, - invitation_id: invitationId, - }), - ); + acceptInvitation(projectId: string, invitationId: string) { + const request = { project_id: projectId, invitation_id: invitationId }; + return this.call("AcceptInvitation", request, project); } - private async call( + private async call( name: ProjectsCall, request: WireMessage, - ): Promise { + read: (reply: WireMessage) => Answer, + ): Promise { // A token the service refuses is replaced once: its keys or the token may have just changed. - const first = await this.attempt(name, request); - if ("reply" in first) return first.reply; - const second = await this.attempt(name, request); - if ("reply" in second) return second.reply; + const first = await this.attempt(name, request, read); + if ("answer" in first) return first.answer; + const second = await this.attempt(name, request, read); + if ("answer" in second) return second.answer; throw problemWith(name, second.signInRefused); } - private async attempt( + /** One try, from the token to the reply as MemCode's own record. */ + private async attempt( name: ProjectsCall, request: WireMessage, - ): Promise<{ reply: WireMessage } | { signInRefused: GrpcFailure }> { + read: (reply: WireMessage) => Answer, + ): Promise<{ answer: Answer } | { signInRefused: GrpcFailure }> { const { token } = await this.access.current(); const shapes = projectsCalls[name]; try { @@ -205,7 +206,9 @@ export class MemsyncProjects implements ProjectsApi { metadata: { authorization: `Bearer ${token}` }, timeoutMs: this.timeoutMs, }); - return { reply: decodeMessage(projectsContract, shapes.reply, sent) }; + return { + answer: read(decodeMessage(projectsContract, shapes.reply, sent)), + }; } catch (failure) { if (signInWasRefused(failure)) { this.access.forget(token); diff --git a/tests/sharing-projects-api.test.ts b/tests/sharing-projects-api.test.ts index 815d512..6504739 100644 --- a/tests/sharing-projects-api.test.ts +++ b/tests/sharing-projects-api.test.ts @@ -8,6 +8,11 @@ import { SharingUnavailable, } from "../runtime/sharing/problems"; import { refusalRules, refusalSentences } from "../src/sharing-refusals"; +import { projectsContract } from "../runtime/sharing/memsync/projects-contract"; +import { + encodeMessage, + type WireMessage, +} from "../runtime/sharing/memsync/wire"; import { startStandInMemsync } from "./support/memsync-stand-in"; import { cast, @@ -236,6 +241,65 @@ test("a reply that lacks what it always holds is not passed on half read", async } }); +test("a project or invitation that is missing a part every one has is refused whole", async (context) => { + const owner = { account_id: "acct-1", name: "Alex Holm" }; + const moment = { seconds: 1795300000 }; + const invitation = { + id: "invitation-1", + project_id: "project-1", + project_name: "Launch plan", + email: "bo@example.com", + invited_by: owner, + sent_at: moment, + expires_at: moment, + }; + const whole = { id: "project-1", name: "Launch plan", owner, guest_limit: 2 }; + const answering = (message: string, value: WireMessage) => + new MemsyncProjects( + { + unary: async () => encodeMessage(projectsContract, message, value), + close() {}, + }, + { + current: async () => ({ token: "t", accountId: "acct-1" }), + forget() {}, + }, + ); + assert.equal( + (await answering("Project", whole).getProject("project-1")).owner.accountId, + "acct-1", + ); + const incomplete: WireMessage[] = [ + { ...whole, id: "" }, + { ...whole, owner: undefined }, + { ...whole, owner: { name: "Nobody in particular" } }, + { ...whole, guests: [{ name: "A guest with no account" }] }, + { ...whole, open_invitations: [{ ...invitation, id: "" }] }, + { ...whole, open_invitations: [{ ...invitation, project_id: "" }] }, + { ...whole, open_invitations: [{ ...invitation, expires_at: undefined }] }, + { ...whole, open_invitations: [{ ...invitation, sent_at: undefined }] }, + { + ...whole, + open_invitations: [{ ...invitation, invited_by: { name: "No account" } }], + }, + ]; + context.mock.method(console, "error", () => {}); + for (const reply of incomplete) + await assert.rejects( + answering("Project", reply).getProject("project-1"), + unavailable(/could not read/), + JSON.stringify(reply), + ); + // Someone who has left the project since inviting is simply not named. + const [open] = ( + await answering("Project", { + ...whole, + open_invitations: [{ ...invitation, invited_by: undefined }], + }).getProject("project-1") + ).openInvitations; + assert.equal(open.invitedBy, undefined); +}); + test("having no sign-in, or no way to get a token, stops the call before it is made", async () => { const service = await startStandInMemsync(); const channel = grpcChannel(service.address); diff --git a/tests/sharing-wire.test.ts b/tests/sharing-wire.test.ts index adc34d0..70b5b75 100644 --- a/tests/sharing-wire.test.ts +++ b/tests/sharing-wire.test.ts @@ -189,6 +189,19 @@ test("numbers keep their value at the edges", () => { ); }); +test("fields are written in the order of their numbers, however the shape lists them", () => { + const listedBackwards = { + Pair: { + second: { number: 2, kind: "string" }, + first: { number: 1, kind: "string" }, + }, + } satisfies Contract; + assert.equal( + hex(encodeMessage(listedBackwards, "Pair", { second: "b", first: "a" })), + "0a0161" + "120162", + ); +}); + /** Reads the messages and calls out of a .proto file that has no nested messages. */ function parseProto(source: string) { const text = source.replace(/\/\/[^\n]*/g, ""); From b354590be2cdf020d0d0ad9a4a4707482ccda178 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:51:11 +0100 Subject: [PATCH 05/66] docs: describe shared projects and propose the board's Yjs layout [skip ci] shared-projects.md covers what MemCode does with MemSync today: the two addresses, how it signs in, what connecting records, the sentence for every rule and problem, where the code is, the checks, how to try it on one computer, and the choices nobody has confirmed yet. shared-board-layout-proposal.md is a proposal, not a decision. It lays out goals, cycles, tasks, comments, lanes, fields and views in one Yjs document, says how an existing board becomes the first updates, and what MemCode does with an update it cannot apply. The numbers in it were measured with yjs 13.6.33 in a scratch folder, because MemCode has no Yjs dependency yet. Co-Authored-By: Claude Fable 5.2 --- docs/shared-board-layout-proposal.md | 321 +++++++++++++++++++++++++++ docs/shared-projects.md | 266 ++++++++++++++++++++++ 2 files changed, 587 insertions(+) create mode 100644 docs/shared-board-layout-proposal.md create mode 100644 docs/shared-projects.md diff --git a/docs/shared-board-layout-proposal.md b/docs/shared-board-layout-proposal.md new file mode 100644 index 0000000..f87e8c1 --- /dev/null +++ b/docs/shared-board-layout-proposal.md @@ -0,0 +1,321 @@ +# Proposal: the board as one Yjs document + +Status: proposed on 21 November 2026. Nothing here is built. Alex decides first. + +MemSync keeps a board as a log of Yjs updates and never looks inside one +(its ADR-0004 and ADR-0013). What is inside is MemCode's to define. This page proposes +that layout, how a board that already exists on a computer becomes the first updates, and +what MemCode does with an update it cannot apply. + +The questions that need an answer are collected [at the end](#decisions-needed). + +## What a board holds today + +Team Sync already draws the line between what is shared and what stays on a computer, in +`runtime/team/projection.ts` and `runtime/team/history.ts`. The proposal keeps that line. + +| Shared today | Stays on the computer | +| --- | --- | +| Goals: identifier, title, description, phase, color, order, branch, base revision | Worker conversations and tool output | +| Cycles: name, goal, dates, time zone, state, capacity, calendar | The worker, model, route and permissions of a task | +| Tasks: identifier, title, description, stage, lane, priority, kind, goal, cycle, parent, estimate, dates, labels, scope, what it depends on, related tasks, runbook, custom fields, archived | Run state, changes, measurements, review runs | +| Comments on tasks, with their replies | Local paths, the checkout, credentials | +| Lanes, custom field definitions and saved views of the project | Insights from code analysis | + +Claims, messages to a worker, conversations and published results are not board data. +MemSync's ADR-0005 gives them their own calls, and none of them is in this document. + +## The document + +One Yjs document per shared project. Every collection is a map at the top of the document, +named once and never created at run time. An entry is a map of fields under the id of the +thing it describes. + +``` +goals id → { identifier, title, description, phase, color, order, branch, baseRevision, baseBranch, closed, deleted } +cycles id → { name, goal, startDate, endDate, timeZone, state, capacity, calendar, deleted } +tasks id → { identifier, title, description, stage, lane, priority, kind, goal, cycle, parent, + estimate, startDate, dueDate, duplicateOf, category, archived, deleted, + label:, scope:, depends:, related:, + field:, step: } +comments id → { task, parent, text, reference, deleted } +lanes id → { name, stage, color, order, wipLimit, deleted } +fields id → { name, type, options, deleted } +views id → { name, mode, groupBy, sortBy, filters, deleted } +meta { layout: 1 } +``` + +`description` on a goal and on a task is a Yjs text. Every other value is plain: text, a +number, true or false, nothing, or a small object that is always replaced as a whole. + +### Why it is shaped this way + +- **Collections at the top, entries by id.** Two computers that add different tasks never + touch the same key, and two that edit different fields of one task both keep their edit. + Two that set the same field at the same moment end with one of the two values, the same + one everywhere. +- **An entry is made once.** When two computers each put a new map under the same id, one + whole map replaces the other and edits to the loser are gone. Measured with Yjs 13.6.33: + an entry made as "from A" and then edited on A read "from B" on both computers after + they met. So MemCode writes fields into an entry that is already there and makes a new + entry only for an id the document has never held. +- **A set is one key per member.** `label:urgent`, `depends:` and `step:` + are keys of the task's own entry. Adding a label on one computer and another label on a + second keeps both, where a list stored as one value would keep one computer's list. + A step of the runbook holds `{ text, done, order }`, so a worker ticking one step and a + person rewording another do not undo each other. +- **Descriptions merge.** A description is long and two people do edit one at once. As a + Yjs text, MemCode writes the difference between the old and the new wording, and edits + in different places both stay. Titles and comment texts are replaced whole. +- **Stage and lane are written together.** A task has both today. Each move writes both + in one step. Two computers moving the same task at once then end with one computer's + pair, never a stage from one and a lane from the other: 200 rounds, no mixed pair. +- **Deleting marks, it does not remove.** `deleted: true` hides the entry. Removing the + key would throw away an edit made at the same moment on another computer, and would + leave nothing to restore. A marked entry is small and stays in the document. + +### Order + +- **Tasks have no order of their own.** A column is sorted by the view: priority, updated, + created, due or estimate. Nothing is stored. If cards are ever ordered by hand, a task + gets a `rank` field then, and the layout number stays 1. +- **Goals keep the `order` number they are given when they are made.** They cannot be + reordered today. +- **Lanes keep `order` as their position.** Reordering lanes writes the position of every + lane in one step, as it does today. Two computers reordering at once end with one + computer's order, whole. Two lanes with the same number are shown by id, so every + computer shows the same order. + +### Ids + +Ids in the document are the ids the first computer already uses for its goals, cycles, +tasks and comments. They are UUIDs, so a second computer takes them as its own. + +Lane ids are the exception: today they begin with the local project's id +(`:backlog`). In the document they are written without it (`backlog`, +`planned`), and each computer puts its own project id back in front. Team Sync does the +same translation today. + +### Identifiers such as MC-014 + +Two computers that are offline can both create MC-014. Nobody numbers tasks for them, +because MemSync does not read the board. + +Proposed rule: the log decides. Every computer applies the log in the same order, so every +computer sees the same task arrive first with a given identifier. A task that arrives with +an identifier already taken gets the number after the highest one in use, and that new +identifier is written to the document as an ordinary change. Every computer works +out the same number from the same log, so it does not matter which of them writes it. + +Existing identifiers never change when a board is first shared. + +### Who and when + +A Yjs update carries no time and no author that can be trusted. MemSync stamps both on +every update: `logged_at` and `author_account_id`. + +- A task, goal, cycle or comment was **created** when the update that first held it was + logged, and **changed** when the last update that touched it was logged. +- A comment's **author** is the account that logged its first update. A change to a + comment logged by anyone else is not shown. +- The **delivery history** (when a task changed stage, cycle or estimate, which is what + burn-down is drawn from) is read off the same way, update by update, so every computer + draws the same chart. Cycle baselines and snapshots are worked out, not stored. +- A change that has not reached the log yet is shown with the computer's own clock until + its receipt arrives. + +Nothing in the document says who wrote it or when. + +### Not trusting what is read + +Anyone on the project can add an update, and an update can hold anything. MemCode checks +each value as it reads it, with the limits Team Sync has today (a title of at most 240 +characters, a text of at most 20,000, and so on). A value that does not pass is left out +and the last good value stays on screen. A field MemCode does not know is kept and +ignored, which is how a newer MemCode can add one. + +`meta.layout` is 1. A MemCode that finds a higher number shows the board without writing +to it and asks to be updated. + +## On each computer + +The board the app shows stays what it is today: the workspace file. Beside it, for each +connected project, MemCode keeps: + +- the document as the log has built it so far, +- the number of the last log entry it has dealt with, +- its own changes that are not in the log yet, each with the id it will be sent under, +- the log entries it could not apply. + +A local change becomes a Yjs update against the document and joins the unsent changes. +An update from the log is applied to the document and then copied into the workspace +file, field by field. Workers, conversations and everything else in the right-hand column +of the first table never pass through the document. + +Reading follows MemSync's runtime view: `ReadUpdates` in pages until a page is empty, then +`WatchUpdates` from the last number, and again from that number when the stream ends. + +## A board that already exists + +The first computer to connect a board with content to a shared project whose log is empty +writes the board into the log. + +1. Read the log. If it is not empty, see "Two boards meet" below. +2. Build the updates: `meta` first, then lanes, fields and views, then cycles, goals, tasks + and comments. One entry is one update. +3. Write every update to disk with a new id before sending any. +4. Send them in calls of at most 100 updates and at most 3 MiB together, in order. + MemSync takes 4 MiB a call unless it is set up otherwise. +5. A call whose answer is lost is sent again as it was. MemSync adds nothing twice, + because the ids are the same. + +Step 3 is what makes this safe to interrupt. If the updates were built again after a crash +they would be different bytes with different ids, and every entry would be made twice. + +Measured with Yjs 13.6.33: a task with a 600-character description is an update of 953 +bytes, and one with the longest description allowed today, 20,000 characters, is 20,366 +bytes. A board of 2,000 tasks is 2,000 updates and 1.95 MB, which is 20 calls. + +No update comes near 1 MiB unless one value is that large by itself. MemCode splits a +change that would exceed 1 MiB into several updates: the entry first, then a long text in +pieces. A single value over 1 MiB cannot be split. MemCode refuses to save it, with the +sentence for `update_too_large`. + +### Two boards meet + +The second computer finds a log that already has a board. If its own local project is +empty, it takes the board from the log. That is the case of a second computer. + +If both have content, the proposal is to keep everything: the entries of the local board +are added to the log as new entries. Ids cannot collide, and identifiers that do are +renumbered by the rule above. Nothing is lost and nothing is merged by guesswork. The +person is told how many tasks will be added before it happens. + +The same board on two computers of one person, with the same ids, is not two boards: the +second computer finds its ids in the document and adds only what is missing. + +Two computers that both find the log empty at the same moment will both write. MemSync +has no way to say "add this only if the log is still empty". For one board on two +computers that means entries made twice under the same id, which is the case measured +above where one whole entry wins. It needs both computers to connect for the first time +within the same seconds. A small addition to MemSync would close it; see below. + +## An update that cannot be applied + +MemSync cannot tell a damaged update from a good one, so every computer may be handed one. +The rule is MemSync's: skip it and say so, never stop syncing. + +What the Yjs library does, measured with version 13.6.33 on a small document: + +| What was done to a real update | Tries | Refused | Applied as if real | Left waiting | +| --- | --- | --- | --- | --- | +| Cut short at every length | 677 | 677 | 0 | 0 | +| One byte inverted, at every position | 677 | 677 | 0 | 0 | +| One bit flipped, at every position | 5,416 | 1,007 | 4,051 | 358 | +| Random bytes | 5,000 | 5,000 | 0 | 0 | +| Counts that promise far more than the bytes hold | 4 | 4 | 0 | 0 | + +No try took longer than 40 milliseconds, and none grew the memory in use. + +Three things follow. + +**A refused update can still change the document.** In 48 of the tries above, applying +threw an error and the document was no longer what it had been. Applying is not all or +nothing. In all 48, reading the update without applying it (`decodeUpdate`) had already +failed. So: + +1. An update larger than 1 MiB, or one that `decodeUpdate` refuses, is never applied. +2. An update is applied to the document inside a guard. If applying throws anyway, the + document in memory is dropped and loaded again from disk as it was after the last entry + that applied. +3. Either way the entry is written down as not applied (its number, id, author and time) + and the next entry is read. The number of the last entry dealt with moves on. + +**Damage that still reads as an update cannot be seen.** Three quarters of the single +flipped bits gave an update that applied: a changed letter, a changed number. MemCode +cannot know. What it can do is give every update an id made from its bytes (a UUID built +from their SHA-256). A reader that finds bytes which do not match their id knows the +update changed after it was written, and treats it as not applied. This catches damage in +storage and on the way. It does not catch a MemCode that writes nonsense on purpose, and +nothing in a board without a server that reads it can. + +**An update can wait for one that never comes.** Yjs applies an update that builds on +something missing by setting it aside. In the measurement, two changes to a task applied +without the update that created it left the task invisible and the document waiting. That +is what happens to everything a person wrote after a damaged update of theirs, on every +other computer. + +The repair is that whoever has more than the log sends it. After catching up, each +computer compares its own document with the one the log builds and sends the difference +as a new update. In the measurement the author's difference was 350 bytes, and the two +waiting changes took effect on arrival. As long as one computer still holds what a damaged +update carried, the board heals. If none does, the waiting updates stay set aside and are +listed with the updates that could not be applied. + +What the person sees: a line in the Sharing view such as "2 changes from Dana Ek on +21 November could not be read and were left out", with nothing else interrupted. + +Two computers with different versions of MemCode could disagree about one update. The one +that left it out will set later changes aside until someone sends the difference, and the +same repair covers it. + +## What this adds to MemCode + +- The `yjs` package (MIT, three packages with what it needs). It would be the first + package added for sharing, and it goes into the lock file and the third-party notices. + MemSync's tests use `yrs`, which reads and writes the same v1 updates. +- Two more calls of the kind MemCode already makes, and one that stays open + (`WatchUpdates`). The gRPC client reads one reply today and would learn to read many. +- The measurements on this page as tests. They were made in a scratch folder, because + `yjs` is not in the repository yet. + +## What would help from MemSync + +None of this blocks a first version. + +- **Add only if the log is at a number.** One optional field on `AppendUpdates` closes the + case of two computers writing a first board at once. +- **A snapshot.** The log only grows and a new computer reads all of it. At 2,000 tasks + that is 2 MB. MemSync's own notes already list this. +- **A reader for the delivery history** that is safe on bytes from outside, and that reads + this layout. Until then MemCode works the history out itself, as described above. + +## Decisions needed + +1. **Is this the layout?** Collections at the top, an entry per id, one key per member of + a set, descriptions as Yjs text, everything else replaced whole. +2. **Deleting on a shared board marks the entry and keeps it.** Today a deleted task is + gone. The alternative is to remove it, which loses a simultaneous edit and cannot be + undone. +3. **When two boards with content meet, keep everything from both.** The alternatives are + to refuse and make the person choose one, or to let the shared board replace the local + one. +4. **Anyone on a project can change anything on its board**, guests included, except + another person's comment. MemSync lets everyone on a project add updates, so a stricter + rule would live in MemCode alone and could be worked around. +5. **A second MC-014 is renumbered by log order.** The alternative is a prefix per person. +6. **Saved views, lanes and custom fields are shared**, as Team Sync shares them. Views + could be each person's own instead. +7. **The runbook is shared**, as it is in Team Sync, so the other computer sees a worker + tick its steps. +8. **Update ids are made from the bytes.** MemSync only asks for a UUID, so this needs no + change there. +9. **Add `yjs` to MemCode.** +10. **A project in Team Sync is not carried over by this.** Moving the two boards that + exist on the relay is a step of its own. + +## Looked at and left out + +- **One list per collection instead of a map by id.** Order would be free, but Yjs has no + move: moving an entry is removing and adding it, and two computers moving the same one + leave it there twice. +- **Everything as one value per task.** Simple, and any two edits to the same task at once + would lose one. +- **Every set as a nested Yjs map.** It merges like one key per member, at the price of + several nested types per task. Each nested type is something two computers can make at + the same moment, with one replacing the other. +- **A collection per task at the top of the document**, so that nothing nested is ever + made at run time. It removes the "made once" rule and leaves thousands of names at the + top that can never be removed. The rule is simpler than that. +- **Checking an update on a server before logging it.** MemSync decided against reading + updates, because the Rust library it would use is not safe on bytes from outside. diff --git a/docs/shared-projects.md b/docs/shared-projects.md new file mode 100644 index 0000000..503633d --- /dev/null +++ b/docs/shared-projects.md @@ -0,0 +1,266 @@ +# Shared projects + +MemCode can sign in to MemSync, the service that is to replace Team Sync, and show the +projects a person shares. This page says what exists, how to turn it on and how to try it +on one computer. + +Nothing is deployed. Until two addresses are entered in Settings, none of this is in the +app: no sidebar entry, no request to anyone. Team Sync is unchanged and keeps working +beside it. + +## What it does today + +- Signs in to MemSync with the Memtrace account MemCode is already connected to. +- Lists the shared projects the person owns or is a guest on, and the invitations waiting + for them. +- Accepts an invitation. +- Connects the open project to one shared project, and disconnects it. +- Opens the MemCode tab of the Memtrace account, where projects are started, renamed and + deleted and people are invited. + +It does not sync the board. Connecting records which shared project a board belongs to, +and the view says so. [The board layout proposal](shared-board-layout-proposal.md) is the +next step and waits for a decision. + +A project is the thing people share. There is no team. A person's own computers are never +invited: signing in to MemCode on each is enough, and each then connects its own local +project to the same shared project. + +## Turning it on + +Settings → Account → **Advanced · sharing service** has two fields. + +| Field | What goes in it | +| --- | --- | +| Sharing service address | Where MemSync is. `https://` anywhere. Plain `http://` only for `127.0.0.1`, `localhost` or `[::1]`, because MemSync speaks unencrypted HTTP/2 and every call carries an access token. A path is kept, for a proxy that serves MemSync under one. | +| Sign-in address for sharing | Where MemCode exchanges its Memtrace sign-in for a MemSync access token. It must be at `https://www.memtrace.io` or on this computer. | + +Both empty: sharing is absent. One without the other, or an address that cannot be used, +is refused when Settings is saved, with a sentence that says why. Once both are saved, +**Sharing** appears in the sidebar. + +The sign-in address is limited to memtrace.io because the request carries the session's +refresh token, and the only session MemCode holds is a memtrace.io one. A self-hosted +MemSync will need its own way to sign in before this rule can widen. + +When MemSync is deployed, the hosted addresses should become the default, so nobody has to +type them. + +## How MemCode signs in + +```mermaid +sequenceDiagram + title Signing in to MemSync + participant App as MemCode runtime + participant Site as memtrace.io + participant Sync as MemSync + + App->>App: wait for a session refresh in flight + App->>Site: POST token address { refresh_token, device_id, session_id } + Site-->>App: { access_token, token_type: Bearer, expires_in: 600 } + App->>Sync: any call, authorization: Bearer access_token + Sync-->>App: the answer, or a status that names a rule + Note over App: The token is kept in memory and renewed a minute before it expires +``` + +- The three values are the ones MemCode sends to `/api/memcode/beta/refresh`. Nothing is + spent, so a lost reply is asked for again. +- A refresh spends the refresh token. MemCode waits for one in flight before the exchange, + and when memtrace.io still answers 401 it looks at the session once more and tries again + only if the refresh token has changed since. +- The token belongs to one sign-in. Signing out, or signing in as someone else, stops it + being used at the next call. +- When MemSync turns a token away, MemCode asks for a new one and makes the call once + more. A second refusal is shown as "did not accept this sign-in", which is what a + signing key published in the last five minutes looks like. +- Neither the session nor a token is written to `workspace.json` or sent to the window. + +## Connecting a project + +A link is kept on this computer, in `sharedProjectLinks` in `workspace.json`: the local +project, the shared project and its name when last seen, the account that connected it, +the sharing service it lives on and when. + +- A local project is connected to one shared project, and a shared project to one local + project on a computer. +- The example project cannot be connected, and neither can a project that is shared + through Team Sync. Two services must not both keep one board in step. +- Connecting asks MemSync whether the person is on that shared project. Disconnecting + asks nothing: it forgets the link here, and the person stays on the shared project. +- A link whose shared project was deleted, or that was made under another account or on + another sharing service, is shown as such and can be disconnected. + +## What a person is told + +MemSync names the rule that turned a request down in `memsync-refusal` metadata. The +sentences are MemCode's own, in `src/sharing-refusals.ts`. A test fails when a rule has no +sentence. + +| Rule | Sentence | +| --- | --- | +| `no_such_project` | This shared project no longer exists, or you are no longer on it. | +| `no_such_invitation` | That invitation is no longer open. Ask the owner of the project to invite you again. | +| `no_such_guest` | That person is not a guest on this project. | +| `only_the_owner_invites` | Only the owner of a project can invite people to it. | +| `not_the_owner` | Only the owner of a project can change it. | +| `the_owner_cannot_leave` | You own this project, so you cannot leave it. You can delete it at memtrace.io. | +| `guest_limit_reached` | Every guest place on this project is taken. An invitation holds its place until it is accepted, cancelled or expires. | +| `already_on_project` | You are already on this project. | +| `already_invited` | That email address already has an open invitation to this project. | +| `invitation_expired` | This invitation has expired. Ask the owner of the project to send a new one. | +| `email_not_verified` | Invitations go to a verified email address, and the one on your Memtrace account is not verified. Verify it at memtrace.io, then accept again. | +| `invalid_project_name` | A project name is one line of text, at most 240 characters long. | +| `invalid_email` | That is not an email address. Check it and try again. | +| `invalid_update_id` | MemCode sent a board change without a usable id. This is a fault in MemCode, not something you did. | +| `empty_update` | MemCode sent an empty board change. This is a fault in MemCode, not something you did. | +| `update_too_large` | One change to the board was too large to share. Shorten the text you just added and try again. | +| `too_many_updates` | MemCode sent too many board changes at once. This is a fault in MemCode, not something you did. | + +The last four belong to the board log, which MemCode does not call yet. `already_on_project` +is worded for accepting, the only call of MemCode's that can meet it. + +Other problems have a sentence each as well: + +| When | Sentence | +| --- | --- | +| Nobody is signed in | Sign in to Memtrace to see the projects you share. | +| memtrace.io no longer knows the session | Your Memtrace sign-in has ended. Sign in again to see the projects you share. | +| memtrace.io answers 422 | The name or email on your Memtrace account cannot be used for sharing. Change it at memtrace.io, then try again. | +| memtrace.io answers 503 | Sharing is switched off or not set up at memtrace.io right now. Try again later. | +| MemSync cannot be reached | The sharing service could not be reached. Check your connection and try again. | +| MemSync is too slow | The sharing service did not answer in time. Try again in a moment. | +| MemSync answers with trouble of its own | The sharing service is having trouble right now. Try again in a few minutes. | +| MemSync refuses the token twice | The sharing service did not accept this sign-in. Try again in a few minutes. | +| The address is not a MemSync | The sharing address did not answer as a sharing service. Check it in Settings. | +| A reply cannot be read | The sharing service sent a reply MemCode could not read. Updating MemCode may help. | +| A rule MemCode does not know | The sharing service turned this down for a reason this version of MemCode does not know. Updating MemCode may help. | + +The call, the status and MemSync's own words go to the runtime's log on a line that starts +with `[sharing]`. + +## Where the code is + +| Piece | File | +| --- | --- | +| The use cases: overview, accept, connect, disconnect | `runtime/sharing/sharing.ts` | +| Requests the window may make, and what Settings may save | `runtime/sharing/routes.ts` | +| The two addresses and their rules | `runtime/sharing/addresses.ts` | +| The access token: exchange, renewal, one retry | `runtime/sharing/access.ts` | +| The session shown to memtrace.io | `sessionProof` in `runtime/beta.ts` | +| Problems a person can be told about | `runtime/sharing/problems.ts` | +| MemSync's Projects API as MemCode uses it | `runtime/sharing/memsync/projects-api.ts` | +| gRPC over Node's own HTTP/2 | `runtime/sharing/memsync/grpc.ts` | +| Protocol Buffers on the wire | `runtime/sharing/memsync/wire.ts` | +| The contract, and the part of it MemCode uses | `runtime/sharing/memsync/projects.proto`, `projects-contract.ts` | +| Rule names and sentences | `src/sharing-refusals.ts` | +| What the window knows of sharing | `src/sharing.ts` | +| The Sharing view, and the fields in Settings | `src/components/SharedProjects.tsx`, `SharingSettings.tsx` | +| The page that opens at memtrace.io | `open_memcode_projects` in `src-tauri/src/native.rs` | + +MemCode makes four of the Projects calls: `ListProjects`, `ListInvitations`, `GetProject` +and `AcceptInvitation`. + +No package was added. The client is under 900 lines over `node:http2`, because the lock +file and the third-party notices are inputs to a release, and the app otherwise has no +gRPC dependency. `projects-contract.ts` is written by hand; `tests/sharing-wire.test.ts` +reads `projects.proto` and fails when the two disagree, and checks the codec against bytes +made by `protoc`. + +### When the contract changes + +`runtime/sharing/memsync/projects.proto` is a copy of `proto/memsync/v1/projects.proto` in +the `memsync` repository, taken on 21 November 2026. Copy the newer file over it and run: + +```sh +node --import tsx --test tests/sharing-wire.test.ts +``` + +The test names every message and call that no longer matches. + +## Checks + +```sh +node --import tsx --test tests/sharing*.test.ts +``` + +One file runs MemCode's client against a real `memsync-server`. It is skipped unless both +variables are set: + +```sh +MEMSYNC_SERVER_BINARY=/path/to/memsync/target/release/memsync-server MEMSYNC_TEST_DATABASE_URL=postgres://memsync@127.0.0.1:54329/postgres node --import tsx --test tests/sharing-real-memsync.test.ts +``` + +`MEMSYNC_TEST_DATABASE_URL` names a PostgreSQL server where tests may create databases, +as in the `memsync` repository. The test makes a database of its own with `psql` and drops +it, so nothing that already exists there is touched. Never point it at a server that holds +real data. `MEMSYNC_TEST_PSQL` names another `psql` when the one on the PATH will not do. + +The same scenarios run against a stand-in service in `tests/support/memsync-stand-in.ts` +on every `npm test`. Eleven of the thirteen project rules are reached against the real +server. `invitation_expired` is reached only on the stand-in, where days can be made to +pass, and `the_owner_cannot_leave` nowhere, because MemCode never asks to leave. + +## Trying it on one computer + +`scripts/shared-projects-local.mts` runs the real runtime and the real app window in a +browser, signed in through a memtrace.io on the same computer. + +What is real: the runtime, its beta sign-in and refresh, the token exchange, the calls to +`memsync-server` and the app's own screens. What stands in: the native shell, whose calls +the script answers; the person in the browser, whose approval the script gives with a +session cookie; and the code engine, which is switched off so that nothing is downloaded +and no installed Memtrace is touched. + +1. Start a throwaway PostgreSQL and create two databases, one for the site and one for + MemSync. +2. Run memtrace.io from a branch that has `POST /api/memcode/memsync/token`, with + `MEMCODE_BETA_ENABLED=1` and a signing key. The `memtrace` repository describes this in + `memtrace-ui/docs/memsync-access-tokens.md` and `memcode-projects.md`. +3. Start `memsync-server` after the site, with `MEMSYNC_TOKEN_KEYS_URL` set to the site's + `/api/memcode/jwks`. +4. Give the site a signed-in, approved person: a `user`, an approved `app_users` row and a + `session`, as `e2e/seed.mjs` in `memtrace-ui` does. Their signed session cookie is what + the script needs. +5. Start MemCode: + + ```sh + MEMCODE_LOCAL_SITE=http://127.0.0.1:3000 MEMCODE_LOCAL_SITE_COOKIE= node --import tsx scripts/shared-projects-local.mts --port 5310 + ``` + +6. Open the address it prints. Choose **Connect Memtrace beta** under Account in Settings, + then enter the sharing service address and the token address the script printed. + +A second run on another port, with another `--profile` folder, is a second computer. + +## Choices that are not confirmed + +1. **Where sharing sits.** Its own sidebar entry, shown only once the addresses are set. + It is next to Team until Team Sync goes. +2. **The addresses are typed in Settings**, under an Advanced section of Account. Until + MemSync is deployed there is no default to ship. +3. **The sign-in address must be at www.memtrace.io or on this computer.** +4. **No new package.** gRPC and Protocol Buffers are written against Node's own HTTP/2, + and checked against the `.proto` file. The website uses Connect. +5. **One local project per shared project on a computer, and one shared project per local + project.** +6. **A project in Team Sync cannot be connected** until it has left its team. +7. **Disconnecting is local.** It does not leave the shared project. MemCode has no leave. +8. **The window is given names only.** Account ids and email addresses of other people + stay in the runtime. +9. **Every sentence** on this page and on the screens. +10. **Ten seconds** of patience for a MemSync call and fifteen for the token exchange. +11. **A token is renewed a minute before it expires**, or at half its life when it lives + under two minutes. +12. **The page that opens at memtrace.io** is `/account?workspace=all§ion=memcode`, + which is where the MemCode tab was put on its own branch. The address is fixed in the + native shell. +13. **The local-run script is in the repository**, with a stand-in for the native shell. + +## Not built + +- Board sync. See [the layout proposal](shared-board-layout-proposal.md). +- Leaving a shared project from MemCode. +- Anything for organization projects. MemSync has none yet. +- Moving a Team Sync project to a shared project. +- A default address. It needs a deployed MemSync. +- A notice in the app when an invitation arrives. The Sharing view shows it when opened. From 02afa155cac700006a73aec5053c241954f120cb Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:11:19 +0100 Subject: [PATCH 06/66] chore: add yjs for syncing the board [skip ci] yjs 13.6.33 with lib0 0.2.120 and isomorphic.js 0.2.5, all MIT, pinned exactly like the other packages. The shared board is one Yjs document, as agreed on 21 November 2026. The three packages are added to the notice inventory and table by hand, with their licence files copied by scripts/third-party-notices.mjs. verify-third-party-notices.mjs passes: 852 packages, both lock fingerprints match. The generator was not left to rewrite THIRD_PARTY_NOTICES.md and SOURCE_ACCESS.md, because it drops the hand-written sections on the bundled engine, WebView2 and local inference. Co-Authored-By: Claude Fable 5.2 --- THIRD_PARTY_NOTICES.md | 3 ++ package-lock.json | 49 +++++++++++++++++++ package.json | 1 + third_party/inventory.json | 41 +++++++++++++++- .../licenses/npm/isomorphic.js-0.2.5/LICENSE | 21 ++++++++ third_party/licenses/npm/lib0-0.2.120/LICENSE | 21 ++++++++ third_party/licenses/npm/yjs-13.6.33/LICENSE | 23 +++++++++ 7 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 third_party/licenses/npm/isomorphic.js-0.2.5/LICENSE create mode 100644 third_party/licenses/npm/lib0-0.2.120/LICENSE create mode 100644 third_party/licenses/npm/yjs-13.6.33/LICENSE diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 5e50b9d..da4ccbf 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -795,10 +795,12 @@ commit and provenance in the inventory. | npm | is-promise | 4.0.0 | MIT | [Source](https://www.npmjs.com/package/is-promise/v/4.0.0) | | npm | isarray | 1.0.0 | MIT | [Source](https://www.npmjs.com/package/isarray/v/1.0.0) | | npm | isexe | 2.0.0 | ISC | [Source](https://www.npmjs.com/package/isexe/v/2.0.0) | +| npm | isomorphic.js | 0.2.5 | MIT | [Source](https://www.npmjs.com/package/isomorphic.js/v/0.2.5) | | npm | jose | 6.2.17 | MIT | [Source](https://www.npmjs.com/package/jose/v/6.2.17) | | npm | json-schema-traverse | 1.0.0 | MIT | [Source](https://www.npmjs.com/package/json-schema-traverse/v/1.0.0) | | npm | json-schema-typed | 8.0.2 | BSD-2-Clause | [Source](https://www.npmjs.com/package/json-schema-typed/v/8.0.2) | | npm | jszip | 3.10.2 | (MIT OR GPL-3.0-or-later) | [Source](https://www.npmjs.com/package/jszip/v/3.10.2) | +| npm | lib0 | 0.2.120 | MIT | [Source](https://www.npmjs.com/package/lib0/v/0.2.120) | | npm | lie | 3.3.0 | MIT | [Source](https://www.npmjs.com/package/lie/v/3.3.0) | | npm | longest-streak | 3.1.0 | MIT | [Source](https://www.npmjs.com/package/longest-streak/v/3.1.0) | | npm | lucide-react | 1.72.0 | ISC | [Source](https://www.npmjs.com/package/lucide-react/v/1.72.0) | @@ -932,6 +934,7 @@ commit and provenance in the inventory. | npm | which | 2.0.2 | ISC | [Source](https://www.npmjs.com/package/which/v/2.0.2) | | npm | worker-f | 0.1.24 | MIT | [Source](https://www.npmjs.com/package/worker-f/v/0.1.24) | | npm | wrappy | 1.0.2 | ISC | [Source](https://www.npmjs.com/package/wrappy/v/1.0.2) | +| npm | yjs | 13.6.33 | MIT | [Source](https://www.npmjs.com/package/yjs/v/13.6.33) | | npm | zod-to-json-schema | 3.25.2 | ISC | [Source](https://www.npmjs.com/package/zod-to-json-schema/v/3.25.2) | | npm | zod | 4.6.7 | MIT | [Source](https://www.npmjs.com/package/zod/v/4.6.7) | | npm | zrender | 6.1.0 | BSD-3-Clause | [Source](https://www.npmjs.com/package/zrender/v/6.1.0) | diff --git a/package-lock.json b/package-lock.json index 80cea25..f166249 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,6 +29,7 @@ "react-markdown": "10.1.0", "read-excel-file": "9.3.17", "remark-gfm": "4.0.1", + "yjs": "13.6.33", "zod": "4.6.7" }, "devDependencies": { @@ -3530,6 +3531,16 @@ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "license": "ISC" }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "license": "MIT", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/jose": { "version": "6.2.17", "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", @@ -3599,6 +3610,27 @@ "safe-buffer": "~5.1.0" } }, + "node_modules/lib0": { + "version": "0.2.120", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.120.tgz", + "integrity": "sha512-/a2eRImR8sZbmMVKe2we1/KukDQkuPyPf8yol6epvCu2PH6hurjcRI3mdGFFAi0uGoRJGyns99JquZgxwW1tQg==", + "license": "MIT", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/lie": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", @@ -6136,6 +6168,23 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/yjs": { + "version": "13.6.33", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz", + "integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.99" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/zod": { "version": "4.6.7", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", diff --git a/package.json b/package.json index 3e24520..5d496f3 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "react-markdown": "10.1.0", "read-excel-file": "9.3.17", "remark-gfm": "4.0.1", + "yjs": "13.6.33", "zod": "4.6.7" }, "devDependencies": { diff --git a/third_party/inventory.json b/third_party/inventory.json index 6b66de0..ee6ee7c 100644 --- a/third_party/inventory.json +++ b/third_party/inventory.json @@ -1,7 +1,7 @@ { "scope": "Resolved production npm dependencies and Cargo lockfile dependencies, including target-specific entries. Some Cargo entries are build-only, not shipped executable code.", "inputs": { - "packageLockSha256": "842154542303b5a8e0632e2f840da8637e5601874587d5dd9f61f72e5b3c8266", + "packageLockSha256": "d62a4df05eaf939e6c81561ae59a236526ec7f67a5a9e4a9bd6ad435eaece19c", "cargoLockSha256": "b2fb7fbfa3ab11f34ab8ea68ddc97c3645f5774ddf8840d4eb7fb1618148d79e" }, "packages": [ @@ -11015,6 +11015,19 @@ } ] }, + { + "ecosystem": "npm", + "name": "isomorphic.js", + "version": "0.2.5", + "license": "MIT", + "source": "https://www.npmjs.com/package/isomorphic.js/v/0.2.5", + "notices": [ + { + "file": "licenses/npm/isomorphic.js-0.2.5/LICENSE", + "sha256": "dd6488c9c1a4ce2dc978ecee067e5b6a725b52e6057a450b24f1a23bc373b057" + } + ] + }, { "ecosystem": "npm", "name": "jose", @@ -11071,6 +11084,19 @@ } ] }, + { + "ecosystem": "npm", + "name": "lib0", + "version": "0.2.120", + "license": "MIT", + "source": "https://www.npmjs.com/package/lib0/v/0.2.120", + "notices": [ + { + "file": "licenses/npm/lib0-0.2.120/LICENSE", + "sha256": "5446db1e43fe52faf3faab7e9959fe3762ac11bdc61c0945934c498affd52d73" + } + ] + }, { "ecosystem": "npm", "name": "lie", @@ -12872,6 +12898,19 @@ } ] }, + { + "ecosystem": "npm", + "name": "yjs", + "version": "13.6.33", + "license": "MIT", + "source": "https://www.npmjs.com/package/yjs/v/13.6.33", + "notices": [ + { + "file": "licenses/npm/yjs-13.6.33/LICENSE", + "sha256": "341baa53605ed85d6f95782322854cca56c655ebc7fd4712649b8e7afc6020ff" + } + ] + }, { "ecosystem": "npm", "name": "zod-to-json-schema", diff --git a/third_party/licenses/npm/isomorphic.js-0.2.5/LICENSE b/third_party/licenses/npm/isomorphic.js-0.2.5/LICENSE new file mode 100644 index 0000000..fa92d45 --- /dev/null +++ b/third_party/licenses/npm/isomorphic.js-0.2.5/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Kevin Jahns . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/licenses/npm/lib0-0.2.120/LICENSE b/third_party/licenses/npm/lib0-0.2.120/LICENSE new file mode 100644 index 0000000..ac0e51d --- /dev/null +++ b/third_party/licenses/npm/lib0-0.2.120/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Kevin Jahns . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/licenses/npm/yjs-13.6.33/LICENSE b/third_party/licenses/npm/yjs-13.6.33/LICENSE new file mode 100644 index 0000000..f55e8b4 --- /dev/null +++ b/third_party/licenses/npm/yjs-13.6.33/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2023 + - Kevin Jahns . + - Chair of Computer Science 5 (Databases & Information Systems), RWTH Aachen University, Germany + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 9edf2a3407c3dc8d85603a62bd09877afc7f16ab Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:16:53 +0100 Subject: [PATCH 07/66] feat: follow a streamed reply in the MemSync gRPC client [skip ci] A watched board log is one call the service keeps answering. The client hands over each message in order, one at a time, and asks the service to wait when the reader falls 32 messages behind. The stream ends with the service's status, quietly when the caller hangs up, and as unavailable when the connection is lost under it. A connection that carries a stream is not closed as unused, and is asked every 20 seconds whether it is still there, because a watched log can be silent for hours. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/memsync/grpc.ts | 215 +++++++++++++++++++++- tests/sharing-grpc.test.ts | 303 ++++++++++++++++++++++++++++++++ 2 files changed, 511 insertions(+), 7 deletions(-) diff --git a/runtime/sharing/memsync/grpc.ts b/runtime/sharing/memsync/grpc.ts index 4a06c71..e0340ec 100644 --- a/runtime/sharing/memsync/grpc.ts +++ b/runtime/sharing/memsync/grpc.ts @@ -45,21 +45,43 @@ export interface GrpcCall { metadata?: Record; timeoutMs?: number; } +/** A call the service keeps answering until it ends the call or the caller hangs up. */ +export interface GrpcStream { + /** Settles when the stream is over: rejects with what ended it, unless the caller hung up. */ + finished: Promise; + cancel(): void; +} export interface GrpcChannel { /** One request, one reply. */ unary(call: GrpcCall): Promise; + /** + * One request, then a message at a time for as long as the service sends them. + * `timeoutMs` is how long the service may take to begin. Messages are handed + * over in order, the next one only when the one before has been dealt with. + */ + serverStream( + call: GrpcCall, + onMessage: (message: Uint8Array) => void | Promise, + ): GrpcStream; close(): void; } export interface GrpcChannelOptions { /** How long an unused connection is kept. A stale one is the usual way a call hangs. */ idleMs?: number; maxReplyBytes?: number; + /** How often a connection with an open stream is asked whether it is still there. */ + keepAliveMs?: number; } const FRAME_HEADER_BYTES = 5, NOT_COMPRESSED = 0; const DEFAULT_TIMEOUT_MS = 10_000, DEFAULT_IDLE_MS = 10_000, + DEFAULT_KEEP_ALIVE_MS = 20_000, + // A stream can be silent for hours, so a lost connection shows only when asked. + KEEP_ALIVE_PATIENCE_MS = 10_000, + // Messages read ahead of a slow reader before the service is asked to wait. + HELD_FOR_A_SLOW_READER = 32, // What a gRPC server sends at most unless it is set up otherwise. DEFAULT_MAX_REPLY_BYTES = 4 * 1024 * 1024; @@ -145,11 +167,8 @@ function withoutStatus( ); } -function outcome({ - headers, - trailers, - body, -}: Received): Uint8Array | GrpcFailure { +/** Why the call did not succeed, or nothing when the service said it did. */ +function failureOf({ headers, trailers }: Received): GrpcFailure | undefined { if (!headers) return new GrpcFailure( grpcStatus.UNAVAILABLE, @@ -160,7 +179,7 @@ function outcome({ const status = metadata["grpc-status"]; if (status === undefined) return withoutStatus(headers, metadata); const code = Number(status); - if (code === grpcStatus.OK) return soleMessage(Buffer.concat(body)); + if (code === grpcStatus.OK) return undefined; return new GrpcFailure( Number.isInteger(code) ? code : grpcStatus.UNKNOWN, reasonSent(metadata["grpc-message"]), @@ -168,6 +187,33 @@ function outcome({ ); } +const outcome = (received: Received): Uint8Array | GrpcFailure => + failureOf(received) ?? soleMessage(Buffer.concat(received.body)); + +/** The first whole message in what has arrived so far, or nothing when more bytes are needed. */ +function nextMessage( + arrived: Buffer, + maxMessageBytes: number, +): { message: Uint8Array; rest: Buffer } | GrpcFailure | undefined { + if (arrived.length < FRAME_HEADER_BYTES) return undefined; + if (arrived[0] !== NOT_COMPRESSED) + return new GrpcFailure( + grpcStatus.INTERNAL, + "The sharing service sent a message that is compressed.", + ); + const end = FRAME_HEADER_BYTES + arrived.readUInt32BE(1); + if (end - FRAME_HEADER_BYTES > maxMessageBytes) + return new GrpcFailure( + grpcStatus.RESOURCE_EXHAUSTED, + "The sharing service sent a larger message than MemCode reads.", + ); + if (arrived.length < end) return undefined; + return { + message: new Uint8Array(arrived.subarray(FRAME_HEADER_BYTES, end)), + rest: arrived.subarray(end), + }; +} + const notReached = (error: unknown) => new GrpcFailure( grpcStatus.UNAVAILABLE, @@ -231,6 +277,101 @@ function exchange( }); } +function follow( + session: ClientHttp2Session, + path: string, + call: GrpcCall, + maxMessageBytes: number, + onMessage: (message: Uint8Array) => void | Promise, +): GrpcStream { + const received: Received = { body: [], bytes: 0 }; + const stream = session.request({ + ...call.metadata, + ":method": "POST", + ":path": path, + "content-type": "application/grpc", + te: "trailers", + }); + let arrived: Buffer = Buffer.alloc(0), + handling: Promise = Promise.resolve(), + held = 0, + hungUp = false, + failure: unknown; + const fail = (problem: unknown) => { + if (failure !== undefined || hungUp) return; + failure = problem; + clearTimeout(silence); + stream.close(constants.NGHTTP2_CANCEL); + }; + const silence = setTimeout( + () => + fail( + new GrpcFailure( + grpcStatus.DEADLINE_EXCEEDED, + "The sharing service did not answer in time.", + ), + ), + call.timeoutMs ?? DEFAULT_TIMEOUT_MS, + ); + const handOver = (message: Uint8Array) => { + if (++held > HELD_FOR_A_SLOW_READER) stream.pause(); + handling = handling + .then(() => + failure === undefined && !hungUp ? onMessage(message) : undefined, + ) + .then(() => { + if (--held <= HELD_FOR_A_SLOW_READER / 2) stream.resume(); + }, fail); + }; + stream.on("response", (headers) => { + received.headers = headers; + clearTimeout(silence); + }); + stream.on("trailers", (trailers) => (received.trailers = trailers)); + stream.on("data", (part: Buffer) => { + arrived = arrived.length ? Buffer.concat([arrived, part]) : part; + for (;;) { + const next = nextMessage(arrived, maxMessageBytes); + if (!next) return; + if (next instanceof GrpcFailure) return fail(next); + arrived = next.rest; + handOver(next.message); + } + }); + stream.on("error", (error) => fail(notReached(error))); + const finished = new Promise((resolve, reject) => { + stream.on("close", () => { + clearTimeout(silence); + void handling.then(() => { + const ended = hungUp + ? undefined + : (failure ?? endOf(received, arrived)); + if (ended === undefined) resolve(); + else reject(ended); + }); + }); + }); + stream.end(frame(call.request)); + return { + finished, + cancel() { + hungUp = true; + clearTimeout(silence); + stream.close(constants.NGHTTP2_CANCEL); + }, + }; +} + +/** Why a stream that closed did not end well, or nothing when the service ended it properly. */ +function endOf(received: Received, unread: Buffer): GrpcFailure | undefined { + const failure = failureOf(received); + if (failure || !unread.length) return failure; + return new GrpcFailure( + grpcStatus.INTERNAL, + "The sharing service ended in the middle of a message.", + ); +} + /** After one of these the connection itself is in doubt, so the next call opens another. */ const connectionInDoubt = (failure: unknown) => failure instanceof GrpcFailure && @@ -253,7 +394,8 @@ export function grpcChannel( ): GrpcChannel { const pathPrefix = address.pathname.replace(/\/+$/, ""); const idleMs = options.idleMs ?? DEFAULT_IDLE_MS, - maxReplyBytes = options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES; + maxReplyBytes = options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES, + keepAliveMs = options.keepAliveMs ?? DEFAULT_KEEP_ALIVE_MS; let session: ClientHttp2Session | undefined, idle: ReturnType | undefined, callsInFlight = 0, @@ -271,6 +413,23 @@ export function grpcChannel( session = opened; return opened; }; + /** Asks a connection that carries a stream whether it is still there, and drops one that is not. */ + const keptAlive = (carrying: ClientHttp2Session) => { + const asking = setInterval(() => { + const gaveUp = setTimeout( + () => carrying.destroy(), + KEEP_ALIVE_PATIENCE_MS, + ); + gaveUp.unref(); + const asked = carrying.ping((unanswered) => { + clearTimeout(gaveUp); + if (unanswered) carrying.destroy(); + }); + if (!asked) clearTimeout(gaveUp); + }, keepAliveMs); + asking.unref(); + return () => clearInterval(asking); + }; const restWhenUnused = () => { if (--callsInFlight > 0 || !session) return; const resting = session; @@ -308,6 +467,48 @@ export function grpcChannel( restWhenUnused(); } }, + serverStream(call, onMessage) { + if (closed) + return { + finished: Promise.reject( + new GrpcFailure( + grpcStatus.CANCELLED, + "Sharing was closed before the call was made.", + ), + ), + cancel() {}, + }; + clearTimeout(idle); + callsInFlight++; + let using: ClientHttp2Session; + try { + using = connected(); + } catch (failure) { + restWhenUnused(); + return { finished: Promise.reject(notReached(failure)), cancel() {} }; + } + const stream = follow( + using, + pathPrefix + call.path, + call, + maxReplyBytes, + onMessage, + ); + const stopAsking = keptAlive(using); + const finished = stream.finished + .catch((failure) => { + if (connectionInDoubt(failure)) { + retire(using); + using.close(); + } + throw failure; + }) + .finally(() => { + stopAsking(); + restWhenUnused(); + }); + return { finished, cancel: stream.cancel }; + }, close() { closed = true; clearTimeout(idle); diff --git a/tests/sharing-grpc.test.ts b/tests/sharing-grpc.test.ts index bcef585..e39d217 100644 --- a/tests/sharing-grpc.test.ts +++ b/tests/sharing-grpc.test.ts @@ -431,3 +431,306 @@ test("a closed channel makes no more calls", async () => { await server.close(); } }); + +const trailersWhenDone = (stream: ServerHttp2Stream, status = "0") => { + stream.respond( + { ":status": 200, "content-type": "application/grpc" }, + { waitForTrailers: true }, + ); + stream.on("wantTrailers", () => + stream.sendTrailers({ "grpc-status": status }), + ); +}; +const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const text = (message: Uint8Array) => Buffer.from(message).toString(); + +test("a watched call hands over each message as it arrives, in order, until the service ends it", async () => { + const server = await listening(async (stream) => { + trailersWhenDone(stream); + // Two messages in one piece, then one message in two pieces. + stream.write(Buffer.concat([framed(say("one")), framed(say("two"))])); + await pause(20); + const third = framed(say("three")); + stream.write(third.subarray(0, 3)); + await pause(20); + stream.write(third.subarray(3)); + await pause(20); + stream.end(framed(new Uint8Array())); + }); + const channel = grpcChannel(server.address); + try { + const seen: string[] = []; + const watching = channel.serverStream( + { path: "/s/watch", request: say("from 41") }, + (message) => void seen.push(text(message)), + ); + await watching.finished; + assert.deepEqual(seen, ["one", "two", "three", ""]); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a watched call sends its request and metadata like any other, with no deadline on the stream", async () => { + let seen: IncomingHttpHeaders = {}, + asked = ""; + const server = await listening((stream, headers, request) => { + seen = headers; + asked = request.subarray(5).toString(); + trailersWhenDone(stream); + stream.end(); + }); + const channel = grpcChannel(new URL("/memsync/", server.address)); + try { + await channel.serverStream( + { + path: "/memsync.v1.Boards/WatchUpdates", + request: say("after 7"), + metadata: { authorization: "Bearer token-1" }, + }, + () => {}, + ).finished; + assert.equal(asked, "after 7"); + assert.equal(seen[":path"], "/memsync/memsync.v1.Boards/WatchUpdates"); + assert.equal(seen.authorization, "Bearer token-1"); + assert.equal(seen["content-type"], "application/grpc"); + assert.equal(seen["grpc-timeout"], undefined); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a stream the service ends with a status fails with it, after the messages before it", async () => { + const server = await listening((stream) => { + trailersWhenDone(stream, String(grpcStatus.UNAVAILABLE)); + stream.end(framed(say("last one"))); + }); + const channel = grpcChannel(server.address); + try { + const seen: string[] = []; + const ended = await failure( + channel.serverStream( + { path: "/s/watch", request: say("") }, + (message) => { + seen.push(text(message)); + }, + ).finished, + ); + assert.equal(ended.code, grpcStatus.UNAVAILABLE); + assert.deepEqual(seen, ["last one"]); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a watched call that is turned down at once fails with the rule's name", async () => { + const server = await listening((stream) => + refuse(stream, grpcStatus.NOT_FOUND, "there is no such project", { + "memsync-refusal": "no_such_project", + }), + ); + const channel = grpcChannel(server.address); + try { + const refused = await failure( + channel.serverStream({ path: "/s/watch", request: say("") }, () => {}) + .finished, + ); + assert.equal(refused.code, grpcStatus.NOT_FOUND); + assert.equal(refused.metadata["memsync-refusal"], "no_such_project"); + } finally { + channel.close(); + await server.close(); + } +}); + +test("hanging up ends a watched call quietly, and the service sees it go", async () => { + let gone!: () => void; + const serviceSawItGo = new Promise((resolve) => (gone = resolve)); + const server = await listening((stream) => { + trailersWhenDone(stream); + stream.write(framed(say("first"))); + stream.on("close", gone); + }); + const channel = grpcChannel(server.address); + try { + const seen: string[] = []; + const watching = channel.serverStream( + { path: "/s/watch", request: say("") }, + (message) => void seen.push(text(message)), + ); + await pause(40); + watching.cancel(); + await watching.finished; + await serviceSawItGo; + assert.deepEqual(seen, ["first"]); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a slow reader gets one message at a time and none is lost", async () => { + const count = 200; + const server = await listening((stream) => { + trailersWhenDone(stream); + for (let number = 0; number < count; number++) + stream.write(framed(say(String(number)))); + stream.end(); + }); + const channel = grpcChannel(server.address); + try { + const seen: number[] = []; + let inHand = 0, + mostInHand = 0; + await channel.serverStream( + { path: "/s/watch", request: say("") }, + async (message) => { + mostInHand = Math.max(mostInHand, ++inHand); + await pause(1); + seen.push(Number(text(message))); + inHand--; + }, + ).finished; + assert.equal(mostInHand, 1); + assert.deepEqual( + seen, + Array.from({ length: count }, (_, number) => number), + ); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a reader that fails ends the stream with its own failure", async () => { + const server = await listening((stream) => { + trailersWhenDone(stream); + stream.write( + Buffer.concat([ + framed(say("fine")), + framed(say("bad")), + framed(say("never")), + ]), + ); + }); + const channel = grpcChannel(server.address); + try { + const seen: string[] = []; + await assert.rejects( + channel.serverStream( + { path: "/s/watch", request: say("") }, + (message) => { + seen.push(text(message)); + if (text(message) === "bad") throw new Error("could not keep it"); + }, + ).finished, + /could not keep it/, + ); + assert.deepEqual(seen, ["fine", "bad"]); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a streamed message that is too large, compressed or cut short ends the stream", async () => { + const broken: Array<[string, number, (stream: ServerHttp2Stream) => void]> = [ + [ + "too large", + grpcStatus.RESOURCE_EXHAUSTED, + (stream) => stream.end(framed(new Uint8Array(5000))), + ], + [ + "compressed", + grpcStatus.INTERNAL, + (stream) => stream.end(framed(say("squeezed"), 1)), + ], + [ + "cut short", + grpcStatus.INTERNAL, + (stream) => stream.end(framed(say("whole")).subarray(0, 7)), + ], + ]; + for (const [name, code, send] of broken) { + const server = await listening((stream) => { + trailersWhenDone(stream); + send(stream); + }); + const channel = grpcChannel(server.address, { maxReplyBytes: 4096 }); + try { + const ended = await failure( + channel.serverStream({ path: "/s/watch", request: say("") }, () => {}) + .finished, + ); + assert.equal(ended.code, code, name); + } finally { + channel.close(); + await server.close(); + } + } +}); + +test("a service that never begins to answer a watched call is given up on", async () => { + const server = await listening(() => {}); + const channel = grpcChannel(server.address); + try { + const late = await failure( + channel.serverStream( + { path: "/s/watch", request: say(""), timeoutMs: 100 }, + () => {}, + ).finished, + ); + assert.equal(late.code, grpcStatus.DEADLINE_EXCEEDED); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a quiet stream keeps its connection, and a connection lost under it ends it as unavailable", async () => { + let send!: (message: string) => void; + const server = await listening((stream) => { + trailersWhenDone(stream); + stream.write(framed(say("first"))); + send = (message) => stream.write(framed(say(message))); + }); + const channel = grpcChannel(server.address, { idleMs: 30, keepAliveMs: 25 }); + try { + const seen: string[] = []; + const watching = channel.serverStream( + { path: "/s/watch", request: say("") }, + (message) => void seen.push(text(message)), + ); + // Longer than an unused connection is kept, with a call made and finished in between. + await pause(150); + send("after a long silence"); + await pause(40); + assert.deepEqual(seen, ["first", "after a long silence"]); + assert.equal(server.sessions, 1); + server.hangUp(); + const lost = await failure(watching.finished); + assert.equal(lost.code, grpcStatus.UNAVAILABLE); + } finally { + channel.close(); + await server.close(); + } +}); + +test("a closed channel starts no watched call", async () => { + const server = await listening((stream) => trailersWhenDone(stream)); + const channel = grpcChannel(server.address); + channel.close(); + try { + const refused = await failure( + channel.serverStream({ path: "/s/watch", request: say("") }, () => {}) + .finished, + ); + assert.equal(refused.code, grpcStatus.CANCELLED); + assert.equal(server.sessions, 0); + } finally { + await server.close(); + } +}); From 5a98bdf5274acca8d0a98aa88d596420088141bc Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:16:53 +0100 Subject: [PATCH 08/66] refactor: share signed MemSync calls between its APIs [skip ci] Getting a token, replacing one the service refuses, and turning a failed call into something a person can be told were part of the Projects client. They move to SignedCalls unchanged, so the Boards client can use the same. No behaviour changes: the Projects tests pass as they were, apart from how they build the client. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/memsync/projects-api.ts | 133 +++--------------- runtime/sharing/memsync/signed-calls.ts | 170 ++++++++++++++++++++++++ runtime/sharing/sharing.ts | 3 +- tests/sharing-projects-api.test.ts | 12 +- tests/sharing-real-memsync.test.ts | 4 +- tests/support/projects-api-scenarios.ts | 21 ++- 6 files changed, 215 insertions(+), 128 deletions(-) create mode 100644 runtime/sharing/memsync/signed-calls.ts diff --git a/runtime/sharing/memsync/projects-api.ts b/runtime/sharing/memsync/projects-api.ts index 98e56c9..e433255 100644 --- a/runtime/sharing/memsync/projects-api.ts +++ b/runtime/sharing/memsync/projects-api.ts @@ -1,18 +1,11 @@ -import type { AccessToken } from "../access"; -import { refusalNamed, SharingUnavailable } from "../problems"; -import { GrpcFailure, grpcStatus, type GrpcChannel } from "./grpc"; +import { WireError, type WireMessage } from "./wire"; import { projectsCalls, projectsContract, projectsService, type ProjectsCall, } from "./projects-contract"; -import { - decodeMessage, - encodeMessage, - WireError, - type WireMessage, -} from "./wire"; +import { SignedCalls, type ServiceCall } from "./signed-calls"; export interface PersonRecord { accountId: string; @@ -50,14 +43,6 @@ export interface ProjectsApi { ): Promise; } -/** Where access tokens come from, and where one the service refused is handed back. */ -export interface AccessTokens { - current(): Promise; - forget(token: string): void; -} - -const REFUSAL_HEADER = "memsync-refusal"; - const unreadable = () => new WireError("A reply lacks something it always holds."); const isMessage = (value: unknown): value is WireMessage => @@ -105,120 +90,36 @@ function project(sent: WireMessage): ProjectRecord { }; } -function unavailable(failure: GrpcFailure): SharingUnavailable { - const serviceAnswered = failure.metadata["grpc-status"] !== undefined; - let sentence = - "The sharing address did not answer as a sharing service. Check it in Settings."; - if (failure.code === grpcStatus.UNAUTHENTICATED) - sentence = - "The sharing service did not accept this sign-in. Try again in a few minutes."; - else if (failure.code === grpcStatus.DEADLINE_EXCEEDED) - sentence = - "The sharing service did not answer in time. Try again in a moment."; - else if (serviceAnswered) - sentence = - "The sharing service is having trouble right now. Try again in a few minutes."; - else if (failure.code === grpcStatus.UNAVAILABLE) - sentence = - "The sharing service could not be reached. Check your connection and try again."; - return new SharingUnavailable(sentence, { cause: failure }); -} - -/** What to tell the person about a call that did not end in a reply. */ -function problemWith(call: ProjectsCall, failure: unknown): Error { - if (failure instanceof WireError) - return new SharingUnavailable( - "The sharing service sent a reply MemCode could not read. Updating MemCode may help.", - { cause: failure }, - ); - if (!(failure instanceof GrpcFailure)) return failure as Error; - const rule = failure.metadata[REFUSAL_HEADER]; - const refusal = refusalNamed(rule); - if (refusal) return refusal; - // The log keeps what the sentence leaves out: which call, and the service's own words. - console.error( - `[sharing] ${call} failed: status ${failure.code}${rule ? `, rule ${rule}` : ""}: ${failure.message}`, - ); - if (rule) - return new SharingUnavailable( - "The sharing service turned this down for a reason this version of MemCode does not know. Updating MemCode may help.", - { cause: failure }, - ); - return unavailable(failure); -} - -const signInWasRefused = (failure: unknown) => - failure instanceof GrpcFailure && - failure.code === grpcStatus.UNAUTHENTICATED && - !failure.metadata[REFUSAL_HEADER]; +const call = (name: ProjectsCall): ServiceCall => ({ + service: projectsService, + name, + contract: projectsContract, + ...projectsCalls[name], +}); /** The Projects API over gRPC, signed in with the caller's access token. */ export class MemsyncProjects implements ProjectsApi { - constructor( - private readonly channel: GrpcChannel, - private readonly access: AccessTokens, - private readonly timeoutMs?: number, - ) {} + constructor(private readonly calls: SignedCalls) {} listProjects() { - return this.call("ListProjects", {}, (reply) => + return this.calls.unary(call("ListProjects"), {}, (reply) => messages(reply.projects).map(project), ); } listInvitations() { - return this.call("ListInvitations", {}, (reply) => + return this.calls.unary(call("ListInvitations"), {}, (reply) => messages(reply.invitations).map(invitation), ); } getProject(projectId: string) { - return this.call("GetProject", { project_id: projectId }, project); + return this.calls.unary( + call("GetProject"), + { project_id: projectId }, + project, + ); } acceptInvitation(projectId: string, invitationId: string) { const request = { project_id: projectId, invitation_id: invitationId }; - return this.call("AcceptInvitation", request, project); - } - - private async call( - name: ProjectsCall, - request: WireMessage, - read: (reply: WireMessage) => Answer, - ): Promise { - // A token the service refuses is replaced once: its keys or the token may have just changed. - const first = await this.attempt(name, request, read); - if ("answer" in first) return first.answer; - const second = await this.attempt(name, request, read); - if ("answer" in second) return second.answer; - throw problemWith(name, second.signInRefused); - } - - /** One try, from the token to the reply as MemCode's own record. */ - private async attempt( - name: ProjectsCall, - request: WireMessage, - read: (reply: WireMessage) => Answer, - ): Promise<{ answer: Answer } | { signInRefused: GrpcFailure }> { - const { token } = await this.access.current(); - const shapes = projectsCalls[name]; - try { - const sent = await this.channel.unary({ - path: `/${projectsService}/${name}`, - request: encodeMessage(projectsContract, shapes.request, request), - metadata: { authorization: `Bearer ${token}` }, - timeoutMs: this.timeoutMs, - }); - return { - answer: read(decodeMessage(projectsContract, shapes.reply, sent)), - }; - } catch (failure) { - if (signInWasRefused(failure)) { - this.access.forget(token); - return { signInRefused: failure as GrpcFailure }; - } - const problem = problemWith(name, failure); - // A newly verified address reaches the service only in a new token. - if ("rule" in problem && problem.rule === "email_not_verified") - this.access.forget(token); - throw problem; - } + return this.calls.unary(call("AcceptInvitation"), request, project); } } diff --git a/runtime/sharing/memsync/signed-calls.ts b/runtime/sharing/memsync/signed-calls.ts new file mode 100644 index 0000000..2ac07ba --- /dev/null +++ b/runtime/sharing/memsync/signed-calls.ts @@ -0,0 +1,170 @@ +import type { AccessToken } from "../access"; +import { refusalNamed, SharingUnavailable } from "../problems"; +import { + GrpcFailure, + grpcStatus, + type GrpcChannel, + type GrpcStream, +} from "./grpc"; +import { + decodeMessage, + encodeMessage, + WireError, + type Contract, + type WireMessage, +} from "./wire"; + +/** Where access tokens come from, and where one the service refused is handed back. */ +export interface AccessTokens { + current(): Promise; + forget(token: string): void; +} + +/** One call of one of the sharing service's APIs, with the shapes of what travels. */ +export interface ServiceCall { + service: string; + name: string; + contract: Contract; + request: string; + reply: string; +} + +const REFUSAL_HEADER = "memsync-refusal"; + +function unavailable(failure: GrpcFailure): SharingUnavailable { + const serviceAnswered = failure.metadata["grpc-status"] !== undefined; + let sentence = + "The sharing address did not answer as a sharing service. Check it in Settings."; + if (failure.code === grpcStatus.UNAUTHENTICATED) + sentence = + "The sharing service did not accept this sign-in. Try again in a few minutes."; + else if (failure.code === grpcStatus.DEADLINE_EXCEEDED) + sentence = + "The sharing service did not answer in time. Try again in a moment."; + else if (serviceAnswered) + sentence = + "The sharing service is having trouble right now. Try again in a few minutes."; + else if (failure.code === grpcStatus.UNAVAILABLE) + sentence = + "The sharing service could not be reached. Check your connection and try again."; + return new SharingUnavailable(sentence, { cause: failure }); +} + +/** What to tell the person about a call that did not end in a reply. */ +function problemWith(call: ServiceCall, failure: unknown): Error { + if (failure instanceof WireError) + return new SharingUnavailable( + "The sharing service sent a reply MemCode could not read. Updating MemCode may help.", + { cause: failure }, + ); + if (!(failure instanceof GrpcFailure)) return failure as Error; + const rule = failure.metadata[REFUSAL_HEADER]; + const refusal = refusalNamed(rule); + if (refusal) return refusal; + // The log keeps what the sentence leaves out: which call, and the service's own words. + console.error( + `[sharing] ${call.name} failed: status ${failure.code}${rule ? `, rule ${rule}` : ""}: ${failure.message}`, + ); + if (rule) + return new SharingUnavailable( + "The sharing service turned this down for a reason this version of MemCode does not know. Updating MemCode may help.", + { cause: failure }, + ); + return unavailable(failure); +} + +const signInWasRefused = (failure: unknown) => + failure instanceof GrpcFailure && + failure.code === grpcStatus.UNAUTHENTICATED && + !failure.metadata[REFUSAL_HEADER]; + +/** + * Calls to the sharing service made as the signed-in person. A token the service + * refuses is replaced once, because its keys or the token may have just changed. + * What goes wrong comes back as a problem the person can be told about. + */ +export class SignedCalls { + constructor( + private readonly channel: Pick, + private readonly access: AccessTokens, + private readonly timeoutMs?: number, + ) {} + + async unary( + call: ServiceCall, + request: WireMessage, + read: (reply: WireMessage) => Answer, + ): Promise { + const first = await this.attempt(call, request, read); + if ("answer" in first) return first.answer; + const second = await this.attempt(call, request, read); + if ("answer" in second) return second.answer; + throw problemWith(call, second.signInRefused); + } + + /** A call the service keeps answering. Each message is read before it is handed over. */ + stream( + call: ServiceCall, + request: WireMessage, + onMessage: (message: WireMessage) => void | Promise, + ): GrpcStream { + let open: GrpcStream | undefined, + hungUp = false; + const follow = async (isLastTry: boolean): Promise => { + const { token } = await this.access.current(); + if (hungUp) return; + open = this.channel.serverStream( + this.sent(call, request, token), + (bytes) => onMessage(decodeMessage(call.contract, call.reply, bytes)), + ); + try { + await open.finished; + } catch (failure) { + if (signInWasRefused(failure)) this.access.forget(token); + if (signInWasRefused(failure) && !isLastTry) return follow(true); + throw problemWith(call, failure); + } + }; + return { + finished: follow(false), + cancel() { + hungUp = true; + open?.cancel(); + }, + }; + } + + private sent(call: ServiceCall, request: WireMessage, token: string) { + return { + path: `/${call.service}/${call.name}`, + request: encodeMessage(call.contract, call.request, request), + metadata: { authorization: `Bearer ${token}` }, + timeoutMs: this.timeoutMs, + }; + } + + /** One try, from the token to the reply as MemCode's own record. */ + private async attempt( + call: ServiceCall, + request: WireMessage, + read: (reply: WireMessage) => Answer, + ): Promise<{ answer: Answer } | { signInRefused: GrpcFailure }> { + const { token } = await this.access.current(); + try { + const reply = await this.channel.unary(this.sent(call, request, token)); + return { + answer: read(decodeMessage(call.contract, call.reply, reply)), + }; + } catch (failure) { + if (signInWasRefused(failure)) { + this.access.forget(token); + return { signInRefused: failure as GrpcFailure }; + } + const problem = problemWith(call, failure); + // A newly verified address reaches the service only in a new token. + if ("rule" in problem && problem.rule === "email_not_verified") + this.access.forget(token); + throw problem; + } + } +} diff --git a/runtime/sharing/sharing.ts b/runtime/sharing/sharing.ts index ad8c9ff..964d9aa 100644 --- a/runtime/sharing/sharing.ts +++ b/runtime/sharing/sharing.ts @@ -17,6 +17,7 @@ import { type ProjectRecord, type ProjectsApi, } from "./memsync/projects-api"; +import { SignedCalls } from "./memsync/signed-calls"; import { SharingRefused, SharingSignedOut, @@ -229,7 +230,7 @@ export class Sharing { address: memsync.href, channel, access, - projects: new MemsyncProjects(channel, access), + projects: new MemsyncProjects(new SignedCalls(channel, access)), }; return this.service; } diff --git a/tests/sharing-projects-api.test.ts b/tests/sharing-projects-api.test.ts index 6504739..044e009 100644 --- a/tests/sharing-projects-api.test.ts +++ b/tests/sharing-projects-api.test.ts @@ -1,7 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; import { grpcChannel, grpcStatus } from "../runtime/sharing/memsync/grpc"; -import { MemsyncProjects } from "../runtime/sharing/memsync/projects-api"; import { SharingRefused, SharingSignedOut, @@ -17,6 +16,7 @@ import { startStandInMemsync } from "./support/memsync-stand-in"; import { cast, projectsApiScenarios, + projectsOver, signedInTo, } from "./support/projects-api-scenarios"; @@ -30,7 +30,7 @@ async function fixture(timeoutMs?: number) { let issued = 0; const channel = grpcChannel(service.address); const state = { token: service.tokenFor(people.alex) }; - const projects = new MemsyncProjects( + const projects = projectsOver( channel, { current: async () => { @@ -215,14 +215,13 @@ test("a reply that lacks what it always holds is not passed on half read", async // The same bytes read as an invitation have no project id, sender or dates. const channel = grpcChannel(f.service.address); context.after(() => channel.close()); - const asInvitation = new MemsyncProjects( + const asInvitation = projectsOver( { unary: (call) => channel.unary({ ...call, path: call.path.replace("ListInvitations", "ListProjects"), }), - close() {}, }, { current: async () => ({ token: f.state.token, accountId: "" }), @@ -255,10 +254,9 @@ test("a project or invitation that is missing a part every one has is refused wh }; const whole = { id: "project-1", name: "Launch plan", owner, guest_limit: 2 }; const answering = (message: string, value: WireMessage) => - new MemsyncProjects( + projectsOver( { unary: async () => encodeMessage(projectsContract, message, value), - close() {}, }, { current: async () => ({ token: "t", accountId: "acct-1" }), @@ -308,7 +306,7 @@ test("having no sign-in, or no way to get a token, stops the call before it is m new SharingSignedOut(), new SharingUnavailable("memtrace.io could not be reached."), ]) { - const projects = new MemsyncProjects(channel, { + const projects = projectsOver(channel, { current: async () => { throw problem; }, diff --git a/tests/sharing-real-memsync.test.ts b/tests/sharing-real-memsync.test.ts index a63f530..5749632 100644 --- a/tests/sharing-real-memsync.test.ts +++ b/tests/sharing-real-memsync.test.ts @@ -1,13 +1,13 @@ import test, { after } from "node:test"; import assert from "node:assert/strict"; import { grpcChannel } from "../runtime/sharing/memsync/grpc"; -import { MemsyncProjects } from "../runtime/sharing/memsync/projects-api"; import { SharingUnavailable } from "../runtime/sharing/problems"; import { refusalRules } from "../src/sharing-refusals"; import { actingAs } from "./support/memsync-owner"; import { cast, projectsApiScenarios, + projectsOver, signedInTo, } from "./support/projects-api-scenarios"; import { @@ -62,7 +62,7 @@ test( const channel = grpcChannel(real.address); const forgotten: string[] = []; const token = real.tokenFor(alex, changes); - const projects = new MemsyncProjects(channel, { + const projects = projectsOver(channel, { current: async () => ({ token, accountId: alex.accountId }), forget: (refused) => forgotten.push(refused), }); diff --git a/tests/support/projects-api-scenarios.ts b/tests/support/projects-api-scenarios.ts index f3e56bf..95c0340 100644 --- a/tests/support/projects-api-scenarios.ts +++ b/tests/support/projects-api-scenarios.ts @@ -1,13 +1,30 @@ import test from "node:test"; import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; -import { grpcChannel } from "../../runtime/sharing/memsync/grpc"; +import { + grpcChannel, + type GrpcChannel, +} from "../../runtime/sharing/memsync/grpc"; +import { + SignedCalls, + type AccessTokens, +} from "../../runtime/sharing/memsync/signed-calls"; import { MemsyncProjects } from "../../runtime/sharing/memsync/projects-api"; import { SharingRefused } from "../../runtime/sharing/problems"; import type { RefusalRule } from "../../src/sharing-refusals"; import { actingAs } from "./memsync-owner"; import type { StandInPerson } from "./memsync-stand-in"; +/** MemCode's Projects client over a channel, signed in with the tokens it is handed. */ +export const projectsOver = ( + channel: Pick, + access: AccessTokens, + timeoutMs?: number, +) => + new MemsyncProjects( + new SignedCalls(channel as GrpcChannel, access, timeoutMs), + ); + /** A sharing service to run a scenario against: the stand-in, or a real memsync-server. */ export interface SharingWorld { address: URL; @@ -44,7 +61,7 @@ export function signedInTo(world: SharingWorld, person: StandInPerson) { return { token, /** MemCode's own client. */ - projects: new MemsyncProjects(channel, { + projects: projectsOver(channel, { current: async () => ({ token, accountId: person.accountId }), forget() {}, }), From 407287bbe9238eb32bb6a18258196132b2d0e99d Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:19:53 +0100 Subject: [PATCH 09/66] feat: read, add to and watch a board's log at MemSync [skip ci] MemsyncBoards makes the three Boards calls: append updates, read the next page after a number, and watch everything after a number as it is logged. The shapes are held to a copy of boards.proto by the same test as the Projects shapes, and the owner's calls that only tests make are now held to their contract too. Eight scenarios run against a stand-in log with MemSync's rules and, when a server is named, against the real memsync-server: numbering and dating, sending an update again, a guest and a stranger, each limit by the name of its rule, a log longer than a page, a watcher fed live, and a removed guest whose stream ends with no_such_project. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/memsync/boards-api.ts | 112 +++++++ runtime/sharing/memsync/boards-contract.ts | 51 +++ runtime/sharing/memsync/boards.proto | 78 +++++ tests/sharing-boards-api.test.ts | 147 +++++++++ tests/sharing-real-memsync.test.ts | 4 + tests/sharing-wire.test.ts | 97 ++++-- tests/support/boards-api-scenarios.ts | 359 +++++++++++++++++++++ tests/support/memsync-stand-in-boards.ts | 225 +++++++++++++ tests/support/memsync-stand-in.ts | 31 +- tests/support/projects-api-scenarios.ts | 13 +- 10 files changed, 1086 insertions(+), 31 deletions(-) create mode 100644 runtime/sharing/memsync/boards-api.ts create mode 100644 runtime/sharing/memsync/boards-contract.ts create mode 100644 runtime/sharing/memsync/boards.proto create mode 100644 tests/sharing-boards-api.test.ts create mode 100644 tests/support/boards-api-scenarios.ts create mode 100644 tests/support/memsync-stand-in-boards.ts diff --git a/runtime/sharing/memsync/boards-api.ts b/runtime/sharing/memsync/boards-api.ts new file mode 100644 index 0000000..05d9825 --- /dev/null +++ b/runtime/sharing/memsync/boards-api.ts @@ -0,0 +1,112 @@ +import { + boardsCalls, + boardsContract, + boardsService, + type BoardsCall, +} from "./boards-contract"; +import type { GrpcStream } from "./grpc"; +import type { ServiceCall, SignedCalls } from "./signed-calls"; +import { WireError, type WireMessage } from "./wire"; + +/** One change to a board, as its sender made it. The service never reads the bytes. */ +export interface NewBoardUpdate { + /** A UUID the sender chooses. Sending the same id again adds nothing. */ + id: string; + payload: Uint8Array; +} +export interface UpdateReceipt { + id: string; + /** Its place in the project's log, from 1 with no gaps. */ + sequence: number; + loggedAt: string; +} +export interface LoggedUpdate extends UpdateReceipt { + /** The account that sent it. */ + author: string; + payload: Uint8Array; +} + +/** A project's board log at the sharing service. */ +export interface BoardsApi { + /** Adds updates to the end of the log: at most 100, each at most 1 MiB. */ + append( + projectId: string, + updates: NewBoardUpdate[], + ): Promise; + /** The next page after a number, oldest first. An empty page: nothing newer. */ + readAfter(projectId: string, sequence: number): Promise; + /** Everything after a number, then each new update as it is logged. */ + watchAfter( + projectId: string, + sequence: number, + onUpdate: (update: LoggedUpdate) => void | Promise, + ): GrpcStream; +} + +const unreadable = () => + new WireError("A board update lacks something it always holds."); +const isMessage = (value: unknown): value is WireMessage => + !!value && typeof value === "object" && !Array.isArray(value); +const messages = (value: unknown) => (Array.isArray(value) ? value : []); + +function receipt(sent: WireMessage): UpdateReceipt { + const when = sent.logged_at; + if (!sent.id || !Number(sent.sequence) || !isMessage(when)) + throw unreadable(); + const loggedAt = new Date( + Number(when.seconds) * 1000 + Number(when.nanos) / 1e6, + ); + if (Number.isNaN(loggedAt.getTime())) throw unreadable(); + return { + id: String(sent.id), + sequence: Number(sent.sequence), + loggedAt: loggedAt.toISOString(), + }; +} + +function logged(sent: WireMessage): LoggedUpdate { + if (!(sent.payload instanceof Uint8Array)) throw unreadable(); + return { + ...receipt(sent), + author: String(sent.author_account_id), + payload: sent.payload, + }; +} + +const call = (name: BoardsCall): ServiceCall => ({ + service: boardsService, + name, + contract: boardsContract, + ...boardsCalls[name], +}); + +/** The Boards API over gRPC, signed in with the caller's access token. */ +export class MemsyncBoards implements BoardsApi { + constructor(private readonly calls: SignedCalls) {} + + append(projectId: string, updates: NewBoardUpdate[]) { + const request = { + project_id: projectId, + updates: updates.map(({ id, payload }) => ({ id, payload })), + }; + return this.calls.unary(call("AppendUpdates"), request, (reply) => + messages(reply.receipts).map(receipt), + ); + } + readAfter(projectId: string, sequence: number) { + const request = { project_id: projectId, after_sequence: sequence }; + return this.calls.unary(call("ReadUpdates"), request, (reply) => + messages(reply.updates).map(logged), + ); + } + watchAfter( + projectId: string, + sequence: number, + onUpdate: (update: LoggedUpdate) => void | Promise, + ) { + const request = { project_id: projectId, after_sequence: sequence }; + return this.calls.stream(call("WatchUpdates"), request, (update) => + onUpdate(logged(update)), + ); + } +} diff --git a/runtime/sharing/memsync/boards-contract.ts b/runtime/sharing/memsync/boards-contract.ts new file mode 100644 index 0000000..d23d3ab --- /dev/null +++ b/runtime/sharing/memsync/boards-contract.ts @@ -0,0 +1,51 @@ +import type { Contract } from "./wire"; + +/** + * boards.proto, written out by hand. A test reads the .proto file beside this one + * and fails when the two disagree. + */ +const text = (number: number) => ({ number, kind: "string" }) as const; +const bytes = (number: number) => ({ number, kind: "bytes" }) as const; +const count = (number: number) => ({ number, kind: "uint64" }) as const; +const moment = "google.protobuf.Timestamp"; +const loggedAt = (number: number) => + ({ number, kind: { message: moment } }) as const; +const many = (number: number, message: string) => + ({ number, kind: { message }, repeated: true }) as const; + +export const boardsService = "memsync.v1.Boards"; + +export const boardsContract = { + [moment]: { + seconds: { number: 1, kind: "int64" }, + nanos: { number: 2, kind: "int32" }, + }, + NewBoardUpdate: { id: text(1), payload: bytes(2) }, + BoardUpdate: { + id: text(1), + sequence: count(2), + logged_at: loggedAt(3), + author_account_id: text(4), + payload: bytes(5), + }, + UpdateReceipt: { id: text(1), sequence: count(2), logged_at: loggedAt(3) }, + AppendUpdatesRequest: { + project_id: text(1), + updates: many(2, "NewBoardUpdate"), + }, + AppendUpdatesResponse: { receipts: many(1, "UpdateReceipt") }, + ReadUpdatesRequest: { project_id: text(1), after_sequence: count(2) }, + ReadUpdatesResponse: { updates: many(1, "BoardUpdate") }, + WatchUpdatesRequest: { project_id: text(1), after_sequence: count(2) }, +} satisfies Contract; + +export const boardsCalls = { + AppendUpdates: { + request: "AppendUpdatesRequest", + reply: "AppendUpdatesResponse", + }, + ReadUpdates: { request: "ReadUpdatesRequest", reply: "ReadUpdatesResponse" }, + /** The reply is a stream of these, one per update. */ + WatchUpdates: { request: "WatchUpdatesRequest", reply: "BoardUpdate" }, +} as const; +export type BoardsCall = keyof typeof boardsCalls; diff --git a/runtime/sharing/memsync/boards.proto b/runtime/sharing/memsync/boards.proto new file mode 100644 index 0000000..3219aba --- /dev/null +++ b/runtime/sharing/memsync/boards.proto @@ -0,0 +1,78 @@ +syntax = "proto3"; + +package memsync.v1; + +import "google/protobuf/timestamp.proto"; + +// A project's board, kept in step between computers. +// +// The board is one Yjs document. MemSync keeps its updates in a log: every update gets +// the next number in its project's log and the time the server logged it, once. +// Applying a log in order gives every computer the same board and the same dates. +// MemSync never looks inside an update, so a caller must cope with one it cannot apply. +// +// Calls are signed in and turned down as in the Projects service. Anyone on the project +// can read and add. +service Boards { + // Adds updates to the end of the project's board log. An update whose id is already + // in the log is not added again, so a call can be sent again when its answer was lost. + rpc AppendUpdates(AppendUpdatesRequest) returns (AppendUpdatesResponse); + // Reads the next page of the log after a number, oldest first. An empty page means + // there is nothing newer. + rpc ReadUpdates(ReadUpdatesRequest) returns (ReadUpdatesResponse); + // Sends everything in the log after a number, then every new update as it is logged, + // until the caller hangs up or is no longer on the project. + rpc WatchUpdates(WatchUpdatesRequest) returns (stream BoardUpdate); +} + +message NewBoardUpdate { + // A UUID chosen by the sender. Sending the same id again adds nothing. + string id = 1; + // One Yjs update in the v1 encoding, at most 1 MiB. + bytes payload = 2; +} + +message BoardUpdate { + string id = 1; + // Its place in the project's log, from 1, with no gaps. + uint64 sequence = 2; + // When MemSync logged it. Never earlier than the update before it. + google.protobuf.Timestamp logged_at = 3; + // The `Person.account_id` of whoever sent it. + string author_account_id = 4; + bytes payload = 5; +} + +message UpdateReceipt { + string id = 1; + uint64 sequence = 2; + google.protobuf.Timestamp logged_at = 3; +} + +message AppendUpdatesRequest { + string project_id = 1; + // At most 100, and together small enough for one gRPC message: 4 MiB unless the + // server is set up otherwise. Send a large first sync in several calls. + repeated NewBoardUpdate updates = 2; +} + +message AppendUpdatesResponse { + // One for each update sent, in the order sent. + repeated UpdateReceipt receipts = 1; +} + +message ReadUpdatesRequest { + string project_id = 1; + // 0 reads from the start. + uint64 after_sequence = 2; +} + +message ReadUpdatesResponse { + repeated BoardUpdate updates = 1; +} + +message WatchUpdatesRequest { + string project_id = 1; + // 0 watches from the start. + uint64 after_sequence = 2; +} diff --git a/tests/sharing-boards-api.test.ts b/tests/sharing-boards-api.test.ts new file mode 100644 index 0000000..a15255b --- /dev/null +++ b/tests/sharing-boards-api.test.ts @@ -0,0 +1,147 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { grpcChannel } from "../runtime/sharing/memsync/grpc"; +import { MemsyncBoards } from "../runtime/sharing/memsync/boards-api"; +import { SignedCalls } from "../runtime/sharing/memsync/signed-calls"; +import { SharingUnavailable } from "../runtime/sharing/problems"; +import { boardsApiScenarios } from "./support/boards-api-scenarios"; +import { startStandInMemsync } from "./support/memsync-stand-in"; +import { actingAs } from "./support/memsync-owner"; +import { cast } from "./support/projects-api-scenarios"; + +boardsApiScenarios("stand-in sharing service", startStandInMemsync); + +/** MemCode's Boards client on a project of its own, with tokens the test hands out. */ +async function fixture() { + const service = await startStandInMemsync(); + const { alex } = cast(); + const state = { token: service.tokenFor(alex) }; + const forgotten: string[] = []; + const channel = grpcChannel(service.address); + const boards = new MemsyncBoards( + new SignedCalls(channel, { + current: async () => ({ token: state.token, accountId: alex.accountId }), + forget: (token) => { + forgotten.push(token); + state.token = service.tokenFor(alex); + }, + }), + ); + const project = await actingAs(service.address, state.token).startProject( + "Board", + ); + return { + service, + boards, + project, + state, + forgotten, + close: async () => { + channel.close(); + await service.close(); + }, + }; +} +const update = () => ({ id: randomUUID(), payload: randomBytes(16) }); +const quiet = (context: test.TestContext) => + context.mock.method(console, "error", () => {}); + +test("updates whose receipts were lost are sent again as they were and logged once", async (context) => { + quiet(context); + const f = await fixture(); + try { + const sent = [update(), update()]; + f.service.boards.loseNextReceipts(); + await assert.rejects(f.boards.append(f.project, sent), SharingUnavailable); + assert.equal(f.service.boards.log(f.project).length, 2); + const receipts = await f.boards.append(f.project, sent); + assert.deepEqual( + receipts.map((receipt) => receipt.sequence), + [1, 2], + ); + assert.equal(f.service.boards.log(f.project).length, 2); + } finally { + await f.close(); + } +}); + +test("a watcher whose stream is cut is told the service is unavailable, so it can watch again from its number", async (context) => { + quiet(context); + const f = await fixture(); + try { + await f.boards.append(f.project, [update(), update()]); + const seen: number[] = []; + const watching = f.boards.watchAfter(f.project, 0, (logged) => { + seen.push(logged.sequence); + }); + while (seen.length < 2) + await new Promise((resolve) => setTimeout(resolve, 5)); + f.service.boards.cutWatchers(); + await assert.rejects(watching.finished, SharingUnavailable); + await f.boards.append(f.project, [update()]); + const again = f.boards.watchAfter(f.project, seen.at(-1)!, (logged) => { + seen.push(logged.sequence); + }); + while (seen.length < 3) + await new Promise((resolve) => setTimeout(resolve, 5)); + again.cancel(); + await again.finished; + assert.deepEqual(seen, [1, 2, 3]); + } finally { + await f.close(); + } +}); + +test("a watcher whose token is turned away watches again with a new one, once", async (context) => { + quiet(context); + const f = await fixture(); + try { + await f.boards.append(f.project, [update()]); + const first = f.state.token; + f.service.expire(first); + const seen: number[] = []; + const watching = f.boards.watchAfter(f.project, 0, (logged) => { + seen.push(logged.sequence); + }); + while (!seen.length) await new Promise((resolve) => setTimeout(resolve, 5)); + assert.deepEqual(f.forgotten, [first]); + watching.cancel(); + await watching.finished; + f.service.turnAwayNextCall(); + f.service.turnAwayNextCall(); + await assert.rejects( + f.boards.watchAfter(f.project, 0, () => {}).finished, + (problem) => + problem instanceof SharingUnavailable && + /did not accept this sign-in/.test(problem.message), + ); + } finally { + await f.close(); + } +}); + +test("hanging up before the token has arrived starts no watch", async () => { + const service = await startStandInMemsync(); + const channel = grpcChannel(service.address); + try { + let hand!: (token: string) => void; + const boards = new MemsyncBoards( + new SignedCalls(channel, { + current: () => + new Promise((resolve) => { + hand = (token) => resolve({ token, accountId: "a" }); + }), + forget() {}, + }), + ); + const watching = boards.watchAfter("any", 0, () => {}); + watching.cancel(); + hand("a token that arrives too late"); + await watching.finished; + assert.equal(service.calls.length, 0); + } finally { + channel.close(); + await service.close(); + } +}); diff --git a/tests/sharing-real-memsync.test.ts b/tests/sharing-real-memsync.test.ts index 5749632..d8ef64d 100644 --- a/tests/sharing-real-memsync.test.ts +++ b/tests/sharing-real-memsync.test.ts @@ -4,6 +4,7 @@ import { grpcChannel } from "../runtime/sharing/memsync/grpc"; import { SharingUnavailable } from "../runtime/sharing/problems"; import { refusalRules } from "../src/sharing-refusals"; import { actingAs } from "./support/memsync-owner"; +import { boardsApiScenarios } from "./support/boards-api-scenarios"; import { cast, projectsApiScenarios, @@ -36,6 +37,9 @@ projectsApiScenarios( skip: realMemsyncMissing, }, ); +boardsApiScenarios("real memsync-server", async () => worldOn(await server()), { + skip: realMemsyncMissing, +}); test( "real memsync-server: a token it has no reason to trust is turned away", diff --git a/tests/sharing-wire.test.ts b/tests/sharing-wire.test.ts index 70b5b75..6e68615 100644 --- a/tests/sharing-wire.test.ts +++ b/tests/sharing-wire.test.ts @@ -12,6 +12,12 @@ import { projectsContract, projectsService, } from "../runtime/sharing/memsync/projects-contract"; +import { + boardsCalls, + boardsContract, + boardsService, +} from "../runtime/sharing/memsync/boards-contract"; +import { ownerCalls, ownerContract } from "./support/memsync-owner"; const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString("hex"); const bytes = (text: string) => new Uint8Array(Buffer.from(text, "hex")); @@ -224,7 +230,7 @@ function parseProto(source: string) { } const calls: Record = {}; for (const [, name, request, reply] of text.matchAll( - /rpc\s+(\w+)\s*\(\s*(\w+)\s*\)\s*returns\s*\(\s*(\w+)\s*\)/g, + /rpc\s+(\w+)\s*\(\s*(\w+)\s*\)\s*returns\s*\(\s*(?:stream\s+)?(\w+)\s*\)/g, )) calls[name] = { request, reply }; return { @@ -235,36 +241,77 @@ function parseProto(source: string) { }; } -test("what MemCode reads and writes is what the contract says", async () => { - const contract = parseProto( +/** The shapes written by hand, as the .proto file would state them. */ +const written = (shapes: Contract) => + Object.fromEntries( + Object.entries(shapes) + .filter(([name]) => !name.startsWith("google.protobuf.")) + .map(([name, shape]) => [ + name, + Object.fromEntries( + Object.entries(shape).map(([field, stated]) => [ + field, + { + number: stated.number, + kind: + typeof stated.kind === "string" + ? stated.kind + : stated.kind.message, + repeated: "repeated" in stated && !!stated.repeated, + }, + ]), + ), + ]), + ); +const contractIn = async (file: string) => + parseProto( await readFile( - new URL("../runtime/sharing/memsync/projects.proto", import.meta.url), + new URL(`../runtime/sharing/memsync/${file}`, import.meta.url), "utf8", ), ); + +test("what MemCode reads and writes of projects is what the contract says", async () => { + const contract = await contractIn("projects.proto"); assert.equal(`${contract.package}.${contract.service}`, projectsService); - for (const [name, call] of Object.entries(projectsCalls)) + // The owner's calls are used by tests only, and are held to the contract all the same. + for (const [name, call] of Object.entries(ownerCalls)) assert.deepEqual(contract.calls[name], call, `call ${name}`); - const shapes = projectsContract as Contract; - for (const [name, shape] of Object.entries(shapes)) { - if (name.startsWith("google.protobuf.")) continue; - const written = Object.fromEntries( - Object.entries(shape).map(([field, written]) => [ - field, - { - number: written.number, - kind: - typeof written.kind === "string" - ? written.kind - : written.kind.message, - repeated: "repeated" in written && !!written.repeated, - }, - ]), - ); - assert.deepEqual(written, contract.messages[name], `message ${name}`); - } - // Every message a call uses is one MemCode has a shape for. + for (const [name, shape] of Object.entries(written(ownerContract))) + assert.deepEqual(shape, contract.messages[name], `message ${name}`); for (const call of Object.values(projectsCalls)) for (const used of [call.request, call.reply]) - assert.ok(shapes[used], `no shape for ${used}`); + assert.ok((projectsContract as Contract)[used], `no shape for ${used}`); +}); + +test("what MemCode reads and writes of a board's log is what the contract says", async () => { + const contract = await contractIn("boards.proto"); + assert.equal(`${contract.package}.${contract.service}`, boardsService); + // A watched log answers with a stream, which the contract marks and the shape does not. + assert.deepEqual( + Object.keys(contract.calls).sort(), + Object.keys(boardsCalls).sort(), + ); + for (const [name, call] of Object.entries(boardsCalls)) + assert.deepEqual(contract.calls[name], call, `call ${name}`); + assert.deepEqual(written(boardsContract), contract.messages); +}); + +test("a logged update travels with its bytes, its number and its time intact", () => { + const payload = new Uint8Array([0, 1, 2, 250, 255, 0]); + const logged = { + id: "5f0c7a52-0b1f-4a43-8a3b-0c5d7e9f1a22", + sequence: 4294967297, + logged_at: { seconds: 1795300000, nanos: 5 }, + author_account_id: "acct-1", + payload, + }; + assert.deepEqual( + decodeMessage( + boardsContract, + "BoardUpdate", + encodeMessage(boardsContract, "BoardUpdate", logged), + ), + logged, + ); }); diff --git a/tests/support/boards-api-scenarios.ts b/tests/support/boards-api-scenarios.ts new file mode 100644 index 0000000..c99e899 --- /dev/null +++ b/tests/support/boards-api-scenarios.ts @@ -0,0 +1,359 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import type { LoggedUpdate } from "../../runtime/sharing/memsync/boards-api"; +import { + cast, + refusedBy, + signedInTo, + type SharingWorld, +} from "./projects-api-scenarios"; + +const update = (bytes = 24) => ({ + id: randomUUID(), + payload: randomBytes(bytes), +}); +const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +async function until(isTrue: () => boolean, what: string) { + const deadline = Date.now() + 5000; + while (!isTrue()) { + if (Date.now() > deadline) assert.fail(`still waiting for ${what}`); + await pause(10); + } +} +/** Reads a whole log the way MemCode does: page after page until one is empty. */ +async function wholeLog( + boards: ReturnType["boards"], + project: string, +) { + const all: LoggedUpdate[] = []; + for (;;) { + const page = await boards.readAfter(project, all.at(-1)?.sequence ?? 0); + if (!page.length) return all; + all.push(...page); + } +} + +/** What MemCode's Boards client must do against any sharing service that follows the contract. */ +export function boardsApiScenarios( + where: string, + open: () => Promise, + options: { skip?: string | false } = {}, +) { + const scenario = ( + name: string, + run: (world: SharingWorld) => Promise, + ) => + test(`${where}: ${name}`, { skip: options.skip }, async () => { + const world = await open(); + try { + await run(world); + } finally { + await world.close(); + } + }); + + scenario( + "updates are numbered from one, dated, and read back as the bytes that were sent", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex); + try { + const project = await alex.website.startProject("Board"); + assert.deepEqual(await alex.boards.readAfter(project, 0), []); + const sent = [update(), update(1), update(5000)]; + const receipts = await alex.boards.append(project, sent); + assert.deepEqual( + receipts.map((receipt) => [receipt.id, receipt.sequence]), + sent.map((one, at) => [one.id, at + 1]), + ); + // Updates sent in one call share a time. + assert.equal( + new Set(receipts.map((receipt) => receipt.loggedAt)).size, + 1, + ); + assert.ok( + Math.abs(Date.parse(receipts[0].loggedAt) - Date.now()) < + 400 * 86400000, + ); + const read = await alex.boards.readAfter(project, 0); + assert.deepEqual( + read.map((logged) => [ + logged.id, + logged.sequence, + logged.loggedAt, + logged.author, + ]), + receipts.map((receipt) => [ + receipt.id, + receipt.sequence, + receipt.loggedAt, + people.alex.accountId, + ]), + ); + for (const [at, logged] of read.entries()) + assert.deepEqual( + Buffer.from(logged.payload), + Buffer.from(sent[at].payload), + ); + assert.deepEqual( + (await alex.boards.readAfter(project, 1)).map( + (logged) => logged.sequence, + ), + [2, 3], + ); + assert.deepEqual(await alex.boards.readAfter(project, 3), []); + } finally { + alex.close(); + } + }, + ); + + scenario( + "an update sent again adds nothing and is told the number it already has", + async (world) => { + const alex = signedInTo(world, cast().alex); + try { + const project = await alex.website.startProject("Board"); + const first = [update(), update()]; + const before = await alex.boards.append(project, first); + const again = await alex.boards.append(project, [ + first[1], + update(), + first[0], + ]); + assert.deepEqual( + again.map((receipt) => receipt.sequence), + [2, 3, 1], + ); + assert.equal(again[2].loggedAt, before[0].loggedAt); + assert.equal((await wholeLog(alex.boards, project)).length, 3); + } finally { + alex.close(); + } + }, + ); + + scenario( + "a later call is never dated before an earlier one", + async (world) => { + const alex = signedInTo(world, cast().alex); + try { + const project = await alex.website.startProject("Board"); + const times: string[] = []; + for (let call = 0; call < 5; call++) + times.push( + (await alex.boards.append(project, [update()]))[0].loggedAt, + ); + assert.deepEqual(times, [...times].sort()); + } finally { + alex.close(); + } + }, + ); + + scenario( + "a guest reads and adds like the owner, and anyone else finds no such project", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo), + dana = signedInTo(world, people.dana); + try { + const project = await alex.website.startProject("Board"); + await bo.projects.acceptInvitation( + project, + await alex.website.invite(project, people.bo.email!), + ); + await alex.boards.append(project, [update()]); + const [fromBo] = await bo.boards.append(project, [update()]); + assert.equal(fromBo.sequence, 2); + assert.deepEqual( + (await alex.boards.readAfter(project, 0)).map( + (logged) => logged.author, + ), + [people.alex.accountId, people.bo.accountId], + ); + await assert.rejects( + dana.boards.append(project, [update()]), + refusedBy("no_such_project"), + ); + await assert.rejects( + dana.boards.readAfter(project, 0), + refusedBy("no_such_project"), + ); + await assert.rejects( + dana.boards.watchAfter(project, 0, () => {}).finished, + refusedBy("no_such_project"), + ); + await assert.rejects( + alex.boards.readAfter("not-an-id", 0), + refusedBy("no_such_project"), + ); + assert.equal((await wholeLog(alex.boards, project)).length, 2); + } finally { + for (const person of [alex, bo, dana]) person.close(); + } + }, + ); + + scenario( + "what the log will not take is refused by the name of its rule, and what it just takes is taken", + async (world) => { + const alex = signedInTo(world, cast().alex); + try { + const project = await alex.website.startProject("Board"); + const mebibyte = 1024 * 1024; + await assert.rejects( + alex.boards.append( + project, + Array.from({ length: 101 }, () => update(1)), + ), + refusedBy("too_many_updates"), + ); + await assert.rejects( + alex.boards.append(project, [ + { id: randomUUID(), payload: new Uint8Array() }, + ]), + refusedBy("empty_update"), + ); + await assert.rejects( + alex.boards.append(project, [update(mebibyte + 1)]), + refusedBy("update_too_large"), + ); + await assert.rejects( + alex.boards.append(project, [ + { id: "not-a-uuid", payload: randomBytes(4) }, + ]), + refusedBy("invalid_update_id"), + ); + // A call that is turned down logs none of its updates. + await assert.rejects( + alex.boards.append(project, [ + update(), + { id: "nope", payload: randomBytes(4) }, + ]), + refusedBy("invalid_update_id"), + ); + assert.deepEqual(await alex.boards.readAfter(project, 0), []); + const hundred = await alex.boards.append( + project, + Array.from({ length: 100 }, () => update(8)), + ); + assert.equal(hundred.at(-1)!.sequence, 100); + const [largest] = await alex.boards.append(project, [update(mebibyte)]); + assert.equal(largest.sequence, 101); + const read = await wholeLog(alex.boards, project); + assert.equal(read.length, 101); + assert.equal(read.at(-1)!.payload.length, mebibyte); + } finally { + alex.close(); + } + }, + ); + + scenario( + "a log longer than a page is read whole, page after page, in order", + async (world) => { + const alex = signedInTo(world, cast().alex); + try { + const project = await alex.website.startProject("Board"); + const sent = Array.from({ length: 230 }, () => update(16)); + for (let from = 0; from < sent.length; from += 100) + await alex.boards.append(project, sent.slice(from, from + 100)); + const read = await wholeLog(alex.boards, project); + assert.deepEqual( + read.map((logged) => logged.id), + sent.map((one) => one.id), + ); + assert.deepEqual( + read.map((logged) => logged.sequence), + sent.map((_, at) => at + 1), + ); + } finally { + alex.close(); + } + }, + ); + + scenario( + "a watcher is sent what the log holds after a number, then each new update as it is logged", + async (world) => { + const people = cast(); + const mac = signedInTo(world, people.alex), + windows = signedInTo(world, people.alex); + try { + const project = await mac.website.startProject("Board"); + const early = [update(), update(), update()]; + await mac.boards.append(project, early); + const seen: LoggedUpdate[] = []; + const watching = windows.boards.watchAfter(project, 1, (logged) => { + seen.push(logged); + }); + await until(() => seen.length === 2, "what the log already held"); + const late = update(300); + const [receipt] = await mac.boards.append(project, [late]); + await until( + () => seen.length === 3, + "the update logged while watching", + ); + assert.deepEqual( + seen.map((logged) => [logged.id, logged.sequence]), + [ + [early[1].id, 2], + [early[2].id, 3], + [late.id, 4], + ], + ); + assert.equal(seen[2].loggedAt, receipt.loggedAt); + assert.deepEqual( + Buffer.from(seen[2].payload), + Buffer.from(late.payload), + ); + watching.cancel(); + await watching.finished; + await mac.boards.append(project, [update()]); + await pause(60); + assert.equal(seen.length, 3, "nothing arrives after hanging up"); + } finally { + mac.close(); + windows.close(); + } + }, + ); + + scenario( + "a guest who is removed stops being sent updates, and is told the project is gone", + async (world) => { + const people = cast(); + const alex = signedInTo(world, people.alex), + bo = signedInTo(world, people.bo); + try { + const project = await alex.website.startProject("Board"); + await bo.projects.acceptInvitation( + project, + await alex.website.invite(project, people.bo.email!), + ); + const seen: number[] = []; + const watching = bo.boards.watchAfter(project, 0, (logged) => { + seen.push(logged.sequence); + }); + // The stream may end at any moment from here on, so its end is awaited from the start. + const toldItIsGone = assert.rejects( + watching.finished, + refusedBy("no_such_project"), + ); + await alex.boards.append(project, [update()]); + await until(() => seen.length === 1, "the first update"); + await alex.website.removeGuest(project, people.bo.accountId); + // MemSync asks who is on the project again when the log grows. + await alex.boards.append(project, [update()]); + await toldItIsGone; + assert.deepEqual(seen, [1]); + } finally { + alex.close(); + bo.close(); + } + }, + ); +} diff --git a/tests/support/memsync-stand-in-boards.ts b/tests/support/memsync-stand-in-boards.ts new file mode 100644 index 0000000..89b2157 --- /dev/null +++ b/tests/support/memsync-stand-in-boards.ts @@ -0,0 +1,225 @@ +import type { ServerHttp2Stream } from "node:http2"; +import { + boardsCalls, + boardsContract, +} from "../../runtime/sharing/memsync/boards-contract"; +import { + decodeMessage, + encodeMessage, + type WireMessage, +} from "../../runtime/sharing/memsync/wire"; +import type { StandInPerson } from "./memsync-stand-in"; + +export interface StandInLoggedUpdate { + id: string; + sequence: number; + loggedAt: number; + author: string; + payload: Uint8Array; +} +type BoardRule = + | "no_such_project" + | "invalid_update_id" + | "empty_update" + | "update_too_large" + | "too_many_updates"; +interface Watcher { + project: string; + person: StandInPerson; + after: number; + stream: ServerHttp2Stream; +} + +const MAX_UPDATES_PER_CALL = 100, + MAX_UPDATE_BYTES = 1024 * 1024, + PAGE = 50; +const UNAVAILABLE = 14; +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const framed = (message: Uint8Array) => { + const frame = Buffer.alloc(5 + message.length); + frame.writeUInt32BE(message.length, 1); + frame.set(message, 5); + return frame; +}; +const moment = (ms: number) => ({ + seconds: Math.floor(ms / 1000), + nanos: (ms % 1000) * 1e6, +}); +const logged = (update: StandInLoggedUpdate): WireMessage => ({ + id: update.id, + sequence: update.sequence, + logged_at: moment(update.loggedAt), + author_account_id: update.author, + payload: update.payload, +}); + +/** + * MemSync's board logs, kept in memory with its rules: every update numbered + * and dated once, an id never logged twice, and a watcher fed what is new. + */ +export function standInBoardLogs(the: { + isOnProject(project: string, person: StandInPerson): boolean; + now(): number; + refuse(rule: BoardRule): never; +}) { + const logs = new Map(); + const watchers = new Set(); + let loseNextReceipts = false; + const logOf = (project: string) => { + if (!logs.has(project)) logs.set(project, []); + return logs.get(project)!; + }; + const allowed = (project: unknown, person: StandInPerson) => + the.isOnProject(String(project), person) + ? String(project) + : the.refuse("no_such_project"); + + function feed(watcher: Watcher) { + if (!the.isOnProject(watcher.project, watcher.person)) { + watchers.delete(watcher); + return void watcher.stream.end(); + } + for (const update of logOf(watcher.project)) + if (update.sequence > watcher.after) { + watcher.stream.write( + framed(encodeMessage(boardsContract, "BoardUpdate", logged(update))), + ); + watcher.after = update.sequence; + } + } + + function append(request: WireMessage, caller: StandInPerson): WireMessage { + const sent = request.updates as WireMessage[]; + if (sent.length > MAX_UPDATES_PER_CALL) the.refuse("too_many_updates"); + for (const update of sent) { + if (!uuid.test(String(update.id))) the.refuse("invalid_update_id"); + const payload = update.payload as Uint8Array; + if (!payload.length) the.refuse("empty_update"); + if (payload.length > MAX_UPDATE_BYTES) the.refuse("update_too_large"); + } + const log = logOf(allowed(request.project_id, caller)); + // Updates sent in one call share a time, never earlier than the entry before. + const at = Math.max(the.now(), log.at(-1)?.loggedAt ?? 0); + const receipts = sent.map((update) => { + const id = String(update.id).toLowerCase(); + let entry = log.find((known) => known.id === id); + if (!entry) { + entry = { + id, + sequence: log.length + 1, + loggedAt: at, + author: caller.accountId, + payload: update.payload as Uint8Array, + }; + log.push(entry); + } + return { + id: entry.id, + sequence: entry.sequence, + logged_at: moment(entry.loggedAt), + }; + }); + watchers.forEach(feed); + return { receipts }; + } + + function read(request: WireMessage, caller: StandInPerson): WireMessage { + const log = logOf(allowed(request.project_id, caller)); + const after = Number(request.after_sequence); + return { + updates: log + .filter((update) => update.sequence > after) + .slice(0, PAGE) + .map(logged), + }; + } + + function watch( + stream: ServerHttp2Stream, + request: WireMessage, + caller: StandInPerson, + ) { + const watcher: Watcher = { + project: allowed(request.project_id, caller), + person: caller, + after: Number(request.after_sequence), + stream, + }; + stream.respond( + { ":status": 200, "content-type": "application/grpc" }, + { waitForTrailers: true }, + ); + stream.on("wantTrailers", () => + stream.sendTrailers( + the.isOnProject(watcher.project, caller) + ? { "grpc-status": String(UNAVAILABLE) } + : { + "grpc-status": "5", + "memsync-refusal": "no_such_project", + }, + ), + ); + stream.on("close", () => watchers.delete(watcher)); + watchers.add(watcher); + feed(watcher); + } + + return { + /** Answers one Boards call. A refusal is thrown before anything is sent. */ + answer( + stream: ServerHttp2Stream, + method: keyof typeof boardsCalls, + caller: StandInPerson, + body: Buffer, + ) { + const call = boardsCalls[method]; + const request = decodeMessage( + boardsContract, + call.request, + body.subarray(5), + ); + if (method === "WatchUpdates") return watch(stream, request, caller); + const reply = + method === "AppendUpdates" + ? append(request, caller) + : read(request, caller); + if (method === "AppendUpdates" && loseNextReceipts) { + // Logged, and the answer never arrives. + loseNextReceipts = false; + return void stream.close(); + } + stream.respond( + { ":status": 200, "content-type": "application/grpc" }, + { waitForTrailers: true }, + ); + stream.on("wantTrailers", () => + stream.sendTrailers({ "grpc-status": "0" }), + ); + stream.end(framed(encodeMessage(boardsContract, call.reply, reply))); + }, + /** A project's log as it stands. */ + log: (project: string) => [...logOf(project)], + /** What is kept for an entry is no longer what was sent, as after a fault in storage. */ + damage(project: string, sequence: number, payload: Uint8Array) { + logOf(project)[sequence - 1].payload = payload; + }, + loseNextReceipts() { + loseNextReceipts = true; + }, + /** Ends every watcher's stream, as a proxy that drops quiet connections does. */ + cutWatchers() { + for (const watcher of [...watchers]) watcher.stream.end(); + }, + /** Looks again at who may watch, as MemSync does every ten seconds. */ + recheckWatchers() { + watchers.forEach(feed); + }, + get watching() { + return watchers.size; + }, + forget(project: string) { + logs.delete(project); + }, + }; +} diff --git a/tests/support/memsync-stand-in.ts b/tests/support/memsync-stand-in.ts index a17a704..960ebe2 100644 --- a/tests/support/memsync-stand-in.ts +++ b/tests/support/memsync-stand-in.ts @@ -7,7 +7,9 @@ import { type WireMessage, } from "../../runtime/sharing/memsync/wire"; import { grpcStatus } from "../../runtime/sharing/memsync/grpc"; +import { boardsCalls } from "../../runtime/sharing/memsync/boards-contract"; import { ownerCalls, ownerContract } from "./memsync-owner"; +import { standInBoardLogs } from "./memsync-stand-in-boards"; /** Someone a token signs in. `email` is their verified address, if they have one. */ export interface StandInPerson { @@ -56,6 +58,10 @@ const refusals = { email_not_verified: grpcStatus.FAILED_PRECONDITION, invalid_project_name: grpcStatus.INVALID_ARGUMENT, invalid_email: grpcStatus.INVALID_ARGUMENT, + invalid_update_id: grpcStatus.INVALID_ARGUMENT, + empty_update: grpcStatus.INVALID_ARGUMENT, + update_too_large: grpcStatus.INVALID_ARGUMENT, + too_many_updates: grpcStatus.INVALID_ARGUMENT, } as const; const refuse = (rule: keyof typeof refusals): never => { throw new Refused(refusals[rule], rule); @@ -126,6 +132,15 @@ export async function startStandInMemsync() { : refuse(guestsAreTold); }; + const boards = standInBoardLogs({ + isOnProject: (id, person) => { + const project = projects.get(id); + return !!project && isOn(project, person); + }, + now: () => now, + refuse, + }); + const handlers: Record< keyof typeof ownerCalls, (request: WireMessage, caller: StandInPerson) => WireMessage @@ -221,10 +236,15 @@ export async function startStandInMemsync() { project.guests = project.guests.filter( (guest) => guest.accountId !== account_id, ); + boards.recheckWatchers(); return projectMessage(project); }, DeleteProject({ project_id }, caller) { - projects.delete(ownedBy(project_id, caller, "not_the_owner").id); + const deleted = ownedBy(project_id, caller, "not_the_owner").id; + projects.delete(deleted); + // A board goes with its project, and whoever watched it is told it is gone. + boards.recheckWatchers(); + boards.forget(deleted); return {}; }, }; @@ -262,6 +282,13 @@ export async function startStandInMemsync() { const caller = signedIn.get(token); if (!caller || !bearer.startsWith("Bearer ")) throw new Refused(grpcStatus.UNAUTHENTICATED); + if (method in boardsCalls) + return boards.answer( + stream, + method as keyof typeof boardsCalls, + caller, + body, + ); const call = ownerCalls[method]; if (!call) throw new Refused(grpcStatus.UNIMPLEMENTED); const reply = handlers[method]( @@ -346,6 +373,8 @@ export async function startStandInMemsync() { stallNextCall() { stallNext = true; }, + /** The board logs, with what a test may do to them. */ + boards, async close() { sessions.forEach((session) => session.destroy()); await new Promise((resolve) => server.close(() => resolve())); diff --git a/tests/support/projects-api-scenarios.ts b/tests/support/projects-api-scenarios.ts index 95c0340..2354974 100644 --- a/tests/support/projects-api-scenarios.ts +++ b/tests/support/projects-api-scenarios.ts @@ -9,6 +9,7 @@ import { SignedCalls, type AccessTokens, } from "../../runtime/sharing/memsync/signed-calls"; +import { MemsyncBoards } from "../../runtime/sharing/memsync/boards-api"; import { MemsyncProjects } from "../../runtime/sharing/memsync/projects-api"; import { SharingRefused } from "../../runtime/sharing/problems"; import type { RefusalRule } from "../../src/sharing-refusals"; @@ -58,13 +59,15 @@ export function cast() { export function signedInTo(world: SharingWorld, person: StandInPerson) { const token = world.tokenFor(person); const channel = grpcChannel(world.address); + const access = { + current: async () => ({ token, accountId: person.accountId }), + forget() {}, + }; return { token, - /** MemCode's own client. */ - projects: projectsOver(channel, { - current: async () => ({ token, accountId: person.accountId }), - forget() {}, - }), + /** MemCode's own clients. */ + projects: projectsOver(channel, access), + boards: new MemsyncBoards(new SignedCalls(channel, access)), /** What the same person does at memtrace.io. */ website: actingAs(world.address, token), close: () => channel.close(), From 957e6103204b693b6feb61a993e34d4579aadaee Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:22:46 +0100 Subject: [PATCH 10/66] feat: lay a board out in one Yjs document [skip ci] runtime/sharing/board/document.ts keeps a board the way the layout agreed on 21 November 2026 says: a map per collection at the top of the document, an entry per id, plain values replaced whole, a set as one key per member, and long text written as the difference between the old and the new wording. Deleting marks an entry and keeps it. An entry is made once: an id the document already holds is written into, never replaced, because a second map under the same id would discard every edit made to the first. The tests have two computers change one board and meet: different tasks, different fields of one task, one field, labels, runbook steps, a description edited in two places, two moves at once, and a deletion against an edit. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/board/document.ts | 184 +++++++++++++ tests/sharing-board-document.test.ts | 384 +++++++++++++++++++++++++++ 2 files changed, 568 insertions(+) create mode 100644 runtime/sharing/board/document.ts create mode 100644 tests/sharing-board-document.test.ts diff --git a/runtime/sharing/board/document.ts b/runtime/sharing/board/document.ts new file mode 100644 index 0000000..c6a5d4f --- /dev/null +++ b/runtime/sharing/board/document.ts @@ -0,0 +1,184 @@ +import * as Y from "yjs"; + +/** + * A shared board as one Yjs document: docs/shared-board-layout-proposal.md. + * + * Every collection is a map at the top of the document. An entry is a map of + * fields under the id of the thing it describes. This file knows how entries + * are kept and merged, and nothing about what a task or a goal is. + */ +export const collections = [ + "goals", + "cycles", + "tasks", + "comments", + "lanes", + "fields", + "views", +] as const; +export type Collection = (typeof collections)[number]; +export type Json = + string | number | boolean | null | Json[] | { [key: string]: Json }; + +export interface Entry { + /** Plain values. Each is replaced whole, so the last change to one wins. */ + fields: Record; + /** Long text. A change is written as the difference, so edits in different places both stay. */ + texts: Record; + /** Sets, kept as one key per member (`label:urgent`), so two additions both stay. */ + sets: Record>; +} +/** Every entry of every collection that has not been deleted, by id. */ +export type Board = Record>; + +/** The number MemCode writes into a document it lays out, and the highest it will write to. */ +export const LAYOUT = 1; +/** What marks a change this computer made, as opposed to one that came from the log. */ +export const LOCAL = "local"; + +const META = "meta", + LAYOUT_KEY = "layout", + DELETED = "deleted", + MEMBER_OF = ":"; + +export const emptyBoard = (): Board => + Object.fromEntries(collections.map((name) => [name, {}])) as Board; + +const same = (left: unknown, right: unknown) => + left === right || JSON.stringify(left) === JSON.stringify(right); + +/** The layout the document was written in, or nothing for a document nobody has laid out. */ +export function layoutOf(doc: Y.Doc): number | undefined { + const layout = doc.getMap(META).get(LAYOUT_KEY); + return typeof layout === "number" ? layout : undefined; +} + +function readEntry(kept: Y.Map): Entry & { deleted: boolean } { + const entry: Entry = { fields: {}, texts: {}, sets: {} }; + let deleted = false; + kept.forEach((value, key) => { + if (key === DELETED) deleted = value === true; + else if (value instanceof Y.Text) entry.texts[key] = value.toString(); + else if (value instanceof Y.AbstractType) return; + else if (key.includes(MEMBER_OF)) { + const at = key.indexOf(MEMBER_OF); + (entry.sets[key.slice(0, at)] ??= {})[key.slice(at + 1)] = value as Json; + } else entry.fields[key] = value as Json; + }); + return { ...entry, deleted }; +} + +/** What the document holds now. Deleted entries are left out. */ +export function readBoard(doc: Y.Doc): Board { + const board = emptyBoard(); + for (const collection of collections) + doc.getMap(collection).forEach((kept, id) => { + if (!(kept instanceof Y.Map)) return; + const { deleted, ...entry } = readEntry(kept); + if (!deleted) board[collection][id] = entry; + }); + return board; +} + +/** Where two wordings differ: what to take out of the old one and what to put in its place. */ +export function textChange(from: string, to: string) { + let start = 0; + const shortest = Math.min(from.length, to.length); + while (start < shortest && from[start] === to[start]) start++; + let end = 0; + while ( + end < shortest - start && + from[from.length - 1 - end] === to[to.length - 1 - end] + ) + end++; + // Never cut between the two halves of one character. + const isFirstHalf = (text: string, at: number) => + at >= 0 && text.charCodeAt(at) >= 0xd800 && text.charCodeAt(at) <= 0xdbff; + if (isFirstHalf(from, start - 1)) start--; + if (end > 0 && isFirstHalf(from, from.length - end - 1)) end--; + return { + at: start, + remove: from.length - start - end, + insert: to.slice(start, to.length - end), + }; +} + +function writeText(kept: Y.Map, name: string, wording: string) { + const text = kept.get(name); + if (!(text instanceof Y.Text)) + return void kept.set(name, new Y.Text(wording)); + const change = textChange(text.toString(), wording); + if (change.remove) text.delete(change.at, change.remove); + if (change.insert) text.insert(change.at, change.insert); +} + +/** Writes the values that differ between two records, and takes out the ones that are gone. */ +function writeValues( + kept: Y.Map, + was: Record, + now: Record, + keyOf: (name: string) => string, +) { + for (const name of new Set([...Object.keys(was), ...Object.keys(now)])) { + if (same(was[name], now[name])) continue; + if (name in now) kept.set(keyOf(name), now[name]); + else kept.delete(keyOf(name)); + } +} + +function writeEntry( + held: Y.Map, + id: string, + before: Entry | undefined, + after: Entry, +) { + // An entry is made once. Putting a second map under an id that is already there + // would replace the first one whole, with every edit anyone made to it. + let kept = held.get(id); + if (!(kept instanceof Y.Map)) { + kept = new Y.Map(); + held.set(id, kept); + } + const map = kept as Y.Map; + const known = before ?? readEntry(map); + if (map.get(DELETED) === true) map.delete(DELETED); + writeValues(map, known.fields, after.fields, (name) => name); + for (const set of new Set([ + ...Object.keys(known.sets), + ...Object.keys(after.sets), + ])) + writeValues( + map, + known.sets[set] ?? {}, + after.sets[set] ?? {}, + (member) => set + MEMBER_OF + member, + ); + for (const [name, wording] of Object.entries(after.texts)) + if (known.texts[name] !== wording) writeText(map, name, wording); +} + +/** + * Writes what changed on this computer into the document, as one change. + * `before` is the board as this computer last saw it and `after` as it is now: + * only what differs between the two is written, so a change that arrived from + * someone else in the meantime is not undone. + */ +export function writeChanges(doc: Y.Doc, before: Board, after: Board): void { + doc.transact(() => { + const meta = doc.getMap(META); + if (meta.get(LAYOUT_KEY) === undefined) meta.set(LAYOUT_KEY, LAYOUT); + for (const collection of collections) { + const held = doc.getMap(collection); + const was = before[collection], + now = after[collection]; + for (const id of Object.keys(was)) + if (!(id in now)) { + const gone = held.get(id); + // Marked, not removed: an edit made elsewhere at the same moment is kept. + if (gone instanceof Y.Map) gone.set(DELETED, true); + } + for (const [id, entry] of Object.entries(now)) + if (!same(was[id], entry)) writeEntry(held, id, was[id], entry); + } + }, LOCAL); +} diff --git a/tests/sharing-board-document.test.ts b/tests/sharing-board-document.test.ts new file mode 100644 index 0000000..033afbe --- /dev/null +++ b/tests/sharing-board-document.test.ts @@ -0,0 +1,384 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as Y from "yjs"; +import { + emptyBoard, + LAYOUT, + layoutOf, + LOCAL, + readBoard, + textChange, + writeChanges, + type Board, + type Entry, +} from "../runtime/sharing/board/document"; + +const entry = (changes: Partial = {}): Entry => ({ + fields: {}, + texts: {}, + sets: {}, + ...changes, +}); +const task = (title: string, changes: Partial = {}): Entry => + entry({ + fields: { identifier: "MC-001", title, stage: "planned", lane: "planned" }, + texts: { description: "" }, + ...changes, + }); +const board = (changes: Partial = {}): Board => ({ + ...emptyBoard(), + ...changes, +}); + +/** A computer: its own document, the board it last saw, and the updates it has made. */ +function computer() { + const doc = new Y.Doc(); + const made: Uint8Array[] = []; + doc.on("update", (update: Uint8Array, origin: unknown) => { + if (origin === LOCAL) made.push(update); + }); + const self = { + doc, + made, + seen: emptyBoard(), + /** Changes the board on this computer, as an edit in the app does. */ + change(edit: (board: Board) => void) { + const next = structuredClone(self.seen); + edit(next); + writeChanges(doc, self.seen, next); + self.seen = next; + }, + /** Takes what another computer made, and sees the board anew. */ + receive(from: { made: Uint8Array[] }) { + for (const update of from.made) Y.applyUpdate(doc, update); + self.seen = readBoard(doc); + }, + }; + return self; +} +function meet(a: ReturnType, b: ReturnType) { + a.receive(b); + b.receive(a); + assert.deepEqual(readBoard(a.doc), readBoard(b.doc)); + return readBoard(a.doc); +} + +test("a board written into a document is read back as it was", () => { + const whole = board({ + goals: { + "goal-1": entry({ + fields: { + identifier: "EP-01", + title: "Reports", + order: 0, + closed: false, + }, + texts: { description: "Customers can export reports." }, + }), + }, + tasks: { + "task-1": task("Export as CSV", { + texts: { description: "Line one.\nLine two ✈" }, + sets: { + label: { urgent: true, "needs design": true }, + depends: { "task-2": true }, + field: { "field-1": "blue", "field-2": 3, "field-3": null }, + step: { "step-1": { text: "Read the code", done: true, order: 0 } }, + }, + }), + "task-2": task("Export as PDF"), + }, + comments: { + "comment-1": entry({ + fields: { task: "task-1", parent: null, text: "Looks right." }, + }), + }, + lanes: { + planned: entry({ + fields: { name: "Planned", stage: "planned", order: 1 }, + }), + }, + views: { + "view-1": entry({ + fields: { name: "Mine", filters: { priority: "all", archived: false } }, + }), + }, + }); + const one = computer(); + one.change((next) => Object.assign(next, whole)); + assert.deepEqual(readBoard(one.doc), whole); + const other = computer(); + other.receive(one); + assert.deepEqual(readBoard(other.doc), whole); + assert.equal(layoutOf(one.doc), LAYOUT); + assert.equal(layoutOf(new Y.Doc()), undefined); +}); + +test("nothing is written when nothing changed, and one edit is one small update", () => { + const one = computer(); + one.change((next) => { + for (let number = 0; number < 50; number++) + next.tasks[`task-${number}`] = task(`Task ${number}`, { + texts: { description: "x".repeat(500) }, + }); + }); + assert.equal(one.made.length, 1); + one.change(() => {}); + assert.equal(one.made.length, 1); + one.change((next) => (next.tasks["task-7"].fields.stage = "done")); + assert.equal(one.made.length, 2); + assert.ok(one.made[1].length < 100, `${one.made[1].length} bytes`); +}); + +test("two computers that add different tasks, or edit different fields of one, both keep their change", () => { + const mac = computer(), + windows = computer(); + mac.change((next) => (next.tasks.shared = task("Shared"))); + windows.receive(mac); + mac.made.length = 0; + mac.change((next) => { + next.tasks.fromMac = task("From the Mac"); + next.tasks.shared.fields.priority = "high"; + }); + windows.change((next) => { + next.tasks.fromWindows = task("From Windows"); + next.tasks.shared.fields.estimate = 5; + }); + const both = meet(mac, windows); + assert.deepEqual(Object.keys(both.tasks).sort(), [ + "fromMac", + "fromWindows", + "shared", + ]); + assert.equal(both.tasks.shared.fields.priority, "high"); + assert.equal(both.tasks.shared.fields.estimate, 5); +}); + +test("two computers that set the same field end with one of the two values, the same on both", () => { + const mac = computer(), + windows = computer(); + mac.change((next) => (next.tasks.shared = task("Shared"))); + windows.receive(mac); + mac.made.length = 0; + mac.change((next) => (next.tasks.shared.fields.title = "The Mac's title")); + windows.change((next) => (next.tasks.shared.fields.title = "The PC's title")); + const title = meet(mac, windows).tasks.shared.fields.title; + assert.ok(["The Mac's title", "The PC's title"].includes(String(title))); +}); + +test("a set keeps a member added on each computer, and loses the one a computer took out", () => { + const mac = computer(), + windows = computer(); + mac.change( + (next) => + (next.tasks.shared = task("Shared", { sets: { label: { old: true } } })), + ); + windows.receive(mac); + mac.made.length = 0; + mac.change((next) => { + next.tasks.shared.sets.label.urgent = true; + delete next.tasks.shared.sets.label.old; + }); + windows.change((next) => (next.tasks.shared.sets.label.design = true)); + assert.deepEqual(meet(mac, windows).tasks.shared.sets.label, { + urgent: true, + design: true, + }); +}); + +test("a step ticked on one computer and another reworded on the second both stay", () => { + const mac = computer(), + windows = computer(); + const step = (text: string, order: number, done = false) => ({ + text, + done, + order, + }); + mac.change( + (next) => + (next.tasks.shared = task("Shared", { + sets: { step: { a: step("Read the code", 0), b: step("Write it", 1) } }, + })), + ); + windows.receive(mac); + mac.made.length = 0; + mac.change( + (next) => (next.tasks.shared.sets.step.a = step("Read the code", 0, true)), + ); + windows.change( + (next) => (next.tasks.shared.sets.step.b = step("Write the fix", 1)), + ); + assert.deepEqual(meet(mac, windows).tasks.shared.sets.step, { + a: step("Read the code", 0, true), + b: step("Write the fix", 1), + }); +}); + +test("edits to a description in different places are both kept", () => { + const mac = computer(), + windows = computer(); + const wording = "First paragraph.\n\nSecond paragraph.\n\nThird paragraph."; + mac.change( + (next) => + (next.tasks.shared = task("Shared", { texts: { description: wording } })), + ); + windows.receive(mac); + mac.made.length = 0; + mac.change( + (next) => + (next.tasks.shared.texts.description = wording.replace( + "First", + "The very first", + )), + ); + windows.change( + (next) => + (next.tasks.shared.texts.description = wording.replace( + "Third paragraph.", + "Third, and last.", + )), + ); + assert.equal( + meet(mac, windows).tasks.shared.texts.description, + "The very first paragraph.\n\nSecond paragraph.\n\nThird, and last.", + ); +}); + +test("a move writes stage and lane together, so two moves at once never leave a mixed pair", () => { + for (let round = 0; round < 60; round++) { + const mac = computer(), + windows = computer(); + mac.change((next) => (next.tasks.shared = task("Shared"))); + windows.receive(mac); + mac.made.length = 0; + mac.change((next) => + Object.assign(next.tasks.shared.fields, { + stage: "review", + lane: "code-review", + }), + ); + windows.change((next) => + Object.assign(next.tasks.shared.fields, { stage: "done", lane: "done" }), + ); + const { stage, lane } = meet(mac, windows).tasks.shared.fields; + assert.ok( + ["review/code-review", "done/done"].includes(`${stage}/${lane}`), + `${stage}/${lane}`, + ); + } +}); + +test("deleting marks the entry: it is gone from the board, and an edit made elsewhere at that moment is not lost", () => { + const mac = computer(), + windows = computer(); + mac.change((next) => { + next.tasks.kept = task("Kept"); + next.tasks.gone = task("Gone"); + }); + windows.receive(mac); + mac.made.length = 0; + mac.change((next) => void delete next.tasks.gone); + windows.change( + (next) => (next.tasks.gone.fields.title = "Edited while it was deleted"), + ); + assert.deepEqual(Object.keys(meet(mac, windows).tasks), ["kept"]); + // Putting it back finds the entry that was marked, with the edit still in it. + mac.made.length = 0; + windows.made.length = 0; + windows.change( + (next) => (next.tasks.gone = task("Edited while it was deleted")), + ); + const back = meet(mac, windows).tasks.gone; + assert.equal(back.fields.title, "Edited while it was deleted"); + assert.equal(mac.doc.getMap("tasks").size, 2); +}); + +test("an entry is made once: a computer that brings an id the document already holds writes into that entry", () => { + const mac = computer(), + windows = computer(); + mac.change((next) => (next.tasks.same = task("One board, two computers"))); + // Windows has the same task from before and has not seen the document's copy as its own. + windows.receive(mac); + windows.seen = emptyBoard(); + mac.made.length = 0; + windows.change( + (next) => (next.tasks.same = task("One board, two computers")), + ); + assert.equal( + windows.made.length, + 0, + "nothing differs, so nothing is written", + ); + // An edit on the Mac to the entry it made is still there afterwards. + mac.change((next) => (next.tasks.same.fields.priority = "high")); + windows.seen = emptyBoard(); + windows.change( + (next) => + (next.tasks.same = task("One board, two computers", { + sets: { label: { pc: true } }, + })), + ); + const merged = meet(mac, windows).tasks.same; + assert.equal(merged.fields.priority, "high"); + assert.deepEqual(merged.sets.label, { pc: true }); +}); + +test("the difference between two wordings is the smallest cut that turns one into the other", () => { + const apply = (from: string, to: string) => { + const { at, remove, insert } = textChange(from, to); + return from.slice(0, at) + insert + from.slice(at + remove); + }; + const pairs: Array<[string, string]> = [ + ["", "new"], + ["old", ""], + ["same", "same"], + ["one two three", "one 2 three"], + ["aaa", "aaaa"], + ["aaaa", "aaa"], + ["abcabc", "abc"], + ["begin middle end", "begin end"], + ["a✈b", "a🚀b"], + ["👍 fine", "👎 fine"], + ["fine 👍", "fine 👎"], + ["👨‍👩‍👧 family", "👨‍👩‍👦 family"], + ]; + for (const [from, to] of pairs) { + assert.equal(apply(from, to), to, `${from} → ${to}`); + const { at, remove, insert } = textChange(from, to); + const lone = + /[\ud800-\udbff](?![\udc00-\udfff])|(? { + const doc = new Y.Doc(); + doc.transact(() => { + const tasks = doc.getMap("tasks"); + tasks.set("not-an-entry", "just text"); + tasks.set("a-list", new Y.Array()); + const odd = new Y.Map(); + tasks.set("odd", odd); + odd.set("title", "Still a task"); + odd.set("nested", new Y.Array()); + odd.set("deleted", "yes"); + odd.set(":", 1); + odd.set("label:", true); + doc.getArray("something-newer").push([1]); + doc.getMap("meta").set("layout", "two"); + }); + const read = readBoard(doc); + assert.deepEqual(Object.keys(read.tasks), ["odd"]); + assert.equal(read.tasks.odd.fields.title, "Still a task"); + assert.equal(layoutOf(doc), undefined); +}); From 0c9caac1c9e8631b80f381fa8200e5b1350b6097 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:26:21 +0100 Subject: [PATCH 11/66] feat: map a project to its shared board and back [skip ci] boardOf takes the plan out of the workspace: goals, cycles, tasks with their labels, scope, runbook and custom fields, comments, lanes, fields and saved views. Workers, conversations, changes, reviews and local paths are not on the board, and a test checks that none of them is. applyBoard makes the project here follow a board that changed. It touches only what differs and only the shared part of a task. Every value read from a board is checked; one that does not pass is left out and what was here stays. A task with a worker running here is not taken away under it, and a comment that was taken back keeps its place. Lanes that come with a project are written without the project's id, which differs on every computer. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/board/board.ts | 672 +++++++++++++++++++++++++++++++++ tests/sharing-board.test.ts | 492 ++++++++++++++++++++++++ 2 files changed, 1164 insertions(+) create mode 100644 runtime/sharing/board/board.ts create mode 100644 tests/sharing-board.test.ts diff --git a/runtime/sharing/board/board.ts b/runtime/sharing/board/board.ts new file mode 100644 index 0000000..181a6b1 --- /dev/null +++ b/runtime/sharing/board/board.ts @@ -0,0 +1,672 @@ +import type { AppState, Epic, WorkItem } from "../../../src/shared"; +import type { + Cycle, + CustomField, + SavedView, + WorkflowState, +} from "../../../src/planning/types"; +import type { StoryComment } from "../../../src/story-comments"; +import { isActive } from "../../../src/domain"; +import { + emptyBoard, + type Board, + type Collection, + type Entry, + type Json, +} from "./document"; + +/** + * What of a MemCode project is on its shared board, and what a board from the + * document means for the project on this computer. Everything else in the + * workspace stays here: workers, conversations, changes, reviews, paths. + */ + +/** When the log says an entry was made and last changed, and by which account. */ +export interface EntryStamp { + createdAt?: string; + createdBy?: string; + changedAt?: string; +} +export interface ApplyOptions { + /** The moment to date a change with when the log has not dated it. */ + at: string; + stampOf?: (collection: Collection, id: string) => EntryStamp | undefined; + /** The name of a person on the project, by account. */ + nameOf?: (accountId: string) => string | undefined; +} + +const uuidShape = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const SOMEONE = "Someone on this project"; + +/** + * A lane that comes with a project carries the project's id in front, and that id + * differs on every computer. On the board it is written without it. A lane a + * person added has an id of its own and is written as it is. + */ +function laneOnBoard(projectId: string, id: string): string | undefined { + if (id.startsWith(projectId + ":")) return id.slice(projectId.length + 1); + return uuidShape.test(id) ? id : undefined; +} +const laneHere = (projectId: string, id: string) => + uuidShape.test(id) ? id : `${projectId}:${id}`; + +const entry = ( + fields: Record, + texts: Record = {}, + sets: Record> = {}, +): Entry => ({ + fields: Object.fromEntries( + Object.entries(fields).filter(([, value]) => value !== undefined), + ) as Record, + texts, + sets, +}); +const members = (ids: string[] | undefined) => + Object.fromEntries((ids ?? []).map((id) => [id, true])); + +/** A path a second computer can use: inside the project, with forward slashes. */ +const isPortablePath = (path: string) => + path.length > 0 && + path.length <= 1000 && + !path.includes("\\") && + !path.startsWith("/") && + !/^[A-Za-z]:/.test(path) && + !/[\x00-\x1f]/.test(path) && + path.split("/").every((part) => part && part !== "." && part !== ".."); + +function taskOnBoard(task: WorkItem): Entry { + const lane = task.statusId && laneOnBoard(task.projectId, task.statusId); + const scope = (task.scope ?? []) + .map((path) => path.replaceAll("\\", "/").replace(/\/+$/, "")) + .filter(isPortablePath); + return entry( + { + identifier: task.identifier, + title: task.title, + stage: task.stage, + lane: lane || undefined, + priority: task.priority, + kind: task.kind ?? "feature", + goal: task.epicId ?? null, + cycle: task.cycleId ?? null, + parent: task.parentId ?? null, + estimate: task.estimate ?? null, + startDate: task.startDate ?? null, + dueDate: task.dueDate ?? null, + duplicateOf: task.duplicateOf ?? null, + category: task.category, + archived: !!task.archivedAt, + }, + { description: task.description }, + { + label: members(task.labels), + scope: members(scope), + depends: members(task.dependsOn), + related: members(task.relatedIds), + field: { ...task.customFields }, + step: Object.fromEntries( + task.checklist.map((step, order) => [ + step.id, + { text: step.text, done: step.done, order }, + ]), + ), + }, + ); +} + +const goalOnBoard = (goal: Epic): Entry => + entry( + { + identifier: goal.identifier, + title: goal.title, + phase: goal.phase, + color: goal.color, + order: goal.order, + branch: goal.branch, + baseRevision: goal.baseRevision, + baseBranch: goal.baseBranch, + closed: !!goal.closedAt, + }, + { description: goal.description }, + ); + +const cycleOnBoard = (cycle: Cycle): Entry => + entry({ + name: cycle.name, + goal: cycle.goal, + startDate: cycle.startDate, + endDate: cycle.endDate, + timeZone: cycle.timeZone, + state: cycle.state, + capacity: cycle.capacity, + calendar: cycle.calendar, + }); + +const commentOnBoard = (comment: StoryComment): Entry => + entry({ + task: comment.taskId, + parent: comment.parentId ?? null, + text: comment.text, + reference: comment.reference as Json | undefined, + }); + +/** The shared board of one project, as the workspace on this computer has it. */ +export function boardOf(state: AppState, projectId: string): Board { + const board = emptyBoard(); + const tasks = state.tasks.filter( + (task) => task.projectId === projectId && !task.example, + ); + for (const task of tasks) board.tasks[task.id] = taskOnBoard(task); + for (const goal of state.epics) + if (goal.projectId === projectId) board.goals[goal.id] = goalOnBoard(goal); + for (const cycle of state.cycles) + if (cycle.projectId === projectId) + board.cycles[cycle.id] = cycleOnBoard(cycle); + for (const comment of state.storyComments ?? []) + if (comment.taskId in board.tasks && !comment.deletedAt) + board.comments[comment.id] = commentOnBoard(comment); + for (const lane of state.workflowStates) { + const id = lane.projectId === projectId && laneOnBoard(projectId, lane.id); + if (id) + board.lanes[id] = entry({ + name: lane.name, + stage: lane.stage, + color: lane.color, + order: lane.order, + wipLimit: lane.wipLimit ?? null, + }); + } + for (const field of state.customFields) + if (field.projectId === projectId) + board.fields[field.id] = entry({ + name: field.name, + type: field.type, + options: field.options, + }); + for (const view of state.savedViews) + if (view.projectId === projectId) + board.views[view.id] = entry({ + name: view.name, + mode: view.mode, + groupBy: view.groupBy, + sortBy: view.sortBy, + filters: view.filters as unknown as Json, + }); + return board; +} + +// What is read from a board was written by someone else's computer, so every value +// is checked. One that does not pass is left out and the value already here stays. +type Read = (value: Json | undefined) => T | undefined; +const line = + (longest: number): Read => + (value) => + typeof value === "string" && + value.length > 0 && + value.length <= longest && + !/[\x00-\x1f\x7f]/.test(value) + ? value + : undefined; +const wording = + (longest: number) => + (value: unknown): string | undefined => + typeof value === "string" && value.length <= longest ? value : undefined; +const oneOf = + (...choices: T[]): Read => + (value) => + choices.includes(value as T) ? (value as T) : undefined; +const idOrNone: Read = (value) => + value === null + ? null + : typeof value === "string" && value.length > 0 && value.length <= 250 + ? value + : undefined; +const dayOrNone: Read = (value) => + value === null + ? null + : typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) + ? value + : undefined; +const numberWithin = + (least: number, most: number): Read => + (value) => + typeof value === "number" && + Number.isFinite(value) && + value >= least && + value <= most + ? value + : undefined; +const orNone = + (read: Read): Read => + (value) => + value === null ? null : read(value); +const flag: Read = (value) => + typeof value === "boolean" ? value : undefined; +const or = (read: T | undefined, kept: T): T => + read === undefined ? kept : read; +const memberIds = (set: Record | undefined, most: number) => + Object.keys(set ?? {}) + .filter((id) => id.length > 0 && id.length <= 1000) + .slice(0, most); + +const stageRead = oneOf("planned", "working", "review", "done"); + +function stepsFrom(set: Record | undefined) { + const steps: Array<{ + id: string; + text: string; + done: boolean; + order: number; + }> = []; + for (const [id, value] of Object.entries(set ?? {})) { + const step = value as { text?: Json; done?: Json; order?: Json } | null; + const text = wording(20000)(step?.text); + if (!step || typeof step !== "object" || text === undefined) continue; + steps.push({ + id, + text, + done: step.done === true, + order: typeof step.order === "number" ? step.order : steps.length, + }); + } + return steps + .sort((a, b) => a.order - b.order || a.id.localeCompare(b.id)) + .slice(0, 500) + .map(({ id, text, done }) => ({ id, text, done })); +} + +function customValues(set: Record | undefined) { + const values: Record = {}; + for (const [id, value] of Object.entries(set ?? {})) + if ( + value === null || + (typeof value === "number" && Number.isFinite(value)) || + wording(20000)(value) !== undefined + ) + values[id] = value as string | number | null; + return Object.keys(values).length ? values : undefined; +} + +/** The shared part of a task as the board has it. Nothing when the board has no usable task there. */ +function taskFromBoard( + projectId: string, + shared: Entry, + kept: WorkItem | undefined, +): Partial | undefined { + const { fields, texts, sets } = shared; + const identifier = or(line(240)(fields.identifier), kept?.identifier), + title = or(line(240)(fields.title), kept?.title), + stage = or(stageRead(fields.stage), kept?.stage); + if (!identifier || !title || !stage) return undefined; + const lane = line(250)(fields.lane); + return { + identifier, + title, + stage, + statusId: lane ? laneHere(projectId, lane) : undefined, + description: or(wording(20000)(texts.description), kept?.description ?? ""), + priority: or( + oneOf("high", "medium", "low")(fields.priority), + kept?.priority ?? "medium", + ), + kind: or( + oneOf("feature", "fix", "refactor", "research", "test")(fields.kind), + kept?.kind ?? "feature", + ), + epicId: or(idOrNone(fields.goal), kept?.epicId ?? null), + cycleId: or(idOrNone(fields.cycle), kept?.cycleId ?? null), + parentId: or(idOrNone(fields.parent), kept?.parentId ?? null), + estimate: or( + orNone(numberWithin(0, 10000))(fields.estimate), + kept?.estimate ?? null, + ), + startDate: or(dayOrNone(fields.startDate), kept?.startDate ?? null), + dueDate: or(dayOrNone(fields.dueDate), kept?.dueDate ?? null), + duplicateOf: or(idOrNone(fields.duplicateOf), kept?.duplicateOf ?? null), + category: or(line(200)(fields.category), kept?.category ?? "Work"), + labels: memberIds(sets.label, 30).filter((label) => label.length <= 100), + scope: memberIds(sets.scope, 200).filter(isPortablePath), + dependsOn: memberIds(sets.depends, 200), + relatedIds: memberIds(sets.related, 200), + customFields: customValues(sets.field), + checklist: stepsFrom(sets.step), + }; +} + +function applyTasks( + state: AppState, + projectId: string, + before: Board, + after: Board, + options: ApplyOptions, +) { + const gone = new Set( + Object.keys(before.tasks).filter((id) => !(id in after.tasks)), + ); + // A task with a worker running on this computer is not taken away under it. + state.tasks = state.tasks.filter( + (task) => + task.projectId !== projectId || !gone.has(task.id) || isActive(task), + ); + for (const [id, shared] of Object.entries(after.tasks)) { + if (JSON.stringify(before.tasks[id]) === JSON.stringify(shared)) continue; + const kept = state.tasks.find((task) => task.id === id); + if (kept && kept.projectId !== projectId) continue; + const read = taskFromBoard(projectId, shared, kept); + if (!read) continue; + const stamp = options.stampOf?.("tasks", id); + const archived = or(flag(shared.fields.archived), !!kept?.archivedAt); + const dated = { + updatedAt: stamp?.changedAt ?? options.at, + archivedAt: archived + ? (kept?.archivedAt ?? stamp?.changedAt ?? options.at) + : null, + }; + if (kept) { + Object.assign(kept, read, dated); + continue; + } + const createdAt = stamp?.createdAt ?? options.at; + state.tasks.push({ + id, + projectId, + harness: state.settings.defaultHarness, + assignment: "auto", + // The brief a worker here starts from, as the first message of any task is. + messages: [ + { + id: `brief:${id}`, + role: "user", + text: read.description || read.title!, + at: createdAt, + }, + ], + run: { state: "idle" }, + createdAt, + ...(read as Required< + Pick + > & + Pick), + ...dated, + }); + } +} + +function applyGoals( + state: AppState, + projectId: string, + before: Board, + after: Board, + at: string, +) { + state.epics = state.epics.filter( + (goal) => + goal.projectId !== projectId || + !(goal.id in before.goals) || + goal.id in after.goals, + ); + for (const [id, shared] of Object.entries(after.goals)) { + if (JSON.stringify(before.goals[id]) === JSON.stringify(shared)) continue; + const kept = state.epics.find((goal) => goal.id === id); + if (kept && kept.projectId !== projectId) continue; + const { fields, texts } = shared; + const identifier = or(line(240)(fields.identifier), kept?.identifier), + title = or(line(240)(fields.title), kept?.title); + if (!identifier || !title) continue; + const closed = or(flag(fields.closed), !!kept?.closedAt); + const read: Omit = { + identifier, + title, + description: or( + wording(20000)(texts.description), + kept?.description ?? "", + ), + phase: or( + oneOf("now", "next", "later")(fields.phase), + kept?.phase ?? "next", + ), + color: or( + oneOf("mint", "cyan", "lavender", "amber")(fields.color), + kept?.color ?? "mint", + ), + order: or(numberWithin(-1e9, 1e9)(fields.order), kept?.order ?? 0), + branch: line(240)(fields.branch), + baseRevision: line(64)(fields.baseRevision), + baseBranch: line(240)(fields.baseBranch), + closedAt: closed ? (kept?.closedAt ?? at) : undefined, + }; + if (kept) Object.assign(kept, read); + else state.epics.push({ id, projectId, ...read }); + } +} + +function applyCycles( + state: AppState, + projectId: string, + before: Board, + after: Board, + options: ApplyOptions, +) { + state.cycles = state.cycles.filter( + (cycle) => + cycle.projectId !== projectId || + !(cycle.id in before.cycles) || + cycle.id in after.cycles, + ); + for (const [id, shared] of Object.entries(after.cycles)) { + if (JSON.stringify(before.cycles[id]) === JSON.stringify(shared)) continue; + const kept = state.cycles.find((cycle) => cycle.id === id); + if (kept && kept.projectId !== projectId) continue; + const { fields } = shared; + const name = or(line(240)(fields.name), kept?.name), + startDate = or(dayOrNone(fields.startDate), kept?.startDate), + endDate = or(dayOrNone(fields.endDate), kept?.endDate); + if (!name || !startDate || !endDate) continue; + const stamp = options.stampOf?.("cycles", id); + const changedAt = stamp?.changedAt ?? options.at; + const state_ = or( + oneOf("planned", "active", "completed")(fields.state), + kept?.state ?? "planned", + ); + const read = { + name, + goal: or(wording(20000)(fields.goal), kept?.goal ?? ""), + startDate, + endDate, + timeZone: or(line(100)(fields.timeZone), kept?.timeZone ?? "UTC"), + state: state_, + capacity: or( + orNone(numberWithin(0, 100000))(fields.capacity), + kept?.capacity ?? null, + ), + calendar: or( + oneOf("weekdays", "calendar")(fields.calendar), + kept?.calendar ?? "weekdays", + ), + // A cycle started or finished when the log says its state changed. + startedAt: + state_ === "planned" ? kept?.startedAt : (kept?.startedAt ?? changedAt), + completedAt: + state_ === "completed" ? (kept?.completedAt ?? changedAt) : undefined, + }; + if (kept) Object.assign(kept, read); + else + state.cycles.push({ + id, + projectId, + createdAt: stamp?.createdAt ?? options.at, + snapshots: [], + ...read, + }); + } +} + +function applyComments( + state: AppState, + before: Board, + after: Board, + options: ApplyOptions, +) { + const comments = (state.storyComments ??= []); + for (const id of Object.keys(before.comments)) { + const kept = comments.find((comment) => comment.id === id); + // A comment that was taken back keeps its place, so replies still have something to answer. + if (kept && !(id in after.comments) && !kept.deletedAt) + kept.deletedAt = + options.stampOf?.("comments", id)?.changedAt ?? options.at; + } + for (const [id, shared] of Object.entries(after.comments)) { + if (JSON.stringify(before.comments[id]) === JSON.stringify(shared)) + continue; + const kept = comments.find((comment) => comment.id === id); + const { fields } = shared; + const taskId = or(line(250)(fields.task), kept?.taskId), + text = or(wording(20000)(fields.text), kept?.text); + if (!taskId || text === undefined) continue; + const stamp = options.stampOf?.("comments", id); + const parentId = or(idOrNone(fields.parent), kept?.parentId ?? null); + const read = { + taskId, + text, + parentId: parentId ?? undefined, + reference: + fields.reference && typeof fields.reference === "object" + ? (fields.reference as unknown as StoryComment["reference"]) + : undefined, + updatedAt: stamp?.changedAt ?? options.at, + deletedAt: undefined, + }; + if (kept) { + Object.assign(kept, read); + continue; + } + const account = stamp?.createdBy; + comments.push({ + id, + ...read, + // The log says who sent a comment. What the comment says about itself is not asked. + author: { + id: account ?? "unknown", + name: (account && options.nameOf?.(account)) || SOMEONE, + source: "memtrace", + }, + createdAt: stamp?.createdAt ?? options.at, + }); + } +} + +/** Lanes, custom fields and saved views are small lists that a project holds whole. */ +function applyProjectLists( + state: AppState, + projectId: string, + before: Board, + after: Board, +) { + const changed = (collection: "lanes" | "fields" | "views") => + JSON.stringify(before[collection]) !== JSON.stringify(after[collection]); + if (changed("lanes") && Object.keys(after.lanes).length) { + const lanes: WorkflowState[] = []; + for (const [id, { fields }] of Object.entries(after.lanes)) { + const name = line(200)(fields.name), + stage = stageRead(fields.stage); + if (!name || !stage) continue; + lanes.push({ + id: laneHere(projectId, id), + projectId, + name, + stage, + color: or(line(100)(fields.color), "#98a59d"), + order: or(numberWithin(-1e9, 1e9)(fields.order), lanes.length), + wipLimit: or(orNone(numberWithin(0, 100000))(fields.wipLimit), null), + }); + } + // A lane that is not on the board and cannot be written there stays where it is. + const local = (lane: WorkflowState) => + lane.projectId !== projectId || !laneOnBoard(projectId, lane.id); + state.workflowStates = [...state.workflowStates.filter(local), ...lanes]; + } + if (changed("fields")) { + const fields: CustomField[] = []; + for (const [id, { fields: read }] of Object.entries(after.fields)) { + const name = line(200)(read.name), + type = oneOf("text", "number", "select")(read.type); + if (!name || !type) continue; + const options = Array.isArray(read.options) + ? read.options.filter( + (option): option is string => + typeof option === "string" && option.length <= 200, + ) + : []; + fields.push({ + id, + projectId, + name, + type, + options: options.slice(0, 200), + }); + } + state.customFields = [ + ...state.customFields.filter((field) => field.projectId !== projectId), + ...fields, + ]; + } + if (changed("views")) { + const views: SavedView[] = []; + for (const [id, { fields }] of Object.entries(after.views)) { + const name = line(200)(fields.name), + mode = oneOf("board", "list", "timeline", "calendar")(fields.mode), + groupBy = oneOf( + "status", + "epic", + "priority", + "harness", + "cycle", + "none", + )(fields.groupBy), + sortBy = oneOf( + "priority", + "updated", + "created", + "due", + "estimate", + )(fields.sortBy); + const filters = fields.filters; + if (!name || !mode || !groupBy || !sortBy) continue; + if (!filters || typeof filters !== "object" || Array.isArray(filters)) + continue; + views.push({ + id, + projectId, + name, + mode, + groupBy, + sortBy, + filters: filters as unknown as SavedView["filters"], + }); + } + state.savedViews = [ + ...state.savedViews.filter((view) => view.projectId !== projectId), + ...views, + ]; + } +} + +/** + * Makes the project on this computer follow a board that changed. Only what + * differs between `before` and `after` is touched, and only the shared part of + * a task: its worker, its conversation and its changes are left alone. + */ +export function applyBoard( + state: AppState, + projectId: string, + before: Board, + after: Board, + options: ApplyOptions, +): void { + applyProjectLists(state, projectId, before, after); + applyGoals(state, projectId, before, after, options.at); + applyCycles(state, projectId, before, after, options); + applyTasks(state, projectId, before, after, options); + applyComments(state, before, after, options); +} diff --git a/tests/sharing-board.test.ts b/tests/sharing-board.test.ts new file mode 100644 index 0000000..a6c7add --- /dev/null +++ b/tests/sharing-board.test.ts @@ -0,0 +1,492 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { initialState } from "../src/seed"; +import type { AppState, Epic, Project, WorkItem } from "../src/shared"; +import { applyBoard, boardOf } from "../runtime/sharing/board/board"; +import { emptyBoard, type Board } from "../runtime/sharing/board/document"; + +const at = "2026-11-21T12:00:00.000Z"; +const project = (id: string, name: string): Project => ({ + id, + name, + description: "", + path: `/work/${name}`, + branch: "main", + analysis: "idle", + createdAt: at, +}); +function workspace(projectId: string): AppState { + const state = initialState(); + state.projects.push(project(projectId, "website")); + state.activeProjectId = projectId; + state.storyComments = []; + return state; +} +const goal = (projectId: string, changes: Partial = {}): Epic => ({ + id: "goal-1", + projectId, + identifier: "EP-01", + title: "Customers can export reports", + description: "As CSV and as PDF.", + phase: "now", + color: "mint", + order: 0, + branch: "epic/ep-01-reports", + baseBranch: "dev", + ...changes, +}); +const task = ( + projectId: string, + changes: Partial = {}, +): WorkItem => ({ + id: "task-1", + identifier: "MC-001", + projectId, + title: "Export as CSV", + description: "Line one.\nLine two.", + stage: "working", + statusId: `${projectId}:working`, + priority: "high", + category: "Work", + kind: "feature", + harness: "claude", + assignment: "manual", + modelOverride: "the model this computer chose", + epicId: "goal-1", + cycleId: "cycle-1", + parentId: null, + estimate: 3, + startDate: "2026-11-20", + dueDate: null, + labels: ["urgent", "export"], + scope: ["src/export", "C:\\work\\website\\src\\secret.ts", "docs/"], + dependsOn: ["task-0"], + relatedIds: ["task-9"], + duplicateOf: null, + customFields: { "field-1": "blue", "field-2": 2 }, + checklist: [ + { id: "step-1", text: "Read the code", done: true }, + { id: "step-2", text: "Write it", done: false }, + ], + messages: [{ id: "m1", role: "tool", text: "PRIVATE TOOL OUTPUT", at }], + run: { + state: "idle", + workspace: "/private/checkout", + sessionId: "secret-session", + }, + diff: "PRIVATE DIFF", + createdAt: at, + updatedAt: at, + ...changes, +}); +/** A whole project on the Mac, as MemCode keeps it. */ +function mac(): AppState { + const state = workspace("mac-project"); + state.epics.push(goal("mac-project")); + state.cycles.push({ + id: "cycle-1", + projectId: "mac-project", + name: "Week 47", + goal: "Ship the export", + startDate: "2026-11-16", + endDate: "2026-11-22", + timeZone: "Europe/Copenhagen", + state: "active", + capacity: 20, + calendar: "weekdays", + createdAt: at, + startedAt: at, + snapshots: [], + }); + state.tasks.push(task("mac-project")); + state.storyComments!.push({ + id: "comment-1", + taskId: "task-1", + text: "Looks right to me.", + author: { id: "acct-alex", name: "Alex Holm", source: "memtrace" }, + createdAt: at, + updatedAt: at, + }); + state.workflowStates.push( + { + id: "mac-project:working", + projectId: "mac-project", + name: "In progress", + stage: "working", + color: "#18c8b5", + order: 2, + }, + { + id: "5d3a2f0e-5a52-4c1e-9d3e-2f1f5f3a9c11", + projectId: "mac-project", + name: "Blocked", + stage: "working", + color: "#cc8", + order: 3, + wipLimit: 2, + }, + ); + state.customFields.push({ + id: "field-1", + projectId: "mac-project", + name: "Colour", + type: "select", + options: ["blue", "green"], + }); + state.savedViews.push({ + id: "view-1", + projectId: "mac-project", + name: "Mine", + mode: "list", + groupBy: "epic", + sortBy: "due", + filters: { + query: "", + priority: "all", + epicId: "goal-1", + cycleId: "all", + label: "all", + kind: "all", + harness: "all", + archived: false, + }, + }); + return state; +} +/** The same board arriving on a computer whose project has nothing in it yet. */ +function arrivesOn(board: Board, projectId = "pc-project") { + const state = workspace(projectId); + applyBoard(state, projectId, emptyBoard(), board, { at }); + return state; +} + +test("the board holds a project's plan and nothing a worker said or did", () => { + const board = boardOf(mac(), "mac-project"); + const everything = JSON.stringify(board); + for (const kept of [ + "PRIVATE", + "secret", + "/private/checkout", + "the model this computer chose", + "claude", + "mac-project", + ]) + assert.ok(!everything.includes(kept), `${kept} is on the board`); + assert.deepEqual(board.tasks["task-1"], { + fields: { + identifier: "MC-001", + title: "Export as CSV", + stage: "working", + lane: "working", + priority: "high", + kind: "feature", + goal: "goal-1", + cycle: "cycle-1", + parent: null, + estimate: 3, + startDate: "2026-11-20", + dueDate: null, + duplicateOf: null, + category: "Work", + archived: false, + }, + texts: { description: "Line one.\nLine two." }, + sets: { + label: { urgent: true, export: true }, + scope: { "src/export": true, docs: true }, + depends: { "task-0": true }, + related: { "task-9": true }, + field: { "field-1": "blue", "field-2": 2 }, + step: { + "step-1": { text: "Read the code", done: true, order: 0 }, + "step-2": { text: "Write it", done: false, order: 1 }, + }, + }, + }); + assert.deepEqual(Object.keys(board.lanes), [ + "working", + "5d3a2f0e-5a52-4c1e-9d3e-2f1f5f3a9c11", + ]); + assert.deepEqual(Object.keys(boardOf(mac(), "example").tasks), []); +}); + +test("a board that arrives on a second computer becomes the same plan there, under that computer's project", () => { + const board = boardOf(mac(), "mac-project"); + const pc = arrivesOn(board); + assert.deepEqual(boardOf(pc, "pc-project"), board); + const [arrived] = pc.tasks.filter((item) => item.projectId === "pc-project"); + assert.equal(arrived.statusId, "pc-project:working"); + assert.equal(arrived.harness, pc.settings.defaultHarness); + assert.equal(arrived.assignment, "auto"); + assert.deepEqual(arrived.run, { state: "idle" }); + // A worker started here begins from the brief, as it does for a task made here. + assert.deepEqual( + arrived.messages.map((message) => [message.role, message.text]), + [["user", "Line one.\nLine two."]], + ); + assert.deepEqual(arrived.checklist, [ + { id: "step-1", text: "Read the code", done: true }, + { id: "step-2", text: "Write it", done: false }, + ]); + assert.equal(pc.epics[0].projectId, "pc-project"); + assert.equal(pc.cycles[0].state, "active"); + assert.deepEqual(pc.workflowStates.map((lane) => lane.id).sort(), [ + "5d3a2f0e-5a52-4c1e-9d3e-2f1f5f3a9c11", + "pc-project:working", + ]); + assert.equal(pc.savedViews[0].filters.epicId, "goal-1"); +}); + +test("a change on the board changes the shared part of a task here and leaves its worker alone", () => { + const state = mac(); + const before = boardOf(state, "mac-project"); + const after = structuredClone(before); + Object.assign(after.tasks["task-1"].fields, { + title: "Export as CSV and TSV", + stage: "review", + lane: "review", + estimate: null, + }); + after.tasks["task-1"].texts.description = "A new brief."; + after.tasks["task-1"].sets.step["step-2"] = { + text: "Write it", + done: true, + order: 1, + }; + applyBoard(state, "mac-project", before, after, { + at: "2026-11-22T08:00:00.000Z", + stampOf: () => ({ changedAt: "2026-11-22T07:59:00.000Z" }), + }); + const [changed] = state.tasks.filter((item) => item.id === "task-1"); + assert.equal(changed.title, "Export as CSV and TSV"); + assert.equal(changed.stage, "review"); + assert.equal(changed.statusId, "mac-project:review"); + assert.equal(changed.estimate, null); + assert.equal(changed.description, "A new brief."); + assert.equal(changed.checklist[1].done, true); + assert.equal(changed.updatedAt, "2026-11-22T07:59:00.000Z"); + assert.equal(changed.harness, "claude"); + assert.equal(changed.modelOverride, "the model this computer chose"); + assert.equal(changed.messages[0].text, "PRIVATE TOOL OUTPUT"); + assert.equal(changed.run.sessionId, "secret-session"); + assert.equal(changed.diff, "PRIVATE DIFF"); + assert.equal(changed.createdAt, at); +}); + +test("only what changed on the board is touched: an edit made here in the meantime stays", () => { + const state = mac(); + const before = boardOf(state, "mac-project"); + const after = structuredClone(before); + after.goals["goal-1"].fields.title = "A new name for the goal"; + state.tasks.find((item) => item.id === "task-1")!.title = + "Edited here, not sent yet"; + applyBoard(state, "mac-project", before, after, { at }); + assert.equal(state.epics[0].title, "A new name for the goal"); + assert.equal( + state.tasks.find((item) => item.id === "task-1")!.title, + "Edited here, not sent yet", + ); +}); + +test("a task deleted on the board goes, unless a worker is running on it here", () => { + for (const running of [false, true]) { + const state = mac(); + if (running) + state.tasks.find((item) => item.id === "task-1")!.run.state = "running"; + const before = boardOf(state, "mac-project"); + const after = structuredClone(before); + delete after.tasks["task-1"]; + delete after.goals["goal-1"]; + delete after.cycles["cycle-1"]; + applyBoard(state, "mac-project", before, after, { at }); + assert.equal( + state.tasks.some((item) => item.id === "task-1"), + running, + ); + assert.equal(state.epics.length, 0); + assert.equal(state.cycles.length, 0); + // The example project and its tasks are no part of this. + assert.ok(state.tasks.some((item) => item.example)); + } +}); + +test("a comment arrives under the name of whoever the log says sent it, and one taken back keeps its place", () => { + const board = boardOf(mac(), "mac-project"); + const pc = workspace("pc-project"); + applyBoard(pc, "pc-project", emptyBoard(), board, { + at, + stampOf: (collection) => + collection === "comments" + ? { + createdAt: "2026-11-20T10:00:00.000Z", + createdBy: "acct-dana", + changedAt: "2026-11-20T10:05:00.000Z", + } + : undefined, + nameOf: (account) => (account === "acct-dana" ? "Dana Ek" : undefined), + }); + assert.deepEqual(pc.storyComments, [ + { + id: "comment-1", + taskId: "task-1", + text: "Looks right to me.", + parentId: undefined, + reference: undefined, + updatedAt: "2026-11-20T10:05:00.000Z", + deletedAt: undefined, + author: { id: "acct-dana", name: "Dana Ek", source: "memtrace" }, + createdAt: "2026-11-20T10:00:00.000Z", + }, + ]); + const without = structuredClone(board); + delete without.comments["comment-1"]; + applyBoard(pc, "pc-project", board, without, { + at: "2026-11-22T09:00:00.000Z", + }); + assert.equal(pc.storyComments![0].deletedAt, "2026-11-22T09:00:00.000Z"); + assert.equal(boardOf(pc, "pc-project").comments["comment-1"], undefined); + // Someone the project does not name is still shown as someone. + const unnamed = workspace("pc-project"); + applyBoard(unnamed, "pc-project", emptyBoard(), board, { at }); + assert.equal( + unnamed.storyComments![0].author.name, + "Someone on this project", + ); +}); + +test("a value that cannot be what it claims is left out, and what was here stays", () => { + const state = mac(); + const before = boardOf(state, "mac-project"); + const after = structuredClone(before); + Object.assign(after.tasks["task-1"].fields, { + title: "x".repeat(241), + stage: "shipped", + priority: 7, + estimate: -1, + startDate: "tomorrow", + goal: 42, + kind: null, + archived: "yes", + }); + after.tasks["task-1"].texts.description = "y".repeat(20001); + after.tasks["task-1"].sets.step.bad = "not a step"; + after.tasks["task-1"].sets.field["field-3"] = { nested: true }; + after.tasks["task-1"].sets.scope["../outside"] = true; + after.tasks["task-1"].sets.scope["/etc/passwd"] = true; + after.goals["goal-1"].fields.phase = "never"; + after.goals["goal-1"].fields.order = "first"; + after.cycles["cycle-1"].fields.endDate = 5; + applyBoard(state, "mac-project", before, after, { at }); + const kept = state.tasks.find((item) => item.id === "task-1")!; + assert.equal(kept.title, "Export as CSV"); + assert.equal(kept.stage, "working"); + assert.equal(kept.priority, "high"); + assert.equal(kept.estimate, 3); + assert.equal(kept.startDate, "2026-11-20"); + assert.equal(kept.epicId, "goal-1"); + assert.equal(kept.kind, "feature"); + assert.equal(kept.archivedAt, null); + assert.equal(kept.description, "Line one.\nLine two."); + assert.deepEqual( + kept.checklist.map((step) => step.id), + ["step-1", "step-2"], + ); + assert.deepEqual(kept.customFields, { "field-1": "blue", "field-2": 2 }); + assert.deepEqual(kept.scope, ["src/export", "docs"]); + assert.equal(state.epics[0].phase, "now"); + assert.equal(state.epics[0].order, 0); + assert.equal(state.cycles[0].endDate, "2026-11-22"); +}); + +test("an entry with nothing usable in it is not shown, and never breaks the rest", () => { + const board = boardOf(mac(), "mac-project"); + board.tasks["nameless"] = { + fields: { stage: "planned" }, + texts: {}, + sets: {}, + }; + board.tasks["task-2"] = structuredClone(board.tasks["task-1"]); + board.tasks["task-2"].fields.identifier = "MC-002"; + board.goals["empty"] = { fields: {}, texts: {}, sets: {} }; + board.cycles["dateless"] = { + fields: { name: "No dates" }, + texts: {}, + sets: {}, + }; + board.comments["orphan"] = { fields: { text: 5 }, texts: {}, sets: {} }; + board.lanes["nameless"] = { + fields: { stage: "planned" }, + texts: {}, + sets: {}, + }; + const pc = arrivesOn(board); + assert.deepEqual( + pc.tasks + .filter((item) => item.projectId === "pc-project") + .map((item) => item.id) + .sort(), + ["task-1", "task-2"], + ); + assert.equal(pc.epics.length, 1); + assert.equal(pc.cycles.length, 1); + assert.equal(pc.storyComments!.length, 1); + assert.ok(!pc.workflowStates.some((lane) => lane.id.endsWith("nameless"))); +}); + +test("archiving and closing are flags on the board and dates here", () => { + const state = mac(); + const before = boardOf(state, "mac-project"); + const after = structuredClone(before); + after.tasks["task-1"].fields.archived = true; + after.goals["goal-1"].fields.closed = true; + after.cycles["cycle-1"].fields.state = "completed"; + applyBoard(state, "mac-project", before, after, { + at: "2026-11-23T10:00:00.000Z", + stampOf: () => ({ changedAt: "2026-11-23T09:00:00.000Z" }), + }); + assert.equal( + state.tasks.find((item) => item.id === "task-1")!.archivedAt, + "2026-11-23T09:00:00.000Z", + ); + assert.equal(state.epics[0].closedAt, "2026-11-23T10:00:00.000Z"); + assert.equal(state.cycles[0].completedAt, "2026-11-23T09:00:00.000Z"); + assert.equal(state.cycles[0].startedAt, at); + assert.equal( + boardOf(state, "mac-project").tasks["task-1"].fields.archived, + true, + ); + // Taking the flag off again takes the date off. + const restored = boardOf(state, "mac-project"); + const reopened = structuredClone(restored); + reopened.tasks["task-1"].fields.archived = false; + applyBoard(state, "mac-project", restored, reopened, { at }); + assert.equal( + state.tasks.find((item) => item.id === "task-1")!.archivedAt, + null, + ); +}); + +test("a lane a person made by hand in an older way stays on this computer and off the board", () => { + const state = mac(); + state.workflowStates.push({ + id: "hand-made", + projectId: "mac-project", + name: "Odd", + stage: "planned", + color: "#000", + order: 9, + }); + state.tasks.find((item) => item.id === "task-1")!.statusId = "hand-made"; + const board = boardOf(state, "mac-project"); + assert.ok(!("hand-made" in board.lanes)); + assert.equal(board.tasks["task-1"].fields.lane, undefined); + const after = structuredClone(board); + after.lanes.working.fields.name = "Doing"; + applyBoard(state, "mac-project", board, after, { at }); + assert.ok(state.workflowStates.some((lane) => lane.id === "hand-made")); + assert.equal( + state.workflowStates.find((lane) => lane.id === "mac-project:working")! + .name, + "Doing", + ); +}); From 68516c3e333816bf3d9cbfd0e0cd10b1061c5e08 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:00:05 +0100 Subject: [PATCH 12/66] feat: write a large board change as several small updates [skip ci] The sharing service takes no update over 1 MiB. A change is now written to the document in pieces of at most about 256 KiB: an entry stays whole when it fits, and one that is too large by itself goes key by key. A single value the service would refuse for its size is not written. writeChanges and writeEntryAlone answer how many of those there were. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/board/document.ts | 195 ++++++++++++++++++++------- tests/sharing-board-document.test.ts | 94 +++++++++++++ 2 files changed, 244 insertions(+), 45 deletions(-) diff --git a/runtime/sharing/board/document.ts b/runtime/sharing/board/document.ts index c6a5d4f..c09ae99 100644 --- a/runtime/sharing/board/document.ts +++ b/runtime/sharing/board/document.ts @@ -35,6 +35,15 @@ export type Board = Record>; export const LAYOUT = 1; /** What marks a change this computer made, as opposed to one that came from the log. */ export const LOCAL = "local"; +/** The sharing service takes no update larger than this. */ +export const LARGEST_UPDATE = 1024 * 1024; +/** + * How much is written as one change before the rest goes into the next. A + * quarter of what the service takes, so that no update comes near the limit. + */ +const ROOM_IN_ONE_CHANGE = 256 * 1024; +/** One value this large would be an update the service refuses. It is not written. */ +const LARGEST_VALUE = LARGEST_UPDATE - 64 * 1024; const META = "meta", LAYOUT_KEY = "layout", @@ -112,73 +121,169 @@ function writeText(kept: Y.Map, name: string, wording: string) { if (change.insert) text.insert(change.at, change.insert); } -/** Writes the values that differ between two records, and takes out the ones that are gone. */ -function writeValues( - kept: Y.Map, +/** One thing to write, with a number its update will not be larger than. */ +interface Write { + bytes: number; + run(): void; +} +const OVERHEAD = 48; +const bytesOf = (key: string, value: unknown) => + OVERHEAD + + Buffer.byteLength(key) + + Buffer.byteLength(JSON.stringify(value) ?? ""); + +/** The values that differ between two records, and the ones that are gone. */ +function valueWrites( + kept: () => Y.Map, was: Record, now: Record, keyOf: (name: string) => string, -) { +): Write[] { + const writes: Write[] = []; for (const name of new Set([...Object.keys(was), ...Object.keys(now)])) { if (same(was[name], now[name])) continue; - if (name in now) kept.set(keyOf(name), now[name]); - else kept.delete(keyOf(name)); + const key = keyOf(name); + if (name in now) + writes.push({ + bytes: bytesOf(key, now[name]), + run: () => kept().set(key, now[name]), + }); + else + writes.push({ bytes: bytesOf(key, null), run: () => kept().delete(key) }); } + return writes; } -function writeEntry( +/** What it takes to make the document's entry say what `after` says. */ +function entryWrites( held: Y.Map, id: string, before: Entry | undefined, after: Entry, -) { +): Write[] { // An entry is made once. Putting a second map under an id that is already there // would replace the first one whole, with every edit anyone made to it. - let kept = held.get(id); - if (!(kept instanceof Y.Map)) { - kept = new Y.Map(); - held.set(id, kept); - } - const map = kept as Y.Map; - const known = before ?? readEntry(map); - if (map.get(DELETED) === true) map.delete(DELETED); - writeValues(map, known.fields, after.fields, (name) => name); + const kept = () => { + let entry = held.get(id); + if (!(entry instanceof Y.Map)) { + entry = new Y.Map(); + held.set(id, entry); + } + return entry as Y.Map; + }; + const there = held.get(id); + const known = + before ?? + (there instanceof Y.Map + ? readEntry(there) + : { fields: {}, texts: {}, sets: {} }); + const writes: Write[] = [ + { + bytes: bytesOf(id, null), + run: () => { + const entry = kept(); + if (entry.get(DELETED) === true) entry.delete(DELETED); + }, + }, + ...valueWrites(kept, known.fields, after.fields, (name) => name), + ]; for (const set of new Set([ ...Object.keys(known.sets), ...Object.keys(after.sets), ])) - writeValues( - map, - known.sets[set] ?? {}, - after.sets[set] ?? {}, - (member) => set + MEMBER_OF + member, + writes.push( + ...valueWrites( + kept, + known.sets[set] ?? {}, + after.sets[set] ?? {}, + (member) => set + MEMBER_OF + member, + ), ); for (const [name, wording] of Object.entries(after.texts)) - if (known.texts[name] !== wording) writeText(map, name, wording); + if (known.texts[name] !== wording) + writes.push({ + bytes: bytesOf(name, wording), + run: () => writeText(kept(), name, wording), + }); + return writes; } /** - * Writes what changed on this computer into the document, as one change. - * `before` is the board as this computer last saw it and `after` as it is now: - * only what differs between the two is written, so a change that arrived from - * someone else in the meantime is not undone. + * Writes entries as few changes as will stay small. An entry goes into one + * change whole unless it is too large for that by itself. + * Answers how many values were too large to write at all. */ -export function writeChanges(doc: Y.Doc, before: Board, after: Board): void { - doc.transact(() => { - const meta = doc.getMap(META); - if (meta.get(LAYOUT_KEY) === undefined) meta.set(LAYOUT_KEY, LAYOUT); - for (const collection of collections) { - const held = doc.getMap(collection); - const was = before[collection], - now = after[collection]; - for (const id of Object.keys(was)) - if (!(id in now)) { - const gone = held.get(id); - // Marked, not removed: an edit made elsewhere at the same moment is kept. - if (gone instanceof Y.Map) gone.set(DELETED, true); - } - for (const [id, entry] of Object.entries(now)) - if (!same(was[id], entry)) writeEntry(held, id, was[id], entry); - } - }, LOCAL); +function writeEntries(doc: Y.Doc, entries: Write[][]): number { + let together: Write[] = [], + room = ROOM_IN_ONE_CHANGE, + tooLarge = 0; + const written = () => { + const writes = together; + together = []; + room = ROOM_IN_ONE_CHANGE; + if (!writes.length) return; + doc.transact(() => { + const meta = doc.getMap(META); + if (meta.get(LAYOUT_KEY) === undefined) meta.set(LAYOUT_KEY, LAYOUT); + for (const write of writes) write.run(); + }, LOCAL); + }; + const add = (writes: Write[], bytes: number) => { + if (bytes > room) written(); + together.push(...writes); + room -= bytes; + }; + for (const all of entries) { + const writes = all.filter((write) => write.bytes <= LARGEST_VALUE); + tooLarge += all.length - writes.length; + const bytes = writes.reduce((sum, write) => sum + write.bytes, 0); + if (bytes <= ROOM_IN_ONE_CHANGE) add(writes, bytes); + else for (const write of writes) add([write], write.bytes); + } + written(); + return tooLarge; +} + +/** + * Writes what changed on this computer into the document. `before` is the + * board as this computer last saw it and `after` as it is now: only what + * differs between the two is written, so a change that arrived from someone + * else in the meantime is not undone. + * Answers how many values were too large for the sharing service to take. + */ +export function writeChanges(doc: Y.Doc, before: Board, after: Board): number { + const entries: Write[][] = []; + for (const collection of collections) { + const held = doc.getMap(collection); + const was = before[collection], + now = after[collection]; + for (const id of Object.keys(was)) + if (!(id in now)) + entries.push([ + { + bytes: bytesOf(id, true), + run: () => { + const gone = held.get(id); + // Marked, not removed: an edit made elsewhere at the same moment is kept. + if (gone instanceof Y.Map) gone.set(DELETED, true); + }, + }, + ]); + for (const [id, entry] of Object.entries(now)) + if (!same(was[id], entry)) + entries.push(entryWrites(held, id, was[id], entry)); + } + return writeEntries(doc, entries); +} + +/** Writes one entry as a change of its own, as when a whole board is first written out. */ +export function writeEntryAlone( + doc: Y.Doc, + collection: Collection, + id: string, + entry: Entry, +): number { + return writeEntries(doc, [ + entryWrites(doc.getMap(collection), id, undefined, entry), + ]); } diff --git a/tests/sharing-board-document.test.ts b/tests/sharing-board-document.test.ts index 033afbe..f16a814 100644 --- a/tests/sharing-board-document.test.ts +++ b/tests/sharing-board-document.test.ts @@ -3,12 +3,14 @@ import assert from "node:assert/strict"; import * as Y from "yjs"; import { emptyBoard, + LARGEST_UPDATE, LAYOUT, layoutOf, LOCAL, readBoard, textChange, writeChanges, + writeEntryAlone, type Board, type Entry, } from "../runtime/sharing/board/document"; @@ -382,3 +384,95 @@ test("what MemCode did not put in a document is read past, never tripped over", assert.equal(read.tasks.odd.fields.title, "Still a task"); assert.equal(layoutOf(doc), undefined); }); + +/** What another computer reads after taking every update, in the order they were made. */ +function readBy(updates: Uint8Array[]) { + const reader = new Y.Doc(); + for (const update of updates) Y.applyUpdate(reader, update); + return readBoard(reader); +} +const QUARTER_OF_THE_LIMIT = LARGEST_UPDATE / 4; + +test("a change with more in it than one update should hold is written as several small ones", () => { + const mac = computer(); + const tasks = Object.fromEntries( + Array.from({ length: 900 }, (_, at) => [ + `task-${at}`, + task(`Task ${at}`, { texts: { description: "å".repeat(600) } }), + ]), + ); + mac.change((board) => void (board.tasks = tasks)); + assert.ok(mac.made.length > 1, `${mac.made.length} update`); + for (const update of mac.made) + assert.ok( + update.length <= QUARTER_OF_THE_LIMIT + 4096, + `${update.length} bytes`, + ); + assert.deepEqual(readBy(mac.made).tasks, tasks); + // A task is never cut in two when it fits in one update. + const afterTheFirst = readBy(mac.made.slice(0, 1)); + assert.ok(Object.keys(afterTheFirst.tasks).length > 0); + for (const [id, read] of Object.entries(afterTheFirst.tasks)) + assert.deepEqual(read, tasks[id]); +}); + +test("an entry too large for one update by itself goes in pieces, and arrives whole", () => { + const mac = computer(); + const steps = Object.fromEntries( + Array.from({ length: 30 }, (_, at) => [ + `step-${at}`, + { text: "x".repeat(20000), done: false, order: at }, + ]), + ); + const large = task("Has a very long runbook", { sets: { step: steps } }); + mac.change((board) => void (board.tasks.large = large)); + assert.ok(mac.made.length > 1); + for (const update of mac.made) + assert.ok(update.length <= QUARTER_OF_THE_LIMIT + 32768); + assert.deepEqual(readBy(mac.made).tasks.large, large); +}); + +test("a value the service would refuse for its size is not written, and everything else is", () => { + const mac = computer(); + let tooLarge = 0; + const next = board({ + tasks: { + "task-1": task("Carries far too much", { + fields: { + identifier: "MC-001", + title: "Carries far too much", + stage: "planned", + category: "y".repeat(LARGEST_UPDATE), + }, + texts: { description: "z".repeat(LARGEST_UPDATE) }, + }), + "task-2": task("An ordinary task"), + }, + }); + tooLarge = writeChanges(mac.doc, emptyBoard(), next); + assert.equal(tooLarge, 2); + for (const update of mac.made) assert.ok(update.length < LARGEST_UPDATE); + const read = readBy(mac.made); + assert.deepEqual(read.tasks["task-2"], next.tasks["task-2"]); + assert.deepEqual(read.tasks["task-1"].fields, { + identifier: "MC-001", + title: "Carries far too much", + stage: "planned", + }); + assert.deepEqual(read.tasks["task-1"].texts, {}); +}); + +test("an entry written alone is one update that holds the entry and the layout it is in", () => { + const mac = computer(); + const first = task("The first task of a board", { + texts: { description: "Written out when the board is first shared." }, + sets: { label: { urgent: true } }, + }); + assert.equal(writeEntryAlone(mac.doc, "tasks", "task-1", first), 0); + writeEntryAlone(mac.doc, "tasks", "task-2", task("The second")); + assert.equal(mac.made.length, 2); + const reader = new Y.Doc(); + Y.applyUpdate(reader, mac.made[0]); + assert.equal(layoutOf(reader), LAYOUT); + assert.deepEqual(readBoard(reader).tasks, { "task-1": first }); +}); From d344d706e2a8bb648894cb7422d35d255dad1040 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:00:05 +0100 Subject: [PATCH 13/66] feat: give board updates ids made from their bytes [skip ci] An update is sent under a UUID built from the SHA-256 of its bytes, so a reader can tell bytes that changed after they were written. The same bytes can get up to eight ids, which lets a repair be told from the damaged entry it repairs. Also here: the check a log entry passes before it is applied (size, id, decodeUpdate), whether one document holds more than another, and how many updates go into one call (100, 3 MiB). The tests keep the Yjs 13.6.33 measurements from the layout proposal. One of them is new. Of 2,241 damaged copies of two small updates, 839 made applyUpdate throw, and 7 of those had read fine with decodeUpdate. Reading first is not enough, so the log reader has to guard every apply. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/board/updates.ts | 120 ++++++++++++++ tests/sharing-board-updates.test.ts | 238 ++++++++++++++++++++++++++++ 2 files changed, 358 insertions(+) create mode 100644 runtime/sharing/board/updates.ts create mode 100644 tests/sharing-board-updates.test.ts diff --git a/runtime/sharing/board/updates.ts b/runtime/sharing/board/updates.ts new file mode 100644 index 0000000..6188744 --- /dev/null +++ b/runtime/sharing/board/updates.ts @@ -0,0 +1,120 @@ +import { createHash } from "node:crypto"; +import * as Y from "yjs"; +import { LARGEST_UPDATE } from "./document"; + +/** + * Updates on their way to and from a board's log: the id each is sent under, + * whether one that arrived may be applied, and what a document holds that the + * log does not. + */ + +/** How many ids the same bytes can be sent under. More than one, so a repair can be told from what it repairs. */ +const IDS_PER_UPDATE = 8; +/** The service takes a hundred updates a call, and four mebibytes unless it is set up otherwise. */ +const MOST_UPDATES_IN_A_CALL = 100, + MOST_BYTES_IN_A_CALL = 3 * 1024 * 1024; + +/** + * The id an update is sent under: a UUID made from its bytes. A reader that + * finds bytes which do not give their id knows they changed after they were + * written. `again` gives the same bytes another id, for sending them a second + * time when the log's copy of the first is damaged. + */ +export function idOf(payload: Uint8Array, again = 0): string { + const hash = createHash("sha256").update(payload); + if (again) hash.update(Uint8Array.of(again)); + const bytes = hash.digest().subarray(0, 16); + // Version 8 is the one for ids made by a rule of the sender's own. + bytes[6] = (bytes[6] & 0x0f) | 0x80; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = bytes.toString("hex"); + return [ + hex.slice(0, 8), + hex.slice(8, 12), + hex.slice(12, 16), + hex.slice(16, 20), + hex.slice(20), + ].join("-"); +} + +export function isMadeFrom(id: string, payload: Uint8Array): boolean { + const sent = id.toLowerCase(); + for (let again = 0; again < IDS_PER_UPDATE; again++) + if (idOf(payload, again) === sent) return true; + return false; +} + +export type NotApplied = "too-large" | "changed" | "unreadable"; + +/** + * Why an update from the log must not be applied, or nothing when it may be. + * Reading it first matters: applying an update that does not read can leave + * the document half changed. + */ +export function whyNotApplied( + id: string, + payload: Uint8Array, +): NotApplied | undefined { + if (payload.length > LARGEST_UPDATE) return "too-large"; + if (!isMadeFrom(id, payload)) return "changed"; + try { + Y.decodeUpdate(payload); + } catch { + return "unreadable"; + } + return undefined; +} + +type Deleted = Array<{ clock: number; len: number }>; +/** Whether every deleted stretch of one list lies inside the stretches of the other. */ +function covers(theirs: Deleted | undefined, mine: Deleted): boolean { + let at = 0; + for (const range of mine) { + let clock = range.clock; + const end = range.clock + range.len; + while (clock < end) { + while ( + theirs && + at < theirs.length && + theirs[at].clock + theirs[at].len <= clock + ) + at++; + const cover = theirs?.[at]; + if (!cover || cover.clock > clock) return false; + clock = cover.clock + cover.len; + } + } + return true; +} + +/** Whether a document holds a change or a deletion that another one lacks. */ +export function holdsMore(mine: Y.Doc, theirs: Y.Doc): boolean { + const known = Y.decodeStateVector(Y.encodeStateVector(theirs)); + for (const [client, clock] of Y.decodeStateVector(Y.encodeStateVector(mine))) + if (clock > (known.get(client) ?? 0)) return true; + const deletedThere = Y.createDeleteSetFromStructStore(theirs.store).clients; + for (const [client, deleted] of Y.createDeleteSetFromStructStore(mine.store) + .clients) + if (!covers(deletedThere.get(client), deleted)) return true; + return false; +} + +/** One update with everything `from` holds that `reader` lacks. */ +export const missingFrom = (reader: Y.Doc, from: Y.Doc): Uint8Array => + Y.encodeStateAsUpdate(from, Y.encodeStateVector(reader)); + +/** The updates to send in the next call: from the front, as many as one call may hold. */ +export function nextCall( + waiting: Update[], +): Update[] { + const call: Update[] = []; + let bytes = 0; + for (const update of waiting) { + if (call.length === MOST_UPDATES_IN_A_CALL) break; + if (call.length && bytes + update.payload.length > MOST_BYTES_IN_A_CALL) + break; + call.push(update); + bytes += update.payload.length; + } + return call; +} diff --git a/tests/sharing-board-updates.test.ts b/tests/sharing-board-updates.test.ts new file mode 100644 index 0000000..312d5aa --- /dev/null +++ b/tests/sharing-board-updates.test.ts @@ -0,0 +1,238 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as Y from "yjs"; +import { + emptyBoard, + LARGEST_UPDATE, + LOCAL, + readBoard, + writeChanges, + type Board, +} from "../runtime/sharing/board/document"; +import { + holdsMore, + idOf, + isMadeFrom, + missingFrom, + nextCall, + whyNotApplied, +} from "../runtime/sharing/board/updates"; + +const uuid = + /^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const oneTask = (title: string): Board => ({ + ...emptyBoard(), + tasks: { + "task-1": { + fields: { identifier: "MC-001", title, stage: "planned" }, + texts: { description: "Line one.\nLine two, with an é and a 🙂." }, + sets: { label: { urgent: true } }, + }, + }, +}); +/** A document, and every update a change to it made. */ +function written(...boards: Board[]) { + const doc = new Y.Doc(); + doc.clientID = 20261121; + const updates: Uint8Array[] = []; + doc.on("update", (update: Uint8Array, origin: unknown) => { + if (origin === LOCAL) updates.push(update); + }); + let seen = emptyBoard(); + for (const board of boards) { + writeChanges(doc, seen, board); + seen = board; + } + return { doc, updates }; +} +const copyOf = (doc: Y.Doc) => { + const copy = new Y.Doc(); + Y.applyUpdate(copy, Y.encodeStateAsUpdate(doc)); + return copy; +}; + +test("an update's id is a UUID made from its bytes, the same wherever it is worked out", () => { + const { updates } = written(oneTask("Export as CSV")); + const id = idOf(updates[0]); + assert.match(id, uuid); + assert.equal(idOf(Uint8Array.from(updates[0])), id); + assert.ok(isMadeFrom(id, updates[0])); + assert.ok(isMadeFrom(id.toUpperCase(), updates[0])); + const other = Uint8Array.from(updates[0]); + other[other.length - 1] ^= 1; + assert.notEqual(idOf(other), id); + assert.equal(isMadeFrom(id, other), false); +}); + +test("the same bytes can be sent again under another id that is still made from them", () => { + const { updates } = written(oneTask("Export as CSV")); + const ids = [0, 1, 2, 7].map((again) => idOf(updates[0], again)); + assert.equal(new Set(ids).size, 4); + for (const id of ids) { + assert.match(id, uuid); + assert.ok(isMadeFrom(id, updates[0])); + } + assert.equal(isMadeFrom(idOf(updates[0], 8), updates[0]), false); +}); + +test("an update is applied only when it is small enough, is what its id says, and reads as an update", () => { + const { updates } = written(oneTask("Export as CSV")); + const [update] = updates; + assert.equal(whyNotApplied(idOf(update), update), undefined); + const large = new Uint8Array(LARGEST_UPDATE + 1); + assert.equal(whyNotApplied(idOf(large), large), "too-large"); + const flipped = Uint8Array.from(update); + flipped[10] ^= 4; + assert.equal(whyNotApplied(idOf(update), flipped), "changed"); + assert.equal( + whyNotApplied("2f1f5f3a-5a52-4c1e-9d3e-5d3a2f0e9c11", update), + "changed", + ); + const nonsense = Uint8Array.from([255, 255, 255, 255, 7, 1, 2, 3]); + assert.equal(whyNotApplied(idOf(nonsense), nonsense), "unreadable"); + assert.equal( + whyNotApplied(idOf(new Uint8Array()), new Uint8Array()), + "unreadable", + ); +}); + +test("a damaged update that someone sends under its own id is refused, or applies without harm", () => { + // What the layout proposal measured, kept as a test: cut short or with one + // byte inverted, an update never applies; and nothing that is let through throws. + const { updates } = written(oneTask("Export as CSV")); + const [update] = updates; + const damaged: Uint8Array[] = []; + for (let length = 0; length < update.length; length++) + damaged.push(update.subarray(0, length)); + for (let at = 0; at < update.length; at++) { + const inverted = Uint8Array.from(update); + inverted[at] ^= 0xff; + damaged.push(inverted); + } + let refused = 0; + for (const bytes of damaged) { + if (whyNotApplied(idOf(bytes), bytes)) { + refused++; + continue; + } + const reader = new Y.Doc(); + assert.doesNotThrow(() => Y.applyUpdate(reader, bytes)); + assert.doesNotThrow(() => readBoard(reader)); + } + assert.ok(refused >= update.length, `${refused} of ${damaged.length}`); +}); + +test("a flipped bit that still reads as an update is caught by the id, which is what the id is for", () => { + const { updates } = written(oneTask("Export as CSV")); + const [update] = updates; + const id = idOf(update); + let readable = 0; + for (let bit = 0; bit < update.length * 8; bit++) { + const flipped = Uint8Array.from(update); + flipped[bit >> 3] ^= 1 << (bit & 7); + assert.equal(whyNotApplied(id, flipped), "changed"); + if (!whyNotApplied(idOf(flipped), flipped)) readable++; + } + // Most single flipped bits give bytes that would apply as a real change. + assert.ok(readable > update.length, `${readable} still read as an update`); +}); + +test("a document holds more than another when it has a change or a deletion the other lacks", () => { + const mine = written(oneTask("Export as CSV")); + const theirs = copyOf(mine.doc); + assert.equal(holdsMore(mine.doc, theirs), false); + assert.equal(holdsMore(theirs, mine.doc), false); + + writeChanges(mine.doc, oneTask("Export as CSV"), oneTask("Export as PDF")); + assert.equal(holdsMore(mine.doc, theirs), true); + // The one that is behind does not hold more. + assert.equal(holdsMore(theirs, mine.doc), false); + + Y.applyUpdate(theirs, missingFrom(theirs, mine.doc)); + assert.equal(holdsMore(mine.doc, theirs), false); + assert.deepEqual(readBoard(theirs), oneTask("Export as PDF")); +}); + +test("what one document is missing can be sent as one update, and changes that waited for it take effect", () => { + // The proposal's measurement: two changes to a task, applied without the update + // that made the task, change nothing and wait. + const author = written( + oneTask("Export as CSV"), + oneTask("Export as PDF"), + oneTask("Export as PDF and CSV"), + ); + const [made, ...later] = author.updates; + assert.equal(later.length, 2); + const reader = new Y.Doc(); + for (const update of later) Y.applyUpdate(reader, update); + assert.deepEqual(readBoard(reader), emptyBoard()); + assert.notEqual(reader.store.pendingStructs, null); + assert.equal(holdsMore(author.doc, reader), true); + + const difference = missingFrom(reader, author.doc); + assert.ok(difference.length < made.length + 200); + Y.applyUpdate(reader, difference); + assert.equal(reader.store.pendingStructs, null); + assert.deepEqual(readBoard(reader), oneTask("Export as PDF and CSV")); + assert.equal(holdsMore(author.doc, reader), false); +}); + +test("applying a damaged update can throw and still change the document, so it is read first and applied inside a guard", () => { + // Measured with Yjs 13.6.33 and kept here. The client id is fixed so that the + // bytes, and with them the counts, are the same on every run. + const { updates } = written( + oneTask("Export as CSV"), + oneTask("Export as PDF"), + ); + let changedAfterBeingRefused = 0, + changedThoughItRead = 0, + threwThoughItRead = 0; + for (const update of updates) + for (let at = 0; at < update.length; at++) + for (const mask of [0xff, 0x80, 0x40, 0x20, 0x10, 8, 4, 2, 1]) { + const damaged = Uint8Array.from(update); + damaged[at] ^= mask; + const reader = new Y.Doc(); + Y.applyUpdate(reader, updates[0]); + const before = Buffer.from(Y.encodeStateAsUpdate(reader)); + try { + Y.applyUpdate(reader, damaged); + continue; + } catch { + // Applying threw. What is the document now? + } + const changed = + Buffer.compare(before, Buffer.from(Y.encodeStateAsUpdate(reader))) !== + 0; + const refused = whyNotApplied(idOf(damaged), damaged) !== undefined; + if (refused && changed) changedAfterBeingRefused++; + if (!refused) threwThoughItRead++; + if (!refused && changed) changedThoughItRead++; + } + // Applying is not all or nothing: this is why an update that does not read is never applied. + assert.ok(changedAfterBeingRefused > 0, String(changedAfterBeingRefused)); + // Reading first is not enough either: some bytes read as an update and cannot + // be applied. The log reader guards every apply and reloads the document. + assert.ok(threwThoughItRead > 0, String(threwThoughItRead)); + assert.equal(changedThoughItRead, 0); +}); + +test("updates go to the service in calls of at most a hundred and at most three mebibytes", () => { + const small = Array.from({ length: 250 }, (_, at) => ({ + id: `id-${at}`, + payload: new Uint8Array(1000), + })); + assert.equal(nextCall(small).length, 100); + assert.equal(nextCall(small.slice(200)).length, 50); + assert.deepEqual(nextCall([]), []); + + const large = Array.from({ length: 9 }, (_, at) => ({ + id: `id-${at}`, + payload: new Uint8Array(700 * 1024), + })); + // 4 × 700 KiB is 2.8 MiB. A fifth would pass three. + assert.equal(nextCall(large).length, 4); + // One update is always sent, whatever its size: the service says if it is too large. + const huge = [{ id: "huge", payload: new Uint8Array(4 * 1024 * 1024) }]; + assert.equal(nextCall(huge).length, 1); +}); From 456ffe7477dacd21f00ab2fb6c4f72ed32a15785 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:00:05 +0100 Subject: [PATCH 14/66] feat: keep a connected board's sync state beside the workspace [skip ci] One folder per connected project: the document the log has built (log.bin) and one file with the log position, the board as last seen, the changes not sent yet and the entries left out (sync.json). A save is written next to what is there and renamed into place. When the workspace file has to change with it, the workspace is saved between the two steps. Both carry the same counter, so after a crash load() can tell whether the workspace got there, and finishes or drops the save. State kept for another workspace, or a document that is not the one that was saved, is not used. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/board/store.ts | 199 ++++++++++++++++++++++++++++++ tests/sharing-board-store.test.ts | 171 +++++++++++++++++++++++++ 2 files changed, 370 insertions(+) create mode 100644 runtime/sharing/board/store.ts create mode 100644 tests/sharing-board-store.test.ts diff --git a/runtime/sharing/board/store.ts b/runtime/sharing/board/store.ts new file mode 100644 index 0000000..75388dc --- /dev/null +++ b/runtime/sharing/board/store.ts @@ -0,0 +1,199 @@ +import { createHash } from "node:crypto"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { replaceWorkspace } from "../../persistence"; +import { collections, type Board } from "./document"; +import type { NotApplied } from "./updates"; + +/** A change this computer made that is not in the log yet. */ +export interface UnsentUpdate { + id: string; + payload: Uint8Array; +} +/** A log entry that was not applied. `failed`: it read as an update and could not be applied. */ +export interface LeftOutUpdate { + sequence: number; + id: string; + author: string; + loggedAt: string; + reason: NotApplied | "failed"; +} +/** What one connected project keeps beside the workspace file. */ +export interface KeptBoard { + /** The number of the last log entry dealt with. */ + cursor: number; + /** + * How many times the log has changed the workspace file. The workspace holds + * the same number, which is how a save that was cut off is told apart. + */ + applied: number; + /** Whether the board here and the board in the log have been brought together. */ + joined: boolean; + /** The board as this computer last wrote or took it. Its own changes are told from this. */ + seen: Board; + unsent: UnsentUpdate[]; + leftOut: LeftOutUpdate[]; + /** The document as the log has built it. */ + log: Uint8Array; +} +/** A save. Leaving `log` out says the document is as it was last saved. */ +export type BoardToKeep = Omit & { log?: Uint8Array }; + +const VERSION = 1; +const STATE = "sync.json", + LOG = "log.bin", + NEXT = ".next"; + +const digestOf = (bytes: Uint8Array) => + createHash("sha256").update(bytes).digest("hex"); +const isMissing = (problem: unknown) => + (problem as NodeJS.ErrnoException).code === "ENOENT"; + +interface StateFile { + version: number; + cursor: number; + applied: number; + joined: boolean; + seen: Board; + unsent: Array<{ id: string; payload: string }>; + leftOut: LeftOutUpdate[]; + log: { bytes: number; sha256: string }; +} + +function isStateFile(read: unknown): read is StateFile { + const file = read as StateFile | null; + return ( + !!file && + typeof file === "object" && + file.version === VERSION && + Number.isSafeInteger(file.cursor) && + Number.isSafeInteger(file.applied) && + typeof file.joined === "boolean" && + !!file.seen && + collections.every( + (name) => file.seen[name] && typeof file.seen[name] === "object", + ) && + Array.isArray(file.unsent) && + file.unsent.every( + (update) => + typeof update?.id === "string" && typeof update.payload === "string", + ) && + Array.isArray(file.leftOut) && + typeof file.log?.sha256 === "string" + ); +} + +/** + * Where one connected project's sync state is kept: a folder with the document + * the log has built and everything else in one file. + * + * A save is written beside what is there and then put in its place. When the + * workspace file has to change with it, the workspace is saved between the two + * steps, so after a crash the pair is either both old or both new. + */ +export class BoardStore { + private logDigest = digestOf(new Uint8Array()); + private logBytes = 0; + constructor(private readonly folder: string) {} + + private path(name: string) { + return join(this.folder, name); + } + private async read(name: string): Promise { + try { + const read: unknown = JSON.parse(await readFile(this.path(name), "utf8")); + return isStateFile(read) ? read : undefined; + } catch (problem) { + if (isMissing(problem) || problem instanceof SyntaxError) + return undefined; + throw problem; + } + } + private drop(...names: string[]) { + return Promise.all( + names.map((name) => rm(this.path(name), { force: true })), + ); + } + + /** + * What was kept, or nothing when there is nothing this workspace can use. + * `workspaceAt` is the number the workspace file holds. + */ + async load(workspaceAt: number): Promise { + const waiting = await this.read(STATE + NEXT); + // A save that waited for the workspace counts only if the workspace got there. + if (waiting?.applied === workspaceAt) await this.commit(); + else await this.drop(STATE + NEXT, LOG + NEXT); + const file = await this.read(STATE); + if (!file || file.applied !== workspaceAt) return undefined; + let log: Uint8Array; + try { + log = await readFile(this.path(LOG)); + } catch (problem) { + if (!isMissing(problem)) throw problem; + log = new Uint8Array(); + } + // A document that is not the one that was saved would quietly lose the board. + if (log.length !== file.log.bytes || digestOf(log) !== file.log.sha256) + return undefined; + this.logDigest = file.log.sha256; + this.logBytes = file.log.bytes; + return { + cursor: file.cursor, + applied: file.applied, + joined: file.joined, + seen: file.seen, + unsent: file.unsent.map((update) => ({ + id: update.id, + payload: Buffer.from(update.payload, "base64"), + })), + leftOut: file.leftOut, + log, + }; + } + + /** Writes a save beside what is kept. It counts once `commit` has put it in place. */ + async prepare(kept: BoardToKeep): Promise { + await mkdir(this.folder, { recursive: true }); + if (kept.log) { + await writeFile(this.path(LOG + NEXT), kept.log); + this.logDigest = digestOf(kept.log); + this.logBytes = kept.log.length; + } else await this.drop(LOG + NEXT); + const file: StateFile = { + version: VERSION, + cursor: kept.cursor, + applied: kept.applied, + joined: kept.joined, + seen: kept.seen, + unsent: kept.unsent.map((update) => ({ + id: update.id, + payload: Buffer.from(update.payload).toString("base64"), + })), + leftOut: kept.leftOut, + log: { bytes: this.logBytes, sha256: this.logDigest }, + }; + await writeFile(this.path(STATE + NEXT), JSON.stringify(file), "utf8"); + } + + /** Puts the prepared save in place: the document first, then the file that describes it. */ + async commit(): Promise { + try { + await replaceWorkspace(this.path(LOG + NEXT), this.path(LOG)); + } catch (problem) { + // No new document: this save left it as it was, or it is already in place. + if (!isMissing(problem)) throw problem; + } + await replaceWorkspace(this.path(STATE + NEXT), this.path(STATE)); + } + + async save(kept: BoardToKeep): Promise { + await this.prepare(kept); + await this.commit(); + } + + /** Forgets everything kept for this project. */ + remove(): Promise { + return rm(this.folder, { recursive: true, force: true }); + } +} diff --git a/tests/sharing-board-store.test.ts b/tests/sharing-board-store.test.ts new file mode 100644 index 0000000..31d476d --- /dev/null +++ b/tests/sharing-board-store.test.ts @@ -0,0 +1,171 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readdir, rm, truncate, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { emptyBoard } from "../runtime/sharing/board/document"; +import { + BoardStore, + type BoardToKeep, + type KeptBoard, +} from "../runtime/sharing/board/store"; + +async function folder(context: test.TestContext) { + const made = await mkdtemp(join(tmpdir(), "memcode-board-store-")); + context.after(() => rm(made, { recursive: true, force: true })); + return join(made, "board"); +} +const kept = (changes: Partial = {}): KeptBoard => ({ + cursor: 12, + applied: 3, + joined: true, + seen: { + ...emptyBoard(), + tasks: { + "task-1": { + fields: { identifier: "MC-001", title: "Export as CSV" }, + texts: { description: "Line one." }, + sets: { label: { urgent: true } }, + }, + }, + }, + unsent: [ + { + id: "0b0b0b0b-0000-8000-8000-000000000001", + payload: Uint8Array.of(1, 2, 3), + }, + { + id: "0b0b0b0b-0000-8000-8000-000000000002", + payload: Uint8Array.of(0, 255), + }, + ], + leftOut: [ + { + sequence: 7, + id: "0b0b0b0b-0000-8000-8000-000000000007", + author: "acct-dana", + loggedAt: "2026-11-21T12:00:00.000Z", + reason: "unreadable", + }, + ], + log: Uint8Array.of(9, 8, 7, 6), + ...changes, +}); +const plain = (read: KeptBoard | undefined) => + read && { + ...read, + log: [...read.log], + unsent: read.unsent.map((update) => ({ + id: update.id, + payload: [...update.payload], + })), + }; + +test("a project that has kept nothing starts with nothing", async (context) => { + const store = new BoardStore(await folder(context)); + assert.equal(await store.load(0), undefined); +}); + +test("what is saved for a board is read back as it was", async (context) => { + const where = await folder(context); + await new BoardStore(where).save(kept()); + assert.deepEqual(plain(await new BoardStore(where).load(3)), plain(kept())); + assert.deepEqual((await readdir(where)).sort(), ["log.bin", "sync.json"]); +}); + +test("a save that leaves the document out keeps the document that was saved before", async (context) => { + const where = await folder(context); + const store = new BoardStore(where); + await store.save(kept()); + const { log: _unchanged, ...rest } = kept({ cursor: 12, unsent: [] }); + await store.save(rest satisfies BoardToKeep); + const read = await new BoardStore(where).load(3); + assert.deepEqual(read?.unsent, []); + assert.deepEqual([...read!.log], [9, 8, 7, 6]); +}); + +test("a save that waited for the workspace is taken once the workspace holds its number", async (context) => { + const where = await folder(context); + const store = new BoardStore(where); + await store.save(kept()); + await store.prepare(kept({ cursor: 20, applied: 4, log: Uint8Array.of(1) })); + // The workspace file was written and MemCode stopped before the save was put in place. + const read = await new BoardStore(where).load(4); + assert.equal(read?.cursor, 20); + assert.deepEqual([...read!.log], [1]); + assert.deepEqual((await readdir(where)).sort(), ["log.bin", "sync.json"]); +}); + +test("a save that waited for a workspace change that never happened is dropped", async (context) => { + const where = await folder(context); + const store = new BoardStore(where); + await store.save(kept()); + await store.prepare(kept({ cursor: 20, applied: 4, log: Uint8Array.of(1) })); + // MemCode stopped before the workspace file was written: it still holds 3. + const read = await new BoardStore(where).load(3); + assert.deepEqual(plain(read), plain(kept())); + assert.deepEqual((await readdir(where)).sort(), ["log.bin", "sync.json"]); +}); + +test("a save that was cut off while being written is dropped", async (context) => { + const where = await folder(context); + const store = new BoardStore(where); + await store.save(kept()); + await writeFile(join(where, "log.bin.next"), Uint8Array.of(1)); + await writeFile(join(where, "sync.json.next"), '{"version":1,"cursor":2'); + assert.deepEqual(plain(await new BoardStore(where).load(3)), plain(kept())); + assert.deepEqual((await readdir(where)).sort(), ["log.bin", "sync.json"]); +}); + +test("a save whose document was put in place and whose description was not is finished on the next start", async (context) => { + const where = await folder(context); + const store = new BoardStore(where); + await store.save(kept()); + await store.prepare(kept({ cursor: 20, applied: 4, log: Uint8Array.of(1) })); + // Stopped half-way through putting the save in place. + const { rename } = await import("node:fs/promises"); + await rename(join(where, "log.bin.next"), join(where, "log.bin")); + const read = await new BoardStore(where).load(4); + assert.equal(read?.cursor, 20); + assert.deepEqual([...read!.log], [1]); +}); + +test("what was kept for another state of the workspace is not used", async (context) => { + const where = await folder(context); + await new BoardStore(where).save(kept()); + // A workspace file from a backup, or from another computer. + assert.equal(await new BoardStore(where).load(9), undefined); + assert.equal(await new BoardStore(where).load(0), undefined); +}); + +test("a document that is not the one that was saved is not used", async (context) => { + const where = await folder(context); + await new BoardStore(where).save(kept()); + await truncate(join(where, "log.bin"), 0); + assert.equal(await new BoardStore(where).load(3), undefined); + await writeFile(join(where, "log.bin"), Uint8Array.of(9, 8, 7, 5)); + assert.equal(await new BoardStore(where).load(3), undefined); +}); + +test("a file MemCode cannot read as its own is not used", async (context) => { + const where = await folder(context); + const store = new BoardStore(where); + await store.save(kept()); + await writeFile( + join(where, "sync.json"), + JSON.stringify({ version: 2, cursor: 1 }), + ); + assert.equal(await new BoardStore(where).load(3), undefined); + await writeFile(join(where, "sync.json"), "not json"); + assert.equal(await new BoardStore(where).load(3), undefined); +}); + +test("removing forgets everything, and removing twice is fine", async (context) => { + const where = await folder(context); + const store = new BoardStore(where); + await store.save(kept()); + await store.remove(); + await store.remove(); + assert.equal(await new BoardStore(where).load(3), undefined); + await assert.rejects(readdir(where), { code: "ENOENT" }); +}); From 54c6223adfc92341dc4e224a5b86c53da21b73a9 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:00:41 +0100 Subject: [PATCH 15/66] feat: keep a local board and its shared log in step [skip ci] BoardSync reads a shared project's log (pages, then the stream, again after the last entry when the stream ends), applies what it can to a Yjs document and makes the workspace follow. Changes made on this computer are found by comparing the workspace with the board as last seen, written as updates, kept on disk and sent in calls of at most 100. An entry that is too large, does not match its id, does not read, or throws when applied is written down and passed over. The log position moves on. An update of this computer's own that the log holds damaged is sent again as the difference between its document and the log's. The first time, what only this computer has is added to the log, one entry an update, and where both have an entry the log's is taken. When both boards have work on them nothing happens until keepBoth(). A change from the log and the workspace file are saved as a pair: the store's save is written first, then the workspace, then the save is put in place. SharedProjectLink.applied is the counter both carry. Not wired into the runtime yet. Seven two-computer scenarios run against the stand-in and against the real memsync-server, eleven more against the stand-in only (lost answers, damage, crashes, a full disk). Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/board/sync.ts | 762 +++++++++++++++++++++++ src/shared.ts | 2 + src/sharing.ts | 41 ++ tests/sharing-board-sync.test.ts | 422 +++++++++++++ tests/sharing-real-memsync.test.ts | 4 + tests/support/board-computers.ts | 371 +++++++++++ tests/support/board-sync-scenarios.ts | 400 ++++++++++++ tests/support/memsync-stand-in-boards.ts | 11 + 8 files changed, 2013 insertions(+) create mode 100644 runtime/sharing/board/sync.ts create mode 100644 tests/sharing-board-sync.test.ts create mode 100644 tests/support/board-computers.ts create mode 100644 tests/support/board-sync-scenarios.ts diff --git a/runtime/sharing/board/sync.ts b/runtime/sharing/board/sync.ts new file mode 100644 index 0000000..ec97b46 --- /dev/null +++ b/runtime/sharing/board/sync.ts @@ -0,0 +1,762 @@ +import * as Y from "yjs"; +import type { AppState } from "../../../src/shared"; +import type { + SharedBoardStatus, + SharedProjectLink, +} from "../../../src/sharing"; +import { refusalSentences } from "../../../src/sharing-refusals"; +import type { + BoardsApi, + LoggedUpdate, + UpdateReceipt, +} from "../memsync/boards-api"; +import type { GrpcStream } from "../memsync/grpc"; +import { + SharingRefused, + SharingSignedOut, + SharingUnavailable, +} from "../problems"; +import { applyBoard, boardOf, type EntryStamp } from "./board"; +import { + collections, + emptyBoard, + LARGEST_UPDATE, + LAYOUT, + layoutOf, + LOCAL, + readBoard, + writeChanges, + writeEntryAlone, + type Board, + type Collection, +} from "./document"; +import { BoardStore, type BoardToKeep, type KeptBoard } from "./store"; +import { + holdsMore, + idOf, + missingFrom, + nextCall, + whyNotApplied, +} from "./updates"; + +export interface BoardSyncOptions { + /** The project on this computer. */ + projectId: string; + /** The shared project whose log holds its board. */ + sharedProjectId: string; + /** Where this board keeps what it needs between runs. */ + folder: string; + state(): AppState; + boards: BoardsApi; + /** + * Saves the workspace as it is at the moment of the call, and writes it only + * after `first` has finished. + */ + saveWorkspace(first: () => Promise): Promise; + /** What the window shows about this board changed. Nothing needs saving. */ + shown(): void; + /** The names of the people on the shared project, by account. */ + people(): Promise>; + /** How long to wait before trying again after failing this many times in a row. */ + waitBeforeRetry?: (failures: number) => number; +} + +type Kept = Omit; +/** `live`: caught up and listening. The window is told `synced`, `sending` or `newer`. */ +type Condition = + "starting" | "live" | "offline" | "choose" | "gone" | "stopped"; +/** The documents went back to what was last saved, and the log is read again from there. */ +class StartAgain extends Error {} + +/** What marks a change that came from the log, as opposed to one this computer made. */ +const FROM_LOG = "log"; +const SOMEONE = "Someone on this project"; +const LEFT_OUT_KEPT = 200, + ARRIVALS_HELD = 256; +const WAITS = [1000, 2000, 5000, 15000, 30000, 60000]; +/** A board that is first written out goes in this order, so what a task points at is there before it. */ +const WRITING_ORDER: Collection[] = [ + "lanes", + "fields", + "views", + "cycles", + "goals", + "tasks", + "comments", +]; +const WORK: Collection[] = ["goals", "cycles", "tasks", "comments"]; +const NEWER = + "A newer MemCode laid this board out. Update MemCode to change it from this computer. Until then it is shown here and what you change stays on this computer."; +const CANNOT_SEND = + "Your changes could not be sent to the shared board yet. They are kept on this computer and sent when it works again."; +const CANNOT_SAVE = + "The workspace could not be saved, so changes from the shared board are waiting. Free disk space, and they are taken up again."; + +const sameBoard = (left: Board, right: Board) => + JSON.stringify(left) === JSON.stringify(right); +const hasWork = (board: Board) => + WORK.some((collection) => Object.keys(board[collection]).length > 0); +/** The entries of one board whose ids another does not hold. */ +function onlyIn(mine: Board, theirs: Board): Board { + const own = emptyBoard(); + for (const collection of collections) + for (const [id, entry] of Object.entries(mine[collection])) + if (!(id in theirs[collection])) own[collection][id] = entry; + return own; +} + +/** + * Keeps the board of one local project and the board in a shared project's log + * the same: docs/shared-board-layout-proposal.md. + * + * Two documents are kept. One holds exactly what the log has built. The other + * holds that and this computer's own changes that are not in the log yet. The + * app goes on showing the workspace file, which follows the second. + * + * Everything that changes them runs in turn, one after the other. + */ +export class BoardSync { + private readonly store: BoardStore; + private kept: Kept = this.nothingKept(0); + private doc = new Y.Doc(); + private logDoc = new Y.Doc(); + private turns: Promise = Promise.resolve(); + private running?: Promise; + private stopped = false; + private mustReopen = false; + private watching?: GrpcStream; + private arrived: LoggedUpdate[] = []; + private taking?: Promise; + private capturing?: Promise; + private sending?: Promise; + /** What the service has said it logged, in this run. */ + private logged = new Set(); + private repairs = new Set(); + /** Entries that read as updates and could not be applied. */ + private unusable = new Set(); + private names = new Map(); + private askedAbout = new Set(); + private stamps = new Map(); + private arriving?: LoggedUpdate; + private condition: Condition = "starting"; + private detail?: string; + /** Why the last call to send did not get through, while something is still waiting. */ + private notSent?: string; + private choice?: { shared: number; added: number }; + private tooLarge = 0; + private lastShown = ""; + private pauses = new Set<() => void>(); + + constructor(private readonly options: BoardSyncOptions) { + this.store = new BoardStore(options.folder); + } + + /** Begins reading the log and sending what this computer has. */ + start(): void { + this.running ??= this.run(); + } + + /** Ends sync for now. What is not sent yet stays on disk for the next start. */ + async stop(): Promise { + this.stopped = true; + this.watching?.cancel(); + for (const end of [...this.pauses]) end(); + await this.running; + await this.sending; + await this.turns; + this.doc.destroy(); + this.logDoc.destroy(); + } + + /** Forgets what was kept for this board. For after `stop`. */ + forget(): Promise { + return this.store.remove(); + } + + /** + * Looks at the workspace for changes made on this computer and queues them + * for the log. Called after every save of the workspace. + */ + capture(): Promise { + this.capturing ??= this.inTurn(async () => { + this.capturing = undefined; + if (this.stopped || !this.noteOwnChanges()) return; + await this.store.save(this.toKeep(false)); + await this.settle(); + }); + return this.capturing; + } + + /** The person said to keep both boards. */ + async keepBoth(): Promise { + await this.inTurn(async () => { + if (this.stopped || this.kept.joined || !this.choice) return; + await this.join(true); + if (this.condition === "choose") this.condition = "live"; + await this.settle(); + }); + } + + /** The name of someone on the shared project, when it is known. */ + nameOf(accountId: string): string | undefined { + return this.names.get(accountId); + } + + status(): SharedBoardStatus { + const waiting = this.kept.unsent.length; + const leftOut = new Map< + string, + { by: string; on: string; count: number } + >(); + for (const entry of this.kept.leftOut) { + const by = this.names.get(entry.author) ?? SOMEONE, + on = entry.loggedAt.slice(0, 10); + const line = leftOut.get(`${by}\n${on}`) ?? { by, on, count: 0 }; + line.count++; + leftOut.set(`${by}\n${on}`, line); + } + const live = this.condition === "live", + newer = live && this.isNewer(), + held = live && !newer && waiting > 0 ? this.notSent : undefined; + return { + projectId: this.options.projectId, + state: newer + ? "newer" + : this.condition !== "live" + ? this.condition + : held + ? "offline" + : waiting + ? "sending" + : "synced", + detail: newer ? NEWER : (held ?? this.detail), + waiting, + leftOut: [...leftOut.values()], + setAside: this.logDoc.store.pendingStructs !== null, + tooLarge: this.tooLarge, + choice: this.condition === "choose" ? this.choice : undefined, + }; + } + + // ── Reading the log ────────────────────────────────────────────────────── + + private async run(): Promise { + this.mustReopen = true; + void this.learn(); + for (let failures = 0; !this.stopped;) { + try { + if (this.mustReopen) await this.inTurn(() => this.open()); + await this.catchUp(); + if (this.stopped) return; + await this.inTurn(async () => { + if (!this.kept.joined) await this.join(false); + await this.settle(); + }); + failures = 0; + this.say(this.choice ? "choose" : "live"); + await this.watch(); + // A stream that ends is started again, as the service's own notes say. + failures = 1; + } catch (problem) { + if (this.stopped) return; + if (this.isGone(problem)) return; + failures++; + this.failed(problem); + } + await this.pause(this.waitFor(failures)); + } + } + + private async catchUp(): Promise { + for (;;) { + const page = await this.options.boards.readAfter( + this.options.sharedProjectId, + this.kept.cursor, + ); + if (this.stopped || !page.length) return; + await this.inTurn(() => this.take(page)); + } + } + + private watch(): Promise { + const stream = this.options.boards.watchAfter( + this.options.sharedProjectId, + this.kept.cursor, + (update) => this.arrive(update), + ); + this.watching = stream; + return stream.finished.finally(() => { + if (this.watching === stream) this.watching = undefined; + }); + } + + /** Updates from the stream are taken together when several are waiting. */ + private arrive(update: LoggedUpdate): Promise | undefined { + this.arrived.push(update); + this.taking ??= this.inTurn(async () => { + this.taking = undefined; + await this.take(this.arrived.splice(0)); + await this.settle(); + }).catch((problem) => { + // The stream is read again from what was last saved. + this.failed(problem); + this.watching?.cancel(); + }); + return this.arrived.length > ARRIVALS_HELD ? this.taking : undefined; + } + + private async open(): Promise { + this.mustReopen = false; + const at = this.link()?.applied ?? 0; + let read = await this.store.load(at); + try { + this.rebuild(read ?? { ...this.nothingKept(at), log: new Uint8Array() }); + } catch { + // What was kept cannot be used. The log and the workspace are still whole. + read = undefined; + } + if (read) return; + await this.store.remove(); + this.rebuild({ ...this.nothingKept(at), log: new Uint8Array() }); + } + + private nothingKept(applied: number): Kept { + return { + cursor: 0, + applied, + joined: false, + seen: emptyBoard(), + unsent: [], + leftOut: [], + }; + } + + private rebuild({ log, ...kept }: KeptBoard): void { + const doc = new Y.Doc(), + logDoc = new Y.Doc(); + if (log.length) { + Y.applyUpdate(logDoc, log, FROM_LOG); + Y.applyUpdate(doc, log, FROM_LOG); + } + for (const update of kept.unsent) { + if (whyNotApplied(update.id, update.payload)) + throw new Error("A change that was waiting to be sent is damaged."); + Y.applyUpdate(doc, update.payload, FROM_LOG); + } + for (const collection of collections) + logDoc + .getMap(collection) + .observeDeep((events) => this.stamp(collection, events)); + this.doc.destroy(); + this.logDoc.destroy(); + this.doc = doc; + this.logDoc = logDoc; + this.kept = kept; + this.stamps.clear(); + this.arrived = []; + } + + /** Notes which entries the log entry being applied made or changed. */ + private stamp(collection: Collection, events: Y.YEvent[]): void { + const from = this.arriving; + if (!from) return; + for (const event of events) { + const made = event.path.length === 0; + const ids = made + ? [...event.changes.keys.keys()] + : [String(event.path[0])]; + for (const id of ids) { + const key = `${collection}/${id}`; + const stamp = this.stamps.get(key) ?? {}; + if (made && event.changes.keys.get(id)?.action === "add") { + stamp.createdAt = from.loggedAt; + stamp.createdBy = from.author; + } + stamp.changedAt = from.loggedAt; + this.stamps.set(key, stamp); + } + } + } + + /** + * Deals with the next entries of the log: applies the ones that can be + * applied, writes down the ones that cannot, and makes the workspace follow. + */ + private async take(entries: LoggedUpdate[]): Promise { + const next = entries.filter((entry) => entry.sequence > this.kept.cursor); + if (!next.length || this.stopped) return; + await this.learnNames(next); + if (this.stopped) return; + + // From here until the workspace is asked to save, nothing waits. Whatever + // saves the workspace sees it before all of this or after all of it. + this.noteOwnChanges(); + const before = this.kept.joined ? readBoard(this.doc) : undefined; + if (before) this.stamps.clear(); + let logChanged = false; + for (const entry of next) { + const id = entry.id.toLowerCase(); + const mine = this.kept.unsent.findIndex((update) => update.id === id); + const why = this.unusable.has(id) + ? "failed" + : whyNotApplied(id, entry.payload); + if (why) { + this.kept.leftOut.push({ + sequence: entry.sequence, + id, + author: entry.author, + loggedAt: entry.loggedAt, + reason: why, + }); + this.kept.leftOut.splice(0, this.kept.leftOut.length - LEFT_OUT_KEPT); + } else if (!this.apply(entry, mine < 0)) { + // Applying threw, and may have left a document half changed. Both go + // back to what was last saved and the log is read again from there, + // this entry left out. + this.unusable.add(id); + this.mustReopen = true; + throw new StartAgain(); + } else logChanged = true; + // The log has it now, damaged or not. A damaged one is sent again as a repair. + if (mine >= 0) this.kept.unsent.splice(mine, 1); + this.logged.delete(id); + this.kept.cursor = entry.sequence; + } + if (!before) return; + + const after = readBoard(this.doc); + const follows = !sameBoard(before, after); + if (follows) { + const state = this.options.state(); + applyBoard(state, this.options.projectId, before, after, { + at: next[next.length - 1].loggedAt, + stampOf: (collection, id) => this.stamps.get(`${collection}/${id}`), + nameOf: (account) => this.names.get(account), + }); + // Read-only on a newer layout: `seen` stays, so changes made here are still found later. + if (!this.isNewer()) + this.kept.seen = boardOf(state, this.options.projectId); + } + await this.keep(logChanged, follows); + } + + /** Applies one entry inside a guard. Says whether it applied. */ + private apply(entry: LoggedUpdate, toBoth: boolean): boolean { + this.arriving = entry; + try { + Y.applyUpdate(this.logDoc, entry.payload, FROM_LOG); + // This computer's own update is in the second document since it was made. + if (toBoth) Y.applyUpdate(this.doc, entry.payload, FROM_LOG); + return true; + } catch { + return false; + } finally { + this.arriving = undefined; + } + } + + private async learnNames(entries: LoggedUpdate[]): Promise { + const unknown = entries.filter( + (entry) => + !this.names.has(entry.author) && !this.askedAbout.has(entry.author), + ); + if (!unknown.length) return; + for (const entry of unknown) this.askedAbout.add(entry.author); + await this.learn(); + } + + private async learn(): Promise { + try { + // Someone who has left the project keeps the name they had. + for (const [account, name] of await this.options.people()) + this.names.set(account, name); + } catch { + // A name is a nicety. The board does not wait for one. + } + } + + // ── This computer's own changes ────────────────────────────────────────── + + private isNewer(): boolean { + return (layoutOf(this.doc) ?? 0) > LAYOUT; + } + + /** Writes what changed on this computer into the document. Says whether there was something. */ + private noteOwnChanges(): boolean { + if (!this.kept.joined || this.isNewer()) return false; + const now = boardOf(this.options.state(), this.options.projectId); + if (sameBoard(this.kept.seen, now)) return false; + const made = this.recording(() => { + this.tooLarge += writeChanges(this.doc, this.kept.seen, now); + }); + this.kept.seen = now; + return made > 0; + } + + /** Runs changes to the document and queues each update they make. Says how many. */ + private recording(change: () => void): number { + const made: Uint8Array[] = []; + const listen = (update: Uint8Array, origin: unknown) => { + if (origin === LOCAL) made.push(update); + }; + this.doc.on("update", listen); + try { + change(); + } finally { + this.doc.off("update", listen); + } + for (const payload of made) + this.kept.unsent.push({ id: idOf(payload), payload }); + return made.length; + } + + /** + * Brings the board on this computer and the one in the log together, once. + * What only this computer has is added to the log. Where both have an entry, + * the log's is taken. + */ + private async join(confirmed: boolean): Promise { + const state = this.options.state(), + projectId = this.options.projectId; + // Nothing of this computer's is in the document before this, so it holds what the log holds. + const shared = readBoard(this.doc); + const own = onlyIn(boardOf(state, projectId), shared); + if (hasWork(shared) && hasWork(own) && !confirmed) { + this.choice = { + shared: Object.keys(shared.tasks).length, + added: Object.keys(own.tasks).length, + }; + return; + } + this.choice = undefined; + if (!this.isNewer()) + this.recording(() => { + for (const collection of WRITING_ORDER) + for (const [id, entry] of Object.entries(own[collection])) + this.tooLarge += writeEntryAlone(this.doc, collection, id, entry); + }); + const joined = readBoard(this.doc); + // What was just written is on this computer already. Only the rest is taken. + const written = onlyIn(joined, shared); + applyBoard(state, projectId, written, joined, { + at: new Date().toISOString(), + stampOf: (collection, id) => this.stamps.get(`${collection}/${id}`), + nameOf: (account) => this.names.get(account), + }); + this.stamps.clear(); + this.kept.joined = true; + if (!this.isNewer()) this.kept.seen = boardOf(state, projectId); + await this.keep(true, !sameBoard(written, joined)); + } + + /** After the log or this computer changed something: repair, send, and tell the window. */ + private async settle(): Promise { + if (this.stopped) return; + if ( + this.kept.joined && + !this.kept.unsent.length && + !this.isNewer() && + holdsMore(this.doc, this.logDoc) + ) + await this.repair(); + this.send(); + this.report(); + } + + /** + * This computer holds something the log does not, and has nothing waiting + * to be sent: an update of its own was damaged on the way into the log. It + * sends what is missing as a new update. + */ + private async repair(): Promise { + const payload = missingFrom(this.logDoc, this.doc); + if (payload.length > LARGEST_UPDATE) return; + const taken = new Set(this.kept.leftOut.map((entry) => entry.id)); + for (let again = 0; again < 8; again++) { + const id = idOf(payload, again); + if (taken.has(id) || this.repairs.has(id)) continue; + this.repairs.add(id); + this.kept.unsent.push({ id, payload }); + return this.store.save(this.toKeep(false)); + } + } + + // ── Sending ────────────────────────────────────────────────────────────── + + private send(): void { + this.sending ??= this.sendAll().finally(() => { + this.sending = undefined; + }); + } + + private async sendAll(): Promise { + for (let failures = 0; !this.stopped;) { + const call = nextCall( + this.kept.unsent.filter((update) => !this.logged.has(update.id)), + ); + if (!call.length) return; + try { + const receipts = await this.options.boards.append( + this.options.sharedProjectId, + call, + ); + failures = 0; + this.notSent = undefined; + await this.inTurn(() => this.sent(receipts)); + } catch (problem) { + if (this.stopped || this.isGone(problem)) return; + if (problem instanceof SharingRefused) { + // The service will not take it, now or later. Asking again changes nothing. + this.say("stopped", problem.message); + return; + } + this.notSent = + problem instanceof Error && problem.name.startsWith("Sharing") + ? problem.message + : CANNOT_SEND; + this.report(); + await this.pause(this.waitFor(++failures)); + } + } + } + + private async sent(receipts: UpdateReceipt[]): Promise { + let dropped = false; + for (const receipt of receipts) { + const id = receipt.id.toLowerCase(); + this.logged.add(id); + // Logged at a number this computer is already past: it will not come by again. + const at = this.kept.unsent.findIndex((update) => update.id === id); + if (at >= 0 && receipt.sequence <= this.kept.cursor) { + this.kept.unsent.splice(at, 1); + dropped = true; + } + } + if (dropped) await this.store.save(this.toKeep(false)); + this.report(); + } + + // ── Keeping ────────────────────────────────────────────────────────────── + + private toKeep(withLog: boolean): BoardToKeep { + return { + ...this.kept, + unsent: [...this.kept.unsent], + leftOut: [...this.kept.leftOut], + log: withLog ? Y.encodeStateAsUpdate(this.logDoc) : undefined, + }; + } + + /** + * Saves what is kept. When the workspace changed with it, the workspace is + * saved between writing this save and putting it in place, so that after a + * crash the two are either both as before or both as now. + */ + private async keep(log: boolean, workspace: boolean): Promise { + // Until the boards have been brought together nothing is kept: the log is + // read from its start again, which also gives every entry its author and time. + if (!this.kept.joined) return; + const link = this.link(); + if (!workspace || !link) return this.store.save(this.toKeep(log)); + link.applied = this.kept.applied = this.kept.applied + 1; + const kept = this.toKeep(log); + for (let failures = 1; ; failures++) { + try { + // Not after a wait: the workspace must be saved as it is right now. + await this.options.saveWorkspace(() => this.store.prepare(kept)); + break; + } catch (problem) { + if (this.stopped) return; + console.error("A change from the shared board was not saved:", problem); + this.say("stopped", CANNOT_SAVE); + await this.pause(this.waitFor(failures)); + if (this.stopped) return; + } + } + await this.store.commit(); + if (this.condition === "stopped" && this.detail === CANNOT_SAVE) + this.say("live"); + } + + // ── Small things ───────────────────────────────────────────────────────── + + private link(): SharedProjectLink | undefined { + return this.options + .state() + .sharedProjectLinks?.find( + (link) => + link.projectId === this.options.projectId && + link.sharedProjectId === this.options.sharedProjectId, + ); + } + + private inTurn(job: () => Promise | Result): Promise { + const turn = this.turns.then(job); + this.turns = turn.catch(() => {}); + return turn; + } + + private waitFor(failures: number): number { + return ( + this.options.waitBeforeRetry?.(failures) ?? + WAITS[Math.min(failures, WAITS.length) - 1] + ); + } + + private pause(ms: number): Promise { + if (this.stopped) return Promise.resolve(); + return new Promise((resolve) => { + const end = () => { + clearTimeout(timer); + this.pauses.delete(end); + resolve(); + }; + const timer = setTimeout(end, ms); + this.pauses.add(end); + }); + } + + /** The shared project is not there for this person any more. Sync ends; the board stays here. */ + private isGone(problem: unknown): boolean { + if ( + !(problem instanceof SharingRefused) || + problem.rule !== "no_such_project" + ) + return false; + this.stopped = true; + this.watching?.cancel(); + for (const end of [...this.pauses]) end(); + this.say("gone", refusalSentences.no_such_project); + return true; + } + + private failed(problem: unknown): void { + if (problem instanceof StartAgain) return this.say("starting"); + if ( + problem instanceof SharingUnavailable || + problem instanceof SharingRefused || + problem instanceof SharingSignedOut + ) + return this.say("offline", problem.message); + // Not something the service said: start again from what was last saved. + console.error("Board sync failed and starts again:", problem); + this.mustReopen = true; + this.say( + "offline", + "Board sync ran into a problem and is starting again. Nothing on this computer was lost.", + ); + } + + private say(condition: Condition, detail?: string): void { + this.condition = condition; + this.detail = detail; + this.report(); + } + + private report(): void { + const shown = JSON.stringify(this.status()); + if (shown === this.lastShown) return; + this.lastShown = shown; + this.options.shown(); + } +} diff --git a/src/shared.ts b/src/shared.ts index 87c4223..8415fa6 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -417,6 +417,8 @@ export interface TeamInvite { export interface AppState { /** Which shared project each local project's board belongs to, on this computer. */ sharedProjectLinks?: import("./sharing").SharedProjectLink[]; + /** How each connected board stands right now. Worked out again on every start. */ + sharedBoards?: import("./sharing").SharedBoardStatus[]; reviewWorkflows?: Record< string, import("./code-review").ReviewWorkflowBinding diff --git a/src/sharing.ts b/src/sharing.ts index 2a4a633..907b54c 100644 --- a/src/sharing.ts +++ b/src/sharing.ts @@ -51,6 +51,47 @@ export interface SharedProjectLink { /** The sharing service it lives on. */ service: string; connectedAt: string; + /** + * How many times the shared board has changed this workspace. Board sync + * keeps the same number beside the workspace file, and compares the two to + * tell whether a save was cut off. + */ + applied?: number; +} + +/** How the board of one connected project stands with the shared one. */ +export interface SharedBoardStatus { + projectId: string; + /** + * `starting`: reading what the shared board holds. + * `synced`: both hold the same. `sending`: changes made here are on their way. + * `offline`: the sharing service cannot be reached; changes wait on this computer. + * `choose`: both boards have work on them and nobody has said to keep both yet. + * `newer`: a newer MemCode laid the board out; it is shown here and not changed. + * `gone`: the shared project is not there for this person any more. + * `stopped`: sync cannot go on, and `detail` says why. + */ + state: + | "starting" + | "synced" + | "sending" + | "offline" + | "choose" + | "newer" + | "gone" + | "stopped"; + /** A sentence for the person, when there is something to say. */ + detail?: string; + /** Changes made on this computer that the shared board does not have yet. */ + waiting: number; + /** Changes in the shared board's log that could not be read and were left out. */ + leftOut: Array<{ by: string; on: string; count: number }>; + /** Changes are set aside until one they build on arrives. */ + setAside: boolean; + /** Values too large for the sharing service. They stay on this computer. */ + tooLarge: number; + /** For `choose`: how many tasks each board has that the other lacks. */ + choice?: { shared: number; added: number }; } export type SharingOverview = diff --git a/tests/sharing-board-sync.test.ts b/tests/sharing-board-sync.test.ts new file mode 100644 index 0000000..6c67b17 --- /dev/null +++ b/tests/sharing-board-sync.test.ts @@ -0,0 +1,422 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readdir } from "node:fs/promises"; +import { join } from "node:path"; +import * as Y from "yjs"; +import { idOf, whyNotApplied } from "../runtime/sharing/board/updates"; +import { + agree, + computer, + giveWork, + task, + until, + type Computer, +} from "./support/board-computers"; +import { boardSyncScenarios } from "./support/board-sync-scenarios"; +import { startStandInMemsync } from "./support/memsync-stand-in"; +import { + cast, + signedInTo, + type SharingWorld, +} from "./support/projects-api-scenarios"; + +boardSyncScenarios("stand-in sharing service", async () => { + const service = await startStandInMemsync(); + return { + address: service.address, + tokenFor: (person) => service.tokenFor(person), + close: () => service.close(), + }; +}); + +// What follows needs a sharing service that can be made to misbehave. + +/** The same person on a Mac with a board and on a PC without one, against the stand-in. */ +async function standIn(context: test.TestContext) { + const service = await startStandInMemsync(); + const world: SharingWorld = { + address: service.address, + tokenFor: (person) => service.tokenFor(person), + close: () => service.close(), + }; + const people = cast(); + const alex = signedInTo(world, people.alex); + const shared = await alex.website.startProject("Website"); + const mac = await computer(world, people.alex, "mac"); + const pc = await computer(world, people.alex, "pc"); + giveWork(mac.state, mac.projectId); + await mac.save(); + context.after(async () => { + await mac.close(); + await pc.close(); + alex.close(); + await service.close(); + }); + return { service, world, people, alex, shared, mac, pc }; +} +const find = (on: Computer, id: string) => + on.state.tasks.find((one) => one.id === id)!; +const quiet = (context: test.TestContext) => + context.mock.method(console, "error", () => {}); +/** The log as a document, and the entry that first held an id. */ +function logAsDocument(log: Array<{ sequence: number; payload: Uint8Array }>) { + const doc = new Y.Doc(); + const madeAt = new Map(); + for (const entry of log) { + Y.applyUpdate(doc, entry.payload); + for (const collection of ["tasks", "goals", "comments"] as const) + for (const id of doc.getMap(collection).keys()) + if (!madeAt.has(id)) madeAt.set(id, entry.sequence); + } + return { doc, madeAt }; +} + +test("a call whose answer is lost is made again, and nothing is in the log twice", async (context) => { + const { service, shared, mac, pc } = await standIn(context); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + const logged = service.boards.log(shared).length; + + service.boards.loseNextReceipts(); + await mac.edit(() => void (find(mac, "task-1").title = "Sent, answer lost")); + await agree(mac, pc); + assert.equal(find(pc, "task-1").title, "Sent, answer lost"); + assert.equal(service.boards.log(shared).length, logged + 1); + assert.equal(mac.status().waiting, 0); +}); + +test("a whole board goes to the service in calls of at most a hundred updates, one entry an update", async (context) => { + const { service, shared, mac, pc } = await standIn(context); + for (let at = 10; at < 260; at++) + mac.state.tasks.push( + task(mac.projectId, `task-${at}`, { + description: `What task ${at} is about. `.repeat(20), + }), + ); + await mac.save(); + mac.connect(shared); + await mac.synced(); + // 252 tasks, a goal, a cycle, a comment, two lanes, a field and a view. + const entries = 252 + 1 + 1 + 1 + 2 + 1 + 1; + assert.equal(service.boards.log(shared).length, entries); + assert.ok( + mac.appends.every((sent) => sent <= 100), + String(mac.appends), + ); + assert.ok(mac.appends.length >= 3); + assert.ok(mac.appendBytes.every((bytes) => bytes <= 3 * 1024 * 1024)); + + pc.connect(shared); + await agree(mac, pc); + assert.equal( + pc.state.tasks.filter((one) => one.projectId === pc.projectId).length, + 252, + ); + // The PC took the board in a few saves, not one for every entry. + assert.ok(pc.saves < 20, String(pc.saves)); +}); + +test("an update that cannot be read is left out and said so, and the log goes on being read", async (context) => { + const { service, people, shared, mac, pc } = await standIn(context); + mac.connect(shared); + await mac.synced(); + // A fault in storage, after the Mac has read its own update back whole. + const log = service.boards.log(shared); + const damaged = logAsDocument(log).madeAt.get("task-2")!; + service.boards.damage(shared, damaged, Uint8Array.of(0xff, 0xff, 0xff, 7)); + + pc.connect(shared); + await pc.synced(); + assert.equal(find(pc, "task-2"), undefined); + assert.equal(find(pc, "task-1").title, "Export as CSV"); + assert.deepEqual(pc.status().leftOut, [ + { + by: people.alex.name, + on: new Date(log[damaged - 1].loggedAt).toISOString().slice(0, 10), + count: 1, + }, + ]); + // What the Mac wrote after it in the same run builds on it, and is set aside. + assert.deepEqual(pc.state.storyComments, []); + assert.equal(pc.status().setAside, true); + + // The Mac is started again. What it writes now does not build on the lost update. + await mac.quit(); + mac.reopen(); + await mac.synced(); + await mac.edit(() => { + find(mac, "task-2").title = "Changed on the Mac"; + find(mac, "task-1").title = "Also changed"; + }); + await until( + () => find(pc, "task-1").title === "Also changed", + "the PC to take what it can", + ); + assert.equal(find(pc, "task-2"), undefined); + assert.equal(pc.status().state, "synced"); + + // The entry is not asked for again after a restart: it was dealt with. + await pc.quit(); + pc.reads.length = 0; + pc.reopen(); + await pc.synced(); + assert.equal(pc.reads[0], service.boards.log(shared).length); + assert.equal(pc.status().leftOut[0].count, 1); +}); + +test("an update of this computer's own that the log holds damaged is sent again, and what waited for it takes effect", async (context) => { + const { service, shared, mac, pc } = await standIn(context); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + + service.boards.damageNextLogged(); + await mac.edit((state) => { + state.tasks.push( + task(mac.projectId, "task-5", { title: "Damaged on the way" }), + ); + }); + // Changes that build on it follow at once. + await mac.edit(() => void (find(mac, "task-5").priority = "high")); + await mac.edit(() => void (find(mac, "task-5").title = "Arrived after all")); + await agree(mac, pc); + assert.equal(find(pc, "task-5").title, "Arrived after all"); + assert.equal(find(pc, "task-5").priority, "high"); + assert.equal(pc.status().setAside, false); + // Both say that one entry of the log could not be read. + assert.equal(pc.status().leftOut[0].count, 1); + assert.equal(mac.status().leftOut[0].count, 1); + assert.equal(mac.status().waiting, 0); + + // The repair is sent once. The Mac is not still sending it. + const logged = service.boards.log(shared).length; + await mac.edit(() => void (find(mac, "task-1").estimate = 5)); + await agree(mac, pc); + assert.equal(service.boards.log(shared).length, logged + 1); +}); + +test("an update that reads as one and still cannot be applied is left out, and sync goes on from what was saved", async (context) => { + quiet(context); + const { service, alex, shared, mac, pc } = await standIn(context); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + + // Someone's MemCode writes bytes that read as an update and cannot be applied. + const { doc } = logAsDocument(service.boards.log(shared)); + doc.clientID = 20261121; + let real: Uint8Array | undefined; + doc.on("update", (update: Uint8Array) => void (real = update)); + const made = new Y.Map(); + doc.getMap("tasks").set("task-made-elsewhere", made); + made.set("title", "Made by another MemCode"); + assert.ok(real); + let poison: Uint8Array | undefined; + for (let bit = 0; bit < real.length * 8 && !poison; bit++) { + const flipped = Uint8Array.from(real); + flipped[bit >> 3] ^= 1 << (bit & 7); + if (whyNotApplied(idOf(flipped), flipped)) continue; + const reader = logAsDocument(service.boards.log(shared)).doc; + try { + Y.applyUpdate(reader, flipped); + } catch { + poison = flipped; + } + } + assert.ok(poison, "no bytes found that read as an update and do not apply"); + + pc.reads.length = 0; + const before = service.boards.log(shared).length; + await alex.boards.append(shared, [{ id: idOf(poison), payload: poison }]); + await mac.edit(() => void (find(mac, "task-1").title = "After the bad one")); + await agree(mac, pc); + assert.equal(find(pc, "task-1").title, "After the bad one"); + for (const one of [mac, pc]) { + assert.equal(one.status().leftOut[0].count, 1); + assert.equal(one.status().state, "synced"); + } + // The PC went back to what it had saved and read the log again from there. + assert.ok(pc.reads.includes(before), String(pc.reads)); + assert.deepEqual(pc.board(), mac.board()); +}); + +test("a board laid out by a newer MemCode is shown and not changed", async (context) => { + const { service, alex, shared, mac } = await standIn(context); + mac.connect(shared); + await mac.synced(); + + // A newer MemCode changes a task and says the layout is 2. + const { doc } = logAsDocument(service.boards.log(shared)); + const made: Uint8Array[] = []; + doc.on("update", (update: Uint8Array) => void made.push(update)); + doc.transact(() => { + doc.getMap("meta").set("layout", 2); + (doc.getMap("tasks").get("task-1") as Y.Map).set( + "title", + "Renamed by a newer MemCode", + ); + }); + await alex.boards.append( + shared, + made.map((payload) => ({ id: idOf(payload), payload })), + ); + await until(() => mac.status().state === "newer", "the Mac to notice"); + assert.match(mac.status().detail ?? "", /newer MemCode/); + assert.equal(find(mac, "task-1").title, "Renamed by a newer MemCode"); + + const sent = mac.appends.length; + await mac.edit( + () => void (find(mac, "task-2").title = "Changed on an old MemCode"), + ); + assert.equal(mac.appends.length, sent); + assert.equal(mac.status().waiting, 0); + assert.equal(mac.status().state, "newer"); + // The change is still on this computer. + assert.equal(find(mac, "task-2").title, "Changed on an old MemCode"); +}); + +test("MemCode stopped before the workspace file was written: the change from the log is applied once, after the restart", async (context) => { + quiet(context); + const { shared, mac, pc } = await standIn(context); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + const appliedBefore = pc.file().sharedProjectLinks![0].applied; + + pc.failingSaves = Infinity; + await mac.edit((state) => { + find(mac, "task-1").description = "Line one.\nLine two.\nLine three."; + state.tasks.push( + task(mac.projectId, "task-4", { title: "Arrives during the crash" }), + ); + }); + await until(() => pc.status().state === "stopped", "the PC to fail to save"); + assert.match(pc.status().detail ?? "", /could not be saved/); + await pc.quit(); + // The workspace file is as it was. Board sync's save for the change is beside it, not in place. + assert.equal(pc.file().sharedProjectLinks![0].applied, appliedBefore); + assert.ok( + (await readdir(join(pc.folder, "board"))).includes("sync.json.next"), + ); + + pc.failingSaves = 0; + pc.appends.length = 0; + pc.reopen(); + await agree(mac, pc); + assert.equal( + find(pc, "task-1").description, + "Line one.\nLine two.\nLine three.", + ); + assert.equal(find(pc, "task-4").title, "Arrives during the crash"); + // Nothing of it was taken for a change made on the PC. + assert.deepEqual(pc.appends, []); + assert.deepEqual((await readdir(join(pc.folder, "board"))).sort(), [ + "log.bin", + "sync.json", + ]); +}); + +test("MemCode stopped after the workspace file was written: the change is not applied again and not sent back", async (context) => { + quiet(context); + const { service, shared, mac, pc } = await standIn(context); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + + // The file is written, and MemCode is gone before board sync hears of it. + pc.afterNextSave = () => { + pc.failingSaves = Infinity; + throw new Error("MemCode was stopped"); + }; + await mac.edit((state) => { + find(mac, "task-1").description = "Line one.\nLine two.\nLine three."; + state.tasks.push( + task(mac.projectId, "task-4", { title: "Arrives during the crash" }), + ); + }); + await until(() => pc.status().state === "stopped", "the PC to stop"); + await pc.quit(); + assert.equal( + pc.file().tasks.find((one) => one.id === "task-4")?.title, + "Arrives during the crash", + ); + assert.ok( + (await readdir(join(pc.folder, "board"))).includes("sync.json.next"), + ); + + pc.failingSaves = 0; + pc.appends.length = 0; + pc.reads.length = 0; + const logged = service.boards.log(shared).length; + pc.reopen(); + await agree(mac, pc); + assert.equal( + find(pc, "task-1").description, + "Line one.\nLine two.\nLine three.", + ); + // The PC knew it had dealt with the whole log, and sent nothing. + assert.equal(pc.reads[0], logged); + assert.deepEqual(pc.appends, []); + assert.equal(service.boards.log(shared).length, logged); +}); + +test("while the workspace cannot be saved, changes from the shared board wait, and are taken up when it can", async (context) => { + quiet(context); + const { shared, mac, pc } = await standIn(context); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + + pc.failingSaves = 4; + await mac.edit( + () => void (find(mac, "task-2").title = "While the disk was full"), + ); + await until(() => pc.status().state === "stopped", "the PC to say so"); + await agree(mac, pc); + assert.equal( + pc.file().tasks.find((one) => one.id === "task-2")?.title, + "While the disk was full", + ); + assert.equal(pc.status().detail, undefined); +}); + +test("a stream that is cut is started again after the last entry that was dealt with", async (context) => { + const { service, shared, mac, pc } = await standIn(context); + mac.connect(shared); + await mac.synced(); + pc.connect(shared); + await agree(mac, pc); + const logged = service.boards.log(shared).length; + assert.deepEqual(pc.watches, [logged]); + + await until(() => service.boards.watching === 2, "both to be listening"); + service.boards.cutWatchers(); + await until( + () => pc.watches.length === 2 && mac.watches.length === 2, + "both to listen again", + ); + assert.equal(pc.watches[1], logged); + await mac.edit(() => void (find(mac, "task-1").title = "After the cut")); + await agree(mac, pc); + assert.equal(find(pc, "task-1").title, "After the cut"); +}); + +test("a value too large for the sharing service stays on this computer, and the rest of the task is shared", async (context) => { + const { shared, mac, pc } = await standIn(context); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + await mac.edit(() => { + find(mac, "task-2").title = "Shared all the same"; + find(mac, "task-2").category = "c".repeat(1024 * 1024); + }); + await until( + () => find(pc, "task-2").title === "Shared all the same", + "the PC", + ); + assert.equal(mac.status().tooLarge, 1); + assert.equal(find(pc, "task-2").category, "Work"); + await mac.synced(); + await pc.synced(); +}); diff --git a/tests/sharing-real-memsync.test.ts b/tests/sharing-real-memsync.test.ts index d8ef64d..1c06104 100644 --- a/tests/sharing-real-memsync.test.ts +++ b/tests/sharing-real-memsync.test.ts @@ -4,6 +4,7 @@ import { grpcChannel } from "../runtime/sharing/memsync/grpc"; import { SharingUnavailable } from "../runtime/sharing/problems"; import { refusalRules } from "../src/sharing-refusals"; import { actingAs } from "./support/memsync-owner"; +import { boardSyncScenarios } from "./support/board-sync-scenarios"; import { boardsApiScenarios } from "./support/boards-api-scenarios"; import { cast, @@ -40,6 +41,9 @@ projectsApiScenarios( boardsApiScenarios("real memsync-server", async () => worldOn(await server()), { skip: realMemsyncMissing, }); +boardSyncScenarios("real memsync-server", async () => worldOn(await server()), { + skip: realMemsyncMissing, +}); test( "real memsync-server: a token it has no reason to trust is turned away", diff --git a/tests/support/board-computers.ts b/tests/support/board-computers.ts new file mode 100644 index 0000000..84f952c --- /dev/null +++ b/tests/support/board-computers.ts @@ -0,0 +1,371 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { initialState } from "../../src/seed"; +import type { AppState, WorkItem } from "../../src/shared"; +import type { SharedBoardStatus } from "../../src/sharing"; +import { boardOf } from "../../runtime/sharing/board/board"; +import { BoardSync } from "../../runtime/sharing/board/sync"; +import type { BoardsApi } from "../../runtime/sharing/memsync/boards-api"; +import type { GrpcStream } from "../../runtime/sharing/memsync/grpc"; +import { SharingUnavailable } from "../../runtime/sharing/problems"; +import type { StandInPerson } from "./memsync-stand-in"; +import { signedInTo, type SharingWorld } from "./projects-api-scenarios"; + +const at = "2026-11-21T12:00:00.000Z"; + +export async function until( + isTrue: () => boolean, + what: string | (() => string), +) { + const deadline = Date.now() + 8000; + while (!isTrue()) { + if (Date.now() > deadline) + assert.fail( + `still waiting for ${typeof what === "string" ? what : what()}`, + ); + await new Promise((resolve) => setTimeout(resolve, 5)); + } +} + +export const task = ( + projectId: string, + id: string, + changes: Partial = {}, +): WorkItem => ({ + id, + identifier: `MC-${id.replace(/\D/g, "").padStart(3, "0") || "001"}`, + projectId, + title: `Task ${id}`, + description: "", + stage: "planned", + statusId: `${projectId}:planned`, + priority: "medium", + category: "Work", + kind: "feature", + harness: "claude", + assignment: "auto", + epicId: null, + checklist: [], + messages: [ + { id: `private-${id}`, role: "tool", text: "PRIVATE TOOL OUTPUT", at }, + ], + run: { state: "idle", workspace: "/private/checkout" }, + createdAt: at, + updatedAt: at, + ...changes, +}); + +/** Puts a small board with one of everything on a computer's project. */ +export function giveWork(state: AppState, projectId: string): void { + state.epics.push({ + id: "goal-1", + projectId, + identifier: "EP-01", + title: "Customers can export reports", + description: "As CSV and as PDF.", + phase: "now", + color: "mint", + order: 0, + branch: "epic/ep-01-reports", + baseBranch: "dev", + }); + state.cycles.push({ + id: "cycle-1", + projectId, + name: "Week 47", + goal: "Ship the export", + startDate: "2026-11-16", + endDate: "2026-11-22", + timeZone: "Europe/Copenhagen", + state: "active", + capacity: 20, + calendar: "weekdays", + createdAt: at, + startedAt: at, + snapshots: [], + }); + state.tasks.push( + task(projectId, "task-1", { + title: "Export as CSV", + description: "Line one.\nLine two.", + stage: "working", + statusId: `${projectId}:working`, + priority: "high", + epicId: "goal-1", + cycleId: "cycle-1", + estimate: 3, + labels: ["urgent"], + scope: ["src/export"], + checklist: [ + { id: "step-1", text: "Read the code", done: true }, + { id: "step-2", text: "Write it", done: false }, + ], + customFields: { "field-1": "blue" }, + }), + task(projectId, "task-2", { title: "Export as PDF", epicId: "goal-1" }), + ); + (state.storyComments ??= []).push({ + id: "comment-1", + taskId: "task-1", + text: "Looks right to me.", + author: { id: "local-owner", name: "You", source: "local" }, + createdAt: at, + updatedAt: at, + }); + state.workflowStates.push( + { + id: `${projectId}:planned`, + projectId, + name: "Planned", + stage: "planned", + color: "#98a59d", + order: 1, + }, + { + id: `${projectId}:working`, + projectId, + name: "In progress", + stage: "working", + color: "#18c8b5", + order: 2, + }, + ); + state.customFields.push({ + id: "field-1", + projectId, + name: "Colour", + type: "select", + options: ["blue", "green"], + }); + state.savedViews.push({ + id: "view-1", + projectId, + name: "Urgent first", + mode: "board", + groupBy: "status", + sortBy: "priority", + filters: { labels: ["urgent"] } as never, + }); +} + +export interface ComputerOptions { + /** A folder to keep board sync in, when the test wants to look at it or reuse it. */ + folder?: string; + people?: StandInPerson[]; +} + +/** + * One computer running MemCode: a workspace in memory, the workspace file, + * and board sync for one local project, signed in as one person. + */ +export async function computer( + world: SharingWorld, + person: StandInPerson, + name: string, + options: ComputerOptions = {}, +) { + const folder = + options.folder ?? (await mkdtemp(join(tmpdir(), `memcode-${name}-`))); + const projectId = `${name}-project`; + const signedIn = signedInTo(world, person); + const streams = new Set(); + let state: AppState = initialState(); + state.projects.push({ + id: projectId, + name, + description: "", + path: `/work/${name}`, + branch: "main", + analysis: "idle", + createdAt: at, + }); + state.activeProjectId = projectId; + state.storyComments = []; + let file = JSON.stringify(state); + let writes: Promise = Promise.resolve(); + let sync: BoardSync | undefined; + let sharedProjectId = ""; + const unreachable = () => + new SharingUnavailable("The sharing service cannot be reached."); + + const self = { + name, + projectId, + folder, + get state() { + return state; + }, + get sync() { + return sync!; + }, + isOffline: false, + /** How many of the next saves of the workspace fail, as on a full disk. */ + failingSaves: 0, + /** Run after the workspace file was written and before board sync hears of it. */ + afterNextSave: undefined as (() => void) | undefined, + saves: 0, + shown: 0, + appends: [] as number[], + appendBytes: [] as number[], + reads: [] as number[], + watches: [] as number[], + /** What the workspace file holds. */ + file: (): AppState => JSON.parse(file), + board: () => boardOf(state, projectId), + status: (): SharedBoardStatus => sync!.status(), + + /** Saves the workspace as the runtime does: as it is now, written in turn. */ + save(first?: () => Promise): Promise { + const snapshot = JSON.stringify(state); + const pending = writes + .catch(() => {}) + .then(async () => { + await first?.(); + if (self.failingSaves > 0) { + self.failingSaves--; + throw new Error("No space left on device"); + } + file = snapshot; + self.saves++; + const then = self.afterNextSave; + self.afterNextSave = undefined; + then?.(); + }); + writes = pending; + return pending; + }, + /** A change made in the app: the workspace changes, is saved, and sync looks at it. */ + async edit(change: (state: AppState) => void): Promise { + change(state); + await self.save(); + await sync?.capture(); + }, + /** A change made while board sync is not running, as when signed out. */ + async editUnseen(change: (state: AppState) => void): Promise { + change(state); + await self.save(); + }, + /** Connects the project to a shared one and starts sync. */ + connect(shared: string): void { + sharedProjectId = shared; + (state.sharedProjectLinks ??= []).push({ + projectId, + sharedProjectId: shared, + sharedProjectName: "Shared", + accountId: person.accountId, + service: world.address.href, + connectedAt: at, + }); + file = JSON.stringify(state); + self.start(); + }, + start(): void { + const boards: BoardsApi = { + async append(project, updates) { + if (self.isOffline) throw unreachable(); + self.appends.push(updates.length); + self.appendBytes.push( + updates.reduce((sum, update) => sum + update.payload.length, 0), + ); + return signedIn.boards.append(project, updates); + }, + async readAfter(project, sequence) { + if (self.isOffline) throw unreachable(); + self.reads.push(sequence); + return signedIn.boards.readAfter(project, sequence); + }, + watchAfter(project, sequence, onUpdate) { + if (self.isOffline) + return { finished: Promise.reject(unreachable()), cancel() {} }; + self.watches.push(sequence); + const stream = signedIn.boards.watchAfter( + project, + sequence, + onUpdate, + ); + streams.add(stream); + return stream; + }, + }; + sync = new BoardSync({ + projectId, + sharedProjectId, + folder: join(folder, "board"), + state: () => state, + boards, + saveWorkspace: (first) => self.save(first), + shown: () => void self.shown++, + people: async () => + new Map( + (options.people ?? [person]).map((one) => [ + one.accountId, + one.name, + ]), + ), + waitBeforeRetry: () => 15, + }); + sync.start(); + }, + goOffline(): void { + self.isOffline = true; + for (const stream of streams) stream.cancel(); + streams.clear(); + }, + comeBack(): void { + self.isOffline = false; + }, + /** MemCode is quit: sync ends, and what is in memory is gone. */ + async quit(): Promise { + await sync?.stop(); + sync = undefined; + streams.clear(); + }, + /** MemCode is started again: the workspace is what the file holds. */ + reopen(): void { + state = JSON.parse(file); + self.start(); + }, + async synced(): Promise { + await until( + () => sync!.status().state === "synced", + () => `${name} to be in sync: ${JSON.stringify(sync!.status())}`, + ); + }, + async close(): Promise { + await self.quit(); + signedIn.close(); + if (!options.folder) await rm(folder, { recursive: true, force: true }); + }, + }; + return self; +} +export type Computer = Awaited>; + +/** Waits until two computers are in sync and show the same board. */ +export async function agree(left: Computer, right: Computer): Promise { + const same = () => { + try { + assert.deepEqual(left.board(), right.board()); + return true; + } catch { + return false; + } + }; + await until( + () => + left.status().state === "synced" && + right.status().state === "synced" && + same(), + () => + `${left.name} and ${right.name} to agree: ${JSON.stringify([left.status(), right.status()])}`, + ); + // Nothing is still on its way to a workspace file. + await left.sync.capture(); + await right.sync.capture(); + assert.deepEqual(left.board(), right.board()); +} + +export const newId = () => randomUUID(); diff --git a/tests/support/board-sync-scenarios.ts b/tests/support/board-sync-scenarios.ts new file mode 100644 index 0000000..0db3a0a --- /dev/null +++ b/tests/support/board-sync-scenarios.ts @@ -0,0 +1,400 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + agree, + computer, + giveWork, + task, + until, + type Computer, +} from "./board-computers"; +import { cast, signedInTo, type SharingWorld } from "./projects-api-scenarios"; + +const find = (on: Computer, id: string) => + on.state.tasks.find((one) => one.id === id)!; + +/** What board sync must do against any sharing service that follows the contract. */ +export function boardSyncScenarios( + where: string, + open: () => Promise, + options: { skip?: string | false } = {}, +) { + const scenario = ( + name: string, + run: ( + world: SharingWorld, + later: (close: () => unknown) => void, + ) => Promise, + ) => + test(`${where}: ${name}`, { skip: options.skip }, async () => { + const world = await open(); + const closing: Array<() => unknown> = []; + try { + await run(world, (close) => closing.push(close)); + } finally { + for (const close of closing.reverse()) await close(); + await world.close(); + } + }); + + /** The same person on a Mac that has a board and a PC that has none, both connected. */ + async function twoComputers( + world: SharingWorld, + later: (close: () => unknown) => void, + ) { + const people = cast(); + const website = signedInTo(world, people.alex); + later(() => website.close()); + const shared = await website.website.startProject("Website"); + const mac = await computer(world, people.alex, "mac"); + later(() => mac.close()); + const pc = await computer(world, people.alex, "pc"); + later(() => pc.close()); + giveWork(mac.state, mac.projectId); + await mac.save(); + return { people, shared, mac, pc, website }; + } + + scenario( + "a board that exists on one computer is written out, and the person's second computer takes it", + async (world, later) => { + const { people, shared, mac, pc, website } = await twoComputers( + world, + later, + ); + const before = structuredClone(mac.board()); + mac.connect(shared); + await mac.synced(); + // Writing the board out changes nothing on the computer it came from. + assert.deepEqual(mac.board(), before); + assert.equal(mac.status().waiting, 0); + + pc.connect(shared); + await agree(mac, pc); + assert.deepEqual(pc.board(), before); + + // What stays on a computer never left the Mac. + const taken = find(pc, "task-1"); + assert.equal(taken.projectId, pc.projectId); + assert.equal(taken.statusId, "pc-project:working"); + assert.equal(taken.run.state, "idle"); + assert.equal(taken.run.workspace, undefined); + assert.doesNotMatch(JSON.stringify(pc.state), /PRIVATE|\/private\//); + // The brief a worker on the PC would start from. + assert.equal(taken.messages[0].text, "Line one.\nLine two."); + + // Who and when come from the log, not from the Mac's own clock or name. + const logged = await website.boards.readAfter(shared, 0); + const times = logged.map((update) => update.loggedAt); + assert.ok(times.includes(taken.createdAt), taken.createdAt); + const [comment] = pc.state.storyComments!; + assert.deepEqual(comment.author, { + id: people.alex.accountId, + name: people.alex.name, + source: "memtrace", + }); + assert.ok(times.includes(comment.createdAt)); + + // The PC's workspace file holds the board, and the PC sent nothing of its own. + assert.deepEqual( + pc + .file() + .tasks.filter((one) => one.projectId === pc.projectId) + .map((one) => one.id) + .sort(), + ["task-1", "task-2"], + ); + assert.deepEqual(pc.appends, []); + assert.equal(new Set(logged.map((update) => update.author)).size, 1); + }, + ); + + scenario( + "a change on either computer shows on the other, and changes to different parts of one task both stay", + async (world, later) => { + const { shared, mac, pc } = await twoComputers(world, later); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + + await pc.edit((state) => { + const one = state.tasks.find((each) => each.id === "task-1")!; + one.stage = "review"; + one.statusId = "pc-project:review"; + one.checklist[1].done = true; + }); + await until( + () => find(mac, "task-1").stage === "review", + "the Mac to see the move made on the PC", + ); + assert.equal(find(mac, "task-1").statusId, "mac-project:review"); + assert.equal(find(mac, "task-1").checklist[1].done, true); + // The Mac's own parts of the task were not touched. + assert.equal(find(mac, "task-1").messages[0].text, "PRIVATE TOOL OUTPUT"); + assert.equal(find(mac, "task-1").run.workspace, "/private/checkout"); + + // Both change the same task at the same moment, in different places. + await Promise.all([ + mac.edit((state) => { + const one = state.tasks.find((each) => each.id === "task-1")!; + one.title = "Export as CSV, with a header row"; + one.description = "Line zero.\nLine one.\nLine two."; + one.labels = ["urgent", "export"]; + }), + pc.edit((state) => { + const one = state.tasks.find((each) => each.id === "task-1")!; + one.priority = "low"; + one.description = "Line one.\nLine two.\nLine three."; + one.labels = ["urgent", "customer"]; + }), + ]); + await agree(mac, pc); + const merged = find(pc, "task-1"); + assert.equal(merged.title, "Export as CSV, with a header row"); + assert.equal(merged.priority, "low"); + assert.equal( + merged.description, + "Line zero.\nLine one.\nLine two.\nLine three.", + ); + assert.deepEqual([...merged.labels!].sort(), [ + "customer", + "export", + "urgent", + ]); + + // A new task, a comment and a deletion travel too. + await pc.edit((state) => { + state.tasks.push( + task(pc.projectId, "task-3", { title: "Made on the PC" }), + ); + state.storyComments!.push({ + id: "comment-2", + taskId: "task-3", + text: "Started here, to be continued on the Mac.", + author: { id: "local-owner", name: "You", source: "local" }, + createdAt: "2026-11-21T13:00:00.000Z", + updatedAt: "2026-11-21T13:00:00.000Z", + }); + state.tasks = state.tasks.filter((each) => each.id !== "task-2"); + }); + await agree(mac, pc); + assert.equal(find(mac, "task-3").title, "Made on the PC"); + assert.equal(find(mac, "task-2"), undefined); + assert.equal( + mac.state.storyComments!.find((each) => each.id === "comment-2")?.text, + "Started here, to be continued on the Mac.", + ); + }, + ); + + scenario( + "changes made while the service cannot be reached wait, survive a restart, and are sent when it is back", + async (world, later) => { + const { shared, mac, pc } = await twoComputers(world, later); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + + pc.goOffline(); + await until(() => pc.status().state === "offline", "the PC to notice"); + await pc.edit((state) => { + find(pc, "task-2").title = "Export as PDF, landscape"; + state.tasks.push( + task(pc.projectId, "task-7", { title: "Made offline" }), + ); + }); + assert.equal(pc.status().state, "offline"); + assert.ok(pc.status().waiting > 0); + assert.match(pc.status().detail ?? "", /cannot be reached/); + + // Meanwhile the Mac goes on. + await mac.edit(() => void (find(mac, "task-1").priority = "low")); + await mac.synced(); + + // MemCode on the PC is quit and started again, still offline. + await pc.quit(); + pc.reopen(); + await until(() => pc.status().state === "offline", "the PC, restarted"); + assert.ok(pc.status().waiting > 0); + assert.equal(find(pc, "task-7").title, "Made offline"); + + pc.comeBack(); + await agree(mac, pc); + assert.equal(find(mac, "task-2").title, "Export as PDF, landscape"); + assert.equal(find(mac, "task-7").title, "Made offline"); + assert.equal(find(pc, "task-1").priority, "low"); + assert.equal(pc.status().waiting, 0); + }, + ); + + scenario( + "a computer that is started again goes on from where it stopped, and sends nothing twice", + async (world, later) => { + const { shared, mac, pc, website } = await twoComputers(world, later); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + const logged = (await website.boards.readAfter(shared, 0)).length; + assert.ok(logged > 0); + + await pc.quit(); + await mac.edit( + () => void (find(mac, "task-2").title = "Changed meanwhile"), + ); + await mac.synced(); + pc.reads.length = 0; + pc.appends.length = 0; + pc.reopen(); + await agree(mac, pc); + assert.equal(find(pc, "task-2").title, "Changed meanwhile"); + // It asked for what came after the last entry it had dealt with, not for the whole log. + assert.equal(pc.reads[0], logged); + assert.deepEqual(pc.appends, []); + assert.equal( + (await website.boards.readAfter(shared, 0)).length, + logged + 1, + ); + }, + ); + + scenario( + "changes made while board sync was not running are found and sent at the next start", + async (world, later) => { + const { shared, mac, pc } = await twoComputers(world, later); + mac.connect(shared); + pc.connect(shared); + await agree(mac, pc); + + // Signed out on the PC, say: MemCode runs, sync does not. + await pc.quit(); + await pc.editUnseen((state) => { + find(pc, "task-1").estimate = 8; + state.tasks.push(task(pc.projectId, "task-9", { title: "While away" })); + }); + await mac.edit( + () => void (find(mac, "task-1").title = "Renamed on the Mac"), + ); + pc.reopen(); + await agree(mac, pc); + assert.equal(find(mac, "task-1").estimate, 8); + assert.equal(find(mac, "task-9").title, "While away"); + assert.equal(find(pc, "task-1").title, "Renamed on the Mac"); + }, + ); + + scenario( + "two boards that both have work are left as they are until the person says to keep both", + async (world, later) => { + const people = cast(); + const alex = signedInTo(world, people.alex); + later(() => alex.close()); + const dana = signedInTo(world, people.dana); + later(() => dana.close()); + const shared = await alex.website.startProject("Website"); + const invitation = await alex.website.invite(shared, people.dana.email!); + await dana.projects.acceptInvitation(shared, invitation); + const everyone = [people.alex, people.dana]; + + const mac = await computer(world, people.alex, "mac", { + people: everyone, + }); + later(() => mac.close()); + giveWork(mac.state, mac.projectId); + await mac.save(); + mac.connect(shared); + await mac.synced(); + + const laptop = await computer(world, people.dana, "laptop", { + people: everyone, + }); + later(() => laptop.close()); + laptop.state.tasks.push( + task(laptop.projectId, "dana-1", { + identifier: "MC-001", + title: "Dana's own task", + }), + task(laptop.projectId, "dana-2", { title: "Dana's second" }), + ); + await laptop.save(); + const mine = structuredClone(laptop.board()); + laptop.connect(shared); + await until( + () => laptop.status().state === "choose", + "the question whether to keep both", + ); + assert.deepEqual(laptop.status().choice, { shared: 2, added: 2 }); + // Nothing was added to either board, and nothing was sent. + assert.deepEqual(laptop.board(), mine); + assert.deepEqual(laptop.appends, []); + + // The question is still there after a restart. + await laptop.quit(); + laptop.reopen(); + await until( + () => laptop.status().state === "choose", + "the question again", + ); + assert.deepEqual(laptop.board(), mine); + + await laptop.sync.keepBoth(); + await agree(mac, laptop); + assert.deepEqual( + mac.state.tasks + .filter((one) => one.projectId === mac.projectId) + .map((one) => one.id) + .sort(), + ["dana-1", "dana-2", "task-1", "task-2"], + ); + assert.equal(find(laptop, "task-1").title, "Export as CSV"); + // A comment made on the Mac is by the person who is signed in there. + assert.equal( + laptop.state.storyComments![0].author.name, + people.alex.name, + ); + }, + ); + + scenario( + "a person taken off a project keeps the board on their computer, and it stops syncing", + async (world, later) => { + const people = cast(); + const alex = signedInTo(world, people.alex); + later(() => alex.close()); + const dana = signedInTo(world, people.dana); + later(() => dana.close()); + const shared = await alex.website.startProject("Website"); + const invitation = await alex.website.invite(shared, people.dana.email!); + await dana.projects.acceptInvitation(shared, invitation); + const mac = await computer(world, people.alex, "mac"); + later(() => mac.close()); + giveWork(mac.state, mac.projectId); + await mac.save(); + mac.connect(shared); + const laptop = await computer(world, people.dana, "laptop"); + later(() => laptop.close()); + laptop.connect(shared); + await agree(mac, laptop); + + await alex.website.removeGuest(shared, people.dana.accountId); + // The service looks every ten seconds at who may still watch. A change says so at once. + await laptop.edit( + () => void (find(laptop, "task-2").title = "After being removed"), + ); + await until( + () => laptop.status().state === "gone", + () => `the laptop to be told: ${JSON.stringify(laptop.status())}`, + ); + assert.match( + laptop.status().detail ?? "", + /no longer|not exist|does not/i, + ); + // The board is still on the laptop, with the change that could not be sent. + assert.equal(find(laptop, "task-2").title, "After being removed"); + assert.equal(find(laptop, "task-1").title, "Export as CSV"); + await mac.edit(() => void (find(mac, "task-1").title = "Not for Dana")); + await mac.synced(); + assert.equal(find(mac, "task-2").title, "Export as PDF"); + assert.equal(find(laptop, "task-1").title, "Export as CSV"); + }, + ); +} diff --git a/tests/support/memsync-stand-in-boards.ts b/tests/support/memsync-stand-in-boards.ts index 89b2157..18bd39d 100644 --- a/tests/support/memsync-stand-in-boards.ts +++ b/tests/support/memsync-stand-in-boards.ts @@ -66,6 +66,7 @@ export function standInBoardLogs(the: { const logs = new Map(); const watchers = new Set(); let loseNextReceipts = false; + let damageNextLogged = false; const logOf = (project: string) => { if (!logs.has(project)) logs.set(project, []); return logs.get(project)!; @@ -112,6 +113,12 @@ export function standInBoardLogs(the: { author: caller.accountId, payload: update.payload as Uint8Array, }; + if (damageNextLogged) { + // What is kept is not what was sent: its last byte is inverted. + damageNextLogged = false; + entry.payload = Uint8Array.from(entry.payload); + entry.payload[entry.payload.length - 1] ^= 0xff; + } log.push(entry); } return { @@ -207,6 +214,10 @@ export function standInBoardLogs(the: { loseNextReceipts() { loseNextReceipts = true; }, + /** The next update is damaged on its way into the log, before anyone reads it. */ + damageNextLogged() { + damageNextLogged = true; + }, /** Ends every watcher's stream, as a proxy that drops quiet connections does. */ cutWatchers() { for (const watcher of [...watchers]) watcher.stream.end(); From 447012e3afb36aec305a6c868a443ffbca3a1aae Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:07:53 +0100 Subject: [PATCH 16/66] fix: look for local board changes when sync starts [skip ci] A change made while board sync was not running (signed out, MemCode closed) was only sent once something else prompted a look at the workspace. Sync now compares the workspace with the board as last seen right after it has caught up with the log. The scenario that covers it no longer passes by accident. Also: a local project that is no longer in the workspace is not read as a board whose tasks were all deleted. Without that check the shared board of everyone on the project would have been emptied. Co-Authored-By: Claude Fable 5.2 --- runtime/sharing/board/sync.ts | 9 ++++++++- tests/sharing-board-sync.test.ts | 23 +++++++++++++++++++++++ tests/support/board-sync-scenarios.ts | 8 ++++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/runtime/sharing/board/sync.ts b/runtime/sharing/board/sync.ts index ec97b46..748fe68 100644 --- a/runtime/sharing/board/sync.ts +++ b/runtime/sharing/board/sync.ts @@ -250,6 +250,9 @@ export class BoardSync { if (this.stopped) return; await this.inTurn(async () => { if (!this.kept.joined) await this.join(false); + // What changed on this computer while sync was not running. + else if (this.noteOwnChanges()) + await this.store.save(this.toKeep(false)); await this.settle(); }); failures = 0; @@ -484,7 +487,11 @@ export class BoardSync { /** Writes what changed on this computer into the document. Says whether there was something. */ private noteOwnChanges(): boolean { if (!this.kept.joined || this.isNewer()) return false; - const now = boardOf(this.options.state(), this.options.projectId); + const state = this.options.state(); + // A project that is gone from this computer is not a board that was emptied. + if (!state.projects.some((one) => one.id === this.options.projectId)) + return false; + const now = boardOf(state, this.options.projectId); if (sameBoard(this.kept.seen, now)) return false; const made = this.recording(() => { this.tooLarge += writeChanges(this.doc, this.kept.seen, now); diff --git a/tests/sharing-board-sync.test.ts b/tests/sharing-board-sync.test.ts index 6c67b17..9b5e920 100644 --- a/tests/sharing-board-sync.test.ts +++ b/tests/sharing-board-sync.test.ts @@ -420,3 +420,26 @@ test("a value too large for the sharing service stays on this computer, and the await mac.synced(); await pc.synced(); }); + +test("a project that is taken off this computer is not a board that was emptied", async (context) => { + const { service, shared, mac, pc } = await standIn(context); + mac.connect(shared); + await mac.synced(); + pc.connect(shared); + await agree(mac, pc); + const logged = service.boards.log(shared).length; + + await mac.edit((state) => { + state.projects = state.projects.filter((one) => one.id !== mac.projectId); + state.tasks = state.tasks.filter((one) => one.projectId !== mac.projectId); + state.epics = state.epics.filter((one) => one.projectId !== mac.projectId); + }); + await pc.edit(() => void (find(pc, "task-1").estimate = 13)); + await pc.synced(); + assert.equal(service.boards.log(shared).length, logged + 1); + assert.equal(find(pc, "task-2").title, "Export as PDF"); + assert.equal( + pc.state.epics.some((one) => one.id === "goal-1"), + true, + ); +}); diff --git a/tests/support/board-sync-scenarios.ts b/tests/support/board-sync-scenarios.ts index 0db3a0a..9550b70 100644 --- a/tests/support/board-sync-scenarios.ts +++ b/tests/support/board-sync-scenarios.ts @@ -271,13 +271,17 @@ export function boardSyncScenarios( find(pc, "task-1").estimate = 8; state.tasks.push(task(pc.projectId, "task-9", { title: "While away" })); }); + pc.reopen(); + // Nothing prompts it: starting is enough for the PC to find what changed. + await until( + () => find(mac, "task-9")?.title === "While away", + "the Mac to get what was made while the PC was not syncing", + ); await mac.edit( () => void (find(mac, "task-1").title = "Renamed on the Mac"), ); - pc.reopen(); await agree(mac, pc); assert.equal(find(mac, "task-1").estimate, 8); - assert.equal(find(mac, "task-9").title, "While away"); assert.equal(find(pc, "task-1").title, "Renamed on the Mac"); }, ); From 77f8214a1878d4064163418aba41ff8030da397d Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:07:53 +0100 Subject: [PATCH 17/66] feat: sync the board of every connected project [skip ci] Sharing now runs board sync for each project the signed-in person has connected at the sharing service in use. It starts when MemCode starts and after connecting, and is matched again when the sign-in or the sharing addresses change. Disconnecting ends it and deletes what was kept for the board, in /shared-boards/. The runtime tells sharing after every save of the workspace, which is when changes made on this computer are picked up. LocalStore.save takes a step to run before the file is written, so a change from the shared board and board sync's own save are written as a pair. How each board stands is in AppState.sharedBoards. A new request, sharing:keep-both, answers the question asked when both boards have work on them. A comment written in a connected project is by the Memtrace account, so the same person can edit it from another computer. Co-Authored-By: Claude Fable 5.2 --- runtime/app.ts | 32 +++- runtime/local.ts | 8 +- runtime/sharing/routes.ts | 5 + runtime/sharing/sharing.ts | 183 +++++++++++++++++- tests/sharing-runtime.test.ts | 150 ++++++++++++++- tests/sharing.test.ts | 336 +++++++++++++++++++++++++++++++--- 6 files changed, 674 insertions(+), 40 deletions(-) diff --git a/runtime/app.ts b/runtime/app.ts index a422297..ad450fe 100644 --- a/runtime/app.ts +++ b/runtime/app.ts @@ -212,17 +212,19 @@ export async function createRuntime( let dispatchQueued = () => {}; let closed = false; let team: TeamSyncClient | undefined; + let sharing: Sharing | undefined; let persistenceFailed = false; - const changed = () => { + /** Tells the window once the workspace is written, and says so when it could not be. */ + const saved = (write: () => Promise, then?: () => Promise) => { const pending = (async () => { - await team?.capture(); - await store.save(); + await write(); emit("workspace:state", store.state); dispatchQueued(); if (persistenceFailed) { persistenceFailed = false; emit("workspace:save-status", { state: "saved" }); } + await then?.(); })(); return observePersistence(pending, (error) => { persistenceFailed = true; @@ -237,6 +239,15 @@ export async function createRuntime( }); }); }; + const changed = () => + saved( + async () => { + await team?.capture(); + await store.save(); + }, + // A board shared through the sharing service looks at what was just saved. + async () => sharing?.workspaceSaved(), + ); let reconcilingArtifacts: Promise | undefined; let artifactsCheckedAt = 0; const reconcileCatalog = () => { @@ -723,6 +734,8 @@ export async function createRuntime( }, changed: (status) => { emit("beta:status", status); + // Signing in or out decides which connected boards are synchronized. + if (!closed) void sharing?.syncBoards(); if (!status.loginPending && !closed) { if ( betaNeedsAnalysis && @@ -754,10 +767,14 @@ export async function createRuntime( }, }); // Sharing shows memtrace.io the same session, and holds no credential of its own. - const sharing = new Sharing({ + sharing = new Sharing({ state, changed, session: () => beta!.sessionProof(), + boardsFolder: join(store.dir, "shared-boards"), + // The workspace is read at this very call, so a board change is saved whole or not at all. + saveWorkspace: (first) => saved(() => store.save(first)), + shown: () => emit("workspace:state", store.state), }); registerSharing(register, sharing, host); register("beta:status", z.undefined(), () => beta!.status()); @@ -1422,6 +1439,8 @@ export async function createRuntime( handoffAttribution: state().settings.handoffAttribution, }; await changed(); + // New sharing addresses: boards on the old service stop, boards on the new one start. + void sharing?.syncBoards(); return dshProfileChanged ? revalidateDshOverrides() : store.runtime(); }, ); @@ -1487,6 +1506,7 @@ export async function createRuntime( : state().activeProjectId; return ( (projectId ? team?.identity(projectId) : undefined) ?? + (projectId ? sharing?.author(projectId) : undefined) ?? connections.account.current.principal ); }); @@ -1966,6 +1986,8 @@ export async function createRuntime( if (!team.status(parent.id)) initializeCodeReviewWorkflow(state(), parent.id); await changed(); + // Boards connected on an earlier run take up where they stopped. + void sharing.syncBoards(); const artifactMaintenance = setInterval(() => { void reconcileCatalog().catch((error) => console.error("Artifact catalog check failed:", error), @@ -2066,7 +2088,7 @@ export async function createRuntime( teamIdentity.cancel(); await repositories.close(); await team?.close(); - sharing.close(); + await sharing?.close(); await speech.close(); await retrieval.close(); await connections.close(); diff --git a/runtime/local.ts b/runtime/local.ts index 681d5e7..ee40215 100644 --- a/runtime/local.ts +++ b/runtime/local.ts @@ -85,12 +85,18 @@ export class LocalStore { initializePlanning(this.state); return this.state; } - save(): Promise { + /** + * Saves the workspace as it is at the moment of the call. `first` runs before + * the file is written: something that must be on disk before the workspace + * that goes with it. + */ + save(first?: () => Promise): Promise { observePlanning(this.state); const serialized = JSON.stringify(this.state, null, 2); const pending = this.writes .catch(() => {}) .then(async () => { + await first?.(); const path = join(this.dir, "workspace.json"); const temp = join(this.dir, "workspace.json.next"); await writeFile(temp, serialized, "utf8"); diff --git a/runtime/sharing/routes.ts b/runtime/sharing/routes.ts index 7023762..71e04d5 100644 --- a/runtime/sharing/routes.ts +++ b/runtime/sharing/routes.ts @@ -52,6 +52,11 @@ export function registerSharing( z.object({ projectId: id }).strict(), ({ projectId }) => sharing.disconnect(projectId), ); + register( + "sharing:keep-both", + z.object({ projectId: id }).strict(), + ({ projectId }) => sharing.keepBoth(projectId), + ); // Starting, renaming and deleting a project and inviting people happen at memtrace.io. register("sharing:manage", z.undefined(), () => host.call("open_memcode_projects", {}), diff --git a/runtime/sharing/sharing.ts b/runtime/sharing/sharing.ts index 964d9aa..c5fe08f 100644 --- a/runtime/sharing/sharing.ts +++ b/runtime/sharing/sharing.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; +import { join } from "node:path"; import type { AppState, Project } from "../../src/shared"; import type { PendingInvitation, @@ -6,9 +8,13 @@ import type { SharedProjectLink, SharingOverview, } from "../../src/sharing"; +import type { StoryAuthor } from "../../src/story-comments"; import type { BetaSessionProof } from "../beta"; import { SharingAccess } from "./access"; import { sharingAddresses } from "./addresses"; +import { BoardStore } from "./board/store"; +import { BoardSync } from "./board/sync"; +import { MemsyncBoards, type BoardsApi } from "./memsync/boards-api"; import { grpcChannel, type GrpcChannel } from "./memsync/grpc"; import { MemsyncProjects, @@ -30,6 +36,15 @@ export interface SharingOptions { changed(): Promise; /** The Memtrace sign-in to show memtrace.io. Null: nobody is signed in. */ session(): Promise; + /** Where each connected board keeps what it needs between runs. */ + boardsFolder: string; + /** + * Saves the workspace as it is at the moment of the call, and writes it only + * after `first` has finished. Board sync saves its own state through `first`. + */ + saveWorkspace(first: () => Promise): Promise; + /** What the window shows changed, and nothing needs saving. */ + shown?(): void; fetcher?: typeof fetch; now?: () => string; } @@ -41,6 +56,13 @@ interface Service { channel: GrpcChannel; access: SharingAccess; projects: ProjectsApi; + boards: BoardsApi; +} +/** Board sync running for one connected project. */ +interface RunningBoard { + link: SharedProjectLink; + service: Service; + sync: BoardSync; } const NOT_SET_UP = @@ -73,13 +95,22 @@ const shownInvitation = (invitation: InvitationRecord): PendingInvitation => ({ expiresAt: invitation.expiresAt, }); +/** A folder name for a link that no other link on this computer gets. */ +const folderOf = (link: SharedProjectLink) => + createHash("sha256") + .update([link.service, link.sharedProjectId, link.projectId].join("\n")) + .digest("hex") + .slice(0, 32); + /** * Sharing a project through the sharing service: who is signed in, the shared - * projects and invitations of that person, and which shared project each local - * project is connected to. The board itself is not synchronized here. + * projects and invitations of that person, which shared project each local + * project is connected to, and the board sync that runs for each of those. */ export class Sharing { private service?: Service; + private readonly boards = new Map(); + private matching: Promise = Promise.resolve(); private readonly now: () => string; constructor(private readonly options: SharingOptions) { this.now = options.now ?? (() => new Date().toISOString()); @@ -136,8 +167,6 @@ export class Sharing { service.access.current(), service.projects.getProject(input.sharedProjectId), ]); - // Another connect may have finished while the service was being asked. - this.assertFree(input, service); const link: SharedProjectLink = { projectId: input.projectId, sharedProjectId: shared.id, @@ -146,8 +175,13 @@ export class Sharing { service: service.address, connectedAt: this.now(), }; + // Whatever an earlier connection left behind belongs to another moment of this board. + await new BoardStore(this.boardFolder(link)).remove(); + // Another connect may have finished while the service was being asked. + this.assertFree(input, service); (this.options.state().sharedProjectLinks ??= []).push(link); await this.options.changed(); + await this.syncBoards(); return link; } @@ -158,15 +192,148 @@ export class Sharing { (link) => link.projectId !== projectId, ); if (kept.length === (state.sharedProjectLinks ?? []).length) return; + const running = this.boards.get(projectId); + this.boards.delete(projectId); + await running?.sync.stop(); + for (const link of state.sharedProjectLinks ?? []) + if (link.projectId === projectId) + await new BoardStore(this.boardFolder(link)).remove(); state.sharedProjectLinks = kept; + this.showBoards(); await this.options.changed(); } - close() { + /** + * Makes board sync run for exactly the projects the signed-in person has + * connected to the sharing service in use. For when MemCode starts, and when + * the sign-in, the addresses or the links change. + */ + syncBoards(): Promise { + const matched = this.matching.then(() => this.matchBoardsToLinks()); + this.matching = matched.catch((problem) => + console.error("Board sync could not be started:", problem), + ); + return this.matching; + } + + /** The workspace was saved. Changes made on this computer to connected boards are found now. */ + async workspaceSaved(): Promise { + const projects = this.options.state().projects; + await Promise.all( + [...this.boards.values()].map(({ link, sync }) => + projects.some((project) => project.id === link.projectId) + ? sync + .capture() + .catch((problem) => + console.error("A board change was not picked up:", problem), + ) + : undefined, + ), + ); + } + + /** The person said to keep both boards: theirs is added to the shared one. */ + async keepBoth(projectId: string): Promise { + const running = this.boards.get(projectId); + if (!running) throw new Error("This project's board is not being shared."); + await running.sync.keepBoth(); + } + + /** Who a comment written in a connected project is by: the person signed in to Memtrace. */ + author(projectId: string): StoryAuthor | undefined { + const running = this.boards.get(projectId); + if (!running) return undefined; + const { accountId } = running.link; + return { + id: accountId, + name: running.sync.nameOf(accountId) ?? "You", + source: "memtrace", + }; + } + + async close(): Promise { + await this.matching; + const running = [...this.boards.values()]; + this.boards.clear(); + await Promise.all(running.map(({ sync }) => sync.stop())); + this.closeService(); + } + + private closeService() { this.service?.channel.close(); this.service = undefined; } + private boardFolder(link: SharedProjectLink) { + return join(this.options.boardsFolder, folderOf(link)); + } + + private async matchBoardsToLinks(): Promise { + const state = this.options.state(); + let service: Service | null = null; + try { + service = this.serviceInUse(); + } catch { + // An address that cannot be used: nothing is synchronized, and the Sharing view says why. + } + const session = service + ? await this.options.session().catch(() => null) + : null; + const wanted = (state.sharedProjectLinks ?? []).filter( + (link) => + link.service === service?.address && + link.accountId === session?.accountId && + state.projects.some( + (project) => project.id === link.projectId && !project.example, + ), + ); + for (const [projectId, running] of this.boards) { + const stays = wanted.some( + (link) => + link.projectId === projectId && + link.sharedProjectId === running.link.sharedProjectId && + running.service === service, + ); + if (stays) continue; + this.boards.delete(projectId); + await running.sync.stop(); + } + for (const link of wanted) + if (!this.boards.has(link.projectId)) this.startBoard(link, service!); + this.showBoards(); + } + + private startBoard(link: SharedProjectLink, service: Service): void { + const sync = new BoardSync({ + projectId: link.projectId, + sharedProjectId: link.sharedProjectId, + folder: this.boardFolder(link), + state: this.options.state, + boards: service.boards, + saveWorkspace: this.options.saveWorkspace, + shown: () => this.showBoards(), + people: async () => { + const shared = await service.projects.getProject(link.sharedProjectId); + return new Map( + [shared.owner, ...shared.guests].map((person) => [ + person.accountId, + person.name, + ]), + ); + }, + }); + this.boards.set(link.projectId, { link, service, sync }); + sync.start(); + } + + /** Puts how each board stands where the window reads it. */ + private showBoards(): void { + this.options.state().sharedBoards = [...this.boards.values()].map( + ({ sync }) => sync.status(), + ); + this.options.shown?.(); + } + private assertFree( input: { projectId: string; sharedProjectId: string }, service: Service, @@ -210,7 +377,7 @@ export class Sharing { settings?.tokenUrl ?? "", ]); if (this.service?.settingsKey === settingsKey) return this.service; - this.close(); + this.closeService(); let addresses: ReturnType; try { addresses = sharingAddresses(settings); @@ -225,12 +392,14 @@ export class Sharing { tokenEndpoint: () => tokenEndpoint, fetcher: this.options.fetcher, }); + const calls = new SignedCalls(channel, access); this.service = { settingsKey, address: memsync.href, channel, access, - projects: new MemsyncProjects(new SignedCalls(channel, access)), + projects: new MemsyncProjects(calls), + boards: new MemsyncBoards(calls), }; return this.service; } diff --git a/tests/sharing-runtime.test.ts b/tests/sharing-runtime.test.ts index 76fe472..4eb3f2b 100644 --- a/tests/sharing-runtime.test.ts +++ b/tests/sharing-runtime.test.ts @@ -7,13 +7,16 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { createRuntime } from "../runtime/app"; import type { BetaCredentials, BetaStoredState } from "../runtime/beta"; -import type { AppState, Project } from "../src/shared"; +import type { AppState, Project, WorkItem } from "../src/shared"; +import type { StoryComment } from "../src/story-comments"; import type { SharingOverview } from "../src/sharing"; import { refusalSentences } from "../src/sharing-refusals"; import { signedInBetaStore } from "./support/beta-session"; import { actingAs } from "./support/memsync-owner"; +import { until } from "./support/board-computers"; import { startStandInMemsync, + type StandInMemsync, type StandInPerson, } from "./support/memsync-stand-in"; import { cast } from "./support/projects-api-scenarios"; @@ -70,10 +73,13 @@ async function tokenEndpointFor( } /** The whole local runtime, signed in to the beta, beside a stand-in memtrace.io and sharing service. */ -async function fixture(signedIn = true) { +async function fixture( + signedIn = true, + beside?: { service: StandInMemsync; people: ReturnType }, +) { const root = await mkdtemp(join(tmpdir(), "memcode-sharing-runtime-")); - const service = await startStandInMemsync(); - const people = cast(); + const service = beside?.service ?? (await startStandInMemsync()); + const people = beside?.people ?? cast(); const me: StandInPerson = people.alex; const stored: BetaStoredState = signedIn ? signedInBetaStore( @@ -147,7 +153,7 @@ async function fixture(signedIn = true) { async close() { await runtime.current.close(); await tokens.close(); - await service.close(); + if (!beside) await service.close(); await rm(root, { recursive: true, force: true }); }, }; @@ -363,3 +369,137 @@ test("connecting through sharing makes no Team room, and Team's own requests are await f.close(); } }); + +test("a board connected on two computers of one person follows what is done in the app on either", async () => { + const mac = await fixture(); + const pc = await fixture(true, mac); + const tasksOf = (f: typeof mac) => + f.state().tasks.filter((task) => task.projectId === "local-web"); + const boardOf = (f: typeof mac) => f.state().sharedBoards?.[0]; + try { + for (const f of [mac, pc]) + await f.saveAddresses({ + memsyncUrl: f.service.address.href, + tokenUrl: f.tokens.url, + }); + // The Mac has a goal with two tasks, made in the app. + const goal = await mac.request<{ id: string }>("epic:create", { + projectId: "local-web", + title: "Customers can export reports", + description: "As CSV and as PDF.", + phase: "now", + }); + const made: WorkItem[] = []; + for (const title of ["Export as CSV", "Export as PDF"]) + made.push( + await mac.request("task:create", { + projectId: "local-web", + title, + description: `What “${title}” means.`, + priority: "medium", + harness: mac.state().settings.defaultHarness, + epicId: goal.id, + }), + ); + const shared = await mac.website(mac.me).startProject("Website"); + await mac.request("sharing:connect", { + projectId: "local-web", + sharedProjectId: shared, + }); + await until(() => boardOf(mac)?.state === "synced", "the Mac's board"); + assert.ok(mac.service.boards.log(shared).length > 0); + + // The PC connects its own, empty project to the same shared project. + await pc.request("sharing:connect", { + projectId: "local-web", + sharedProjectId: shared, + }); + await until( + () => tasksOf(pc).length === 2 && boardOf(pc)?.state === "synced", + "the PC to take the board", + ); + assert.deepEqual( + tasksOf(pc).map((task) => [task.identifier, task.title, task.epicId]), + made.map((task) => [task.identifier, task.title, goal.id]), + ); + // It is in the PC's workspace file, and the window was told. + const onDisk = JSON.parse( + await readFile(join(pc.root, "profile", "workspace.json"), "utf8"), + ) as AppState; + assert.equal( + onDisk.tasks.filter((task) => task.projectId === "local-web").length, + 2, + ); + assert.equal(onDisk.sharedProjectLinks![0].applied, 1); + assert.ok(pc.emitted.includes("workspace:state")); + + // Work goes on from the PC: a task is moved and renamed, and a comment is written. + await pc.request("task:update", { + id: made[0].id, + patch: { title: "Export as CSV, continued on the PC", stage: "working" }, + }); + const comment = await pc.request("story-comment:add", { + taskId: made[0].id, + text: "Picked this up on the PC.", + }); + assert.deepEqual(comment.author, { + id: pc.me.accountId, + name: pc.me.name, + source: "memtrace", + }); + await until( + () => + tasksOf(mac).find((task) => task.id === made[0].id)?.stage === + "working" && (mac.state().storyComments ?? []).length === 1, + "the Mac to see what was done on the PC", + ); + const onMac = tasksOf(mac).find((task) => task.id === made[0].id)!; + assert.equal(onMac.title, "Export as CSV, continued on the PC"); + assert.deepEqual(mac.state().storyComments![0].author, comment.author); + assert.equal( + mac.state().storyComments![0].text, + "Picked this up on the PC.", + ); + // The person may change their own comment from the other computer. + await mac.request("story-comment:edit", { + taskId: made[0].id, + id: comment.id, + text: "Picked this up on the PC, finished on the Mac.", + }); + await until( + () => + pc.state().storyComments?.[0].text === + "Picked this up on the PC, finished on the Mac.", + "the PC to see the comment change", + ); + + // The PC is restarted. What the Mac does meanwhile is there afterwards. + await pc.restart(); + await mac.request("task:update", { + id: made[1].id, + patch: { title: "Export as PDF, while the PC was off" }, + }); + await until( + () => + tasksOf(pc).find((task) => task.id === made[1].id)?.title === + "Export as PDF, while the PC was off", + "the restarted PC to catch up", + ); + + // Disconnecting on the PC leaves the board there and the Mac alone. + await pc.request("sharing:disconnect", { projectId: "local-web" }); + assert.deepEqual(pc.state().sharedBoards, []); + assert.equal(tasksOf(pc).length, 2); + await assert.rejects( + pc.request("sharing:keep-both", { projectId: "local-web" }), + /not being shared/, + ); + await assert.rejects( + pc.request("sharing:keep-both", {}), + /expected string/, + ); + } finally { + await pc.close(); + await mac.close(); + } +}); diff --git a/tests/sharing.test.ts b/tests/sharing.test.ts index 2065bb4..3e2eb4d 100644 --- a/tests/sharing.test.ts +++ b/tests/sharing.test.ts @@ -1,5 +1,8 @@ import test from "node:test"; import assert from "node:assert/strict"; +import { mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { initialState } from "../src/seed"; import type { AppState, Project } from "../src/shared"; import type { SharingOverview } from "../src/sharing"; @@ -10,6 +13,7 @@ import { type StandInMemsync, type StandInPerson, } from "./support/memsync-stand-in"; +import { giveWork, task, until } from "./support/board-computers"; import { actingAs } from "./support/memsync-owner"; import { cast } from "./support/projects-api-scenarios"; @@ -28,9 +32,12 @@ const encoded = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); /** MemCode's sharing with a sign-in the test controls, a stand-in memtrace.io and a stand-in service. */ -async function fixture() { - const service = await startStandInMemsync(); - const people = cast(); +async function fixture(beside?: { + service: StandInMemsync; + people: ReturnType; +}) { + const service = beside?.service ?? (await startStandInMemsync()); + const people = beside?.people ?? cast(); const state: AppState = initialState(); state.projects.push( localProject("local-web", "website"), @@ -47,9 +54,34 @@ async function fixture() { admitAt: service as StandInMemsync, }; let serial = 0; + const issueToken = (async (url) => { + world.exchanges.push(String(url)); + if (world.tokenEndpointStatus !== 200) + return new Response("{}", { status: world.tokenEndpointStatus }); + const token = [ + encoded({ alg: "EdDSA", typ: "JWT" }), + encoded({ sub: world.signedIn!.accountId, serial: ++serial }), + "c2lnbmF0dXJl", + ].join("."); + world.admitAt.admit(token, world.signedIn!); + return Response.json({ + access_token: token, + token_type: "Bearer", + expires_in: 600, + }); + }) as typeof fetch; + const boardsFolder = await mkdtemp(join(tmpdir(), "memcode-sharing-")); const sharing = new Sharing({ state: () => state, - changed: async () => void world.saves++, + changed: async () => { + world.saves++; + await sharing.workspaceSaved(); + }, + boardsFolder, + saveWorkspace: async (first) => { + await first(); + world.saves++; + }, session: async () => world.signedIn && { refreshToken: "refresh-" + "r".repeat(40), @@ -58,22 +90,7 @@ async function fixture() { accountId: world.signedIn.accountId, }, now: () => at, - fetcher: (async (url) => { - world.exchanges.push(String(url)); - if (world.tokenEndpointStatus !== 200) - return new Response("{}", { status: world.tokenEndpointStatus }); - const token = [ - encoded({ alg: "EdDSA", typ: "JWT" }), - encoded({ sub: world.signedIn!.accountId, serial: ++serial }), - "c2lnbmF0dXJl", - ].join("."); - world.admitAt.admit(token, world.signedIn!); - return Response.json({ - access_token: token, - token_type: "Bearer", - expires_in: 600, - }); - }) as typeof fetch, + fetcher: issueToken, }); const as = (person: StandInPerson) => actingAs(service.address, service.tokenFor(person)); @@ -84,12 +101,45 @@ async function fixture() { world, sharing, as, + boardsFolder, + /** MemCode is started again on the same profile: what was kept is still there. */ + restarted: () => + new Sharing({ + state: () => state, + changed: async () => void world.saves++, + boardsFolder, + saveWorkspace: async (first) => { + await first(); + world.saves++; + }, + session: async () => + world.signedIn && { + refreshToken: "refresh-" + "r".repeat(40), + deviceId: "device-1234567890abcdef", + sessionId: world.sessionId, + accountId: world.signedIn.accountId, + }, + fetcher: issueToken, + }), close: async () => { - sharing.close(); - await service.close(); + await sharing.close(); + if (!beside) await service.close(); + await rm(boardsFolder, { recursive: true, force: true }); }, }; } +/** Waits until board sync has nothing left to do for the connected projects. */ +const boardsSynced = ( + f: { state: AppState }, + boards: number, + state = "synced", +) => + until( + () => + f.state.sharedBoards?.length === boards && + f.state.sharedBoards.every((board) => board.state === state), + () => `the boards to be ${state}: ${JSON.stringify(f.state.sharedBoards)}`, + ); type Ready = Extract; const ready = (overview: SharingOverview): Ready => { assert.equal(overview.state, "ready", JSON.stringify(overview)); @@ -427,6 +477,16 @@ test("disconnecting forgets the link on this computer and asks the service nothi projectId: "local-app", sharedProjectId: website, }); + // Board sync has read both logs and asked who is on the projects. + await boardsSynced(f, 2); + await until( + () => + ["local-web", "local-app"].every( + (id) => f.sharing.author(id)?.name === alex.name, + ), + "board sync to know who is on the projects", + ); + await until(() => f.service.boards.watching === 2, "both to be listening"); const asked = f.service.calls.length; await f.sharing.disconnect("local-web"); assert.deepEqual( @@ -481,3 +541,235 @@ test("a new sharing address in Settings is used from the next call on", async () await elsewhere.close(); } }); + +test("connecting writes the project's board to the shared project, and the person's second computer takes it", async () => { + const mac = await fixture(); + const pc = await fixture(mac); + const { alex } = mac.people; + try { + giveWork(mac.state, "local-web"); + const shared = await mac.as(alex).startProject("Website"); + await mac.sharing.connect({ + projectId: "local-web", + sharedProjectId: shared, + }); + await boardsSynced(mac, 1); + assert.equal(mac.state.sharedBoards![0].projectId, "local-web"); + assert.ok(mac.service.boards.log(shared).length > 0); + assert.deepEqual(await readdir(mac.boardsFolder), [ + (await readdir(mac.boardsFolder))[0], + ]); + + await pc.sharing.connect({ + projectId: "local-app", + sharedProjectId: shared, + }); + await boardsSynced(pc, 1); + const taken = pc.state.tasks.filter((one) => one.projectId === "local-app"); + assert.deepEqual(taken.map((one) => one.title).sort(), [ + "Export as CSV", + "Export as PDF", + ]); + // The second computer saved the workspace with the board in it, as one change. + assert.equal(pc.state.sharedProjectLinks![0].applied, 1); + + // A change made on the Mac after a save of its workspace reaches the PC. + mac.state.tasks.find((one) => one.id === "task-2")!.title = + "Export as PDF/A"; + await mac.sharing.workspaceSaved(); + await until( + () => + pc.state.tasks.find((one) => one.id === "task-2")?.title === + "Export as PDF/A", + "the PC to see the change", + ); + } finally { + await pc.close(); + await mac.close(); + } +}); + +test("a comment written in a connected project is by the person signed in to Memtrace", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + assert.equal(f.sharing.author("local-web"), undefined); + const shared = await f.as(alex).startProject("Website"); + await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: shared, + }); + await boardsSynced(f, 1); + await until( + () => f.sharing.author("local-web")?.name === alex.name, + "the name of the person signed in", + ); + assert.deepEqual(f.sharing.author("local-web"), { + id: alex.accountId, + name: alex.name, + source: "memtrace", + }); + assert.equal(f.sharing.author("local-app"), undefined); + } finally { + await f.close(); + } +}); + +test("disconnecting ends sync for the board and forgets what was kept for it", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + giveWork(f.state, "local-web"); + const shared = await f.as(alex).startProject("Website"); + await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: shared, + }); + await boardsSynced(f, 1); + assert.equal((await readdir(f.boardsFolder)).length, 1); + const logged = f.service.boards.log(shared).length; + + await f.sharing.disconnect("local-web"); + assert.deepEqual(f.state.sharedBoards, []); + assert.deepEqual(await readdir(f.boardsFolder), []); + assert.equal(f.service.boards.watching, 0); + // The board stays on this computer, and what changes on it now goes nowhere. + assert.equal( + f.state.tasks.filter((one) => one.projectId === "local-web").length, + 2, + ); + f.state.tasks.find((one) => one.id === "task-1")!.title = "Mine alone"; + await f.sharing.workspaceSaved(); + assert.equal(f.service.boards.log(shared).length, logged); + await assert.rejects(f.sharing.keepBoth("local-web"), /not being shared/); + } finally { + await f.close(); + } +}); + +test("a board is synchronized only for the account that connected it, on the service it was connected at", async () => { + const f = await fixture(); + const { alex, dana } = f.people; + try { + giveWork(f.state, "local-web"); + const shared = await f.as(alex).startProject("Website"); + await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: shared, + }); + await boardsSynced(f, 1); + const logged = f.service.boards.log(shared).length; + + // Someone else signs in to Memtrace on this computer. + f.world.signedIn = dana; + await f.sharing.syncBoards(); + assert.deepEqual(f.state.sharedBoards, []); + f.state.tasks.find((one) => one.id === "task-1")!.title = + "While Dana was signed in"; + await f.sharing.workspaceSaved(); + assert.equal(f.service.boards.log(shared).length, logged); + + // Nobody is signed in. + f.world.signedIn = null; + await f.sharing.syncBoards(); + assert.deepEqual(f.state.sharedBoards, []); + + // Alex signs in again: the board takes up where it stopped, with the change made meanwhile. + f.world.signedIn = alex; + await f.sharing.syncBoards(); + await boardsSynced(f, 1); + assert.equal(f.service.boards.log(shared).length, logged + 1); + + // The sharing addresses are taken out of Settings. + f.state.settings.sharing = undefined; + await f.sharing.syncBoards(); + assert.deepEqual(f.state.sharedBoards, []); + assert.equal(f.state.sharedProjectLinks!.length, 1); + } finally { + await f.close(); + } +}); + +test("boards connected on an earlier run are synchronized again when MemCode starts", async () => { + const f = await fixture(); + const { alex } = f.people; + try { + giveWork(f.state, "local-web"); + const shared = await f.as(alex).startProject("Website"); + await f.sharing.connect({ + projectId: "local-web", + sharedProjectId: shared, + }); + await boardsSynced(f, 1); + const logged = f.service.boards.log(shared).length; + await f.sharing.close(); + f.state.sharedBoards = [ + { ...f.state.sharedBoards![0], state: "offline", detail: "left over" }, + ]; + + const again = f.restarted(); + try { + f.state.tasks.push( + task("local-web", "task-3", { title: "Made while MemCode was closed" }), + ); + await again.syncBoards(); + await boardsSynced(f, 1); + assert.equal(f.state.sharedBoards![0].detail, undefined); + assert.equal(f.service.boards.log(shared).length, logged + 1); + } finally { + await again.close(); + } + } finally { + await f.close(); + } +}); + +test("when both boards have work, nothing is added until the person says to keep both", async () => { + const mac = await fixture(); + const laptop = await fixture(mac); + const { alex, dana } = mac.people; + try { + laptop.world.signedIn = dana; + giveWork(mac.state, "local-web"); + const shared = await mac.as(alex).startProject("Website"); + const invitation = await mac.as(alex).invite(shared, dana.email!); + await laptop.sharing.acceptInvitation({ + projectId: shared, + invitationId: invitation, + }); + await mac.sharing.connect({ + projectId: "local-web", + sharedProjectId: shared, + }); + await boardsSynced(mac, 1); + const logged = mac.service.boards.log(shared).length; + + laptop.state.tasks.push( + task("local-app", "dana-1", { title: "Dana's own" }), + ); + await laptop.sharing.connect({ + projectId: "local-app", + sharedProjectId: shared, + }); + await boardsSynced(laptop, 1, "choose"); + assert.deepEqual(laptop.state.sharedBoards![0].choice, { + shared: 2, + added: 1, + }); + assert.equal(mac.service.boards.log(shared).length, logged); + + await laptop.sharing.keepBoth("local-app"); + await boardsSynced(laptop, 1); + await until( + () => mac.state.tasks.some((one) => one.id === "dana-1"), + "the Mac to get Dana's task", + ); + assert.equal( + laptop.state.tasks.filter((one) => one.projectId === "local-app").length, + 3, + ); + } finally { + await laptop.close(); + await mac.close(); + } +}); From fc3d877b5acbc1671ec92300389ee91b2926616c Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:09:41 +0100 Subject: [PATCH 18/66] feat: show how a connected board stands in the Sharing view [skip ci] The open project's line now says whether its board is in sync, how many changes are on their way, or why it is not syncing. Changes that could not be read are named by person and day. A value too large to share and changes that are set aside each get a line of their own. When both boards have work on them the view says how many tasks each has and what keeping both does, with a Keep both button beside Disconnect. Nothing is added before that. The sentence that the board does not sync yet is gone. Co-Authored-By: Claude Fable 5.2 --- src/components/SharedProjects.tsx | 73 ++++++++++-- src/shared.ts | 2 + src/sharing-board.ts | 99 ++++++++++++++++ src/styles-sharing.css | 21 ++++ src/tauri.ts | 2 + tests/sharing-view.test.ts | 180 +++++++++++++++++++++++++++++- 6 files changed, 365 insertions(+), 12 deletions(-) create mode 100644 src/sharing-board.ts diff --git a/src/components/SharedProjects.tsx b/src/components/SharedProjects.tsx index 45d0ee2..9649607 100644 --- a/src/components/SharedProjects.tsx +++ b/src/components/SharedProjects.tsx @@ -13,14 +13,19 @@ import { projectSharing, type PendingInvitation, type ProjectSharing, + type SharedBoardStatus, type SharedProject, type SharingOverview, } from "../sharing"; +import { boardStanding } from "../sharing-board"; import { dateLabel } from "../planning/dates"; import { errorMessage } from "../errors"; const REFRESH_ON_RETURN_MS = 15_000; -type Workspace = Pick; +type Workspace = Pick< + AppState, + "projects" | "team" | "sharedProjectLinks" | "sharedBoards" +>; type Ready = Extract; interface PanelProps { @@ -38,8 +43,12 @@ interface PanelProps { onAccept(invitation: PendingInvitation): void; onConnect(shared: SharedProject): void; onDisconnect(): void; + onKeepBoth(): void; } +const boardOf = (state: Workspace, project: Project) => + state.sharedBoards?.find((board) => board.projectId === project.id); + const people = (shared: SharedProject) => { const others = [shared.owner, ...shared.guests] .filter((person) => !person.isYou) @@ -53,17 +62,34 @@ const people = (shared: SharedProject) => { ].join(" · "); }; +/** How the open project's board stands with the shared one. */ +function BoardLines({ board }: { board: ReturnType }) { + return ( + <> + {board.line} + {board.notes.map((note) => ( + {note} + ))} + + ); +} + /** What the open project's own line says, and whether it can be disconnected. */ function OpenProject({ project, standing, + board, busy, onDisconnect, + onKeepBoth, }: { project: Project; standing: ProjectSharing; + /** How board sync stands, when it runs for this project. */ + board?: SharedBoardStatus; busy: string; onDisconnect(): void; + onKeepBoth(): void; }) { const name = {project.name}; const linked = @@ -71,6 +97,17 @@ function OpenProject({ standing.kind === "gone" || standing.kind === "elsewhere" || standing.kind === "remembered"; + const shared = + standing.kind === "connected" + ? standing.shared.name + : standing.kind === "remembered" + ? standing.name + : undefined; + // A project that is connected and has no word from board sync yet is about to get one. + const lines = + shared !== undefined && (board || standing.kind === "connected") + ? boardStanding(board, { local: project.name, shared }) + : undefined; return (
    @@ -97,16 +134,16 @@ function OpenProject({

    {name} is connected to {standing.shared.name}.

    - - Connecting records which shared project this board belongs to. The - board does not sync between computers yet. - + {lines && } )} {standing.kind === "remembered" && ( -

    - {name} is connected to {standing.name}. -

    + <> +

    + {name} is connected to {standing.name}. +

    + {lines && } + )} {standing.kind === "gone" && (

    @@ -121,6 +158,16 @@ function OpenProject({

    )} + {lines?.asksToKeepBoth && ( + + )} {linked && ( - )} {linked && ( + )} + + ))} + +
    + ); +} diff --git a/src/components/WorkDetail.tsx b/src/components/WorkDetail.tsx index 27bf095..b7d5716 100644 --- a/src/components/WorkDetail.tsx +++ b/src/components/WorkDetail.tsx @@ -36,6 +36,13 @@ import "../styles-worker-input.css"; import "../styles-annotations.css"; import "../styles-card-comments.css"; import { WorkerChanges } from "./WorkerChanges"; +import { ShareFromCard } from "./ShareFromCard"; +import { + cardRunElsewhere, + isUnfetchedSharedFile, + runElsewhereNote, + sharedFilesToFetch, +} from "../sharing-cards"; import { StoryTabBar, type StoryTab, type StoryTabItem } from "./StoryTabBar"; import { isCodeReviewTask } from "../code-review-workflow"; import { taskStatus, workflowFor } from "../planning/workflow"; @@ -134,7 +141,7 @@ export function WorkDetail({ state, task: localTask, project, - artifacts, + artifacts: ownArtifacts, initialArtifact, runtime, epics, @@ -157,7 +164,27 @@ export function WorkDetail({ const task = presentedTask(localTask); const health = useRuntimeHealth(); const team = state.team?.find((item) => item.projectId === task.projectId); - const owner = teamClaimForStory(team, task.id); + // A run shown from the card's log at the sharing service: read here, never steered. + const elsewhere = cardRunElsewhere(localTask); + const owner = teamClaimForStory(team, task.id) ?? elsewhere; + const sharedBoard = state.sharedBoards?.find( + (board) => board.projectId === localTask.projectId, + ); + const sharedProjectName = state.sharedProjectLinks?.find( + (link) => link.projectId === localTask.projectId, + )?.sharedProjectName; + const artifacts = [ + ...ownArtifacts, + ...sharedFilesToFetch(localTask, ownArtifacts), + ]; + const [sharing, setSharing] = useState(""); + // While a card of a shared project is open, what happens to it elsewhere is followed. + useEffect(() => { + if (!sharedBoard) return; + const taskId = localTask.id; + void window.memcode.followSharedCard(taskId).catch(() => {}); + return () => void window.memcode.unfollowSharedCard(taskId).catch(() => {}); + }, [localTask.id, !!sharedBoard]); const remote = owner && !owner.local ? owner : undefined; const teamBlock = teamStartBlocked(team, task.id); const blockers = pendingPrerequisites(task, tasks); @@ -402,9 +429,38 @@ export function WorkDetail({ }); }; const openArtifact = async (item: Artifact) => { + if (isUnfetchedSharedFile(item)) + return act(async () => { + const fetched = await window.memcode.openSharedCardFile({ + taskId: task.id, + resultId: item.id.slice("shared:".length), + }); + setArtifact(fetched); + setTab("artifacts"); + }); setArtifact(item); setTab("artifacts"); }; + const shareFile = (item: Artifact) => + void act(async () => { + setSharing(item.id); + try { + await window.memcode.shareCardFile({ + taskId: task.id, + artifactId: item.id, + }); + notify(`${item.name} is shared with ${sharedProjectName}`); + } finally { + setSharing(""); + } + }); + const shareChanges = () => + act(async () => { + await window.memcode.shareCardChanges(task.id); + notify(`These changes are shared with ${sharedProjectName}`); + }); + // Sharing is offered on the computer that ran the worker, for a shared project. + const mayShare = !!sharedBoard && !elsewhere && !task.example; const comment = (reference: ReviewReference) => { if (reference.taskId !== task.id) return; setReferences([reference]); @@ -913,12 +969,15 @@ export function WorkDetail({ )}