The best way to control Claude Code, Codex and more from any computer or phone

main
ts 176 lines 6.89 KB
Raw
1 import type { NavigationState } from "@react-navigation/native";
2 import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3 import * as Linking from "expo-linking";
4 import { AppState, Dimensions, Platform } from "react-native";
5
6 import { environmentCatalog } from "../../../connection/catalog";
7 import { deriveLayout } from "../../../lib/layout";
8 import {
9 NATIVE_METRICS_TIMEOUT_MS,
10 nativeWorkspaceColumnsSupportedFor,
11 } from "../../../native/NativeWorkspaceColumns";
12 import {
13 currentNativeLayoutMetrics,
14 firstNativeLayoutMetrics,
15 } from "../../../native/native-layout-metrics";
16 import { loadPreferences, savePreferencesPatch } from "../../../persistence/imperative";
17 import { rootStackState, type RootStackNavigation } from "../../../lib/root-stack-reset";
18 import { workspaceRoutesOf } from "../workspace-overlay-routes";
19 import type { WorkspaceSelections } from "../../../persistence/mobile-preferences";
20 import { appAtomRegistry } from "../../../state/atom-registry";
21 import { environmentPresentations } from "../../../state/presentation";
22 import {
23 environmentThreadShells,
24 startOpeningEnvironmentThread,
25 threadEnvironment,
26 } from "../../../state/threads";
27 import {
28 rememberedSettingsPage,
29 workspaceSelectionsIn,
30 type WorkspaceSelectionCheck,
31 } from "./workspace-tab-navigation";
32
33 // Only iOS columns reopen a remembered page; Android always opens a tab on its list.
34 const REMEMBERS = Platform.OS === "ios";
35
36 // Read synchronously when a tab opens, so it lives in memory and is saved when the app leaves
37 // the foreground rather than on every chat switch.
38 let selections: WorkspaceSelections = {};
39 let saved = selections;
40 let hydration: Promise<void> | null = null;
41
42 function save() {
43 const writing = selections;
44 if (saved === writing) return;
45 // Marked saved only once written, so a failed write is retried on the next background.
46 void savePreferencesPatch({ workspaceSelections: writing })
47 .then(() => {
48 saved = writing;
49 })
50 .catch(() => undefined);
51 }
52
53 // Route keys only name routes of the session that wrote them; a saved one would make a tab rebuild
54 // its page under a stale key, which UIKit animates as a pop and a push.
55 function withoutRouteKeys(saved: WorkspaceSelections | undefined): WorkspaceSelections {
56 const omitKey = <Selection extends { readonly key?: string }>({ key: _, ...rest }: Selection) =>
57 rest;
58 const {
59 threads,
60 pullRequests,
61 issues,
62 settingsKey: _,
63 threadsDraft: _draft,
64 ...rest
65 } = saved ?? {};
66 return {
67 ...rest,
68 ...(threads ? { threads: omitKey(threads) } : {}),
69 ...(pullRequests ? { pullRequests: omitKey(pullRequests) } : {}),
70 ...(issues ? { issues: omitKey(issues) } : {}),
71 };
72 }
73
74 /** Loads the saved selections once; pages visited before it resolves win over saved ones. */
75 export function hydrateWorkspaceSelections() {
76 if (!REMEMBERS) return Promise.resolve();
77 hydration ??= loadPreferences()
78 .then((preferences) => {
79 selections = { ...withoutRouteKeys(preferences.workspaceSelections), ...selections };
80 saved = selections;
81 AppState.addEventListener("change", (status) => {
82 if (status !== "active") save();
83 });
84 })
85 .catch(() => undefined);
86 return hydration;
87 }
88
89 export function currentWorkspaceSelections() {
90 return selections;
91 }
92
93 /**
94 * The navigation container's `onReady` and `onStateChange`: remembers the page each tab is
95 * showing. The initial state, such as a cold start's reopened chat, reaches only `onReady`.
96 */
97 export function recordWorkspaceSelections(state: NavigationState | undefined) {
98 if (!REMEMBERS || !state) return;
99 selections = workspaceSelectionsIn(state.routes.slice(0, state.index + 1), selections);
100 }
101
102 function environmentRemoved(environmentId: string) {
103 const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);
104 return (
105 catalog.isReady &&
106 !appAtomRegistry
107 .get(environmentPresentations.presentationsAtom)
108 .has(environmentId as EnvironmentId)
109 );
110 }
111
112 /**
113 * A remembered chat is gone once its environment was removed, or once that environment's
114 * snapshot has loaded without it. Before it loads there is nothing to contradict it.
115 */
116 export const workspaceSelectionCheck: WorkspaceSelectionCheck = {
117 thread: (selection) => {
118 if (environmentRemoved(selection.environmentId)) return false;
119 const environmentId = selection.environmentId as EnvironmentId;
120 if (!appAtomRegistry.get(threadEnvironment.snapshotAtom(environmentId))) return true;
121 return appAtomRegistry
122 .get(environmentThreadShells.environmentThreadIndexAtom(environmentId))
123 .has(selection.threadId as ThreadId);
124 },
125 pullRequest: (selection) => !environmentRemoved(selection.environmentId),
126 issue: (selection) => !environmentRemoved(selection.environmentId),
127 };
128
129 /** Whether the window lays the workspace out in columns, by the rule the layout itself uses. */
130 export function workspaceHasColumns() {
131 const metrics = currentNativeLayoutMetrics();
132 const { width, height } = metrics ?? Dimensions.get("window");
133 return deriveLayout({
134 width,
135 height,
136 nativeMetrics: metrics,
137 nativeWorkspace: nativeWorkspaceColumnsSupportedFor(metrics),
138 }).usesSplitView;
139 }
140
141 /** The Settings page a bare `settings` link opens beside the list when there are columns. */
142 export function settingsLinkPage() {
143 return REMEMBERS && workspaceHasColumns() ? rememberedSettingsPage(selections) : undefined;
144 }
145
146 /**
147 * Where a cold start without a link opens. A window that starts with columns reopens the last
148 * chat beside the list instead of an empty detail column; a compact window opens on the list.
149 * It waits for the first layout metrics as long as the workspace itself does.
150 */
151 export async function launchWorkspaceURL(): Promise<string | null> {
152 if (!REMEMBERS) return null;
153 const metrics = firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS);
154 await hydrateWorkspaceSelections();
155 const thread = selections.threads;
156 // Read the chat's cached copy while the layout metrics are still on their way.
157 if (thread) {
158 startOpeningEnvironmentThread(
159 thread.environmentId as EnvironmentId,
160 thread.threadId as ThreadId,
161 );
162 }
163 await metrics;
164 if (!thread || !workspaceHasColumns() || !workspaceSelectionCheck.thread(thread)) return null;
165 // createURL runs encodeURI over its path, which would encode each segment a second time.
166 return `${Linking.createURL("/")}threads/${encodeURIComponent(thread.environmentId)}/${encodeURIComponent(thread.threadId)}`;
167 }
168
169 /** Whether the workspace shows its first detail page, directly above its list. */
170 export function firstWorkspaceDetailOpen(navigation: RootStackNavigation) {
171 const state = rootStackState(navigation);
172 if (!state) return false;
173 const { workspace, overlays } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
174 const list = (name: string | undefined) => name === "Home" || name === "Settings";
175 return overlays.length === 0 && !list(workspace.at(-1)?.name) && list(workspace.at(-2)?.name);
176 }