Repository navigation
Expand file tree
/
Copy pathHomePage.tsx
More file actions
374 lines (353 loc) · 15.4 KB
/
Copy pathHomePage.tsx
File metadata and controls
374 lines (353 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import type { ProjectSource } from "@aoagents/product-ui";
import { useNavigate } from "@tanstack/react-router";
import { useTranslation } from "react-i18next";
import { AlertTriangle, Cloud, Folder, Folders, FolderOpen, GitFork, MessageSquarePlus, Star } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useCloudGate } from "../hooks/useCloudGate";
import { useMigrationOffer } from "../hooks/useMigrationOffer";
import { useSystemRequirementsGate } from "../hooks/useSystemRequirementsGate";
import { useWorkspaceQuery } from "../hooks/useWorkspaceQuery";
import { aoBridge } from "../lib/bridge";
import { firstRunPromptVariant, type FirstRunPromptAction, type FirstRunPromptVariant } from "../lib/experiments";
import { captureRendererEvent } from "../lib/telemetry";
import { formatTimeCompact } from "../lib/format-time";
import { getProjectLastOpenedAt } from "../lib/project-history";
import { recordManualWorkerOpen } from "../lib/session-management-telemetry";
import { usesPreviewWorkspaceData } from "../lib/preview-mode";
import { useShell } from "../lib/shell-context";
import { cn } from "../lib/utils";
import { useUiStore } from "../stores/ui-store";
import {
STANDALONE_PROJECT_KIND,
STANDALONE_WORKSPACE_ID,
type WorkspaceSummary,
} from "../types/workspace";
import { CreateProjectFlow } from "./CreateProjectFlow";
import { DaemonStartupLoader } from "./DaemonStartupLoader";
import { NAV_ROW_HIGHLIGHT_HOST_CLASS, NavRowHighlight } from "./NavRowHighlight";
import { dragStyle } from "./PageTopbar";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Pressable } from "./ui/pressable";
/**
* Home landing layout contracts (do not regress without explicit design sign-off):
* - One centered column (`max-w-[640px]`); no upward translate hack.
* - "Star us" is a quiet text link with dashed underline on hover — NOT a
* TopbarButton / accent pill / bordered card.
* - Primary actions are always a 2×2 grid. The fourth cell is the
* standalone-agent action, or Clone to the cloud when Developer Mode and
* Cloud are both enabled (standalone stays reachable from the sidebar's
* Scratchpad "+"). Never add a fifth row. Connect Mobile is settings-only.
* - Recent rows use shared {@link NavRowHighlight} (same as sidebar), not a
* flat `hover:bg-interactive-hover` wash.
* - One heading ({@link HOME_SECTION_TITLE_CLASS}) above the grid: Get started
* with no projects, otherwise Jump back right in. Recent-project rows sit
* under the grid with no heading of their own; each is one compact line
* (name and time, no path). The Scratchpad (standalone agents) is not a
* project: it never appears in the recent rows or counts toward the
* heading — the grid's standalone action and the sidebar own it.
*/
const GITHUB_REPOSITORY_URL = "https://github.com/Untrivial-ai/agent-orchestrator";
const RECENT_PROJECT_LIMIT = 3;
const HOME_BUTTON_CLASS =
"flex w-full items-center gap-3 rounded-lg bg-card px-4 py-3 transition-[background-color] duration-fast ease-out hover:bg-accent hover:text-foreground";
const HOME_ICON_SLOT_CLASS =
"grid size-8 shrink-0 place-items-center text-muted-foreground [&_svg]:size-4";
const HOME_PROJECT_ICON_CLASS =
"grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground [&_svg]:size-4";
const HOME_SECTION_TITLE_CLASS =
"text-base font-medium tracking-tight text-foreground";
function latestProjectTimestamp(project: WorkspaceSummary): string {
return [
getProjectLastOpenedAt(project.id),
...project.sessions.flatMap((session) => [session.lastUserMessageAt, session.createdAt]),
]
.filter((timestamp): timestamp is string => Boolean(timestamp))
.sort()
.at(-1) ?? "";
}
// Relative times must follow the app language (i18n catalogs), not the OS locale —
// formatTimeCompact routes through appI18n like every other time surface.
function relativeProjectTime(timestamp: string | undefined, emptyLabel: string): string {
if (!timestamp) return emptyLabel;
return formatTimeCompact(timestamp);
}
function sortProjectsByActivity(projects: WorkspaceSummary[]): WorkspaceSummary[] {
return projects
.slice()
.sort((left, right) => latestProjectTimestamp(right).localeCompare(latestProjectTimestamp(left)));
}
function ProjectRow({ project, onClick, emptyTimeLabel }: { project: WorkspaceSummary; onClick: () => void; emptyTimeLabel: string }) {
const { t } = useTranslation();
const lastOpenedAt = getProjectLastOpenedAt(project.id);
const latestProjectFact = latestProjectTimestamp(project) || lastOpenedAt;
return (
<Pressable
// Host must use NAV_ROW_HIGHLIGHT_HOST_CLASS — pill owns the fill.
className={cn(
"flex w-full items-center gap-3 rounded-lg px-4 py-1 text-muted-foreground",
NAV_ROW_HIGHLIGHT_HOST_CLASS,
)}
onClick={onClick}
>
<NavRowHighlight className="bg-card" />
<span className={cn(HOME_PROJECT_ICON_CLASS, "relative z-[1]")} aria-hidden="true">
{project.folderMissing ? <AlertTriangle strokeWidth={1.8} className="text-warning" /> : <Folder strokeWidth={1.8} />}
</span>
<span className="relative z-[1] min-w-0 text-sm leading-5">
<span className="flex items-center gap-1.5">
<span className="block truncate font-medium text-foreground">{project.name}</span>
{project.folderMissing ? (
<Badge variant="warning" className="h-4 shrink-0 px-1.5 text-2xs">{t("home.folderMissing")}</Badge>
) : null}
</span>
</span>
<span className="relative z-[1] ml-auto shrink-0 text-right text-caption tabular-nums text-muted-foreground">
{relativeProjectTime(latestProjectFact, emptyTimeLabel)}
</span>
</Pressable>
);
}
function HomeActionCard({
disabled,
icon,
label,
onClick,
}: {
disabled?: boolean;
icon: ReactNode;
label: string;
onClick?: () => void;
}) {
return (
<Pressable
className={cn(HOME_BUTTON_CLASS, "disabled:pointer-events-none disabled:opacity-50")}
disabled={disabled}
onClick={onClick}
>
<span className={HOME_ICON_SLOT_CLASS} aria-hidden="true">
{icon}
</span>
<span className="min-w-0 text-sm font-medium leading-5 text-foreground">{label}</span>
</Pressable>
);
}
export function HomePage() {
return (
<div className="relative flex h-full min-h-0 flex-col">
{/* The welcome page has no header. On macOS an invisible strip keeps
the top edge draggable without moving the content. */}
{dragStyle ? <div aria-hidden="true" className="absolute inset-x-0 top-0 z-chrome h-toolbar" style={dragStyle} /> : null}
<HomePageContent />
</div>
);
}
function HomePageContent() {
const navigate = useNavigate();
const { t } = useTranslation();
const requestNewTask = useUiStore((state) => state.requestNewTask);
const { cloneProject, createProject, daemonStatus, initializeProjectRepository, workspaceStartupState } =
useShell();
const { blocked: requirementsBlocked } = useSystemRequirementsGate();
const { cloudEnabled } = useCloudGate();
const workspaceQuery = useWorkspaceQuery();
const migrationOffer = useMigrationOffer();
const [sourceSignal, setSourceSignal] = useState<{ source: ProjectSource | "cloud"; nonce: number } | null>(null);
const [firstRunStatus, setFirstRunStatus] = useState<"loading" | "pending" | "seen">("loading");
const [firstRunPromptOpen, setFirstRunPromptOpen] = useState(false);
// True once we know whether this launch shows the prompt, so the agent-updates notice only waits for that decision.
const [firstRunDecided, setFirstRunDecided] = useState(false);
const firstRunOfferedThisMount = useRef(false);
const firstRunVariant = useRef<FirstRunPromptVariant | null>(null);
const firstRunActionRecorded = useRef(false);
const projects = workspaceQuery.data ?? [];
useEffect(() => {
let mounted = true;
void aoBridge.appState.getFirstRunProjectPrompt()
.then((status) => { if (mounted) setFirstRunStatus(status); })
.catch(() => { if (mounted) setFirstRunStatus("seen"); });
return () => { mounted = false; };
}, []);
const recentProjects = useMemo(
() =>
sortProjectsByActivity(projects.filter((project) => project.kind !== STANDALONE_PROJECT_KIND)).slice(
0,
RECENT_PROJECT_LIMIT,
),
[projects],
);
const isDaemonReady = usesPreviewWorkspaceData || daemonStatus.state === "ready";
const daemonHasFailed = Boolean(daemonStatus.code);
const showStartup =
!daemonHasFailed &&
(!isDaemonReady ||
workspaceStartupState === "loading" ||
(!workspaceQuery.isSuccess && !workspaceQuery.isError) ||
requirementsBlocked);
useEffect(() => {
if (showStartup || !workspaceQuery.isSuccess || firstRunStatus !== "pending") return;
if (!usesPreviewWorkspaceData && migrationOffer.isPending) return;
if (projects.length > 0 || migrationOffer.data?.show) {
setFirstRunDecided(true);
void aoBridge.appState.markFirstRunProjectPromptSeen().then(() => setFirstRunStatus("seen")).catch(() => undefined);
return;
}
if (firstRunOfferedThisMount.current) return;
let cancelled = false;
void aoBridge.appState.getExperimentCohort().catch(() => null).then((cohort) => {
if (cancelled) return;
const variant = firstRunPromptVariant(cohort);
firstRunOfferedThisMount.current = true;
firstRunVariant.current = variant;
setFirstRunDecided(true);
void aoBridge.appState.claimFirstRunExperimentExposure().then((claimed) => {
if (claimed) void captureRendererEvent("ao.onboarding.first_run_experiment_exposed", { variant });
}).catch(() => undefined);
if (variant === "prompt") {
setFirstRunPromptOpen(true);
setSourceSignal({ source: "clone", nonce: Date.now() });
} else {
setFirstRunStatus("seen");
void aoBridge.appState.markFirstRunProjectPromptSeen().catch(() => undefined);
}
});
return () => { cancelled = true; };
}, [firstRunStatus, migrationOffer.data?.show, migrationOffer.isPending, projects.length, showStartup, workspaceQuery.isSuccess]);
const setFirstRunPromptActive = useUiStore((state) => state.setFirstRunPromptActive);
// Shell notices wait while the prompt is showing or still being decided. Once the
// user starts a clone the prompt closes, so a failed or abandoned clone cannot
// hold them back for the rest of the session.
const firstRunBlocksNotices = firstRunStatus === "loading" || firstRunPromptOpen || (firstRunStatus === "pending" && !firstRunDecided);
useEffect(() => {
setFirstRunPromptActive(firstRunBlocksNotices);
return () => setFirstRunPromptActive(false);
}, [firstRunBlocksNotices, setFirstRunPromptActive]);
const recordFirstRunPromptAction = (action: FirstRunPromptAction) => {
if (firstRunVariant.current !== "prompt" || firstRunActionRecorded.current) return;
firstRunActionRecorded.current = true;
void captureRendererEvent("ao.onboarding.first_run_prompt_action", { action });
};
const finishFirstRunPrompt = (action: FirstRunPromptAction = "dismissed") => {
recordFirstRunPromptAction(action);
setFirstRunPromptOpen(false);
setFirstRunStatus("seen");
void aoBridge.appState.markFirstRunProjectPromptSeen().catch(() => {
// A failed write leaves the durable offer pending for the next launch.
});
};
if (showStartup) return <DaemonStartupLoader />;
const requestSource = (source: ProjectSource | "cloud") => {
setSourceSignal({ source, nonce: Date.now() });
};
const openProject = (projectId: string) => {
void navigate({ to: "/projects/$projectId", params: { projectId } });
};
const openExistingProject = (path: string) => {
const project = projects.find((candidate) => candidate.path === path);
if (project) void navigate({ to: "/projects/$projectId", params: { projectId: project.id } });
};
if (workspaceStartupState === "error" || workspaceQuery.isError) {
return (
<div className="flex min-h-0 flex-1 items-center justify-center px-6 py-16">
<p className="text-center text-xs text-passive">{t("shell.couldNotLoadProjects")}</p>
</div>
);
}
return (
<div className="relative flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 py-16">
<div className="w-full max-w-[640px]">
<div className="space-y-6">
<section className="space-y-3 px-3" style={firstRunPromptOpen ? { visibility: "hidden" } : undefined}>
<div className="flex items-baseline justify-between gap-4">
<h1 className={HOME_SECTION_TITLE_CLASS}>{recentProjects.length === 0 ? t("home.getStarted") : t("home.jumpBack")}</h1>
{/* Quiet text link — not TopbarButton / accent. Dashed underline only on hover. */}
<Button
className="gap-1.5 rounded-none border-0 border-b border-dashed border-transparent pb-px text-sm text-muted-foreground no-underline hover:border-current"
onClick={() => void aoBridge.app.openExternal(GITHUB_REPOSITORY_URL)}
type="button"
variant="link"
>
<Star className="size-3.5" strokeWidth={1.8} aria-hidden="true" />
{t("home.starUs")}
</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<HomeActionCard
icon={<GitFork strokeWidth={1.8} />}
label={t("createProject.cloneFromGit")}
onClick={() => requestSource("clone")}
/>
<HomeActionCard
icon={<FolderOpen strokeWidth={1.8} />}
label={t("createProject.openLocal")}
onClick={() => requestSource("local")}
/>
<HomeActionCard
icon={<Folders strokeWidth={1.8} />}
label={t("createProject.addWorkspace")}
onClick={() => requestSource("workspace")}
/>
{/* Cloud is on for everyone a control plane is configured for. */}
{cloudEnabled ? (
<HomeActionCard
icon={<Cloud strokeWidth={1.8} />}
label={t("createProject.cloudTitle")}
onClick={() => requestSource("cloud")}
/>
) : (
<HomeActionCard
icon={<MessageSquarePlus strokeWidth={1.8} />}
label={t("home.newStandaloneAgent")}
onClick={() => requestNewTask(STANDALONE_WORKSPACE_ID)}
/>
)}
</div>
{/* Same section as the grid so the gap matches the grid's gap-3. */}
{recentProjects.length > 0 && (
<div>
{recentProjects.map((project) => (
<ProjectRow
key={project.id}
project={project}
onClick={() => {
if (project.kind === STANDALONE_PROJECT_KIND) {
const session = project.sessions.find((candidate) => candidate.kind === "worker");
if (session) recordManualWorkerOpen(session.id);
session
? void navigate({ to: "/sessions/$sessionId", params: { sessionId: session.id } })
: requestNewTask(STANDALONE_WORKSPACE_ID);
return;
}
openProject(project.id);
}}
emptyTimeLabel={t("home.never")}
/>
))}
</div>
)}
</section>
</div>
<CreateProjectFlow
firstRunClone={firstRunPromptOpen}
onFirstRunDismiss={finishFirstRunPrompt}
onFirstRunProgress={() => {
recordFirstRunPromptAction("clone");
setFirstRunPromptOpen(false);
}}
existingProjectNames={projects.map((project) => project.name)}
existingProjectPaths={projects.map((project) => project.path)}
mode="choose"
onCloneProject={cloneProject}
onCreateProject={async (input) => {
await createProject(input);
if (firstRunStatus === "pending") finishFirstRunPrompt("clone");
}}
onCreateStandaloneAgent={() => requestNewTask(STANDALONE_WORKSPACE_ID)}
onInitializeProject={initializeProjectRepository}
onOpenExistingProject={openExistingProject}
sourceSignal={sourceSignal}
/>
</div>
</div>
);
}