Skip to content

Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.

Phone companion: the desktop side, hidden until the iPhone app ships (#145)

Christian Mathiesen8a06d403383b
diff --git a/.gitignore b/.gitignore
index 74de2150..4e223e67 100644
--- a/.gitignore
+++ b/.gitignore
@@ -44,6 +44,10 @@ output/
# written by next dev
+# Swift package builds
+ios/YogurtKit/.build/
+ios/YogurtKit/.swiftpm/
+
# plans, specs and agent notes stay local
docs/superpowers/
AGENTS.md
diff --git a/app/electron-builder.yml b/app/electron-builder.yml
index fa64dfaf..31ce0f66 100644
--- a/app/electron-builder.yml
+++ b/app/electron-builder.yml
@@ -82,6 +82,8 @@ mac:
NSCalendarsFullAccessUsageDescription: Yogurt reads your calendar to name your notes after the meeting and to know who is in it. Nothing leaves your Mac.
NSCalendarsUsageDescription: Yogurt reads your calendar to name your notes after the meeting and to know who is in it. Nothing leaves your Mac.
NSAppleEventsUsageDescription: Yogurt checks the browser tab's name to tell when you're in a call, and pauses your music while it records.
+ # macOS 15 and later ask before an app can be found on the local network (Bonjour), which the iPhone app needs
+ NSLocalNetworkUsageDescription: Yogurt lets your iPhone find this computer on your Wi-Fi so your notes can sync. Nothing goes through the internet.
# Electron's own defaults ("This app needs access to..."): Yogurt never asks for these, so plain words instead
NSCameraUsageDescription: Yogurt doesn't use the camera.
NSBluetoothAlwaysUsageDescription: Yogurt doesn't use Bluetooth.
diff --git a/app/package.json b/app/package.json
index 36223d74..37ffae12 100644
--- a/app/package.json
+++ b/app/package.json
@@ -13,9 +13,11 @@
"typecheck": "tsc -p ."
},
"dependencies": {
+ "bonjour-service": "1.4.4",
"chrono-node": "2.10.3",
"electron-updater": "6.8.10",
"ical.js": "2.2.1",
+ "libsodium-wrappers-sumo": "0.8.4",
"node-llama-cpp": "3.22.1"
},
"devDependencies": {
diff --git a/app/scripts/companion-peer.mjs b/app/scripts/companion-peer.mjs
new file mode 100644
index 00000000..cb2f934a
--- /dev/null
+++ b/app/scripts/companion-peer.mjs
@@ -0,0 +1,116 @@
+// A tiny desktop stand-in for YogurtKit's interop tests: runs the pairing exchange and then Noise KK echo
+// sessions with the real companion crypto from src/main/companion.
+// node app/scripts/companion-peer.mjs desktop <port> [code]
+// Prints JSON lines: {"listening": port}, then {"paired": {isk, phoneKey, desktopKey}} or {"pairFail": reason}.
+// Not shipped; test use only. The modules use extensionless imports, so they're bundled with esbuild first.
+import { build } from 'esbuild'
+import { createServer } from 'node:net'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+
+const [role, portArg, code = '482913'] = process.argv.slice(2)
+if (role !== 'desktop' || portArg === undefined) {
+ console.error('usage: companion-peer.mjs desktop <port> [code]')
+ process.exit(2)
+}
+
+const companion = join(dirname(fileURLToPath(import.meta.url)), '../src/main/companion')
+const dir = mkdtempSync(join(tmpdir(), 'companion-peer-'))
+process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
+for (const sig of ['SIGTERM', 'SIGINT']) process.on(sig, () => process.exit(0))
+const outfile = join(dir, 'companion.mjs')
+await build({
+ stdin: {
+ contents: ['sodium', 'cpace', 'noise', 'box'].map((m) => `export * from './${m}'`).join('\n'),
+ resolveDir: companion, loader: 'ts',
+ },
+ bundle: true, platform: 'node', format: 'esm', outfile, logLevel: 'error',
+})
+const { ready, cpaceStart, cpaceFinish, pairKeys, sealBox, openBox, generateKeyPair, NoiseKK } = await import(pathToFileURL(outfile).href)
+await ready()
+
+const report = (o) => process.stdout.write(JSON.stringify(o) + '\n')
+const enc = (s) => new TextEncoder().encode(s)
+const b64 = (b) => Buffer.from(b).toString('base64')
+const unb64 = (s) => Uint8Array.from(Buffer.from(s, 'base64'))
+const hex = (b) => Buffer.from(b).toString('hex')
+const concat = (...p) => Uint8Array.from(Buffer.concat(p))
+
+const desktop = generateKeyPair()
+const desktopId = hex(crypto.getRandomValues(new Uint8Array(8)))
+let phoneKey = null
+
+/** Frames on a socket: 2-byte big-endian length + payload. `next()` resolves with the next payload. */
+function framed(socket) {
+ let buf = Buffer.alloc(0)
+ const queue = [], waiting = []
+ socket.on('data', (d) => {
+ buf = Buffer.concat([buf, d])
+ while (buf.length >= 2 && buf.length >= 2 + buf.readUInt16BE(0)) {
+ const frame = Uint8Array.from(buf.subarray(2, 2 + buf.readUInt16BE(0)))
+ buf = buf.subarray(2 + frame.length)
+ waiting.length ? waiting.shift().resolve(frame) : queue.push(frame)
+ }
+ })
+ const fail = () => { while (waiting.length) waiting.shift().reject(new Error('closed')) }
+ socket.on('close', fail)
+ socket.on('error', fail)
+ return {
+ next: () => queue.length ? Promise.resolve(queue.shift()) : new Promise((resolve, reject) => waiting.push({ resolve, reject })),
+ send: (payload) => {
+ const len = Buffer.alloc(2)
+ len.writeUInt16BE(payload.length)
+ socket.write(Buffer.concat([len, payload]))
+ },
+ }
+}
+
+const json = async (f) => JSON.parse(new TextDecoder().decode(await f.next()))
+const sendJson = (f, o) => f.send(enc(JSON.stringify(o)))
+
+async function pair(f) {
+ const hello = await json(f)
+ if (hello.type !== 'pairHello') throw new Error('expected pairHello')
+ const phoneSession = unb64(hello.phoneSession)
+ const desktopSession = crypto.getRandomValues(new Uint8Array(16))
+ const sid = concat(desktopSession, phoneSession)
+ const ci = concat(enc('yogurt-pair-v1'), desktopSession, phoneSession)
+ const { ya, secret } = cpaceStart(code, ci, sid)
+ sendJson(f, { type: 'pairStart', v: 1, desktopSession: b64(desktopSession), desktopId, desktopName: 'Test Mac', ya: b64(ya) })
+ const reply = await json(f)
+ const isk = cpaceFinish(secret, unb64(reply.yb))
+ const keys = pairKeys(isk)
+ const mine = enc(JSON.stringify({ key: b64(desktop.publicKey), name: 'Test Mac', id: desktopId }))
+ sendJson(f, { type: 'pairConfirm', box: b64(sealBox(keys.toPhone, mine, enc('pairConfirm'))) })
+ const done = await json(f)
+ let phone
+ try {
+ phone = JSON.parse(new TextDecoder().decode(openBox(keys.toDesktop, unb64(done.box), enc('pairDone'))))
+ } catch {
+ sendJson(f, { type: 'pairFail', reason: 'code' })
+ report({ pairFail: 'code' })
+ return
+ }
+ phoneKey = unb64(phone.key)
+ sendJson(f, { type: 'pairOk' })
+ report({ paired: { isk: hex(isk), phoneKey: hex(phoneKey), desktopKey: hex(desktop.publicKey) } })
+}
+
+async function echo(f) {
+ const noise = new NoiseKK({ initiator: false, s: desktop, rs: phoneKey, prologue: enc('yogurt-v1') })
+ noise.readMessage(await f.next())
+ f.send(noise.writeMessage(new Uint8Array(0)))
+ const { send, recv } = noise.split()
+ for (;;) f.send(send.encrypt(recv.decrypt(await f.next())))
+}
+
+// until a phone is paired every connection is a pairing attempt; after that, a Noise session
+const server = createServer((socket) => {
+ const f = framed(socket)
+ ;(phoneKey ? echo(f) : pair(f)).catch((err) => { if (err.message !== 'closed') console.error('companion-peer:', err.message) }).finally(() => socket.end())
+})
+server.listen(Number(portArg), '127.0.0.1', () => report({ listening: server.address().port }))
+// the test owns this process: when it goes away, so does the peer
+process.stdin.on('end', () => process.exit(0)).resume()
diff --git a/app/scripts/companion-server-harness.mjs b/app/scripts/companion-server-harness.mjs
new file mode 100644
index 00000000..d118fabc
--- /dev/null
+++ b/app/scripts/companion-server-harness.mjs
@@ -0,0 +1,78 @@
+// The desktop's real companion server (src/main/companion) with a throwaway profile, for YogurtKit's interop tests:
+// a temp userData folder, an in-memory store seeded with made-up meetings, a stub Ask, no Bonjour, localhost only.
+// node app/scripts/companion-server-harness.mjs
+// Opens pairing and prints {"port", "code", "desktopId", "meetings": {name: id}} as one JSON line. Then each JSON line
+// on stdin is a question answered on stdout: {"cmd":"meeting","id"} → {"meeting": {title, trashedAt}},
+// {"cmd":"notes","id"} → {"notes": mine}, {"cmd":"add","title"} → {"added": id}. An import prints {"imported": id, bytes}.
+// Exits when stdin closes. Never touches the real Yogurt profile. Not shipped; test use only.
+import { build } from 'esbuild'
+import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { createInterface } from 'node:readline'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+
+const src = join(dirname(fileURLToPath(import.meta.url)), '../src/main')
+const dir = mkdtempSync(join(tmpdir(), 'companion-harness-'))
+const cleanup = () => rmSync(dir, { recursive: true, force: true })
+process.on('exit', cleanup)
+for (const sig of ['SIGTERM', 'SIGINT']) process.on(sig, () => process.exit(0))
+
+// the modules use extensionless imports, so they're bundled first
+const outfile = join(dir, 'harness.mjs')
+await build({
+ stdin: {
+ contents: ["export { createCompanion } from './companion'", "export { openStore } from './store'", "export { initMeetings } from './meeting'"].join('\n'),
+ resolveDir: src, loader: 'ts',
+ },
+ bundle: true, platform: 'node', format: 'esm', outfile, logLevel: 'error',
+ // the translation tables load through Vite's import.meta.glob; English (no tables) is all the harness needs
+ define: { 'import.meta.glob': '__noGlob' }, // bundled CommonJS (bonjour-service) asks for Node's built-ins through require
+ banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); const __noGlob = () => ({});" },
+})
+const { createCompanion, openStore, initMeetings } = await import(pathToFileURL(outfile).href)
+
+const out = (o) => process.stdout.write(JSON.stringify(o) + '\n')
+const store = openStore(':memory:')
+initMeetings(store)
+const base = { eventId: null, app: null, attendees: [], state: 'done' }
+const banana = store.createMeeting({ ...base, title: 'Banana sync', startedAt: 1_700_000_000_000, endedAt: 1_700_000_600_000 })
+store.setNotes(banana.id, { mine: 'buy apples', enhanced: '## Decisions\n- Bananas.' })
+store.addSegments([
+ { meetingId: banana.id, track: 'me', startMs: 0, endMs: 900, text: 'hello there', speaker: 'me' },
+ { meetingId: banana.id, track: 'them', startMs: 1000, endMs: 1900, text: 'we chose bananas', speaker: null },
+])
+const cherry = store.createMeeting({ ...base, title: 'Cherry review', startedAt: 1_700_100_000_000, endedAt: 1_700_100_600_000 })
+const fruit = store.createFolder('Fruit')
+store.addToFolder(fruit.id, banana.id)
+// a made-up "them" track for Banana sync, a few chunks long
+const audio = join(dir, 'them.m4a')
+writeFileSync(audio, Buffer.from(Array.from({ length: 100_000 }, (_, i) => i % 251)))
+
+const companion = await createCompanion({
+ store, userDataDir: dir,
+ seal: (s) => s, open: (s) => s,
+ ask: async (question) => ({ answer: `Made-up answer to: ${question}`, sources: [{ n: 1, meetingId: banana.id, title: 'Banana sync', atMs: 1200, text: 'we chose bananas' }] }),
+ importRecording: async (meeting, path, draft) => {
+ const bytes = statSync(path).size
+ store.createMeeting({ ...base, title: meeting.title, startedAt: meeting.startedAt, endedAt: meeting.endedAt }, meeting.id)
+ store.setNotes(meeting.id, { mine: draft.myNotes })
+ out({ imported: meeting.id, bytes })
+ },
+ audioFiles: async (id) => id === banana.id ? [{ track: 'them', path: audio }] : [],
+ deviceName: () => 'Harness Mac', appVersion: '0.0.0-harness', log: () => {},
+ ops: { notesRewrite: (id, mine) => store.setNotes(id, { mine }) },
+ host: '127.0.0.1', advertiser: { publish: () => {}, stop: () => {} }, pollMs: 50,
+})
+const { code } = await companion.startPairing()
+out({ port: companion.port(), code, desktopId: companion.desktopId, meetings: { banana: banana.id, cherry: cherry.id }, folders: { fruit: fruit.id } })
+
+const lines = createInterface({ input: process.stdin })
+lines.on('line', (line) => {
+ const q = JSON.parse(line)
+ if (q.cmd === 'meeting') { const m = store.meeting(q.id); out({ meeting: m && { title: m.title, trashedAt: m.trashedAt ?? null } }) }
+ else if (q.cmd === 'notes') out({ notes: store.notes(q.id).mine })
+ else if (q.cmd === 'add') out({ added: store.createMeeting({ ...base, title: q.title, startedAt: 1_700_200_000_000, endedAt: 1_700_200_600_000 }).id })
+})
+// the test owns this process: when it goes away, so does the harness
+lines.on('close', async () => { await companion.stop(); process.exit(0) })
diff --git a/app/src/main/asr/index.ts b/app/src/main/asr/index.ts
index 6bc16574..4a095ac4 100644
--- a/app/src/main/asr/index.ts
+++ b/app/src/main/asr/index.ts
@@ -101,7 +101,8 @@ export function liveSilentMs(id: string, now = Date.now()): number {
return Math.max(0, now - live.quietSince)
}
-export type RecordedOptions = { signal?: AbortSignal; progress?: (ms: number) => void; fromMs?: Partial<Record<Track,number>>; save?: (segments: Omit<Segment,'id'>[]) => void }
+/** language: a code whisper is told for every chunk instead of the spoken setting (a phone recording's own) */
+export type RecordedOptions = { signal?: AbortSignal; progress?: (ms: number) => void; fromMs?: Partial<Record<Track,number>>; save?: (segments: Omit<Segment,'id'>[]) => void; language?: string }
type Recorded = (id: string, tracks: Partial<Record<Track, AsyncIterable<Float32Array>>>, stopped?: () => boolean, options?: RecordedOptions) => Promise<boolean>
let recorded: Recorded = async () => false
/**
@@ -230,7 +231,7 @@ export function hookTranscription(p: {
// the model takes a few seconds to load: start now, so the first chunk does not wait for it
srv.url().catch((e) => console.error('whisper-server did not start', e))
transcribe = createTranscriber({ url: () => srv.url(), recover: recoverer(srv), onLanguage: (_t, lang, chars, locked) => hear(lang, chars, locked), prompt: promptOf,
- language: () => whisperLanguage(spokenNow()), signal: options?.signal })
+ language: () => options?.language ?? whisperLanguage(spokenNow()), signal: options?.signal })
} else {
console.warn('no speech model yet: this meeting is recorded but not transcribed')
setTimeout(() => warnOnce('no-speech-model'), NO_MODEL_NOTE_DELAY_MS)
diff --git a/app/src/main/backup.ts b/app/src/main/backup.ts
index 313b6af3..b2e3ad54 100644
--- a/app/src/main/backup.ts
+++ b/app/src/main/backup.ts
@@ -153,8 +153,12 @@ export async function exportBackup(o: { db: DatabaseSync; meetingsDir: string; o
const snap = new DatabaseSync(file)
// meetings in the Trash are on their way out: not in the backup (their rows go with them by ON DELETE CASCADE)
snap.exec('PRAGMA foreign_keys = ON')
- // and VACUUM so their words aren't left in the file's free pages
- if (columns(snap, 'meetings').some((c) => c.name === 'trashed_at') && Number(snap.prepare('DELETE FROM meetings WHERE trashed_at IS NOT NULL').run().changes) > 0) snap.exec('VACUUM')
+ // the iPhone pairing and what it has fetched belong to this Mac: never in a backup (triggers first, they write the log)
+ for (const r of snap.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'companion\\_%' ESCAPE '\\'").all() as Row[]) snap.exec(`DROP TRIGGER "${String(r.name)}"`)
+ snap.exec('DROP TABLE IF EXISTS companion_changes; DROP TABLE IF EXISTS companion_devices; DROP TABLE IF EXISTS companion_meta')
+ if (columns(snap, 'meetings').some((c) => c.name === 'trashed_at')) snap.prepare('DELETE FROM meetings WHERE trashed_at IS NOT NULL').run()
+ // and VACUUM so none of it is left in the file's free pages
+ snap.exec('VACUUM')
const ids = (snap.prepare('SELECT id FROM meetings').all() as Row[]).map((r) => r.id).filter(isId)
snap.close()
for (const id of ids) {
diff --git a/app/src/main/companion/advertise.ts b/app/src/main/companion/advertise.ts
new file mode 100644
index 00000000..edc6793d
--- /dev/null
+++ b/app/src/main/companion/advertise.ts
@@ -0,0 +1,49 @@
+// Bonjour for the companion: the phone finds this computer as _yogurt._tcp on the local network.
+import { Bonjour, type Service } from 'bonjour-service'
+
+export type Advert = { name: string; port: number; txt: Record<string, string> }
+export type Advertiser = {
+ publish: (a: Advert) => void; stop: () => void; /** says goodbye on the network, then lets go */ destroy?: () => Promise<void>
+ /** set by the companion: the network refused the advert (macOS Local Network permission, a firewall), so no phone can find it */
+ onFailure?: () => void
+}
+
+/** mDNS through bonjour-service (plain JavaScript, so the same on Mac, Windows and Linux) */
+export function bonjourAdvertiser(log: (...parts: unknown[]) => void): Advertiser {
+ let bonjour: Bonjour | null = null
+ let service: Service | null = null
+ let current = ''
+ const stop = () => {
+ const s = service
+ service = null
+ current = ''
+ try { s?.stop?.() } catch (err) { log('COMPANION', 'advert stop failed', (err as Error).name) }
+ }
+ const adv: Advertiser = {
+ publish(a) {
+ // the same advert again: nothing to do (re-announcing churns the network)
+ const key = JSON.stringify(a)
+ if (key === current) return
+ stop()
+ try {
+ bonjour ??= new Bonjour(undefined, (err: Error) => { log('COMPANION', 'mdns error', err?.name); adv.onFailure?.() })
+ service = bonjour.publish({ name: a.name, type: 'yogurt', protocol: 'tcp', port: a.port, txt: a.txt })
+ service.on('error', (err: Error) => { log('COMPANION', 'advert error', err?.name); adv.onFailure?.() })
+ current = key
+ log('COMPANION', 'advertising', `pairing=${a.txt.pairing}`)
+ } catch (err) { log('COMPANION', 'advert failed', (err as Error).name); adv.onFailure?.() }
+ },
+ stop,
+ async destroy() {
+ const b = bonjour
+ bonjour = null
+ if (!b) return
+ service = null
+ current = ''
+ // unpublishAll sends the goodbye packets; destroy closes the socket only after
+ await new Promise<void>((r) => { try { b.unpublishAll(() => r()) } catch { r() } })
+ await new Promise<void>((r) => { try { b.destroy(() => r()) } catch { r() } })
+ },
+ }
+ return adv
+}
diff --git a/app/src/main/companion/box.ts b/app/src/main/companion/box.ts
new file mode 100644
index 00000000..20ea2b78
--- /dev/null
+++ b/app/src/main/companion/box.ts
@@ -0,0 +1,24 @@
+// XChaCha20-Poly1305 for the pairing exchange. A box is the 24-byte random nonce followed by the ciphertext.
+import { sodium } from './sodium'
+
+const NONCE = 24
+
+export function sealBox(key: Uint8Array, plaintext: Uint8Array, ad: Uint8Array): Uint8Array {
+ const s = sodium()
+ const nonce = s.randombytes_buf(NONCE)
+ const ct = s.crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, ad, null, nonce, key)
+ const box = new Uint8Array(NONCE + ct.length)
+ box.set(nonce)
+ box.set(ct, NONCE)
+ return box
+}
+
+/** Throws when the box was changed, or sealed under another key or associated data. */
+export function openBox(key: Uint8Array, box: Uint8Array, ad: Uint8Array): Uint8Array {
+ if (box.length < NONCE + 16) throw new Error('box: too short')
+ try {
+ return sodium().crypto_aead_xchacha20poly1305_ietf_decrypt(null, box.subarray(NONCE), ad, box.subarray(0, NONCE), key)
+ } catch {
+ throw new Error('box: could not open')
+ }
+}
diff --git a/app/src/main/companion/cpace.ts b/app/src/main/companion/cpace.ts
new file mode 100644
index 00000000..7a3da669
--- /dev/null
+++ b/app/src/main/companion/cpace.ts
@@ -0,0 +1,110 @@
+// CPace on ristretto255 + SHA-512, initiator/responder setting, exactly as draft-irtf-cfrg-cpace-21.
+// The desktop is A (initiator), the phone is B (responder). YogurtKit's Cpace.swift mirrors this file.
+import { hkdfSync } from 'node:crypto'
+import { sodium } from './sodium'
+
+const DSI = new TextEncoder().encode('CPaceRistretto255')
+const DSI_ISK = new TextEncoder().encode('CPaceRistretto255_ISK')
+const SHA512_BLOCK = 128
+const EMPTY = new Uint8Array(0)
+
+export interface CpaceSecret { scalar: Uint8Array; sid: Uint8Array; ya: Uint8Array; ada: Uint8Array }
+
+function concat(...parts: Uint8Array[]): Uint8Array {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
+ let at = 0
+ for (const p of parts) { out.set(p, at); at += p.length }
+ return out
+}
+
+/** LEB128 length, then the bytes (the draft's prepend_len). */
+function prependLen(data: Uint8Array): Uint8Array {
+ const len: number[] = []
+ let n = data.length
+ do { len.push((n & 0x7f) | (n >= 0x80 ? 0x80 : 0)); n >>>= 7 } while (n > 0)
+ return concat(Uint8Array.from(len), data)
+}
+
+export function lvCat(...parts: Uint8Array[]): Uint8Array {
+ return concat(...parts.map(prependLen))
+}
+
+export function generatorString(prs: string, ci: Uint8Array, sid: Uint8Array): Uint8Array {
+ const p = new TextEncoder().encode(prs)
+ // pads DSI and PRS out to a whole hash block, so hashing time doesn't depend on the code
+ const zpad = Math.max(0, SHA512_BLOCK - prependLen(p).length - prependLen(DSI).length - 1)
+ return lvCat(DSI, p, new Uint8Array(zpad), ci, sid)
+}
+
+/** The encoded generator g; scalar_mult takes the encoding, so there's no separate internal form here. */
+export function cpaceGenerator(prs: string, ci: Uint8Array, sid: Uint8Array): Uint8Array {
+ const s = sodium()
+ return s.crypto_core_ristretto255_from_hash(s.crypto_hash_sha512(generatorString(prs, ci, sid)))
+}
+
+/** 32 random bytes with the bits above 252 cleared (the draft's recommended sampling). */
+function sampleScalar(): Uint8Array {
+ const y = sodium().randombytes_buf(32)
+ y[31] &= 0x0f
+ return y
+}
+
+/** scalar_mult_vfy: throws on an invalid encoding or the identity, which means abort. */
+function scalarMultVfy(y: Uint8Array, x: Uint8Array): Uint8Array {
+ if (x.length !== 32) throw new Error('cpace: bad point')
+ try {
+ return sodium().crypto_scalarmult_ristretto255(y, x)
+ } catch {
+ throw new Error('cpace: bad point')
+ }
+}
+
+// wipes K and the hash input once the key is out (best effort: JS may keep copies)
+function isk(sid: Uint8Array, k: Uint8Array, ya: Uint8Array, ada: Uint8Array, yb: Uint8Array, adb: Uint8Array): Uint8Array {
+ const input = concat(lvCat(DSI_ISK, sid, k), lvCat(ya, ada), lvCat(yb, adb))
+ try {
+ return sodium().crypto_hash_sha512(input)
+ } finally {
+ k.fill(0)
+ input.fill(0)
+ }
+}
+
+/** Initiator, step 1: send `ya` (the public share Ya), keep `secret` for cpaceFinish. Never pass `testScalar` outside test vectors. */
+export function cpaceStart(prs: string, ci: Uint8Array, sid: Uint8Array, ada = EMPTY, testScalar?: Uint8Array): { ya: Uint8Array; secret: CpaceSecret } {
+ const scalar = testScalar ?? sampleScalar()
+ try {
+ const ya = sodium().crypto_scalarmult_ristretto255(scalar, cpaceGenerator(prs, ci, sid))
+ return { ya, secret: { scalar, sid, ya, ada } }
+ } catch (err) {
+ scalar.fill(0)
+ throw err
+ }
+}
+
+/** Initiator, step 2: the 64-byte ISK from the responder's Yb. Single use: the scalar is wiped. */
+export function cpaceFinish(secret: CpaceSecret, yb: Uint8Array, adb = EMPTY): Uint8Array {
+ try {
+ return isk(secret.sid, scalarMultVfy(secret.scalar, yb), secret.ya, secret.ada, yb, adb)
+ } finally {
+ secret.scalar.fill(0)
+ }
+}
+
+/** Responder: answer the initiator's Ya with Yb and get the same ISK. Never pass `testScalar` outside test vectors. */
+export function cpaceRespond(prs: string, ci: Uint8Array, sid: Uint8Array, ya: Uint8Array, ada = EMPTY, adb = EMPTY, testScalar?: Uint8Array): { yb: Uint8Array; isk: Uint8Array } {
+ const scalar = testScalar ?? sampleScalar()
+ try {
+ const yb = sodium().crypto_scalarmult_ristretto255(scalar, cpaceGenerator(prs, ci, sid))
+ return { yb, isk: isk(sid, scalarMultVfy(scalar, ya), ya, ada, yb, adb) }
+ } finally {
+ scalar.fill(0)
+ }
+}
+
+const hkdf = (isk: Uint8Array, label: string) => new Uint8Array(hkdfSync('sha512', isk, EMPTY, label, 32))
+
+/** The keys for the pairing boxes: HKDF-SHA-512, empty salt, 32 bytes each. */
+export function pairKeys(isk: Uint8Array): { toPhone: Uint8Array; toDesktop: Uint8Array; confirm: Uint8Array } {
+ return { toPhone: hkdf(isk, 'yogurt pair to-phone'), toDesktop: hkdf(isk, 'yogurt pair to-desktop'), confirm: hkdf(isk, 'yogurt pair confirm') }
+}
diff --git a/app/src/main/companion/frames.ts b/app/src/main/companion/frames.ts
new file mode 100644
index 00000000..ae65eb87
--- /dev/null
+++ b/app/src/main/companion/frames.ts
@@ -0,0 +1,114 @@
+// The wire under the iPhone companion: every frame is a 2-byte big-endian length then that many bytes (a pairing JSON
+// message, a Noise handshake message, or a Noise transport message). App messages bigger than CHUNK_AT bytes go as
+// several transport messages {chunk: base64 of the next slice of the message's UTF-8 JSON, of: how many}, in order.
+// The phone's sync client (YogurtKit) speaks exactly this.
+
+export const MAX_FRAME = 65535
+/** an app message longer than this is split */
+export const CHUNK_AT = 60000
+/** bytes of the message in each chunk: base64 makes 44000 into 58668, under CHUNK_AT with the JSON around it */
+export const CHUNK_BYTES = 44000
+/** one reassembled message is at most this big */
+export const MAX_MESSAGE = 64 * 1024 * 1024
+
+export function frame(payload: Uint8Array): Buffer {
+ if (payload.length > MAX_FRAME) throw new Error('frame: too big')
+ const out = Buffer.alloc(2 + payload.length)
+ out.writeUInt16BE(payload.length, 0)
+ out.set(payload, 2)
+ return out
+}
+
+/**
+ * Cuts a byte stream into frames. Holds at most one unfinished frame, so a peer can't make it buffer more, and copies
+ * each byte once however finely it trickles in.
+ */
+export class FrameReader {
+ private head = Buffer.alloc(2)
+ private headLen = 0
+ private body: Buffer | null = null
+ private filled = 0
+
+ push(data: Buffer): Uint8Array[] {
+ const out: Uint8Array[] = []
+ let at = 0
+ while (at < data.length) {
+ if (!this.body) {
+ const n = Math.min(2 - this.headLen, data.length - at)
+ data.copy(this.head, this.headLen, at, at + n)
+ this.headLen += n; at += n
+ if (this.headLen < 2) break
+ this.body = Buffer.alloc(this.head.readUInt16BE(0))
+ this.filled = 0
+ if (!this.body.length) { out.push(new Uint8Array(0)); this.body = null; this.headLen = 0; continue }
+ }
+ const n = Math.min(this.body.length - this.filled, data.length - at)
+ data.copy(this.body, this.filled, at, at + n)
+ this.filled += n; at += n
+ if (this.filled === this.body.length) {
+ out.push(new Uint8Array(this.body.buffer, this.body.byteOffset, this.body.length))
+ this.body = null; this.headLen = 0
+ }
+ }
+ return out
+ }
+
+ /** bytes of a frame that hasn't fully arrived */
+ get waiting(): number { return this.headLen + (this.body ? this.filled : 0) }
+}
+
+const enc = new TextEncoder()
+const dec = new TextDecoder('utf-8', { fatal: true })
+
+/** One app message as the plaintexts to encrypt: itself, or its chunks. */
+export function splitMessage(message: object): Uint8Array[] {
+ const bytes = enc.encode(JSON.stringify(message))
+ if (bytes.length <= CHUNK_AT) return [bytes]
+ if (bytes.length > MAX_MESSAGE) throw new Error('frames: message too big')
+ const of = Math.ceil(bytes.length / CHUNK_BYTES)
+ const parts: Uint8Array[] = []
+ for (let i = 0; i < of; i++) {
+ const chunk = Buffer.from(bytes.subarray(i * CHUNK_BYTES, (i + 1) * CHUNK_BYTES)).toString('base64')
+ parts.push(enc.encode(JSON.stringify({ chunk, of })))
+ }
+ return parts
+}
+
+export function parseJson(bytes: Uint8Array): unknown {
+ return JSON.parse(dec.decode(bytes))
+}
+
+const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
+
+/** Puts chunked messages back together; throws on anything malformed or too big (the connection then closes). */
+export class Reassembler {
+ private parts: Buffer[] = []
+ private of = 0
+ private size = 0
+
+ constructor(private readonly max = MAX_MESSAGE) {}
+
+ /** A whole message once it has arrived, else null. */
+ push(plain: Uint8Array): Record<string, unknown> | null {
+ const v = parseJson(plain)
+ if (!isObject(v)) throw new Error('frames: not an object')
+ if (!('chunk' in v)) {
+ if (this.of) throw new Error('frames: message inside a chunked one')
+ return v
+ }
+ const { chunk, of } = v
+ if (typeof chunk !== 'string' || !Number.isSafeInteger(of) || (of as number) < 2 || (of as number) > Math.ceil(this.max / CHUNK_BYTES)) throw new Error('frames: bad chunk')
+ if (this.of && of !== this.of) throw new Error('frames: chunk count changed')
+ this.of = of as number
+ const part = Buffer.from(chunk, 'base64')
+ this.size += part.length
+ if (this.size > this.max) throw new Error('frames: message too big')
+ this.parts.push(part)
+ if (this.parts.length < this.of) return null
+ const whole = Buffer.concat(this.parts)
+ this.parts = []; this.of = 0; this.size = 0
+ const msg = parseJson(whole)
+ if (!isObject(msg) || 'chunk' in msg) throw new Error('frames: bad chunked message')
+ return msg
+ }
+}
diff --git a/app/src/main/companion/gate.ts b/app/src/main/companion/gate.ts
new file mode 100644
index 00000000..f1f852cf
--- /dev/null
+++ b/app/src/main/companion/gate.ts
@@ -0,0 +1,5 @@
+import { phoneCompanionOn } from '../../shared/companion'
+
+/** Whether to start the companion at all: never while the flag is off; in fake mode only when a test asks for it */
+export const companionWanted = (env: Record<string, string | undefined>, fake: boolean): boolean =>
+ phoneCompanionOn(env) && (!fake || env.YOGURT_FAKE_COMPANION === '1')
diff --git a/app/src/main/companion/handlers.ts b/app/src/main/companion/handlers.ts
new file mode 100644
index 00000000..c0b8f6bf
--- /dev/null
+++ b/app/src/main/companion/handlers.ts
@@ -0,0 +1,272 @@
+// What a paired phone can ask for once its Noise session is up. Requests are {id, type, body}; each gets
+// {id, type: "ok" | "error", body} (an error body is {code}), except `audio`, which answers with audioChunk messages.
+import { randomUUID } from 'node:crypto'
+import { createReadStream } from 'node:fs'
+import { mkdir, open, rm, stat, type FileHandle } from 'node:fs/promises'
+import { extname, join } from 'node:path'
+import type { Store } from '../store'
+import { applyOp, changesSince, type Op, type OpDeps } from './records'
+import { CHUNK_BYTES } from './frames'
+
+export type Scope = { folderId?: string; meetingIds?: string[] }
+/** n: the number the answer's [n] citations use for it */
+export type AskSource = { n: number; meetingId: string; title: string; atMs?: number | null; text: string }
+
+/** An Ask turn's sources as the phone gets them, each with its citation number */
+export const askSources = (sources: { n: number; meetingId: string; title: string; atMs: number | null; excerpt?: string }[]): AskSource[] =>
+ sources.map((s) => ({ n: s.n, meetingId: s.meetingId, title: s.title, atMs: s.atMs, text: s.excerpt ?? '' }))
+/** titleSource: 'default' for the phone's "Meeting at 3:04 PM", 'model' when Apple's model wrote it, 'typed' when the person did */
+/** language: the code of the language it was spoken in ('de'), as whisper takes it; left out when the phone didn't say */
+export type UploadMeeting = { id: string; title: string; titleSource: 'default' | 'model' | 'typed'; startedAt: number; endedAt: number; attendees: { name: string; email: string | null }[]; language?: string }
+export type PhoneDraft = { myNotes: string; transcript: { startMs: number; endMs: number; text: string }[]; summary?: string }
+
+export type HandlerDeps = {
+ store: Store
+ ask: (question: string, scope?: Scope) => Promise<{ answer: string; sources: AskSource[] }>
+ /** makes the meeting with the phone's id from its audio; called once per meeting */
+ importRecording: (meeting: UploadMeeting, audioPath: string, phoneDraft: PhoneDraft) => Promise<void>
+ audioFiles: (meetingId: string) => Promise<{ track: 'me' | 'them'; path: string }[]>
+ ops: Omit<OpDeps, 'nowMs'> & { /** a trash the desktop's own UI would refuse right now (saving, resuming) */ trashBlocked?: (meetingId: string) => boolean }
+ now: () => number
+ log: (...parts: unknown[]) => void
+}
+
+export type Hello = { desktopId: string; desktopName: string; desktopVersion: string }
+
+/** Where an upload's audio collects until all of it is in */
+export const MAX_AUDIO = 2 * 1024 ** 3
+const MAX_CHUNKS = Math.ceil(MAX_AUDIO / 1024)
+const ID = /^[\w-]{1,64}$/
+// names Windows keeps for devices: companion-uploads/NUL.m4a would write nowhere
+const DEVICE = /^(con|prn|aux|nul|com\d|lpt\d)$/i
+/** uploads staged at once (each can be up to MAX_AUDIO on disk) */
+const MAX_UPLOADS = 4
+
+export class RequestError extends Error {}
+/** an error's kind for the log: messages can hold paths with the person's name in them */
+const why = (err: unknown) => String((err as NodeJS.ErrnoException)?.code ?? (err as Error)?.name ?? 'error')
+const bad = () => new RequestError('bad-request')
+
+const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
+const str = (v: unknown, max: number): string => { if (typeof v !== 'string' || v.length > max) throw bad(); return v }
+const id = (v: unknown): string => { if (typeof v !== 'string' || !ID.test(v) || DEVICE.test(v)) throw bad(); return v }
+const int = (v: unknown, min = 0, max = Number.MAX_SAFE_INTEGER): number => { if (!Number.isSafeInteger(v) || (v as number) < min || (v as number) > max) throw bad(); return v as number }
+const ms = (v: unknown): number => int(v, 0, 8.64e15)
+
+function scopeOf(v: unknown): Scope | undefined {
+ if (v === undefined || v === null) return undefined
+ if (!isObject(v)) throw bad()
+ const out: Scope = {}
+ if (v.folderId !== undefined) out.folderId = id(v.folderId)
+ if (v.meetingIds !== undefined) {
+ if (!Array.isArray(v.meetingIds) || v.meetingIds.length > 500) throw bad()
+ out.meetingIds = v.meetingIds.map(id)
+ }
+ return out
+}
+
+/** The phone's BCP-47 language ('de-DE') as a language code; anything else is no language (whisper then listens for it) */
+function languageOf(v: unknown): string | undefined {
+ if (typeof v !== 'string' || !/^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i.test(v)) return undefined
+ const code = v.split('-')[0].toLowerCase()
+ // whisper calls Norwegian Bokmål "no"
+ return code === 'nb' ? 'no' : code
+}
+
+function meetingOf(v: unknown): UploadMeeting {
+ if (!isObject(v)) throw bad()
+ const startedAt = ms(v.startedAt), endedAt = ms(v.endedAt)
+ if (endedAt < startedAt) throw bad()
+ const attendees = v.attendees ?? []
+ if (!Array.isArray(attendees) || attendees.length > 200) throw bad()
+ const language = languageOf(v.language)
+ return {
+ id: id(v.id), title: str(v.title, 200).trim() || 'Recording', startedAt, endedAt, ...(language ? { language } : {}),
+ // anything else (left out, or from a newer phone) counts as the default title
+ titleSource: v.titleSource === 'model' || v.titleSource === 'typed' ? v.titleSource : 'default',
+ attendees: attendees.map((a) => {
+ if (!isObject(a)) throw bad()
+ return { name: str(a.name ?? '', 200), email: a.email == null ? null : str(a.email, 320) }
+ }),
+ }
+}
+
+function draftOf(body: Record<string, unknown>): PhoneDraft {
+ const transcript = body.transcript ?? []
+ if (!Array.isArray(transcript) || transcript.length > 100_000) throw bad()
+ return {
+ myNotes: str(body.myNotes ?? '', 1_000_000),
+ transcript: transcript.map((s) => {
+ if (!isObject(s)) throw bad()
+ return { startMs: int(s.startMs), endMs: int(s.endMs), text: str(s.text, 100_000) }
+ }),
+ ...(body.summary == null ? {} : { summary: str(body.summary, 1_000_000) }),
+ }
+}
+
+type Upload = { meeting: UploadMeeting; draft: PhoneDraft; file?: FileHandle; base: string; path: string; mime: string; next: number; of: number; size: number }
+/** what a phone may send: WAV (16 kHz mono, every platform transcribes it), or m4a from an older phone (Mac only) */
+const AUDIO_TYPES: Record<string, string> = { 'audio/wav': '.wav', 'audio/mp4': '.m4a' }
+
+/** One phone's requests. `uploadDir` holds audio being received; it's emptied when the handlers are made. */
+export function createHandlers(d: HandlerDeps & { hello: () => Hello; uploadDir: string }) {
+ const uploads = new Map<string, Upload>()
+ /** imports running now: a re-sent upload waits for its import to say whether the meeting really is in */
+ const importing = new Map<string, Promise<void>>()
+ /** true once the meeting is in for good; false when an import was running and failed (the phone sends it again) */
+ const imported = async (meetingId: string): Promise<boolean> => {
+ const running = importing.get(meetingId)
+ if (running) return running.then(() => true, () => false)
+ return !!d.store.meeting(meetingId)
+ }
+ const cleared = rm(d.uploadDir, { recursive: true, force: true }).catch(() => {})
+
+ const drop = async (u: Upload) => {
+ await u.file?.close().catch(() => {})
+ u.file = undefined
+ await rm(u.path, { force: true }).catch(() => {})
+ }
+
+ async function uploadMeeting(body: Record<string, unknown>) {
+ const meeting = meetingOf(body.meeting)
+ const draft = draftOf(body)
+ // sent again after a dropped connection: the meeting is made once. imported only when it is really in; until
+ // then the phone keeps its copy
+ if (await imported(meeting.id)) return { accepted: true, imported: true }
+ const old = uploads.get(meeting.id)
+ if (old) await drop(old)
+ else if (uploads.size >= MAX_UPLOADS) throw new RequestError('busy')
+ await cleared
+ await mkdir(d.uploadDir, { recursive: true })
+ const base = join(d.uploadDir, `${meeting.id}-${randomUUID()}`)
+ uploads.set(meeting.id, { meeting, draft, base, path: `${base}.m4a`, mime: 'audio/mp4', next: 0, of: 0, size: 0 })
+ d.log('COMPANION', 'upload', meeting.id)
+ return { accepted: true }
+ }
+
+ async function uploadAudio(body: Record<string, unknown>) {
+ const meetingId = id(body.meetingId)
+ const index = int(body.index, 0, MAX_CHUNKS), of = int(body.of, 1, MAX_CHUNKS)
+ const mime = body.mime === undefined ? 'audio/mp4' : body.mime
+ if (index >= of || typeof mime !== 'string' || !AUDIO_TYPES[mime]) throw bad()
+ if (importing.has(meetingId)) {
+ if (await imported(meetingId)) return { received: index, done: true, imported: true }
+ throw new RequestError('gone')
+ }
+ if (d.store.meeting(meetingId)) return { received: index, done: true, imported: true }
+ const u = uploads.get(meetingId)
+ if (!u) throw new RequestError('gone')
+ const chunk = Buffer.from(str(body.chunk, 4 * CHUNK_BYTES), 'base64')
+ // index 0 starts the audio over (a resumed upload); otherwise chunks come in order, a repeat of the last is fine
+ if (index === 0) { await drop(u); u.mime = mime; u.path = u.base + AUDIO_TYPES[mime]; u.file = await open(u.path, 'w'); u.next = 0; u.size = 0; u.of = of }
+ else if (mime !== u.mime) throw bad()
+ else if (index === u.next - 1 && of === u.of) return { received: index }
+ else if (index !== u.next || of !== u.of || !u.file) throw new RequestError('order')
+ u.size += chunk.length
+ if (u.size > MAX_AUDIO) { await drop(u); uploads.delete(meetingId); throw new RequestError('too-big') }
+ await u.file!.write(chunk)
+ u.next = index + 1
+ if (u.next < of) return { received: index }
+ await u.file!.sync(); await u.file!.close(); u.file = undefined
+ uploads.delete(meetingId)
+ const job = d.importRecording(u.meeting, u.path, u.draft)
+ importing.set(meetingId, job)
+ try {
+ await job
+ d.log('COMPANION', 'imported', meetingId, `chunks=${of}`)
+ } catch (err) {
+ d.log('COMPANION', 'import failed', meetingId, why(err))
+ throw new RequestError('failed')
+ } finally {
+ importing.delete(meetingId)
+ await rm(u.path, { force: true }).catch(() => {})
+ }
+ return { received: index, done: true, imported: true }
+ }
+
+ async function op(body: Record<string, unknown>) {
+ const kinds = ['setMine', 'rename', 'addToFolder', 'removeFromFolder', 'trash', 'restore']
+ if (typeof body.kind !== 'string' || !kinds.includes(body.kind)) throw bad()
+ const o: Op = {
+ kind: body.kind as Op['kind'], meetingId: id(body.meetingId),
+ ...(body.folderId !== undefined ? { folderId: id(body.folderId) } : {}),
+ ...(body.text !== undefined ? { text: str(body.text, 1_000_000) } : {}),
+ ...(body.title !== undefined ? { title: str(body.title, 200) } : {}),
+ ...(body.baseHash !== undefined ? { baseHash: str(body.baseHash, 64) } : {}),
+ }
+ if (o.kind === 'trash' && d.ops.trashBlocked?.(o.meetingId)) throw new RequestError('busy')
+ try {
+ return applyOp(d.store, o, { ...d.ops, nowMs: d.now })
+ } catch (err) {
+ const code = (err as Error).message
+ throw new RequestError(['gone', 'recording', 'bad-op'].includes(code) ? code : 'failed')
+ }
+ }
+
+ /** Streams one track as audioChunk messages under the request's id */
+ async function audio(reqId: string, body: Record<string, unknown>, send: (m: object) => Promise<void>) {
+ const meetingId = id(body.meetingId)
+ if (body.track !== 'me' && body.track !== 'them') throw bad()
+ const m = d.store.meeting(meetingId)
+ if (!m || m.trashedAt != null) throw new RequestError('gone')
+ const file = (await d.audioFiles(meetingId)).find((f) => f.track === body.track)
+ if (!file) throw new RequestError('gone')
+ const { size } = await stat(file.path)
+ const ext = extname(file.path).slice(1).toLowerCase()
+ const of = Math.max(1, Math.ceil(size / CHUNK_BYTES))
+ let index = 0
+ for await (const part of createReadStream(file.path, { highWaterMark: CHUNK_BYTES })) {
+ await send({ id: reqId, type: 'audioChunk', body: { chunk: (part as Buffer).toString('base64'), index: index++, of, ext } })
+ }
+ if (index === 0) await send({ id: reqId, type: 'audioChunk', body: { chunk: '', index: 0, of: 1, ext } })
+ d.log('COMPANION', 'audio', meetingId, `chunks=${of}`)
+ }
+
+ /** Answers one request; long ones (ask, audio) are awaited by the caller off the main queue. */
+ async function handle(msg: Record<string, unknown>, send: (m: object) => Promise<void>): Promise<void> {
+ const reqId = typeof msg.id === 'string' && msg.id.length <= 64 ? msg.id : null
+ if (reqId === null) throw new Error('handlers: request without an id')
+ const body = isObject(msg.body) ? msg.body : {}
+ const ok = (b: object) => send({ id: reqId, type: 'ok', body: b })
+ try {
+ switch (msg.type) {
+ case 'hello': {
+ if (body.schema !== 1) throw new RequestError('schema')
+ return await ok({ ...d.hello(), epoch: changesSince(d.store, Number.MAX_SAFE_INTEGER, 1).epoch })
+ }
+ case 'pull': {
+ const since = int(body.since ?? 0), limit = int(body.limit ?? 200, 1, 10_000)
+ const page = changesSince(d.store, since, limit)
+ d.log('COMPANION', 'pull', `since=${since}`, `changes=${page.changes.length}`, `more=${page.more}`)
+ return await ok(page)
+ }
+ case 'op': return await ok(await op(body))
+ case 'uploadMeeting': return await ok(await uploadMeeting(body))
+ case 'uploadAudio': return await ok(await uploadAudio(body))
+ case 'ask': {
+ const question = str(body.question, 4000)
+ if (!question.trim()) throw bad()
+ const r = await d.ask(question, scopeOf(body.scope))
+ d.log('COMPANION', 'ask', `sources=${r.sources.length}`)
+ return await ok(r)
+ }
+ case 'audio': return await audio(reqId, body, send)
+ default: throw new RequestError('unknown-type')
+ }
+ } catch (err) {
+ if (!(err instanceof RequestError)) d.log('COMPANION', 'request failed', String(msg.type).slice(0, 20), why(err))
+ await send({ id: reqId, type: 'error', body: { code: err instanceof RequestError ? err.message : 'failed' } })
+ }
+ }
+
+ return {
+ handle,
+ /** the connection went: audio half received is dropped (the phone sends it again from the start) */
+ async reset() {
+ // taken out first: an upload a new session stages meanwhile is its own
+ const old = [...uploads.values()]
+ uploads.clear()
+ for (const u of old) await drop(u)
+ },
+ }
+}
diff --git a/app/src/main/companion/index.ts b/app/src/main/companion/index.ts
new file mode 100644
index 00000000..97fd7fa9
--- /dev/null
+++ b/app/src/main/companion/index.ts
@@ -0,0 +1,357 @@
+// The iPhone companion on the desktop: off until the person starts pairing or a phone is paired. Then it listens on
+// every interface (a fixed port once picked, so the phone can try the last host:port) and advertises _yogurt._tcp
+// with TXT v=1, id, name, pairing=0|1. One phone at a time: pairing another replaces it.
+import { createHash, randomUUID } from 'node:crypto'
+import { existsSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { Store } from '../store'
+import { ready, sodium } from './sodium'
+import { keyPairFromPrivate, generateKeyPair, type KeyPair } from './noise'
+import { ATTEMPTS, newCode, PAIR_MS, type PairCtx, type PairedPhone } from './pairing'
+import { createHandlers, type HandlerDeps } from './handlers'
+import { LIMITS, startServer, type Limits, type Listening, type Session } from './server'
+import { bonjourAdvertiser, type Advertiser } from './advertise'
+import type { CompanionStatus } from '../../shared/companion'
+
+export type { CompanionStatus }
+
+export type CompanionDeps = Omit<HandlerDeps, 'now' | 'store'> & {
+ store: Store
+ userDataDir: string
+ /** keep the private key sealed with the system keychain (safeStorage) */
+ seal: (plain: string) => string
+ open: (sealed: string) => string
+ deviceName: () => string
+ appVersion?: string
+ /** a meeting is recording: its transcript changes all the time, so the phone hears of changes less often */
+ recording?: () => boolean
+ // for tests
+ now?: () => number
+ host?: string
+ advertiser?: Advertiser
+ limits?: Partial<Limits>
+ /** how often the change log is checked for something new to tell the phone about */
+ pollMs?: number
+}
+
+type Saved = { id: string; port?: number; publicKey: string; privateKey: string }
+type Device = { id: string; name: string; key: Uint8Array; lastSeen: number | null }
+
+/** While recording, a `changed` goes out at most this often */
+const RECORDING_PUSH_MS = 30_000
+/** codes one "Pair a phone" can go through (ATTEMPTS wrong guesses each) before pairing closes */
+const CODES = 3
+/** the pause after a wrong guess before the next one is taken */
+const RETRY_MS = 1000
+
+export async function createCompanion(d: CompanionDeps) {
+ await ready()
+ const now = d.now ?? Date.now
+ const limits: Limits = { ...LIMITS, ...d.limits }
+ const file = join(d.userDataDir, 'companion.json')
+ const advertiser = d.advertiser ?? bonjourAdvertiser(d.log)
+
+ const device = (): Device | null => {
+ const r = d.store.db.prepare('SELECT id, name, public_key, last_seen FROM companion_devices ORDER BY paired_at DESC LIMIT 1').get()
+ return r ? { id: String(r.id), name: String(r.name), key: Uint8Array.from(Buffer.from(String(r.public_key), 'base64')), lastSeen: r.last_seen == null ? null : Number(r.last_seen) } : null
+ }
+
+ // this computer's id and static key, made once; the private half sealed on disk
+ const found = identity()
+ if ('locked' in found) return lockedCompanion(found.locked, device)
+ const { saved, keys } = found
+ function identity(): { saved: Saved; keys: KeyPair } | { locked: string } {
+ let s: Saved | undefined
+ try {
+ const v = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : undefined
+ if (v && typeof v.id === 'string' && typeof v.publicKey === 'string' && typeof v.privateKey === 'string') s = v
+ } catch { /* not JSON: made again below */ }
+ if (s) {
+ let plain: string
+ // the keychain said no (locked, denied, not ready): keep the file and the pairing, try again next start
+ try { plain = d.open(s.privateKey) } catch (err) { d.log('COMPANION', 'keychain would not open the key', (err as Error).name); return { locked: s.id } }
+ const keys = keyPairFromPrivate(Uint8Array.from(Buffer.from(plain, 'base64')))
+ if (keys.privateKey.length === 32 && Buffer.from(keys.publicKey).toString('base64') === s.publicKey) return { saved: s, keys }
+ d.log('COMPANION', 'identity does not match its key, making a new one')
+ }
+ // a new key means the phone has to pair again
+ d.store.db.exec('DELETE FROM companion_devices')
+ const keys = generateKeyPair()
+ const made: Saved = { id: randomUUID(), publicKey: Buffer.from(keys.publicKey).toString('base64'), privateKey: d.seal(Buffer.from(keys.privateKey).toString('base64')) }
+ writeFileSync(file, JSON.stringify(made, null, 2), { mode: 0o600 })
+ return { saved: made, keys }
+ }
+ const persist = () => writeFileSync(file, JSON.stringify(saved, null, 2), { mode: 0o600 })
+
+ let pairing: { code: string; expiresAt: number; attemptsLeft: number; codes: number } | null = null
+ let pairingClosed: CompanionStatus['pairingClosed'] = null
+ let retryAt = 0
+ let listenFailed = false
+ /** the network refused the advert: the phone can't find this computer (cleared once one connects, or pairing starts again) */
+ let advertFailed = false
+ advertiser.onFailure = () => {
+ if (advertFailed) return
+ advertFailed = true
+ emit()
+ }
+ let expiry: NodeJS.Timeout | undefined
+ let server: Listening | null = null
+ let starting: Promise<void> | null = null
+ let session: Session | null = null
+ let busy = 0
+ let stopped = false
+ const listeners = new Set<(s: CompanionStatus) => void>()
+
+ const status = (): CompanionStatus => {
+ const dev = device()
+ const open = openPairing()
+ return {
+ paired: dev && { name: dev.name, lastSeen: dev.lastSeen },
+ pairing: open && { code: open.code, expiresAt: open.expiresAt, attemptsLeft: open.attemptsLeft },
+ pairingClosed,
+ error: listenFailed ? 'listen' : advertFailed ? 'network' : null,
+ connected: !!session,
+ syncing: busy > 0,
+ }
+ }
+ const emit = () => { const s = status(); for (const cb of listeners) cb(s) }
+
+ /** the pairing window, if still open: it closes on its own after PAIR_MS */
+ function openPairing() {
+ if (pairing && now() >= pairing.expiresAt) closePairing('expired')
+ return pairing
+ }
+
+ function closePairing(why: CompanionStatus['pairingClosed']) {
+ pairing = null
+ pairingClosed = why
+ clearTimeout(expiry)
+ void refresh()
+ }
+
+ /** A new code. One "Pair a phone" keeps its first two minutes, however many codes it goes through. */
+ function freshCode(window?: { expiresAt: number; codes: number }) {
+ const expiresAt = window?.expiresAt ?? now() + PAIR_MS
+ pairing = { code: newCode(), expiresAt, attemptsLeft: ATTEMPTS, codes: (window?.codes ?? 0) + 1 }
+ clearTimeout(expiry)
+ expiry = setTimeout(() => { openPairing(); emit() }, Math.max(0, expiresAt - now()) + 50)
+ expiry.unref?.()
+ }
+
+ const pairCtx = (): PairCtx | null => openPairing() && {
+ code: () => openPairing()?.code ?? null,
+ waiting: () => now() < retryAt,
+ guessed: () => { if (pairing) pairing.attemptsLeft-- },
+ stalled: () => { retryAt = now() + RETRY_MS },
+ failed: () => {
+ d.log('COMPANION', 'pair attempt failed', `left=${pairing?.attemptsLeft ?? 0}`)
+ retryAt = now() + RETRY_MS
+ if (pairing && pairing.attemptsLeft <= 0) {
+ // someone may be guessing: a few codes, then the person has to start pairing again
+ if (pairing.codes >= CODES) closePairing('tooMany')
+ else freshCode(pairing)
+ emit()
+ return 'tooMany'
+ }
+ emit()
+ return 'code'
+ },
+ desktop: { id: saved.id, name: d.deviceName(), publicKey: keys.publicKey },
+ }
+
+ function paired(phone: PairedPhone) {
+ const keyB64 = Buffer.from(phone.key).toString('base64')
+ const id = phone.id || createHash('sha256').update(phone.key).digest('hex').slice(0, 32)
+ // one phone: a new pairing replaces the old one, and the old one's session ends
+ d.store.db.exec('BEGIN')
+ try {
+ d.store.db.exec('DELETE FROM companion_devices')
+ d.store.db.prepare('INSERT INTO companion_devices (id, name, public_key, paired_at, last_seen) VALUES (?, ?, ?, ?, NULL)').run(id, phone.name || 'iPhone', keyB64, now())
+ d.store.db.exec('COMMIT')
+ } catch (err) { d.store.db.exec('ROLLBACK'); throw err }
+ session?.close()
+ closePairing(null)
+ d.log('COMPANION', 'paired', id)
+ emit()
+ }
+
+ const seen = () => { d.store.db.prepare('UPDATE companion_devices SET last_seen = ?').run(now()) }
+
+ const handlers = createHandlers({
+ ...d, now,
+ hello: () => ({ desktopId: saved.id, desktopName: d.deviceName(), desktopVersion: d.appVersion ?? '' }),
+ uploadDir: join(d.userDataDir, 'companion-uploads'),
+ })
+
+ // tells the phone when the change log moved, so it pulls; checked rather than hooked, so every write path counts
+ let lastCursor = 0, lastPush = 0
+ const maxSeq = () => Number(d.store.db.prepare('SELECT COALESCE(MAX(seq), 0) AS seq FROM companion_changes').get()?.seq ?? 0)
+ const poll = setInterval(() => {
+ if (!session) return
+ const cursor = maxSeq()
+ if (cursor === lastCursor) return
+ if (d.recording?.() && now() - lastPush < RECORDING_PUSH_MS) return
+ lastCursor = cursor; lastPush = now()
+ session.send({ type: 'changed', body: { cursor } }).catch(() => {})
+ }, d.pollMs ?? 1000)
+ poll.unref?.()
+
+ // every message 1 since start-up, oldest first, kept across the server turning off and on
+ const seenEphemerals = new Set<string>()
+ const fresh = (e: Uint8Array) => {
+ const k = Buffer.from(e).toString('base64')
+ if (seenEphemerals.has(k)) return false
+ seenEphemerals.add(k)
+ if (seenEphemerals.size > limits.replays) seenEphemerals.delete(seenEphemerals.values().next().value!)
+ return true
+ }
+
+ async function listen() {
+ if (server || stopped) return
+ starting ??= (async () => {
+ const hooks = {
+ limits, now, log: d.log,
+ pairing: pairCtx, paired,
+ phoneKey: () => device()?.key ?? null,
+ fresh,
+ staticKey: () => keys,
+ opened: (s: Session) => {
+ session?.close()
+ session = s
+ advertFailed = false
+ lastCursor = maxSeq()
+ seen()
+ d.log('COMPANION', 'session opened')
+ emit()
+ },
+ closed: (s: Session) => {
+ if (session !== s) return
+ session = null
+ busy = 0
+ seen()
+ void handlers.reset()
+ d.log('COMPANION', 'session closed')
+ emit()
+ },
+ handle: handlers.handle,
+ busy: (delta: 1 | -1) => { const was = busy > 0; busy = Math.max(0, busy + delta); if (was !== busy > 0) emit() },
+ }
+ const host = d.host ?? '0.0.0.0'
+ try {
+ try {
+ server = await startServer(hooks, saved.port ?? 0, host)
+ } catch (err) {
+ // the port we had is taken now: a new one (the phone finds it again through Bonjour)
+ if ((err as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw err
+ server = await startServer(hooks, 0, host)
+ }
+ } catch (err) { listenFailed = true; throw err }
+ listenFailed = false
+ const port = server.port
+ if (port !== saved.port) { saved.port = port; persist() }
+ d.log('COMPANION', 'listening', `port=${port}`)
+ })().finally(() => { starting = null })
+ await starting
+ }
+
+ /** On while pairing or paired, off otherwise; the advertisement follows. One at a time, so the last word wins. */
+ let refreshing: Promise<void> = Promise.resolve()
+ const refresh = () => {
+ refreshing = refreshing.then(turn).catch((err) => {
+ d.log('COMPANION', 'could not turn on or off', (err as NodeJS.ErrnoException).code ?? (err as Error).name)
+ })
+ return refreshing
+ }
+ const wanted = () => !stopped && (!!pairing || !!device())
+ async function turn() {
+ if (wanted()) await listen()
+ // asked again while it started (pairing cancelled, expired): off after all
+ if (!wanted() || !server) {
+ advertiser.stop()
+ if (!stopped) session?.close()
+ const s = server
+ server = null
+ await s?.close()
+ return
+ }
+ advertiser.publish({ name: `Yogurt ${saved.id.slice(0, 8)}`, port: saved.port!, txt: { v: '1', id: saved.id, name: d.deviceName(), pairing: pairing ? '1' : '0' } })
+ }
+
+ await refresh()
+
+ return {
+ /** a new six-digit code for two minutes; the server starts if it wasn't running */
+ async startPairing(): Promise<{ code: string; expiresAt: number }> {
+ listenFailed = false
+ advertFailed = false
+ freshCode()
+ pairingClosed = null
+ retryAt = 0
+ const { code, expiresAt } = pairing!
+ emit()
+ await refresh()
+ // nothing listens, so no phone could reach the code: closed, and the status says why (also when it was
+ // cancelled meanwhile, so the caller never hears ok for a code nobody could use)
+ if (!server && listenFailed) {
+ if (pairing?.code === code) { pairing = null; clearTimeout(expiry); await refresh() }
+ emit()
+ throw new Error('listen')
+ }
+ d.log('COMPANION', 'pairing opened')
+ return { code, expiresAt }
+ },
+ async cancelPairing() {
+ listenFailed = false
+ closePairing(null)
+ await refresh()
+ emit()
+ },
+ async unpair() {
+ listenFailed = false
+ d.store.db.exec('DELETE FROM companion_devices')
+ session?.close()
+ d.log('COMPANION', 'unpaired')
+ await refresh()
+ emit()
+ },
+ status,
+ onStatus(cb: (s: CompanionStatus) => void) { listeners.add(cb); return () => { listeners.delete(cb) } },
+ /** the port it listens on, when it does */
+ port: () => server?.port ?? null,
+ desktopId: saved.id,
+ publicKey: keys.publicKey,
+ async stop() {
+ stopped = true
+ clearInterval(poll)
+ clearTimeout(expiry)
+ session?.close()
+ // goodbye first, so the phone sees this computer leave rather than waiting out the record's lifetime
+ await advertiser.destroy?.()
+ await refresh()
+ await handlers.reset()
+ sodium().memzero(keys.privateKey)
+ },
+ }
+}
+
+
+/** The keychain wouldn't open the key: everything stays as it was, off, and says why. */
+function lockedCompanion(desktopId: string, device: () => { name: string; lastSeen: number | null } | null) {
+ const status = (): CompanionStatus => {
+ const dev = device()
+ return { paired: dev && { name: dev.name, lastSeen: dev.lastSeen }, pairing: null, pairingClosed: null, error: 'keychain', connected: false, syncing: false }
+ }
+ return {
+ async startPairing(): Promise<{ code: string; expiresAt: number }> { throw new Error('keychain') },
+ async cancelPairing() {},
+ async unpair() {},
+ status,
+ onStatus(_cb: (s: CompanionStatus) => void) { return () => {} },
+ port: (): number | null => null,
+ desktopId,
+ publicKey: new Uint8Array(0),
+ async stop() {},
+ }
+}
+
+export type Companion = Awaited<ReturnType<typeof createCompanion>>
diff --git a/app/src/main/companion/ipc.ts b/app/src/main/companion/ipc.ts
new file mode 100644
index 00000000..69e25d06
--- /dev/null
+++ b/app/src/main/companion/ipc.ts
@@ -0,0 +1,22 @@
+// Settings → Phone talks to the companion through these. It starts after the window can ask, so each call waits for
+// it; when it never started (fake mode, or it failed) the status is null and Settings shows nothing to pair.
+import { ipcMain } from 'electron'
+import type { CompanionStatus } from '../../shared/companion'
+import type { Companion } from './index'
+
+type Bridge = Pick<Companion, 'status' | 'onStatus' | 'startPairing' | 'cancelPairing' | 'unpair'>
+
+export function hookCompanion(d: { companion: Promise<Bridge | undefined>; send: (s: CompanionStatus) => void }) {
+ const ready = d.companion.catch(() => undefined)
+ void ready.then((c) => { c?.onStatus(d.send) })
+ ipcMain.handle('companion:status', async () => (await ready)?.status() ?? null)
+ // the code itself is in the status; a failure's reason too (keychain, listen)
+ ipcMain.handle('companion:start-pairing', async () => {
+ const c = await ready
+ if (!c) return { ok: false, status: null }
+ try { await c.startPairing(); return { ok: true, status: c.status() } } catch { return { ok: false, status: c.status() } }
+ })
+ // a failure answers the status as it is, so the window shows what is true rather than an error it can't place
+ ipcMain.handle('companion:cancel-pairing', async () => { const c = await ready; await c?.cancelPairing().catch(() => {}); return c?.status() ?? null })
+ ipcMain.handle('companion:unpair', async () => { const c = await ready; await c?.unpair().catch(() => {}); return c?.status() ?? null })
+}
diff --git a/app/src/main/companion/noise.ts b/app/src/main/companion/noise.ts
new file mode 100644
index 00000000..6937ebb4
--- /dev/null
+++ b/app/src/main/companion/noise.ts
@@ -0,0 +1,280 @@
+// Noise_KK_25519_ChaChaPoly_BLAKE2b (Noise spec rev 34). Both static keys are known from pairing:
+// -> s <- s ... -> e, es, ss <- e, ee, se
+// YogurtKit's Noise.swift mirrors this file.
+import { sodium } from './sodium'
+
+const PROTOCOL = 'Noise_KK_25519_ChaChaPoly_BLAKE2b'
+const HASHLEN = 64
+const BLOCKLEN = 128
+const MAX_MESSAGE = 65535
+const EMPTY = new Uint8Array(0)
+
+export interface KeyPair { publicKey: Uint8Array; privateKey: Uint8Array }
+
+export function keyPairFromPrivate(privateKey: Uint8Array): KeyPair {
+ return { publicKey: sodium().crypto_scalarmult_base(privateKey), privateKey }
+}
+
+export function generateKeyPair(): KeyPair {
+ return keyPairFromPrivate(sodium().randombytes_buf(32))
+}
+
+function concat(...parts: Uint8Array[]): Uint8Array {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
+ let at = 0
+ for (const p of parts) { out.set(p, at); at += p.length }
+ return out
+}
+
+const hash = (data: Uint8Array) => sodium().crypto_generichash(HASHLEN, data, null)
+
+// HMAC built from plain BLAKE2b as the spec says (§4.3), not BLAKE2b's own keyed mode
+function hmac(key: Uint8Array, data: Uint8Array): Uint8Array {
+ const k = new Uint8Array(BLOCKLEN)
+ k.set(key.length > BLOCKLEN ? hash(key) : key)
+ const inner = k.map((x) => x ^ 0x36), outer = k.map((x) => x ^ 0x5c)
+ const out = hash(concat(outer, hash(concat(inner, data))))
+ for (const b of [k, inner, outer]) b.fill(0)
+ return out
+}
+
+function hkdf(ck: Uint8Array, ikm: Uint8Array): [Uint8Array, Uint8Array] {
+ const temp = hmac(ck, ikm)
+ const one = hmac(temp, Uint8Array.of(1))
+ const two = hmac(temp, concat(one, Uint8Array.of(2)))
+ temp.fill(0)
+ return [one, two]
+}
+
+/** First 32 bytes as a new key; wipes the 64-byte HKDF output. */
+function key32(out: Uint8Array): Uint8Array {
+ const k = out.slice(0, 32)
+ out.fill(0)
+ return k
+}
+
+const dh = (kp: KeyPair, pub: Uint8Array) => sodium().crypto_scalarmult(kp.privateKey, pub)
+
+// 4 zero bytes then the 64-bit counter, little-endian
+function nonceBytes(n: bigint): Uint8Array {
+ const out = new Uint8Array(12)
+ new DataView(out.buffer).setBigUint64(4, n, true)
+ return out
+}
+
+const MAX_NONCE = 2n ** 64n - 1n
+const TAG = 16
+
+/** A transport cipher. Always keyed: an unkeyed one would put plaintext on the wire. */
+export class CipherState {
+ private k: Uint8Array
+ private n = 0n
+
+ constructor(k: Uint8Array) {
+ if (!(k instanceof Uint8Array) || k.length !== 32) throw new Error('noise: a cipher needs a 32-byte key')
+ // its own copy: a caller reusing or wiping its buffer can't change this key
+ this.k = k.slice()
+ }
+
+ encryptWithAd(ad: Uint8Array, pt: Uint8Array): Uint8Array {
+ if (pt.length + TAG > MAX_MESSAGE) throw new Error('noise: message too big')
+ if (this.n >= MAX_NONCE) throw new Error('noise: nonce exhausted')
+ const ct = sodium().crypto_aead_chacha20poly1305_ietf_encrypt(pt, ad, null, nonceBytes(this.n), this.k)
+ this.n++
+ return ct
+ }
+
+ /** Throws on a changed, replayed or out-of-order message; the counter only moves on success. */
+ decryptWithAd(ad: Uint8Array, ct: Uint8Array): Uint8Array {
+ if (ct.length > MAX_MESSAGE) throw new Error('noise: message too big')
+ if (this.n >= MAX_NONCE) throw new Error('noise: nonce exhausted')
+ let pt: Uint8Array
+ try {
+ pt = sodium().crypto_aead_chacha20poly1305_ietf_decrypt(null, ct, ad, nonceBytes(this.n), this.k)
+ } catch {
+ throw new Error('noise: could not decrypt')
+ }
+ this.n++
+ return pt
+ }
+
+ encrypt(pt: Uint8Array): Uint8Array { return this.encryptWithAd(EMPTY, pt) }
+ decrypt(ct: Uint8Array): Uint8Array { return this.decryptWithAd(EMPTY, ct) }
+
+ rekey(): void {
+ const out = sodium().crypto_aead_chacha20poly1305_ietf_encrypt(new Uint8Array(32), EMPTY, null, nonceBytes(MAX_NONCE), this.k)
+ this.k.fill(0)
+ this.k = key32(out)
+ }
+
+ /** Best-effort wipe of the key; the cipher is unusable afterwards. */
+ wipe(): void { this.k.fill(0) }
+}
+
+/** A cipher on a key made here; the temporary copy is wiped. */
+function keyed(k: Uint8Array): CipherState {
+ const c = new CipherState(k)
+ k.fill(0)
+ return c
+}
+
+class SymmetricState {
+ h: Uint8Array
+ private ck: Uint8Array
+ // null until the first DH: handshake payloads before that go in the clear, as Noise says
+ private cipher: CipherState | null = null
+
+ constructor() {
+ const name = new TextEncoder().encode(PROTOCOL)
+ this.h = new Uint8Array(HASHLEN)
+ this.h.set(name) // shorter than HASHLEN, so zero-padded rather than hashed
+ this.ck = this.h.slice()
+ }
+
+ mixHash(data: Uint8Array): void { this.h = hash(concat(this.h, data)) }
+
+ /** Wipes ikm (always a DH output here) once mixed in. */
+ mixKey(ikm: Uint8Array): void {
+ const [ck, k] = hkdf(this.ck, ikm)
+ ikm.fill(0)
+ this.ck.fill(0)
+ this.ck = ck
+ this.cipher?.wipe()
+ this.cipher = keyed(key32(k))
+ }
+
+ encryptAndHash(pt: Uint8Array): Uint8Array {
+ const ct = this.cipher ? this.cipher.encryptWithAd(this.h, pt) : pt
+ this.mixHash(ct)
+ return ct
+ }
+
+ decryptAndHash(ct: Uint8Array): Uint8Array {
+ const pt = this.cipher ? this.cipher.decryptWithAd(this.h, ct) : ct
+ this.mixHash(ct)
+ return pt
+ }
+
+ /** One shot: wipes the chaining key and the handshake cipher. */
+ split(): [CipherState, CipherState] {
+ const [a, b] = hkdf(this.ck, EMPTY)
+ this.ck.fill(0)
+ this.cipher?.wipe()
+ this.cipher = null
+ return [keyed(key32(a)), keyed(key32(b))]
+ }
+}
+
+export interface NoiseOptions {
+ initiator: boolean
+ s: KeyPair
+ /** The other side's static public key, known from pairing. */
+ rs: Uint8Array
+ prologue: Uint8Array
+ /** A fixed ephemeral key. Test vectors only: reusing one in a real session breaks forward secrecy. */
+ testEphemeral?: KeyPair
+}
+
+export class NoiseKK {
+ private readonly ss = new SymmetricState()
+ private readonly o: NoiseOptions
+ private e: KeyPair | undefined
+ private re: Uint8Array | undefined
+ private step = 0
+ private failed = false
+ private splitDone = false
+
+ constructor(o: NoiseOptions) {
+ if (o.rs.length !== 32) throw new Error('noise: bad remote key')
+ this.o = o
+ this.e = o.testEphemeral
+ this.ss.mixHash(o.prologue)
+ const [is, rs] = o.initiator ? [o.s.publicKey, o.rs] : [o.rs, o.s.publicKey]
+ this.ss.mixHash(is)
+ this.ss.mixHash(rs)
+ }
+
+ get done(): boolean { return this.step === 2 }
+
+ /** Same on both ends once done; usable as a channel binding. A copy, and only once the handshake is done. */
+ get handshakeHash(): Uint8Array {
+ if (!this.done) throw new Error('noise: handshake not done')
+ return this.ss.h.slice()
+ }
+
+ private myTurn(): boolean { return (this.step === 0) === this.o.initiator }
+
+ private check(writing: boolean): void {
+ if (this.failed) throw new Error('noise: handshake failed')
+ if (this.done) throw new Error('noise: handshake already done')
+ if (this.myTurn() !== writing) throw new Error('noise: not this side\'s turn')
+ }
+
+ // es/ss for message 1, ee/se for message 2, from whichever side is running
+ private mixDh(): void {
+ const { s, rs, initiator } = this.o
+ const e = this.e!, re = this.re!
+ if (this.step === 0) {
+ this.ss.mixKey(initiator ? dh(e, rs) : dh(s, re))
+ this.ss.mixKey(dh(s, rs))
+ } else {
+ this.ss.mixKey(dh(e, re))
+ this.ss.mixKey(initiator ? dh(s, re) : dh(e, rs))
+ }
+ }
+
+ // the ephemeral private key is only needed until both DH steps that use it are done
+ private advance(): void {
+ this.step++
+ if (this.done) this.e?.privateKey.fill(0)
+ }
+
+ // a dead handshake never needs its ephemeral again
+ private fail(): void {
+ this.failed = true
+ this.e?.privateKey.fill(0)
+ }
+
+ /** Throws on a bad remote key or oversized payload; the handshake can't continue after that. */
+ writeMessage(payload: Uint8Array): Uint8Array {
+ this.check(true)
+ if (32 + payload.length + 16 > MAX_MESSAGE) throw new Error('noise: payload too big')
+ try {
+ this.e ??= generateKeyPair()
+ this.ss.mixHash(this.e.publicKey)
+ this.mixDh()
+ const msg = concat(this.e.publicKey, this.ss.encryptAndHash(payload))
+ this.advance()
+ return msg
+ } catch (err) {
+ this.fail()
+ throw err
+ }
+ }
+
+ /** Throws when the message wasn't made by the expected peer; the handshake can't continue after that. */
+ readMessage(msg: Uint8Array): Uint8Array {
+ this.check(false)
+ try {
+ if (msg.length < 32 + 16 || msg.length > MAX_MESSAGE) throw new Error('noise: bad message length')
+ this.re = msg.slice(0, 32)
+ this.ss.mixHash(this.re)
+ this.mixDh()
+ const payload = this.ss.decryptAndHash(msg.subarray(32))
+ this.advance()
+ return payload
+ } catch (err) {
+ this.fail()
+ throw err
+ }
+ }
+
+ /** The transport ciphers for this side: send to the peer, receive from the peer. Once only: a second pair would reuse nonces. */
+ split(): { send: CipherState; recv: CipherState } {
+ if (!this.done) throw new Error('noise: handshake not done')
+ if (this.splitDone) throw new Error('noise: already split')
+ this.splitDone = true
+ const [c1, c2] = this.ss.split()
+ return this.o.initiator ? { send: c1, recv: c2 } : { send: c2, recv: c1 }
+ }
+}
diff --git a/app/src/main/companion/pairing.ts b/app/src/main/companion/pairing.ts
new file mode 100644
index 00000000..0a402b8e
--- /dev/null
+++ b/app/src/main/companion/pairing.ts
@@ -0,0 +1,117 @@
+// Pairing over one connection, before any Noise session (the desktop is CPace initiator A):
+// pairHello {v:1, phoneSession, phoneName} → pairStart {v:1, desktopSession, desktopId, desktopName, ya}
+// → pairReply {yb} → pairConfirm {box} → pairDone {box} → pairOk {} | pairFail {reason: code | expired | tooMany | busy}
+// sid = desktopSession ‖ phoneSession, CI = "yogurt-pair-v1" ‖ desktopSession ‖ phoneSession, no AD. The boxes are
+// XChaCha20-Poly1305 under pairKeys(ISK) (toPhone, AD "pairConfirm"; toDesktop, AD "pairDone") holding JSON
+// {key, name, id}; opening one is the key confirmation. Binary fields are base64. Every frame has a "type".
+import { randomInt } from 'node:crypto'
+import { cpaceFinish, cpaceStart, pairKeys } from './cpace'
+import { openBox, sealBox } from './box'
+import { parseJson } from './frames'
+import { sodium } from './sodium'
+
+/** How long a code works, and how many wrong tries it takes before a new one */
+export const PAIR_MS = 2 * 60 * 1000
+export const ATTEMPTS = 5
+
+/** busy: another phone is mid-exchange, or a wrong guess was just made (try again in a second) */
+export type PairFail = 'code' | 'expired' | 'tooMany' | 'busy'
+export type PairedPhone = { key: Uint8Array; name: string; id: string }
+
+/** Six digits, every one equally likely */
+export const newCode = () => String(randomInt(0, 1_000_000)).padStart(6, '0')
+
+export type PairIo = { next: () => Promise<Uint8Array>; send: (msg: object) => void }
+
+export type PairCtx = {
+ /** the code now, or null when pairing is closed or the code ran out */
+ code: () => string | null
+ /** a wrong guess was made a moment ago: the next one waits */
+ waiting: () => boolean
+ /** one guess at the code was made (the phone has a box it can check its guess against): counts against the code */
+ guessed: () => void
+ /** a phone said hello and then nothing usable: no guess, but the same pause as one, so stalls can't hold pairing */
+ stalled: () => void
+ /** a counted guess didn't pair: 'tooMany' once the code is used up (the caller makes a new one) */
+ failed: () => PairFail
+ desktop: { id: string; name: string; publicKey: Uint8Array }
+}
+
+const enc = new TextEncoder()
+const dec = new TextDecoder()
+const b64 = (b: Uint8Array) => Buffer.from(b).toString('base64')
+
+function bytes(v: unknown, length: number): Uint8Array {
+ if (typeof v !== 'string' || v.length > 200) throw new Error('pairing: bad field')
+ const out = Uint8Array.from(Buffer.from(v, 'base64'))
+ if (out.length !== length || b64(out) !== v) throw new Error('pairing: bad field')
+ return out
+}
+
+function name(v: unknown): string {
+ if (typeof v !== 'string') throw new Error('pairing: bad name')
+ return v.replace(/\s+/g, ' ').trim().slice(0, 100)
+}
+
+async function message(io: PairIo, type: string): Promise<Record<string, unknown>> {
+ const v = parseJson(await io.next()) as Record<string, unknown>
+ if (!v || typeof v !== 'object' || v.type !== type) throw new Error(`pairing: expected ${type}`)
+ return v
+}
+
+/** A pairHello that is well formed, or throws */
+export function readHello(v: Record<string, unknown>): { phoneSession: Uint8Array; phoneName: string } {
+ if (v.type !== 'pairHello' || v.v !== 1) throw new Error('pairing: bad hello')
+ return { phoneSession: bytes(v.phoneSession, 16), phoneName: name(v.phoneName) }
+}
+
+/**
+ * Runs the exchange after a pairHello. Resolves with the phone on success (the caller stores it and answers pairOk),
+ * or the reason it was refused (already sent as pairFail). Throws when the phone breaks off or sends garbage after
+ * its guess; that guess still counts (ctx.failed is called).
+ */
+export async function pair(io: PairIo, hello: Record<string, unknown>, ctx: PairCtx): Promise<{ phone: PairedPhone } | { fail: PairFail }> {
+ const { phoneSession } = readHello(hello)
+ const code = ctx.code()
+ if (!code) { io.send({ type: 'pairFail', reason: 'expired' }); return { fail: 'expired' } }
+ const desktopSession = sodium().randombytes_buf(16)
+ const sid = new Uint8Array([...desktopSession, ...phoneSession])
+ const ci = new Uint8Array([...enc.encode('yogurt-pair-v1'), ...desktopSession, ...phoneSession])
+ const { ya, secret } = cpaceStart(code, ci, sid)
+ io.send({ type: 'pairStart', v: 1, desktopSession: b64(desktopSession), desktopId: ctx.desktop.id, desktopName: ctx.desktop.name, ya: b64(ya) })
+ let yb: Uint8Array
+ try { yb = bytes((await message(io, 'pairReply')).yb, 32) } catch (err) { secret.scalar.fill(0); ctx.stalled(); throw err }
+ // from here the phone can test its one guess against pairConfirm, so it counts whatever happens next
+ ctx.guessed()
+ let keys: ReturnType<typeof pairKeys> | undefined
+ let paired = false
+ try {
+ const isk = cpaceFinish(secret, yb)
+ keys = pairKeys(isk)
+ isk.fill(0)
+ const mine = enc.encode(JSON.stringify({ key: b64(ctx.desktop.publicKey), name: ctx.desktop.name, id: ctx.desktop.id }))
+ io.send({ type: 'pairConfirm', box: b64(sealBox(keys.toPhone, mine, enc.encode('pairConfirm'))) })
+ const done = await message(io, 'pairDone')
+ let phone: PairedPhone
+ try {
+ const box = done.box
+ if (typeof box !== 'string' || box.length > 2000) throw new Error('pairing: bad box')
+ const v = JSON.parse(dec.decode(openBox(keys.toDesktop, Uint8Array.from(Buffer.from(box, 'base64')), enc.encode('pairDone'))))
+ phone = { key: bytes(v.key, 32), name: name(v.name), id: typeof v.id === 'string' && /^[\w-]{1,64}$/.test(v.id) ? v.id : '' }
+ } catch {
+ // a wrong code: this side's box doesn't open
+ const reason = ctx.failed()
+ io.send({ type: 'pairFail', reason })
+ return { fail: reason }
+ }
+ paired = true
+ // the window closed (or the code changed) while this ran: the person no longer expects a phone
+ if (ctx.code() !== code) { io.send({ type: 'pairFail', reason: 'expired' }); return { fail: 'expired' } }
+ return { phone }
+ } catch (err) {
+ if (!paired) ctx.failed()
+ throw err
+ } finally {
+ if (keys) for (const k of Object.values(keys)) k.fill(0)
+ }
+}
diff --git a/app/src/main/companion/phoneImport.ts b/app/src/main/companion/phoneImport.ts
new file mode 100644
index 00000000..99bc8c2b
--- /dev/null
+++ b/app/src/main/companion/phoneImport.ts
@@ -0,0 +1,59 @@
+// A meeting recorded on the iPhone, made on this computer from its upload. The phone sends 16 kHz mono 16-bit WAV, the
+// same audio an uploaded file is turned into, so every platform can transcribe it (older phones sent m4a, which only a
+// Mac decodes). What the phone already has (its transcript and draft notes) shows until this computer has its own.
+import { mkdir, open, rename, copyFile, rm } from 'node:fs/promises'
+import { extname, join } from 'node:path'
+import type { Meeting, Store } from '../store'
+import { AUDIO_SPEAKER } from '../../shared/audioUpload'
+import { languageCode, languageName } from '../asr/appleSpeech'
+import type { PhoneDraft, UploadMeeting } from './handlers'
+
+/** sourceId of a phone meeting whose notes are still the phone's draft: the computer's notes replace them once */
+const DRAFT = 'phone-draft:'
+
+export const isPhoneDraft = (m: Pick<Meeting, 'sourceId'> | undefined): boolean => !!m?.sourceId?.startsWith(DRAFT)
+/** The language a phone recording was spoken in, as whisper's code: the phone said so, so it is not guessed */
+export const phoneLanguage = (m: Pick<Meeting, 'sourceId' | 'language'> | undefined): string | undefined =>
+ (m?.sourceId?.startsWith('phone') && languageCode(m.language)) || undefined
+/** the computer is writing its own notes now: the draft mark goes, so later transcriptions keep them */
+export const phoneDraftReplaced = (store: Pick<Store, 'updateMeeting'>, id: string) => store.updateMeeting(id, { sourceId: `phone:${id}` })
+
+/** A canonical WAV header: PCM, one channel, 16 kHz, 16-bit, data right after (what uploadedAudio reads). */
+export async function phoneWavOk(path: string): Promise<boolean> {
+ const f = await open(path, 'r')
+ try {
+ const h = Buffer.alloc(44)
+ const { bytesRead } = await f.read(h, 0, 44, 0)
+ return bytesRead === 44 && h.toString('ascii', 0, 4) === 'RIFF' && h.toString('ascii', 8, 12) === 'WAVE' && h.toString('ascii', 12, 16) === 'fmt '
+ && h.readUInt16LE(20) === 1 && h.readUInt16LE(22) === 1 && h.readUInt32LE(24) === 16000 && h.readUInt16LE(34) === 16
+ && h.toString('ascii', 36, 40) === 'data'
+ } finally { await f.close() }
+}
+
+export async function importPhoneRecording(
+ d: { store: Store; meetingDir: (id: string) => string; start: (id: string, again: boolean) => unknown; changed: () => void },
+ m: UploadMeeting, audioPath: string, draft: PhoneDraft,
+): Promise<void> {
+ if (d.store.meeting(m.id)) return
+ const wav = extname(audioPath).toLowerCase() === '.wav'
+ if (wav && !(await phoneWavOk(audioPath))) throw new Error('Unsupported phone audio')
+ const dir = d.meetingDir(m.id), target = join(dir, wav ? 'them.wav' : 'them.m4a')
+ await mkdir(dir, { recursive: true })
+ await rename(audioPath, target).catch(async () => { await copyFile(audioPath, target); await rm(audioPath, { force: true }) })
+ const lines = draft.transcript.filter((l) => l.text.trim())
+ const summary = draft.summary?.trim() ? draft.summary : undefined
+ // the phone's default title is this computer's to replace once its notes are written, like a generic one here; a
+ // title Apple's model wrote can be improved the same way; one the person typed stays
+ const titleSource = m.titleSource === 'typed' ? 'user' : m.titleSource === 'model' ? 'auto' : 'generic'
+ d.store.createMeeting({ title: m.title, titleSource, source: 'audio-file',
+ startedAt: m.startedAt, endedAt: m.endedAt, durationMs: m.endedAt - m.startedAt, eventId: null, app: null, attendees: m.attendees,
+ state: 'stopped', transcriptionPending: true, language: m.language ? languageName(m.language) : null }, m.id)
+ // marked as the phone's, so its language is kept when it is transcribed (phoneLanguage)
+ d.store.updateMeeting(m.id, { sourceId: summary ? DRAFT + m.id : `phone:${m.id}` })
+ if (draft.myNotes.trim() || summary) d.store.setNotes(m.id, { mine: draft.myNotes, ...(summary ? { enhanced: summary } : {}) })
+ // one microphone in a room: nobody is named, like an uploaded file
+ if (lines.length) d.store.addSegments(lines.map((l) => ({ meetingId: m.id, track: 'them' as const, startMs: l.startMs, endMs: l.endMs, text: l.text.trim(), speaker: AUDIO_SPEAKER })))
+ d.changed()
+ // with the phone's lines shown, this computer's transcript is staged and replaces them only when it is done
+ void d.start(m.id, lines.length > 0)
+}
diff --git a/app/src/main/companion/records.ts b/app/src/main/companion/records.ts
new file mode 100644
index 00000000..35d40b16
--- /dev/null
+++ b/app/src/main/companion/records.ts
@@ -0,0 +1,147 @@
+import { createHash } from 'node:crypto'
+import type { Store } from '../store'
+import { renameMeeting } from '../meeting'
+import { moveToTrash } from '../trash'
+import { FROM_IPHONE } from '../../shared/companion'
+import { AUDIO_SPEAKER } from '../../shared/audioUpload'
+
+/**
+ * What the iPhone receives on `pull`, and the edits it sends back as `op`s. The change log is the companion_changes
+ * table (triggers in store.ts); each record is read fresh from the store, so a phone always gets the current state.
+ *
+ * Records, by entity (id in brackets):
+ * - meeting [meeting id]: { id, title, startedAt, endedAt, attendees: [{ name, email }], app, trashedAt, language }
+ * startedAt/endedAt/trashedAt are ms since 1970; trashedAt null unless it is in the Trash (it can be restored there).
+ * - notes [meeting id]: { meetingId, mine, summary, mineHash }: mine is My notes, summary the written notes (enhanced,
+ * null until written); mineHash = notesHash(mine), the baseHash a setMine op sends back.
+ * - segments [meeting id]: { meetingId, oneMic, segments: [{ startMs, endMs, speaker, text }] }: the whole transcript in
+ * order, hidden echo lines left out; speaker 'me' on the mic, the call's name for the other side, null for Them.
+ * oneMic: one microphone in a room (an uploaded file or a phone recording), so every speaker is null.
+ * - folder [folder id]: { id, name, createdAt }
+ * - folderMembers [folder id]: { folderId, meetingIds }: trashed meetings stay listed (a restore puts them back).
+ * - people [email]: { email, displayName }: a name the person gave someone, null for none.
+ * A thing that no longer exists comes as { entity, id, deleted: true }, a meeting deleted for good from the Trash too.
+ *
+ * pull replies { changes, cursor, more, epoch }: epoch is a random id made once per log (companion_meta). A phone whose
+ * kept epoch differs (this Mac's database was replaced or started afresh) drops its cursor and pulls from 0.
+ */
+export type Entity = 'meeting' | 'notes' | 'segments' | 'folder' | 'folderMembers' | 'people'
+export type Change = { entity: Entity; id: string; deleted?: true; record?: object }
+export type Op = { kind: 'setMine' | 'rename' | 'addToFolder' | 'removeFromFolder' | 'trash' | 'restore'; meetingId: string; folderId?: string; text?: string; title?: string; baseHash?: string }
+export type OpDeps = {
+ /** saves My notes the way the editor does (the notes module), so an open note shows the phone's text */
+ notesRewrite: (meetingId: string, mine: string) => void
+ nowMs: () => number
+ /** after a change, for the windows and the search index to follow (index.ts does the same after its own IPC) */
+ trashed?: (meetingId: string) => void
+ restored?: (meetingId: string) => void
+ foldersChanged?: () => void
+}
+
+/** Heading over the phone's My notes when both sides changed them while apart (shared with the editor). */
+export { FROM_IPHONE }
+
+/** sha256 hex of the NFC text: the same notes typed on either side hash the same */
+export const notesHash = (text: string) => createHash('sha256').update(text.normalize('NFC'), 'utf8').digest('hex')
+
+function record(store: Store, entity: Entity, id: string): object | undefined {
+ switch (entity) {
+ case 'meeting': {
+ const m = store.meeting(id)
+ return m && { id: m.id, title: m.title, startedAt: m.startedAt, endedAt: m.endedAt, attendees: m.attendees, app: m.app, trashedAt: m.trashedAt ?? null, language: m.language }
+ }
+ case 'notes': {
+ if (!store.meeting(id)) return undefined
+ const n = store.notes(id)
+ return { meetingId: id, mine: n.mine, summary: n.enhanced, mineHash: notesHash(n.mine) }
+ }
+ case 'segments': {
+ const m = store.meeting(id)
+ // one microphone in a room (an uploaded file, a phone recording): nobody is named, and the phone doesn't run
+ // its lines together by speaker
+ return m && { meetingId: id, oneMic: m.source === 'audio-file',
+ segments: store.segments(id).map((s) => ({ startMs: s.startMs, endMs: s.endMs, speaker: s.speaker === AUDIO_SPEAKER ? null : s.speaker, text: s.text })) }
+ }
+ case 'folder': {
+ const f = store.folder(id)
+ return f && { id: f.id, name: f.name, createdAt: f.createdAt }
+ }
+ case 'folderMembers':
+ if (!store.folder(id)) return undefined
+ return { folderId: id, meetingIds: (store.db.prepare('SELECT meeting_id FROM folder_meetings WHERE folder_id = ? ORDER BY added_at, meeting_id').all(id)).map((r) => String(r.meeting_id)) }
+ case 'people': {
+ const p = store.db.prepare('SELECT email, display_name FROM people WHERE email = ?').get(id)
+ return p && { email: String(p.email), displayName: p.display_name == null ? null : String(p.display_name) }
+ }
+ }
+}
+
+/** At most this many changes in one pull, and about this many bytes of records (one huge transcript still goes alone) */
+export const PAGE_MAX = 500
+export const PAGE_BYTES = 1_000_000
+
+/**
+ * The changes after `since`, oldest first, at most `limit` (clamped to 1..PAGE_MAX) and about PAGE_BYTES; cursor is
+ * the `since` for the next pull. epoch names this log: when it differs from the one the phone kept, it pulls from 0.
+ */
+export function changesSince(store: Store, since: number, limit: number): { changes: Change[]; cursor: number; more: boolean; epoch: string } {
+ const max = Math.min(PAGE_MAX, Math.max(1, Math.floor(limit) || 1))
+ const epoch = String(store.db.prepare("SELECT value FROM companion_meta WHERE key = 'epoch'").get()?.value)
+ const rows = store.db.prepare('SELECT seq, entity, entity_id FROM companion_changes WHERE seq > ? ORDER BY seq LIMIT ?').all(since, max + 1)
+ const changes: Change[] = []
+ let cursor = since, bytes = 0
+ for (const r of rows.slice(0, max)) {
+ const entity = String(r.entity) as Entity, id = String(r.entity_id)
+ const rec = record(store, entity, id)
+ const change: Change = rec ? { entity, id, record: rec } : { entity, id, deleted: true }
+ const size = Buffer.byteLength(JSON.stringify(change))
+ if (changes.length && bytes + size > PAGE_BYTES) break
+ changes.push(change); bytes += size; cursor = Number(r.seq)
+ }
+ return { changes, cursor, more: rows.some((r) => Number(r.seq) > cursor), epoch }
+}
+
+/** An edit from the phone, through the same functions the desktop's own UI uses. Throws 'gone', 'recording' or 'bad-op'. */
+export function applyOp(store: Store, op: Op, deps: OpDeps): { applied: true; merged?: true } {
+ const meeting = store.meeting(op.meetingId)
+ if (!meeting) throw new Error('gone')
+ switch (op.kind) {
+ case 'setMine': {
+ if (typeof op.text !== 'string') throw new Error('bad-op')
+ const desk = store.notes(op.meetingId).mine
+ // the same text: nothing to write, and no change to echo back to the phone
+ if (notesHash(op.text) === notesHash(desk)) return { applied: true }
+ if (op.baseHash === notesHash(desk)) {
+ deps.notesRewrite(op.meetingId, op.text)
+ return { applied: true }
+ }
+ // both sides changed: the desktop's text stays, the phone's goes under it. Only its own block counts as already
+ // there (a retry): last, or followed by another block. A short phone text inside the desktop's words ("ok" in
+ // "book"), or one that only starts an earlier block ("phone" of "phone edit"), is still added.
+ const block = (FROM_IPHONE + op.text).normalize('NFC'), there = desk.normalize('NFC')
+ const retry = there.endsWith(block) || there.includes(block + FROM_IPHONE)
+ if (op.text.trim() && !retry) deps.notesRewrite(op.meetingId, desk.trim() ? desk.trimEnd() + FROM_IPHONE + op.text : op.text)
+ return { applied: true, merged: true }
+ }
+ case 'rename':
+ if (typeof op.title !== 'string' || !renameMeeting(op.meetingId, op.title)) throw new Error('bad-op')
+ return { applied: true }
+ case 'addToFolder':
+ case 'removeFromFolder':
+ if (!op.folderId || !store.folder(op.folderId)) throw new Error('gone')
+ if (op.kind === 'addToFolder') store.addToFolder(op.folderId, op.meetingId)
+ else store.removeFromFolder(op.folderId, op.meetingId)
+ deps.foldersChanged?.()
+ return { applied: true }
+ case 'trash': {
+ const r = moveToTrash(op.meetingId, { store: { meeting: (id) => store.meeting(id), trashMeeting: (id) => store.trashMeeting(id, deps.nowMs()) }, moved: (id) => deps.trashed?.(id) })
+ if (r !== 'trashed') throw new Error(r === 'recording' ? 'recording' : 'gone')
+ return { applied: true }
+ }
+ case 'restore':
+ if (meeting.trashedAt != null) { store.restoreMeeting(op.meetingId); deps.restored?.(op.meetingId) }
+ return { applied: true }
+ default:
+ throw new Error('bad-op')
+ }
+}
diff --git a/app/src/main/companion/server.ts b/app/src/main/companion/server.ts
new file mode 100644
index 00000000..aeecaa79
--- /dev/null
+++ b/app/src/main/companion/server.ts
@@ -0,0 +1,214 @@
+// The TCP side of the companion: each connection is either a pairing attempt (its first frame is a JSON pairHello,
+// accepted only while pairing is open) or a Noise KK session from the paired phone (its first frame is Noise
+// message 1; the phone is the initiator, prologue "yogurt-v1"). Anything else, an unknown key, a frame that doesn't
+// decrypt or a handshake that stalls closes the socket before any request is handled.
+import { createServer, type Server, type Socket } from 'node:net'
+import { frame, FrameReader, parseJson } from './frames'
+import { NoiseKK, type KeyPair } from './noise'
+import { pair, type PairCtx, type PairedPhone } from './pairing'
+import { SecureChannel, type Rekey } from './session'
+
+export type Limits = {
+ /** pairing or the Noise handshake must be done by then */
+ handshakeMs: number
+ /** a new connection says something by then */
+ firstFrameMs: number
+ /** each answer during pairing comes by then */
+ stepMs: number
+ /** connections not yet paired or authenticated, from one address */
+ perAddress: number
+ /** a session with nothing from the phone for this long is closed (it pings) */
+ idleMs: number
+ /** connections not yet paired or authenticated, in all; an authenticated session never counts here */
+ connections: number
+ /** requests waiting their turn on one session */
+ queued: number
+ /** first handshake messages remembered since start-up, so an exact replay is dropped at once */
+ replays: number
+ rekey: Rekey
+}
+export const LIMITS: Limits = { handshakeMs: 10_000, firstFrameMs: 3000, stepMs: 3000, perAddress: 2, idleMs: 2 * 60 * 1000, connections: 4, queued: 64, replays: 10_000, rekey: { bytes: 2 ** 30, ms: 60 * 60 * 1000 } }
+
+const PROLOGUE = new TextEncoder().encode('yogurt-v1')
+/** requests that may take long run beside the queue, so pings and pulls still get through */
+const BESIDE = new Set(['ask', 'audio'])
+const MAX_BESIDE = 4
+
+export type Session = { send: (msg: object) => Promise<void>; close: () => void }
+
+export type ServerHooks = {
+ limits: Limits
+ now: () => number
+ /** pairing is on: a pairHello gets an answer */
+ pairing: () => PairCtx | null
+ paired: (phone: PairedPhone) => void
+ phoneKey: () => Uint8Array | null
+ /** false when this ephemeral key was seen before (a replayed message 1); remembers it otherwise */
+ fresh: (ephemeral: Uint8Array) => boolean
+ staticKey: () => KeyPair
+ /** a session is up: the one before it (if any) is closed by the caller */
+ opened: (s: Session) => void
+ closed: (s: Session) => void
+ handle: (msg: Record<string, unknown>, send: (m: object) => Promise<void>) => Promise<void>
+ busy: (delta: 1 | -1) => void
+ log: (...parts: unknown[]) => void
+}
+
+export type Listening = { port: number; close: () => Promise<void> }
+
+export function startServer(h: ServerHooks, port: number, host: string): Promise<Listening> {
+ let pairingBusy = false
+ const sockets = new Set<Socket>()
+ // sockets that haven't proved anything yet, by address: a few strangers can't fill the server for the phone
+ const strangers = new Map<string, number>()
+ let strangersAll = 0
+ const server: Server = createServer({ noDelay: true }, (socket) => connection(socket))
+
+ function connection(socket: Socket) {
+ const addr = socket.remoteAddress ?? ''
+ if ((strangers.get(addr) ?? 0) >= h.limits.perAddress || strangersAll >= h.limits.connections) { socket.destroy(); return }
+ strangers.set(addr, (strangers.get(addr) ?? 0) + 1); strangersAll++
+ let stranger = true
+ const known = () => {
+ if (!stranger) return
+ stranger = false; strangersAll--
+ const n = (strangers.get(addr) ?? 1) - 1
+ if (n) strangers.set(addr, n); else strangers.delete(addr)
+ }
+ sockets.add(socket)
+ socket.on('close', () => { sockets.delete(socket); known() })
+ const reader = new FrameReader()
+ const early: Uint8Array[] = []
+ let waiter: { resolve: (f: Uint8Array) => void; reject: (e: Error) => void } | undefined
+ let onFrame: ((f: Uint8Array) => void) | undefined
+ let ended = false
+ const fail = (why: string) => {
+ if (ended) return
+ ended = true
+ h.log('COMPANION', 'closed', why)
+ socket.destroy()
+ }
+ const handshake = setTimeout(() => fail('handshake timeout'), h.limits.handshakeMs)
+ const silent = setTimeout(() => fail('silent'), h.limits.firstFrameMs)
+ socket.on('close', () => {
+ ended = true
+ clearTimeout(handshake)
+ clearTimeout(silent)
+ waiter?.reject(new Error('closed'))
+ waiter = undefined
+ })
+ socket.on('error', () => {})
+ socket.on('end', () => { if (!ended) { ended = true; socket.destroy() } })
+ socket.on('data', (data: Buffer) => {
+ let frames: Uint8Array[]
+ try { frames = reader.push(data) } catch { return fail('bad framing') }
+ for (const f of frames) {
+ if (ended) return
+ clearTimeout(silent)
+ if (onFrame) { onFrame(f); continue }
+ if (waiter) { const w = waiter; waiter = undefined; w.resolve(f) }
+ // before the handshake the phone waits for each answer, so more than a couple queued is not a phone
+ else if (early.push(f) > 2) return fail('too many frames')
+ }
+ })
+ const next = () => early.length ? Promise.resolve(early.shift()!)
+ : ended ? Promise.reject(new Error('closed')) : new Promise<Uint8Array>((resolve, reject) => { waiter = { resolve, reject } })
+ /** the next frame of a pairing exchange, which comes quickly or not at all */
+ const step = () => new Promise<Uint8Array>((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error('slow')), h.limits.stepMs)
+ next().then((f) => { clearTimeout(t); resolve(f) }, (e) => { clearTimeout(t); reject(e) })
+ })
+ const sendJson = (msg: object) => { if (!ended) socket.write(frame(new TextEncoder().encode(JSON.stringify(msg)))) }
+
+ void (async () => {
+ const first = await next()
+ const hello = first[0] === 0x7b ? jsonOf(first) : null
+ if (hello?.type === 'pairHello') return pairing(hello)
+ return session(first)
+ })().catch((err: Error) => fail(err.message === 'closed' ? 'gone' : 'refused'))
+
+ async function pairing(hello: Record<string, unknown>) {
+ const ctx = h.pairing()
+ if (!ctx) { sendJson({ type: 'pairFail', reason: 'expired' }); socket.end(); return }
+ // one exchange at a time, and a pause after a wrong guess
+ if (pairingBusy || ctx.waiting()) { sendJson({ type: 'pairFail', reason: 'busy' }); socket.end(); return }
+ pairingBusy = true
+ try {
+ const r = await pair({ next: step, send: sendJson }, hello, ctx)
+ if ('phone' in r) {
+ h.paired(r.phone)
+ sendJson({ type: 'pairOk' })
+ } else h.log('COMPANION', 'pair refused', r.fail)
+ } finally {
+ pairingBusy = false
+ clearTimeout(handshake)
+ }
+ socket.end()
+ }
+
+ function session(first: Uint8Array) {
+ const rs = h.phoneKey()
+ if (!rs) return fail('not paired')
+ const noise = new NoiseKK({ initiator: false, s: h.staticKey(), rs, prologue: PROLOGUE })
+ // throws when the phone isn't the paired one: closed, no request seen
+ noise.readMessage(first)
+ // checked after it verifies, so made-up messages can't push real ones out of the cache
+ if (!h.fresh(first.subarray(0, 32))) return fail('replayed')
+ socket.write(frame(noise.writeMessage(new Uint8Array(0))))
+ const { send, recv } = noise.split()
+ const channel = new SecureChannel(socket, send, recv, h.now, h.limits.rekey)
+ if (early.length) { channel.close(); return fail('spoke before the handshake ended') }
+
+ // msg 1 can be replayed: one that isn't followed by a frame that decrypts frees its slot after one step
+ const proof = setTimeout(() => fail('no proof'), h.limits.stepMs)
+ let idle: NodeJS.Timeout | undefined
+ const awake = () => { clearTimeout(idle); idle = setTimeout(() => fail('idle'), h.limits.idleMs) }
+ awake()
+ let queue: Promise<void> = Promise.resolve(), queued = 0, beside = 0
+ const s: Session = { send: (m) => channel.send(m), close: () => fail('replaced') }
+ // a replayed message 1 gets this far too; only a phone holding its ephemeral key can send a frame that
+ // decrypts, so that is when it counts as connected (and replaces an older session)
+ let proved = false
+ socket.on('close', () => { clearTimeout(idle); clearTimeout(proof); channel.close(); if (proved) h.closed(s) })
+ const run = (msg: Record<string, unknown>) => {
+ h.busy(1)
+ return h.handle(msg, (m) => channel.send(m)).catch(() => fail('reply failed')).finally(() => h.busy(-1))
+ }
+ onFrame = (f) => {
+ awake()
+ let msg: Record<string, unknown> | null
+ try { msg = channel.receive(f) } catch { return fail('bad message') }
+ if (!proved) { proved = true; clearTimeout(handshake); clearTimeout(proof); known(); h.opened(s) }
+ if (!msg) return
+ if (msg.type === 'ping') { channel.send({ ...(typeof msg.id === 'string' ? { id: msg.id } : {}), type: 'pong', body: {} }).catch(() => fail('reply failed')); return }
+ if (typeof msg.type !== 'string' || typeof msg.id !== 'string') return fail('bad request')
+ if (BESIDE.has(msg.type)) {
+ if (++beside > MAX_BESIDE) return fail('too many requests')
+ void run(msg).finally(() => { beside-- })
+ return
+ }
+ if (++queued > h.limits.queued) return fail('too many requests')
+ queue = queue.then(() => run(msg)).finally(() => { queued-- })
+ }
+ }
+ }
+
+ return new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(port, host, () => {
+ server.off('error', reject)
+ server.on('error', (err) => h.log('COMPANION', 'server error', (err as NodeJS.ErrnoException).code ?? err.name))
+ resolve({
+ port: (server.address() as { port: number }).port,
+ close: () => new Promise<void>((r) => { server.close(() => r()); for (const s of sockets) s.destroy() }),
+ })
+ })
+ })
+}
+
+function jsonOf(f: Uint8Array): Record<string, unknown> | null {
+ try {
+ const v = parseJson(f)
+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null
+ } catch { return null }
+}
diff --git a/app/src/main/companion/session.ts b/app/src/main/companion/session.ts
new file mode 100644
index 00000000..3b61ea68
--- /dev/null
+++ b/app/src/main/companion/session.ts
@@ -0,0 +1,91 @@
+// A Noise transport session over one socket: JSON app messages in and out, chunked when big, and a rekey of each
+// direction after REKEY_BYTES or REKEY_MS. The side that rekeys its sending key first sends {type: "rekey"} under the
+// old key, so the other side moves its receiving key at the same message.
+import type { Socket } from 'node:net'
+import type { CipherState } from './noise'
+import { frame, Reassembler, splitMessage } from './frames'
+
+export const REKEY_BYTES = 2 ** 30
+export const REKEY_MS = 60 * 60 * 1000
+
+export type Rekey = { bytes: number; ms: number }
+
+export class SecureChannel {
+ private readonly reassembler = new Reassembler()
+ private sent = 0
+ private sentSince: number
+ private received = 0
+ private closed = false
+ /** writes go one at a time, so chunks of two messages never interleave */
+ private writing: Promise<void> = Promise.resolve()
+
+ constructor(
+ private readonly socket: Socket,
+ private readonly tx: CipherState,
+ private readonly rx: CipherState,
+ private readonly now: () => number = Date.now,
+ private readonly rekey: Rekey = { bytes: REKEY_BYTES, ms: REKEY_MS },
+ ) {
+ this.sentSince = now()
+ }
+
+ /**
+ * One transport frame in: a whole app message once it has arrived, else null. Throws on anything that doesn't
+ * decrypt or parse, or a peer that never rekeys; the caller closes the connection.
+ */
+ receive(ct: Uint8Array): Record<string, unknown> | null {
+ const plain = this.rx.decrypt(ct)
+ this.received += ct.length
+ // the peer rekeys its own sending side; one that never does is cut off well past the limit
+ if (this.received > 2 * this.rekey.bytes) throw new Error('session: peer never rekeyed')
+ const msg = this.reassembler.push(plain)
+ if (msg?.type === 'rekey' && msg.id === undefined) {
+ this.rx.rekey()
+ this.received = 0
+ return null
+ }
+ return msg
+ }
+
+ /** Sends one app message (chunked when big); resolves once the socket has taken it. */
+ send(message: object): Promise<void> {
+ const run = this.writing.then(() => this.write(message))
+ this.writing = run.catch(() => {})
+ return run
+ }
+
+ private async write(message: object): Promise<void> {
+ if (this.closed) throw new Error('session: closed')
+ if (this.sent >= this.rekey.bytes || this.now() - this.sentSince >= this.rekey.ms) {
+ await this.put(this.tx.encrypt(new TextEncoder().encode(JSON.stringify({ type: 'rekey' }))))
+ this.tx.rekey()
+ this.sent = 0
+ this.sentSince = this.now()
+ }
+ for (const part of splitMessage(message)) {
+ const ct = this.tx.encrypt(part)
+ this.sent += ct.length
+ await this.put(ct)
+ }
+ }
+
+ private put(ct: Uint8Array): Promise<void> {
+ if (this.closed || this.socket.destroyed) return Promise.reject(new Error('session: closed'))
+ if (this.socket.write(frame(ct))) return Promise.resolve()
+ // the phone reads slower than this writes (audio): wait for the socket to drain
+ return new Promise((resolve, reject) => {
+ const done = (err?: Error) => { this.socket.off('drain', ok); this.socket.off('close', gone); if (err) reject(err); else resolve() }
+ const ok = () => done()
+ const gone = () => done(new Error('session: closed'))
+ this.socket.once('drain', ok)
+ this.socket.once('close', gone)
+ })
+ }
+
+ close(): void {
+ if (this.closed) return
+ this.closed = true
+ this.tx.wipe()
+ this.rx.wipe()
+ }
+}
diff --git a/app/src/main/companion/sodium.ts b/app/src/main/companion/sodium.ts
new file mode 100644
index 00000000..3232dd62
--- /dev/null
+++ b/app/src/main/companion/sodium.ts
@@ -0,0 +1,17 @@
+// libsodium (sumo build: it has ristretto255). Plain Node, no Electron, so scripts and tests can import it too.
+import lib from 'libsodium-wrappers-sumo'
+
+let loaded = false
+
+/** Await once before calling anything in companion/; the library loads its WebAssembly asynchronously. */
+export async function ready(): Promise<typeof lib> {
+ await lib.ready
+ loaded = true
+ return lib
+}
+
+/** The loaded library; throws instead of failing obscurely when ready() was never awaited. */
+export function sodium(): typeof lib {
+ if (!loaded) throw new Error('companion crypto used before ready()')
+ return lib
+}
diff --git a/app/src/main/index.ts b/app/src/main/index.ts
index 8de81370..929dcc1f 100644
--- a/app/src/main/index.ts
+++ b/app/src/main/index.ts
@@ -1,3 +1,4 @@
+import { importPhoneRecording } from './companion/phoneImport'
import { loadWindowState, placeWindow, saveWindowState } from './windowState'
import { trustSystemCertificates } from './systemCerts'
import { createSavedTranscriptions } from './savedTranscription'
@@ -89,6 +90,11 @@ import { deleteRecording } from './deleteRecording'
import { AUDIO_SCHEME, audioExts, createAudioHandler, trackFile, type AudioExt } from './audio'
import { helperDecode, wavDecode } from './asr/backfill'
import { finishQuit, hookUpdates, isPreviewBuild, updatesOn } from './updates'
+import { createCompanion, type Companion } from './companion'
+import { askSources } from './companion/handlers'
+import { hookCompanion } from './companion/ipc'
+import { companionWanted } from './companion/gate'
+import { copyFile, mkdir, rename } from 'node:fs/promises'
import type { NoteSaveResult, StartResult } from '../shared/types'
// the transcript's player streams each meeting's audio from here; seeking needs stream support (before ready)
@@ -113,6 +119,8 @@ if (x11) { stripAppImageEnv(); app.relaunch(x11); app.exit(0) }
// One Yogurt at a time: a second launch focuses the existing window
else if (!app.requestSingleInstanceLock()) app.quit()
let win: BrowserWindow | undefined
+/** the iPhone companion once it has started (Settings → Phone pairs and unpairs through it) */
+let companion: Companion | undefined
let allowQuit = false
let presentMain = (_foreground = false) => {}
let updateMainMenu = () => {}
@@ -550,12 +558,12 @@ app.whenReady().then(() => {
if (!isFake()) syncLoginItem(settings.openAtLogin)
// Windows and Linux: the calendar is a pasted private calendar address, kept sealed with the system keychain
// a Mac: the same links, next to its own calendars (Settings → Calendars → Add a calendar link)
+ // no keychain (Linux without a secret service): scrambled, not encrypted, so a secret isn't readable at a glance
+ const sealSecret = (plain: string) => (safeStorage.isEncryptionAvailable() ? `k:${safeStorage.encryptString(plain).toString('base64')}` : `b:${Buffer.from(plain).toString('base64')}`)
+ const openSecret = (sealed: string) => (sealed.startsWith('k:') ? safeStorage.decryptString(Buffer.from(sealed.slice(2), 'base64'))
+ : sealed.startsWith('b:') ? Buffer.from(sealed.slice(2), 'base64').toString() : sealed.replace(/^p:/, ''))
const calendarLinks = caps.calendar ? createCalendarLinks({
- file: join(userDataDir(), 'settings.json'), get: getCalendar,
- // no keychain (Linux without a secret service): scrambled, not encrypted, so the address isn't readable at a glance
- seal: (plain) => (safeStorage.isEncryptionAvailable() ? `k:${safeStorage.encryptString(plain).toString('base64')}` : `b:${Buffer.from(plain).toString('base64')}`),
- open: (sealed) => (sealed.startsWith('k:') ? safeStorage.decryptString(Buffer.from(sealed.slice(2), 'base64'))
- : sealed.startsWith('b:') ? Buffer.from(sealed.slice(2), 'base64').toString() : sealed.replace(/^p:/, '')),
+ file: join(userDataDir(), 'settings.json'), get: getCalendar, seal: sealSecret, open: openSecret,
}) : null
if (calendarLinks) setCalendarLinkSource(calendarLinks, { alongside: !caps.calendarLink })
const preferences = hookPreferences({
@@ -1013,7 +1021,9 @@ app.whenReady().then(() => {
const recording = activeMeeting()
if (recording) stopMeeting(recording.id, 'quit')
// Music, recorder files and transcription still receive the same bounded graceful shutdown.
- await Promise.all([media.resume(), settleRecording().then(() => settleTranscription())])
+ // the companion says goodbye on the network (so the phone sees the computer leave), for half a second at most
+ const companionStopped = Promise.race([companion?.stop(), new Promise((r) => setTimeout(r, 500))])
+ await Promise.all([media.resume(), settleRecording().then(() => settleTranscription()), companionStopped])
allowQuit = true
finishQuit()
})().catch((err) => console.error('quit was cancelled because saving or shutdown failed', err)).finally(() => {
@@ -1116,6 +1126,50 @@ app.whenReady().then(() => {
} catch (e) { console.warn('tidying prepared notes failed', e) }
}
tidyPrepared(); setInterval(tidyPrepared, 60_000).unref()
+ // the iPhone companion: never started until the iPhone app ships (YOGURT_PHONE=1 turns it on); then off until a phone
+ // is paired or Settings starts pairing. Tests also need YOGURT_FAKE_COMPANION=1
+ app.on('will-quit', () => { void companion?.stop() })
+ const meetingsChanged = () => { win?.webContents.send('meetings:changed'); win?.webContents.send('folders:changed') }
+ const companionOn = companionWanted(process.env, isFake())
+ // Linux without a secret service: the key is only scrambled on disk (the file is the person's own, mode 600)
+ if (companionOn && !safeStorage.isEncryptionAvailable()) console.warn('COMPANION key not sealed: no system keychain')
+ const companionReady = !companionOn ? Promise.resolve(undefined) : createCompanion({
+ store, userDataDir: userDataDir(), seal: sealSecret, open: openSecret, appVersion: app.getVersion(),
+ deviceName: () => os.hostname().replace(/\.local$/i, ''), recording: () => !!activeMeeting(),
+ log: (...parts) => console.info(...parts),
+ // the phone's question asked like one in Ask (it is kept there too), answered once it's written
+ ask: async (question, scope) => {
+ if (askUnavailable()) throw new Error('waits for the meeting')
+ const meetingIds = scope?.meetingIds ?? (scope?.folderId ? store.folderMeetingIds(scope.folderId) : undefined)
+ const { id, done } = conversations.ask(null, question, meetingIds ? { scope: meetingIds } : {})
+ await done
+ const turn = conversations.view(id)?.turns.at(-1)
+ if (!turn || turn.status !== 'done') throw new Error('no answer')
+ return { answer: turn.answer, sources: askSources(turn.sources) }
+ },
+ // a meeting recorded on the phone: its audio goes where an imported file's would, then it is transcribed and its
+ // notes written the same way; the phone's transcript and draft notes show until this computer's replace them
+ importRecording: (m, audioPath, draft) => importPhoneRecording({ store, meetingDir, changed: meetingsChanged,
+ start: (id, again) => savedTranscriptions.start(id, again) }, m, audioPath, draft),
+ audioFiles: async (id) => {
+ await rejoined; await recordingSettled(id)
+ return (['me', 'them'] as const).flatMap((track) => { const path = trackFile(meetingDir(id), track, audioKinds); return path ? [{ track, path }] : [] })
+ },
+ ops: {
+ // a new revision; an open note takes it unless it was typed in since (then both texts are kept)
+ notesRewrite: (id, mine) => { notes.phoneMine(id, mine) },
+ // the same refusals and follow-ups as the window's own Delete and Restore
+ trashBlocked: (id) => id === resumingId || stopSavePending(id),
+ trashed: (id) => {
+ indexer.forget(id)
+ meetingsChanged()
+ if (route === `/note/${id}`) { route = ''; win?.webContents.send('nav:go', route) }
+ },
+ restored: (id) => { indexer.restored(id); meetingsChanged() },
+ foldersChanged: () => { win?.webContents.send('folders:changed'); folderSuggestions.refresh() },
+ },
+ }).then((c) => { companion = c; return c }, (err) => { console.error('COMPANION could not start', (err as Error).name); return undefined })
+ hookCompanion({ companion: companionReady, send: (s) => { if (win && !win.isDestroyed()) win.webContents.send('companion:status', s) } })
ipcMain.handle('meetings:cards', (_e, o: { before?: { at: number; id: string }; limit?: number; folder?: string }) => {
const limit = Math.max(1, Math.min(1000, Number(o?.limit) || 40))
const b = o?.before
diff --git a/app/src/main/notes/index.ts b/app/src/main/notes/index.ts
index 6c75791a..05554ac2 100644
--- a/app/src/main/notes/index.ts
+++ b/app/src/main/notes/index.ts
@@ -80,7 +80,7 @@ export function hookNotes(p: {
}
const set = (id: string, status: NoteStatus, draft = '', part?: { part: number; of: number }, step?: 'loading') => { live.set(id, { status, draft, part, step }); p.send(view(id)) }
- const saveEdit = (id: string, side: NoteSide, md: string, revision?: number): NoteSaveResult => {
+ const saveEdit = (id: string, side: NoteSide, md: string, revision?: number, extra?: Pick<NoteView, 'mineFrom'>): NoteSaveResult => {
const sides = edits.get(id) ?? {}, previous = sides[side]
const rev = revision ?? (previous?.revision ?? 0) + 1
// A delayed request/acknowledgement cannot replace a newer edit.
@@ -98,7 +98,7 @@ export function hookNotes(p: {
edit.status = 'saved'; delete edit.text
}
} catch (e) { console.error('note edit was not saved; kept for retry', id, side, e) }
- try { p.send(view(id)) } catch (e) { console.error('could not refresh the note after saving', id, e) }
+ try { p.send({ ...view(id), ...(edit.status === 'saved' ? extra : {}) }) } catch (e) { console.error('could not refresh the note after saving', id, e) }
return { revision: rev, status: edit.status, ...(edit.status === 'failed' ? { retained: true, ...(edit.reason ? { reason: edit.reason } : {}) } : {}) }
}
const retryDrafts = (onlyId?: string): boolean => {
@@ -329,6 +329,8 @@ export function hookNotes(p: {
return 'saved'
},
setMine: (id: string, md: string, revision?: number) => saveEdit(id, 'mine', md, revision),
+ /** My notes from the iPhone: a new revision, and an open editor hears what they replaced so it can take them */
+ phoneMine: (id: string, md: string) => saveEdit(id, 'mine', md, undefined, { mineFrom: currentNotes(id).mine }),
setEnhanced: (id: string, md: string, revision?: number) => saveEdit(id, 'enhanced', md, revision),
retryDrafts,
pendingDraftId: () => [...edits].find(([, sides]) => Object.values(sides).some((v) => v.text !== undefined))?.[0],
diff --git a/app/src/main/savedTranscription.ts b/app/src/main/savedTranscription.ts
index 023b4c80..86f6abe6 100644
--- a/app/src/main/savedTranscription.ts
+++ b/app/src/main/savedTranscription.ts
@@ -1,4 +1,5 @@
import type { Store } from './store'
+import { isPhoneDraft, phoneDraftReplaced, phoneLanguage } from './companion/phoneImport'
import type { Track } from './capture'
import type { RecordedOptions } from './asr'
import type { TranscriptionState } from '../shared/transcription'
@@ -38,7 +39,9 @@ export function createSavedTranscriptions(d: {
const segments=meeting.transcriptionAgain?d.store.transcriptionDraft(id):d.store.segments(id,{hidden:true})
const fromMs:Partial<Record<Track,number>>={}
for(const segment of segments)fromMs[segment.track]=Math.max(fromMs[segment.track]??0,segment.endMs)
- const complete=await d.transcribe(id,tracks,{signal:job.abort.signal,fromMs,...(meeting.transcriptionAgain?{save:segs=>{d.store.addTranscriptionDraft(id,segs);d.draft?.(id)}}:{})})
+ // a phone recording is heard in the language the phone said; everything else follows the spoken setting
+ const language=phoneLanguage(current)
+ const complete=await d.transcribe(id,tracks,{signal:job.abort.signal,fromMs,...(language?{language}:{}),...(meeting.transcriptionAgain?{save:segs=>{d.store.addTranscriptionDraft(id,segs);d.draft?.(id)}}:{})})
if(!d.store.meeting(id)||d.store.meeting(id)?.trashedAt!=null)continue
if(job.abort.signal.aborted){if(job.stopped)stopped(id);else set(id,d.recording()?'waiting-recording':'queued');continue}
if(!complete)throw new Error('Saved transcription incomplete')
@@ -47,7 +50,10 @@ export function createSavedTranscriptions(d: {
else d.store.updateMeeting(id,{transcriptionPending:false,transcriptionState:'done'})
d.changed(id,!!meeting.transcriptionAgain)
// Replacing a transcript must not overwrite an existing or edited summary.
- if(!d.store.notes(id).enhanced?.trim())d.summarize(id)
+ // a phone recording's draft notes are rewritten once, by this computer's notes model
+ const phoneDraft=isPhoneDraft(d.store.meeting(id))
+ if(phoneDraft)phoneDraftReplaced(d.store,id)
+ if(phoneDraft||!d.store.notes(id).enhanced?.trim())d.summarize(id)
} catch(error) {
if(d.store.meeting(id)){if(job.stopped)stopped(id);else set(id,job.abort.signal.aborted?'queued':'error')}
if(!job.abort.signal.aborted)console.error('Saved transcription failed',id,error)
diff --git a/app/src/main/store.ts b/app/src/main/store.ts
index 027a9c2f..501d695a 100644
--- a/app/src/main/store.ts
+++ b/app/src/main/store.ts
@@ -154,6 +154,52 @@ function around(raw: string, pairs: string[]): SnippetPart[] {
return parts
}
+/**
+ * What the iPhone has to fetch again, by trigger so every write path is seen (the app, backup import, the Trash).
+ * One row per thing: a new change drops its older row, so the log never outgrows what it describes and a
+ * phone behind by any amount gets each thing once. companion/records.ts reads it.
+ */
+const COMPANION_SOURCES: Array<{ table: string; entity: string; id: string; update: string }> = [
+ // only what the phone shows: opening a note or a folder suggestion is no change to it
+ { table: 'meetings', entity: 'meeting', id: 'id', update: 'title, started_at, ended_at, attendees, app, trashed_at, language' },
+ { table: 'notes', entity: 'notes', id: 'meeting_id', update: 'mine, enhanced' },
+ { table: 'segments', entity: 'segments', id: 'meeting_id', update: 'start_ms, end_ms, text, speaker, hidden' },
+ { table: 'folders', entity: 'folder', id: 'id', update: 'name' },
+ { table: 'folder_meetings', entity: 'folderMembers', id: 'folder_id', update: 'folder_id, meeting_id' },
+ { table: 'people', entity: 'people', id: 'email', update: 'display_name' },
+]
+/** Raise when the triggers change: a database with an older set gets them made again. */
+const COMPANION_TRIGGERS = 1
+function companionTables(db: DatabaseSync) {
+ // one transaction: a crash between making the log and filling it would leave old history out for good
+ db.exec('BEGIN')
+ try {
+ const fresh = !db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'companion_changes'").get()
+ db.exec(`CREATE TABLE IF NOT EXISTS companion_changes (seq INTEGER PRIMARY KEY AUTOINCREMENT, entity TEXT NOT NULL, entity_id TEXT NOT NULL, at INTEGER NOT NULL);
+ CREATE UNIQUE INDEX IF NOT EXISTS companion_changes_entity ON companion_changes(entity, entity_id);
+ CREATE TABLE IF NOT EXISTS companion_devices (id TEXT PRIMARY KEY, name TEXT NOT NULL, public_key TEXT NOT NULL, paired_at INTEGER NOT NULL, last_seen INTEGER);
+ CREATE TABLE IF NOT EXISTS companion_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);`)
+ // the epoch names this log: a phone seeing a new one starts again from 0 (its seq numbers mean nothing here)
+ db.prepare(`INSERT ${fresh ? 'OR REPLACE' : 'OR IGNORE'} INTO companion_meta (key, value) VALUES ('epoch', ?)`).run(randomUUID())
+ const version = db.prepare("SELECT value FROM companion_meta WHERE key = 'triggers'").get()?.value
+ if (fresh || Number(version) !== COMPANION_TRIGGERS) {
+ for (const r of db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'companion\\_%' ESCAPE '\\'").all()) db.exec(`DROP TRIGGER "${String(r.name)}"`)
+ // delete then insert, not OR REPLACE: an upsert outside a trigger overrides its conflict policy
+ const log = (entity: string, id: string) => `DELETE FROM companion_changes WHERE entity = '${entity}' AND entity_id = ${id};
+ INSERT INTO companion_changes (entity, entity_id, at) VALUES ('${entity}', ${id}, CAST(unixepoch('subsec') * 1000 AS INTEGER));`
+ for (const s of COMPANION_SOURCES) {
+ db.exec(`CREATE TRIGGER companion_${s.table}_ai AFTER INSERT ON ${s.table} BEGIN ${log(s.entity, `new.${s.id}`)} END;
+ CREATE TRIGGER companion_${s.table}_ad AFTER DELETE ON ${s.table} BEGIN ${log(s.entity, `old.${s.id}`)} END;
+ CREATE TRIGGER companion_${s.table}_au AFTER UPDATE OF ${s.update} ON ${s.table} BEGIN ${log(s.entity, `old.${s.id}`)} ${log(s.entity, `new.${s.id}`)} END;`)
+ }
+ db.prepare("INSERT OR REPLACE INTO companion_meta (key, value) VALUES ('triggers', ?)").run(String(COMPANION_TRIGGERS))
+ }
+ // a database from before the log: everything in it is new to a phone
+ if (fresh) for (const s of COMPANION_SOURCES) db.exec(`INSERT OR IGNORE INTO companion_changes (entity, entity_id, at) SELECT DISTINCT '${s.entity}', ${s.id}, 0 FROM ${s.table}`)
+ db.exec('COMMIT')
+ } catch (e) { db.exec('ROLLBACK'); throw e }
+}
+
/** Meetings, transcripts and notes in one SQLite file, with full-text search. */
export class Store {
/** public only so tests can poke at tables */
@@ -265,6 +311,7 @@ export class Store {
const hadPeople = this.db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'people'").get()
this.db.exec('CREATE TABLE IF NOT EXISTS people (email TEXT PRIMARY KEY, display_name TEXT, seen_names TEXT NOT NULL DEFAULT "[]", first_seen INTEGER NOT NULL, last_seen INTEGER NOT NULL)')
if (!hadPeople) backfillPeople(this.db)
+ companionTables(this.db)
// chat across meetings: its chunks, vectors and saved conversations (library/store.ts)
libraryTables(this.db)
// voices told apart by letter (Speaker A, B) are gone: a database from then loses the letters, so those lines say Them
@@ -345,7 +392,7 @@ export class Store {
updateMeeting(id: string, patch: Partial<Omit<Meeting, 'id'>>) {
if (patch.ownEmail) this.rememberOwnEmail(patch.ownEmail)
if (patch.attendees) rememberPeople(this.db, patch.attendees)
- const col: Record<string, string> = { title: 'title', startedAt: 'started_at', endedAt: 'ended_at', eventId: 'event_id', eventStartedAt: 'event_started_at', eventEndedAt: 'event_ended_at', eventTitle: 'event_title', eventCalendarName: 'event_calendar_name', eventCalendarSource: 'event_calendar_source', ownEmail: 'own_email', app: 'app', attendees: 'attendees', keepAttendees: 'keep_attendees', state: 'state', language: 'language', titleSource: 'title_source', durationMs: 'duration_ms', transcriptionPending: 'transcription_pending', transcriptionState: 'transcription_state', transcriptionAgain: 'transcription_again' }
+ const col: Record<string, string> = { title: 'title', startedAt: 'started_at', endedAt: 'ended_at', eventId: 'event_id', eventStartedAt: 'event_started_at', eventEndedAt: 'event_ended_at', eventTitle: 'event_title', eventCalendarName: 'event_calendar_name', eventCalendarSource: 'event_calendar_source', ownEmail: 'own_email', app: 'app', attendees: 'attendees', keepAttendees: 'keep_attendees', state: 'state', language: 'language', titleSource: 'title_source', durationMs: 'duration_ms', transcriptionPending: 'transcription_pending', transcriptionState: 'transcription_state', transcriptionAgain: 'transcription_again', sourceId: 'source_id' }
const keys = Object.keys(patch).filter((k) => k in col && (patch as Row)[k] !== undefined)
if (!keys.length) return
const vals = keys.map(k => {
diff --git a/app/src/preload/index.ts b/app/src/preload/index.ts
index 80dce548..d68fc63e 100644
--- a/app/src/preload/index.ts
+++ b/app/src/preload/index.ts
@@ -3,6 +3,7 @@ import { audioUpload } from './audioUpload'
import type { WidgetLayout } from '../shared/widgetMorph'
import { contextBridge, ipcRenderer } from 'electron'
import { capabilities, platformOf } from '../shared/platform'
+import { phoneCompanionOn, type CompanionStatus } from '../shared/companion'
import type { ChatView, ConversationSummary, ConversationView, NoteView, PromptAction, SetupState, UpdateStatus, WidgetView, YogurtApi } from '../shared/types'
const api: YogurtApi = {
@@ -11,6 +12,7 @@ const api: YogurtApi = {
os: platformOf(process.platform, process.env),
capabilities: capabilities(platformOf(process.platform, process.env)),
fake: process.env.YOGURT_FAKE === '1',
+ phone: phoneCompanionOn(process.env),
setup: {
state: () => ipcRenderer.invoke('setup:state'),
onState: (cb) => {
@@ -230,6 +232,13 @@ const api: YogurtApi = {
setChanges: (on) => ipcRenderer.invoke('mcp:set-changes', on),
onClients: (fn) => { const f = (_e: unknown, c: string[]) => fn(c); ipcRenderer.on('mcp:clients', f); return () => { ipcRenderer.off('mcp:clients', f) } },
},
+ companion: {
+ status: () => ipcRenderer.invoke('companion:status'),
+ startPairing: () => ipcRenderer.invoke('companion:start-pairing'),
+ cancelPairing: () => ipcRenderer.invoke('companion:cancel-pairing'),
+ unpair: () => ipcRenderer.invoke('companion:unpair'),
+ onStatus: (fn) => { const f = (_e: unknown, s: CompanionStatus) => fn(s); ipcRenderer.on('companion:status', f); return () => { ipcRenderer.off('companion:status', f) } },
+ },
updates: {
status: () => ipcRenderer.invoke('updates:status'),
set: (on) => ipcRenderer.invoke('updates:set', on),
diff --git a/app/src/renderer/src/components/Icons.tsx b/app/src/renderer/src/components/Icons.tsx
index 91942ed7..24384ddc 100644
--- a/app/src/renderer/src/components/Icons.tsx
+++ b/app/src/renderer/src/components/Icons.tsx
@@ -455,6 +455,11 @@ export const SlidersHorizontal = icon('SlidersHorizontal', [
['path', { d: 'M14.9998 12.0002L20.9998 12.0002M14.9998 12.0002V10.0002M14.9998 12.0002V14.0002', key: '5' }],
])
+export const Smartphone = icon('Smartphone', [
+ ['path', { d: 'M5.5 7C5.5 4.64298 5.5 3.46447 6.23223 2.73223C6.96447 2 8.14298 2 10.5 2H13.5C15.857 2 17.0355 2 17.7678 2.73223C18.5 3.46447 18.5 4.64298 18.5 7V17C18.5 19.357 18.5 20.5355 17.7678 21.2678C17.0355 22 15.857 22 13.5 22H10.5C8.14298 22 6.96447 22 6.23223 21.2678C5.5 20.5355 5.5 19.357 5.5 17V7Z', key: '0' }],
+ ['path', { d: 'M11 19H13', key: '1' }],
+])
+
export const Square = icon('Square', [
['path', { d: 'M2.5 12C2.5 7.52166 2.5 5.28249 3.89124 3.89124C5.28249 2.5 7.52166 2.5 12 2.5C16.4783 2.5 18.7175 2.5 20.1088 3.89124C21.5 5.28249 21.5 7.52166 21.5 12C21.5 16.4783 21.5 18.7175 20.1088 20.1088C18.7175 21.5 16.4783 21.5 12 21.5C7.52166 21.5 5.28249 21.5 3.89124 20.1088C2.5 18.7175 2.5 16.4783 2.5 12Z', key: '0' }],
])
diff --git a/app/src/renderer/src/components/PhoneSettings.tsx b/app/src/renderer/src/components/PhoneSettings.tsx
new file mode 100644
index 00000000..5b4372ec
--- /dev/null
+++ b/app/src/renderer/src/components/PhoneSettings.tsx
@@ -0,0 +1,123 @@
+import { createElement, useEffect, useState } from 'react'
+import { Smartphone } from './Icons'
+import type { CompanionStatus } from '../../../shared/companion'
+import { language, t } from '../../../shared/i18n'
+
+/** m:ss left on the code */
+const countdown = (ms: number) => {
+ const s = Math.max(0, Math.ceil(ms / 1000))
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
+}
+
+/** "Last seen 2h ago" in the interface language, from the language's own relative-time words */
+function lastSeen(at: number, now: number) {
+ const s = Math.max(0, (now - at) / 1000)
+ if (s < 60) return t('Last seen just now')
+ const rtf = new Intl.RelativeTimeFormat(language(), { style: 'narrow' })
+ const when = s < 3600 ? rtf.format(-Math.floor(s / 60), 'minute') : s < 86400 ? rtf.format(-Math.floor(s / 3600), 'hour') : rtf.format(-Math.floor(s / 86400), 'day')
+ return t('Last seen {when}', { when })
+}
+
+/** Settings → Phone, only while the iPhone companion is turned on (hidden until the iPhone app ships) */
+export function PhoneSettings() {
+ return globalThis.window?.yogurt?.phone ? createElement(PhoneSection) : null
+}
+
+/** pair the iPhone app with a code, see the paired phone, unpair it */
+function PhoneSection() {
+ const [status, setStatus] = useState<CompanionStatus | null>()
+ const [failed, setFailed] = useState(false)
+ const [busy, setBusy] = useState(false)
+ const [confirming, setConfirming] = useState(false)
+ const [now, setNow] = useState(Date.now)
+ useEffect(() => {
+ // a push that lands before the first answer is newer than it
+ let live = true, pushed = false
+ void window.yogurt.companion.status().then((s) => { if (live && !pushed) setStatus(s) }, () => { if (live && !pushed) setStatus(null) })
+ const off = window.yogurt.companion.onStatus((s) => { pushed = true; setStatus(s) })
+ return () => { live = false; off() }
+ }, [])
+ // the countdown moves every second, "last seen" by the minute
+ const tick = status?.pairing ? 1000 : status?.paired ? 30_000 : 0
+ useEffect(() => {
+ if (!tick) return
+ setNow(Date.now())
+ const timer = setInterval(() => setNow(Date.now()), tick)
+ return () => clearInterval(timer)
+ }, [tick])
+ // fake mode, or it didn't start: nothing here to pair
+ if (status === null) return null
+
+ const act = async (run: () => Promise<CompanionStatus | null>) => {
+ setBusy(true)
+ try { const s = await run(); if (s) setStatus(s) } catch { /* the next status push says what is true */ } finally { setBusy(false) }
+ }
+ const start = () => act(async () => {
+ setFailed(false); setConfirming(false)
+ const r = await window.yogurt.companion.startPairing().catch(() => ({ ok: false, status: null }))
+ if (!r.ok) setFailed(true)
+ return r.status
+ })
+ const cancel = () => act(() => window.yogurt.companion.cancelPairing())
+ const unpair = () => act(async () => { setConfirming(false); return window.yogurt.companion.unpair() })
+
+ const pairing = status?.pairing
+ const paired = status?.paired
+ // the phone can't find this computer: say what to allow, in this computer's words
+ const network = status?.error !== 'network' ? null
+ : <p role="alert" data-testid="phone-network" className="settings-description text-danger">{globalThis.window?.yogurt?.platform === 'darwin'
+ ? t("Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.")
+ : t("Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.")}</p>
+ const notice = status?.error === 'keychain' ? t("Yogurt couldn't reach this computer's secure storage, so it can't pair right now.")
+ : failed || status?.error === 'listen' ? t("Yogurt couldn't start pairing. Try again.")
+ : status?.pairingClosed === 'tooMany' ? t('Too many wrong codes. Start pairing again.')
+ : status?.pairingClosed === 'expired' ? t('The code ran out. Start pairing again.')
+ : ''
+ const pairButton = <button type="button" data-testid="phone-pair" disabled={busy || !status} onClick={() => void start()} className="workspace-button settings-action">{t('Pair a phone')}</button>
+
+ return <section data-testid="phone-settings" aria-labelledby="phone-settings-heading">
+ <h2 id="phone-settings-heading" className="settings-section-heading">{t('Phone')}</h2>
+ <div className="settings-group">
+ {pairing ? <div data-testid="phone-pairing" className="settings-row">
+ <div className="settings-row-copy">
+ <p className="settings-label">{t('Open Yogurt on your iPhone and type this code')}</p>
+ <p data-testid="phone-code" dir="ltr" aria-label={pairing.code.split('').join(' ')} className="my-2 flex gap-3 font-mono text-[28px] leading-[36px] font-semibold tracking-[0.12em] tabular-nums">
+ <span>{pairing.code.slice(0, 3)}</span><span>{pairing.code.slice(3)}</span>
+ </p>
+ <p data-testid="phone-countdown" aria-live="off" className="settings-description">{t('Code works for {time}', { time: countdown(pairing.expiresAt - now) })}</p>
+ {network}
+ </div>
+ <button type="button" data-testid="phone-cancel" disabled={busy} onClick={() => void cancel()} className="workspace-button settings-action">{t('Cancel')}</button>
+ </div>
+ : paired && status?.error !== 'keychain' ? <div data-testid="phone-paired" className="settings-row">
+ <Smartphone size={16} aria-hidden="true" className="shrink-0 text-muted" />
+ <div className="settings-row-copy" aria-live="polite">
+ <p className="settings-label truncate">{paired.name}</p>
+ {confirming
+ ? <p className="settings-description">{t('Unpair your iPhone? It keeps its copy until you pair again.')}</p>
+ : <p className="settings-description flex items-center gap-1.5">
+ {status.connected && <span data-testid="phone-live-dot" aria-hidden="true" className="phone-live-dot inline-block size-2 shrink-0 rounded-full" style={{ backgroundColor: 'var(--status-live)' }} />}
+ {status.connected ? t('Connected') : paired.lastSeen == null ? t('Not connected yet') : lastSeen(paired.lastSeen, now)}
+ </p>}
+ {status.error === 'listen' && <p role="alert" data-testid="phone-notice" className="settings-description text-danger">{t("Your iPhone can't reach this computer right now. Try restarting Yogurt.")}</p>}
+ {network}
+ </div>
+ {confirming ? <div className="flex shrink-0 gap-2">
+ <button type="button" data-testid="phone-unpair-cancel" disabled={busy} onClick={() => setConfirming(false)} className="workspace-button">{t('Cancel')}</button>
+ <button type="button" data-testid="phone-unpair-confirm" disabled={busy} onClick={() => void unpair()} className="workspace-button text-danger">{t('Unpair')}</button>
+ </div>
+ : <button type="button" data-testid="phone-unpair" disabled={busy} onClick={() => setConfirming(true)} className="workspace-button settings-action">{t('Unpair')}</button>}
+ </div>
+ : <div data-testid="phone-unpaired" className="settings-row">
+ <Smartphone size={16} aria-hidden="true" className="shrink-0 text-muted" />
+ <div className="settings-row-copy">
+ <p className="settings-label">{t('Yogurt on your iPhone')}</p>
+ <p className="settings-description">{t('Read your notes and record meetings on your iPhone. They come back here to be transcribed.')}</p>
+ {notice && <p role="alert" data-testid="phone-notice" className="settings-description text-danger">{notice}</p>}
+ </div>
+ {status?.error !== 'keychain' && pairButton}
+ </div>}
+ <p className="settings-row settings-description">{t('Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.')}</p>
+ </div>
+ </section>
+}
diff --git a/app/src/renderer/src/noteMerge.ts b/app/src/renderer/src/noteMerge.ts
index 25b4f150..3ed82ae7 100644
--- a/app/src/renderer/src/noteMerge.ts
+++ b/app/src/renderer/src/noteMerge.ts
@@ -1,4 +1,5 @@
import type { NoteView } from '../../shared/types'
+import { FROM_IPHONE } from '../../shared/companion'
/**
* A new view of a note that is open. What the person typed here is newer than any copy from the app, and so are
@@ -6,8 +7,15 @@ import type { NoteView } from '../../shared/types'
* once, unless they edited it since: their autosave then keeps their version, and the app hears so (keptEdits) to keep
* the people-changed hint.
*/
-export function mergeNoteView(cur: NoteView | undefined, v: NoteView): { view: NoteView; /** a rewrite was turned down for edits on screen */ keptEdits?: true } {
+export function mergeNoteView(cur: NoteView | undefined, v: NoteView): { view: NoteView; /** a rewrite was turned down for edits on screen */ keptEdits?: true; /** My notes on screen took the phone's text under theirs: save them */ resaveMine?: true } {
if (!cur) return { view: v }
+ // My notes from the iPhone: shown if nothing was typed here since; otherwise what was typed stays and the phone's
+ // text goes under it (the same rule as edits made while apart), saved again so neither is lost
+ if (v.mineFrom !== undefined) {
+ const { view } = mergeNoteView(cur, { ...v, mineFrom: undefined })
+ if (cur.mine === v.mineFrom || cur.mine === v.mine) return { view: { ...view, mine: v.mine } }
+ return { view: { ...view, mine: cur.mine.trimEnd() + FROM_IPHONE + v.mine }, resaveMine: true }
+ }
// A failed or stopped rewrite's previous result is still editable, including when the person clears its text.
const finished = cur.status === v.status && (cur.status === 'done' || ((cur.status === 'failed' || cur.status === 'stopped') && cur.enhanced != null))
if (!finished) return { view: { ...v, mine: cur.mine } }
diff --git a/app/src/renderer/src/screens/Note.tsx b/app/src/renderer/src/screens/Note.tsx
index 0e35de31..6de0e574 100644
--- a/app/src/renderer/src/screens/Note.tsx
+++ b/app/src/renderer/src/screens/Note.tsx
@@ -144,6 +144,7 @@ export function Note({ id, onTitleChange, at, folderSuggestion, onSource, onResu
const [chatAnchor, setChatAnchor] = useState<HTMLDivElement | null>(null)
/** the notes as shown, for merging a new view from the app outside a state update */
const current = useRef<NoteView | undefined>(undefined)
+ const changeMine = useRef<(md: string) => void>(() => {})
/** what the recorder has to say right now (a hint, a hiccup), shown under the note too */
const [recorder, setRecorder] = useState<WidgetView | null>(null)
const hint = recorder?.note
@@ -198,10 +199,12 @@ export function Note({ id, onTitleChange, at, folderSuggestion, onSource, onResu
const show = (v: NoteView) => {
const first = !current.current
// what they typed here is newer than any copy from the app; notes written again for new people replace it unless edited (noteMerge.ts)
- const { view, keptEdits } = mergeNoteView(current.current, v)
+ const { view, keptEdits, resaveMine } = mergeNoteView(current.current, v)
if (keptEdits) window.yogurt.notes.keptEdits(id)
current.current = view
setNotes(view)
+ // typed here while the phone changed My notes: both texts, saved as a new edit
+ if (resaveMine) changeMine.current(view.mine)
// A reopened failed draft is the useful place to resume, including Settings' Open note action.
const failedSide = v.saves?.mine?.status === 'failed' ? 'mine' : v.saves?.enhanced?.status === 'failed' ? 'enhanced' : undefined
if (first && failedSide) { picked.current = true; setView(failedSide); setPrimary('notes') }
@@ -234,6 +237,7 @@ export function Note({ id, onTitleChange, at, folderSuggestion, onSource, onResu
return () => clearTimeout(timer)
}, [id, finishRequested, hasEnhanced, reducedMotion])
const mineSave = useAutosave(id, 'mine', notes?.mine ?? '', notes?.saves?.mine)
+ changeMine.current = mineSave.change
const enhancedSave = useAutosave(id, 'enhanced', notes?.enhanced ?? '', notes?.saves?.enhanced)
useLayoutEffect(() => {
diff --git a/app/src/renderer/src/screens/Settings.tsx b/app/src/renderer/src/screens/Settings.tsx
index 9297afff..f2cc1918 100644
--- a/app/src/renderer/src/screens/Settings.tsx
+++ b/app/src/renderer/src/screens/Settings.tsx
@@ -15,6 +15,7 @@ import { SpokenSetting } from '../components/SpokenSetting'
import { useScrollMemory } from '../useScrollMemory'
import { appShortcuts } from '../components/Shortcuts'
import { CalendarSettings } from '../components/CalendarSettings'
+import { PhoneSettings } from '../components/PhoneSettings'
import { supportedKinds, settingsPage } from '../../../shared/platform'
import { Swap, SwapText } from '../components/Swap'
@@ -269,6 +270,8 @@ export function Settings({ revision = 0, focus }: { revision?: number; focus?: s
<AiApps />
+ <PhoneSettings />
+
<Updates />
<AboutYogurt />
diff --git a/app/src/shared/companion.ts b/app/src/shared/companion.ts
new file mode 100644
index 00000000..db472e58
--- /dev/null
+++ b/app/src/shared/companion.ts
@@ -0,0 +1,22 @@
+/** Heading over the phone's My notes when both sides changed them while apart; neither text is lost. */
+export const FROM_IPHONE = '\n\n## From your iPhone\n\n'
+
+/** What Settings → Phone shows: the paired phone, an open pairing code, or why pairing closed or can't start */
+export type CompanionStatus = {
+ paired: null | { name: string; lastSeen: number | null }
+ pairing: null | { code: string; expiresAt: number; attemptsLeft: number }
+ /** why the last pairing closed without a phone: its two minutes ran out, or too many wrong codes (null otherwise) */
+ pairingClosed: null | 'expired' | 'tooMany'
+ /**
+ * keychain: the system keychain wouldn't open this computer's key (off, the pairing kept, until a start where it opens);
+ * listen: the server couldn't start listening, so pairing closed (the next start tries again);
+ * network: the local network refused the advert (macOS Local Network permission, a firewall), so the phone can't find it
+ */
+ error: null | 'keychain' | 'listen' | 'network'
+ connected: boolean
+ syncing: boolean
+}
+
+/** The iPhone companion stays off and hidden until the iPhone app ships. YOGURT_PHONE=1 turns it on (dev, tests). */
+export const PHONE_COMPANION = false
+export const phoneCompanionOn = (env: Record<string, string | undefined>): boolean => PHONE_COMPANION || env.YOGURT_PHONE === '1'
diff --git a/app/src/shared/locales/ar.json b/app/src/shared/locales/ar.json
index e3e5cd34..1278ebd8 100644
--- a/app/src/shared/locales/ar.json
+++ b/app/src/shared/locales/ar.json
@@ -820,5 +820,25 @@
"Send feedback": "إرسال ملاحظات",
"Help and settings": "المساعدة والإعدادات",
"Yogurt menu": "قائمة Yogurt",
- "Restart to update · {version}": "إعادة التشغيل للتحديث · {version}"
+ "Restart to update · {version}": "إعادة التشغيل للتحديث · {version}",
+ "Phone": "الهاتف",
+ "Pair a phone": "إقران هاتف",
+ "Open Yogurt on your iPhone and type this code": "افتح Yogurt على iPhone واكتب هذا الرمز",
+ "Code works for {time}": "الرمز صالح لمدة {time}",
+ "Connected": "متصل",
+ "Last seen just now": "آخر ظهور الآن",
+ "Last seen {when}": "آخر ظهور {when}",
+ "Not connected yet": "لم يتصل بعد",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "اقرأ ملاحظاتك وسجّل الاجتماعات على iPhone. تعود إلى هنا لتُفرَّغ نصيًا.",
+ "The code ran out. Start pairing again.": "انتهت صلاحية الرمز. ابدأ الإقران من جديد.",
+ "Too many wrong codes. Start pairing again.": "رموز خاطئة كثيرة. ابدأ الإقران من جديد.",
+ "Unpair": "إلغاء الإقران",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "هل تريد إلغاء إقران iPhone؟ يحتفظ بنسخته حتى تقرنه مرة أخرى.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "تعذّر على Yogurt الوصول إلى التخزين الآمن في هذا الكمبيوتر، لذا لا يمكنه الإقران الآن.",
+ "Yogurt couldn't start pairing. Try again.": "تعذّر على Yogurt بدء الإقران. حاول مرة أخرى.",
+ "Yogurt on your iPhone": "Yogurt على iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "يتواصل iPhone مع هذا الكمبيوتر فقط على شبكة Wi-Fi نفسها. لا شيء يمر عبر الإنترنت.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "لا يستطيع iPhone الوصول إلى هذا الكمبيوتر الآن. جرّب إعادة تشغيل Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "لا يستطيع iPhone رؤية هذا الكمبيوتر. اسمح لـ Yogurt بالشبكة المحلية في إعدادات النظام ← الخصوصية والأمن.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "لا يستطيع iPhone رؤية هذا الكمبيوتر. اسمح لـ Yogurt بالمرور عبر جدار الحماية على الشبكات الخاصة."
}
diff --git a/app/src/shared/locales/bn.json b/app/src/shared/locales/bn.json
index 5625059a..14cf7989 100644
--- a/app/src/shared/locales/bn.json
+++ b/app/src/shared/locales/bn.json
@@ -752,5 +752,25 @@
"Send feedback": "মতামত পাঠান",
"Help and settings": "সহায়তা ও সেটিংস",
"Yogurt menu": "Yogurt মেনু",
- "Restart to update · {version}": "আপডেট করতে পুনরায় চালু করুন · {version}"
+ "Restart to update · {version}": "আপডেট করতে পুনরায় চালু করুন · {version}",
+ "Phone": "ফোন",
+ "Pair a phone": "ফোন যুক্ত করুন",
+ "Open Yogurt on your iPhone and type this code": "আপনার iPhone-এ Yogurt খুলুন এবং এই কোডটি লিখুন",
+ "Code works for {time}": "কোডটি আর {time} চলবে",
+ "Connected": "সংযুক্ত",
+ "Last seen just now": "এইমাত্র দেখা গেছে",
+ "Last seen {when}": "শেষ দেখা গেছে {when}",
+ "Not connected yet": "এখনো সংযুক্ত হয়নি",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "আপনার iPhone-এ নোট পড়ুন এবং মিটিং রেকর্ড করুন। ট্রান্সক্রাইব হওয়ার জন্য সেগুলো এখানে ফিরে আসে।",
+ "The code ran out. Start pairing again.": "কোডের মেয়াদ শেষ। আবার যুক্ত করা শুরু করুন।",
+ "Too many wrong codes. Start pairing again.": "অনেক বেশি ভুল কোড। আবার যুক্ত করা শুরু করুন।",
+ "Unpair": "বিচ্ছিন্ন করুন",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "আপনার iPhone বিচ্ছিন্ন করবেন? আবার যুক্ত না করা পর্যন্ত এটি নিজের কপি রাখে।",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt এই কম্পিউটারের সুরক্ষিত স্টোরেজে পৌঁছাতে পারেনি, তাই এখন যুক্ত করতে পারছে না।",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt যুক্ত করা শুরু করতে পারেনি। আবার চেষ্টা করুন।",
+ "Yogurt on your iPhone": "আপনার iPhone-এ Yogurt",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "আপনার iPhone শুধু একই Wi-Fi-তে এই কম্পিউটারের সঙ্গে কথা বলে। কিছুই ইন্টারনেট দিয়ে যায় না।",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "আপনার iPhone এখন এই কম্পিউটারে পৌঁছাতে পারছে না। Yogurt আবার চালু করে দেখুন।",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "আপনার iPhone এই কম্পিউটারটি দেখতে পাচ্ছে না। সিস্টেম সেটিংস → গোপনীয়তা ও নিরাপত্তায় Yogurt-কে লোকাল নেটওয়ার্ক ব্যবহারের অনুমতি দিন।",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "আপনার iPhone এই কম্পিউটারটি দেখতে পাচ্ছে না। প্রাইভেট নেটওয়ার্কে আপনার ফায়ারওয়ালের মধ্য দিয়ে Yogurt-কে অনুমতি দিন।"
}
diff --git a/app/src/shared/locales/cs.json b/app/src/shared/locales/cs.json
index 945da790..04967d16 100644
--- a/app/src/shared/locales/cs.json
+++ b/app/src/shared/locales/cs.json
@@ -795,5 +795,25 @@
"Send feedback": "Odeslat zpětnou vazbu",
"Help and settings": "Nápověda a nastavení",
"Yogurt menu": "Nabídka Yogurt",
- "Restart to update · {version}": "Restartovat a aktualizovat · {version}"
+ "Restart to update · {version}": "Restartovat a aktualizovat · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Spárovat telefon",
+ "Open Yogurt on your iPhone and type this code": "Otevřete Yogurt v iPhonu a zadejte tento kód",
+ "Code works for {time}": "Kód platí ještě {time}",
+ "Connected": "Připojeno",
+ "Last seen just now": "Naposledy viděn právě teď",
+ "Last seen {when}": "Naposledy viděn {when}",
+ "Not connected yet": "Zatím nepřipojeno",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Čtěte poznámky a nahrávejte schůzky v iPhonu. Vracejí se sem k přepisu.",
+ "The code ran out. Start pairing again.": "Platnost kódu vypršela. Začněte párování znovu.",
+ "Too many wrong codes. Start pairing again.": "Příliš mnoho špatných kódů. Začněte párování znovu.",
+ "Unpair": "Zrušit párování",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Zrušit párování iPhonu? Svou kopii si ponechá, dokud ho znovu nespárujete.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt se nedostal k zabezpečenému úložišti tohoto počítače, takže teď nemůže párovat.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt nemohl zahájit párování. Zkuste to znovu.",
+ "Yogurt on your iPhone": "Yogurt v iPhonu",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Váš iPhone komunikuje s tímto počítačem jen ve stejné síti Wi-Fi. Nic nejde přes internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Váš iPhone se teď k tomuto počítači nedostane. Zkuste Yogurt restartovat.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Váš iPhone tento počítač nevidí. Povolte Yogurtu místní síť v Nastavení systému → Soukromí a zabezpečení.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Váš iPhone tento počítač nevidí. Povolte Yogurt ve firewallu pro soukromé sítě."
}
diff --git a/app/src/shared/locales/da.json b/app/src/shared/locales/da.json
index 05be6ecc..d720990c 100644
--- a/app/src/shared/locales/da.json
+++ b/app/src/shared/locales/da.json
@@ -764,5 +764,25 @@
"Send feedback": "Send feedback",
"Help and settings": "Hjælp og indstillinger",
"Yogurt menu": "Yogurt-menu",
- "Restart to update · {version}": "Genstart for at opdatere · {version}"
+ "Restart to update · {version}": "Genstart for at opdatere · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Par en telefon",
+ "Open Yogurt on your iPhone and type this code": "Åbn Yogurt på din iPhone, og skriv denne kode",
+ "Code works for {time}": "Koden virker i {time} endnu",
+ "Connected": "Forbundet",
+ "Last seen just now": "Set lige nu",
+ "Last seen {when}": "Sidst set {when}",
+ "Not connected yet": "Ikke forbundet endnu",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Læs dine noter, og optag møder på din iPhone. De kommer tilbage hertil for at blive transskriberet.",
+ "The code ran out. Start pairing again.": "Koden udløb. Start parringen igen.",
+ "Too many wrong codes. Start pairing again.": "For mange forkerte koder. Start parringen igen.",
+ "Unpair": "Fjern parring",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Fjern parringen med din iPhone? Den beholder sin kopi, indtil du parrer igen.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt kunne ikke nå computerens sikre lager, så den kan ikke parre lige nu.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt kunne ikke starte parringen. Prøv igen.",
+ "Yogurt on your iPhone": "Yogurt på din iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Din iPhone taler kun med denne computer på samme wi-fi. Intet går via internettet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Din iPhone kan ikke nå denne computer lige nu. Prøv at genstarte Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Din iPhone kan ikke se denne computer. Giv Yogurt adgang til lokalt netværk i Systemindstillinger → Anonymitet og sikkerhed.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Din iPhone kan ikke se denne computer. Tillad Yogurt gennem din firewall på private netværk."
}
diff --git a/app/src/shared/locales/de.json b/app/src/shared/locales/de.json
index 30543a2a..311e340b 100644
--- a/app/src/shared/locales/de.json
+++ b/app/src/shared/locales/de.json
@@ -764,5 +764,25 @@
"Send feedback": "Feedback senden",
"Help and settings": "Hilfe und Einstellungen",
"Yogurt menu": "Yogurt-Menü",
- "Restart to update · {version}": "Zum Aktualisieren neu starten · {version}"
+ "Restart to update · {version}": "Zum Aktualisieren neu starten · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "iPhone koppeln",
+ "Open Yogurt on your iPhone and type this code": "Öffne Yogurt auf deinem iPhone und gib diesen Code ein",
+ "Code works for {time}": "Code gilt noch {time}",
+ "Connected": "Verbunden",
+ "Last seen just now": "Zuletzt gesehen gerade eben",
+ "Last seen {when}": "Zuletzt gesehen {when}",
+ "Not connected yet": "Noch nicht verbunden",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Lies deine Notizen und nimm Meetings auf deinem iPhone auf. Sie kommen hierher zurück, um transkribiert zu werden.",
+ "The code ran out. Start pairing again.": "Der Code ist abgelaufen. Starte das Koppeln neu.",
+ "Too many wrong codes. Start pairing again.": "Zu viele falsche Codes. Starte das Koppeln neu.",
+ "Unpair": "Entkoppeln",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "iPhone entkoppeln? Es behält seine Kopie, bis du es wieder koppelst.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt konnte den sicheren Speicher dieses Computers nicht erreichen und kann deshalb gerade nicht koppeln.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt konnte das Koppeln nicht starten. Versuch es noch einmal.",
+ "Yogurt on your iPhone": "Yogurt auf deinem iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Dein iPhone spricht mit diesem Computer nur im selben WLAN. Nichts geht über das Internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Dein iPhone kann diesen Computer gerade nicht erreichen. Starte Yogurt neu.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Dein iPhone sieht diesen Computer nicht. Erlaube Yogurt das lokale Netzwerk in Systemeinstellungen → Datenschutz & Sicherheit.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Dein iPhone sieht diesen Computer nicht. Lass Yogurt in deiner Firewall für private Netzwerke zu."
}
diff --git a/app/src/shared/locales/el.json b/app/src/shared/locales/el.json
index c4903b3d..a6b9216b 100644
--- a/app/src/shared/locales/el.json
+++ b/app/src/shared/locales/el.json
@@ -767,5 +767,25 @@
"Send feedback": "Αποστολή σχολίων",
"Help and settings": "Βοήθεια και ρυθμίσεις",
"Yogurt menu": "Μενού Yogurt",
- "Restart to update · {version}": "Επανεκκίνηση για ενημέρωση · {version}"
+ "Restart to update · {version}": "Επανεκκίνηση για ενημέρωση · {version}",
+ "Phone": "Τηλέφωνο",
+ "Pair a phone": "Σύζευξη τηλεφώνου",
+ "Open Yogurt on your iPhone and type this code": "Άνοιξε το Yogurt στο iPhone σου και πληκτρολόγησε αυτόν τον κωδικό",
+ "Code works for {time}": "Ο κωδικός ισχύει ακόμη {time}",
+ "Connected": "Συνδεδεμένο",
+ "Last seen just now": "Εμφανίστηκε μόλις τώρα",
+ "Last seen {when}": "Τελευταία εμφάνιση {when}",
+ "Not connected yet": "Δεν έχει συνδεθεί ακόμη",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Διάβασε τις σημειώσεις σου και ηχογράφησε συσκέψεις στο iPhone σου. Επιστρέφουν εδώ για απομαγνητοφώνηση.",
+ "The code ran out. Start pairing again.": "Ο κωδικός έληξε. Ξεκίνα πάλι τη σύζευξη.",
+ "Too many wrong codes. Start pairing again.": "Πάρα πολλοί λάθος κωδικοί. Ξεκίνα πάλι τη σύζευξη.",
+ "Unpair": "Κατάργηση σύζευξης",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Κατάργηση σύζευξης του iPhone σου; Κρατά το αντίγραφό του μέχρι να το συζεύξεις ξανά.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Το Yogurt δεν μπόρεσε να φτάσει στον ασφαλή χώρο αποθήκευσης αυτού του υπολογιστή, οπότε δεν μπορεί να κάνει σύζευξη τώρα.",
+ "Yogurt couldn't start pairing. Try again.": "Το Yogurt δεν μπόρεσε να ξεκινήσει τη σύζευξη. Δοκίμασε ξανά.",
+ "Yogurt on your iPhone": "Το Yogurt στο iPhone σου",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Το iPhone σου μιλά με αυτόν τον υπολογιστή μόνο στο ίδιο Wi-Fi. Τίποτα δεν περνά από το διαδίκτυο.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Το iPhone σου δεν μπορεί να φτάσει αυτόν τον υπολογιστή τώρα. Δοκίμασε να επανεκκινήσεις το Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Το iPhone σου δεν βλέπει αυτόν τον υπολογιστή. Επίτρεψε το Τοπικό δίκτυο για το Yogurt στις Ρυθμίσεις συστήματος → Απόρρητο και ασφάλεια.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Το iPhone σου δεν βλέπει αυτόν τον υπολογιστή. Επίτρεψε το Yogurt στο τείχος προστασίας για ιδιωτικά δίκτυα."
}
diff --git a/app/src/shared/locales/es.json b/app/src/shared/locales/es.json
index 4c6e504e..6d544f68 100644
--- a/app/src/shared/locales/es.json
+++ b/app/src/shared/locales/es.json
@@ -777,5 +777,25 @@
"Send feedback": "Enviar comentarios",
"Help and settings": "Ayuda y ajustes",
"Yogurt menu": "Menú de Yogurt",
- "Restart to update · {version}": "Reiniciar para actualizar · {version}"
+ "Restart to update · {version}": "Reiniciar para actualizar · {version}",
+ "Phone": "Teléfono",
+ "Pair a phone": "Vincular un teléfono",
+ "Open Yogurt on your iPhone and type this code": "Abre Yogurt en tu iPhone y escribe este código",
+ "Code works for {time}": "El código vale {time} más",
+ "Connected": "Conectado",
+ "Last seen just now": "Visto hace un momento",
+ "Last seen {when}": "Visto {when}",
+ "Not connected yet": "Aún no conectado",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Lee tus notas y graba reuniones en tu iPhone. Vuelven aquí para transcribirse.",
+ "The code ran out. Start pairing again.": "El código caducó. Vuelve a empezar la vinculación.",
+ "Too many wrong codes. Start pairing again.": "Demasiados códigos incorrectos. Vuelve a empezar la vinculación.",
+ "Unpair": "Desvincular",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "¿Desvincular tu iPhone? Conserva su copia hasta que lo vuelvas a vincular.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt no pudo acceder al almacenamiento seguro de este ordenador, así que ahora no puede vincular.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt no pudo iniciar la vinculación. Inténtalo de nuevo.",
+ "Yogurt on your iPhone": "Yogurt en tu iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Tu iPhone habla con este ordenador solo en la misma red Wi-Fi. Nada pasa por internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Tu iPhone no puede comunicarse con este ordenador ahora. Prueba a reiniciar Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Tu iPhone no ve este ordenador. Permite la red local para Yogurt en Ajustes del Sistema → Privacidad y seguridad.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Tu iPhone no ve este ordenador. Permite Yogurt en tu cortafuegos para redes privadas."
}
diff --git a/app/src/shared/locales/fi.json b/app/src/shared/locales/fi.json
index 12270f7e..75c71def 100644
--- a/app/src/shared/locales/fi.json
+++ b/app/src/shared/locales/fi.json
@@ -770,5 +770,25 @@
"Send feedback": "Lähetä palautetta",
"Help and settings": "Ohje ja asetukset",
"Yogurt menu": "Yogurt-valikko",
- "Restart to update · {version}": "Käynnistä uudelleen ja päivitä · {version}"
+ "Restart to update · {version}": "Käynnistä uudelleen ja päivitä · {version}",
+ "Phone": "Puhelin",
+ "Pair a phone": "Yhdistä puhelin",
+ "Open Yogurt on your iPhone and type this code": "Avaa Yogurt iPhonessasi ja kirjoita tämä koodi",
+ "Code works for {time}": "Koodi toimii vielä {time}",
+ "Connected": "Yhdistetty",
+ "Last seen just now": "Nähty juuri äsken",
+ "Last seen {when}": "Nähty viimeksi {when}",
+ "Not connected yet": "Ei vielä yhdistetty",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Lue muistiinpanojasi ja nauhoita kokouksia iPhonella. Ne palaavat tänne litteroitaviksi.",
+ "The code ran out. Start pairing again.": "Koodi vanheni. Aloita yhdistäminen uudelleen.",
+ "Too many wrong codes. Start pairing again.": "Liian monta väärää koodia. Aloita yhdistäminen uudelleen.",
+ "Unpair": "Poista yhdistys",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Poistetaanko iPhonen yhdistys? Se säilyttää kopionsa, kunnes yhdistät uudelleen.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt ei saanut yhteyttä tämän tietokoneen suojattuun tallennustilaan, joten se ei voi yhdistää juuri nyt.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt ei voinut aloittaa yhdistämistä. Yritä uudelleen.",
+ "Yogurt on your iPhone": "Yogurt iPhonessasi",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhonesi puhuu tämän tietokoneen kanssa vain samassa Wi-Fi-verkossa. Mitään ei kulje internetin kautta.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhonesi ei tavoita tätä tietokonetta juuri nyt. Kokeile käynnistää Yogurt uudelleen.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhonesi ei näe tätä tietokonetta. Salli Yogurtille paikallisverkko kohdassa Järjestelmäasetukset → Tietosuoja ja turvallisuus.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhonesi ei näe tätä tietokonetta. Salli Yogurt palomuurissa yksityisissä verkoissa."
}
diff --git a/app/src/shared/locales/fil.json b/app/src/shared/locales/fil.json
index ae882f07..c0a699a6 100644
--- a/app/src/shared/locales/fil.json
+++ b/app/src/shared/locales/fil.json
@@ -764,5 +764,25 @@
"Send feedback": "Magpadala ng feedback",
"Help and settings": "Tulong at mga setting",
"Yogurt menu": "Menu ng Yogurt",
- "Restart to update · {version}": "I-restart para mag-update · {version}"
+ "Restart to update · {version}": "I-restart para mag-update · {version}",
+ "Phone": "Telepono",
+ "Pair a phone": "Ipares ang isang phone",
+ "Open Yogurt on your iPhone and type this code": "Buksan ang Yogurt sa iPhone mo at i-type ang code na ito",
+ "Code works for {time}": "Gagana pa ang code nang {time}",
+ "Connected": "Nakakonekta",
+ "Last seen just now": "Nakita ngayon lang",
+ "Last seen {when}": "Huling nakita {when}",
+ "Not connected yet": "Hindi pa nakakonekta",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Basahin ang mga tala mo at mag-record ng mga meeting sa iPhone mo. Bumabalik sila rito para ma-transcribe.",
+ "The code ran out. Start pairing again.": "Nag-expire na ang code. Simulan ulit ang pagpapares.",
+ "Too many wrong codes. Start pairing again.": "Masyadong maraming maling code. Simulan ulit ang pagpapares.",
+ "Unpair": "Alisin ang pares",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Alisin ang pares ng iPhone mo? Itatago nito ang kopya nito hanggang ipares mo ulit.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Hindi maabot ng Yogurt ang secure storage ng computer na ito, kaya hindi ito makakapagpares ngayon.",
+ "Yogurt couldn't start pairing. Try again.": "Hindi masimulan ng Yogurt ang pagpapares. Subukan ulit.",
+ "Yogurt on your iPhone": "Yogurt sa iPhone mo",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Kausap lang ng iPhone mo ang computer na ito sa iisang Wi-Fi. Walang dumadaan sa internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Hindi maabot ng iPhone mo ang computer na ito ngayon. Subukang i-restart ang Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Hindi makita ng iPhone mo ang computer na ito. Payagan ang Local Network para sa Yogurt sa System Settings → Privacy & Security.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Hindi makita ng iPhone mo ang computer na ito. Payagan ang Yogurt sa firewall mo para sa mga private network."
}
diff --git a/app/src/shared/locales/fr.json b/app/src/shared/locales/fr.json
index 8e1062fc..3ca7794b 100644
--- a/app/src/shared/locales/fr.json
+++ b/app/src/shared/locales/fr.json
@@ -780,5 +780,25 @@
"Send feedback": "Envoyer un commentaire",
"Help and settings": "Aide et paramètres",
"Yogurt menu": "Menu de Yogurt",
- "Restart to update · {version}": "Redémarrer pour mettre à jour · {version}"
+ "Restart to update · {version}": "Redémarrer pour mettre à jour · {version}",
+ "Phone": "Téléphone",
+ "Pair a phone": "Associer un téléphone",
+ "Open Yogurt on your iPhone and type this code": "Ouvrez Yogurt sur votre iPhone et saisissez ce code",
+ "Code works for {time}": "Code valable encore {time}",
+ "Connected": "Connecté",
+ "Last seen just now": "Vu à l’instant",
+ "Last seen {when}": "Vu {when}",
+ "Not connected yet": "Pas encore connecté",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Lisez vos notes et enregistrez des réunions sur votre iPhone. Elles reviennent ici pour être transcrites.",
+ "The code ran out. Start pairing again.": "Le code a expiré. Recommencez l’association.",
+ "Too many wrong codes. Start pairing again.": "Trop de codes erronés. Recommencez l’association.",
+ "Unpair": "Dissocier",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Dissocier votre iPhone ? Il garde sa copie jusqu’à la prochaine association.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt n’a pas pu accéder au stockage sécurisé de cet ordinateur, il ne peut donc pas s’associer pour le moment.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt n’a pas pu lancer l’association. Réessayez.",
+ "Yogurt on your iPhone": "Yogurt sur votre iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Votre iPhone ne communique avec cet ordinateur que sur le même réseau Wi-Fi. Rien ne passe par Internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Votre iPhone ne peut pas joindre cet ordinateur pour le moment. Essayez de redémarrer Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Votre iPhone ne voit pas cet ordinateur. Autorisez le réseau local pour Yogurt dans Réglages Système → Confidentialité et sécurité.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Votre iPhone ne voit pas cet ordinateur. Autorisez Yogurt dans votre pare-feu pour les réseaux privés."
}
diff --git a/app/src/shared/locales/he.json b/app/src/shared/locales/he.json
index 7ffd86f5..09c7c7a1 100644
--- a/app/src/shared/locales/he.json
+++ b/app/src/shared/locales/he.json
@@ -774,5 +774,25 @@
"Send feedback": "שליחת משוב",
"Help and settings": "עזרה והגדרות",
"Yogurt menu": "תפריט Yogurt",
- "Restart to update · {version}": "הפעלה מחדש לעדכון · {version}"
+ "Restart to update · {version}": "הפעלה מחדש לעדכון · {version}",
+ "Phone": "טלפון",
+ "Pair a phone": "צימוד טלפון",
+ "Open Yogurt on your iPhone and type this code": "פתחו את Yogurt ב-iPhone והקלידו את הקוד הזה",
+ "Code works for {time}": "הקוד תקף עוד {time}",
+ "Connected": "מחובר",
+ "Last seen just now": "נראה הרגע",
+ "Last seen {when}": "נראה לאחרונה {when}",
+ "Not connected yet": "עדיין לא התחבר",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "קראו את ההערות שלכם והקליטו פגישות ב-iPhone. הן חוזרות לכאן לתמלול.",
+ "The code ran out. Start pairing again.": "תוקף הקוד פג. התחילו את הצימוד מחדש.",
+ "Too many wrong codes. Start pairing again.": "יותר מדי קודים שגויים. התחילו את הצימוד מחדש.",
+ "Unpair": "ביטול צימוד",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "לבטל את הצימוד של ה-iPhone? הוא שומר את העותק שלו עד שתצמדו שוב.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt לא הצליח לגשת לאחסון המאובטח של המחשב הזה, ולכן אינו יכול לצמד כרגע.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt לא הצליח להתחיל את הצימוד. נסו שוב.",
+ "Yogurt on your iPhone": "Yogurt ב-iPhone שלך",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "ה-iPhone מדבר עם המחשב הזה רק באותה רשת Wi-Fi. שום דבר לא עובר דרך האינטרנט.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "ה-iPhone לא מצליח להגיע למחשב הזה כרגע. נסו להפעיל מחדש את Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "ה-iPhone לא רואה את המחשב הזה. אפשרו ל-Yogurt גישה לרשת המקומית בהגדרות המערכת ← פרטיות ואבטחה.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "ה-iPhone לא רואה את המחשב הזה. אפשרו ל-Yogurt לעבור דרך חומת האש ברשתות פרטיות."
}
diff --git a/app/src/shared/locales/hi.json b/app/src/shared/locales/hi.json
index b8390060..82899e45 100644
--- a/app/src/shared/locales/hi.json
+++ b/app/src/shared/locales/hi.json
@@ -752,5 +752,25 @@
"Send feedback": "फ़ीडबैक भेजें",
"Help and settings": "सहायता और सेटिंग",
"Yogurt menu": "Yogurt मेन्यू",
- "Restart to update · {version}": "अपडेट के लिए रीस्टार्ट करें · {version}"
+ "Restart to update · {version}": "अपडेट के लिए रीस्टार्ट करें · {version}",
+ "Phone": "फ़ोन",
+ "Pair a phone": "फ़ोन जोड़ें",
+ "Open Yogurt on your iPhone and type this code": "अपने iPhone पर Yogurt खोलें और यह कोड डालें",
+ "Code works for {time}": "कोड {time} और चलेगा",
+ "Connected": "कनेक्टेड",
+ "Last seen just now": "अभी-अभी देखा गया",
+ "Last seen {when}": "आख़िरी बार देखा गया {when}",
+ "Not connected yet": "अभी तक कनेक्ट नहीं हुआ",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "अपने iPhone पर नोट्स पढ़ें और मीटिंग रिकॉर्ड करें। वे ट्रांसक्राइब होने के लिए यहाँ वापस आती हैं।",
+ "The code ran out. Start pairing again.": "कोड की समय सीमा ख़त्म हो गई। फिर से जोड़ना शुरू करें।",
+ "Too many wrong codes. Start pairing again.": "बहुत सारे ग़लत कोड। फिर से जोड़ना शुरू करें।",
+ "Unpair": "अलग करें",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "अपना iPhone अलग करें? दोबारा जोड़ने तक वह अपनी कॉपी रखता है।",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt इस कंप्यूटर के सुरक्षित स्टोरेज तक नहीं पहुँच सका, इसलिए अभी जोड़ नहीं सकता।",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt जोड़ना शुरू नहीं कर सका। फिर से कोशिश करें।",
+ "Yogurt on your iPhone": "आपके iPhone पर Yogurt",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "आपका iPhone इस कंप्यूटर से सिर्फ़ एक ही Wi-Fi पर बात करता है। कुछ भी इंटरनेट से नहीं जाता।",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "आपका iPhone अभी इस कंप्यूटर तक नहीं पहुँच पा रहा। Yogurt को फिर से शुरू करके देखें।",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "आपका iPhone इस कंप्यूटर को नहीं देख पा रहा। सिस्टम सेटिंग्ज़ → गोपनीयता और सुरक्षा में Yogurt को लोकल नेटवर्क की अनुमति दें।",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "आपका iPhone इस कंप्यूटर को नहीं देख पा रहा। निजी नेटवर्क पर अपने फ़ायरवॉल में Yogurt को अनुमति दें।"
}
diff --git a/app/src/shared/locales/hu.json b/app/src/shared/locales/hu.json
index c285f49a..82f994c1 100644
--- a/app/src/shared/locales/hu.json
+++ b/app/src/shared/locales/hu.json
@@ -752,5 +752,25 @@
"Send feedback": "Visszajelzés küldése",
"Help and settings": "Súgó és beállítások",
"Yogurt menu": "Yogurt menü",
- "Restart to update · {version}": "Újraindítás a frissítéshez · {version}"
+ "Restart to update · {version}": "Újraindítás a frissítéshez · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Telefon párosítása",
+ "Open Yogurt on your iPhone and type this code": "Nyisd meg a Yogurtot az iPhone-odon, és írd be ezt a kódot",
+ "Code works for {time}": "A kód még {time} ideig érvényes",
+ "Connected": "Csatlakoztatva",
+ "Last seen just now": "Épp most látva",
+ "Last seen {when}": "Utoljára látva: {when}",
+ "Not connected yet": "Még nincs csatlakoztatva",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Olvasd a jegyzeteidet, és rögzíts megbeszéléseket az iPhone-odon. Ide kerülnek vissza átírásra.",
+ "The code ran out. Start pairing again.": "A kód lejárt. Kezdd újra a párosítást.",
+ "Too many wrong codes. Start pairing again.": "Túl sok hibás kód. Kezdd újra a párosítást.",
+ "Unpair": "Párosítás megszüntetése",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Megszünteted az iPhone párosítását? Megtartja a másolatát, amíg újra nem párosítod.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "A Yogurt nem érte el a számítógép biztonságos tárhelyét, ezért most nem tud párosítani.",
+ "Yogurt couldn't start pairing. Try again.": "A Yogurt nem tudta elindítani a párosítást. Próbáld újra.",
+ "Yogurt on your iPhone": "Yogurt az iPhone-odon",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Az iPhone-od csak ugyanazon a Wi-Fi-hálózaton beszél ezzel a számítógéppel. Semmi sem megy át az interneten.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Az iPhone-od most nem éri el ezt a számítógépet. Próbáld újraindítani a Yogurtot.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Az iPhone-od nem látja ezt a számítógépet. Engedélyezd a Yogurtnak a helyi hálózatot a Rendszerbeállítások → Adatvédelem és biztonság alatt.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Az iPhone-od nem látja ezt a számítógépet. Engedélyezd a Yogurtot a tűzfaladon a magánhálózatokon."
}
diff --git a/app/src/shared/locales/id.json b/app/src/shared/locales/id.json
index a681bf88..77a86165 100644
--- a/app/src/shared/locales/id.json
+++ b/app/src/shared/locales/id.json
@@ -722,5 +722,25 @@
"Send feedback": "Kirim masukan",
"Help and settings": "Bantuan dan pengaturan",
"Yogurt menu": "Menu Yogurt",
- "Restart to update · {version}": "Mulai ulang untuk memperbarui · {version}"
+ "Restart to update · {version}": "Mulai ulang untuk memperbarui · {version}",
+ "Phone": "Ponsel",
+ "Pair a phone": "Pasangkan ponsel",
+ "Open Yogurt on your iPhone and type this code": "Buka Yogurt di iPhone dan ketik kode ini",
+ "Code works for {time}": "Kode berlaku {time} lagi",
+ "Connected": "Terhubung",
+ "Last seen just now": "Terlihat baru saja",
+ "Last seen {when}": "Terakhir terlihat {when}",
+ "Not connected yet": "Belum terhubung",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Baca catatan dan rekam rapat di iPhone. Semuanya kembali ke sini untuk ditranskripsi.",
+ "The code ran out. Start pairing again.": "Kode sudah kedaluwarsa. Mulai pemasangan lagi.",
+ "Too many wrong codes. Start pairing again.": "Terlalu banyak kode salah. Mulai pemasangan lagi.",
+ "Unpair": "Lepaskan",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Lepaskan iPhone? iPhone menyimpan salinannya sampai kamu memasangkannya lagi.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt tidak bisa menjangkau penyimpanan aman komputer ini, jadi tidak bisa memasangkan sekarang.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt tidak bisa memulai pemasangan. Coba lagi.",
+ "Yogurt on your iPhone": "Yogurt di iPhone kamu",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone kamu hanya berbicara dengan komputer ini di Wi-Fi yang sama. Tidak ada yang lewat internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone kamu tidak bisa menjangkau komputer ini sekarang. Coba mulai ulang Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone kamu tidak bisa melihat komputer ini. Izinkan Jaringan Lokal untuk Yogurt di Pengaturan Sistem → Privasi & Keamanan.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone kamu tidak bisa melihat komputer ini. Izinkan Yogurt melewati firewall kamu di jaringan pribadi."
}
diff --git a/app/src/shared/locales/it.json b/app/src/shared/locales/it.json
index 0f4f0213..a1c0f7ac 100644
--- a/app/src/shared/locales/it.json
+++ b/app/src/shared/locales/it.json
@@ -783,5 +783,25 @@
"Send feedback": "Invia feedback",
"Help and settings": "Aiuto e impostazioni",
"Yogurt menu": "Menu di Yogurt",
- "Restart to update · {version}": "Riavvia per aggiornare · {version}"
+ "Restart to update · {version}": "Riavvia per aggiornare · {version}",
+ "Phone": "Telefono",
+ "Pair a phone": "Abbina un telefono",
+ "Open Yogurt on your iPhone and type this code": "Apri Yogurt sul tuo iPhone e inserisci questo codice",
+ "Code works for {time}": "Il codice vale ancora {time}",
+ "Connected": "Connesso",
+ "Last seen just now": "Visto proprio ora",
+ "Last seen {when}": "Visto {when}",
+ "Not connected yet": "Non ancora connesso",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Leggi le tue note e registra riunioni sul tuo iPhone. Tornano qui per essere trascritte.",
+ "The code ran out. Start pairing again.": "Il codice è scaduto. Ricomincia l’abbinamento.",
+ "Too many wrong codes. Start pairing again.": "Troppi codici sbagliati. Ricomincia l’abbinamento.",
+ "Unpair": "Dissocia",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Dissociare il tuo iPhone? Tiene la sua copia finché non lo abbini di nuovo.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt non è riuscito ad accedere all’archivio sicuro di questo computer, quindi ora non può abbinare.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt non è riuscito ad avviare l’abbinamento. Riprova.",
+ "Yogurt on your iPhone": "Yogurt sul tuo iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Il tuo iPhone parla con questo computer solo sulla stessa rete Wi-Fi. Niente passa da internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Il tuo iPhone non riesce a raggiungere questo computer ora. Prova a riavviare Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Il tuo iPhone non vede questo computer. Consenti la rete locale a Yogurt in Impostazioni di Sistema → Privacy e sicurezza.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Il tuo iPhone non vede questo computer. Consenti Yogurt nel firewall per le reti private."
}
diff --git a/app/src/shared/locales/ja.json b/app/src/shared/locales/ja.json
index 76100c1b..2a99db08 100644
--- a/app/src/shared/locales/ja.json
+++ b/app/src/shared/locales/ja.json
@@ -722,5 +722,25 @@
"Send feedback": "フィードバックを送信",
"Help and settings": "ヘルプと設定",
"Yogurt menu": "Yogurt メニュー",
- "Restart to update · {version}": "再起動してアップデート · {version}"
+ "Restart to update · {version}": "再起動してアップデート · {version}",
+ "Phone": "iPhone",
+ "Pair a phone": "iPhoneとペアリング",
+ "Open Yogurt on your iPhone and type this code": "iPhoneでYogurtを開いて、このコードを入力してください",
+ "Code works for {time}": "コードの有効時間:残り{time}",
+ "Connected": "接続中",
+ "Last seen just now": "たった今接続",
+ "Last seen {when}": "最終接続:{when}",
+ "Not connected yet": "まだ接続していません",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "iPhoneでメモを読んだり、会議を録音したりできます。録音はこちらに戻って文字起こしされます。",
+ "The code ran out. Start pairing again.": "コードの有効期限が切れました。もう一度ペアリングを始めてください。",
+ "Too many wrong codes. Start pairing again.": "間違ったコードが多すぎます。もう一度ペアリングを始めてください。",
+ "Unpair": "ペアリングを解除",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "iPhoneとのペアリングを解除しますか?再びペアリングするまで、iPhoneは自分のコピーを保持します。",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurtがこのコンピュータの安全な保存領域にアクセスできなかったため、今はペアリングできません。",
+ "Yogurt couldn't start pairing. Try again.": "Yogurtはペアリングを開始できませんでした。もう一度お試しください。",
+ "Yogurt on your iPhone": "iPhone版Yogurt",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhoneは同じWi-Fi上でのみこのコンピュータと通信します。インターネットを経由するものはありません。",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhoneが今このコンピュータに接続できません。Yogurtを再起動してみてください。",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhoneからこのコンピュータが見えません。システム設定 → プライバシーとセキュリティで、Yogurtのローカルネットワークを許可してください。",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhoneからこのコンピュータが見えません。ファイアウォールで、プライベートネットワークでのYogurtの通信を許可してください。"
}
diff --git a/app/src/shared/locales/ko.json b/app/src/shared/locales/ko.json
index 00ef1e05..f9afb17b 100644
--- a/app/src/shared/locales/ko.json
+++ b/app/src/shared/locales/ko.json
@@ -722,5 +722,25 @@
"Send feedback": "의견 보내기",
"Help and settings": "도움말 및 설정",
"Yogurt menu": "Yogurt 메뉴",
- "Restart to update · {version}": "다시 시작하여 업데이트 · {version}"
+ "Restart to update · {version}": "다시 시작하여 업데이트 · {version}",
+ "Phone": "휴대폰",
+ "Pair a phone": "휴대폰 페어링",
+ "Open Yogurt on your iPhone and type this code": "iPhone에서 Yogurt를 열고 이 코드를 입력하세요",
+ "Code works for {time}": "코드 남은 시간 {time}",
+ "Connected": "연결됨",
+ "Last seen just now": "방금 연결됨",
+ "Last seen {when}": "마지막 연결 {when}",
+ "Not connected yet": "아직 연결되지 않음",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "iPhone에서 메모를 읽고 회의를 녹음하세요. 녹음은 이곳으로 돌아와 받아쓰기됩니다.",
+ "The code ran out. Start pairing again.": "코드가 만료되었습니다. 페어링을 다시 시작하세요.",
+ "Too many wrong codes. Start pairing again.": "잘못된 코드가 너무 많습니다. 페어링을 다시 시작하세요.",
+ "Unpair": "페어링 해제",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "iPhone 페어링을 해제할까요? 다시 페어링할 때까지 iPhone은 자신의 사본을 유지합니다.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt가 이 컴퓨터의 보안 저장소에 접근할 수 없어 지금은 페어링할 수 없습니다.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt가 페어링을 시작하지 못했습니다. 다시 시도하세요.",
+ "Yogurt on your iPhone": "iPhone의 Yogurt",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone은 같은 Wi-Fi에서만 이 컴퓨터와 통신합니다. 인터넷을 거치는 것은 없습니다.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone이 지금 이 컴퓨터에 연결할 수 없습니다. Yogurt를 다시 시작해 보세요.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone에서 이 컴퓨터가 보이지 않습니다. 시스템 설정 → 개인정보 보호 및 보안에서 Yogurt의 로컬 네트워크를 허용하세요.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone에서 이 컴퓨터가 보이지 않습니다. 방화벽에서 개인 네트워크에 대해 Yogurt를 허용하세요."
}
diff --git a/app/src/shared/locales/ms.json b/app/src/shared/locales/ms.json
index 1237eadc..2b098a0c 100644
--- a/app/src/shared/locales/ms.json
+++ b/app/src/shared/locales/ms.json
@@ -722,5 +722,25 @@
"Send feedback": "Hantar maklum balas",
"Help and settings": "Bantuan dan tetapan",
"Yogurt menu": "Menu Yogurt",
- "Restart to update · {version}": "Mulakan semula untuk mengemas kini · {version}"
+ "Restart to update · {version}": "Mulakan semula untuk mengemas kini · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Pasangkan telefon",
+ "Open Yogurt on your iPhone and type this code": "Buka Yogurt pada iPhone anda dan taip kod ini",
+ "Code works for {time}": "Kod sah {time} lagi",
+ "Connected": "Disambungkan",
+ "Last seen just now": "Dilihat sebentar tadi",
+ "Last seen {when}": "Terakhir dilihat {when}",
+ "Not connected yet": "Belum disambungkan",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Baca nota anda dan rakam mesyuarat pada iPhone. Semuanya kembali ke sini untuk ditranskripsikan.",
+ "The code ran out. Start pairing again.": "Kod telah tamat tempoh. Mulakan pemasangan semula.",
+ "Too many wrong codes. Start pairing again.": "Terlalu banyak kod salah. Mulakan pemasangan semula.",
+ "Unpair": "Nyahpasang",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Nyahpasang iPhone anda? Ia menyimpan salinannya sehingga anda memasangkannya semula.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt tidak dapat mencapai storan selamat komputer ini, jadi ia tidak boleh memasangkan sekarang.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt tidak dapat memulakan pemasangan. Cuba lagi.",
+ "Yogurt on your iPhone": "Yogurt pada iPhone anda",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone anda hanya bercakap dengan komputer ini pada Wi-Fi yang sama. Tiada apa-apa melalui internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone anda tidak dapat mencapai komputer ini sekarang. Cuba mulakan semula Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone anda tidak dapat melihat komputer ini. Benarkan Rangkaian Setempat untuk Yogurt dalam Seting Sistem → Privasi & Keselamatan.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone anda tidak dapat melihat komputer ini. Benarkan Yogurt melalui tembok api anda pada rangkaian peribadi."
}
diff --git a/app/src/shared/locales/nb.json b/app/src/shared/locales/nb.json
index 46524db4..e853040e 100644
--- a/app/src/shared/locales/nb.json
+++ b/app/src/shared/locales/nb.json
@@ -764,5 +764,25 @@
"Send feedback": "Send tilbakemelding",
"Help and settings": "Hjelp og innstillinger",
"Yogurt menu": "Yogurt-meny",
- "Restart to update · {version}": "Start på nytt for å oppdatere · {version}"
+ "Restart to update · {version}": "Start på nytt for å oppdatere · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Koble til en telefon",
+ "Open Yogurt on your iPhone and type this code": "Åpne Yogurt på iPhonen din og skriv inn denne koden",
+ "Code works for {time}": "Koden virker i {time} til",
+ "Connected": "Tilkoblet",
+ "Last seen just now": "Sett akkurat nå",
+ "Last seen {when}": "Sist sett {when}",
+ "Not connected yet": "Ikke tilkoblet ennå",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Les notatene dine og ta opp møter på iPhonen. De kommer tilbake hit for å bli transkribert.",
+ "The code ran out. Start pairing again.": "Koden gikk ut. Start tilkoblingen på nytt.",
+ "Too many wrong codes. Start pairing again.": "For mange feil koder. Start tilkoblingen på nytt.",
+ "Unpair": "Koble fra",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Koble fra iPhonen? Den beholder kopien sin til du kobler til igjen.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt fikk ikke tilgang til den sikre lagringen på denne datamaskinen, så den kan ikke koble til nå.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt fikk ikke startet tilkoblingen. Prøv igjen.",
+ "Yogurt on your iPhone": "Yogurt på iPhonen din",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhonen din snakker bare med denne datamaskinen på samme wifi. Ingenting går via internett.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhonen din når ikke denne datamaskinen akkurat nå. Prøv å starte Yogurt på nytt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhonen din ser ikke denne datamaskinen. Gi Yogurt tilgang til lokalt nettverk i Systeminnstillinger → Personvern og sikkerhet.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhonen din ser ikke denne datamaskinen. Slipp Yogurt gjennom brannmuren på private nettverk."
}
diff --git a/app/src/shared/locales/nl.json b/app/src/shared/locales/nl.json
index 96c347d9..bedcdb23 100644
--- a/app/src/shared/locales/nl.json
+++ b/app/src/shared/locales/nl.json
@@ -764,5 +764,25 @@
"Send feedback": "Feedback sturen",
"Help and settings": "Help en instellingen",
"Yogurt menu": "Yogurt-menu",
- "Restart to update · {version}": "Herstarten om bij te werken · {version}"
+ "Restart to update · {version}": "Herstarten om bij te werken · {version}",
+ "Phone": "Telefoon",
+ "Pair a phone": "Telefoon koppelen",
+ "Open Yogurt on your iPhone and type this code": "Open Yogurt op je iPhone en typ deze code",
+ "Code works for {time}": "Code werkt nog {time}",
+ "Connected": "Verbonden",
+ "Last seen just now": "Zojuist gezien",
+ "Last seen {when}": "Laatst gezien {when}",
+ "Not connected yet": "Nog niet verbonden",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Lees je notities en neem vergaderingen op met je iPhone. Ze komen hier terug om uitgeschreven te worden.",
+ "The code ran out. Start pairing again.": "De code is verlopen. Begin opnieuw met koppelen.",
+ "Too many wrong codes. Start pairing again.": "Te veel verkeerde codes. Begin opnieuw met koppelen.",
+ "Unpair": "Ontkoppelen",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Je iPhone ontkoppelen? Hij houdt zijn kopie tot je opnieuw koppelt.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt kon de beveiligde opslag van deze computer niet bereiken en kan nu dus niet koppelen.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt kon het koppelen niet starten. Probeer het opnieuw.",
+ "Yogurt on your iPhone": "Yogurt op je iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Je iPhone praat alleen via hetzelfde wifi-netwerk met deze computer. Er gaat niets via internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Je iPhone kan deze computer nu niet bereiken. Probeer Yogurt opnieuw te starten.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Je iPhone ziet deze computer niet. Sta het lokale netwerk toe voor Yogurt in Systeeminstellingen → Privacy en beveiliging.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Je iPhone ziet deze computer niet. Laat Yogurt door je firewall op privénetwerken."
}
diff --git a/app/src/shared/locales/pl.json b/app/src/shared/locales/pl.json
index 6da77838..f1267742 100644
--- a/app/src/shared/locales/pl.json
+++ b/app/src/shared/locales/pl.json
@@ -800,5 +800,25 @@
"Send feedback": "Wyślij opinię",
"Help and settings": "Pomoc i ustawienia",
"Yogurt menu": "Menu Yogurt",
- "Restart to update · {version}": "Uruchom ponownie, aby zaktualizować · {version}"
+ "Restart to update · {version}": "Uruchom ponownie, aby zaktualizować · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Sparuj telefon",
+ "Open Yogurt on your iPhone and type this code": "Otwórz Yogurt na iPhonie i wpisz ten kod",
+ "Code works for {time}": "Kod działa jeszcze {time}",
+ "Connected": "Połączono",
+ "Last seen just now": "Widziany przed chwilą",
+ "Last seen {when}": "Ostatnio widziany {when}",
+ "Not connected yet": "Jeszcze nie połączono",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Czytaj notatki i nagrywaj spotkania na iPhonie. Wracają tutaj do transkrypcji.",
+ "The code ran out. Start pairing again.": "Kod wygasł. Zacznij parowanie od nowa.",
+ "Too many wrong codes. Start pairing again.": "Za dużo błędnych kodów. Zacznij parowanie od nowa.",
+ "Unpair": "Rozłącz",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Rozłączyć iPhone’a? Zachowa swoją kopię, dopóki znów go nie sparujesz.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt nie mógł uzyskać dostępu do bezpiecznego magazynu tego komputera, więc teraz nie może parować.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt nie mógł rozpocząć parowania. Spróbuj ponownie.",
+ "Yogurt on your iPhone": "Yogurt na iPhonie",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Twój iPhone łączy się z tym komputerem tylko w tej samej sieci Wi-Fi. Nic nie przechodzi przez internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Twój iPhone nie może teraz połączyć się z tym komputerem. Spróbuj uruchomić Yogurt ponownie.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Twój iPhone nie widzi tego komputera. Zezwól Yogurtowi na sieć lokalną w Ustawieniach systemowych → Prywatność i ochrona.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Twój iPhone nie widzi tego komputera. Zezwól na Yogurt w zaporze sieciowej dla sieci prywatnych."
}
diff --git a/app/src/shared/locales/pt-BR.json b/app/src/shared/locales/pt-BR.json
index 751fe1e3..f3e4eba0 100644
--- a/app/src/shared/locales/pt-BR.json
+++ b/app/src/shared/locales/pt-BR.json
@@ -780,5 +780,25 @@
"Send feedback": "Enviar feedback",
"Help and settings": "Ajuda e configurações",
"Yogurt menu": "Menu do Yogurt",
- "Restart to update · {version}": "Reiniciar para atualizar · {version}"
+ "Restart to update · {version}": "Reiniciar para atualizar · {version}",
+ "Phone": "Celular",
+ "Pair a phone": "Parear um celular",
+ "Open Yogurt on your iPhone and type this code": "Abra o Yogurt no seu iPhone e digite este código",
+ "Code works for {time}": "O código vale por mais {time}",
+ "Connected": "Conectado",
+ "Last seen just now": "Visto agora mesmo",
+ "Last seen {when}": "Visto {when}",
+ "Not connected yet": "Ainda não conectado",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Leia suas notas e grave reuniões no seu iPhone. Elas voltam para cá para serem transcritas.",
+ "The code ran out. Start pairing again.": "O código expirou. Comece o pareamento de novo.",
+ "Too many wrong codes. Start pairing again.": "Códigos errados demais. Comece o pareamento de novo.",
+ "Unpair": "Desparear",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Desparear seu iPhone? Ele mantém a cópia dele até você parear de novo.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "O Yogurt não conseguiu acessar o armazenamento seguro deste computador, então não pode parear agora.",
+ "Yogurt couldn't start pairing. Try again.": "O Yogurt não conseguiu iniciar o pareamento. Tente de novo.",
+ "Yogurt on your iPhone": "Yogurt no seu iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Seu iPhone fala com este computador só na mesma rede Wi-Fi. Nada passa pela internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Seu iPhone não consegue falar com este computador agora. Tente reiniciar o Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Seu iPhone não vê este computador. Permita a Rede Local para o Yogurt em Ajustes do Sistema → Privacidade e Segurança.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Seu iPhone não vê este computador. Permita o Yogurt no seu firewall em redes privadas."
}
diff --git a/app/src/shared/locales/ro.json b/app/src/shared/locales/ro.json
index f71b32ff..a586d4ab 100644
--- a/app/src/shared/locales/ro.json
+++ b/app/src/shared/locales/ro.json
@@ -781,5 +781,25 @@
"Send feedback": "Trimite feedback",
"Help and settings": "Ajutor și setări",
"Yogurt menu": "Meniul Yogurt",
- "Restart to update · {version}": "Repornește pentru actualizare · {version}"
+ "Restart to update · {version}": "Repornește pentru actualizare · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Asociază un telefon",
+ "Open Yogurt on your iPhone and type this code": "Deschide Yogurt pe iPhone și introdu acest cod",
+ "Code works for {time}": "Codul mai e valabil {time}",
+ "Connected": "Conectat",
+ "Last seen just now": "Văzut chiar acum",
+ "Last seen {when}": "Văzut ultima dată {when}",
+ "Not connected yet": "Încă neconectat",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Citește-ți notițele și înregistrează întâlniri pe iPhone. Revin aici ca să fie transcrise.",
+ "The code ran out. Start pairing again.": "Codul a expirat. Începe din nou asocierea.",
+ "Too many wrong codes. Start pairing again.": "Prea multe coduri greșite. Începe din nou asocierea.",
+ "Unpair": "Disociază",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Disociezi iPhone-ul? Își păstrează copia până îl asociezi din nou.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt nu a putut accesa stocarea securizată a acestui computer, așa că nu poate asocia acum.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt nu a putut porni asocierea. Încearcă din nou.",
+ "Yogurt on your iPhone": "Yogurt pe iPhone-ul tău",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone-ul tău vorbește cu acest computer doar în aceeași rețea Wi-Fi. Nimic nu trece prin internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone-ul tău nu poate ajunge acum la acest computer. Încearcă să repornești Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone-ul tău nu vede acest computer. Permite rețeaua locală pentru Yogurt în Configurări sistem → Confidențialitate și securitate.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone-ul tău nu vede acest computer. Permite Yogurt în firewall pentru rețelele private."
}
diff --git a/app/src/shared/locales/ru.json b/app/src/shared/locales/ru.json
index 5d4ec7cc..b3c63c73 100644
--- a/app/src/shared/locales/ru.json
+++ b/app/src/shared/locales/ru.json
@@ -792,5 +792,25 @@
"Send feedback": "Отправить отзыв",
"Help and settings": "Справка и настройки",
"Yogurt menu": "Меню Yogurt",
- "Restart to update · {version}": "Перезапустить для обновления · {version}"
+ "Restart to update · {version}": "Перезапустить для обновления · {version}",
+ "Phone": "Телефон",
+ "Pair a phone": "Подключить телефон",
+ "Open Yogurt on your iPhone and type this code": "Откройте Yogurt на iPhone и введите этот код",
+ "Code works for {time}": "Код действует ещё {time}",
+ "Connected": "Подключён",
+ "Last seen just now": "Был в сети только что",
+ "Last seen {when}": "Был в сети {when}",
+ "Not connected yet": "Ещё не подключался",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Читайте заметки и записывайте встречи на iPhone. Записи возвращаются сюда для расшифровки.",
+ "The code ran out. Start pairing again.": "Срок действия кода истёк. Начните подключение заново.",
+ "Too many wrong codes. Start pairing again.": "Слишком много неверных кодов. Начните подключение заново.",
+ "Unpair": "Отключить",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Отключить iPhone? Его копия сохранится, пока вы не подключите его снова.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt не смог обратиться к защищённому хранилищу этого компьютера, поэтому сейчас не может подключить телефон.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt не смог начать подключение. Попробуйте ещё раз.",
+ "Yogurt on your iPhone": "Yogurt на вашем iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone связывается с этим компьютером только в одной сети Wi-Fi. Ничего не идёт через интернет.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone сейчас не может связаться с этим компьютером. Попробуйте перезапустить Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone не видит этот компьютер. Разрешите Yogurt доступ к локальной сети в Системных настройках → Конфиденциальность и безопасность.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone не видит этот компьютер. Разрешите Yogurt в брандмауэре для частных сетей."
}
diff --git a/app/src/shared/locales/sv.json b/app/src/shared/locales/sv.json
index c37ac724..057a91fa 100644
--- a/app/src/shared/locales/sv.json
+++ b/app/src/shared/locales/sv.json
@@ -764,5 +764,25 @@
"Send feedback": "Skicka feedback",
"Help and settings": "Hjälp och inställningar",
"Yogurt menu": "Yogurt-menyn",
- "Restart to update · {version}": "Starta om för att uppdatera · {version}"
+ "Restart to update · {version}": "Starta om för att uppdatera · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Parkoppla en telefon",
+ "Open Yogurt on your iPhone and type this code": "Öppna Yogurt på din iPhone och skriv den här koden",
+ "Code works for {time}": "Koden gäller i {time} till",
+ "Connected": "Ansluten",
+ "Last seen just now": "Sågs nyss",
+ "Last seen {when}": "Sågs senast {when}",
+ "Not connected yet": "Inte ansluten än",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Läs dina anteckningar och spela in möten på din iPhone. De kommer tillbaka hit för att transkriberas.",
+ "The code ran out. Start pairing again.": "Koden gick ut. Börja parkopplingen igen.",
+ "Too many wrong codes. Start pairing again.": "För många fel koder. Börja parkopplingen igen.",
+ "Unpair": "Koppla från",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Koppla från din iPhone? Den behåller sin kopia tills du parkopplar igen.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt kom inte åt datorns säkra lagring, så den kan inte parkoppla just nu.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt kunde inte starta parkopplingen. Försök igen.",
+ "Yogurt on your iPhone": "Yogurt på din iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "Din iPhone pratar bara med den här datorn på samma wifi. Inget går via internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "Din iPhone når inte den här datorn just nu. Testa att starta om Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "Din iPhone ser inte den här datorn. Tillåt lokalt nätverk för Yogurt i Systeminställningar → Integritet och säkerhet.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "Din iPhone ser inte den här datorn. Släpp igenom Yogurt i brandväggen på privata nätverk."
}
diff --git a/app/src/shared/locales/th.json b/app/src/shared/locales/th.json
index 32e8cd47..15f2cdfe 100644
--- a/app/src/shared/locales/th.json
+++ b/app/src/shared/locales/th.json
@@ -722,5 +722,25 @@
"Send feedback": "ส่งความคิดเห็น",
"Help and settings": "ความช่วยเหลือและการตั้งค่า",
"Yogurt menu": "เมนู Yogurt",
- "Restart to update · {version}": "เริ่มใหม่เพื่ออัปเดต · {version}"
+ "Restart to update · {version}": "เริ่มใหม่เพื่ออัปเดต · {version}",
+ "Phone": "โทรศัพท์",
+ "Pair a phone": "จับคู่โทรศัพท์",
+ "Open Yogurt on your iPhone and type this code": "เปิด Yogurt บน iPhone แล้วพิมพ์รหัสนี้",
+ "Code works for {time}": "รหัสใช้ได้อีก {time}",
+ "Connected": "เชื่อมต่อแล้ว",
+ "Last seen just now": "เห็นล่าสุดเมื่อสักครู่",
+ "Last seen {when}": "เห็นล่าสุด {when}",
+ "Not connected yet": "ยังไม่ได้เชื่อมต่อ",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "อ่านโน้ตและบันทึกการประชุมบน iPhone แล้วจะกลับมาที่นี่เพื่อถอดเสียง",
+ "The code ran out. Start pairing again.": "รหัสหมดอายุแล้ว เริ่มจับคู่ใหม่อีกครั้ง",
+ "Too many wrong codes. Start pairing again.": "ใส่รหัสผิดหลายครั้งเกินไป เริ่มจับคู่ใหม่อีกครั้ง",
+ "Unpair": "เลิกจับคู่",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "เลิกจับคู่ iPhone ใช่ไหม iPhone จะเก็บสำเนาไว้จนกว่าคุณจะจับคู่อีกครั้ง",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt เข้าถึงพื้นที่จัดเก็บที่ปลอดภัยของคอมพิวเตอร์เครื่องนี้ไม่ได้ จึงจับคู่ไม่ได้ในตอนนี้",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt เริ่มจับคู่ไม่ได้ ลองอีกครั้ง",
+ "Yogurt on your iPhone": "Yogurt บน iPhone ของคุณ",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone จะคุยกับคอมพิวเตอร์เครื่องนี้ผ่าน Wi-Fi เดียวกันเท่านั้น ไม่มีอะไรผ่านอินเทอร์เน็ต",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone ของคุณเชื่อมต่อกับคอมพิวเตอร์เครื่องนี้ไม่ได้ในตอนนี้ ลองเปิด Yogurt ใหม่",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone ของคุณมองไม่เห็นคอมพิวเตอร์เครื่องนี้ อนุญาตเครือข่ายเฉพาะที่ให้ Yogurt ในการตั้งค่าระบบ → ความเป็นส่วนตัวและความปลอดภัย",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone ของคุณมองไม่เห็นคอมพิวเตอร์เครื่องนี้ อนุญาตให้ Yogurt ผ่านไฟร์วอลล์ของคุณบนเครือข่ายส่วนตัว"
}
diff --git a/app/src/shared/locales/tr.json b/app/src/shared/locales/tr.json
index 3329d986..a8f7c1bb 100644
--- a/app/src/shared/locales/tr.json
+++ b/app/src/shared/locales/tr.json
@@ -752,5 +752,25 @@
"Send feedback": "Geri bildirim gönder",
"Help and settings": "Yardım ve ayarlar",
"Yogurt menu": "Yogurt menüsü",
- "Restart to update · {version}": "Güncellemek için yeniden başlat · {version}"
+ "Restart to update · {version}": "Güncellemek için yeniden başlat · {version}",
+ "Phone": "Telefon",
+ "Pair a phone": "Telefon eşle",
+ "Open Yogurt on your iPhone and type this code": "iPhone’unda Yogurt’u aç ve bu kodu yaz",
+ "Code works for {time}": "Kod {time} daha geçerli",
+ "Connected": "Bağlı",
+ "Last seen just now": "Az önce görüldü",
+ "Last seen {when}": "Son görülme {when}",
+ "Not connected yet": "Henüz bağlanmadı",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Notlarını oku ve toplantıları iPhone’unda kaydet. Metne dökülmek için buraya geri gelirler.",
+ "The code ran out. Start pairing again.": "Kodun süresi doldu. Eşlemeyi yeniden başlat.",
+ "Too many wrong codes. Start pairing again.": "Çok fazla yanlış kod. Eşlemeyi yeniden başlat.",
+ "Unpair": "Eşlemeyi kaldır",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "iPhone’unun eşlemesi kaldırılsın mı? Yeniden eşleyene kadar kendi kopyasını saklar.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt bu bilgisayarın güvenli depolamasına ulaşamadı, bu yüzden şu anda eşleme yapamıyor.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt eşlemeyi başlatamadı. Yeniden dene.",
+ "Yogurt on your iPhone": "iPhone’unda Yogurt",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone’un bu bilgisayarla yalnızca aynı Wi-Fi ağında konuşur. Hiçbir şey internetten geçmez.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone’un şu anda bu bilgisayara ulaşamıyor. Yogurt’u yeniden başlatmayı dene.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone’un bu bilgisayarı göremiyor. Sistem Ayarları → Gizlilik ve Güvenlik’te Yogurt için Yerel Ağ’a izin ver.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone’un bu bilgisayarı göremiyor. Güvenlik duvarında özel ağlar için Yogurt’a izin ver."
}
diff --git a/app/src/shared/locales/uk.json b/app/src/shared/locales/uk.json
index 7cd8f653..51365fdc 100644
--- a/app/src/shared/locales/uk.json
+++ b/app/src/shared/locales/uk.json
@@ -792,5 +792,25 @@
"Send feedback": "Надіслати відгук",
"Help and settings": "Довідка й налаштування",
"Yogurt menu": "Меню Yogurt",
- "Restart to update · {version}": "Перезапустити для оновлення · {version}"
+ "Restart to update · {version}": "Перезапустити для оновлення · {version}",
+ "Phone": "Телефон",
+ "Pair a phone": "Під’єднати телефон",
+ "Open Yogurt on your iPhone and type this code": "Відкрийте Yogurt на iPhone і введіть цей код",
+ "Code works for {time}": "Код діє ще {time}",
+ "Connected": "Під’єднано",
+ "Last seen just now": "Був у мережі щойно",
+ "Last seen {when}": "Був у мережі {when}",
+ "Not connected yet": "Ще не під’єднувався",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Читайте нотатки й записуйте зустрічі на iPhone. Записи повертаються сюди для розшифрування.",
+ "The code ran out. Start pairing again.": "Термін дії коду минув. Почніть під’єднання знову.",
+ "Too many wrong codes. Start pairing again.": "Забагато неправильних кодів. Почніть під’єднання знову.",
+ "Unpair": "Від’єднати",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Від’єднати iPhone? Його копія залишиться, доки ви не під’єднаєте його знову.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt не зміг звернутися до захищеного сховища цього комп’ютера, тож зараз не може під’єднати телефон.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt не зміг почати під’єднання. Спробуйте ще раз.",
+ "Yogurt on your iPhone": "Yogurt на вашому iPhone",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone спілкується з цим комп’ютером лише в тій самій мережі Wi-Fi. Нічого не йде через інтернет.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone зараз не може зв’язатися з цим комп’ютером. Спробуйте перезапустити Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone не бачить цей комп’ютер. Дозвольте Yogurt доступ до локальної мережі в Системних параметрах → Приватність і безпека.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone не бачить цей комп’ютер. Дозвольте Yogurt у брандмауері для приватних мереж."
}
diff --git a/app/src/shared/locales/vi.json b/app/src/shared/locales/vi.json
index 5ced0509..b4505812 100644
--- a/app/src/shared/locales/vi.json
+++ b/app/src/shared/locales/vi.json
@@ -722,5 +722,25 @@
"Send feedback": "Gửi ý kiến phản hồi",
"Help and settings": "Trợ giúp và cài đặt",
"Yogurt menu": "Menu Yogurt",
- "Restart to update · {version}": "Khởi động lại để cập nhật · {version}"
+ "Restart to update · {version}": "Khởi động lại để cập nhật · {version}",
+ "Phone": "Điện thoại",
+ "Pair a phone": "Ghép nối điện thoại",
+ "Open Yogurt on your iPhone and type this code": "Mở Yogurt trên iPhone và nhập mã này",
+ "Code works for {time}": "Mã còn hiệu lực {time}",
+ "Connected": "Đã kết nối",
+ "Last seen just now": "Vừa thấy",
+ "Last seen {when}": "Thấy lần cuối {when}",
+ "Not connected yet": "Chưa kết nối",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "Đọc ghi chú và ghi âm cuộc họp trên iPhone. Chúng quay về đây để được chép lời.",
+ "The code ran out. Start pairing again.": "Mã đã hết hạn. Hãy bắt đầu ghép nối lại.",
+ "Too many wrong codes. Start pairing again.": "Quá nhiều mã sai. Hãy bắt đầu ghép nối lại.",
+ "Unpair": "Hủy ghép nối",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "Hủy ghép nối iPhone? iPhone vẫn giữ bản sao của nó cho đến khi bạn ghép nối lại.",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt không truy cập được bộ lưu trữ an toàn của máy tính này nên chưa thể ghép nối lúc này.",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt không bắt đầu ghép nối được. Hãy thử lại.",
+ "Yogurt on your iPhone": "Yogurt trên iPhone của bạn",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "iPhone chỉ trò chuyện với máy tính này trên cùng mạng Wi-Fi. Không có gì đi qua internet.",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "iPhone hiện không kết nối được với máy tính này. Hãy thử khởi động lại Yogurt.",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "iPhone không thấy máy tính này. Hãy cho phép Mạng cục bộ cho Yogurt trong Cài đặt hệ thống → Quyền riêng tư & Bảo mật.",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "iPhone không thấy máy tính này. Hãy cho phép Yogurt qua tường lửa trên mạng riêng."
}
diff --git a/app/src/shared/locales/zh-CN.json b/app/src/shared/locales/zh-CN.json
index 317f9ff5..2182fc51 100644
--- a/app/src/shared/locales/zh-CN.json
+++ b/app/src/shared/locales/zh-CN.json
@@ -722,5 +722,25 @@
"Send feedback": "发送反馈",
"Help and settings": "帮助和设置",
"Yogurt menu": "Yogurt 菜单",
- "Restart to update · {version}": "重启以更新 · {version}"
+ "Restart to update · {version}": "重启以更新 · {version}",
+ "Phone": "手机",
+ "Pair a phone": "配对手机",
+ "Open Yogurt on your iPhone and type this code": "在 iPhone 上打开 Yogurt 并输入此代码",
+ "Code works for {time}": "代码还可用 {time}",
+ "Connected": "已连接",
+ "Last seen just now": "刚刚在线",
+ "Last seen {when}": "上次在线 {when}",
+ "Not connected yet": "尚未连接",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "在 iPhone 上阅读笔记、录制会议。录音会回到这里进行转写。",
+ "The code ran out. Start pairing again.": "代码已过期。请重新开始配对。",
+ "Too many wrong codes. Start pairing again.": "错误代码太多。请重新开始配对。",
+ "Unpair": "取消配对",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "要取消与 iPhone 的配对吗?在你再次配对之前,它会保留自己的副本。",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt 无法访问这台电脑的安全存储,因此现在无法配对。",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt 无法开始配对。请重试。",
+ "Yogurt on your iPhone": "iPhone 上的 Yogurt",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "你的 iPhone 只在同一 Wi-Fi 下与这台电脑通信。任何内容都不经过互联网。",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "你的 iPhone 现在无法连接这台电脑。请尝试重新启动 Yogurt。",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "你的 iPhone 看不到这台电脑。请在“系统设置”→“隐私与安全性”中允许 Yogurt 使用本地网络。",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "你的 iPhone 看不到这台电脑。请在防火墙中允许 Yogurt 在专用网络上通信。"
}
diff --git a/app/src/shared/locales/zh-TW.json b/app/src/shared/locales/zh-TW.json
index 6c5f37d3..024f0c22 100644
--- a/app/src/shared/locales/zh-TW.json
+++ b/app/src/shared/locales/zh-TW.json
@@ -722,5 +722,25 @@
"Send feedback": "傳送意見回饋",
"Help and settings": "說明與設定",
"Yogurt menu": "Yogurt 選單",
- "Restart to update · {version}": "重新啟動以更新 · {version}"
+ "Restart to update · {version}": "重新啟動以更新 · {version}",
+ "Phone": "手機",
+ "Pair a phone": "配對手機",
+ "Open Yogurt on your iPhone and type this code": "在 iPhone 上打開 Yogurt 並輸入此代碼",
+ "Code works for {time}": "代碼還可用 {time}",
+ "Connected": "已連線",
+ "Last seen just now": "剛剛在線",
+ "Last seen {when}": "上次在線 {when}",
+ "Not connected yet": "尚未連線",
+ "Read your notes and record meetings on your iPhone. They come back here to be transcribed.": "在 iPhone 上閱讀筆記、錄製會議。錄音會回到這裡進行轉寫。",
+ "The code ran out. Start pairing again.": "代碼已過期。請重新開始配對。",
+ "Too many wrong codes. Start pairing again.": "錯誤代碼太多。請重新開始配對。",
+ "Unpair": "取消配對",
+ "Unpair your iPhone? It keeps its copy until you pair again.": "要取消與 iPhone 的配對嗎?在你再次配對之前,它會保留自己的副本。",
+ "Yogurt couldn't reach this computer's secure storage, so it can't pair right now.": "Yogurt 無法存取這台電腦的安全儲存空間,因此現在無法配對。",
+ "Yogurt couldn't start pairing. Try again.": "Yogurt 無法開始配對。請再試一次。",
+ "Yogurt on your iPhone": "iPhone 上的 Yogurt",
+ "Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.": "你的 iPhone 只在同一 Wi-Fi 下與這台電腦通訊。任何內容都不經過網際網路。",
+ "Your iPhone can't reach this computer right now. Try restarting Yogurt.": "你的 iPhone 現在無法連線這台電腦。請試著重新啟動 Yogurt。",
+ "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security.": "你的 iPhone 看不到這台電腦。請在「系統設定」→「隱私權與安全性」中允許 Yogurt 使用本地網路。",
+ "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks.": "你的 iPhone 看不到這台電腦。請在防火牆中允許 Yogurt 在私人網路上通訊。"
}
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts
index 765a3a2b..bfbbef23 100644
--- a/app/src/shared/types.ts
+++ b/app/src/shared/types.ts
@@ -1,3 +1,4 @@
+import type { CompanionStatus } from './companion'
import type { MeterPacket } from './speechWave'
import type { AudioUploadFile, AudioUploadStatus } from './audioUpload'
import type { RendererError } from './rendererError'
@@ -37,6 +38,8 @@ export type YogurtApi = {
capabilities: Capabilities
/** test mode: stand-ins for models, audio and calendars */
fake: boolean
+ /** the iPhone companion is turned on (shared/companion.ts PHONE_COMPANION, or YOGURT_PHONE=1); Settings → Phone shows only then */
+ phone: boolean
setup: {
state(): Promise<SetupState>
/** called with each change; returns the way to stop listening */
@@ -167,6 +170,15 @@ export type YogurtApi = {
setChanges(on: boolean): Promise<McpStatus>
onClients(fn: (clients: string[]) => void): () => void
}
+ /** Settings → Phone: pairing the iPhone app with this computer over the local network; null when it isn't running */
+ companion: {
+ status(): Promise<CompanionStatus | null>
+ /** ok: false when it couldn't (the status says why when it knows: keychain, listen) */
+ startPairing(): Promise<{ ok: boolean; status: CompanionStatus | null }>
+ cancelPairing(): Promise<CompanionStatus | null>
+ unpair(): Promise<CompanionStatus | null>
+ onStatus(fn: (s: CompanionStatus) => void): () => void
+ }
updates: {
status(): Promise<UpdateStatus>
set(on: boolean): Promise<UpdateStatus>
@@ -402,6 +414,8 @@ export type NoteView = {
peopleChanged: boolean
/** the notes were just written again (for new people): what they replaced, so an open editor with no edits since takes them */
rewrittenFrom?: string
+ /** My notes were just changed from the iPhone: what they replaced, so an open editor with no edits since takes them */
+ mineFrom?: string
/** latest acknowledged edit revision on each side; failed text is retained in main and overlaid above */
saves?: Partial<Record<NoteSide, NoteSaveResult>>
}
diff --git a/app/test/backup.test.ts b/app/test/backup.test.ts
index 0aea0a12..10e3681e 100644
--- a/app/test/backup.test.ts
+++ b/app/test/backup.test.ts
@@ -150,7 +150,8 @@ describe('backup merge', () => {
expect(meetingTables(s.db).map((t) => t.table).sort()).toEqual(['chat_turns', 'folder_meetings', 'library_chunks', 'library_sources', 'notes', 'segments', 'transcription_drafts'])
// a new table that is not tied to a meeting would be left out of backups: decide what a backup does with it, then list it here
const all = (s.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '%_fts%'").all() as Array<{ name: string }>).map((r) => r.name)
- expect(all.filter((t) => t !== 'meetings' && !meetingTables(s.db).some((m) => m.table === t)).sort()).toEqual(['conversation_turns', 'conversations', 'folders', 'own_emails', 'people'])
+ expect(all.filter((t) => t !== 'meetings' && !meetingTables(s.db).some((m) => m.table === t)).sort()).toEqual(['companion_changes', 'companion_devices', 'companion_meta', 'conversation_turns', 'conversations', 'folders', 'own_emails', 'people'])
+ // The companion's tables are this Mac's own (its paired phone, what that phone has fetched): never carried.
// Own addresses merge by email, like the people records. The remaining tables are carried on their own: a conversation and every turn of it, and folders (test/folders.test.ts)
expect(carriedTables(s.db)).toEqual([{ table: 'conversations', column: 'id' }, { table: 'conversation_turns', column: 'conversation_id' }, { table: 'folders', column: 'id' }])
})
@@ -200,6 +201,21 @@ describe('backup file', { timeout: 20_000 }, () => {
expect(await importBackup({ db: s.db, meetingsDir: tmp(), zip: '/unreadable.zip' })).toEqual({ ok: false, error: 'failed' })
})
+ it('leaves the paired phone and the companion change log out of an export: pairing belongs to this Mac', async () => {
+ const s = fresh(), out = join(tmp(), 'backup.zip')
+ const m = fill(s, 'Paired', 'paired')
+ s.trashMeeting(fill(s, 'Binned', 'binned').id)
+ s.db.prepare('INSERT INTO companion_devices (id, name, public_key, paired_at) VALUES (?, ?, ?, ?)').run('phone-1', 'Test iPhone', 'cHVibGlj', 1)
+ await exportBackup({ db: s.db, meetingsDir: tmp(), out, appVersion: '1' })
+ const look = tmp()
+ await unpack(out, look)
+ const db = new DatabaseSync(join(look, 'yogurt.db'))
+ const names = (db.prepare("SELECT name FROM sqlite_master WHERE name LIKE 'companion_%'").all() as Array<{ name: string }>).map((r) => r.name)
+ expect(names).toEqual([])
+ expect(db.prepare('SELECT id FROM meetings').all().map((r) => r.id)).toEqual([m.id])
+ db.close()
+ })
+
it('keeps the successful export result when cleaning its staging directory fails', async () => {
const s = fresh(), out = join(tmp(), 'backup.zip')
fill(s, 'Saved', 'saved')
diff --git a/app/test/companionCpace.test.ts b/app/test/companionCpace.test.ts
new file mode 100644
index 00000000..4beb86d1
--- /dev/null
+++ b/app/test/companionCpace.test.ts
@@ -0,0 +1,119 @@
+import { beforeAll, describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { ready } from '../src/main/companion/sodium'
+import { cpaceFinish, cpaceGenerator, cpaceRespond, cpaceStart, generatorString, lvCat, pairKeys } from '../src/main/companion/cpace'
+import { openBox, sealBox } from '../src/main/companion/box'
+
+const fixtures = JSON.parse(readFileSync(join(__dirname, '../../ios/Fixtures/cpace-ristretto255-vectors.json'), 'utf8'))
+const hex = (s: string) => Uint8Array.from(Buffer.from(s, 'hex'))
+const toHex = (b: Uint8Array) => Buffer.from(b).toString('hex')
+const utf8 = (s: string) => new TextEncoder().encode(s)
+const random = (n: number) => crypto.getRandomValues(new Uint8Array(n))
+
+beforeAll(() => ready())
+
+describe('CPace ristretto255 / SHA-512', () => {
+ it('lv_cat matches the draft', () => {
+ expect(toHex(lvCat(utf8('1234'), utf8('5'), new Uint8Array(0), utf8('678')))).toBe('043132333401350003363738')
+ expect(toHex(lvCat(new Uint8Array(128))).slice(0, 4)).toBe('8001')
+ })
+
+ for (const v of fixtures.vectors) {
+ const prs = Buffer.from(v.PRS, 'hex').toString('utf8')
+ it(`${v.name}: generator`, () => {
+ expect(toHex(generatorString(prs, hex(v.CI), hex(v.sid)))).toBe(v.generatorString)
+ expect(toHex(cpaceGenerator(prs, hex(v.CI), hex(v.sid)))).toBe(v.g)
+ })
+
+ it(`${v.name}: Ya, Yb and the initiator/responder ISK`, () => {
+ const a = cpaceStart(prs, hex(v.CI), hex(v.sid), hex(v.ADa), hex(v.ya))
+ expect(toHex(a.ya)).toBe(v.Ya)
+ const b = cpaceRespond(prs, hex(v.CI), hex(v.sid), a.ya, hex(v.ADa), hex(v.ADb), hex(v.yb))
+ expect(toHex(b.yb)).toBe(v.Yb)
+ expect(toHex(b.isk)).toBe(v.ISK_IR)
+ expect(toHex(cpaceFinish(a.secret, b.yb, hex(v.ADb)))).toBe(v.ISK_IR)
+ })
+ }
+
+ it('random runs agree, and a wrong code gives a different key', () => {
+ const ci = utf8('yogurt-pair-v1'), sid = random(16)
+ const a = cpaceStart('123456', ci, sid)
+ const b = cpaceRespond('123456', ci, sid, a.ya)
+ const isk = cpaceFinish(a.secret, b.yb)
+ expect(isk.length).toBe(64)
+ expect(toHex(isk)).toBe(toHex(b.isk))
+
+ const a2 = cpaceStart('123456', ci, sid)
+ const wrong = cpaceRespond('123457', ci, sid, a2.ya)
+ expect(toHex(cpaceFinish(a2.secret, wrong.yb))).not.toBe(toHex(wrong.isk))
+ })
+
+ it('a different channel id or session id gives a different key', () => {
+ const sid = random(16)
+ const a = cpaceStart('123456', utf8('yogurt-pair-v1A'), sid)
+ const b = cpaceRespond('123456', utf8('yogurt-pair-v1B'), sid, a.ya)
+ expect(toHex(cpaceFinish(a.secret, b.yb))).not.toBe(toHex(b.isk))
+ const c = cpaceStart('123456', utf8('ci'), sid)
+ const d = cpaceRespond('123456', utf8('ci'), random(16), c.ya)
+ expect(toHex(cpaceFinish(c.secret, d.yb))).not.toBe(toHex(d.isk))
+ })
+
+ it('rejects the identity and invalid encodings from either side', () => {
+ const ci = utf8('ci'), sid = random(16)
+ for (const bad of fixtures.invalidPoints) {
+ expect(() => cpaceRespond('123456', ci, sid, hex(bad))).toThrow()
+ const a = cpaceStart('123456', ci, sid)
+ expect(() => cpaceFinish(a.secret, hex(bad))).toThrow()
+ }
+ expect(() => cpaceFinish(cpaceStart('1', ci, sid).secret, new Uint8Array(31))).toThrow()
+ })
+
+ it('wipes the scalar when cpaceStart fails', () => {
+ const scalar = new Uint8Array(31).fill(7)
+ expect(() => cpaceStart('1', utf8('ci'), random(16), undefined, scalar)).toThrow()
+ expect(scalar.every((x) => x === 0)).toBe(true)
+ })
+
+ it('a used secret cannot give a second key', () => {
+ const ci = utf8('ci'), sid = random(16)
+ const a = cpaceStart('123456', ci, sid)
+ const b = cpaceRespond('123456', ci, sid, a.ya)
+ cpaceFinish(a.secret, b.yb)
+ expect(() => cpaceFinish(a.secret, b.yb)).toThrow()
+ })
+
+ it('samples scalars below 2^252', () => {
+ for (let i = 0; i < 20; i++) expect(cpaceStart('1', utf8('ci'), random(16)).secret.scalar[31]).toBeLessThan(0x10)
+ })
+})
+
+describe('pairing keys and boxes', () => {
+ it('derives three different 32-byte keys, the same on both sides', () => {
+ const isk = random(64)
+ const k = pairKeys(isk)
+ for (const key of [k.toPhone, k.toDesktop, k.confirm]) expect(key.length).toBe(32)
+ expect(new Set([k.toPhone, k.toDesktop, k.confirm].map(toHex)).size).toBe(3)
+ expect(toHex(pairKeys(isk.slice()).toPhone)).toBe(toHex(k.toPhone))
+ expect(toHex(pairKeys(random(64)).toPhone)).not.toBe(toHex(k.toPhone))
+ })
+
+ it('matches HKDF-SHA-512 with an empty salt (what the phone computes)', async () => {
+ const { hkdfSync } = await import('node:crypto')
+ const isk = random(64)
+ expect(toHex(pairKeys(isk).toDesktop)).toBe(Buffer.from(hkdfSync('sha512', isk, new Uint8Array(0), 'yogurt pair to-desktop', 32)).toString('hex'))
+ })
+
+ it('seals and opens; a changed byte, key or associated data fails', () => {
+ const key = random(32), ad = utf8('pairConfirm')
+ const box = sealBox(key, utf8('hello'), ad)
+ expect(box.length).toBe(24 + 5 + 16)
+ expect(new TextDecoder().decode(openBox(key, box, ad))).toBe('hello')
+ const tampered = box.slice(); tampered[30] ^= 1
+ expect(() => openBox(key, tampered, ad)).toThrow()
+ expect(() => openBox(random(32), box, ad)).toThrow()
+ expect(() => openBox(key, box, utf8('pairDone'))).toThrow()
+ expect(() => openBox(key, box.slice(0, 20), ad)).toThrow()
+ expect(toHex(sealBox(key, utf8('hello'), ad))).not.toBe(toHex(box))
+ })
+})
diff --git a/app/test/companionIpc.test.ts b/app/test/companionIpc.test.ts
new file mode 100644
index 00000000..9294830c
--- /dev/null
+++ b/app/test/companionIpc.test.ts
@@ -0,0 +1,72 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { hookCompanion } from '../src/main/companion/ipc'
+import type { CompanionStatus } from '../src/shared/companion'
+
+const handlers = new Map<string, (...args: unknown[]) => unknown>()
+vi.mock('electron', () => ({
+ ipcMain: { handle: (channel: string, handler: (...args: unknown[]) => unknown) => handlers.set(channel, handler) },
+}))
+
+const idle: CompanionStatus = { paired: null, pairing: null, pairingClosed: null, error: null, connected: false, syncing: false }
+
+function fake(o: { start?: () => Promise<{ code: string; expiresAt: number }> } = {}) {
+ let status = idle
+ const listeners = new Set<(s: CompanionStatus) => void>()
+ return {
+ set: (s: CompanionStatus) => { status = s; for (const l of listeners) l(s) },
+ c: {
+ status: () => status,
+ onStatus: (cb: (s: CompanionStatus) => void) => { listeners.add(cb); return () => { listeners.delete(cb) } },
+ startPairing: vi.fn(o.start ?? (async () => ({ code: '123456', expiresAt: 1 }))),
+ cancelPairing: vi.fn(async () => {}),
+ unpair: vi.fn(async () => {}),
+ },
+ }
+}
+
+const call = (channel: string) => handlers.get(channel)!({})
+
+beforeEach(() => handlers.clear())
+
+describe('companion IPC', () => {
+ it('waits for the companion, answers its status and pushes changes to the window', async () => {
+ const f = fake()
+ const sent: CompanionStatus[] = []
+ let ready!: (c: typeof f.c) => void
+ hookCompanion({ companion: new Promise((r) => { ready = r }), send: (s) => sent.push(s) })
+ const pending = call('companion:status')
+ ready(f.c)
+ expect(await pending).toEqual(idle)
+ const paired = { ...idle, paired: { name: 'Test iPhone', lastSeen: null } }
+ f.set(paired)
+ expect(sent.at(-1)).toEqual(paired)
+ })
+
+ it('has no status when the companion did not start (fake mode, or it failed)', async () => {
+ hookCompanion({ companion: Promise.resolve(undefined), send: () => {} })
+ expect(await call('companion:status')).toBeNull()
+ expect(await call('companion:start-pairing')).toEqual({ ok: false, status: null })
+ })
+
+ it('starts pairing and says when it could not, with the status explaining why', async () => {
+ const f = fake()
+ hookCompanion({ companion: Promise.resolve(f.c), send: () => {} })
+ expect(await call('companion:start-pairing')).toEqual({ ok: true, status: idle })
+ f.c.startPairing.mockImplementationOnce(async () => { f.set({ ...idle, error: 'listen' }); throw new Error('listen') })
+ expect(await call('companion:start-pairing')).toEqual({ ok: false, status: { ...idle, error: 'listen' } })
+ })
+
+ it('cancels and unpairs, answering the new status', async () => {
+ const f = fake()
+ hookCompanion({ companion: Promise.resolve(f.c), send: () => {} })
+ expect(await call('companion:cancel-pairing')).toEqual(idle)
+ expect(f.c.cancelPairing).toHaveBeenCalledOnce()
+ expect(await call('companion:unpair')).toEqual(idle)
+ expect(f.c.unpair).toHaveBeenCalledOnce()
+ // a failure answers the status as it is, rather than an error the window can't place
+ f.c.unpair.mockRejectedValueOnce(new Error('disk'))
+ expect(await call('companion:unpair')).toEqual(idle)
+ f.c.cancelPairing.mockRejectedValueOnce(new Error('disk'))
+ expect(await call('companion:cancel-pairing')).toEqual(idle)
+ })
+})
diff --git a/app/test/companionNoise.test.ts b/app/test/companionNoise.test.ts
new file mode 100644
index 00000000..b256d783
--- /dev/null
+++ b/app/test/companionNoise.test.ts
@@ -0,0 +1,217 @@
+import { beforeAll, describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { ready } from '../src/main/companion/sodium'
+import { CipherState, NoiseKK, generateKeyPair, keyPairFromPrivate } from '../src/main/companion/noise'
+
+const fixtures = JSON.parse(readFileSync(join(__dirname, '../../ios/Fixtures/noise-kk-vectors.json'), 'utf8'))
+const lowOrder: string[] = JSON.parse(readFileSync(join(__dirname, '../../ios/Fixtures/noise-low-order-points.json'), 'utf8')).points
+const hex = (s: string) => Uint8Array.from(Buffer.from(s, 'hex'))
+const toHex = (b: Uint8Array) => Buffer.from(b).toString('hex')
+const utf8 = (s: string) => new TextEncoder().encode(s)
+const prologue = utf8('yogurt-v1')
+
+beforeAll(() => ready())
+
+function handshake() {
+ const { i, r } = pair()
+ r.readMessage(i.writeMessage(new Uint8Array(0)))
+ i.readMessage(r.writeMessage(new Uint8Array(0)))
+ return { i, r }
+}
+
+function pair() {
+ const a = generateKeyPair(), b = generateKeyPair()
+ const i = new NoiseKK({ initiator: true, s: a, rs: b.publicKey, prologue })
+ const r = new NoiseKK({ initiator: false, s: b, rs: a.publicKey, prologue })
+ return { a, b, i, r }
+}
+
+describe('Noise_KK_25519_ChaChaPoly_BLAKE2b', () => {
+ for (const v of fixtures.vectors) {
+ it(`reproduces the ${v.source} vector`, () => {
+ const i = new NoiseKK({
+ initiator: true, s: keyPairFromPrivate(hex(v.init_static)), rs: hex(v.init_remote_static),
+ prologue: hex(v.init_prologue), testEphemeral: keyPairFromPrivate(hex(v.init_ephemeral)),
+ })
+ const r = new NoiseKK({
+ initiator: false, s: keyPairFromPrivate(hex(v.resp_static)), rs: hex(v.resp_remote_static),
+ prologue: hex(v.resp_prologue), testEphemeral: keyPairFromPrivate(hex(v.resp_ephemeral)),
+ })
+ const [m0, m1, ...transport] = v.messages
+ const c0 = i.writeMessage(hex(m0.payload))
+ expect(toHex(c0)).toBe(m0.ciphertext)
+ expect(toHex(r.readMessage(c0))).toBe(m0.payload)
+ const c1 = r.writeMessage(hex(m1.payload))
+ expect(toHex(c1)).toBe(m1.ciphertext)
+ expect(toHex(i.readMessage(c1))).toBe(m1.payload)
+ expect(i.done && r.done).toBe(true)
+ if (v.handshake_hash) expect(toHex(i.handshakeHash)).toBe(v.handshake_hash)
+ expect(toHex(r.handshakeHash)).toBe(toHex(i.handshakeHash))
+
+ const si = i.split(), sr = r.split()
+ transport.forEach((m: { payload: string; ciphertext: string }, n: number) => {
+ const [send, recv] = n % 2 === 0 ? [si.send, sr.recv] : [sr.send, si.recv]
+ const ct = send.encrypt(hex(m.payload))
+ expect(toHex(ct)).toBe(m.ciphertext)
+ expect(toHex(recv.decrypt(ct))).toBe(m.payload)
+ })
+ })
+ }
+
+ it('a fresh handshake carries payloads both ways and gives matching transport keys', () => {
+ const { i, r } = pair()
+ expect(new TextDecoder().decode(r.readMessage(i.writeMessage(utf8('hi'))))).toBe('hi')
+ expect(i.done).toBe(false)
+ expect(new TextDecoder().decode(i.readMessage(r.writeMessage(utf8('hey'))))).toBe('hey')
+ const si = i.split(), sr = r.split()
+ expect(new TextDecoder().decode(sr.recv.decrypt(si.send.encrypt(utf8('one'))))).toBe('one')
+ expect(new TextDecoder().decode(si.recv.decrypt(sr.send.encrypt(utf8('two'))))).toBe('two')
+ })
+
+ it('throws on a tampered or replayed transport message', () => {
+ const { i, r } = pair()
+ r.readMessage(i.writeMessage(new Uint8Array(0)))
+ i.readMessage(r.writeMessage(new Uint8Array(0)))
+ const si = i.split(), sr = r.split()
+ const ct = si.send.encrypt(utf8('secret'))
+ const bad = ct.slice(); bad[0] ^= 1
+ expect(() => sr.recv.decrypt(bad)).toThrow()
+ // the failed message must not use up a nonce
+ expect(new TextDecoder().decode(sr.recv.decrypt(ct))).toBe('secret')
+ expect(() => sr.recv.decrypt(ct)).toThrow()
+ })
+
+ it('a responder that expects a different static key rejects the first message', () => {
+ const { i } = pair()
+ const stranger = generateKeyPair()
+ const r = new NoiseKK({ initiator: false, s: generateKeyPair(), rs: stranger.publicKey, prologue })
+ expect(() => r.readMessage(i.writeMessage(new Uint8Array(0)))).toThrow()
+ })
+
+ it('a different prologue fails the handshake', () => {
+ const a = generateKeyPair(), b = generateKeyPair()
+ const i = new NoiseKK({ initiator: true, s: a, rs: b.publicKey, prologue })
+ const r = new NoiseKK({ initiator: false, s: b, rs: a.publicKey, prologue: utf8('yogurt-v2') })
+ expect(() => r.readMessage(i.writeMessage(new Uint8Array(0)))).toThrow()
+ })
+
+ it('refuses out-of-turn calls and split before the handshake ends', () => {
+ const { i, r } = pair()
+ expect(() => r.writeMessage(new Uint8Array(0))).toThrow()
+ expect(() => i.split()).toThrow()
+ r.readMessage(i.writeMessage(new Uint8Array(0)))
+ expect(() => i.writeMessage(new Uint8Array(0))).toThrow()
+ })
+
+ it('rekey changes the key the same way on both ends', () => {
+ const k = crypto.getRandomValues(new Uint8Array(32))
+ const a = new CipherState(k.slice()), b = new CipherState(k.slice())
+ a.rekey(); b.rekey()
+ expect(new TextDecoder().decode(b.decrypt(a.encrypt(utf8('after'))))).toBe('after')
+ const c = new CipherState(k.slice()), d = new CipherState(k.slice())
+ d.rekey()
+ expect(() => c.decrypt(d.encrypt(utf8('x')))).toThrow()
+ })
+
+ it('generates X25519 key pairs', () => {
+ const k = generateKeyPair()
+ expect(k.publicKey.length).toBe(32)
+ expect(toHex(keyPairFromPrivate(k.privateKey).publicKey)).toBe(toHex(k.publicKey))
+ })
+
+ it('split works once; a second split throws (it would reuse nonces)', () => {
+ const { i, r } = handshake()
+ const si = i.split(), sr = r.split()
+ expect(() => i.split()).toThrow(/already split/)
+ expect(() => r.split()).toThrow(/already split/)
+ expect(new TextDecoder().decode(sr.recv.decrypt(si.send.encrypt(utf8('ok'))))).toBe('ok')
+ })
+
+ it('rejects every low-order ephemeral key, and the handshake stays dead', () => {
+ for (const point of lowOrder) {
+ for (const tamperFirst of [true, false]) {
+ const { i, r } = pair()
+ const m0 = i.writeMessage(new Uint8Array(0))
+ if (tamperFirst) {
+ const bad = m0.slice(); bad.set(hex(point), 0)
+ expect(() => r.readMessage(bad)).toThrow()
+ expect(() => r.readMessage(m0)).toThrow(/failed/)
+ } else {
+ r.readMessage(m0)
+ const m1 = r.writeMessage(new Uint8Array(0)).slice(); m1.set(hex(point), 0)
+ expect(() => i.readMessage(m1)).toThrow()
+ expect(i.done).toBe(false)
+ }
+ }
+ }
+ })
+
+ it('a failed writeMessage leaves the handshake dead', () => {
+ const i = new NoiseKK({ initiator: true, s: generateKeyPair(), rs: hex(lowOrder[0]), prologue })
+ expect(() => i.writeMessage(new Uint8Array(0))).toThrow()
+ expect(() => i.writeMessage(new Uint8Array(0))).toThrow(/failed/)
+ })
+
+ it('transport ciphers need a 32-byte key', () => {
+ expect(() => new CipherState(undefined as unknown as Uint8Array)).toThrow()
+ expect(() => new CipherState(new Uint8Array(16))).toThrow()
+ })
+
+ it('enforces the 65535-byte Noise message limit', () => {
+ const { i, r } = handshake()
+ const si = i.split(), sr = r.split()
+ expect(si.send.encrypt(new Uint8Array(65535 - 16)).length).toBe(65535)
+ expect(() => si.send.encrypt(new Uint8Array(65535 - 15))).toThrow()
+ expect(() => sr.recv.decrypt(new Uint8Array(65536))).toThrow()
+ expect(() => i.writeMessage(new Uint8Array(0))).toThrow()
+ const { i: i2 } = pair()
+ expect(() => i2.writeMessage(new Uint8Array(65535 - 47))).toThrow()
+ })
+
+ it('gives the handshake hash only once done, as a copy', () => {
+ const { i, r } = pair()
+ expect(() => i.handshakeHash).toThrow()
+ r.readMessage(i.writeMessage(new Uint8Array(0)))
+ i.readMessage(r.writeMessage(new Uint8Array(0)))
+ const h = i.handshakeHash
+ h.fill(0)
+ expect(toHex(i.handshakeHash)).toBe(toHex(r.handshakeHash))
+ expect(toHex(i.handshakeHash)).not.toBe(toHex(h))
+ })
+
+ it('wipes the ephemeral private key once the handshake is done', () => {
+ const a = generateKeyPair(), b = generateKeyPair(), ea = generateKeyPair(), eb = generateKeyPair()
+ const i = new NoiseKK({ initiator: true, s: a, rs: b.publicKey, prologue, testEphemeral: ea })
+ const r = new NoiseKK({ initiator: false, s: b, rs: a.publicKey, prologue, testEphemeral: eb })
+ r.readMessage(i.writeMessage(new Uint8Array(0)))
+ i.readMessage(r.writeMessage(new Uint8Array(0)))
+ expect(ea.privateKey.every((x) => x === 0)).toBe(true)
+ expect(eb.privateKey.every((x) => x === 0)).toBe(true)
+ expect(a.privateKey.some((x) => x !== 0)).toBe(true)
+ })
+
+ it('wipes the ephemeral private key when the handshake fails', () => {
+ const a = generateKeyPair(), b = generateKeyPair(), stranger = generateKeyPair(), ea = generateKeyPair(), eb = generateKeyPair()
+ const i = new NoiseKK({ initiator: true, s: a, rs: b.publicKey, prologue, testEphemeral: ea })
+ // the responder expects someone else, so message 1 fails there
+ const r = new NoiseKK({ initiator: false, s: b, rs: stranger.publicKey, prologue, testEphemeral: eb })
+ const m1 = i.writeMessage(new Uint8Array(0))
+ expect(() => r.readMessage(m1)).toThrow()
+ // a responder that hasn't written yet holds a test ephemeral only; it's wiped as soon as the handshake is dead
+ expect(eb.privateKey.every((x) => x === 0)).toBe(true)
+ const r2 = new NoiseKK({ initiator: false, s: b, rs: a.publicKey, prologue })
+ r2.readMessage(m1)
+ const m2 = r2.writeMessage(new Uint8Array(0))
+ m2[40] ^= 1
+ expect(() => i.readMessage(m2)).toThrow()
+ expect(ea.privateKey.every((x) => x === 0)).toBe(true)
+ })
+
+ it('a cipher keeps its own copy of the key', () => {
+ const k = new Uint8Array(32).fill(7)
+ const a = new CipherState(k), b = new CipherState(k.slice())
+ k.fill(0)
+ expect(b.decrypt(a.encrypt(utf8('pear')))).toEqual(utf8('pear'))
+ })
+})
diff --git a/app/test/companionPairing.test.ts b/app/test/companionPairing.test.ts
new file mode 100644
index 00000000..8a573b1c
--- /dev/null
+++ b/app/test/companionPairing.test.ts
@@ -0,0 +1,274 @@
+import { afterEach, beforeAll, describe, expect, it } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { openStore } from '../src/main/store'
+import { ready } from '../src/main/companion/sodium'
+import { generateKeyPair } from '../src/main/companion/noise'
+import { createCompanion, type Companion, type CompanionDeps } from '../src/main/companion'
+import type { Advert, Advertiser } from '../src/main/companion/advertise'
+import { pairAsPhone, raw, session } from './helpers/companionClient'
+
+beforeAll(() => ready())
+
+const open: { c: Companion; dir: string }[] = []
+afterEach(async () => {
+ for (const { c, dir } of open.splice(0)) { await c.stop(); rmSync(dir, { recursive: true, force: true }) }
+})
+
+async function make(o: Partial<CompanionDeps> = {}) {
+ const dir = mkdtempSync(join(tmpdir(), 'companion-pair-'))
+ const store = openStore(':memory:')
+ const adverts: (Advert | null)[] = []
+ let clock = 1_000_000
+ const lines: string[] = []
+ const c = await createCompanion({
+ store, userDataDir: dir, seal: (s) => 'sealed:' + Buffer.from(s).toString('hex'), open: (s) => Buffer.from(s.slice(7), 'hex').toString(),
+ ask: async () => ({ answer: '', sources: [] }), importRecording: async () => {}, audioFiles: async () => [],
+ deviceName: () => 'Test Mac', log: (...p) => lines.push(p.join(' ')), ops: { notesRewrite: () => {} },
+ host: '127.0.0.1', now: () => clock, advertiser: { publish: (a) => adverts.push(a), stop: () => adverts.push(null) },
+ ...o,
+ })
+ open.push({ c, dir })
+ return { c, store, dir, adverts, lines, tick: (ms: number) => { clock += ms } }
+}
+
+const devices = (store: ReturnType<typeof openStore>) => store.db.prepare('SELECT id, name, public_key FROM companion_devices').all()
+
+describe('companion pairing', () => {
+ it('an advert the network refuses (no Local Network permission, a firewall) says so instead of showing a code as if all is well', async () => {
+ const advertiser: Advertiser = { publish: () => {}, stop: () => {} }
+ const { c } = await make({ advertiser })
+ const pushed: string[] = []
+ c.onStatus((s) => pushed.push(String(s.error)))
+ await c.startPairing()
+ expect(c.status().error).toBeNull()
+ advertiser.onFailure?.()
+ expect(c.status().error).toBe('network')
+ expect(c.status().pairing).not.toBeNull()
+ expect(pushed.at(-1)).toBe('network')
+ // trying again starts from a clean slate
+ await c.cancelPairing()
+ await c.startPairing()
+ expect(c.status().error).toBeNull()
+ })
+
+ it('is off until pairing starts: no port, no advert, and a desktop id plus a sealed key on disk', async () => {
+ const { c, adverts, dir } = await make()
+ expect(c.port()).toBeNull()
+ expect(adverts.filter(Boolean)).toEqual([])
+ const saved = JSON.parse(readFileSync(join(dir, 'companion.json'), 'utf8'))
+ expect(saved.id).toBe(c.desktopId)
+ expect(saved.privateKey).toMatch(/^sealed:/)
+ expect(c.status()).toEqual({ paired: null, pairing: null, pairingClosed: null, error: null, connected: false, syncing: false })
+ })
+
+ it('pairs with the right code: the phone is stored, the advert says pairing=0 and the phone has the desktop key', async () => {
+ const { c, store, adverts } = await make()
+ const { code } = await c.startPairing()
+ expect(code).toMatch(/^\d{6}$/)
+ expect(adverts.at(-1)).toMatchObject({ txt: { v: '1', id: c.desktopId, name: 'Test Mac', pairing: '1' } })
+ const phone = generateKeyPair()
+ const r = await pairAsPhone(c.port()!, code, phone)
+ expect(r.result).toEqual({ type: 'pairOk' })
+ expect(Buffer.from(r.desktop!.key)).toEqual(Buffer.from(c.publicKey))
+ expect(r.desktop!.id).toBe(c.desktopId)
+ expect(devices(store)).toEqual([expect.objectContaining({ name: 'Test iPhone', public_key: Buffer.from(phone.publicKey).toString('base64') })])
+ expect(adverts.at(-1)).toMatchObject({ txt: { pairing: '0' } })
+ expect(c.status()).toMatchObject({ paired: { name: 'Test iPhone', lastSeen: null }, pairing: null })
+ // pairing is closed now: another hello is refused
+ expect((await pairAsPhone(c.port()!, code, generateKeyPair())).result).toEqual({ type: 'pairFail', reason: 'expired' })
+ })
+
+ const wrongFor = (code: string) => (code === '000000' ? '000001' : '000000')
+
+ it('a wrong code fails and counts; five give tooMany and a fresh code in the same window', async () => {
+ const { c, store, tick } = await make()
+ const { code, expiresAt } = await c.startPairing()
+ for (let i = 1; i <= 4; i++) {
+ expect((await pairAsPhone(c.port()!, wrongFor(code), generateKeyPair())).result).toEqual({ type: 'pairFail', reason: 'code' })
+ expect(c.status().pairing).toMatchObject({ code, attemptsLeft: 5 - i })
+ tick(1000)
+ }
+ expect((await pairAsPhone(c.port()!, wrongFor(code), generateKeyPair())).result).toEqual({ type: 'pairFail', reason: 'tooMany' })
+ const fresh = c.status().pairing!
+ expect(fresh.attemptsLeft).toBe(5)
+ // a new code does not buy more time
+ expect(fresh.expiresAt).toBe(expiresAt)
+ expect(devices(store)).toEqual([])
+ tick(1000)
+ expect((await pairAsPhone(c.port()!, fresh.code, generateKeyPair())).result).toEqual({ type: 'pairOk' })
+ })
+
+ it('waits a second after a wrong code before taking another guess', async () => {
+ const { c, tick } = await make()
+ const { code } = await c.startPairing()
+ expect((await pairAsPhone(c.port()!, wrongFor(code), generateKeyPair())).result).toEqual({ type: 'pairFail', reason: 'code' })
+ expect((await pairAsPhone(c.port()!, code, generateKeyPair())).result).toEqual({ type: 'pairFail', reason: 'busy' })
+ expect(c.status().pairing?.attemptsLeft).toBe(4)
+ tick(1000)
+ expect((await pairAsPhone(c.port()!, code, generateKeyPair())).result).toEqual({ type: 'pairOk' })
+ })
+
+ it('after three codes (15 wrong guesses) pairing closes until it is started again', async () => {
+ const { c, tick, adverts } = await make()
+ await c.startPairing()
+ for (let i = 0; i < 15; i++) {
+ const code = c.status().pairing!.code
+ const r = (await pairAsPhone(c.port()!, wrongFor(code), generateKeyPair())).result
+ expect(r).toEqual({ type: 'pairFail', reason: i === 14 || i % 5 === 4 ? 'tooMany' : 'code' })
+ tick(1000)
+ }
+ expect(c.status().pairing).toBeNull()
+ expect(c.status().pairingClosed).toBe('tooMany')
+ // not paired: the server and the advert are off
+ await expect.poll(() => c.port()).toBeNull()
+ expect(adverts.at(-1)).toBeNull()
+ await c.startPairing()
+ expect(c.status()).toMatchObject({ pairingClosed: null, pairing: { attemptsLeft: 5 } })
+ })
+
+ it('a second phone during an exchange is told busy; one that goes quiet after hello frees the slot', async () => {
+ const { c, tick } = await make({ limits: { stepMs: 200 } })
+ const { code } = await c.startPairing()
+ const quiet = await raw(c.port()!)
+ quiet.sendJson({ type: 'pairHello', v: 1, phoneSession: Buffer.alloc(16, 2).toString('base64'), phoneName: 'x' })
+ expect((await quiet.json()).type).toBe('pairStart')
+ expect((await pairAsPhone(c.port()!, code, generateKeyPair())).result).toEqual({ type: 'pairFail', reason: 'busy' })
+ await quiet.closed
+ // nothing guessed, nothing counted, but the next one still waits the pause a wrong guess would get
+ expect(c.status().pairing?.attemptsLeft).toBe(5)
+ expect((await pairAsPhone(c.port()!, code, generateKeyPair())).result).toEqual({ type: 'pairFail', reason: 'busy' })
+ tick(1000)
+ expect((await pairAsPhone(c.port()!, code, generateKeyPair())).result).toEqual({ type: 'pairOk' })
+ })
+
+ it('a server that cannot listen makes startPairing fail and says so in its status', async () => {
+ // an address this computer doesn't have: listening fails the way a refused bind would
+ const { c } = await make({ host: '192.0.2.1' })
+ await expect(c.startPairing()).rejects.toThrow()
+ expect(c.status()).toMatchObject({ error: 'listen', pairing: null })
+ expect(c.port()).toBeNull()
+ // putting it away clears the error, so Settings doesn't greet the next visit with it
+ await c.cancelPairing()
+ expect(c.status().error).toBeNull()
+ })
+
+
+ it('a pairing that finishes after the window closed is refused and stores nothing', async () => {
+ const { c, store } = await make()
+ // paired already, so the server stays up when the new pairing is cancelled
+ const first = await c.startPairing()
+ expect((await pairAsPhone(c.port()!, first.code, generateKeyPair(), 'First phone')).result.type).toBe('pairOk')
+ const { code } = await c.startPairing()
+ const r = await pairAsPhone(c.port()!, code, generateKeyPair(), 'Late phone', { beforeDone: () => c.cancelPairing() })
+ expect(r.result).toEqual({ type: 'pairFail', reason: 'expired' })
+ expect(devices(store).map((x) => x.name)).toEqual(['First phone'])
+ })
+
+ it('a stopped then started pairing in a hurry ends off', async () => {
+ const { c, adverts } = await make()
+ const started = c.startPairing()
+ await c.cancelPairing()
+ await started
+ expect(c.port()).toBeNull()
+ expect(adverts.filter(Boolean).length === 0 || adverts.at(-1) === null).toBe(true)
+ })
+
+ it('a keychain that cannot open the key keeps the pairing and stays off with an error', async () => {
+ const { c, store, dir } = await make()
+ const { code } = await c.startPairing()
+ await pairAsPhone(c.port()!, code, generateKeyPair())
+ await c.stop()
+ const before = readFileSync(join(dir, 'companion.json'), 'utf8')
+ const again = await createCompanion({
+ store, userDataDir: dir, seal: (s) => s, open: () => { throw new Error('locked') },
+ ask: async () => ({ answer: '', sources: [] }), importRecording: async () => {}, audioFiles: async () => [],
+ deviceName: () => 'Test Mac', log: () => {}, ops: { notesRewrite: () => {} }, host: '127.0.0.1', advertiser: { publish: () => {}, stop: () => {} },
+ })
+ open.push({ c: again, dir: mkdtempSync(join(tmpdir(), 'companion-pair-')) })
+ expect(again.status()).toMatchObject({ error: 'keychain', paired: { name: 'Test iPhone' } })
+ expect(again.port()).toBeNull()
+ expect(readFileSync(join(dir, 'companion.json'), 'utf8')).toBe(before)
+ expect(devices(store)).toHaveLength(1)
+ await expect(again.startPairing()).rejects.toThrow()
+ })
+
+ it('a phone that breaks off after its guess still uses up an attempt', async () => {
+ const { c } = await make()
+ await c.startPairing()
+ const s = await raw(c.port()!)
+ s.sendJson({ type: 'pairHello', v: 1, phoneSession: Buffer.alloc(16, 1).toString('base64'), phoneName: 'x' })
+ await s.json()
+ // any valid point: its own share with a guessed code
+ const { cpaceRespond } = await import('../src/main/companion/cpace')
+ const { yb } = cpaceRespond('123456', new Uint8Array(1), new Uint8Array(1), (await import('../src/main/companion/cpace')).cpaceStart('1', new Uint8Array(1), new Uint8Array(1)).ya)
+ s.sendJson({ type: 'pairReply', yb: Buffer.from(yb).toString('base64') })
+ expect((await s.json()).type).toBe('pairConfirm')
+ s.socket.destroy()
+ await expect.poll(() => c.status().pairing?.attemptsLeft).toBe(4)
+ })
+
+ it('the code expires after two minutes', async () => {
+ const { c, adverts, tick } = await make()
+ const { code, expiresAt } = await c.startPairing()
+ expect(expiresAt).toBe(1_000_000 + 120_000)
+ tick(120_000)
+ expect(c.status().pairing).toBeNull()
+ expect(c.status().pairingClosed).toBe('expired')
+ await expect.poll(() => adverts.at(-1)).toBeNull()
+ // not paired, so the server is off
+ await expect.poll(() => c.port()).toBeNull()
+ // pairing again opens it once more, with a fresh window
+ const again = await c.startPairing()
+ expect(again.code).toMatch(/^\d{6}$/)
+ tick(119_000)
+ expect(c.status().pairing?.code).toBe(again.code)
+ void code
+ })
+
+ it('a second pairing replaces the first phone, and the old phone can no longer connect', async () => {
+ const { c, store } = await make()
+ const a = generateKeyPair(), b = generateKeyPair()
+ const first = await c.startPairing()
+ const ra = await pairAsPhone(c.port()!, first.code, a, 'Phone A')
+ expect(ra.result.type).toBe('pairOk')
+ const sa = await session(c.port()!, a, ra.desktop!.key)
+ expect((await sa.request('hello', { appVersion: '1', schema: 1 })).type).toBe('ok')
+ const { code } = await c.startPairing()
+ expect((await pairAsPhone(c.port()!, code, b, 'Phone B')).result.type).toBe('pairOk')
+ await sa.raw.closed
+ expect(devices(store).map((d) => d.name)).toEqual(['Phone B'])
+ // A's key is not the paired one now
+ await expect(session(c.port()!, a, ra.desktop!.key)).rejects.toThrow()
+ const sb = await session(c.port()!, b, ra.desktop!.key)
+ expect((await sb.request('hello', { appVersion: '1', schema: 1 })).type).toBe('ok')
+ sb.close()
+ })
+
+ it('keeps its id and key across restarts, starts by itself when paired, and unpair turns it off', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'companion-pair-'))
+ const store = openStore(':memory:')
+ const base = {
+ store, userDataDir: dir, seal: (s: string) => 'sealed:' + s, open: (s: string) => s.slice(7),
+ ask: async () => ({ answer: '', sources: [] }), importRecording: async () => {}, audioFiles: async () => [],
+ deviceName: () => 'Test Mac', log: () => {}, ops: { notesRewrite: () => {} }, host: '127.0.0.1', advertiser: { publish: () => {}, stop: () => {} },
+ }
+ const one = await createCompanion(base)
+ const { code } = await one.startPairing()
+ const phone = generateKeyPair()
+ const r = await pairAsPhone(one.port()!, code, phone)
+ const port = one.port()
+ await one.stop()
+ const two = await createCompanion(base)
+ open.push({ c: two, dir })
+ expect(two.desktopId).toBe(one.desktopId)
+ expect(two.port()).toBe(port)
+ const s = await session(two.port()!, phone, r.desktop!.key)
+ expect((await s.request('hello', { appVersion: '1', schema: 1 })).type).toBe('ok')
+ await two.unpair()
+ await s.raw.closed
+ expect(two.port()).toBeNull()
+ expect(two.status().paired).toBeNull()
+ })
+})
diff --git a/app/test/companionPhoneImport.test.ts b/app/test/companionPhoneImport.test.ts
new file mode 100644
index 00000000..eaeedcef
--- /dev/null
+++ b/app/test/companionPhoneImport.test.ts
@@ -0,0 +1,84 @@
+import { mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { openStore, type Store } from '../src/main/store'
+import { importPhoneRecording, isPhoneDraft, phoneWavOk } from '../src/main/companion/phoneImport'
+import { wavBytes } from '../src/main/asr/transcribe'
+import { AUDIO_SPEAKER } from '../src/shared/audioUpload'
+
+let store: Store, root: string
+const start = vi.fn(), changed = vi.fn()
+const meeting = { id: 'phone-rec-1', title: 'Meeting at 3:40 PM', titleSource: 'default' as const, startedAt: 1000, endedAt: 61_000, attendees: [] }
+const draft = { myNotes: 'ask about the budget', summary: '## Budget\n- Made-up draft point', transcript: [
+ { startMs: 0, endMs: 900, text: 'Made-up first line.' }, { startMs: 1000, endMs: 1900, text: ' ' }, { startMs: 2000, endMs: 2900, text: 'Made-up second line.' }] }
+/** a tenth of a second of made-up 16 kHz mono 16-bit audio, as the phone sends it */
+const tinyWav = (name = 'up.wav') => { const f = join(root, name); const s = new Float32Array(1600).map((_, i) => Math.sin(i / 8) * 0.2); const b = wavBytes(s); b.writeUInt32LE(36 + s.length * 2, 4); b.writeUInt32LE(s.length * 2, 40); writeFileSync(f, b); return f }
+const deps = () => ({ store, meetingDir: (id: string) => join(root, 'meetings', id), start, changed })
+
+beforeEach(() => { store = openStore(':memory:'); root = mkdtempSync(join(tmpdir(), 'yogurt-phone-')); vi.resetAllMocks() })
+afterEach(() => store.close())
+
+it('a phone WAV becomes them.wav, keeps the phone transcript and draft notes, and is transcribed again over them', async () => {
+ const wav = tinyWav(), bytes = readFileSync(wav)
+ await importPhoneRecording(deps(), meeting, wav, draft)
+ const dir = join(root, 'meetings', meeting.id)
+ expect(readFileSync(join(dir, 'them.wav'))).toEqual(bytes)
+ expect(existsSync(wav)).toBe(false)
+ const m = store.meeting(meeting.id)!
+ expect(m).toMatchObject({ source: 'audio-file', title: meeting.title, transcriptionPending: true })
+ expect(isPhoneDraft(m)).toBe(true)
+ expect(store.segments(meeting.id).map((s) => [s.text, s.track, s.speaker, s.startMs])).toEqual([
+ ['Made-up first line.', 'them', AUDIO_SPEAKER, 0], ['Made-up second line.', 'them', AUDIO_SPEAKER, 2000]])
+ expect(store.notes(meeting.id)).toMatchObject({ mine: 'ask about the budget', enhanced: '## Budget\n- Made-up draft point' })
+ // the computer's transcript replaces the phone's only once it has one
+ expect(start).toHaveBeenCalledExactlyOnceWith(meeting.id, true)
+ expect(changed).toHaveBeenCalled()
+})
+
+it('with nothing from the phone it is transcribed like any upload', async () => {
+ await importPhoneRecording(deps(), meeting, tinyWav(), { myNotes: '', transcript: [] })
+ const m = store.meeting(meeting.id)!
+ expect(isPhoneDraft(m)).toBe(false)
+ expect(store.segments(meeting.id)).toEqual([])
+ expect(store.notes(meeting.id).enhanced).toBeNull()
+ expect(start).toHaveBeenCalledExactlyOnceWith(meeting.id, false)
+})
+
+it('an m4a from an older phone stays them.m4a', async () => {
+ const f = join(root, 'up.m4a'); writeFileSync(f, 'made-up m4a bytes')
+ await importPhoneRecording(deps(), meeting, f, draft)
+ expect(existsSync(join(root, 'meetings', meeting.id, 'them.m4a'))).toBe(true)
+})
+
+it('a WAV that is not 16 kHz mono 16-bit is refused before any meeting is made', async () => {
+ const f = join(root, 'odd.wav'); const b = Buffer.from(readFileSync(tinyWav('good.wav'))); b.writeUInt32LE(44100, 24); writeFileSync(f, b)
+ expect(await phoneWavOk(f)).toBe(false)
+ expect(await phoneWavOk(tinyWav('good.wav'))).toBe(true)
+ await expect(importPhoneRecording(deps(), meeting, f, draft)).rejects.toThrow()
+ expect(store.meeting(meeting.id)).toBeUndefined()
+ expect(start).not.toHaveBeenCalled()
+})
+
+it('imports once', async () => {
+ await importPhoneRecording(deps(), meeting, tinyWav(), draft)
+ await importPhoneRecording(deps(), meeting, tinyWav(), draft)
+ expect(start).toHaveBeenCalledOnce()
+ expect(store.segments(meeting.id)).toHaveLength(2)
+})
+
+it("the phone's default title is the computer's to replace; one its model wrote may be improved; one typed stays", async () => {
+ await importPhoneRecording(deps(), meeting, tinyWav(), draft)
+ expect(store.meeting(meeting.id)!.titleSource).toBe('generic')
+ await importPhoneRecording(deps(), { ...meeting, id: 'phone-rec-2', title: 'Budget walk', titleSource: 'model' }, tinyWav('b.wav'), draft)
+ expect(store.meeting('phone-rec-2')!.titleSource).toBe('auto')
+ await importPhoneRecording(deps(), { ...meeting, id: 'phone-rec-3', title: 'Kiwi plans', titleSource: 'typed' }, tinyWav('c.wav'), draft)
+ expect(store.meeting('phone-rec-3')!.titleSource).toBe('user')
+})
+
+it('a recording said to be in German is kept as German, so this computer transcribes and writes its notes in it', async () => {
+ await importPhoneRecording(deps(), { ...meeting, language: 'de' }, tinyWav(), draft)
+ expect(store.meeting(meeting.id)!.language).toBe('german')
+ await importPhoneRecording(deps(), { ...meeting, id: 'phone-rec-2' }, tinyWav('b.wav'), { myNotes: '', transcript: [] })
+ expect(store.meeting('phone-rec-2')!.language).toBeNull()
+})
diff --git a/app/test/companionRecords.test.ts b/app/test/companionRecords.test.ts
new file mode 100644
index 00000000..3c03f14c
--- /dev/null
+++ b/app/test/companionRecords.test.ts
@@ -0,0 +1,231 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { openStore, type Store } from '../src/main/store'
+import { initMeetings } from '../src/main/meeting'
+import { AUDIO_SPEAKER } from '../src/shared/audioUpload'
+import { applyOp, changesSince, FROM_IPHONE, notesHash, type Change } from '../src/main/companion/records'
+
+let store: Store
+beforeEach(() => { store = openStore(':memory:'); initMeetings(store) })
+const base = { endedAt: 2000, eventId: null, app: 'Zoom', attendees: [], state: 'done' as const }
+const deps = () => ({ notesRewrite: (id: string, mine: string) => store.setNotes(id, { mine }), nowMs: () => 5000 })
+const head = () => changesSince(store, 0, 10_000).cursor
+const keys = (changes: Change[]) => changes.map((c) => `${c.entity}:${c.id}${c.deleted ? ':deleted' : ''}`)
+
+describe('companion change log', () => {
+ it('a new meeting, a notes edit, transcript lines and a folder change each appear once after the cursor', () => {
+ const since = head()
+ const m = store.createMeeting({ ...base, title: 'Banana sync', startedAt: 1000, attendees: [{ name: 'Ada Example', email: '[email protected]' }] })
+ store.setNotes(m.id, { mine: 'first' })
+ store.setNotes(m.id, { mine: 'second', enhanced: '## Summary' })
+ store.addSegments([
+ { meetingId: m.id, track: 'me', startMs: 0, endMs: 900, text: 'hello there', speaker: 'me' },
+ { meetingId: m.id, track: 'them', startMs: 1000, endMs: 1900, text: 'hi back', speaker: null },
+ { meetingId: m.id, track: 'me', startMs: 2000, endMs: 2500, text: 'an echo', speaker: 'me', hidden: true },
+ ])
+ const f = store.createFolder('Fruit')
+ store.addToFolder(f.id, m.id)
+ const { changes, cursor, more } = changesSince(store, since, 100)
+ expect(more).toBe(false)
+ expect(cursor).toBeGreaterThan(since)
+ expect(keys(changes).sort()).toEqual([`folder:${f.id}`, `folderMembers:${f.id}`, `meeting:${m.id}`, `notes:${m.id}`, 'people:[email protected]', `segments:${m.id}`].sort())
+ const rec = (e: string) => changes.find((c) => c.entity === e)!.record
+ expect(rec('meeting')).toEqual({ id: m.id, title: 'Banana sync', startedAt: 1000, endedAt: 2000, attendees: [{ name: 'Ada Example', email: '[email protected]' }], app: 'Zoom', trashedAt: null, language: null })
+ expect(rec('notes')).toEqual({ meetingId: m.id, mine: 'second', summary: '## Summary', mineHash: notesHash('second') })
+ expect(rec('segments')).toEqual({ meetingId: m.id, oneMic: false, segments: [{ startMs: 0, endMs: 900, speaker: 'me', text: 'hello there' }, { startMs: 1000, endMs: 1900, speaker: null, text: 'hi back' }] })
+ expect(rec('folder')).toEqual({ id: f.id, name: 'Fruit', createdAt: f.createdAt })
+ expect(rec('folderMembers')).toEqual({ folderId: f.id, meetingIds: [m.id] })
+ expect(rec('people')).toEqual({ email: '[email protected]', displayName: null })
+ // nothing new: nothing after the cursor
+ expect(changesSince(store, cursor, 100)).toMatchObject({ changes: [], cursor, more: false })
+ store.removeFromFolder(f.id, m.id)
+ const after = changesSince(store, cursor, 100)
+ expect(keys(after.changes)).toEqual([`folderMembers:${f.id}`])
+ expect(after.changes[0].record).toEqual({ folderId: f.id, meetingIds: [] })
+ expect(after.cursor).toBeGreaterThan(cursor)
+ })
+
+ it('pages with limit and more', () => {
+ const since = head()
+ for (const t of ['Apple', 'Pear', 'Plum']) store.createMeeting({ ...base, title: t, startedAt: 1000 })
+ const one = changesSince(store, since, 2)
+ expect(one.changes).toHaveLength(2)
+ expect(one.more).toBe(true)
+ const two = changesSince(store, one.cursor, 2)
+ expect(two.changes).toHaveLength(1)
+ expect(two.more).toBe(false)
+ expect(two.changes.map((c) => (c.record as { title: string }).title)).toEqual(['Plum'])
+ })
+
+ it('clamps limit to 1..500 and stops a page early past about 1 MB, always with at least one change', () => {
+ const since = head()
+ const long = 'word '.repeat(60_000) // ~300 KB per transcript
+ for (let i = 0; i < 5; i++) {
+ const m = store.createMeeting({ ...base, title: `Long ${i}`, startedAt: 1000 + i })
+ store.addSegments([{ meetingId: m.id, track: 'them', startMs: 0, endMs: 1, text: long, speaker: null }])
+ }
+ const all: Change[] = []
+ let cursor = since, more = true, pages = 0
+ while (more) {
+ const page = changesSince(store, cursor, 500)
+ expect(page.changes.length).toBeGreaterThan(0)
+ expect(JSON.stringify(page.changes).length < 1_100_000 || page.changes.length === 1).toBe(true)
+ all.push(...page.changes); cursor = page.cursor; more = page.more; pages++
+ }
+ expect(pages).toBeGreaterThan(1)
+ expect(all.filter((c) => c.entity === 'segments')).toHaveLength(5)
+ expect(changesSince(store, since, 0).changes).toHaveLength(1)
+ expect(changesSince(store, since, Number.NaN).changes).toHaveLength(1)
+ expect(changesSince(store, since, 10_000).changes.length).toBeLessThanOrEqual(500)
+ })
+
+ it('gives the log an epoch that stays the same across opens', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'yogurt-companion-'))
+ try {
+ const a = openStore(join(dir, 'yogurt.db'))
+ const epoch = changesSince(a, 0, 10).epoch
+ expect(epoch).toMatch(/^[0-9a-f-]{36}$/)
+ a.close()
+ const b = openStore(join(dir, 'yogurt.db'))
+ expect(changesSince(b, 0, 10).epoch).toBe(epoch)
+ b.close()
+ expect(changesSince(store, 0, 10).epoch).not.toBe(epoch)
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+ })
+
+ it('triggers are made again under a new version, so their columns can change', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'yogurt-companion-'))
+ try {
+ const a = openStore(join(dir, 'yogurt.db'))
+ a.db.exec('DROP TRIGGER companion_meetings_au')
+ a.db.prepare("UPDATE companion_meta SET value = '0' WHERE key = 'triggers'").run()
+ a.close()
+ const b = openStore(join(dir, 'yogurt.db'))
+ const m = b.createMeeting({ ...base, title: 'Kiwi', startedAt: 1000 })
+ const since = changesSince(b, 0, 500).cursor
+ b.updateMeeting(m.id, { title: 'Kiwi two' })
+ expect(keys(changesSince(b, since, 10).changes)).toEqual([`meeting:${m.id}`])
+ b.close()
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+ })
+
+ it('what was there before the log existed is sent from the start', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'yogurt-companion-'))
+ try {
+ const old = openStore(join(dir, 'yogurt.db'))
+ const m = old.createMeeting({ ...base, title: 'Old one', startedAt: 1000 })
+ // a database from before the companion: no log, no triggers
+ for (const r of old.db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'companion_%'").all()) old.db.exec(`DROP TRIGGER ${String(r.name)}`)
+ old.db.exec('DROP TABLE companion_changes')
+ old.close()
+ const reopened = openStore(join(dir, 'yogurt.db'))
+ expect(keys(changesSince(reopened, 0, 100).changes)).toContain(`meeting:${m.id}`)
+ reopened.close()
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+ })
+
+ it('deleting a folder, and a meeting deleted for good, become tombstones; a trashed meeting is a record with trashedAt', () => {
+ const m = store.createMeeting({ ...base, title: 'Cherry', startedAt: 1000 })
+ const gone = store.createMeeting({ ...base, title: 'Lime', startedAt: 1000 })
+ const f = store.createFolder('Stone fruit')
+ store.addToFolder(f.id, m.id)
+ const since = head()
+ store.deleteFolder(f.id)
+ store.trashMeeting(m.id, 4000)
+ store.deleteMeeting(gone.id)
+ const { changes } = changesSince(store, since, 100)
+ expect(changes).toContainEqual({ entity: 'folder', id: f.id, deleted: true })
+ expect(changes).toContainEqual({ entity: 'folderMembers', id: f.id, deleted: true })
+ expect(changes).toContainEqual({ entity: 'meeting', id: gone.id, deleted: true })
+ expect(changes.find((c) => c.entity === 'meeting' && c.id === m.id)?.record).toMatchObject({ trashedAt: 4000 })
+ expect(new Set(keys(changes)).size).toBe(changes.length)
+ })
+})
+
+describe('companion one-mic meetings', () => {
+ it('an uploaded or phone recording says oneMic and names nobody, never the reserved audio speaker', () => {
+ const m = store.createMeeting({ ...base, title: 'Room chat', startedAt: 1000, source: 'audio-file' })
+ store.addSegments([{ meetingId: m.id, track: 'them', startMs: 0, endMs: 900, text: 'made-up line', speaker: AUDIO_SPEAKER }])
+ const seg = changesSince(store, 0, 100).changes.find((c) => c.entity === 'segments' && c.id === m.id)!.record
+ expect(seg).toEqual({ meetingId: m.id, oneMic: true, segments: [{ startMs: 0, endMs: 900, speaker: null, text: 'made-up line' }] })
+ })
+})
+
+describe('companion ops', () => {
+ it('setMine with the matching base replaces My notes', () => {
+ const m = store.createMeeting({ ...base, title: 'Grape', startedAt: 1000 })
+ store.setNotes(m.id, { mine: 'desk' })
+ expect(applyOp(store, { kind: 'setMine', meetingId: m.id, text: 'phone', baseHash: notesHash('desk') }, deps())).toEqual({ applied: true })
+ expect(store.notes(m.id).mine).toBe('phone')
+ })
+
+ it('setMine with a stale base keeps the desktop text and adds the phone text under a heading', () => {
+ const m = store.createMeeting({ ...base, title: 'Grape', startedAt: 1000 })
+ store.setNotes(m.id, { mine: 'desk edit' })
+ const op = { kind: 'setMine' as const, meetingId: m.id, text: 'phone edit', baseHash: notesHash('older') }
+ expect(applyOp(store, op, deps())).toEqual({ applied: true, merged: true })
+ expect(FROM_IPHONE).toBe('\n\n## From your iPhone\n\n')
+ expect(store.notes(m.id).mine).toBe('desk edit\n\n## From your iPhone\n\nphone edit')
+ // sent again (a retry): not added twice
+ expect(applyOp(store, op, deps())).toEqual({ applied: true, merged: true })
+ expect(store.notes(m.id).mine).toBe('desk edit\n\n## From your iPhone\n\nphone edit')
+ })
+
+ it('a short phone text found inside the desktop notes is still added', () => {
+ const m = store.createMeeting({ ...base, title: 'Grape', startedAt: 1000 })
+ store.setNotes(m.id, { mine: 'book' })
+ expect(applyOp(store, { kind: 'setMine', meetingId: m.id, text: 'ok', baseHash: notesHash('older') }, deps())).toEqual({ applied: true, merged: true })
+ expect(store.notes(m.id).mine).toBe('book' + FROM_IPHONE + 'ok')
+ })
+
+ it('a phone text that only starts an earlier phone block is still added; a block in the middle counts as there', () => {
+ const m = store.createMeeting({ ...base, title: 'Grape', startedAt: 1000 })
+ store.setNotes(m.id, { mine: 'desk' + FROM_IPHONE + 'phone edit' })
+ applyOp(store, { kind: 'setMine', meetingId: m.id, text: 'phone', baseHash: notesHash('older') }, deps())
+ expect(store.notes(m.id).mine).toBe('desk' + FROM_IPHONE + 'phone edit' + FROM_IPHONE + 'phone')
+ // 'phone edit' is a whole block followed by another one: a retry, not added again
+ applyOp(store, { kind: 'setMine', meetingId: m.id, text: 'phone edit', baseHash: notesHash('older') }, deps())
+ expect(store.notes(m.id).mine).toBe('desk' + FROM_IPHONE + 'phone edit' + FROM_IPHONE + 'phone')
+ })
+
+ it('setMine with the text the desktop already has writes nothing', () => {
+ const m = store.createMeeting({ ...base, title: 'Grape', startedAt: 1000 })
+ store.setNotes(m.id, { mine: 'same' })
+ const since = head()
+ let writes = 0
+ expect(applyOp(store, { kind: 'setMine', meetingId: m.id, text: 'same', baseHash: notesHash('older') }, { ...deps(), notesRewrite: () => { writes++ } })).toEqual({ applied: true })
+ expect(writes).toBe(0)
+ expect(changesSince(store, since, 10).changes).toEqual([])
+ })
+
+ it('notesHash is sha256 of the NFC text', () => {
+ expect(notesHash('café')).toBe(notesHash('café'))
+ expect(notesHash('')).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
+ })
+
+ it('rename, folders, trash and restore go through the desktop rules', () => {
+ const m = store.createMeeting({ ...base, title: 'Melon', startedAt: 1000 })
+ const f = store.createFolder('Fruit')
+ expect(applyOp(store, { kind: 'rename', meetingId: m.id, title: ' Melon review ' }, deps())).toEqual({ applied: true })
+ expect(store.meeting(m.id)).toMatchObject({ title: 'Melon review', titleSource: 'user' })
+ applyOp(store, { kind: 'addToFolder', meetingId: m.id, folderId: f.id }, deps())
+ expect(store.folderMeetingIds(f.id)).toEqual([m.id])
+ applyOp(store, { kind: 'removeFromFolder', meetingId: m.id, folderId: f.id }, deps())
+ expect(store.folderMeetingIds(f.id)).toEqual([])
+ applyOp(store, { kind: 'trash', meetingId: m.id }, deps())
+ expect(store.meeting(m.id)?.trashedAt).toBe(5000)
+ expect(store.trashed().map((t) => t.id)).toEqual([m.id])
+ applyOp(store, { kind: 'restore', meetingId: m.id }, deps())
+ expect(store.meeting(m.id)?.trashedAt).toBeUndefined()
+ })
+
+ it('refuses an op for a meeting or folder that is not there, and never trashes a recording', () => {
+ const rec = store.createMeeting({ ...base, title: 'Live', startedAt: 1000, state: 'recording' })
+ expect(() => applyOp(store, { kind: 'rename', meetingId: 'nope', title: 'x' }, deps())).toThrow('gone')
+ expect(() => applyOp(store, { kind: 'addToFolder', meetingId: rec.id, folderId: 'nope' }, deps())).toThrow('gone')
+ expect(() => applyOp(store, { kind: 'trash', meetingId: rec.id }, deps())).toThrow('recording')
+ expect(store.meeting(rec.id)?.trashedAt).toBeUndefined()
+ })
+})
diff --git a/app/test/companionServer.test.ts b/app/test/companionServer.test.ts
new file mode 100644
index 00000000..2c16a5b0
--- /dev/null
+++ b/app/test/companionServer.test.ts
@@ -0,0 +1,414 @@
+import { afterEach, beforeAll, describe, expect, it } from 'vitest'
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { randomBytes } from 'node:crypto'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { openStore, type Store } from '../src/main/store'
+import { initMeetings } from '../src/main/meeting'
+import { ready } from '../src/main/companion/sodium'
+import { generateKeyPair, type KeyPair } from '../src/main/companion/noise'
+import { notesHash } from '../src/main/companion/records'
+import { askSources } from '../src/main/companion/handlers'
+import { createCompanion, type Companion, type CompanionDeps } from '../src/main/companion'
+import { pairAsPhone, raw, session } from './helpers/companionClient'
+
+beforeAll(() => ready())
+
+const open: { c: Companion; dir: string }[] = []
+afterEach(async () => {
+ for (const { c, dir } of open.splice(0)) { await c.stop(); rmSync(dir, { recursive: true, force: true }) }
+})
+
+const base = { endedAt: 2000, eventId: null, app: null, attendees: [], state: 'done' as const }
+
+/** A companion with a phone already paired */
+async function paired(o: Partial<CompanionDeps> = {}) {
+ const dir = mkdtempSync(join(tmpdir(), 'companion-server-'))
+ const store: Store = o.store ?? openStore(':memory:')
+ initMeetings(store)
+ const lines: string[] = []
+ const c = await createCompanion({
+ store, userDataDir: dir, seal: (s) => 'sealed:' + s, open: (s) => s.slice(7),
+ ask: async () => ({ answer: '', sources: [] }), importRecording: async () => {}, audioFiles: async () => [],
+ deviceName: () => 'Test Mac', appVersion: '9.9.9', log: (...p) => lines.push(p.join(' ')),
+ ops: { notesRewrite: (id, mine) => store.setNotes(id, { mine }) },
+ host: '127.0.0.1', advertiser: { publish: () => {}, stop: () => {} }, pollMs: 20,
+ ...o,
+ })
+ open.push({ c, dir })
+ const phone = generateKeyPair()
+ const { code } = await c.startPairing()
+ const r = await pairAsPhone(c.port()!, code, phone)
+ expect(r.result.type).toBe('pairOk')
+ const desktopKey = r.desktop!.key
+ const connect = (key: KeyPair = phone) => session(c.port()!, key, desktopKey)
+ const requests = () => lines.filter((l) => /COMPANION (pull|ask|upload|imported|audio)/.test(l))
+ return { c, store, dir, phone, desktopKey, connect, lines, requests }
+}
+
+const frame = (payload: Uint8Array) => { const b = Buffer.alloc(2 + payload.length); b.writeUInt16BE(payload.length); b.set(payload, 2); return b }
+
+describe('companion sessions', () => {
+ it('answers hello and pull over Noise KK with the paired key', async () => {
+ const { c, store, connect } = await paired()
+ const m = store.createMeeting({ ...base, title: 'Kiwi review', startedAt: 1000 })
+ const s = await connect()
+ const hello = await s.request('hello', { appVersion: '1.0', schema: 1 })
+ expect(hello).toMatchObject({ type: 'ok', body: { desktopId: c.desktopId, desktopName: 'Test Mac', desktopVersion: '9.9.9' } })
+ expect(typeof (hello.body as { epoch: string }).epoch).toBe('string')
+ const pull = await s.request('pull', { since: 0, limit: 100 })
+ expect(pull.type).toBe('ok')
+ const body = pull.body as { changes: { entity: string; id: string }[]; cursor: number; more: boolean; epoch: string }
+ expect(body.epoch).toBe((hello.body as { epoch: string }).epoch)
+ expect(body.changes).toContainEqual(expect.objectContaining({ entity: 'meeting', id: m.id }))
+ expect(body.more).toBe(false)
+ expect(c.status()).toMatchObject({ connected: true, paired: { name: 'Test iPhone' } })
+ expect(c.status().paired!.lastSeen).not.toBeNull()
+ s.close()
+ await expect.poll(() => c.status().connected).toBe(false)
+ })
+
+ it('a big reply comes in chunks and is put back together', async () => {
+ const { store, connect } = await paired()
+ const m = store.createMeeting({ ...base, title: 'Long one', startedAt: 1000 })
+ store.addSegments(Array.from({ length: 400 }, (_, i) => ({ meetingId: m.id, track: 'me' as const, startMs: i * 1000, endMs: i * 1000 + 900, text: 'made-up words '.repeat(30), speaker: 'me' })))
+ const s = await connect()
+ const pull = await s.request('pull', { since: 0, limit: 100 })
+ const seg = (pull.body as { changes: { entity: string; record: { segments: unknown[] } }[] }).changes.find((x) => x.entity === 'segments')!
+ expect(seg.record.segments).toHaveLength(400)
+ // a big request from the phone works the same way
+ const ok = await s.request('op', { kind: 'setMine', meetingId: m.id, text: 'x'.repeat(200_000), baseHash: notesHash('') })
+ expect(ok).toMatchObject({ type: 'ok', body: { applied: true } })
+ expect(store.notes(m.id).mine).toHaveLength(200_000)
+ })
+
+ it('closes an unpaired key, a truncated frame and random bytes before any request, and keeps serving', async () => {
+ const { c, connect, requests } = await paired({ limits: { handshakeMs: 300 } })
+ // a phone that isn't the paired one
+ await expect(connect(generateKeyPair())).rejects.toThrow()
+ // half a frame, then nothing: closed by the handshake timeout
+ const half = await raw(c.port()!)
+ half.socket.write(Buffer.from([0x00, 0x64, 1, 2, 3]))
+ await half.closed
+ // random bytes in a well-formed frame
+ const junk = await raw(c.port()!)
+ junk.socket.write(frame(crypto.getRandomValues(new Uint8Array(80))))
+ await junk.closed
+ // a JSON frame that isn't a pairHello
+ const json = await raw(c.port()!)
+ json.sendJson({ id: '1', type: 'pull', body: { since: 0 } })
+ await json.closed
+ expect(requests()).toEqual([])
+ const s = await connect()
+ expect((await s.request('pull', { since: 0, limit: 1 })).type).toBe('ok')
+ })
+
+ it('a session that sends garbage after the handshake is closed; a newer session replaces the older one', async () => {
+ const { c, connect } = await paired()
+ const a = await connect()
+ a.raw.socket.write(frame(crypto.getRandomValues(new Uint8Array(40))))
+ await a.raw.closed
+ const b = await connect()
+ expect((await b.request('hello', { appVersion: '1', schema: 1 })).type).toBe('ok')
+ const d = await connect()
+ expect((await d.request('hello', { appVersion: '1', schema: 1 })).type).toBe('ok')
+ await b.raw.closed
+ expect((await d.request('hello', { appVersion: '1', schema: 1 })).type).toBe('ok')
+ expect(c.status().connected).toBe(true)
+ })
+
+ it('a replayed first handshake message gets no answer, neither kicks the phone off nor shows it as connected', async () => {
+ const { c, connect, phone, desktopKey } = await paired({ limits: { handshakeMs: 300 } })
+ let captured: Uint8Array | undefined
+ const first = await session(c.port()!, phone, desktopKey, undefined, { sent: (m) => { captured = m } })
+ expect((await first.request('hello', { schema: 1 })).type).toBe('ok')
+ first.close()
+ await expect.poll(() => c.status().connected).toBe(false)
+ // the attacker replays it: dropped at once, nothing connected and nothing seen
+ const seenBefore = c.status().paired!.lastSeen
+ const replay = await raw(c.port()!)
+ replay.send(captured!)
+ await expect(replay.next()).rejects.toThrow('closed')
+ expect(c.status().connected).toBe(false)
+ expect(c.status().paired!.lastSeen).toBe(seenBefore)
+ // with the real phone connected, a replay doesn't close it
+ const live = await connect()
+ expect((await live.request('hello', { schema: 1 })).type).toBe('ok')
+ const again = await raw(c.port()!)
+ again.send(captured!)
+ await expect(again.next()).rejects.toThrow('closed')
+ expect((await live.request('pull', { since: 0, limit: 1 })).type).toBe('ok')
+ expect(c.status().connected).toBe(true)
+ })
+
+ it('remembers a bounded number of first messages: an old enough one is answered, then closed after one step', async () => {
+ const { c, phone, desktopKey } = await paired({ limits: { handshakeMs: 10_000, stepMs: 200, replays: 1 } })
+ let captured: Uint8Array | undefined
+ ;(await session(c.port()!, phone, desktopKey, undefined, { sent: (m) => { captured = m } })).close()
+ // a newer handshake pushes the first one out of the cache
+ ;(await session(c.port()!, phone, desktopKey)).close()
+ const replay = await raw(c.port()!)
+ replay.send(captured!)
+ await replay.next()
+ const at = Date.now()
+ await replay.closed
+ // one that never sends a frame that decrypts can't keep a slot the real phone needs for long
+ expect(Date.now() - at).toBeLessThan(2000)
+ })
+
+ it('takes at most two waiting connections from one address, and drops silent ones fast', async () => {
+ const { c, connect } = await paired({ limits: { firstFrameMs: 200 } })
+ const a = await raw(c.port()!), b = await raw(c.port()!)
+ const extra = await raw(c.port()!)
+ await extra.closed
+ await Promise.all([a.closed, b.closed])
+ const s = await connect()
+ expect((await s.request('hello', { schema: 1 })).type).toBe('ok')
+ })
+
+ it('answers ping with pong, and closes a session that stays quiet', async () => {
+ const { connect } = await paired({ limits: { idleMs: 300 } })
+ const s = await connect()
+ await s.send({ id: 'p1', type: 'ping', body: {} })
+ expect(await s.waitPush((m) => m.type === 'pong')).toMatchObject({ id: 'p1', type: 'pong' })
+ await s.raw.closed
+ })
+
+ it('rekeys after the byte limit and carries on', async () => {
+ const { connect, store } = await paired({ limits: { rekey: { bytes: 2000, ms: 3_600_000 } } })
+ for (let i = 0; i < 5; i++) store.createMeeting({ ...base, title: `Meeting ${i}`, startedAt: 1000 + i })
+ const s = await connect()
+ for (let i = 0; i < 6; i++) expect((await s.request('pull', { since: 0, limit: 50 })).type).toBe('ok')
+ })
+
+ it('a bad request gets an error reply, not a closed connection', async () => {
+ const { connect } = await paired()
+ const s = await connect()
+ expect(await s.request('pull', { since: -1 })).toMatchObject({ type: 'error', body: { code: 'bad-request' } })
+ expect(await s.request('nope', {})).toMatchObject({ type: 'error', body: { code: 'unknown-type' } })
+ expect(await s.request('hello', { schema: 2 })).toMatchObject({ type: 'error', body: { code: 'schema' } })
+ expect(await s.request('op', { kind: 'rename', meetingId: 'missing', title: 'x' })).toMatchObject({ type: 'error', body: { code: 'gone' } })
+ expect((await s.request('hello', { schema: 1 })).type).toBe('ok')
+ })
+
+ it('pushes changed after a store write', async () => {
+ const { store, connect } = await paired()
+ const s = await connect()
+ await s.request('hello', { appVersion: '1', schema: 1 })
+ store.createMeeting({ ...base, title: 'Fresh', startedAt: 5000 })
+ const pushed = await s.waitPush((m) => m.type === 'changed')
+ const cursor = (pushed.body as { cursor: number }).cursor
+ const pull = await s.request('pull', { since: cursor - 1, limit: 10 })
+ expect((pull.body as { changes: { record: { title: string } }[] }).changes[0].record.title).toBe('Fresh')
+ })
+
+ it('ops go through the desktop rules; a trash the desktop would refuse is refused', async () => {
+ let blocked = true
+ const trashed: string[] = []
+ const store = openStore(':memory:')
+ const { connect } = await paired({ store, ops: { notesRewrite: (id, mine) => store.setNotes(id, { mine }), trashBlocked: () => blocked, trashed: (id) => trashed.push(id) } })
+ const m = store.createMeeting({ ...base, title: 'Plum', startedAt: 1000 })
+ const s = await connect()
+ expect(await s.request('op', { kind: 'setMine', meetingId: m.id, text: 'from the phone', baseHash: notesHash('') })).toMatchObject({ type: 'ok', body: { applied: true } })
+ expect(store.notes(m.id).mine).toBe('from the phone')
+ expect(await s.request('op', { kind: 'trash', meetingId: m.id })).toMatchObject({ type: 'error', body: { code: 'busy' } })
+ blocked = false
+ expect(await s.request('op', { kind: 'trash', meetingId: m.id })).toMatchObject({ type: 'ok' })
+ expect(trashed).toEqual([m.id])
+ expect(store.meeting(m.id)?.trashedAt).not.toBeNull()
+ })
+
+ it('an upload sent twice makes one meeting, imported once after all of its audio', async () => {
+ const imported: { id: string; audio: string; notes: string }[] = []
+ const store = openStore(':memory:')
+ const { connect } = await paired({
+ store,
+ importRecording: async (meeting, audioPath, draft) => {
+ imported.push({ id: meeting.id, audio: readFileSync(audioPath).toString(), notes: draft.myNotes })
+ store.createMeeting({ ...base, title: meeting.title, startedAt: meeting.startedAt, source: 'audio-file' }, meeting.id)
+ },
+ })
+ const meeting = { id: 'phone-meeting-1', title: 'Standup in the kitchen', startedAt: 1000, endedAt: 61_000, attendees: [] }
+ const body = { meeting, myNotes: 'bring snacks', transcript: [{ startMs: 0, endMs: 900, text: 'made-up line' }] }
+ const audio = ['first part,', 'second part,', 'last part']
+ const chunk = (i: number) => ({ meetingId: meeting.id, chunk: Buffer.from(audio[i]).toString('base64'), index: i, of: audio.length, mime: 'audio/mp4' })
+ let s = await connect()
+ expect(await s.request('uploadMeeting', body)).toMatchObject({ type: 'ok', body: { accepted: true } })
+ expect(await s.request('uploadAudio', chunk(0))).toMatchObject({ type: 'ok', body: { received: 0 } })
+ // Wi-Fi drops mid-upload
+ s.close()
+ s = await connect()
+ expect(await s.request('uploadMeeting', body)).toMatchObject({ type: 'ok', body: { accepted: true } })
+ expect(await s.request('uploadAudio', chunk(1))).toMatchObject({ type: 'error', body: { code: 'order' } })
+ for (const i of [0, 1]) expect(await s.request('uploadAudio', chunk(i))).toMatchObject({ type: 'ok', body: { received: i } })
+ expect(imported).toEqual([])
+ expect(await s.request('uploadAudio', chunk(2))).toMatchObject({ type: 'ok', body: { received: 2, done: true, imported: true } })
+ expect(imported).toEqual([{ id: meeting.id, audio: audio.join(''), notes: 'bring snacks' }])
+ // sent once more (the reply was lost): nothing new
+ expect(await s.request('uploadMeeting', body)).toMatchObject({ type: 'ok', body: { accepted: true, imported: true } })
+ expect(await s.request('uploadAudio', chunk(2))).toMatchObject({ type: 'ok', body: { done: true } })
+ expect(imported).toHaveLength(1)
+ expect(store.db.prepare('SELECT COUNT(*) AS n FROM meetings WHERE id = ?').get(meeting.id)).toEqual({ n: 1 })
+ })
+
+ it('a phone sends WAV, which reaches the import as a .wav; a mime it does not know, or one that changes midway, is refused', async () => {
+ const paths: string[] = []
+ const store = openStore(':memory:')
+ const { connect } = await paired({
+ store,
+ importRecording: async (meeting, audioPath) => {
+ paths.push(audioPath)
+ store.createMeeting({ ...base, title: meeting.title, startedAt: meeting.startedAt, source: 'audio-file' }, meeting.id)
+ },
+ })
+ const meeting = { id: 'phone-meeting-wav', title: 'Hallway chat', startedAt: 1000, endedAt: 2000, attendees: [] }
+ const part = (index: number, mime: string) => ({ meetingId: meeting.id, chunk: Buffer.from(`made-up ${index}`).toString('base64'), index, of: 2, mime })
+ const s = await connect()
+ await s.request('uploadMeeting', { meeting, myNotes: '' })
+ expect(await s.request('uploadAudio', part(0, 'audio/ogg'))).toMatchObject({ type: 'error', body: { code: 'bad-request' } })
+ expect(await s.request('uploadAudio', part(0, 'audio/wav'))).toMatchObject({ type: 'ok', body: { received: 0 } })
+ expect(await s.request('uploadAudio', part(1, 'audio/mp4'))).toMatchObject({ type: 'error', body: { code: 'bad-request' } })
+ expect(await s.request('uploadAudio', part(1, 'audio/wav'))).toMatchObject({ type: 'ok', body: { done: true, imported: true } })
+ expect(paths).toHaveLength(1)
+ expect(paths[0].endsWith('.wav')).toBe(true)
+ })
+
+ it("an upload says the language it was spoken in: the import gets its code; one left out or made up is no language", async () => {
+ const languages: (string | undefined)[] = []
+ const store = openStore(':memory:')
+ const { connect } = await paired({
+ store,
+ importRecording: async (meeting) => {
+ languages.push(meeting.language)
+ store.createMeeting({ ...base, title: meeting.title, startedAt: meeting.startedAt, source: 'audio-file' }, meeting.id)
+ },
+ })
+ const s = await connect()
+ const send = async (id: string, language?: unknown) => {
+ await s.request('uploadMeeting', { meeting: { id, title: 'Made-up walk', startedAt: 1000, endedAt: 2000, attendees: [], language }, myNotes: '' })
+ await s.request('uploadAudio', { meetingId: id, chunk: Buffer.from('all of it').toString('base64'), index: 0, of: 1, mime: 'audio/mp4' })
+ }
+ await send('lang-1', 'de-DE')
+ await send('lang-2', 'nb-NO')
+ await send('lang-3')
+ await send('lang-4', 'not a language; rm -rf')
+ await send('lang-5', 42)
+ // whisper calls Norwegian Bokmål "no"
+ expect(languages).toEqual(['de', 'no', undefined, undefined, undefined])
+ })
+
+ it('an upload sent again while its import is still running waits for it, and is taken afresh if the import failed', async () => {
+ const store = openStore(':memory:')
+ let fail: (e: Error) => void = () => {}
+ let calls = 0
+ const { connect } = await paired({
+ store,
+ importRecording: async (meeting) => {
+ if (++calls === 1) return new Promise<void>((_, reject) => { fail = reject })
+ store.createMeeting({ ...base, title: meeting.title, startedAt: meeting.startedAt, source: 'audio-file' }, meeting.id)
+ },
+ })
+ const meeting = { id: 'phone-meeting-2', title: 'Walk and talk', startedAt: 1000, endedAt: 2000, attendees: [] }
+ const one = { meetingId: meeting.id, chunk: Buffer.from('all of it').toString('base64'), index: 0, of: 1, mime: 'audio/mp4' }
+ const a = await connect()
+ await a.request('uploadMeeting', { meeting, myNotes: '' })
+ const last = a.request('uploadAudio', one).catch((e: Error) => e)
+ await expect.poll(() => calls).toBe(1)
+ // the reply is lost: the phone comes back and sends it again while the import still runs
+ const b = await connect()
+ const again = b.request('uploadMeeting', { meeting, myNotes: '' })
+ await new Promise((r) => setTimeout(r, 50))
+ fail(new Error('disk full'))
+ expect(await again).toMatchObject({ type: 'ok', body: { accepted: true } })
+ expect(((await again).body as { imported?: boolean }).imported).toBeUndefined()
+ void last
+ expect(await b.request('uploadAudio', one)).toMatchObject({ type: 'ok', body: { done: true, imported: true } })
+ expect(store.meeting(meeting.id)).toBeDefined()
+ })
+
+ it('keeps at most four uploads open, and refuses ids Windows keeps for devices', async () => {
+ const { connect } = await paired()
+ const s = await connect()
+ const up = (id: string) => s.request('uploadMeeting', { meeting: { id, title: 'x', startedAt: 1, endedAt: 2, attendees: [] }, myNotes: '' })
+ for (const id of ['u1', 'u2', 'u3', 'u4']) expect((await up(id)).type).toBe('ok')
+ expect(await up('u5')).toMatchObject({ type: 'error', body: { code: 'busy' } })
+ for (const id of ['NUL', 'con', 'COM1', 'lpt9']) expect(await up(id)).toMatchObject({ type: 'error', body: { code: 'bad-request' } })
+ })
+
+ it('ask goes to the desktop Ask, with its scope', async () => {
+ const asked: unknown[] = []
+ const { connect } = await paired({ ask: async (q, scope) => { asked.push([q, scope]); return { answer: 'Tuesday [1]', sources: [{ n: 1, meetingId: 'm1', title: 'Plan', atMs: 1200, text: 'we ship tuesday' }] } } })
+ const s = await connect()
+ const r = await s.request('ask', { question: 'When do we ship?', scope: { folderId: 'f1' } })
+ expect(r).toMatchObject({ type: 'ok', body: { answer: 'Tuesday [1]', sources: [{ n: 1, meetingId: 'm1', title: 'Plan', atMs: 1200, text: 'we ship tuesday' }] } })
+ expect(asked).toEqual([['When do we ship?', { folderId: 'f1' }]])
+ })
+
+ it("an answer's sources carry the numbers its citations use, so the phone maps [n] exactly", () => {
+ const turn = [{ n: 2, meetingId: 'm2', title: 'Pear', startedAt: 1, atMs: null, excerpt: 'pears' }, { n: 5, meetingId: 'm5', title: 'Plum', startedAt: 1, atMs: 900 }]
+ expect(askSources(turn)).toEqual([{ n: 2, meetingId: 'm2', title: 'Pear', atMs: null, text: 'pears' }, { n: 5, meetingId: 'm5', title: 'Plum', atMs: 900, text: '' }])
+ })
+
+ it('streams a recording as audioChunks', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'companion-audio-'))
+ const file = join(dir, 'them.m4a')
+ const bytes = randomBytes(100_000)
+ writeFileSync(file, bytes)
+ const store = openStore(':memory:')
+ const m = store.createMeeting({ ...base, title: 'Audio', startedAt: 1000 })
+ const { connect } = await paired({ store, audioFiles: async (id) => (id === m.id ? [{ track: 'them', path: file }] : []) })
+ const s = await connect()
+ await s.send({ id: 'a1', type: 'audio', body: { meetingId: m.id, track: 'them' } })
+ const last = await s.waitPush((x) => x.type === 'audioChunk' && (x.body as { index: number; of: number }).index === (x.body as { of: number }).of - 1)
+ const chunks = s.pushes.filter((x) => x.type === 'audioChunk' && x.id === 'a1').map((x) => x.body as { chunk: string; index: number; of: number })
+ expect(chunks.map((x) => x.index)).toEqual([...Array((last.body as { of: number }).of).keys()])
+ expect(Buffer.concat(chunks.map((x) => Buffer.from(x.chunk, 'base64')))).toEqual(Buffer.from(bytes))
+ // the file's own kind, so the phone can name it and refuse what it can't play (ogg)
+ expect(s.pushes.find((x) => x.type === 'audioChunk' && x.id === 'a1')?.body).toMatchObject({ index: 0, ext: 'm4a' })
+ expect(await s.request('audio', { meetingId: m.id, track: 'me' })).toMatchObject({ type: 'error', body: { code: 'gone' } })
+ // in the Trash: not served
+ store.trashMeeting(m.id, 5000)
+ expect(await s.request('audio', { meetingId: m.id, track: 'them' })).toMatchObject({ type: 'error', body: { code: 'gone' } })
+ rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('logs ids and counts, never note text, names or keys', async () => {
+ const { store, connect, lines, phone } = await paired()
+ const m = store.createMeeting({ ...base, title: 'Secret project Zebra', startedAt: 1000 })
+ store.setNotes(m.id, { mine: 'confidential words' })
+ const s = await connect()
+ await s.request('pull', { since: 0, limit: 100 })
+ await s.request('op', { kind: 'setMine', meetingId: m.id, text: 'phone secret', baseHash: 'stale' })
+ const all = lines.join('\n')
+ for (const bad of ['Zebra', 'confidential', 'phone secret', 'Test iPhone', 'Test Mac', Buffer.from(phone.publicKey).toString('base64')]) expect(all).not.toContain(bad)
+ expect(all).toContain('COMPANION')
+ })
+
+ it('a leftover upload folder is emptied at start', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'companion-left-'))
+ const uploads = join(dir, 'companion-uploads')
+ const { mkdirSync } = await import('node:fs')
+ mkdirSync(uploads, { recursive: true })
+ writeFileSync(join(uploads, 'old.m4a'), 'x')
+ const c = await createCompanion({
+ store: openStore(':memory:'), userDataDir: dir, seal: (s) => s, open: (s) => s,
+ ask: async () => ({ answer: '', sources: [] }), importRecording: async () => {}, audioFiles: async () => [],
+ deviceName: () => 'Mac', log: () => {}, ops: { notesRewrite: () => {} }, host: '127.0.0.1', advertiser: { publish: () => {}, stop: () => {} },
+ })
+ open.push({ c, dir })
+ await expect.poll(() => existsSync(join(uploads, 'old.m4a'))).toBe(false)
+ })
+})
+
+describe('companion frames', () => {
+ it('a frame trickling in a byte at a time comes out whole, once', async () => {
+ const { FrameReader } = await import('../src/main/companion/frames')
+ const r = new FrameReader()
+ const payload = randomBytes(65535)
+ const wire = Buffer.concat([frame(payload), frame(Uint8Array.of(7))])
+ const out: Uint8Array[] = []
+ for (let i = 0; i < wire.length; i++) out.push(...r.push(wire.subarray(i, i + 1)))
+ expect(out.map((f) => Buffer.from(f))).toEqual([payload, Buffer.of(7)])
+ expect(r.waiting).toBe(0)
+ })
+})
diff --git a/app/test/helpers/companionClient.ts b/app/test/helpers/companionClient.ts
new file mode 100644
index 00000000..fe595d39
--- /dev/null
+++ b/app/test/helpers/companionClient.ts
@@ -0,0 +1,137 @@
+// A stand-in iPhone for the companion server tests: real localhost sockets, the phone's side of pairing and Noise KK.
+import { connect, type Socket } from 'node:net'
+import { cpaceRespond, pairKeys } from '../../src/main/companion/cpace'
+import { openBox, sealBox } from '../../src/main/companion/box'
+import { frame, FrameReader } from '../../src/main/companion/frames'
+import { NoiseKK, type KeyPair } from '../../src/main/companion/noise'
+import { SecureChannel, type Rekey } from '../../src/main/companion/session'
+
+const enc = new TextEncoder()
+const b64 = (b: Uint8Array) => Buffer.from(b).toString('base64')
+const unb64 = (s: unknown) => Uint8Array.from(Buffer.from(String(s), 'base64'))
+
+export type Raw = {
+ socket: Socket
+ next: (timeoutMs?: number) => Promise<Uint8Array>
+ send: (payload: Uint8Array) => void
+ sendJson: (o: object) => void
+ json: () => Promise<Record<string, unknown>>
+ /** resolves once the server has closed the connection */
+ closed: Promise<void>
+ onFrame?: (f: Uint8Array) => void
+}
+
+export async function raw(port: number): Promise<Raw> {
+ const socket = connect(port, '127.0.0.1')
+ await new Promise<void>((resolve, reject) => { socket.once('connect', resolve); socket.once('error', reject) })
+ const reader = new FrameReader()
+ const queue: Uint8Array[] = []
+ const waiting: { resolve: (f: Uint8Array) => void; reject: (e: Error) => void }[] = []
+ let gone = false
+ const r: Raw = {
+ socket,
+ closed: new Promise((resolve) => socket.on('close', () => resolve())),
+ next: (timeoutMs = 3000) => queue.length ? Promise.resolve(queue.shift()!) : gone ? Promise.reject(new Error('closed')) : new Promise((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error('timeout')), timeoutMs)
+ waiting.push({ resolve: (f) => { clearTimeout(t); resolve(f) }, reject: (e) => { clearTimeout(t); reject(e) } })
+ }),
+ send: (p) => socket.write(frame(p)),
+ sendJson: (o) => socket.write(frame(enc.encode(JSON.stringify(o)))),
+ json: async () => JSON.parse(new TextDecoder().decode(await r.next())),
+ }
+ socket.on('data', (d: Buffer) => {
+ for (const f of reader.push(d)) {
+ if (r.onFrame) r.onFrame(f)
+ else if (waiting.length) waiting.shift()!.resolve(f)
+ else queue.push(f)
+ }
+ })
+ socket.on('error', () => {})
+ socket.on('close', () => { gone = true; while (waiting.length) waiting.shift()!.reject(new Error('closed')) })
+ return r
+}
+
+export type PairResult = { result: Record<string, unknown>; desktop?: { key: Uint8Array; name: string; id: string } }
+
+/** The phone's side of pairing with this code; a wrong code still sends pairDone (sealed under its own key). */
+export async function pairAsPhone(port: number, code: string, phone: KeyPair, name = 'Test iPhone', o: { beforeDone?: () => Promise<void> } = {}): Promise<PairResult> {
+ const c = await raw(port)
+ try {
+ const phoneSession = crypto.getRandomValues(new Uint8Array(16))
+ c.sendJson({ type: 'pairHello', v: 1, phoneSession: b64(phoneSession), phoneName: name })
+ const start = await c.json()
+ if (start.type !== 'pairStart') return { result: start }
+ const desktopSession = unb64(start.desktopSession)
+ const sid = new Uint8Array([...desktopSession, ...phoneSession])
+ const ci = new Uint8Array([...enc.encode('yogurt-pair-v1'), ...desktopSession, ...phoneSession])
+ const { yb, isk } = cpaceRespond(code, ci, sid, unb64(start.ya))
+ c.sendJson({ type: 'pairReply', yb: b64(yb) })
+ const keys = pairKeys(isk)
+ const confirm = await c.json()
+ let desktop: PairResult['desktop']
+ try {
+ const v = JSON.parse(new TextDecoder().decode(openBox(keys.toPhone, unb64(confirm.box), enc.encode('pairConfirm'))))
+ desktop = { key: unb64(v.key), name: v.name, id: v.id }
+ } catch { /* wrong code */ }
+ await o.beforeDone?.()
+ const mine = enc.encode(JSON.stringify({ key: b64(phone.publicKey), name, id: 'phone-' + b64(phone.publicKey).slice(0, 8).replace(/[^\w]/g, 'x') }))
+ c.sendJson({ type: 'pairDone', box: b64(sealBox(keys.toDesktop, mine, enc.encode('pairDone'))) })
+ return { result: await c.json(), desktop }
+ } finally {
+ c.socket.destroy()
+ }
+}
+
+export type Phone = {
+ raw: Raw
+ request: (type: string, body?: object) => Promise<Record<string, unknown>>
+ /** messages that weren't replies to a request: changed pushes, audioChunks */
+ pushes: Record<string, unknown>[]
+ waitPush: (pred: (m: Record<string, unknown>) => boolean, timeoutMs?: number) => Promise<Record<string, unknown>>
+ send: (m: object) => Promise<void>
+ close: () => void
+}
+
+/** A Noise KK session as the phone (initiator). `msg1` replaces the first handshake message (a replay). */
+export async function session(port: number, phone: KeyPair, desktopKey: Uint8Array, rekey?: Rekey, o: { sent?: (msg1: Uint8Array) => void } = {}): Promise<Phone> {
+ const c = await raw(port)
+ const noise = new NoiseKK({ initiator: true, s: phone, rs: desktopKey, prologue: enc.encode('yogurt-v1') })
+ const msg1 = noise.writeMessage(new Uint8Array(0))
+ o.sent?.(msg1)
+ c.send(msg1)
+ noise.readMessage(await c.next())
+ const { send, recv } = noise.split()
+ const channel = new SecureChannel(c.socket, send, recv, Date.now, rekey)
+ const waiting = new Map<string, (m: Record<string, unknown>) => void>()
+ const pushes: Record<string, unknown>[] = []
+ const watchers: { pred: (m: Record<string, unknown>) => boolean; resolve: (m: Record<string, unknown>) => void }[] = []
+ c.onFrame = (f) => {
+ const m = channel.receive(f)
+ if (!m) return
+ const w = typeof m.id === 'string' && (m.type === 'ok' || m.type === 'error') ? waiting.get(m.id) : undefined
+ if (w) { waiting.delete(m.id as string); w(m); return }
+ pushes.push(m)
+ for (const x of [...watchers]) if (x.pred(m)) { watchers.splice(watchers.indexOf(x), 1); x.resolve(m) }
+ }
+ let n = 0
+ return {
+ raw: c, pushes,
+ send: (m) => channel.send(m),
+ request: (type, body = {}) => new Promise((resolve, reject) => {
+ const id = `r${++n}`
+ const t = setTimeout(() => reject(new Error(`timeout waiting for ${type}`)), 5000)
+ waiting.set(id, (m) => { clearTimeout(t); resolve(m) })
+ void c.closed.then(() => { clearTimeout(t); reject(new Error('closed')) })
+ channel.send({ id, type, body }).catch(reject)
+ }),
+ waitPush: (pred, timeoutMs = 3000) => {
+ const found = pushes.find(pred)
+ if (found) return Promise.resolve(found)
+ return new Promise((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error('no push')), timeoutMs)
+ watchers.push({ pred, resolve: (m) => { clearTimeout(t); resolve(m) } })
+ })
+ },
+ close: () => c.socket.destroy(),
+ }
+}
diff --git a/app/test/noteMerge.test.ts b/app/test/noteMerge.test.ts
index 2dfb5613..a508718e 100644
--- a/app/test/noteMerge.test.ts
+++ b/app/test/noteMerge.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { mergeNoteView } from '../src/renderer/src/noteMerge'
import type { NoteView } from '../src/shared/types'
+import { FROM_IPHONE } from '../src/shared/companion'
const view = (o: Partial<NoteView>): NoteView => ({ meetingId: 'm', mine: '', enhanced: '## A\n- Someone ships', edited: false, status: 'done', draft: '', peopleChanged: false, ...o })
@@ -32,4 +33,20 @@ describe('mergeNoteView: a note open on screen when it is written again for new
}
expect(mergeNoteView(view({ status: 'writing', enhanced: 'old text' }), view({ enhanced: 'successful replacement' })).view.enhanced).toBe('successful replacement')
})
+
+ describe('My notes changed on the iPhone while the note is open', () => {
+ it('nothing typed here since: the phone text shows', () => {
+ const merged = mergeNoteView(view({ mine: 'desk' }), view({ mine: 'from the phone', mineFrom: 'desk' }))
+ expect(merged.view.mine).toBe('from the phone')
+ expect(merged.resaveMine).toBeUndefined()
+ })
+ it('typed here and not saved yet: theirs stay, the phone text goes under a heading and is saved again', () => {
+ const merged = mergeNoteView(view({ mine: 'desk, typed more' }), view({ mine: 'from the phone', mineFrom: 'desk' }))
+ expect(merged.view.mine).toBe('desk, typed more' + FROM_IPHONE + 'from the phone')
+ expect(merged.resaveMine).toBe(true)
+ })
+ it('an ordinary update still keeps what they typed', () => {
+ expect(mergeNoteView(view({ mine: 'typing' }), view({ mine: 'older' })).view.mine).toBe('typing')
+ })
+ })
})
diff --git a/app/test/notes.test.ts b/app/test/notes.test.ts
index 7ef9cf8b..5460b96f 100644
--- a/app/test/notes.test.ts
+++ b/app/test/notes.test.ts
@@ -217,6 +217,15 @@ describe('hookNotes', () => {
expect(s.notes.pendingDraftId()).toBeUndefined()
expect(s.notes.view(s.m.id).saves?.mine).toEqual({ revision: 2, status: 'saved' })
})
+ it('My notes from the iPhone save as the next revision and tell an open editor what they replaced', () => {
+ const s = setup()
+ expect(s.notes.setMine(s.m.id, 'typed on the desktop', 3).status).toBe('saved')
+ expect(s.notes.phoneMine(s.m.id, 'typed on the phone')).toEqual({ revision: 4, status: 'saved' })
+ expect(s.store.notes(s.m.id).mine).toBe('typed on the phone')
+ expect(s.sent.at(-1)).toMatchObject({ mine: 'typed on the phone', mineFrom: 'typed on the desktop', saves: { mine: { revision: 4, status: 'saved' } } })
+ // the editor's next edit comes after it
+ expect(s.notes.setMine(s.m.id, 'both', 5).status).toBe('saved')
+ })
it('retains an oversized note in full without acknowledging a truncated save, then saves a shorter revision', () => {
const s = setup(), original = s.store.notes(s.m.id).mine
const full = 'x'.repeat(NOTES_MAX) + 'IMPORTANT-END-SENTINEL'
diff --git a/app/test/phoneGate.test.ts b/app/test/phoneGate.test.ts
new file mode 100644
index 00000000..f4dd2e2e
--- /dev/null
+++ b/app/test/phoneGate.test.ts
@@ -0,0 +1,38 @@
+import { createElement, useState } from 'react'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { afterEach, expect, it, vi } from 'vitest'
+import { PHONE_COMPANION, phoneCompanionOn } from '../src/shared/companion'
+import { companionWanted } from '../src/main/companion/gate'
+import { PhoneSettings } from '../src/renderer/src/components/PhoneSettings'
+import type { CompanionStatus } from '../src/shared/companion'
+
+vi.mock('react', async original => ({ ...await original<typeof import('react')>(), useState: vi.fn() }))
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
+
+const paired: CompanionStatus = { paired: { name: 'Test iPhone', lastSeen: 1 }, pairing: null, pairingClosed: null, error: null, connected: false, syncing: false }
+
+it('the iPhone companion is off until the iPhone app ships; YOGURT_PHONE=1 turns it on', () => {
+ expect(PHONE_COMPANION).toBe(false)
+ expect(phoneCompanionOn({})).toBe(false)
+ expect(phoneCompanionOn({ YOGURT_PHONE: '0' })).toBe(false)
+ expect(phoneCompanionOn({ YOGURT_PHONE: '1' })).toBe(true)
+})
+
+it('with the flag off the companion never starts, so nothing listens or advertises, paired phone or not', () => {
+ expect(companionWanted({}, false)).toBe(false)
+ expect(companionWanted({ YOGURT_FAKE_COMPANION: '1' }, true)).toBe(false)
+ // on: a real app starts it; fake mode only when a test asks
+ expect(companionWanted({ YOGURT_PHONE: '1' }, false)).toBe(true)
+ expect(companionWanted({ YOGURT_PHONE: '1' }, true)).toBe(false)
+ expect(companionWanted({ YOGURT_PHONE: '1', YOGURT_FAKE_COMPANION: '1' }, true)).toBe(true)
+})
+
+it('with the flag off Settings shows no Phone section, even for a paired phone', async () => {
+ const react = await vi.importActual<typeof import('react')>('react')
+ vi.mocked(useState).mockImplementation(react.useState).mockImplementationOnce(() => [paired, vi.fn()])
+ vi.stubGlobal('window', { yogurt: { phone: false } })
+ expect(renderToStaticMarkup(createElement(PhoneSettings))).toBe('')
+ vi.stubGlobal('window', { yogurt: { phone: true } })
+ vi.mocked(useState).mockImplementation(react.useState).mockImplementationOnce(() => [paired, vi.fn()])
+ expect(renderToStaticMarkup(createElement(PhoneSettings))).toContain('data-testid="phone-settings"')
+})
diff --git a/app/test/phoneSettings.test.ts b/app/test/phoneSettings.test.ts
new file mode 100644
index 00000000..53334b50
--- /dev/null
+++ b/app/test/phoneSettings.test.ts
@@ -0,0 +1,107 @@
+import { createElement, useState } from 'react'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { PhoneSettings } from '../src/renderer/src/components/PhoneSettings'
+import { LOCALES, setLanguage, t } from '../src/shared/i18n'
+import type { CompanionStatus } from '../src/shared/companion'
+
+vi.mock('react', async original => ({ ...await original<typeof import('react')>(), useState: vi.fn() }))
+const NOW = Date.UTC(2026, 10, 20, 12)
+// the section shows only while the iPhone companion is turned on (YOGURT_PHONE=1)
+beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(NOW); vi.stubGlobal('window', { yogurt: { phone: true } }) })
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllGlobals(); setLanguage('en') })
+
+const idle: CompanionStatus = { paired: null, pairing: null, pairingClosed: null, error: null, connected: false, syncing: false }
+const WIFI = 'Your iPhone talks to this computer only on the same Wi-Fi. Nothing goes through the internet.'
+
+/** renders with this status; `extra` are the next useState values after it (failed, busy, confirming) */
+async function render(status: CompanionStatus | null, ...extra: unknown[]) {
+ const react = await vi.importActual<typeof import('react')>('react')
+ const mock = vi.mocked(useState).mockImplementation(react.useState).mockImplementationOnce(() => [status, vi.fn()])
+ for (const v of extra) mock.mockImplementationOnce(() => [v, vi.fn()])
+ return renderToStaticMarkup(createElement(PhoneSettings)).replace(/<!-- -->/g, '').replace(/&#x27;/g, "'").replace(/&amp;/g, '&')
+}
+
+it('not paired: explains it and offers Pair a phone, with the Wi-Fi note', async () => {
+ const html = await render(idle)
+ expect(html).toContain('Phone')
+ expect(html).toContain('data-testid="phone-pair"')
+ expect(html).toContain('Pair a phone')
+ expect(html).toContain(WIFI)
+ expect(html).not.toContain('Unpair')
+})
+
+it('pairing: the six digits large in two groups, what to do with them, a countdown and Cancel', async () => {
+ const html = await render({ ...idle, pairing: { code: '482913', expiresAt: NOW + 102_000, attemptsLeft: 5 } })
+ expect(html).toMatch(/data-testid="phone-code"[^>]*>.*482.*913/)
+ expect(html).toContain('Open Yogurt on your iPhone and type this code')
+ expect(html).toContain('Code works for 1:42')
+ expect(html).toContain('data-testid="phone-cancel"')
+ expect(html).toContain(WIFI)
+ expect(html).not.toContain('data-testid="phone-pair"')
+})
+
+it('closed pairing and failures say why, and offer to start again', async () => {
+ for (const [s, text] of [
+ [{ ...idle, pairingClosed: 'tooMany' }, 'Too many wrong codes. Start pairing again.'],
+ [{ ...idle, pairingClosed: 'expired' }, 'The code ran out. Start pairing again.'],
+ [{ ...idle, error: 'listen' }, "Yogurt couldn't start pairing. Try again."],
+ ] as const) {
+ const html = await render(s as CompanionStatus)
+ expect(html).toContain(text)
+ expect(html).toContain('data-testid="phone-pair"')
+ }
+ // a start that failed without a reason from the companion
+ expect(await render(idle, true)).toContain("Yogurt couldn't start pairing. Try again.")
+})
+
+it('a keychain that will not open says so and offers no pairing', async () => {
+ const html = await render({ ...idle, error: 'keychain' })
+ expect(html).toContain("Yogurt couldn't reach this computer's secure storage, so it can't pair right now.")
+ expect(html).not.toContain('data-testid="phone-pair"')
+})
+
+it('paired: the phone, Connected or when it was last seen, and Unpair with an inline confirm', async () => {
+ const connected = await render({ ...idle, paired: { name: 'Test iPhone', lastSeen: NOW }, connected: true })
+ expect(connected).toContain('Test iPhone')
+ expect(connected).toContain('Connected')
+ expect(connected).toContain('phone-live-dot')
+ expect(connected).toContain('data-testid="phone-unpair"')
+ const away = await render({ ...idle, paired: { name: 'Test iPhone', lastSeen: NOW - 2 * 3600_000 } })
+ expect(away).toMatch(/Last seen 2\s?h(r\.?)? ago/)
+ expect(away).not.toContain('phone-live-dot')
+ const confirming = await render({ ...idle, paired: { name: 'Test iPhone', lastSeen: NOW } }, false, false, true)
+ expect(confirming).toContain('Unpair your iPhone? It keeps its copy until you pair again.')
+ expect(confirming).toContain('data-testid="phone-unpair-confirm"')
+ // a paired phone this computer can't listen for says so
+ expect(await render({ ...idle, paired: { name: 'Test iPhone', lastSeen: NOW }, error: 'listen' })).toContain('data-testid="phone-notice"')
+})
+
+const MAC_NETWORK = "Your iPhone can't see this computer. Allow Local Network for Yogurt in System Settings → Privacy & Security."
+const PC_NETWORK = "Your iPhone can't see this computer. Allow Yogurt through your firewall on private networks."
+
+it('an advert the network refused says how to let the iPhone see this computer, while pairing and once paired', async () => {
+ vi.stubGlobal('window', { yogurt: { phone: true, platform: 'darwin' } })
+ try {
+ const pairing = await render({ ...idle, error: 'network', pairing: { code: '482913', expiresAt: NOW + 102_000, attemptsLeft: 5 } })
+ expect(pairing).toContain(MAC_NETWORK)
+ expect(pairing).toContain('data-testid="phone-code"')
+ expect(await render({ ...idle, error: 'network', paired: { name: 'Test iPhone', lastSeen: NOW } })).toContain(MAC_NETWORK)
+ vi.stubGlobal('window', { yogurt: { phone: true, platform: 'win32' } })
+ expect(await render({ ...idle, error: 'network', paired: { name: 'Test iPhone', lastSeen: NOW } })).toContain(PC_NETWORK)
+ } finally { vi.stubGlobal('window', { yogurt: { phone: true } }) }
+})
+
+it('shows nothing when the companion is not running', async () => {
+ expect(await render(null)).toBe('')
+})
+
+it('translates the Phone section in every interface language', () => {
+ for (const { id } of LOCALES) {
+ setLanguage(id)
+ for (const key of ['Phone', 'Pair a phone', 'Open Yogurt on your iPhone and type this code', WIFI, 'Unpair your iPhone? It keeps its copy until you pair again.', MAC_NETWORK, PC_NETWORK]) {
+ expect(t(key).trim()).not.toBe('')
+ if (id !== 'en') expect(t(key)).not.toBe(key)
+ }
+ }
+})
diff --git a/app/test/savedTranscription.test.ts b/app/test/savedTranscription.test.ts
index cbb5cf9d..18a7689f 100644
--- a/app/test/savedTranscription.test.ts
+++ b/app/test/savedTranscription.test.ts
@@ -76,6 +76,25 @@ it('retains a complete original when a replacement finishes without usable words
await vi.waitFor(()=>expect(jobs.owns(id)).toBe(false));expect(store.segments(id).map(l=>l.text)).toEqual(['Original']);expect(store.meeting(id)?.transcriptionAgain).not.toBe(true);expect(summarize).not.toHaveBeenCalled()
})
+it('rewrites the notes of a phone recording once its transcript is replaced, then never again over them',async()=>{
+ const id=note().id;store.addSegments([line(id,0,300,'Phone line')]);store.setNotes(id,{enhanced:'Phone draft'});store.updateMeeting(id,{sourceId:`phone-draft:${id}`})
+ transcribe.mockImplementationOnce(async(_id,_tracks,options)=>{options.save([line(id,0,300,'Computer line')]);return true})
+ await jobs.start(id,true);await vi.waitFor(()=>expect(store.meeting(id)?.transcriptionState).toBe('done'))
+ expect(store.segments(id).map(s=>s.text)).toEqual(['Computer line']);expect(summarize).toHaveBeenCalledExactlyOnceWith(id)
+ expect(store.meeting(id)?.sourceId).toBe(`phone:${id}`)
+ transcribe.mockImplementationOnce(async(_id,_tracks,options)=>{options.save([line(id,0,300,'Again')]);return true})
+ await jobs.start(id,true);await vi.waitFor(()=>expect(store.segments(id)[0]?.text).toBe('Again'));expect(summarize).toHaveBeenCalledOnce()
+})
+
+it("a phone recording is transcribed in the language the phone said it was spoken in; other meetings follow the setting", async () => {
+ const phone=note().id;store.updateMeeting(phone,{language:'german',sourceId:`phone:${phone}`})
+ const other=note().id;store.updateMeeting(other,{language:'french'})
+ await jobs.start(phone);await vi.waitFor(()=>expect(store.meeting(phone)?.transcriptionState).toBe('done'))
+ await jobs.start(other);await vi.waitFor(()=>expect(store.meeting(other)?.transcriptionState).toBe('done'))
+ expect(transcribe.mock.calls[0][2].language).toBe('de')
+ expect(transcribe.mock.calls[1][2].language).toBeUndefined()
+})
+
it('leaves a meeting alone while its live transcript is still being finished (#127)',async()=>{
const id=note().id;store.updateMeeting(id,{transcriptionPending:true});let live=true
jobs=createSavedTranscriptions({store,ready:()=>model,recording:()=>recording,live:()=>live,tracks:async()=>({them:(async function*(){yield new Float32Array(1600)})()}),transcribe,summarize,changed})
diff --git a/ios/Fixtures/README.md b/ios/Fixtures/README.md
new file mode 100644
index 00000000..125be4e7
--- /dev/null
+++ b/ios/Fixtures/README.md
@@ -0,0 +1,27 @@
+# Crypto test vectors
+
+Shared by the desktop tests (`app/test/companionCpace.test.ts`, `app/test/companionNoise.test.ts`) and the
+YogurtKit Swift tests, so both sides are checked against the same published values.
+
+## noise-kk-vectors.json
+
+Only the `Noise_KK_25519_ChaChaPoly_BLAKE2b` entries, copied unchanged (empty `psks` fields dropped) and tagged with
+`source`:
+
+- cacophony: https://github.com/haskell-cryptography/cacophony/blob/8ee9d41e34a1a596cfa3ab12aa4069ff87dc1247/vectors/cacophony.txt
+ — public domain (The Unlicense).
+- snow: https://github.com/mcginty/snow/blob/8ac60f51cfe3e010c84f0a454cc575ad9204fa12/tests/vectors/snow.txt
+ — Apache-2.0 (snow is dual licensed Apache-2.0 / MIT).
+
+Format: the Noise test-vector format. `init_*`/`resp_*` are private keys, `messages[0..1]` are the handshake,
+the rest are transport messages alternating initiator, responder.
+
+## cpace-ristretto255-vectors.json
+
+From draft-irtf-cfrg-cpace-21 (April 2026), Appendix B.3 "Test vector for CPace using group ristretto255 and hash
+SHA-512", decoded from the draft's own BASE64 JSON blocks (B.3.1.1, B.3.9, B.3.11.1) and cross-checked against the
+hex listings. https://www.ietf.org/archive/id/draft-irtf-cfrg-cpace-21.txt — IETF Trust, BCP 78 / Revised BSD
+licence for code components.
+
+`ISK_IR` is the initiator/responder transcript (the one Yogurt uses); `ISK_SY` the ordered-concatenation one.
+`invalidPoints` must make `scalar_mult_vfy` fail (a non-canonical encoding and the identity).
diff --git a/ios/Fixtures/cpace-ristretto255-vectors.json b/ios/Fixtures/cpace-ristretto255-vectors.json
new file mode 100644
index 00000000..88fa2b1f
--- /dev/null
+++ b/ios/Fixtures/cpace-ristretto255-vectors.json
@@ -0,0 +1,33 @@
+{
+ "source": "draft-irtf-cfrg-cpace-21, Appendix B.3 (ristretto255, SHA-512), decoded from its BASE64 JSON blocks B.3.1.1, B.3.9, B.3.11.1",
+ "suite": "CPACE-RISTR255-SHA512",
+ "vectors": [
+ {
+ "name": "draft-21 B.3",
+ "PRS": "50617373776f7264",
+ "CI": "0b415f696e69746961746f720b425f726573706f6e646572",
+ "sid": "7e4b4791d6a8ef019b936c79fb7f2c57",
+ "generatorString": "11435061636552697374726574746f3235350850617373776f72646400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000180b415f696e69746961746f720b425f726573706f6e646572107e4b4791d6a8ef019b936c79fb7f2c57",
+ "generatorHash": "da6d3ddc8802fca9058755ffd3ebde08a9c2c74945901a258482a288b6663af06bf645c93cd1c51512307199c80e84908916d983b34af77205f90851a657ee27",
+ "g": "222b6b195fe84b1652badb6f6a3ae3d24341e7306967f0b8115b40d5698c7e56",
+ "ya": "da3d23700a9e5699258aef94dc060dfda5ebb61f02a5ea77fad53f4ff0976d08",
+ "ADa": "414461",
+ "Ya": "d6bac480f2c386c394efc7c47adb9925dcd2630b64f240c50f8d0eec482b9157",
+ "yb": "d2316b454718c35362d83d69df6320f38578ed5984651435e2949762d900b80d",
+ "ADb": "414462",
+ "Yb": "3ea7e0b19560d7c0b0f5734f63b955286dfa8232b5ebe63324e2d9e7433f7258",
+ "K": "80b69a8a76457ab6a4d7f887a4bf6b55a2f80ac19c333f917a05fc9887c8b40f",
+ "ISK_IR": "b69effbf61b51d56401c0f65601abe428de8206feaaf0e32198896dcae7b35cd2b38950a39dfd5d4a79164614c2984f7daa460b588c1e80c3fa2068af7900447",
+ "ISK_SY": "544199d71f62f8d9a1fee55727e24fe4a45844593c2b6013c4fa3969d0e5debb2244675c0b43397cbb68d342b01fc0f98fc961469a25134de9f0f813c1a57476"
+ }
+ ],
+ "scalarMult": {
+ "s": "7cd0e075fa7955ba52c02759a6c90dbbfc10e6d40aea8d283e407d88cf538a05",
+ "X": "2c3c6b8c4f3800e7aef6864025b4ed79bd599117e427c41bd47d93d654b4a51c",
+ "result": "7c13645fe790a468f62c39beb7388e541d8405d1ade69d1778c5fe3e7f6b600e"
+ },
+ "invalidPoints": [
+ "2b3c6b8c4f3800e7aef6864025b4ed79bd599117e427c41bd47d93d654b4a51c",
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ ]
+}
diff --git a/ios/Fixtures/noise-kk-vectors.json b/ios/Fixtures/noise-kk-vectors.json
new file mode 100644
index 00000000..4e3ced36
--- /dev/null
+++ b/ios/Fixtures/noise-kk-vectors.json
@@ -0,0 +1,74 @@
+{
+ "protocol": "Noise_KK_25519_ChaChaPoly_BLAKE2b",
+ "vectors": [
+ {
+ "source": "cacophony",
+ "protocol_name": "Noise_KK_25519_ChaChaPoly_BLAKE2b",
+ "init_prologue": "4a6f686e2047616c74",
+ "init_static": "e61ef9919cde45dd5f82166404bd08e38bceb5dfdfded0a34c8df7ed542214d1",
+ "init_ephemeral": "893e28b9dc6ca8d611ab664754b8ceb7bac5117349a4439a6b0569da977c464a",
+ "init_remote_static": "31e0303fd6418d2f8c0e78b91f22e8caed0fbe48656dcf4767e4834f701b8f62",
+ "resp_prologue": "4a6f686e2047616c74",
+ "resp_static": "4a3acbfdb163dec651dfa3194dece676d437029c62a408b4c5ea9114246e4893",
+ "resp_ephemeral": "bbdb4cdbd309f1a1f2e1456967fe288cadd6f712d65dc7b7793d5e63da6b375b",
+ "resp_remote_static": "6bc3822a2aa7f4e6981d6538692b3cdf3e6df9eea6ed269eb41d93c22757b75a",
+ "handshake_hash": "76dbc866183c8ee7363dbf0ebab8d6355010245f9817aa78359818a03a052586d7e8b4bb2ae5622a1a61212df90af04bb2b2cc189ce0e819ba0c4970c9f71805",
+ "messages": [
+ {
+ "payload": "4c756477696720766f6e204d69736573",
+ "ciphertext": "ca35def5ae56cec33dc2036731ab14896bc4c75dbb07a61f879f8e3afa4c7944f79a1d4b21fc3ea4a0c87213b8b4f0599d758682c26a3ae5e09195a3e742bc74"
+ },
+ {
+ "payload": "4d757272617920526f746862617264",
+ "ciphertext": "95ebc60d2b1fa672c1f46a8aa265ef51bfe38e7ccb39ec5be34069f144808843e20b1bf85731f75d7e21b5d54baaa66341de4292c3d42571c1bd7e7f1abe38"
+ },
+ {
+ "payload": "462e20412e20486179656b",
+ "ciphertext": "25bfaa58833b07cdd6af7c07f2c51daac681a8ac0a02dd373259bd"
+ },
+ {
+ "payload": "4361726c204d656e676572",
+ "ciphertext": "ef586cff556dec8ef0053871ff0d4bf3f2c72e842487ec6d1da69f"
+ },
+ {
+ "payload": "4a65616e2d426170746973746520536179",
+ "ciphertext": "3265d50513550a354425d0218ba1e5f25d4994ce8990e6964398dba5982dbcbd85"
+ },
+ {
+ "payload": "457567656e2042f6686d20766f6e2042617765726b",
+ "ciphertext": "f11c02d5c3223d7b9281b52e1b134962b91bc3bfbd1646354dab9fc19b66bf6c1e0a6f431e"
+ }
+ ]
+ },
+ {
+ "source": "snow",
+ "protocol_name": "Noise_KK_25519_ChaChaPoly_BLAKE2b",
+ "init_prologue": "5468657265206973206e6f20726967687420616e642077726f6e672e2054686572652773206f6e6c792066756e20616e6420626f72696e672e",
+ "init_static": "12e47144430c5bf5c0f69fa73361a8722412dc140f6de1112f5e0f43fb9c64f6",
+ "init_ephemeral": "537e15bf96ed04e5e9613187df0995a143b0630effad014aab2f816871d553a2",
+ "init_remote_static": "17cb0a578fd259cb5cf73cea091c6e7077ca8e2edf0f01885180c34d2c5a2b33",
+ "resp_prologue": "5468657265206973206e6f20726967687420616e642077726f6e672e2054686572652773206f6e6c792066756e20616e6420626f72696e672e",
+ "resp_static": "de970d8005d3964a1f48893e8cfb9936c53bc90b4cb3dd2e31d241681de2eed9",
+ "resp_ephemeral": "37de8cc7198a303a39bd3d73d4b791b9c39645fee96f13b07cb8d2dabd85db1a",
+ "resp_remote_static": "b31f662695f6667c054f84da03cdcea6a55413d3e3fa72c8e38198c16749356e",
+ "messages": [
+ {
+ "payload": "39b4623710c31b914b0bf1e1c461fe1a428a454d5494a7f31bec659052a615c9",
+ "ciphertext": "abb2d673d120817a9e7d02082fe7b1a4135c30a205f404285c76944599a2c8005eda999e24ce4a8d7c572b45121a85d8b7ebcd6481a15cc18b17a9c06e5a73be324bce6eb89bad3387bc9ecb5adb3b35"
+ },
+ {
+ "payload": "cf00ce6671fcace204f42ef84ee9e905e4bc908bca5d28ebbc3228d8867020db",
+ "ciphertext": "dcaaae4c4722044529dc8ab2b3ee13ed2c6524b3cb4eb053bc4e543f964a5c69acbac8ebf7f827661f0b7e3307eac7805846d6bd2387ae965b207be4a934f556b049e04077405cd1347acdc7d8a2078d"
+ },
+ {
+ "payload": "88a7f14d0bba7824b171aeff0b9795668eb247907d2f7bf33ea668abc72a1055",
+ "ciphertext": "0824757e82ea7a88821a4d9f757d076eafefb5a63679308192040bcf9d7410c31cd052bda6d7c95bf593fe437370a41d"
+ },
+ {
+ "payload": "10633cc890ca24e59981e7c49274f949eb2244c327bd083b64f5a2476ddff32a",
+ "ciphertext": "1abc48ed7b9b0e089e96ed9db64d67ac9050610a94ca9476728358e03923b2ced8240cc9f8685561a1561d8e742d531c"
+ }
+ ]
+ }
+ ]
+}
diff --git a/ios/Fixtures/noise-low-order-points.json b/ios/Fixtures/noise-low-order-points.json
new file mode 100644
index 00000000..75bcd521
--- /dev/null
+++ b/ios/Fixtures/noise-low-order-points.json
@@ -0,0 +1,12 @@
+{
+ "source": "X25519 points of small order (and their non-canonical encodings), as listed in libsodium's has_small_order() blocklist; a DH with any of them must fail",
+ "points": [
+ "0000000000000000000000000000000000000000000000000000000000000000",
+ "0100000000000000000000000000000000000000000000000000000000000000",
+ "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",
+ "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",
+ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
+ "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
+ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"
+ ]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 695f0bdd..dee48da8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -15,6 +15,9 @@ importers:
app:
dependencies:
+ bonjour-service:
+ specifier: 1.4.4
+ version: 1.4.4
chrono-node:
specifier: 2.10.3
version: 2.10.3
@@ -24,6 +27,9 @@ importers:
ical.js:
specifier: 2.2.1
version: 2.2.1
+ libsodium-wrappers-sumo:
+ specifier: 0.8.4
+ version: 0.8.4
node-llama-cpp:
specifier: 3.22.1
version: 3.22.1(patch_hash=fb1b72ef61aee31b92af3fbf2624ad8cd9db513628681b7d141f463433c6ef4c)([email protected])
@@ -530,6 +536,9 @@ packages:
'@kwsites/[email protected]':
resolution: {integrity: sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==}
+ '@leichtgewicht/[email protected]':
+ resolution: {integrity: sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==}
+
'@malept/[email protected]':
resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}
engines: {node: '>= 12.13.0'}
@@ -1228,6 +1237,9 @@ packages:
resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}
+ resolution: {integrity: sha512-jCZcVv7eoc4QesRscwEZtSROBen+6LpKAmBIsQYQrsAeVHLyMXWX/t6eIV5KiRZYNUBl8eVqImEEMQ8L5+c/Kw==}
+
resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
@@ -1439,6 +1451,10 @@ packages:
resolution: {integrity: sha512-EAw1f2iGkICmUvAVBOjm7v5mxJdB7/+OZSycHFhKBimiTkCXtvkCC6wBKzHo7ZQYi58C2MmwIleRbgRnROlK2Q==}
+ resolution: {integrity: sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==}
engines: {node: '>=12'}
@@ -1844,6 +1860,12 @@ packages:
resolution: {integrity: sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==}
+ resolution: {integrity: sha512-TMtHShQfVVsaxDygyapvUC3o7YsPgXa/hRWeIgzyFz6w5k/1hirGptCxp1U7XwW3rCskaTTYKgV10v86UiGgNw==}
+
+ resolution: {integrity: sha512-ql7hcgulKZ3ekfa2DGAogcCKsWU0diA/0nArz1CFzh93WQdb46/Kj18ka/Hifq6uA3Ush34Pc6vU/6HXeRwUkg==}
+
resolution: {integrity: sha512-AnrXnE2/OF9PHCyFg0RSqsnQTzV991XaZA/buhFDoc58xU7rhSCDgCz/09Lqpsn4MpoPHt7TRAXV1kWZypFVsA==}
@@ -2114,6 +2136,10 @@ packages:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
+ resolution: {integrity: sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==}
+ hasBin: true
+
resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -2566,6 +2592,9 @@ packages:
resolution: {integrity: sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==}
engines: {node: '>=6.0.0'}
+ resolution: {integrity: sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==}
+
resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}
@@ -3182,6 +3211,8 @@ snapshots:
'@kwsites/[email protected]': {}
+ '@leichtgewicht/[email protected]': {}
+
'@malept/[email protected]':
dependencies:
cross-spawn: 7.0.6
@@ -3790,6 +3821,11 @@ snapshots:
+ dependencies:
+ fast-deep-equal: 3.1.3
+ multicast-dns: 7.2.5
+
optional: true
@@ -4006,6 +4042,10 @@ snapshots:
- electron-builder-squirrel-windows
- supports-color
+ dependencies:
+ '@leichtgewicht/ip-codec': 2.0.5
+
dependencies:
dotenv: 16.6.1
@@ -4491,6 +4531,12 @@ snapshots:
+
+ dependencies:
+ libsodium-sumo: 0.8.4
+
@@ -4695,6 +4741,11 @@ snapshots:
+ dependencies:
+ dns-packet: 5.6.1
+ thunky: 1.1.0
+
@@ -5221,6 +5272,8 @@ snapshots:
mkdirp: 0.5.6
rimraf: 2.6.3
+
dependencies:
semver: 5.7.2