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

main
ts 308 lines 11.1 KB
Raw
1 import type { WorkspaceSelections } from "../../../persistence/mobile-preferences";
2 import {
3 SETTINGS_PAGE_TARGETS,
4 type SettingsPageTarget,
5 } from "../../settings/components/settings-page-targets";
6 import { settingsNavigationState } from "../../settings/settings-navigation";
7 import type { WorkspaceTab } from "./workspace-tabs-state";
8
9 type RouteLike = {
10 readonly name: string;
11 readonly key?: string;
12 readonly params?: object | undefined;
13 };
14 type ThreadSelection = NonNullable<WorkspaceSelections["threads"]>;
15 type PullRequestSelection = NonNullable<WorkspaceSelections["pullRequests"]>;
16 type IssueSelection = NonNullable<WorkspaceSelections["issues"]>;
17
18 /** Opened when Settings has columns and none of its pages has been opened yet. */
19 export const DEFAULT_SETTINGS_PAGE = "SettingsEnvironments" satisfies SettingsPageTarget;
20
21 export function workspaceTabColumns(
22 platform: string,
23 tab: WorkspaceTab | "settings",
24 columns: boolean,
25 ) {
26 return columns && (platform === "ios" || (platform === "android" && tab === "settings"));
27 }
28
29 // Pages a Settings row opens, minus Project overview: it shows the project chosen in the
30 // Settings scope, which resets whenever Settings closes.
31 const REMEMBERED_SETTINGS_PAGES: ReadonlySet<string> = new Set(
32 SETTINGS_PAGE_TARGETS.filter((page) => page !== "SettingsProjectOverview"),
33 );
34
35 export function rememberedSettingsPage(selections: WorkspaceSelections): SettingsPageTarget {
36 if (selections.settings === "SettingsMicrophone") return "SettingsVoice";
37 return selections.settings && REMEMBERED_SETTINGS_PAGES.has(selections.settings)
38 ? (selections.settings as SettingsPageTarget)
39 : DEFAULT_SETTINGS_PAGE;
40 }
41
42 /** Whether a remembered chat, pull request or issue can still be opened. */
43 export interface WorkspaceSelectionCheck {
44 readonly thread: (selection: ThreadSelection) => boolean;
45 readonly pullRequest: (selection: PullRequestSelection) => boolean;
46 readonly issue: (selection: IssueSelection) => boolean;
47 }
48
49 function stringParam(params: object | undefined, key: string) {
50 const value = (params as Record<string, unknown> | undefined)?.[key];
51 return typeof value === "string" ? value : undefined;
52 }
53
54 function pullRequestSelection(
55 params: object | undefined,
56 ): Omit<PullRequestSelection, "key"> | undefined {
57 const value = params as Record<string, unknown> | undefined;
58 if (
59 typeof value?.environmentId !== "string" ||
60 typeof value.projectId !== "string" ||
61 typeof value.repository !== "string" ||
62 typeof value.number !== "number"
63 ) {
64 return undefined;
65 }
66 return {
67 environmentId: value.environmentId,
68 projectId: value.projectId,
69 repository: value.repository,
70 number: value.number,
71 ...(typeof value.host === "string" ? { host: value.host } : {}),
72 };
73 }
74
75 function samePullRequest(
76 left: PullRequestSelection | undefined,
77 right: Omit<PullRequestSelection, "key">,
78 ) {
79 return (
80 left?.environmentId === right.environmentId &&
81 left.projectId === right.projectId &&
82 left.repository === right.repository &&
83 left.number === right.number &&
84 left.host === right.host
85 );
86 }
87
88 const ISSUE_IDENTITY = ["environmentId", "projectId", "tracker", "scope", "issueKey"] as const;
89
90 function issueSelection(params: object | undefined): Omit<IssueSelection, "key"> | undefined {
91 const value = params as Record<string, unknown> | undefined;
92 if (ISSUE_IDENTITY.some((key) => typeof value?.[key] !== "string")) return undefined;
93 const identity = value as Record<(typeof ISSUE_IDENTITY)[number], string>;
94 return {
95 environmentId: identity.environmentId,
96 projectId: identity.projectId,
97 tracker: identity.tracker,
98 scope: identity.scope,
99 issueKey: identity.issueKey,
100 ...(typeof value?.host === "string" ? { host: value.host } : {}),
101 };
102 }
103
104 function sameIssue(left: IssueSelection | undefined, right: Omit<IssueSelection, "key">) {
105 return (
106 left !== undefined &&
107 ISSUE_IDENTITY.every((key) => left[key] === right[key]) &&
108 left.host === right.host
109 );
110 }
111
112 /**
113 * The page each tab shows in a root route chain: the newest chat, pull request and issue, and
114 * the Settings page directly above the Settings route. Returns `previous` when nothing changed.
115 */
116 export function workspaceSelectionsIn(
117 routes: readonly RouteLike[],
118 previous: WorkspaceSelections,
119 ): WorkspaceSelections {
120 let next = previous;
121 const thread = routes.findLast((route) => route.name === "Thread");
122 const environmentId = stringParam(thread?.params, "environmentId");
123 const threadId = stringParam(thread?.params, "threadId");
124 if (
125 environmentId &&
126 threadId &&
127 (next.threads?.environmentId !== environmentId ||
128 next.threads.threadId !== threadId ||
129 next.threads.key !== thread?.key ||
130 next.threadsDraft)
131 ) {
132 const { threadsDraft: _, ...rest } = next;
133 next = { ...rest, threads: { environmentId, threadId, key: thread?.key } };
134 } else if (
135 thread?.key !== undefined &&
136 !threadId &&
137 (next.threadsDraft?.key !== thread.key || next.threadsDraft.params !== thread.params)
138 ) {
139 next = { ...next, threadsDraft: { key: thread.key, params: thread.params } };
140 }
141 const pullRequestRoute = routes.findLast((route) => route.name === "PullRequest");
142 const pullRequest = pullRequestSelection(pullRequestRoute?.params);
143 if (
144 pullRequest &&
145 (!samePullRequest(next.pullRequests, pullRequest) ||
146 next.pullRequests?.key !== pullRequestRoute?.key)
147 ) {
148 next = { ...next, pullRequests: { ...pullRequest, key: pullRequestRoute?.key } };
149 }
150 const issueRoute = routes.findLast((route) => route.name === "Issue");
151 const issue = issueSelection(issueRoute?.params);
152 if (issue && (!sameIssue(next.issues, issue) || next.issues?.key !== issueRoute?.key)) {
153 next = { ...next, issues: { ...issue, key: issueRoute?.key } };
154 }
155 const list = routes.findIndex((route) => route.name === "Settings");
156 const page = list < 0 ? undefined : routes[list + 1];
157 if (
158 page &&
159 REMEMBERED_SETTINGS_PAGES.has(page.name) &&
160 (page.name !== next.settings || page.key !== next.settingsKey)
161 ) {
162 next = { ...next, settings: page.name, settingsKey: page.key };
163 }
164 return next;
165 }
166
167 function identityOf<Selection extends { readonly key?: string }>({
168 key: _key,
169 ...identity
170 }: Selection) {
171 return identity;
172 }
173
174 let routeKeys = 0;
175
176 /** New routes get their key here, so the caller knows which route it is about to show. */
177 function keyed<Route extends RouteLike>(route: Route): Route & { readonly key: string } {
178 if (route.key !== undefined) return route as Route & { readonly key: string };
179 routeKeys += 1;
180 return { ...route, key: `${route.name}-workspace-${routeKeys}` };
181 }
182
183 // A hidden tab renders the page it would open under this key, so opening it reuses that screen.
184 function keyedPage<Route extends RouteLike>(route: Route): Route & { readonly key: string } {
185 return route.key === undefined
186 ? { ...route, key: `${route.name}-workspace-page` }
187 : (route as Route & { readonly key: string });
188 }
189
190 function detailRoute(
191 state: { readonly routes: readonly RouteLike[] },
192 tab: "threads" | "pullRequests" | "issues",
193 selections: WorkspaceSelections,
194 check: WorkspaceSelectionCheck,
195 seedPullRequest?: (identity: Omit<PullRequestSelection, "key">) => object,
196 ): RouteLike | undefined {
197 if (tab === "threads") {
198 const draft = selections.threadsDraft;
199 if (draft) {
200 return (
201 state.routes.find((route) => route.key === draft.key) ?? {
202 key: draft.key,
203 name: "Thread",
204 params: draft.params as object | undefined,
205 }
206 );
207 }
208 const thread = selections.threads;
209 if (!thread || !check.thread(thread)) return undefined;
210 return (
211 state.routes.find(
212 (route) =>
213 route.name === "Thread" &&
214 stringParam(route.params, "environmentId") === thread.environmentId &&
215 stringParam(route.params, "threadId") === thread.threadId,
216 ) ?? {
217 key: thread.key,
218 name: "Thread",
219 params: { environmentId: thread.environmentId, threadId: thread.threadId },
220 }
221 );
222 }
223 if (tab === "issues") {
224 const issue = selections.issues;
225 if (!issue || !check.issue(issue)) return undefined;
226 return (
227 state.routes.find((route) => {
228 const shown = route.name === "Issue" ? issueSelection(route.params) : undefined;
229 return shown !== undefined && sameIssue(issue, shown);
230 }) ?? { key: issue.key, name: "Issue", params: identityOf(issue) }
231 );
232 }
233 const pullRequest = selections.pullRequests;
234 if (!pullRequest || !check.pullRequest(pullRequest)) return undefined;
235 return (
236 state.routes.find(
237 (route) =>
238 route.name === "PullRequest" &&
239 samePullRequest(pullRequestSelection(route.params), pullRequest),
240 ) ?? {
241 key: pullRequest.key,
242 name: "PullRequest",
243 params: seedPullRequest?.(identityOf(pullRequest)) ?? identityOf(pullRequest),
244 }
245 );
246 }
247
248 /**
249 * The root stack for opening a workspace tab. With columns the detail column must show
250 * something, so the tab reopens the page it last showed (Settings falls back to its default);
251 * without columns the tab opens on its list. Routes already on screen keep their keys, and
252 * `overlays` (open sheets) stay on top.
253 */
254 export function workspaceTabNavigationState<
255 State extends { readonly routes: readonly RouteLike[] },
256 >(
257 state: State,
258 tab: WorkspaceTab | "settings",
259 selections: WorkspaceSelections,
260 options: {
261 readonly columns: boolean;
262 readonly check: WorkspaceSelectionCheck;
263 readonly overlays?: readonly RouteLike[];
264 readonly seedPullRequest?: (identity: Omit<PullRequestSelection, "key">) => object;
265 },
266 ) {
267 const overlays = options.overlays ?? [];
268 if (tab === "settings") {
269 const page = options.columns ? rememberedSettingsPage(selections) : undefined;
270 const settings = settingsNavigationState(
271 state,
272 page,
273 undefined,
274 page === selections.settings ? selections.settingsKey : undefined,
275 );
276 const [home, list, current] = settings.routes;
277 const routes = [
278 ...[home!, list!].map(keyed),
279 ...(current ? [keyedPage(current)] : []),
280 ...overlays,
281 ];
282 return { ...settings, index: routes.length - 1, routes };
283 }
284 const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" };
285 const detail =
286 options.columns && tab !== "usage"
287 ? detailRoute(state, tab, selections, options.check, options.seedPullRequest)
288 : undefined;
289 const routes = [keyed(home), ...(detail ? [keyedPage(detail)] : []), ...overlays];
290 return { ...state, index: routes.length - 1, routes };
291 }
292
293 /** The page opening `tab` would show beside its list, which the hidden tab renders ahead. */
294 export function workspaceTabPage(
295 state: { readonly routes: readonly RouteLike[] },
296 tab: WorkspaceTab | "settings",
297 selections: WorkspaceSelections,
298 options: {
299 readonly columns: boolean;
300 readonly check: WorkspaceSelectionCheck;
301 readonly seedPullRequest?: (identity: Omit<PullRequestSelection, "key">) => object;
302 },
303 ) {
304 const page = workspaceTabNavigationState(state, tab, selections, options).routes.find(
305 (route) => route.name !== "Home" && route.name !== "Settings",
306 );
307 return page?.key === undefined ? undefined : { ...page, key: page.key };
308 }