@@ -1,4 +1,7 @@
11 import { describe, expect, test } from "bun:test";
2+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
25 import type {
36 AssistantMessage,
47 Message,
@@ -86,6 +89,31 @@ function loadSessionOrThrow(db: ReturnType<typeof openDatabase>, id: string) {
8689 return session;
8790 }
8891
92+async function waitForChildStdout(
93+ stdout: ReadableStream<Uint8Array> | number | null,
94+ needle: string,
95+): Promise<void> {
96+ if (!(stdout instanceof ReadableStream)) {
97+ throw new Error("Expected child stdout to be piped");
98+ }
99+
100+ const reader = stdout.getReader();
101+ const decoder = new TextDecoder();
102+ let output = "";
103+
104+ while (!output.includes(needle)) {
105+ const { done, value } = await reader.read();
106+ if (done) {
107+ break;
108+ }
109+ output += decoder.decode(value, { stream: true });
110+ }
111+
112+ if (!output.includes(needle)) {
113+ throw new Error(`Child exited before emitting ${JSON.stringify(needle)}`);
114+ }
115+}
116+
89117 // ---------------------------------------------------------------------------
90118 // Tests
91119 // ---------------------------------------------------------------------------
@@ -205,6 +233,17 @@ describe("session persistence", () => {
205233 });
206234 });
207235
236+describe("database initialization", () => {
237+ test("openDatabase enables a busy timeout for transient writer contention", () => {
238+ const db = openDatabase(":memory:");
239+
240+ const row = db.query<{ timeout: number }, []>("PRAGMA busy_timeout").get();
241+
242+ expect(row?.timeout).toBeGreaterThan(0);
243+ db.close();
244+ });
245+});
246+
208247 describe("message persistence and turn numbering", () => {
209248 test("first user message gets turn 1", () => {
210249 const db = openDatabase(":memory:");
@@ -328,6 +367,73 @@ describe("message persistence and turn numbering", () => {
328367 expect(updated.updatedAt).toBeGreaterThanOrEqual(before);
329368 db.close();
330369 });
370+
371+ test("appendMessage when another writer commits first waits and assigns the next turn", async () => {
372+ const tempDir = mkdtempSync(join(tmpdir(), "mini-coder-session-test-"));
373+ const dbPath = join(tempDir, "session.db");
374+ const lockScriptPath = join(tempDir, "hold-lock.ts");
375+ const db = openDatabase(dbPath);
376+ const session = createSession(db, { cwd: "/tmp/test" });
377+
378+ writeFileSync(
379+ lockScriptPath,
380+ [
381+ 'import { Database } from "bun:sqlite";',
382+ "const dbPath = process.argv[2];",
383+ "const sessionId = process.argv[3];",
384+ 'if (!dbPath || !sessionId) throw new Error("missing args");',
385+ "const db = new Database(dbPath);",
386+ 'db.run("PRAGMA journal_mode = WAL");',
387+ 'db.run("BEGIN IMMEDIATE");',
388+ "const now = Date.now();",
389+ 'db.run("INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)", [',
390+ " sessionId,",
391+ " 1,",
392+ ' JSON.stringify({ role: "user", content: "locked", timestamp: now }),',
393+ " now,",
394+ "]);",
395+ 'db.run("UPDATE sessions SET updated_at = ? WHERE id = ?", [now, sessionId]);',
396+ 'console.log("locked");',
397+ "await Bun.sleep(250);",
398+ 'db.run("COMMIT");',
399+ "db.close();",
400+ "",
401+ ].join("\n"),
402+ "utf-8",
403+ );
404+
405+ const child = Bun.spawn(
406+ [process.execPath, lockScriptPath, dbPath, session.id],
407+ {
408+ stdout: "pipe",
409+ stderr: "pipe",
410+ },
411+ );
412+
413+ try {
414+ await waitForChildStdout(child.stdout, "locked");
415+
416+ const turn = appendMessage(db, session.id, makeUser("after lock"));
417+ expect(turn).toBe(2);
418+
419+ const exitCode = await child.exited;
420+ const stderr = child.stderr
421+ ? await new Response(child.stderr).text()
422+ : "";
423+ expect({ exitCode, stderr }).toEqual({ exitCode: 0, stderr: "" });
424+
425+ const turns = db
426+ .query<{ turn: number | null }, [string]>(
427+ "SELECT turn FROM messages WHERE session_id = ? ORDER BY id",
428+ )
429+ .all(session.id)
430+ .map((row) => row.turn);
431+ expect(turns).toEqual([1, 2]);
432+ } finally {
433+ db.close();
434+ rmSync(tempDir, { recursive: true, force: true });
435+ }
436+ });
331437 });
332438
333439 describe("undo", () => {