[codex] Rewrite client connection architecture #2978
Mergedjuliusmarmingemerged 16 commits into
main fromcodex/connection-state-auditmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/environments/runtime/service.ts line 916OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -880,9 +907,10 @@880907 connectedAt,881908 disconnectedAt: null,882909 lastError: null,910+ lastErrorTraceId: null,883911 lastErrorAt: null,884912 });885913 useSavedEnvironmentRegistryStore.getState().markConnected(environmentId, connectedAt);886914 }887915888916 function setRuntimeDisconnected(environmentId: EnvironmentId, reason?: string | null) {
- apps/web/src/connection/storage.ts lines 165 to 190Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +168,21 @@168+ Effect.fail(catalogError("remove", transaction.error ?? "Unknown IndexedDB remove error")),169+ );170+ });171+ transaction.addEventListener("complete", () => {172+ resume(Effect.void);173+ });174+ const request = transaction.objectStore(storeName).openCursor(range);175+ request.addEventListener("error", () => {176+ resume(177+ Effect.fail(catalogError("remove", request.error ?? "Unknown IndexedDB cursor error")),178+ );179+ });180+ request.addEventListener("success", () => {181+ const cursor = request.result;182+ if (cursor === null) {183+ return;184+ }185+ cursor.delete();186+ cursor.continue();187+ });188+ }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange"));apps/web/src/state/terminalSessions.ts line 126OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ input: {107+ threadId: terminal.threadId,108+ terminalId: terminal.terminalId,109+ cols,110+ rows,111+ },112+ }),113+ [actions.terminal, environmentId, terminal.terminalId, terminal.threadId],114+ );115+ const clear = useCallback(116+ () =>117+ actions.terminal.clear({118+ environmentId,119+ input: {120+ threadId: terminal.threadId,121+ terminalId: terminal.terminalId,122+ },123+ }),124+ [actions.terminal, environmentId, terminal.terminalId, terminal.threadId],125+ );126+ const restart = useCallback(() => {packages/client-runtime/src/state/threads.ts lines 168 to 175OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +155,21 @@155+ ),156+ ),157+ );158+ });159+160+ const applyItem = Effect.fn("EnvironmentThreads.applyItem")(function* (161+ item: OrchestrationThreadStreamItem,162+ ) {163+ if (item.kind === "snapshot") {164+ yield* setThread(item.snapshot.thread);165+ return;166+ }167+168+ const current = yield* SubscriptionRef.get(state);169+ if (Option.isNone(current.data)) {170+ if (item.event.type === "thread.deleted") {171+ yield* setDeleted();172+ }173+ return;174+ }175+ const result = applyThreadDetailEvent(current.data.value, item.event, limits);
juliusmarminge changed the title
- @@ -0,0 +93,21 @@93+ return;94+ }95+ const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);96+ request.addEventListener("upgradeneeded", () => {97+ if (!request.result.objectStoreNames.contains(CATALOG_STORE_NAME)) {98+ request.result.createObjectStore(CATALOG_STORE_NAME);99+ }100+ if (!request.result.objectStoreNames.contains(SHELL_STORE_NAME)) {101+ request.result.createObjectStore(SHELL_STORE_NAME);102+ }103+ if (!request.result.objectStoreNames.contains(THREAD_STORE_NAME)) {104+ request.result.createObjectStore(THREAD_STORE_NAME);105+ }106+ });107+ request.addEventListener("error", () => {108+ resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));109+ });110+ request.addEventListener("success", () => {111+ resume(Effect.succeed(request.result));112+ });113+ });
- apps/web/src/connection/webConnectionPlatform.ts lines 97 to 105OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +85,21 @@85+ Effect.sync(() =>86+ appAtomRegistry.subscribe(managedRelaySessionAtom, () => {87+ Queue.offerUnsafe(queue, "credentials-changed");88+ }),89+ ),90+ (unsubscribe) => Effect.sync(unsubscribe),91+ ).pipe(Effect.asVoid),92+ ),93+ ),94+ }),95+);96+97+function webClientMetadata() {98+ const desktop = window.desktopBridge !== undefined;99+ const platform = navigator.platform.trim();100+ return {101+ label: desktop ? "T3 Code Desktop" : "T3 Code Web",102+ deviceType: "desktop" as const,103+ ...(platform === "" ? {} : { os: platform }),104+ };105+}apps/mobile/src/features/cloud/CloudAuthProvider.tsx lines 74 to 74OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -39,4 +54,21 @@54+ if (cancelled) {55+ return;56+ }57+ previousTokenProviderRef.current = { userId, provider: tokenProvider };58+ setAgentAwarenessRelayTokenProvider(tokenProvider, userId);59+ setManagedRelaySession(60+ appAtomRegistry,61+ createManagedRelaySession({62+ accountId: userId,63+ readClerkToken: tokenProvider,64+ }),65+ );66+ };3967 if (previous && previous.userId !== userId) {68+ previousTokenProviderRef.current = null;69+ setAgentAwarenessRelayTokenProvider(null);70+ setManagedRelaySession(appAtomRegistry, null);4071 void mobileRuntime4172 .runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))4273 .catch(() => undefined);74+ void resetManagedRelayTokenCache().then(activateSession);
- packages/client-runtime/src/connection/registry.ts line 240OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +220,21 @@220+ message: `Environment ${environmentId} is not registered.`,221+ });222+ }223+ return entry;224+ });225+226+ const closeRuntimeLease = Effect.fn("EnvironmentRegistry.closeRuntimeLease")(function* (227+ environmentId: EnvironmentId,228+ ) {229+ const current = yield* Ref.get(leases);230+ const lease = current.get(environmentId);231+ if (lease === undefined) {232+ return;233+ }234+ const next = new Map(current);235+ next.delete(environmentId);236+ yield* Ref.set(leases, next);237+ yield* Scope.close(lease.scope, Exit.void);238+ });239+240+ const createRuntimeLease = Effect.fn("EnvironmentRegistry.createRuntimeLease")(function* (
- @@ -1071,19 +1115,5 @@1071- return retainThreadDetailSubscription(environmentId, threadId);1072- }, [environmentId, routeKind, threadId]);1073-10741115 // Compute the list of environments this logical project spans, used to10751116 // drive the environment picker in BranchToolbar.10761117 const allProjects = useStore(useShallow(selectProjectsAcrossEnvironments));1077- const primaryEnvironmentId = usePrimaryEnvironmentId();1078- const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);1079- const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);1080- const activeSavedEnvironmentRecord =1081- activeThread && activeThread.environmentId !== primaryEnvironmentId1082- ? (savedEnvironmentRegistry[activeThread.environmentId] ?? null)1083- : null;1084- const activeSavedEnvironmentRuntime = activeSavedEnvironmentRecord1085- ? (savedEnvironmentRuntimeById[activeSavedEnvironmentRecord.environmentId] ?? null)1086- : null;1087- const activeSavedEnvironmentConnectionState = activeSavedEnvironmentRecord1088- ? (activeSavedEnvironmentRuntime?.connectionState ?? "disconnected")1089- : "connected";1118+ const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;1119+ const activeEnvironment =apps/web/src/hooks/useSettings.ts line 213Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -193,10 +195,10 @@193195 * persisted via RPC. Client keys go through client persistence.194196 */195197 export function useUpdateSettings() {196- const updateSettings = useCallback((patch: Partial<UnifiedSettings>) => {197- const { serverPatch, clientPatch } = splitPatch(patch);198-199- if (Object.keys(serverPatch).length > 0) {200- const currentServerConfig = getServerConfig();201- if (currentServerConfig) {202- applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));198+ const serverActions = useWebServerActions();199+ const primaryEnvironment = useWebPrimaryEnvironment();200+ const updateSettings = useCallback(201+ (patch: Partial<UnifiedSettings>) => {202+ const { serverPatch, clientPatch } = splitPatch(patch);203+204+ if (Object.keys(serverPatch).length > 0) {apps/web/src/state/query.ts lines 17 to 22Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +2,21 @@2+import * as Cause from "effect/Cause";3+import * as Option from "effect/Option";4+import { AsyncResult, Atom } from "effect/unstable/reactivity";5+6+const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(7+ Atom.withLabel("web-environment-query:empty"),8+);9+10+export interface WebEnvironmentQueryView<A> {11+ readonly data: A | null;12+ readonly error: string | null;13+ readonly isPending: boolean;14+ readonly refresh: () => void;15+}16+17+function formatError(cause: Cause.Cause<unknown>): string {18+ const error = Cause.squash(cause);19+ return error instanceof Error && error.message.trim().length > 020+ ? error.message21+ : "The environment request failed.";22+}apps/mobile/src/features/threads/use-project-actions.ts line 111OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -142,19 +99,13 @@142- branch: buildTemporaryWorktreeBranchName(uuidv4),143- },144- runSetupScript: true,145- }146- : {}),99+ createdAt: metadata.createdAt,147100 },148- createdAt,149101 });150102151- await refreshRemoteData([input.project.environmentId]);152103 return {153104 environmentId: input.project.environmentId,154105 threadId,155106 };156107 },157- [refreshRemoteData],108+ [threadActions],158109 );159110160111 const onCreateThread = useCallback(
- apps/mobile/src/connection/storage.ts lines 382 to 394Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +448,21 @@448+ if (!file.exists) {449+ file.create({ intermediates: true, overwrite: true });450+ }451+ file.write(JSON.stringify(encoded));452+ },453+ catch: (cause) => shellPersistenceError("save-thread", cause),454+ });455+ }),456+ removeThread: (environmentId, threadId) =>457+ Effect.gen(function* () {458+ const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");459+ if (file.exists) {460+ file.delete();461+ }462+ }).pipe(463+ Effect.mapError((cause) =>464+ cause._tag === "ConnectionPersistenceError"465+ ? cause466+ : shellPersistenceError("remove-thread", cause),467+ ),468+ ),packages/client-runtime/src/connection/supervisor.ts lines 91 to 99Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +74,21 @@74+ readonly _tag: "Completed";75+ readonly exit: Exit.Exit<76+ {77+ readonly attemptSpan: Option.Option<Tracer.Span>;78+ readonly lease: EnvironmentConnectionLease;79+ },80+ TracedAttemptFailure81+ >;82+ }83+ | { readonly _tag: "Interrupted" }84+ | { readonly _tag: "TimedOut" };85+86+function exitUnlessInterrupted<A, E, R>(87+ effect: Effect.Effect<A, E, R>,88+): Effect.Effect<Exit.Exit<A, E>, never, R> {89+ return Effect.matchCauseEffect(effect, {90+ onFailure: (cause) =>91+ Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)),92+ onSuccess: (value) => Effect.succeed(Exit.succeed(value)),93+ });94+}
- @@ -63,5 +70,3 @@6370 }64716572 export default function NewTaskRoute() {66- const { projects, state: catalogState, threads } = useRemoteCatalog();67- const { savedConnectionsById } = useRemoteEnvironmentState();apps/mobile/src/features/cloud/CloudAuthProvider.tsx line 136Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -54,0 +88,21 @@88+ setAgentAwarenessRelayTokenProvider(tokenProvider, userId);89+ setManagedRelaySession(90+ appAtomRegistry,91+ createManagedRelaySession({92+ accountId: userId,93+ readClerkToken: tokenProvider,94+ }),95+ );96+ };97+ if (98+ previousObservedAccount !== undefined &&99+ previousObservedAccount !== null &&100+ previousObservedAccount !== userId101+ ) {102+ previousTokenProviderRef.current = null;103+ setAgentAwarenessRelayTokenProvider(null);104+ setManagedRelaySession(appAtomRegistry, null);105+ void queueAccountCleanup(previous).then(activateSession);106+ } else {107+ void accountTransitionRef.current.then(activateSession);108+ }
- apps/mobile/src/connection/catalog-store.ts line 102Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +77,21 @@77+ ),78+ );79+ } else {80+ const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY);81+ catalog =82+ legacyRaw === null || legacyRaw.trim() === ""83+ ? EMPTY_CONNECTION_CATALOG_DOCUMENT84+ : yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(85+ Effect.mapError((cause) => catalogError("migrate", cause)),86+ Effect.catch((error) =>87+ Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(88+ Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),89+ ),90+ ),91+ );92+ if (legacyRaw !== null && legacyRaw.trim() !== "") {93+ const encoded = yield* encodeCatalog(catalog);94+ yield* storage.setItem(CONNECTION_CATALOG_KEY, encoded);95+ yield* storage.deleteItem(LEGACY_CONNECTIONS_KEY);96+ }97+ }apps/mobile/src/app/settings/environments.tsx line 258Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -217,0 +242,21 @@242+ readonly onConnect: () => void;243+ readonly onDisconnect: () => void;244+ readonly onToggleError: () => void;245+}) {246+ return (247+ <CloudEnvironmentRowShell248+ borderTop={props.borderTop}249+ connectionError={props.environment.connectionError}250+ connectionErrorTraceId={props.environment.connectionErrorTraceId}251+ connectionState={props.environment.connectionState}252+ errorExpanded={props.errorExpanded}253+ label={props.environment.environmentLabel}254+ onValueChange={(enabled) => {255+ if (enabled) {256+ props.onConnect();257+ return;258+ }259+ props.onDisconnect();260+ }}261+ onToggleError={props.onToggleError}262+ value={props.environment.connectionState !== "available"}
- apps/mobile/src/features/cloud/CloudAuthProvider.tsx line 104Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -25,10 +62,16 @@62+ if (result.status === "rejected") {63+ console.warn("[t3-cloud] cloud account cleanup failed", result.reason);64+ }65+ }66+ });67+ return accountTransitionRef.current;68+ };69+2570 if (!isSignedIn || !userId) {2671 const previous = previousTokenProviderRef.current;2772 previousTokenProviderRef.current = null;28- if (previous) {29- void mobileRuntime30- .runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))31- .catch(() => undefined);32- }3373 setAgentAwarenessRelayTokenProvider(null);3474 setManagedRelaySession(appAtomRegistry, null);75+ if (previousObservedAccount !== null) {76+ void queueAccountCleanup(previous);77+ }apps/mobile/src/features/agent-awareness/remoteRegistration.ts line 511Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -372,3 +495,4 @@372495 }373496 relayTokenProvider = null;374497 relayTokenProviderIdentity = null;498+ deviceRegistrationGeneration++;@@ -23,14 +25,19 @@2325 detail: "Checking saved environments on this device.",2426 loading: true,2527 };2628 }272928- if (!catalogState.hasSavedConnections) {30+ if (!catalogState.hasConnections) {2931 return {3032 title: "No environments connected",3133 detail: "Add an environment before creating a task.",3234 loading: false,3335 };3436 }353736- if (catalogState.connectionState === "disconnected" && !catalogState.hasLoadedShellSnapshot) {38+ if (39+ (catalogState.connectionState === "available" ||40+ catalogState.connectionState === "offline" ||41+ catalogState.connectionState === "error") &&42+ !catalogState.hasLoadedShellSnapshot43+ ) {
- @@ -14,3 +83,19 @@1483 menu.style.top = `${top}px`;1584 }168586+function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {87+ if (typeof Node !== "undefined" && target instanceof Node) {88+ return menuStack.some((menu) => menu.contains(target));89+ }90+ if (!target || typeof target !== "object") {91+ return false;92+ }93+94+ let current: unknown = target;95+ while (current && typeof current === "object") {96+ if (menuStack.includes(current as HTMLDivElement)) {97+ return true;98+ }99+ current = (current as { parent?: unknown }).parent;100+ }101+ return false;apps/desktop/src/app/DesktopConnectionCatalogStore.ts lines 124 to 140Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +70,21 @@70+function decodeSecretBytes(71+ encoded: string,72+): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {73+ return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(74+ Effect.mapError((cause) => new DesktopConnectionCatalogStoreDecodeError({ cause })),75+ );76+}77+78+const readDocument = (79+ fileSystem: FileSystem.FileSystem,80+ catalogPath: string,81+): Effect.Effect<Option.Option<ConnectionCatalogDocument>> =>82+ fileSystem.readFileString(catalogPath).pipe(83+ Effect.option,84+ Effect.flatMap(85+ Option.match({86+ onNone: () => Effect.succeed(Option.none<ConnectionCatalogDocument>()),87+ onSome: (raw) => decodeConnectionCatalogDocumentJson(raw).pipe(Effect.option),88+ }),89+ ),90+ );@@ -0,0 +93,21 @@93+ if (Array.isArray(answer)) {94+ return answer.flatMap((entry) => {95+ const text = typeof entry === "string" ? trimmed(entry) : undefined;96+ return text ? [text] : [];97+ });98+ }99+ const text = typeof answer === "string" ? trimmed(answer) : undefined;100+ return text ? [text] : [];101+}102+103+function normalizeAnswerForXAi(104+ question: XAiAskUserQuestionRequestParams["questions"][number],105+ answer: unknown,106+): NormalizedXAiAnswer | undefined {107+ const values = answerValues(answer);108+ if (values.length === 0) {109+ return undefined;110+ }111+112+ const optionByLabel = new Map(question.options.map((option) => [option.label, option]));113+ const resolvedValues = values.map((value) => ({
- apps/mobile/src/features/cloud/CloudAuthProvider.tsx line 104Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -25,10 +62,16 @@62+ if (result.status === "rejected") {63+ console.warn("[t3-cloud] cloud account cleanup failed", result.reason);64+ }65+ }66+ });67+ return accountTransitionRef.current;68+ };69+2570 if (!isSignedIn || !userId) {2671 const previous = previousTokenProviderRef.current;2772 previousTokenProviderRef.current = null;28- if (previous) {29- void mobileRuntime30- .runPromise(unregisterAgentAwarenessDeviceForCurrentUser(previous.provider))31- .catch(() => undefined);32- }3373 setAgentAwarenessRelayTokenProvider(null);3474 setManagedRelaySession(appAtomRegistry, null);75+ if (previousObservedAccount !== null) {76+ void queueAccountCleanup(previous);77+ }
- apps/web/src/state/sourceControlActions.ts lines 147 to 160Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +143,21 @@143+ return useSyncExternalStore(144+ (listener) => {145+ actionListeners.add(listener);146+ return () => actionListeners.delete(listener);147+ },148+ () => stableKinds.some((kind) => (activeActionCounts.get(actionKey(kind, scope)) ?? 0) > 0),149+ () => false,150+ );151+}152+153+export function useVcsInitAction(scope: SourceControlActionScope) {154+ const init = useAtomSet(vcsEnvironment.init, { mode: "promise" });155+ const action = useCallback(async () => {156+ const target = requireScope(scope, "Git init is unavailable.");157+ return init({158+ environmentId: target.environmentId,159+ input: { cwd: target.cwd },160+ });161+ }, [init, scope]);162+ return useAction({ kind: "init", scope, action });163+}apps/mobile/src/state/thread-outbox.ts line 178OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +158,21 @@158+ queuedMessagesByThreadKeyAtom,159+ groupQueuedThreadMessages([...current, message]),160+ );161+}162+163+export async function removeThreadOutboxMessage(message: QueuedThreadMessage): Promise<void> {164+ const file = await getMessageFile(message.messageId);165+ if (file.exists) {166+ file.delete();167+ }168+169+ const current = flattenQueues(appAtomRegistry.get(queuedMessagesByThreadKeyAtom));170+ appAtomRegistry.set(171+ queuedMessagesByThreadKeyAtom,172+ groupQueuedThreadMessages(173+ current.filter((candidate) => candidate.messageId !== message.messageId),174+ ),175+ );176+}177+178+export async function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise<void> {
- apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts line 73OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +44,21 @@44+ readonly strikethrough: boolean;45+ readonly code: boolean;46+ readonly href?: string;47+ readonly externalHost?: string;48+ readonly fileIcon?: MarkdownFileIcon;49+ readonly role?: NativeMarkdownTextRun["role"];50+ readonly headingLevel?: number;51+ readonly depth?: number;52+ readonly spacing?: number;53+}54+55+const EMPTY_CONTEXT: RunContext = {56+ bold: false,57+ italic: false,58+ strikethrough: false,59+ code: false,60+};61+62+const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;63+64+function decodeHtmlEntitiesOnce(value: string): string {
- apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift line 718OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +669,21 @@669+ end: textView.sourceOffset(forDisplayOffset: NSMaxRange(textView.selectedRange))670+ )671+ }672+673+ private func displayRange(for selection: ComposerSelectionPayload) -> NSRange {674+ let start = displayOffset(forSourceOffset: selection.start)675+ let end = displayOffset(forSourceOffset: selection.end)676+ return NSRange(location: start, length: max(0, end - start))677+ }678+679+ private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {680+ let boundedOffset = max(0, min((value as NSString).length, sourceOffset))681+ var collapsedLength = 0682+ for token in tokens where token.end <= boundedOffset {683+ collapsedLength += max(0, token.end - token.start - 1)684+ }685+ if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {686+ return token.start - collapsedLength + 1687+ }688+ return boundedOffset - collapsedLength689+ }
- apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts lines 166 to 168OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +148,21 @@148+ runs: NativeMarkdownTextRun[],149+ text: string,150+ context: RunContext,151+): NativeMarkdownTextRun[] {152+ if (text.length === 0) {153+ return runs;154+ }155+156+ const run: NativeMarkdownTextRun = {157+ text,158+ ...(context.bold ? { bold: true } : {}),159+ ...(context.italic ? { italic: true } : {}),160+ ...(context.strikethrough ? { strikethrough: true } : {}),161+ ...(context.code ? { code: true } : {}),162+ ...(context.href ? { href: context.href } : {}),163+ ...(context.externalHost ? { externalHost: context.externalHost } : {}),164+ ...(context.fileIcon ? { fileIcon: context.fileIcon } : {}),165+ ...(context.role ? { role: context.role } : {}),166+ ...(context.headingLevel ? { headingLevel: context.headingLevel } : {}),167+ ...(context.depth ? { depth: context.depth } : {}),168+ ...(context.spacing ? { spacing: context.spacing } : {}),
- apps/desktop/src/preview/Manager.ts line 1156OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1136,21 @@1136+ { concurrency: 2, discard: true },1137+ );1138+ }1139+ const updatedAt = yield* currentIso;1140+ const closed: PreviewTabState = {1141+ ...tab,1142+ webContentsId: null,1143+ navStatus: { kind: "Idle" },1144+ canGoBack: false,1145+ canGoForward: false,1146+ zoomFactor: DEFAULT_ZOOM_FACTOR,1147+ controller: "none",1148+ updatedAt,1149+ };1150+ yield* SynchronizedRef.update(tabsRef, (tabs) =>1151+ replaceMap(tabs, (copy) => {1152+ copy.delete(tabId);1153+ }),1154+ );1155+ yield* emit(tabId, closed);1156+ });
- @@ -400,4 +310,17 @@400- }),401- );402- });403- },310+ toastManager.add(311+ stackedThreadToast({312+ type: "warning",313+ title: "Invalid keybindings configuration",314+ description: decision.message,315+ actionVariant: "outline",316+ actionProps: {317+ children: "Open keybindings.json",318+ onClick: () => {319+ if (!serverConfig || !primaryEnvironment) {320+ return;321+ }322+323+ const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);324+ if (!editor) {325+ return;326+ }@@ -423,2 +438,2 @@423438 const userImages = row.message.attachments ?? [];424439 const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);@@ -0,0 +145,21 @@145+ for (const [requestId, entry] of pending) {146+ if (entry.clientId === clientId) {147+ pending.delete(requestId);148+ disconnected.push(entry);149+ }150+ }151+ return [disconnected, { ...current, clients, owners, pending }] as const;152+ });153+ yield* Effect.forEach(154+ toFail,155+ ({ deferred }) =>156+ Deferred.fail(157+ deferred,158+ new PreviewAutomationUnavailableError({159+ message: "The preview automation client disconnected.",160+ }),161+ ),162+ { discard: true },163+ );164+ yield* Queue.shutdown(queue);165+ });apps/mobile/src/state/thread-outbox.ts line 15Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +111,21 @@111+}112+113+async function loadPersistedMessages(): Promise<ReadonlyArray<QueuedThreadMessage>> {114+ const { File } = await import("expo-file-system");115+ const directory = await getOutboxDirectory();116+ const messages: Array<QueuedThreadMessage> = [];117+118+ for (const entry of directory.list()) {119+ if (!(entry instanceof File) || !entry.name.endsWith(".json")) {120+ continue;121+ }122+ try {123+ messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));124+ } catch (error) {125+ console.warn("[thread-outbox] ignored invalid persisted message", entry.name, error);126+ }127+ }128+ return messages;129+}130+131+export function ensureThreadOutboxLoaded(): void {
- apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift lines 708 to 718OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +698,21 @@698+ end: textView.sourceOffset(forDisplayOffset: NSMaxRange(textView.selectedRange))699+ )700+ }701+702+ private func displayRange(for selection: ComposerSelectionPayload) -> NSRange {703+ let start = displayOffset(forSourceOffset: selection.start)704+ let end = displayOffset(forSourceOffset: selection.end)705+ return NSRange(location: start, length: max(0, end - start))706+ }707+708+ private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {709+ let boundedOffset = max(0, min((value as NSString).length, sourceOffset))710+ var collapsedLength = 0711+ for token in tokens where token.end <= boundedOffset {712+ collapsedLength += max(0, token.end - token.start - 1)713+ }714+ if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {715+ return token.start - collapsedLength + 1716+ }717+ return boundedOffset - collapsedLength718+ }packages/client-runtime/src/authorization/layer.ts lines 178 to 186Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +166,21 @@166+ yield* resetCachedEndpointFailures(input.expectedEnvironmentId);167+ return {168+ environmentId: cached.value.environmentId,169+ label: cached.value.label,170+ httpBaseUrl: cached.value.endpoint.httpBaseUrl,171+ socketUrl: cachedSocket.success,172+ httpAuthorization: {173+ _tag: "Dpop" as const,174+ accessToken: cached.value.accessToken,175+ },176+ };177+ }178+ if (cachedSocket.failure._tag === "ConnectionBlockedError") {179+ return yield* mapDpopSocketError(cachedSocket.failure);180+ }181+ const mappedFailure = mapDpopSocketError(cachedSocket.failure);182+ if (mappedFailure._tag === "ConnectionTransientError") {183+ const failureCount = yield* recordCachedEndpointFailure(input.expectedEnvironmentId);184+ if (failureCount < CACHED_ENDPOINT_FAILURE_THRESHOLD) {185+ return yield* mappedFailure;186+ }
- apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm line 645OutdatedResolvedby juliusmarminge@@ -0,0 +625,21 @@625+626+ // This is UTF16 code units!!627+ currIndex += textChild.text.length;628+629+ if (charIndex <= currIndex) {630+ return textChild;631+ }632+ }633+634+ return nil;635+}636+637+- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender638+{639+ const auto location = [self getLocationOfPress:sender];640+ const auto child = [self getTouchChild:location];641+642+ if (child) {643+ [child onPress];644+ }645+}apps/desktop/src/app/DesktopConnectionCatalogStore.ts line 304Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +284,21 @@284+ const records = yield* savedEnvironments.getRegistry;285+ if (records.length === 0) {286+ return Option.none<string>();287+ }288+ const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments);289+ const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog);290+ yield* writeCatalog(encoded);291+ return Option.some(encoded);292+ }).pipe(Effect.mapError((cause) => new DesktopConnectionCatalogStoreMigrationError({ cause })));293+294+ return DesktopConnectionCatalogStore.of({295+ get: Effect.gen(function* () {296+ const document = yield* readDocument(fileSystem, catalogPath).pipe(297+ Effect.mapError((cause) => new DesktopConnectionCatalogStoreReadError({ cause })),298+ );299+ if (Option.isNone(document)) {300+ return yield* migrateLegacyCatalog;301+ }302+ if (!(yield* safeStorage.isEncryptionAvailable)) {303+ return Option.none<string>();304+ }
- apps/mobile/src/features/review/useReviewSections.ts line 133Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -183,7 +117,17 @@117+ let activeCheckpoint = readyCheckpoints[0] ?? null;118+ if (selectedSection?.kind === "turn") {119+ activeCheckpoint = checkpointBySectionId[selectedSection.id] ?? activeCheckpoint;120+ }121+ const activeSectionId = activeCheckpoint122+ ? getReviewSectionIdForCheckpoint(activeCheckpoint)183123 : null;184- const latestTurnDiffLoaded = latestSectionId185- ? reviewCache.turnDiffById[latestSectionId] !== undefined186- : true;187- const latestTurnDiffLoading = latestSectionId ? loadingTurnIds[latestSectionId] === true : false;124+ const activeTurnDiff = useCheckpointDiff({125+ environmentId: enabled ? (environmentId ?? null) : null,126+ threadId: enabled ? (threadId ?? null) : null,127+ fromTurnCount:128+ enabled && activeCheckpoint ? Math.max(0, activeCheckpoint.checkpointTurnCount - 1) : null,129+ toTurnCount: enabled ? (activeCheckpoint?.checkpointTurnCount ?? null) : null,130+ ignoreWhitespace: false,131+ });188132189133 useEffect(() => {@@ -0,0 +228,21 @@228+ await Promise.all(229+ removed.map(async (message) => {230+ try {231+ const file = await getMessageFile(message.messageId);232+ if (file.exists) {233+ file.delete();234+ }235+ } catch (error) {236+ console.warn("[thread-outbox] failed to clear persisted message", error);237+ }238+ }),239+ );240+241+ appAtomRegistry.set(242+ queuedMessagesByThreadKeyAtom,243+ groupQueuedThreadMessages(244+ allMessages.filter((message) => message.environmentId !== environmentId),245+ ),246+ );247+ });248+}apps/mobile/src/connection/platform.ts lines 176 to 179Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +166,21 @@166+ disconnect: () => Effect.void,167+ }),168+ ),169+ ),170+);171+172+const platformConnectionSourceLayer = Layer.succeed(173+ PlatformConnectionSource,174+ PlatformConnectionSource.of({175+ registrations: Stream.empty,176+ }),177+);178+179+const environmentOwnedDataCleanupLayer = Layer.succeed(180+ EnvironmentOwnedDataCleanup,181+ EnvironmentOwnedDataCleanup.of({182+ clear: (environmentId) =>183+ Effect.all(184+ [185+ Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),186+ Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
- apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift lines 730 to 732OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +712,21 @@712+ collapsedLength += max(0, token.end - token.start - 1)713+ }714+ if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {715+ return token.start - collapsedLength + 1716+ }717+ return boundedOffset - collapsedLength718+ }719+720+ private func applyRequestedSelection() {721+ guard let requestedSelection else {722+ return723+ }724+ let nextRange = displayRange(for: requestedSelection)725+ guard nextRange.location <= textView.attributedText.length,726+ NSMaxRange(nextRange) <= textView.attributedText.length else {727+ return728+ }729+ isApplyingControlledValue = true730+ textView.selectedRange = nextRange731+ isApplyingControlledValue = false732+ }
- @@ -0,0 +78,21 @@78+ style={[flattenedStyle]}79+ // @ts-expect-error Weirdness80+ onPress={undefined}81+ onLongPress={undefined}82+ >83+ {nativeChildren}84+ </T3MarkdownTextNativeComponent>85+ </TextAncestorContext.Provider>86+ );87+ }88+89+ return <>{nativeChildren}</>;90+}91+92+function MarkdownTextPrimitiveInner(props: MarkdownTextPrimitiveProps) {93+ const [isAncestor] = useTextAncestorContext();94+95+ // Even if the uiTextView prop is set, we can still default to using96+ // normal selection (i.e. base RN text) if the text doesn't need to be97+ // selectable98+ if ((!props.selectable || !props.uiTextView) && !isAncestor) {
- @@ -0,0 +8,21 @@8+ createEnvironmentRpcQueryAtomFamily,9+ createEnvironmentSubscriptionAtomFamily,10+} from "./runtime.ts";11+import type { EnvironmentRegistry } from "../connection/registry.ts";12+import { subscribe, type EnvironmentRpcInput } from "../rpc/client.ts";13+14+export function createVcsEnvironmentAtoms<R, E>(15+ runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,16+) {17+ return {18+ listRefs: createEnvironmentRpcQueryAtomFamily(runtime, {19+ label: "environment-data:vcs:list-refs",20+ tag: WS_METHODS.vcsListRefs,21+ staleTimeMs: 5_000,22+ }),23+ status: createEnvironmentSubscriptionAtomFamily(runtime, {24+ label: "environment-data:vcs:status",25+ subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>26+ subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(27+ Stream.mapAccum(28+ () => null as VcsStatusResult | null,
- apps/web/src/cloud/managedAuth.tsx line 111Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -28,5 +94,18 @@94+ activateSession();95+ });96+ reportAtomCommandResult(result, { label: "cloud account activation" });97+ })();98+ };99+ if (previousAccount !== undefined && previousAccount !== null && previousAccount !== userId) {100+ deactivateManagedRelayAuthentication();101+ activateAfterTransition(queueAccountCleanup());102+ } else {103+ activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());104+ }105+ }28106 return () => {29- relayTokenProvider = null;30- setManagedRelaySession(appAtomRegistry, null);107+ cancelled = true;31108 };32- }, [getToken, isSignedIn, userId]);109+ }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);110+111+ useEffect(() => () => deactivateManagedRelayAuthentication(), []);
- @@ -49,7 +51,5 @@4951 this.saving = true;5052 const contents = this.latestContents;5153 const revision = this.latestRevision;52- let succeeded = false;53- try {54- await this.options.persist(contents);55- succeeded = true;54+ const result = await this.options.persist(contents);55+ const succeeded = result._tag === "Success";packages/client-runtime/src/connection/supervisor.ts line 407Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +387,21 @@387+ yield* logManagedRelayAccountChange;388+ return;389+ }390+ break;391+ }392+ }393+ });394+395+ const monitorConnectedLease = Effect.fnUntraced(function* (lease: EnvironmentConnectionLease) {396+ for (;;) {397+ const next = yield* Queue.take(signals);398+ switch (next._tag) {399+ case "DisconnectRequested":400+ case "RetryRequested":401+ return;402+ case "NetworkChanged":403+ if (next.network === "offline") {404+ return;405+ }406+ break;407+ case "Wakeup":
- @@ -1229,10 +1216,10 @@12291216 instanceId: ProviderInstanceId.make("codex"),12301217 model: DEFAULT_MODEL,12311218 },1232- localDraftError,12331219 )12341220 : undefined,1235- [draftThread, fallbackDraftProject?.defaultModelSelection, localDraftError, threadId],1221+ [draftThread, fallbackDraftProject?.defaultModelSelection, threadId],12361222 );1237- const isServerThread = routeKind === "server" && serverThread !== undefined;1223+ const isServerThread = routeKind === "server" && serverThread !== null;12381224 const activeThread = isServerThread ? serverThread : localDraftThread;1225+ const threadError = isServerThread
- packages/client-runtime/src/state/shell.ts line 92Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +72,21 @@72+73+ const persist = Effect.fn("EnvironmentShellState.persist")(function* (74+ snapshot: OrchestrationShellSnapshot,75+ ) {76+ yield* cache.saveShell(environmentId, snapshot).pipe(77+ Effect.catch((error) =>78+ Effect.logWarning("Could not persist environment shell cache.").pipe(79+ Effect.annotateLogs({80+ environmentId,81+ error: error.message,82+ }),83+ ),84+ ),85+ );86+ });87+88+ yield* Stream.fromQueue(persistence).pipe(89+ Stream.debounce("500 millis"),90+ Stream.runForEach(persist),91+ Effect.forkScoped,92+ );apps/web/src/hooks/useHandleNewThread.ts line 75Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -60,3 +63,13 @@6063 const hasWorktreePathOption = options?.worktreePath !== undefined;6164 const hasEnvModeOption = options?.envMode !== undefined;6265 const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);66+ const storedDraftThreadRef = storedDraftThread67+ ? scopeThreadRef(storedDraftThread.environmentId, storedDraftThread.threadId)68+ : null;69+ const reusableStoredDraftThread =70+ storedDraftThreadRef && readThreadShell(storedDraftThreadRef) !== null71+ ? null72+ : storedDraftThread;73+ if (storedDraftThreadRef && reusableStoredDraftThread === null) {74+ markPromotedDraftThreadByRef(storedDraftThreadRef);75+ }
- apps/web/src/components/settings/ProviderInstanceCard.tsx line 164Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -161,4 +161,3 @@161161 props.environment.map(makeEnvironmentDraftRow),162162 );163163164- useEffect(() => {
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:
95e29028-8ce5-4832-9923-acff2a69a2d3You 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)
Comment `@coderabbitai help` to get the list of available commands and usage tips.