feat(sync): bounded tail-first thread sync (v2) with media externalization and transport negotiation #3849
Closedsnipemanmike(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromrefs/pull/3849/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- @@ -16,3 +18,10 @@16181719 const httpClientLayer = remoteHttpClientLayer(fetch);182021+// RN gzip codec for the /ws RPC (Fix 1). pako runs synchronously on the JS22+// thread; fine for one-shot thread sync.23+const pakoCodec: CompressionCodec = {24+ compressSync: (b) => pako.gzip(b),25+ decompressSync: (b) => pako.inflate(b),26+ threshold: 1024,27+};apps/mobile/src/features/threads/ThreadFeed.tsx line 168OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -149,4 +152,17 @@149- const uri = useAssetUrl(props.environmentId, {150- _tag: "attachment",151- attachmentId: props.attachmentId,152- });152+ const [requested, setRequested] = useState(false);153+ const didOpen = useRef(false);154+ const uri = useAssetUrl(155+ props.environmentId,156+ requested157+ ? {158+ _tag: "attachment",159+ attachmentId: props.attachmentId,160+ }161+ : null,162+ );163+164+ useEffect(() => {165+ if (uri === null || didOpen.current) return;166+ didOpen.current = true;167+ props.onPressImage(uri);168+ }, [props.onPressImage, uri]);@@ -0,0 +1,2 @@1+virtual-store-dir=C:/t3s2+virtual-store-dir-max-length=28@@ -1240,0 +1456,21 @@1456+ activityId: oldestActivity.id,1457+ },1458+ },1459+ hasOlderMessages: snapshot.head.counts.messages > built.messages.length,1460+ hasOlderActivities: snapshot.head.counts.activities > built.activities.length,1461+ },1462+ ];1463+ },1464+ ).pipe(1465+ Effect.mapError(1466+ (cause) =>1467+ new OrchestrationGetSnapshotError({1468+ message: `Failed to prepare thread tail ${input.threadId}`,1469+ cause,1470+ }),1471+ ),1472+ );1473+1474+ const lastSentSequence = yield* Ref.make(snapshot.watermark);1475+ const liveEvents = Stream.fromQueue(liveQueue).pipe(1476+ Stream.filter((event) => event.sequence > snapshot.watermark),@@ -1240,0 +1373,21 @@1373+ const streamHead: ReadonlyArray<OrchestrationThreadV2StreamItem> = yield* Effect.gen(1374+ function* () {1375+ if (1376+ input.sinceSequence !== undefined &&1377+ input.historyEpoch === snapshot.historyEpoch &&1378+ input.sinceSequence <= snapshot.watermark1379+ ) {1380+ const rawCatchup = yield* Stream.runCollect(1381+ orchestrationEngine.readThreadEvents(1382+ input.threadId,1383+ input.sinceSequence,1384+ THREAD_CATCHUP_MAX_EVENTS + 1,1385+ ),1386+ ).pipe(Effect.map((events) => Array.from(events)));1387+ const catchup = rawCatchup.filter(1388+ (event) => event.sequence <= snapshot.watermark,1389+ );1390+ if (1391+ catchup.length <= THREAD_CATCHUP_MAX_EVENTS &&1392+ catchup.every((event) => event.type !== "thread.reverted")1393+ ) {
- @@ -0,0 +64,21 @@64+65+export function fromWindowSnapshot(66+ window: WindowedOrchestrationThread,67+): WindowedOrchestrationThreadState {68+ const head = window.head;69+ return {70+ syncVersion: 2,71+ id: head.id,72+ projectId: head.projectId,73+ title: head.title,74+ modelSelection: head.modelSelection,75+ runtimeMode: head.runtimeMode,76+ interactionMode: head.interactionMode,77+ branch: head.branch,78+ worktreePath: head.worktreePath,79+ latestTurn: head.latestTurn,80+ createdAt: head.createdAt,81+ updatedAt: head.updatedAt,82+ archivedAt: head.archivedAt,83+ deletedAt: head.deletedAt,84+ messages: window.messages,packages/client-runtime/src/environment/transport.ts line 34Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +6,21 @@6+export function selectRpcTransport(7+ descriptor: ExecutionEnvironmentDescriptor,8+): ExecutionEnvironmentRpcTransport {9+ return (10+ descriptor.rpcTransports?.find((transport) => transport.kind === "gzip-json") ??11+ descriptor.rpcTransports?.find((transport) => transport.kind === "json") ?? {12+ kind: "json",13+ path: "/ws",14+ }15+ );16+}17+18+export function selectThreadSyncVersion(descriptor: ExecutionEnvironmentDescriptor): 1 | 2 {19+ return descriptor.threadSyncVersions?.includes(2) ? 2 : 1;20+}21+22+export function applyRpcTransport(23+ socketUrl: string,24+ transport: ExecutionEnvironmentRpcTransport,25+): string {26+ const url = new URL(socketUrl);apps/mobile/src/features/threads/ThreadFeed.tsx line 1331Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1280,3 +1316,6 @@12801316 // UIKit's adjustedContentInset, so topContentInset is 0 here). Add the12811317 // header height back or the material toggles a full header too late.12821318 reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);1319+ // Thread-sync v2 pagination: nearing the top of the loaded window pulls1320+ // the next page of older history (single-flight; loadingOlder gates it).1321+ if (apps/mobile/src/features/threads/ThreadFeed.tsx line 188Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -153,2 +166,21 @@166+ didOpen.current = true;167+ props.onPressImage(uri);168+ }, [props.onPressImage, uri]);169+170+ if (!requested) {171+ return (172+ <TouchableOpacity173+ accessibilityRole="imagebutton"174+ accessibilityLabel="Load attached media"175+ activeOpacity={0.7}176+ onPress={() => setRequested(true)}177+ >178+ <View className={`${props.className} items-center justify-center gap-1.5`}>179+ <SymbolView name="photo" size={20} tintColor="#8a8a8a" type="monochrome" />180+ <Text className="font-t3-medium text-xs text-foreground-muted">Tap to load media</Text>181+ </View>182+ </TouchableOpacity>183+ );184+ }153185154186 if (uri === null) {packages/client-runtime/src/state/threads.ts line 548OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -185,0 +528,21 @@528+ );529+ if (!acquired) return;530+ yield* SubscriptionRef.update(state, (current) => ({531+ ...current,532+ loadingOlder: true,533+ }));534+ yield* Effect.gen(function* () {535+ const current = yield* SubscriptionRef.get(state);536+ if (Option.isNone(current.data) || !isWindowedThread(current.data.value)) return;537+ const thread = current.data.value;538+ if (!thread.hasOlderMessages && !thread.hasOlderActivities) return;539+ const session = yield* SubscriptionRef.get(supervisor.session);540+ if (Option.isNone(session)) return;541+ const page = yield* session.value.client[ORCHESTRATION_WS_METHODS.getThreadHistoryPage]({542+ threadId,543+ historyEpoch: thread.historyEpoch,544+ before: thread.before,545+ messageLimit: 32,546+ activityLimit: 128,547+ });548+ const next: WindowedOrchestrationThreadState = mergeWindowHistoryPage(thread, page);packages/client-runtime/src/environment/transport.ts line 6Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+import type {2+ ExecutionEnvironmentDescriptor,3+ ExecutionEnvironmentRpcTransport,4+} from "@t3tools/contracts";5+6+export function selectRpcTransport(packages/client-runtime/src/state/windowedThread.ts line 314OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +294,21 @@294+ id: event.payload.messageId,295+ role: event.payload.role,296+ text: event.payload.text,297+ ...(event.payload.attachments === undefined298+ ? {}299+ : { attachments: event.payload.attachments }),300+ turnId: event.payload.turnId,301+ streaming: event.payload.streaming,302+ createdAt: event.payload.createdAt,303+ updatedAt: event.payload.updatedAt,304+ });305+ const turnStillRunning =306+ event.payload.turnId !== null &&307+ thread.session?.status === "running" &&308+ thread.session.activeTurnId === event.payload.turnId;309+ const settlesTurn = !event.payload.streaming && !turnStillRunning;310+ const latestTurn =311+ event.payload.role === "assistant" && event.payload.turnId !== null312+ ? {313+ turnId: event.payload.turnId,314+ state: settlesTurn ? ("completed" as const) : ("running" as const),@@ -1859,3 +2146,10 @@18592146 }),18602147 );186121482149+// Compression is capability-gated on /ws-compressed. /ws stays byte-for-byte2150+// JSON compatible with pre-negotiation clients.2151+const nodeGzipCodec: CompressionCodec = {2152+ compressSync: (b) => zlib.gzipSync(b, { level: 4 }),2153+ decompressSync: (b) => zlib.gunzipSync(b),2154+ threshold: 1024,2155+};@@ -0,0 +397,21 @@397+ ...thread.session,398+ status: "stopped",399+ activeTurnId: null,400+ updatedAt: event.payload.createdAt,401+ },402+ updatedAt: event.occurredAt,403+ },404+ };405+ case "thread.proposed-plan-upserted":406+ return {407+ kind: "updated",408+ thread: {409+ ...thread,410+ proposedPlans: [event.payload.proposedPlan],411+ updatedAt: event.occurredAt,412+ },413+ };414+ case "project.created":415+ case "project.meta-updated":416+ case "project.deleted":417+ case "thread.created":packages/client-runtime/src/state/threads.ts line 647OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -201,2 +627,21 @@627+ : Stream.empty,628+ }),629+ ),630+ Stream.runForEach(applyV2Item),631+ // Surface silent fiber deaths (defects kill the forked pipeline without any632+ // user-visible signal otherwise — the thread just never loads).633+ Effect.tapCause((cause) =>634+ Effect.logError("Thread sync v2 pipeline failed.").pipe(635+ Effect.annotateLogs({ environmentId, threadId, cause: Cause.pretty(cause) }),636+ ),637+ ),638+ Effect.forkScoped,639+ );640+ // Legacy (v1) flow — upstream's HTTP-snapshot + afterSequence resume,641+ // skipped entirely when the connection negotiated thread-sync v2 (the v2642+ // pipeline above owns the thread in that case). Waiting for the first643+ // prepared connection decides the gate; the cached thread is already on644+ // screen from state creation, so this does not delay first paint.201645 yield* Effect.forkScoped(202646 Effect.gen(function* () {647+ const prepared = yield* SubscriptionRef.changes(supervisor.prepared).pipe(@@ -0,0 +319,21 @@319+ WHERE thread_id = ${threadId}320+ AND json_extract(payload_json, '$.requestId') IS NOT NULL321+ AND kind IN ('user-input.requested', 'user-input.resolved', 'provider.user-input.respond.failed')322+ ) WHERE row_number = 1323+ )324+ SELECT activity.activity_id AS "activityId", activity.thread_id AS "threadId",325+ activity.turn_id AS "turnId", activity.tone, activity.kind, activity.summary,326+ activity.payload_json AS payload, activity.sequence, activity.created_at AS "createdAt"327+ FROM projection_thread_activities activity328+ WHERE activity.thread_id = ${threadId}329+ AND (330+ (activity.kind = 'approval.requested' AND EXISTS (331+ SELECT 1 FROM projection_pending_approvals pending332+ WHERE pending.thread_id = activity.thread_id AND pending.status = 'pending'333+ AND pending.request_id = json_extract(activity.payload_json, '$.requestId')334+ ))335+ OR activity.activity_id IN (336+ SELECT activity_id FROM latest_user_input WHERE kind = 'user-input.requested'337+ )338+ )339+ ORDER BY activity.created_at ASC, activity.activity_id ASC
- @@ -1240,0 +1473,21 @@1473+ snapshotId,1474+ historyEpoch: snapshot.historyEpoch,1475+ lastAppliedSequence: snapshot.watermark,1476+ before: {1477+ message:1478+ oldestMessage === undefined1479+ ? null1480+ : {1481+ createdAt: oldestMessage.createdAt,1482+ messageId: oldestMessage.id,1483+ },1484+ activity:1485+ oldestActivity === undefined1486+ ? null1487+ : {1488+ createdAt: oldestActivity.createdAt,1489+ activityId: oldestActivity.id,1490+ },1491+ },1492+ hasOlderMessages: snapshot.head.counts.messages > built.messages.length,1493+ hasOlderActivities: snapshot.head.counts.activities > built.activities.length,
- @@ -0,0 +67,21 @@67+): WindowedOrchestrationThreadState {68+ const head = window.head;69+ return {70+ syncVersion: 2,71+ id: head.id,72+ projectId: head.projectId,73+ title: head.title,74+ modelSelection: head.modelSelection,75+ runtimeMode: head.runtimeMode,76+ interactionMode: head.interactionMode,77+ branch: head.branch,78+ worktreePath: head.worktreePath,79+ latestTurn: head.latestTurn,80+ createdAt: head.createdAt,81+ updatedAt: head.updatedAt,82+ archivedAt: head.archivedAt,83+ deletedAt: head.deletedAt,84+ messages: window.messages,85+ activities: mergeActivities(window.activities, head.pendingRequests),86+ proposedPlans: head.activeProposedPlan === null ? [] : [head.activeProposedPlan],87+ checkpoints: [],@@ -0,0 +286,21 @@286+ const listTailMessages = SqlSchema.findAll({287+ Request: ThreadLookup,288+ Result: ProjectionMessageDbRow,289+ execute: ({ threadId }) => sql`290+ SELECT message_id AS "messageId", thread_id AS "threadId", turn_id AS "turnId", role, text,291+ attachments_json AS attachments, is_streaming AS "isStreaming",292+ created_at AS "createdAt", updated_at AS "updatedAt"293+ FROM projection_thread_messages WHERE thread_id = ${threadId}294+ ORDER BY created_at DESC, message_id DESC LIMIT ${THREAD_SYNC_TAIL_MESSAGE_LIMIT}295+ `,296+ });297+ const listTailActivities = SqlSchema.findAll({298+ Request: ThreadLookup,299+ Result: ProjectionActivityDbRow,300+ execute: ({ threadId }) => sql`301+ SELECT activity_id AS "activityId", thread_id AS "threadId", turn_id AS "turnId", tone,302+ kind, summary, payload_json AS payload, sequence, created_at AS "createdAt"303+ FROM projection_thread_activities WHERE thread_id = ${threadId}304+ ORDER BY created_at DESC, activity_id DESC LIMIT ${THREAD_SYNC_TAIL_ACTIVITY_LIMIT}305+ `,306+ });@@ -182,0 +494,21 @@494+ case "updated":495+ yield* setThread(result.thread, item.event.sequence);496+ yield* finishV2CatchupEvent();497+ return;498+ case "deleted":499+ pendingCatchup = null;500+ yield* setDeleted(item.event.sequence);501+ return;502+ case "resync":503+ yield* requestV2Resync(`event-reducer-resync (${item.event.type})`);504+ return;505+ case "unchanged":506+ yield* setThread(current.data.value, item.event.sequence);507+ yield* finishV2CatchupEvent();508+ return;509+ }510+ }511+ case "resync-required":512+ yield* requestV2Resync(`server-resync-required (${item.reason})`);513+ return;514+ case "keepalive":@@ -115,3 +130,4 @@115130 import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";116131 import * as RelayClient from "@t3tools/shared/relayClient";117132 const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);133+const isOrchestrationGetSnapshotError = Schema.is(OrchestrationGetSnapshotError);@@ -0,0 +365,21 @@365+ const session = event.payload.session;366+ const latestTurn =367+ session.status === "running" && session.activeTurnId !== null368+ ? {369+ turnId: session.activeTurnId,370+ state: "running" as const,371+ requestedAt:372+ thread.latestTurn?.turnId === session.activeTurnId373+ ? thread.latestTurn.requestedAt374+ : session.updatedAt,375+ startedAt:376+ thread.latestTurn?.turnId === session.activeTurnId377+ ? (thread.latestTurn.startedAt ?? session.updatedAt)378+ : session.updatedAt,379+ completedAt: null,380+ assistantMessageId:381+ thread.latestTurn?.turnId === session.activeTurnId382+ ? thread.latestTurn.assistantMessageId383+ : null,384+ }385+ : thread.latestTurn?.state === "running"@@ -197,3 +595,17 @@197595 Effect.forkScoped,198596 );199597598+ const resolveV2SubscribeInput = Effect.gen(function* () {599+ const seq = yield* SubscriptionRef.get(lastSequence);600+ const current = yield* SubscriptionRef.get(state);601+ const forceSnapshot = yield* Ref.get(forceV2Snapshot);602+ return !forceSnapshot &&603+ seq > 0 &&604+ Option.isSome(current.data) &&605+ isWindowedThread(current.data.value)606+ ? {607+ threadId,608+ sinceSequence: seq,609+ historyEpoch: current.data.value.historyEpoch,610+ }611+ : { threadId };@@ -0,0 +89,21 @@89+ /^[A-Za-z0-9+/]+={0,2}$/u.test(compact)90+ ? Buffer.from(compact, "base64")91+ : null;92+ if (93+ decoded !== null &&94+ declaredMediaType !== null &&95+ decoded.toString("base64") === compact96+ ) {97+ return {98+ bytes: decoded,99+ mediaType: declaredMediaType,100+ extension: declaredMediaType.startsWith("image/")101+ ? inferImageExtension({ mimeType: declaredMediaType })102+ : ".bin",103+ };104+ }105+ // Oversized plain text: externalize the UTF-8 bytes verbatim — bounded106+ // on the wire, impossible to corrupt.107+ return {108+ bytes: Buffer.from(data, "utf8"),109+ mediaType: "text/plain; charset=utf-8",
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
153d72da-acae-4afe-bc37-403fd436f3c3You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share