Skip to content

Commit e13a6b5

Browse files
aneymclaude
andcommitted
fix(mobile): offline cache and outbox keep order and stay consistent
Review found races and dropped writes in the offline sync change. - Disconnect saves the committed projection and cursor pair, so a cold restart never resumes past events the cache does not hold. - Streaming updates are no longer queued while a run is active, and the persist guard is gone, so Stop's repair of an expanded thread reaches the cache. The repair starts from the newest snapshot handed to it. - Queued messages sort by enqueue ordinal or, without one, creation time. Load no longer rewrites legacy records, so a partial load or failed write cannot reorder sends after a restart. - One write lock serializes SQLite writers; exclusive transactions open their own connection with no busy handler. - Pull request pruning deletes cache metadata explicitly, since the transaction connection does not enforce the cascade. - Prefetch counts a thread as refreshed only when its projection is at least as new as the shell, not when a retained snapshot says live. - Pending rows relabel on connection changes; error and unsupported states ask to reconnect instead of promising to load. - The composer send guard no longer uses try/finally, which the React Compiler skipped. Claude Opus 5.5 via Claude Code. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent adbfed5 commit e13a6b5

9 files changed

Lines changed: 92 additions & 106 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2644,6 +2644,7 @@ export const ThreadFeed = memo(function ThreadFeed({
26442644
worktreeSetup: props.worktreeSetup,
26452645
setupWorkingStartedAt: props.setupWorkingStartedAt,
26462646
dispatchingMessageId: props.dispatchingMessageId,
2647+
connected: props.connectionState === "connected",
26472648
unsettledTurnId,
26482649
copiedRowId,
26492650
expandedWorkGroups,

‎apps/mobile/src/features/threads/threadContentPresentation.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ describe("thread content presentation", () => {
2525
).toEqual({
2626
kind: "unavailable",
2727
title: "Not downloaded yet",
28-
detail: "It will load when you’re back online.",
28+
detail: "Reconnect this environment to load the conversation.",
2929
});
3030
});
3131
});

‎apps/mobile/src/features/threads/threadContentPresentation.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ export function projectThreadContentPresentation(input: {
4242
return {
4343
kind: "unavailable",
4444
title: "Not downloaded yet",
45-
detail: "It will load when you’re back online.",
45+
detail:
46+
input.connectionState === "error" || input.connectionState === "unsupported"
47+
? "Reconnect this environment to load the conversation."
48+
: "It will load when you’re back online.",
4649
};
4750
}

‎apps/mobile/src/persistence/mobile-database.ts‎

Lines changed: 44 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
55
import * as Option from "effect/Option";
66
import * as Queue from "effect/Queue";
77
import * as Schema from "effect/Schema";
8+
import * as Semaphore from "effect/Semaphore";
89
import type { SQLiteDatabase } from "expo-sqlite";
910

1011
import {
@@ -341,6 +342,8 @@ const makeAvailable = Effect.gen(function* () {
341342
catch: databaseError("migrate"),
342343
});
343344

345+
// Exclusive transactions get their own connection with no busy handler; overlapping writes fail as locked.
346+
const writeLock = yield* Semaphore.make(1);
344347
const budgetRequests = yield* Queue.sliding<void>(1);
345348
let budgetOutboxLoaded = false;
346349
const budgetProtectedThreadKeys = new Set<string>();
@@ -358,16 +361,19 @@ const makeAvailable = Effect.gen(function* () {
358361
})
359362
: Promise.resolve({ evicted: 0, bytes: 0 }),
360363
catch: databaseError("enforce-thread-cache-budget"),
361-
}).pipe(Effect.catch((error) => Effect.logWarning(error)));
364+
}).pipe(
365+
writeLock.withPermits(1),
366+
Effect.catch((error) => Effect.logWarning(error)),
367+
);
362368
}
363369
}).pipe(Effect.forkScoped);
364370

365371
return MobileDatabase.of({
366-
loadCache: Effect.fn("MobileDatabase.loadCache")((environmentId, kind, cacheKey) =>
367-
Effect.tryPromise({
368-
try: async () => {
369-
const now = Date.now();
370-
const row = await database.getFirstAsync<{
372+
loadCache: Effect.fn("MobileDatabase.loadCache")(function* (environmentId, kind, cacheKey) {
373+
const now = Date.now();
374+
const row = yield* Effect.tryPromise({
375+
try: () =>
376+
database.getFirstAsync<{
371377
readonly payload: string;
372378
readonly accessedAt: number;
373379
}>(
@@ -380,22 +386,25 @@ const makeAvailable = Effect.gen(function* () {
380386
kind,
381387
cacheKey,
382388
now - 30 * 24 * 60 * 60_000,
383-
);
384-
if (kind === "thread" && row && row.accessedAt <= now - 60_000) {
385-
await database.runAsync(
389+
),
390+
catch: databaseError("load-cache"),
391+
});
392+
if (kind === "thread" && row && row.accessedAt <= now - 60_000) {
393+
yield* Effect.tryPromise({
394+
try: () =>
395+
database.runAsync(
386396
`UPDATE client_cache_meta SET accessed_at = ?
387397
WHERE environment_id = ? AND kind = 'thread' AND cache_key = ? AND accessed_at <= ?`,
388398
now,
389399
environmentId,
390400
cacheKey,
391401
now - 60_000,
392-
);
393-
}
394-
return row;
395-
},
396-
catch: databaseError("load-cache"),
397-
}).pipe(Effect.map((row) => Option.fromNullishOr(row?.payload))),
398-
),
402+
),
403+
catch: databaseError("load-cache"),
404+
}).pipe(writeLock.withPermits(1));
405+
}
406+
return Option.fromNullishOr(row?.payload);
407+
}),
399408
listCache: Effect.fn("MobileDatabase.listCache")((kind) =>
400409
Effect.tryPromise({
401410
try: () =>
@@ -422,7 +431,7 @@ const makeAvailable = Effect.gen(function* () {
422431
Effect.tryPromise({
423432
try: () => enforceThreadCacheBudget(database, input),
424433
catch: databaseError("enforce-thread-cache-budget"),
425-
}),
434+
}).pipe(writeLock.withPermits(1)),
426435
),
427436
setThreadCacheProtection: Effect.fn("MobileDatabase.setThreadCacheProtection")((input) =>
428437
Effect.sync(() => {
@@ -474,9 +483,7 @@ const makeAvailable = Effect.gen(function* () {
474483
kind === "thread" ? (sourceUpdatedAt ?? null) : null,
475484
);
476485
if (kind === "pull-request") {
477-
await transaction.runAsync(
478-
`DELETE FROM client_cache WHERE environment_id = ? AND kind = 'pull-request'
479-
AND cache_key IN (
486+
const pruned = `cache_key IN (
480487
SELECT cache_key FROM (
481488
SELECT cache_key, updated_at,
482489
ROW_NUMBER() OVER (ORDER BY updated_at DESC, cache_key) AS position,
@@ -485,17 +492,24 @@ const makeAvailable = Effect.gen(function* () {
485492
) AS total_bytes
486493
FROM client_cache WHERE environment_id = ? AND kind = 'pull-request'
487494
) WHERE position > 256 OR total_bytes > 33554432 OR updated_at < ?
488-
)`,
489-
environmentId,
490-
environmentId,
491-
Date.now() - 30 * 24 * 60 * 60_000,
492-
);
495+
)`;
496+
const cutoff = Date.now() - 30 * 24 * 60 * 60_000;
497+
// The transaction connection does not enforce foreign keys, so the cascade never runs.
498+
for (const table of ["client_cache_meta", "client_cache"]) {
499+
await transaction.runAsync(
500+
`DELETE FROM ${table} WHERE environment_id = ? AND kind = 'pull-request' AND ${pruned}`,
501+
environmentId,
502+
environmentId,
503+
cutoff,
504+
);
505+
}
493506
}
494507
};
495508
await database.withExclusiveTransactionAsync(save);
496509
},
497510
catch: databaseError("save-cache"),
498511
}).pipe(
512+
writeLock.withPermits(1),
499513
Effect.andThen(() =>
500514
kind === "thread" ? Queue.offer(budgetRequests, undefined) : Effect.void,
501515
),
@@ -513,7 +527,7 @@ const makeAvailable = Effect.gen(function* () {
513527
cacheKey,
514528
),
515529
catch: databaseError("remove-cache"),
516-
}).pipe(Effect.asVoid),
530+
}).pipe(writeLock.withPermits(1), Effect.asVoid),
517531
),
518532
clearCacheKind: Effect.fn("MobileDatabase.clearCacheKind")((environmentId, kind) =>
519533
Effect.tryPromise({
@@ -524,19 +538,19 @@ const makeAvailable = Effect.gen(function* () {
524538
kind,
525539
),
526540
catch: databaseError("clear-cache-kind"),
527-
}).pipe(Effect.asVoid),
541+
}).pipe(writeLock.withPermits(1), Effect.asVoid),
528542
),
529543
clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")((environmentId) =>
530544
Effect.tryPromise({
531545
try: () =>
532546
database.runAsync("DELETE FROM client_cache WHERE environment_id = ?", environmentId),
533547
catch: databaseError("clear-environment-cache"),
534-
}).pipe(Effect.asVoid),
548+
}).pipe(writeLock.withPermits(1), Effect.asVoid),
535549
),
536550
clearAllCaches: Effect.tryPromise({
537551
try: () => database.runAsync("DELETE FROM client_cache"),
538552
catch: databaseError("clear-all-caches"),
539-
}).pipe(Effect.asVoid),
553+
}).pipe(writeLock.withPermits(1), Effect.asVoid),
540554
inspectCaches: Effect.tryPromise({
541555
try: () =>
542556
database.getAllAsync<unknown>(`
@@ -584,7 +598,7 @@ const makeAvailable = Effect.gen(function* () {
584598
updatedAt,
585599
),
586600
catch: databaseError("save-preferences"),
587-
}).pipe(Effect.asVoid),
601+
}).pipe(writeLock.withPermits(1), Effect.asVoid),
588602
),
589603
});
590604
});

‎apps/mobile/src/state/thread-outbox-manager.ts‎

Lines changed: 4 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -88,45 +88,15 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
8888
);
8989
nextEnqueueOrdinal = Math.max(
9090
nextEnqueueOrdinal,
91-
...result.messages.map((message) => message.enqueueOrdinal ?? 0),
92-
);
93-
const legacy = recovered
94-
.filter((message) => message.enqueueOrdinal === undefined)
95-
.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt));
96-
const firstOrdinal = Math.min(
97-
...result.messages.flatMap((message) =>
98-
message.enqueueOrdinal === undefined ? [] : [message.enqueueOrdinal],
99-
),
100-
...currentMessages().flatMap((message) =>
101-
message.enqueueOrdinal === undefined ? [] : [message.enqueueOrdinal],
91+
...result.messages.map(
92+
(message) => message.enqueueOrdinal ?? Date.parse(message.createdAt),
10293
),
10394
);
104-
const legacyStart = Number.isFinite(firstOrdinal) ? firstOrdinal - legacy.length : 0;
105-
const backfilled = new Map(
106-
legacy.map((message, index) => [
107-
message.messageId,
108-
{ ...message, enqueueOrdinal: legacyStart + index },
109-
]),
110-
);
111-
nextEnqueueOrdinal = Math.max(
112-
nextEnqueueOrdinal,
113-
...[...backfilled.values()].map((message) => message.enqueueOrdinal ?? 0),
114-
);
115-
await Promise.all(
116-
[...backfilled.values()].map(async (message) => {
117-
try {
118-
await options.storage.write(message);
119-
} catch (cause) {
120-
warn("[thread-outbox] failed to backfill message ordinal", cause);
121-
}
122-
}),
123-
);
124-
const loaded = recovered.map((message) => backfilled.get(message.messageId) ?? message);
125-
if (loaded.length > 0) {
95+
if (recovered.length > 0) {
12696
const latest = currentMessages();
12797
const latestIds = new Set(latest.map((message) => message.messageId));
12898
setMessages([
129-
...loaded.filter(
99+
...recovered.filter(
130100
(message) => !latestIds.has(message.messageId) && !revisions.has(message.messageId),
131101
),
132102
...latest,

‎apps/mobile/src/state/thread-outbox-model.ts‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage {
139139
return message;
140140
}
141141

142+
// Ordinals are enqueue timestamps, so messages saved before ordinals existed sort by creation time.
143+
function queuedMessageOrder(message: QueuedThreadMessage): number {
144+
return message.enqueueOrdinal ?? Date.parse(message.createdAt);
145+
}
146+
142147
export function groupQueuedThreadMessages(
143148
messages: ReadonlyArray<QueuedThreadMessage>,
144149
): Record<string, ReadonlyArray<QueuedThreadMessage>> {
@@ -153,23 +158,17 @@ export function groupQueuedThreadMessages(
153158
(grouped[threadKey] ??= []).push(message);
154159
}
155160
for (const queue of Object.values(grouped)) {
156-
queue.sort((left, right) => {
157-
if (left.enqueueOrdinal !== undefined && right.enqueueOrdinal !== undefined) {
158-
return (
159-
left.enqueueOrdinal - right.enqueueOrdinal ||
160-
left.createdAt.localeCompare(right.createdAt)
161-
);
162-
}
163-
if (left.enqueueOrdinal !== undefined) return -1;
164-
if (right.enqueueOrdinal !== undefined) return 1;
165-
return Date.parse(left.createdAt) - Date.parse(right.createdAt);
166-
});
161+
queue.sort(
162+
(left, right) =>
163+
queuedMessageOrder(left) - queuedMessageOrder(right) ||
164+
left.createdAt.localeCompare(right.createdAt),
165+
);
167166
}
168167
return Object.fromEntries(
169168
Object.entries(grouped).sort(
170169
([, left], [, right]) =>
171-
(left[0]?.enqueueOrdinal ?? Date.parse(left[0]?.createdAt ?? "")) -
172-
(right[0]?.enqueueOrdinal ?? Date.parse(right[0]?.createdAt ?? "")),
170+
(left[0] === undefined ? Number.NaN : queuedMessageOrder(left[0])) -
171+
(right[0] === undefined ? Number.NaN : queuedMessageOrder(right[0])),
173172
),
174173
);
175174
}

‎apps/mobile/src/state/thread-prefetch.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { persistEnvironmentThreadSnapshots } from "@t3tools/client-runtime/state/threads";
22
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/models";
33
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4+
import * as DateTime from "effect/DateTime";
45
import * as Effect from "effect/Effect";
6+
import * as Option from "effect/Option";
57
import { AsyncResult, Atom } from "effect/reactivity";
68
import { AppState } from "react-native";
79

@@ -69,7 +71,11 @@ function waitForThread(target: PrefetchTarget, signal: AbortSignal): Promise<boo
6971
finish();
7072
} else if (
7173
value._tag === "Some" &&
72-
(value.value.status === "live" || value.value.status === "deleted")
74+
(value.value.status === "deleted" ||
75+
(value.value.status === "live" &&
76+
Option.isSome(value.value.data) &&
77+
DateTime.toEpochMillis(value.value.data.value.thread.updatedAt) >=
78+
Date.parse(target.updatedAt)))
7379
) {
7480
finish(true);
7581
}

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -511,11 +511,9 @@ export function useThreadComposerState() {
511511
) => {
512512
if (sendingMessageRef.current) return null;
513513
sendingMessageRef.current = true;
514-
try {
515-
return await sendMessageImpl(followUpOverride, beforeDispatch);
516-
} finally {
514+
return sendMessageImpl(followUpOverride, beforeDispatch).finally(() => {
517515
sendingMessageRef.current = false;
518-
}
516+
});
519517
};
520518

521519
const sendMessageImpl = async (

0 commit comments

Comments
 (0)