Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(web): remove retired workspace frontend (#876)

Gener1d2ed6720782
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 65f831060..ad5df3523 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -271,15 +271,9 @@ importers:
'@base-ui/react':
specifier: ^1.8.0
- '@dagrejs/dagre':
- specifier: ^3.1.1
- version: 3.1.1
'@dnd-kit/core':
specifier: ^6.3.1
- '@dnd-kit/modifiers':
- specifier: ^9.0.0
'@dnd-kit/sortable':
specifier: ^10.0.0
@@ -376,12 +370,6 @@ importers:
'@tauri-apps/plugin-clipboard-manager':
specifier: ^2.4.1
version: 2.4.1
- '@tiptap/extension-image':
- specifier: ^3.31.4
- version: 3.31.4(@tiptap/[email protected](@tiptap/[email protected]))
- '@tiptap/extension-link':
- specifier: ^3.31.4
- version: 3.31.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/extension-list':
specifier: ^3.31.4
version: 3.31.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
@@ -391,15 +379,6 @@ importers:
'@tiptap/extension-placeholder':
specifier: ^3.31.4
version: 3.31.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))
- '@tiptap/extension-text-align':
- specifier: ^3.31.4
- version: 3.31.4(@tiptap/[email protected](@tiptap/[email protected]))
- '@tiptap/extension-underline':
- specifier: ^3.31.4
- version: 3.31.4(@tiptap/[email protected](@tiptap/[email protected]))
- '@tiptap/markdown':
- specifier: ^3.31.4
- version: 3.31.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/pm':
specifier: ^3.31.4
version: 3.31.4
@@ -415,9 +394,6 @@ importers:
'@typesafe-ai/sdk':
specifier: 0.6.0
version: 0.6.0
- '@xyflow/react':
- specifier: ^12.12.0
better-auth:
specifier: 1.7.7
@@ -427,9 +403,6 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
- driver.js:
- specifier: ^1.8.0
- version: 1.8.0
emoji-mart:
specifier: ^5.6.0
version: 5.6.0
@@ -1339,12 +1312,6 @@ packages:
resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==}
engines: {node: '>=20.19.0'}
- '@dagrejs/[email protected]':
- resolution: {integrity: sha512-zroZB1dFOFiGgv4Xcrn1DckB1o4aOikPqD2NDQPV0WM//CXGcS6xiD0rNkqHmw6FEg4tabt4nxPLwgCWT+Vb2A==}
-
- '@dagrejs/[email protected]':
- resolution: {integrity: sha512-7xrBTqIts3o+PMUZX97wSc+7TUbW+/rULzGNCTP6yooNVDXbzw4Wutg/H/xOutTB/c/k0YqOAavgPh4/Zk9PFA==}
-
'@date-fns/[email protected]':
resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}
@@ -1359,12 +1326,6 @@ packages:
react: '>=16.8.0'
react-dom: '>=16.8.0'
- '@dnd-kit/[email protected]':
- resolution: {integrity: sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==}
- peerDependencies:
- '@dnd-kit/core': ^6.3.0
- react: '>=16.8.0'
-
'@dnd-kit/[email protected]':
resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==}
peerDependencies:
@@ -4170,11 +4131,6 @@ packages:
'@tiptap/core': 3.31.4
'@tiptap/pm': 3.31.4
- '@tiptap/[email protected]':
- resolution: {integrity: sha512-vtD+rK73abJnPRKOjU37sQTCa5Auyg451yhqZD/3lZKiFJDBHAZKI7lQARkXBQYK289hBhK6yMIwofoqCBvi3g==}
- peerDependencies:
- '@tiptap/core': 3.31.4
-
'@tiptap/[email protected]':
resolution: {integrity: sha512-pftTQBPYZocNDAj/u6OyDIp7YxmN0+N895cQPogJQ6qMHdLiRhzgawiEewJkniyN1w8k3Wx/Etp8pTKrxaOOBQ==}
peerDependencies:
@@ -4229,11 +4185,6 @@ packages:
peerDependencies:
'@tiptap/core': 3.31.4
- '@tiptap/[email protected]':
- resolution: {integrity: sha512-Z8x/x2N4BiFwu7+UfJABT/OQbwZPUHbmvAH6Fo5lefgeIlTwAXFBzz4x7Eeed7iJAcXUzOnyd6bmkhK36gYJ2g==}
- peerDependencies:
- '@tiptap/core': 3.31.4
-
'@tiptap/[email protected]':
resolution: {integrity: sha512-WL2ZRpFksgQcXJN05/UQH09YCH9LlhdLrSEcviASvEH/aAfsKiJlDrouN8PET+YAWK/F5xFc5/Q1z0xj+I23jw==}
peerDependencies:
@@ -4250,12 +4201,6 @@ packages:
'@tiptap/core': 3.31.4
'@tiptap/pm': 3.31.4
- '@tiptap/[email protected]':
- resolution: {integrity: sha512-lmR9V1/eQ41BaR2zBgYG/+Liy7K7Ch17ZNxVy8dpUVlNpWxxoHUMXNsCg2uEyXP3NLpZaKiY0+drSu9oK1DbSA==}
- peerDependencies:
- '@tiptap/core': 3.31.4
- '@tiptap/pm': 3.31.4
-
'@tiptap/[email protected]':
resolution: {integrity: sha512-x7dwth79cQp4QGae66/RJqMDJQv0+n7b7dD7cyFQBWqzPFLJxN/4paHY4qbWedZjNLhRyIOAD9a5q4AYM1zmPA==}
@@ -4754,22 +4699,6 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==}
- '@xyflow/[email protected]':
- resolution: {integrity: sha512-74oXI0Rgm1Eu33cHQAd74J6oVgCH9mbFyTVQbsGgp2kmWwh0HdtBr2VP04z8mbPD+M/xO69nqG5dDEt7/EN2rQ==}
- peerDependencies:
- '@types/react': '>=17'
- '@types/react-dom': '>=17'
- react: '>=17'
- react-dom: '>=17'
- peerDependenciesMeta:
- '@types/react':
- optional: true
- '@types/react-dom':
- optional: true
-
- '@xyflow/[email protected]':
- resolution: {integrity: sha512-a//eDjez3WZF47aaPTfVUDD0OINOq+WVwBZCRTqG+m0a5euX8EwlJ4jMY1Wxz0Ocj4xOeekJ70V22Pq0ll8RJw==}
-
resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}
engines: {node: '>=6.5'}
@@ -5298,9 +5227,6 @@ packages:
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
- resolution: {integrity: sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==}
-
resolution: {integrity: sha512-8lgKz8LmCRYZZQDpRyT2m5rKJ08TnU4tR9FFFW2rxpxR1FzWi4PQ/NfyODchAatHaUgnSPVcx/R5w6NuTBzFiw==}
engines: {node: '>=4'}
@@ -5872,9 +5798,6 @@ packages:
resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-+8/IO7h1v14IzWh2GP60N7T3PFZweXwdn5e5POuxRSBoCYUojsBxzqawPeXh3YZIibRy7EehYNEyxe7slwwtdg==}
-
resolution: {integrity: sha512-CAloER21cDdcgZ1OmjrZX82EeRNsdP+y0onX/eyoYDaYzki/adrAa91lzM5jWh7zZPK4qUbw/6LGv9J+A+uizA==}
peerDependencies:
@@ -7545,11 +7468,6 @@ packages:
engines: {node: '>= 20'}
hasBin: true
- resolution: {integrity: sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA==}
- engines: {node: '>= 20'}
- hasBin: true
-
resolution: {integrity: sha512-mBHK6FBHuBAlhgRe88w9F0O1AbwwXJUcQibUbC/QcdTbVGAD7aWza+xt3N6oT/jCZx3/OMeS+8rnuiHZcQ9s7A==}
engines: {node: '>= 20'}
@@ -9995,21 +9913,6 @@ packages:
resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}
- resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
- engines: {node: '>=12.7.0'}
- peerDependencies:
- '@types/react': '>=16.8'
- immer: '>=9.0.6'
- react: '>=16.8'
- peerDependenciesMeta:
- '@types/react':
- optional: true
- immer:
- optional: true
- react:
- optional: true
-
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -11004,12 +10907,6 @@ snapshots:
'@csstools/[email protected]': {}
- '@dagrejs/[email protected]':
- dependencies:
- '@dagrejs/graphlib': 4.0.5
-
- '@dagrejs/[email protected]': {}
-
'@date-fns/[email protected]':
optional: true
@@ -11026,13 +10923,6 @@ snapshots:
react-dom: 19.3.0([email protected])
tslib: 2.8.1
- dependencies:
- '@dnd-kit/utilities': 3.2.2([email protected])
- react: 19.3.0
- tslib: 2.8.1
-
dependencies:
@@ -13505,10 +13395,6 @@ snapshots:
'@tiptap/core': 3.31.4(@tiptap/[email protected])
'@tiptap/pm': 3.31.4
- dependencies:
- '@tiptap/core': 3.31.4(@tiptap/[email protected])
-
dependencies:
'@tiptap/core': 3.31.4(@tiptap/[email protected])
@@ -13554,10 +13440,6 @@ snapshots:
dependencies:
'@tiptap/core': 3.31.4(@tiptap/[email protected])
- dependencies:
- '@tiptap/core': 3.31.4(@tiptap/[email protected])
-
dependencies:
'@tiptap/core': 3.31.4(@tiptap/[email protected])
@@ -13571,12 +13453,6 @@ snapshots:
'@tiptap/core': 3.31.4(@tiptap/[email protected])
'@tiptap/pm': 3.31.4
- dependencies:
- '@tiptap/core': 3.31.4(@tiptap/[email protected])
- '@tiptap/pm': 3.31.4
- marked: 17.0.6
-
'@tiptap/[email protected]':
dependencies:
prosemirror-changeset: 2.4.4
@@ -14167,31 +14043,6 @@ snapshots:
convert-source-map: 2.0.0
tinyrainbow: 3.1.1
- dependencies:
- '@xyflow/system': 0.0.83
- classcat: 5.0.5
- react: 19.3.0
- react-dom: 19.3.0([email protected])
- zustand: 4.5.7(@types/[email protected])([email protected])
- optionalDependencies:
- '@types/react': 19.3.0
- '@types/react-dom': 19.3.0(@types/[email protected])
- transitivePeerDependencies:
- - immer
-
- '@xyflow/[email protected]':
- dependencies:
- '@types/d3-drag': 3.0.7
- '@types/d3-interpolate': 3.0.4
- '@types/d3-selection': 3.0.12
- '@types/d3-transition': 3.0.9
- '@types/d3-zoom': 3.0.9
- d3-drag: 3.0.0
- d3-interpolate: 3.0.1
- d3-selection: 3.0.0
- d3-zoom: 3.0.0
-
dependencies:
event-target-shim: 5.0.1
@@ -14709,8 +14560,6 @@ snapshots:
dependencies:
clsx: 2.1.1
-
dependencies:
restore-cursor: 2.0.0
@@ -15273,8 +15122,6 @@ snapshots:
-
optionalDependencies:
'@cloudflare/workers-types': 5.20261002.1
@@ -17266,8 +17113,6 @@ snapshots:
-
@@ -20782,11 +20627,4 @@ snapshots:
- dependencies:
- use-sync-external-store: 1.7.0([email protected])
- optionalDependencies:
- '@types/react': 19.3.0
- react: 19.3.0
-
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 460ce58de..ebfdc3b7b 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -78,7 +78,7 @@ export const SPEC_SECONDS = {
"54-blog-multizone.spec.ts": 5.485,
"55-message-scroll-characterization.spec.ts": 109.548,
"56-inbox-friend-requests.spec.ts": 60,
- "56-remote-image-state-contract.spec.ts": 3.122,
+ "56-retired-workspace-links.spec.ts": DEFAULT_SPEC_SECONDS,
"57-server-delete-navigation-races.spec.ts": 55,
"58-system-notifications.spec.ts": 46.600,
"59-message-pagination-anchor.spec.ts": 45.600,
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index a78ef62ca..a740a1c80 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -75,17 +75,17 @@ describe("planE2eShards", () => {
expect(first).toEqual(second)
expect(Object.keys(SPEC_SECONDS).sort()).toEqual(specs)
- expect(first).toHaveLength(12)
+ expect(first).toHaveLength(13)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(109.548)
expect(specSeconds).toEqual([
- 165, 153.053, 151.656, 152.753, 153.443, 151.8, 154.215,
- 154.336, 153.99, 151.817, 154.381, 151.885,
+ 165, 165, 151.34, 151.656, 152.753, 152.602, 151.8,
+ 154.215, 154.336, 153.422, 151.817, 154.381, 151.885,
])
expect(predictedSeconds).toEqual([
- 240, 228.053, 226.656, 227.753, 228.443, 226.8, 229.215,
- 229.336, 228.99, 226.817, 229.381, 226.885,
+ 240, 240, 226.34, 226.656, 227.753, 227.602, 226.8,
+ 229.215, 229.336, 228.422, 226.817, 229.381, 226.885,
])
expect(first.every((shard) => (
shard.fixed_setup_seconds === E2E_FIXED_SETUP_SECONDS
diff --git a/src/web/knip.json b/src/web/knip.json
index 41dca1e77..57132b215 100644
--- a/src/web/knip.json
+++ b/src/web/knip.json
@@ -35,8 +35,7 @@
"shiki"
],
"ignore": [
- "src/components/ui/**",
- "src/app/(app)/workspaces/client.tsx"
+ "src/components/ui/**"
],
"vitest": {
"entry": ["src/**/*.test.{ts,tsx}", "blog/**/*.test.{ts,tsx}", "auth/**/*.test.ts", "scripts/**/*.test.ts", "src/test/**/*.{ts,tsx}", "test-runtime/**/*.test.ts"]
diff --git a/src/web/package.json b/src/web/package.json
index 3a5db4940..18b747757 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -44,9 +44,7 @@
"@atlaskit/pragmatic-drag-and-drop-hitbox": "2.2.2",
"@atlaskit/pragmatic-drag-and-drop-live-region": "2.1.0",
"@base-ui/react": "^1.8.0",
- "@dagrejs/dagre": "^3.1.1",
"@dnd-kit/core": "^6.3.1",
- "@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@emoji-mart/data": "^1.2.1",
@@ -79,24 +77,17 @@
"@tanstack/react-virtual": "^3.14.13",
"@tanstack/store": "0.11.2",
"@tauri-apps/plugin-clipboard-manager": "^2.4.1",
- "@tiptap/extension-image": "^3.31.4",
- "@tiptap/extension-link": "^3.31.4",
"@tiptap/extension-list": "^3.31.4",
"@tiptap/extension-mention": "^3.31.4",
"@tiptap/extension-placeholder": "^3.31.4",
- "@tiptap/extension-text-align": "^3.31.4",
- "@tiptap/extension-underline": "^3.31.4",
- "@tiptap/markdown": "^3.31.4",
"@tiptap/pm": "^3.31.4",
"@tiptap/react": "^3.31.4",
"@tiptap/starter-kit": "^3.31.4",
"@types/mdx": "^2.0.14",
"@typesafe-ai/sdk": "0.6.0",
- "@xyflow/react": "^12.12.0",
"better-auth": "1.7.7",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
- "driver.js": "^1.8.0",
"emoji-mart": "^5.6.0",
"gsap": "^3.15.0",
"html-to-image": "^1.11.13",
diff --git a/src/web/src/app/(app)/invite/[token]/page.tsx b/src/web/src/app/(app)/invite/[token]/page.tsx
deleted file mode 100644
index 52797d553..000000000
--- a/src/web/src/app/(app)/invite/[token]/page.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions";
-
-
-import { useQuery, useMutation, type Query } from "@tanstack/react-query";
-import { applicationKey, useApplicationOwner, runApplicationRequest } from "@/lib/application-owner";
-import { useApplicationViewSource } from "@/hooks/use-application-view-source";
-import { useParams, useRouter } from "next/navigation";
-import { toast } from "sonner";
-import { getInviteInfo, acceptInvite } from "@/lib/api";
-import { trackInviteAccepted } from "@/lib/analytics";
-import { Button } from "@/components/ui/button";
-import { Skeleton } from "@/components/ui/skeleton";
-
-type State = "loading" | "ready" | "error" | "accepting" | "done";
-
-export default function InvitePage() {
- const { token } = useParams<{ token: string }>();
- const router = useRouter();
-
- const owner = useApplicationOwner();
- const source = useApplicationViewSource(`workspace-invite:${token}`);
- const query = useQuery({ queryKey: applicationKey(owner, "workspace-invite", token), enabled: !!token, retry: false,
- queryFn: ({ signal }) => runApplicationRequest(owner, (options) => getInviteInfo(token, options), signal) });
- const command = useMutation({ meta: { observabilityAction: "workspace.invite.accept" }, mutationKey: applicationKey(owner, "workspace-invite", token, "accept"), gcTime: 0,
- mutationFn: async ({ original, resources }: { original: ReturnType<typeof source.capture>; resources: Query[] }) => {
- original.assert();
- const result = await acceptInvite(token, { authenticationAccount: owner.userId, signal: original.signal, assertActive: original.assert, onUnauthorized: async () => { original.assert(); return false; } });
- original.assert();
- await owner.queryClient.invalidateQueries({ queryKey: applicationKey(owner, "workspaces"), predicate: (query) => resources.includes(query) }, { cancelRefetch: false });
- original.assert();
- return result;
- } });
- const info = query.data;
- useObservedQueryRegion("page", query);
- const error = command.error ?? query.error;
- const errorMsg = error instanceof Error ? error.message : "Invalid or expired invite link";
- const state: State = command.isPending ? "accepting" : command.isSuccess ? "done" : error ? "error" : query.isPending ? "loading" : "ready";
-
- const handleAccept = async () => {
- if (!token || owner.queryClient.isMutating({ mutationKey: applicationKey(owner, "workspace-invite", token, "accept"), exact: true })) return;
- const original = source.capture();
- try {
- const result = await command.mutateAsync({ original, resources: owner.queryClient.getQueryCache().findAll({ queryKey: applicationKey(owner, "workspaces") }) });
- original.assert();
- trackInviteAccepted({ workspace_id: result.workspace_id ?? "" });
- toast.success(`Joined ${info?.workspace_name ?? "workspace"}`);
- router.replace(`/w/${result.workspace_slug}/home`);
- } catch {
- try { original.assert(); } catch { return; }
- }
- };
-
- return (
- <div className="min-h-screen flex items-center justify-center p-6">
- <div className="w-full max-w-sm space-y-6 text-center">
- {state === "loading" && (
- <div className="space-y-3">
- <Skeleton className="h-6 w-48 mx-auto" />
- <Skeleton className="h-4 w-64 mx-auto" />
- <Skeleton className="h-9 w-32 mx-auto" />
- </div>
- )}
-
- {state === "ready" && info && (
- <>
- <div className="space-y-1">
- <h1 className="text-xl font-semibold">You&apos;ve been invited</h1>
- <p className="text-sm text-muted-foreground">
- {info.invited_by} invited you to join
- </p>
- </div>
-
- <div className="rounded-md border border-border/50 px-4 py-3 text-left space-y-1">
- <p className="text-sm font-medium">{info.workspace_name}</p>
- <p className="text-xs text-muted-foreground">Workspace</p>
- </div>
-
- <Button className="w-full" onClick={handleAccept}>
- Join Workspace
- </Button>
- </>
- )}
-
- {state === "accepting" && (
- <div className="space-y-3">
- <Skeleton className="h-6 w-48 mx-auto" />
- <Skeleton className="h-4 w-64 mx-auto" />
- <p className="text-sm text-muted-foreground">Joining workspace…</p>
- </div>
- )}
-
- {state === "error" && (
- <>
- <div className="space-y-1">
- <h1 className="text-xl font-semibold">Invite unavailable</h1>
- <p className="text-sm text-muted-foreground">{errorMsg}</p>
- </div>
- <Button variant="outline" onClick={() => router.replace("/workspaces")}>
- Go to workspaces
- </Button>
- </>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/layout.dom.test.tsx b/src/web/src/app/(app)/layout.dom.test.tsx
deleted file mode 100644
index cb9b8e017..000000000
--- a/src/web/src/app/(app)/layout.dom.test.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { get, set } from "idb-keyval"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, render, waitFor } from "@/test/react-dom-harness"
-import AppLayout from "./layout"
-import { useApplicationOwner, type ApplicationOwner } from "@/lib/application-owner"
-import { clearAllPersistedCaches, createIdbPersister } from "@/lib/query-persister"
-
-const input = vi.hoisted(() => ({ serverId: "A", sdk: { data: { user: { id: "A" } }, isPending: false, error: null } }))
-vi.mock("@/lib/session", () => ({ getSession: async () => ({ user: { id: input.serverId } }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => input.sdk }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("next/navigation", () => ({ usePathname: () => "/w/test", useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }), redirect: vi.fn() }))
-vi.mock("@/components/authenticated-native-oauth-cleanup", () => ({ AuthenticatedNativeOauthCleanup: () => null }))
-vi.mock("@/components/signup-tracker", () => ({ SignupTracker: () => null }))
-vi.mock("@/components/signin-tracker", () => ({ SigninTracker: () => null }))
-vi.mock("@/components/daemon-update-notice", () => ({ DaemonUpdateNotice: () => null }))
-const owners: Record<string, ApplicationOwner> = {}
-function Probe() { const owner = useApplicationOwner(); useLayoutEffect(() => { owners[owner.userId] = owner }); return <output>{owner.userId}</output> }
-async function layout(id: string) { input.serverId = id; return AppLayout({ children: <Probe /> }) }
-beforeEach(async () => { await clearAllPersistedCaches(); input.sdk = { data: { user: { id: "A" } }, isPending: false, error: null } })
-afterEach(async () => {
- await act(async () => {
- for (const owner of Object.values(owners)) owner.queryClient.clear(); for (const key of Object.keys(owners)) delete owners[key]
- })
-})
-
-describe("actual authenticated AppLayout identity boundary", () => {
- it("retires A when immutable public SDK output and the server layout account change in one commit", async () => {
- const view = render(await layout("A"))
- await waitFor(() => expect(owners.A?.sessionViewer()).toBe("A"))
- const old = owners.A, a = createIdbPersister("A", "application"), b = createIdbPersister("B", "application")
- await act(async () => { await a.restoreClient(); }) ; await act(async () => { await b.restoreClient(); }) ; await act(async () => { await set("alook:qc:v2:A:client", "old A"); }) ; await act(async () => { await set("alook:qc:v2:B:client", "old B") }) ;
- const next = await layout("B")
- act(() => { input.sdk = { data: { user: { id: "B" } }, isPending: false, error: null }; view.rerender(next) })
- await waitFor(() => expect(owners.B?.sessionViewer()).toBe("B"))
- expect(old.lifecycle.get().active).toBe(false)
- await waitFor(async () => expect(await a.isCurrent()).toBe(false))
- expect(await get("alook:qc:v2:A:client")).toBeUndefined()
- expect(await get("alook:qc:v2:B:client")).toBe("old B"); expect(await b.isCurrent()).toBe(true)
- expect(owners.B.lifecycle.get().active).toBe(true)
- })
- it("preserves A disk when the same-viewer layout leaves an ordinary route", async () => {
- const view = render(await layout("A"))
- await waitFor(() => expect(owners.A?.sessionViewer()).toBe("A"))
- const a = createIdbPersister("A", "application"); await act(async () => { await a.restoreClient(); }) ; await act(async () => { await set("alook:qc:v2:A:client", "old A") }) ;
- act(() => view.rerender(<p>Public route</p>))
- await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
- expect(await a.isCurrent()).toBe(true); expect(await get("alook:qc:v2:A:client")).toBe("old A")
- })
-})
diff --git a/src/web/src/app/(app)/layout.tsx b/src/web/src/app/(app)/layout.tsx
deleted file mode 100644
index f7a1cbf2c..000000000
--- a/src/web/src/app/(app)/layout.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { ApplicationQueryProvider } from "@/lib/application-owner";
-import type { Metadata } from "next";
-import { redirect } from "next/navigation";
-import { getSession } from "@/lib/session";
-import { SignupTracker } from "@/components/signup-tracker";
-import { SigninTracker } from "@/components/signin-tracker";
-import { DaemonUpdateNotice } from "@/components/daemon-update-notice";
-import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary";
-import { AuthenticatedNativeOauthCleanup } from "@/components/authenticated-native-oauth-cleanup";
-
-export const metadata: Metadata = {
- robots: { index: false, follow: false },
-};
-
-export default async function AppLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
- const session = await getSession();
- if (!session) redirect("/sign-in");
-
- return (
- <ApplicationQueryProvider userId={session.user.id}>
- <AuthenticatedContextMenuBoundary>
- <AuthenticatedNativeOauthCleanup />
- <SignupTracker />
- <SigninTracker />
- <DaemonUpdateNotice userId={session.user.id} />
- {children}
- </AuthenticatedContextMenuBoundary>
- </ApplicationQueryProvider>
- );
-}
diff --git a/src/web/src/app/(app)/studio/new/backfill.test.ts b/src/web/src/app/(app)/studio/new/backfill.test.ts
deleted file mode 100644
index f182869bc..000000000
--- a/src/web/src/app/(app)/studio/new/backfill.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { describe, it, expect } from "vitest";
-
-type Member = { uid: string; name: string; emailHandle?: string };
-
-function backfill(members: Member[], handles: { uid: string; handle: string }[]): Member[] {
- return members.map((m) => {
- const h = handles.find((h) => h.uid === m.uid);
- return h ? { ...m, emailHandle: h.handle } : m;
- });
-}
-
-describe("studio handle backfill by uid", () => {
- it("maps each same-name member to its own uid's handle without crossing", () => {
- const members: Member[] = [
- { uid: "a", name: "Ada" },
- { uid: "b", name: "Ada" },
- ];
- const handles = [
- { uid: "a", handle: "ada" },
- { uid: "b", handle: "ada-blue" },
- ];
-
- const result = backfill(members, handles);
-
- expect(result[0].emailHandle).toBe("ada");
- expect(result[1].emailHandle).toBe("ada-blue");
- });
-
- it("does not cross when response order differs from member order", () => {
- const members: Member[] = [
- { uid: "a", name: "Ada" },
- { uid: "b", name: "Ada" },
- ];
- const handles = [
- { uid: "b", handle: "ada-blue" },
- { uid: "a", handle: "ada" },
- ];
-
- const result = backfill(members, handles);
-
- expect(result[0].emailHandle).toBe("ada");
- expect(result[1].emailHandle).toBe("ada-blue");
- });
-
- it("leaves emailHandle unset for members with no matching uid", () => {
- const members: Member[] = [{ uid: "a", name: "Ada" }];
- const result = backfill(members, [{ uid: "z", handle: "zed" }]);
- expect(result[0].emailHandle).toBeUndefined();
- });
-});
diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsx
deleted file mode 100644
index b5c0802b2..000000000
--- a/src/web/src/app/(app)/studio/new/client.tsx
+++ /dev/null
@@ -1,395 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useEffect, useMemo } from "react";
-import { useQuery, useMutation } from "@tanstack/react-query";
-import { WorkspaceProvider, useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { apiFetch } from "@/lib/api/client";
-import { applicationKey } from "@/lib/application-owner";
-import { useRouter } from "next/navigation";
-import { Button } from "@/components/ui/button";
-import { Loader2, CheckCircle2, LogOut, ArrowLeft, LayoutGrid } from "lucide-react";
-import { toast } from "sonner";
-import { toastApiError } from "@/lib/api/client";
-import { useApplicationSignOut } from "@/hooks/use-application-sign-out";
-import { assertApplicationOwner, captureApplicationOwner } from "@/lib/application-owner";
-import { useApplicationOwner } from "@/lib/application-owner";
-import { trackWorkspaceCreated, trackOnboardingCompleted, trackAgentCreated } from "@/lib/analytics";
-
-import { PublicLayout } from "@/components/public-layout";
-import { ScenarioPicker } from "@/components/studio-onboarding/scenario-picker";
-import { TeamPreview, type TeamMember } from "@/components/studio-onboarding/team-preview";
-import {
- SCENARIO_PRESETS,
- shuffleMembers,
- type ScenarioId,
-} from "@/components/studio-onboarding/scenario-presets";
-
-import type { AgentRuntime as Runtime } from "@alook/shared";
-import type { WsMessage } from "@alook/shared";
-import { listRuntimes, createMachineToken } from "@/lib/api";
-import { useUserWs } from "@/lib/use-user-ws";
-import { ConnectMachineSteps } from "@/components/connect-machine-steps";
-import type { TemplatePreset } from "@/lib/templates";
-
-export function StudioOnboardingClient(props: { workspaceId: string; workspaceSlug: string; initialTemplate?: TemplatePreset }) {
- return <WorkspaceProvider workspaceId={props.workspaceId} slug={props.workspaceSlug}><StudioOnboardingInner {...props} /></WorkspaceProvider>;
-}
-
-function StudioOnboardingInner({
- workspaceId,
- workspaceSlug,
- initialTemplate,
-}: {
- workspaceId: string;
- workspaceSlug: string;
- initialTemplate?: TemplatePreset;
-}) {
- const applicationOwner = useApplicationOwner();
- const logout = useApplicationSignOut();
- const onLogout = async () => {
- const token = captureApplicationOwner(applicationOwner);
- try { if (await logout.mutateAsync()) router.push("/sign-in"); }
- catch (error) { toastApiError(error, "Failed to log out", () => assertApplicationOwner(token)); }
- };
- const router = useRouter();
-
- const owner = useWorkspaceOwner();
- const source = useWorkspaceViewSource(owner, "studio-onboarding", true);
- const runtimesKey = owner.key("runtimes");
- const runtimesQuery = useQuery({ queryKey: runtimesKey,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listRuntimes(workspaceId, options), signal),
- refetchInterval: 30_000, refetchIntervalInBackground: false,
- });
- const runtimes = runtimesQuery.data ?? [];
- useObservedQueryRegion("runtimes", runtimesQuery);
- const loadingRuntimes = runtimesQuery.isPending;
- const [scenarioId, setScenarioId] = useAtom(useCreateAtom<ScenarioId | null>(initialTemplate ? initialTemplate.baseScenario : null));
- const [memberDrafts, setMembers] = useAtom(useCreateAtom<TeamMember[]>([]));
- const [registeredDaemonId, setRegisteredDaemonId] = useAtom(useCreateAtom<string | null>(null));
- const handlesQuery = useQuery({
- queryKey: owner.key("studio-handles", memberDrafts.map(({ uid, name }) => ({ uid, name }))),
- enabled: memberDrafts.length > 0, retry: false, gcTime: 0,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => apiFetch<{ uid: string; handle: string }[]>("/api/studios/check-handles", {
- ...options, method: "POST", body: JSON.stringify({ members: memberDrafts.map(({ uid, name }) => ({ uid, name })) }),
- }), signal),
- });
- const members = useMemo(() => memberDrafts.map((member) => ({
- ...member, emailHandle: handlesQuery.data?.find((row) => row.uid === member.uid)?.handle,
- })), [memberDrafts, handlesQuery.data]);
- const tokenQuery = useQuery({ queryKey: owner.key("studio-pairing"), enabled: false, gcTime: 0, retry: false,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => createMachineToken("cli", workspaceId, options), signal),
- });
- const generatedToken = tokenQuery.data?.token ?? "";
- const generatingToken = tokenQuery.isFetching;
- const onlineRuntimes = useMemo(() => (runtimesQuery.data ?? []).filter((runtime) => runtime.status === "online"), [runtimesQuery.data]);
- const hasOnlineRuntime = onlineRuntimes.length > 0;
- const daemonOnline = registeredDaemonId ? runtimes.some((runtime) => runtime.daemon_id === registeredDaemonId && runtime.status === "online") : hasOnlineRuntime;
- const machineRegistered = !!registeredDaemonId || hasOnlineRuntime;
- const computerConnected = hasOnlineRuntime;
-
- const handleWsMessage = useCallback((message: WsMessage) => {
- try { source.assertActive(); } catch { return; }
- if (message.type === "runtime.registered" && message.workspaceId === workspaceId) {
- setRegisteredDaemonId(message.daemonId);
- void owner.queryClient.invalidateQueries({ queryKey: runtimesKey, exact: true });
- } else if (message.type === "runtime.status" && (!message.workspaceId || message.workspaceId === workspaceId)) {
- setRegisteredDaemonId(message.daemonId);
- void owner.queryClient.invalidateQueries({ queryKey: runtimesKey, exact: true });
- }
- }, [workspaceId, source, setRegisteredDaemonId, owner.queryClient, runtimesKey]);
-
- useUserWs(handleWsMessage, { onReconnect: () => { try { source.assertActive(); } catch { return; } return owner.queryClient.invalidateQueries({ queryKey: runtimesKey, exact: true }); } });
-
- const handleGenerateToken = async () => {
- const assert = source.assertActive;
- assert();
- try {
- const result = await tokenQuery.refetch({ cancelRefetch: false, throwOnError: true });
- assert();
- return result.data;
- } catch (error) {
- try { assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error("Failed to generate token");
- }
- };
-
- useEffect(() => {
- const firstOnline = onlineRuntimes[0]?.id;
- if (!firstOnline) return;
- setMembers((previous) => previous.some((member) => !member.runtimeId) ? previous.map((member) => member.runtimeId ? member : { ...member, runtimeId: firstOnline }) : previous);
- }, [onlineRuntimes, setMembers]);
-
- useEffect(() => {
- if (!initialTemplate || loadingRuntimes || memberDrafts.length > 0) return;
- const generated = shuffleMembers(initialTemplate.members.length);
- const defaultRuntimeId = onlineRuntimes[0]?.id || "";
- setMembers(initialTemplate.members.map((member, index) => ({
- uid: generated[index].uid, name: generated[index].name, role: member.role,
- description: member.description, instructions: member.instructions, avatarUrl: generated[index].avatarUrl,
- runtimeId: defaultRuntimeId, relationship: member.relationship,
- })));
- }, [initialTemplate, loadingRuntimes, memberDrafts.length, onlineRuntimes, setMembers]);
-
- const handleScenarioSelect = (id: ScenarioId) => {
- setScenarioId(id);
- const preset = SCENARIO_PRESETS.find((scenario) => scenario.id === id)!;
- const generated = shuffleMembers(preset.members.length);
- const defaultRuntimeId = onlineRuntimes[0]?.id || "";
- setMembers(preset.members.map((member, index) => ({
- uid: generated[index].uid, name: generated[index].name, role: member.role,
- description: member.description, instructions: member.instructions, avatarUrl: generated[index].avatarUrl,
- runtimeId: defaultRuntimeId, relationship: member.relationship,
- })));
- };
-
- const handleShuffle = () => {
- const generated = shuffleMembers(memberDrafts.length);
- setMembers((previous) => previous.map((member, index) => ({ ...member, uid: generated[index].uid, name: generated[index].name, avatarUrl: generated[index].avatarUrl })));
- };
-
- const handleAssignRuntime = (memberIndex: number, runtimeId: string) => {
- setMembers((previous) => previous.map((member, index) => index === memberIndex ? { ...member, runtimeId } : member));
- };
-
- const createCommand = useMutation({ meta: { observabilityAction: "studio.agent.create" }, gcTime: 0, mutationKey: owner.key("studio-create"), scope: { id: JSON.stringify(owner.key("studio-create")) },
- mutationFn: async ({ scenario, members, token }: { scenario: ScenarioId; members: TeamMember[]; token: ReturnType<typeof captureWorkspaceOwner> }) => {
- const assert = () => assertWorkspaceOwner(token);
- assert();
- let readyMembers = members;
- if (members.some((member) => !member.runtimeId)) {
- const fresh = await owner.queryClient.fetchQuery({ queryKey: runtimesKey,
- queryFn: ({ signal }) => listRuntimes(workspaceId, workspaceRequestOptions(token, signal)), staleTime: 0,
- });
- assert();
- const firstOnline = fresh.find((runtime) => runtime.status === "online")?.id;
- if (!firstOnline) throw new Error("No online runtime to assign — connect a computer and try again");
- readyMembers = members.map((member) => member.runtimeId ? member : { ...member, runtimeId: firstOnline });
- }
- const options = workspaceRequestOptions(token);
- try {
- const data = await apiFetch<{ workspace: { slug: string }; leader_agent_id: string }>("/api/studios", {
- ...options, method: "POST", headers: { "X-Workspace-ID": workspaceId },
- body: JSON.stringify({ scenario, members: readyMembers.map((member) => ({
- name: member.name, role: member.role, runtime_id: member.runtimeId, description: member.description,
- instructions: member.instructions, avatar_url: member.avatarUrl || null, email_handle: member.emailHandle || undefined,
- relationship: member.relationship || undefined,
- })) }),
- });
- assert();
- await apiFetch(`/api/workspaces/${workspaceId}/onboarded`, { ...options, method: "POST" }).catch((error) => { assert(); if (error instanceof DOMException && error.name === "AbortError") throw error; });
- assert();
- await owner.queryClient.invalidateQueries({ queryKey: applicationKey(applicationOwner, "workspaces") });
- assert();
- return data;
- } catch (error) { assert(); throw error; }
- },
- });
- const creating = createCommand.isPending;
- const handleCreate = async () => {
- if (!scenarioId) { toast.error("Pick a focus area first"); return; }
- if (!members.length) { toast.error("Add at least one team member"); return; }
- if (!computerConnected) { toast.error("Connect a computer first — no runtime is online yet"); return; }
- const assert = source.assertActive;
- const token = captureWorkspaceOwner(owner);
- const scenario = scenarioId;
- const team = members;
- assert();
- try {
- const data = await createCommand.mutateAsync({ scenario, members: team, token });
- assert();
- trackWorkspaceCreated("onboarding");
- trackOnboardingCompleted({ template_used: scenario, agent_count: team.length });
- team.forEach((member, index) => trackAgentCreated({ is_first_agent: index === 0, has_email: !!member.emailHandle }));
- toast.success("Company created!");
- router.push(`/w/${data.workspace.slug}/agents/${data.leader_agent_id}`);
- } catch (error) {
- try { assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(error instanceof Error ? error.message : "Failed to create company");
- }
- };
-
-
- const finishCommand = useMutation({ meta: { observabilityAction: "studio.onboarding.finish" }, mutationKey: owner.key("studio-finish"), gcTime: 0,
- mutationFn: async (intent: ReturnType<typeof source.capture> & { resources: import("@tanstack/react-query").Query[] }) => {
- intent.assert();
- await apiFetch(`/api/workspaces/${workspaceId}/onboarded`, { ...workspaceRequestOptions(intent.token, intent.signal, intent.assert), method: "POST" });
- intent.assert();
- await owner.queryClient.invalidateQueries({ predicate: (query) => intent.resources.includes(query) });
- intent.assert();
- router.push(`/w/${workspaceSlug}/home`);
- },
- onError: (error, intent) => { try { intent.assert(); } catch { return; } toastApiError(error, "Failed to finish onboarding", intent.assert); },
- });
- const finishOnboarding = () => {
- if (owner.queryClient.isMutating({ mutationKey: owner.key("studio-finish"), exact: true })) return;
- const intent = source.capture(); intent.assert();
- finishCommand.mutate({ ...intent, resources: owner.queryClient.getQueryCache().findAll({ queryKey: applicationKey(applicationOwner, "workspaces") }) });
- };
-
- if (!scenarioId) {
- return (
- <PublicLayout
- leftSlot={
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground"
- onClick={() => router.push("/workspaces")}
- >
- <LayoutGrid className="size-3 mr-2" />
- Workspaces
- </Button>
- }
- rightSlot={
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground"
- onClick={onLogout}
- >
- <LogOut className="size-3 mr-2" />
- Sign out
- </Button>
- }
- mainClassName="flex items-center justify-center"
- >
- <div className="w-full max-w-3xl space-y-8 px-6 py-6">
- <div className="text-center space-y-2">
- <h1
- className="text-2xl font-semibold tracking-tight"
- style={{ fontFamily: "var(--font-news)" }}
- >
- What will your company do?
- </h1>
- <p className="text-sm text-muted-foreground">
- Pick a focus area. You can always add more agents later.
- </p>
- </div>
-
- <ScenarioPicker selected={scenarioId} onSelect={handleScenarioSelect} onBrowseTemplates={() => router.push(`/templates?workspace_id=${workspaceId}`)} />
-
- <div className="flex justify-center pt-2">
- <button
- type="button"
- onClick={finishOnboarding}
- disabled={finishCommand.isPending}
- className="text-xs text-muted-foreground hover:text-foreground transition-colors"
- >
- Skip for now
- </button>
- </div>
- </div>
- </PublicLayout>
- );
- }
-
- return (
- <PublicLayout
- leftSlot={
- <>
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground"
- onClick={() => router.push("/workspaces")}
- >
- <LayoutGrid className="size-3 mr-2" />
- Workspaces
- </Button>
- <span className="text-muted-foreground/40">/</span>
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground"
- onClick={() => setScenarioId(null)}
- >
- <ArrowLeft className="size-3 mr-2" />
- Back
- </Button>
- </>
- }
- rightSlot={
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground"
- onClick={onLogout}
- >
- <LogOut className="size-3 mr-2" />
- Sign out
- </Button>
- }
- >
- <div className="mx-auto w-full max-w-3xl space-y-10 px-6 py-14">
- <div className="text-center">
- <h1
- className="text-2xl font-semibold tracking-tight"
- style={{ fontFamily: "var(--font-news)" }}
- >
- Build your company
- </h1>
- </div>
-
- {loadingRuntimes ? (
- <div className="flex justify-center py-8">
- <Loader2 className="size-5 animate-spin text-muted-foreground" />
- </div>
- ) : (
- <>
- {/* Team Preview */}
- <TeamPreview
- members={members}
- runtimes={onlineRuntimes as Runtime[]}
- onShuffle={handleShuffle}
- onAssignRuntime={handleAssignRuntime}
- />
-
- <div className="space-y-3">
- {computerConnected ? (
- <p className="text-xs text-emerald-600 flex items-center gap-1">
- <CheckCircle2 className="size-3" /> Computer connected
- </p>
- ) : (
- <>
- <p className="text-xs text-muted-foreground">
- Your company needs a connected computer to run tasks.
- </p>
- <div className="rounded-xl bg-muted/40 p-4">
- <ConnectMachineSteps
- generatedToken={generatedToken}
- generatingToken={generatingToken}
- onGenerateToken={handleGenerateToken}
- registered={machineRegistered}
- daemonOnline={daemonOnline}
- />
- </div>
- </>
- )}
- </div>
-
- {/* Create */}
- <Button
- onClick={handleCreate}
- disabled={creating || !computerConnected}
- className="w-full"
- size="lg"
- >
- {creating ? (
- <>
- <Loader2 className="size-4 animate-spin mr-2" />
- Launching...
- </>
- ) : (
- "Launch company"
- )}
- </Button>
- </>
- )}
- </div>
- </PublicLayout>
- );
-}
diff --git a/src/web/src/app/(app)/studio/new/page.tsx b/src/web/src/app/(app)/studio/new/page.tsx
deleted file mode 100644
index b97b59507..000000000
--- a/src/web/src/app/(app)/studio/new/page.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { redirect } from "next/navigation";
-import { getCloudflareContext } from "@opennextjs/cloudflare";
-import { queries } from "@alook/shared";
-import { getDb } from "@/lib/db";
-import { requireSession } from "@/lib/session";
-import { getTemplateById } from "@/lib/templates";
-import { StudioOnboardingClient } from "./client";
-
-export default async function StudioNewPage({
- searchParams,
-}: {
- searchParams: Promise<Record<string, string | undefined>>;
-}) {
- const session = await requireSession();
- const { env } = await getCloudflareContext({ async: true });
- const db = getDb((env as Env).DB);
-
- const params = await searchParams;
- const templateId = params.template;
- const initialTemplate = templateId ? getTemplateById(templateId) : undefined;
-
- const workspaceId = params.workspace_id ?? null;
-
- if (!workspaceId) {
- redirect("/workspaces");
- }
-
- const membership = await queries.member.getMemberByUserAndWorkspace(
- db,
- session.user.id,
- workspaceId,
- );
- if (!membership) redirect("/workspaces");
-
- const workspace = await queries.workspace.getWorkspace(db, workspaceId, session.user.id);
- if (!workspace) redirect("/workspaces");
-
- return (
- <StudioOnboardingClient
- workspaceId={workspaceId}
- workspaceSlug={workspace.slug}
- initialTemplate={initialTemplate}
- />
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx
deleted file mode 100644
index a6761644f..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx
+++ /dev/null
@@ -1,370 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useEffect, useCallback, useRef, useMemo } from "react";
-import { useInfiniteQuery, useMutation } from "@tanstack/react-query";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { useParams, useRouter, useSearchParams } from "next/navigation";
-import Link from "next/link";
-import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { listAgentActivity, retryTask, type ActivityTask } from "@/lib/api";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectContent,
- SelectItem,
-} from "@/components/ui/select";
-import {
- MessageSquare,
- Mail,
- CalendarDays,
- CircleDot,
- History,
- RotateCw,
- Loader2,
-} from "lucide-react";
-import { ScrollToBottomButton } from "@/components/ui/scroll-to-bottom-button";
-
-const ACTIVITY_LIMIT = 30;
-
-const STATUS_OPTIONS = [
- { label: "All", value: "" },
- { label: "Queued", value: "queued,dispatched" },
- { label: "Running", value: "running" },
- { label: "Completed", value: "completed" },
- { label: "Failed", value: "failed" },
- { label: "Cancelled", value: "cancelled,superseded" },
-];
-
-const TYPE_OPTIONS = [
- { label: "All", value: "" },
- { label: "Message", value: "user_dm_message" },
- { label: "Email", value: "email_notification" },
- { label: "Calendar", value: "calendar_event" },
-];
-
-function relativeTime(dateStr: string): string {
- const date = new Date(dateStr);
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMin = Math.floor(diffMs / 60000);
- if (diffMin < 1) return "just now";
- if (diffMin < 60) return `${diffMin}m ago`;
- const diffHrs = Math.floor(diffMin / 60);
- if (diffHrs < 24) return `${diffHrs}h ago`;
- const diffDays = Math.floor(diffHrs / 24);
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
-}
-
-function formatDuration(startedAt: string | null, completedAt: string | null): string | null {
- if (!startedAt || !completedAt) return null;
- const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime();
- const totalSeconds = Math.max(0, Math.floor(ms / 1000));
- if (totalSeconds >= 3600) {
- const h = Math.floor(totalSeconds / 3600);
- const m = Math.floor((totalSeconds % 3600) / 60);
- return `${h}h ${m}m`;
- }
- if (totalSeconds >= 60) {
- const m = Math.floor(totalSeconds / 60);
- const s = totalSeconds % 60;
- return `${m}m ${s}s`;
- }
- return `${totalSeconds}s`;
-}
-
-const TYPE_ICONS: Record<string, typeof MessageSquare> = {
- user_dm_message: MessageSquare,
- email_notification: Mail,
- calendar_event: CalendarDays,
-};
-
-const STATUS_LABELS: Record<string, string> = {
- queued: "Queued",
- dispatched: "Queued",
- running: "Running",
- completed: "Completed",
- failed: "Failed",
- cancelled: "Cancelled",
- superseded: "Cancelled",
-};
-
-const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "superseded"]);
-
-function StatusDot({ status }: { status: string }) {
- const colorClass =
- status === "completed"
- ? "bg-[oklch(0.72_0.19_145)]"
- : status === "failed"
- ? "bg-destructive"
- : status === "running"
- ? "bg-primary animate-pulse"
- : "bg-muted-foreground/40";
-
- return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;
-}
-
-function ActivityRow({ task, slug, agentId, workspaceId, onRetry }: { task: ActivityTask; slug: string; agentId: string; workspaceId: string; onRetry: () => void }) {
- const Icon = TYPE_ICONS[task.type] ?? CircleDot;
- const duration = TERMINAL_STATUSES.has(task.status)
- ? formatDuration(task.started_at, task.completed_at)
- : null;
-
- const owner = useWorkspaceOwner();
- const source = useWorkspaceViewSource(owner, "activity-retry:" + task.id, true);
- const retry = useMutation({ meta: { observabilityAction: "agent.task.retry" },
- mutationKey: owner.key("task-retry", task.id),
- mutationFn: async (token: ReturnType<typeof captureWorkspaceOwner>) => {
- const assertActive = () => assertWorkspaceOwner(token);
- assertActive();
- try {
- await retryTask(task.id, workspaceId, workspaceRequestOptions(token));
- assertActive();
- await owner.queryClient.invalidateQueries({ queryKey: owner.key("agent-activity", agentId) });
- assertActive();
- } catch (error) { assertActive(); throw error; }
- },
- });
- const retrying = retry.isPending;
- const handleRetry = async (e: React.MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
- const assertView = source.assertActive;
- try {
- await retry.mutateAsync(captureWorkspaceOwner(owner));
- assertView();
- onRetry();
- } catch { }
- };
-
- return (
- <Link
- href={`/w/${slug}/agents/${agentId}?task=${task.id}&conv=${task.conversation_id}`}
- className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
- >
- <div className="flex items-center gap-2 min-w-0">
- <Icon className="shrink-0 size-3.5 text-muted-foreground" />
- <span className="text-sm text-foreground truncate flex-1 min-w-0">
- {task.prompt}
- </span>
- <Tooltip>
- <TooltipTrigger render={<span className="text-xs text-muted-foreground shrink-0 ml-2" />}>
- {relativeTime(task.created_at)}
- </TooltipTrigger>
- <TooltipContent>{new Date(task.created_at).toLocaleString()}</TooltipContent>
- </Tooltip>
- </div>
- <div className="flex items-center gap-2 mt-1 ml-6">
- <StatusDot status={task.status} />
- <span className="text-xs text-muted-foreground">
- {STATUS_LABELS[task.status] ?? task.status}
- </span>
- {duration && (
- <>
- <span className="text-muted-foreground/40">·</span>
- <span className="text-xs text-muted-foreground">{duration}</span>
- </>
- )}
- {task.status === "failed" && task.error && (
- <>
- <span className="text-muted-foreground/40">—</span>
- <span className="text-xs text-destructive truncate max-w-50">
- {task.error}
- </span>
- </>
- )}
- {task.status === "failed" && (
- <Tooltip>
- <TooltipTrigger render={<Button
- variant="ghost"
- size="icon-sm"
- onClick={handleRetry}
- disabled={retrying}
- className="ml-auto text-muted-foreground"
- />}>
- {retrying
- ? <Loader2 className="size-3 animate-spin" />
- : <RotateCw className="size-3" />}
- </TooltipTrigger>
- <TooltipContent>Retry task</TooltipContent>
- </Tooltip>
- )}
- </div>
- </Link>
- );
-}
-
-function SkeletonRow({ promptWidth }: { promptWidth: string }) {
- return (
- <div className="px-4 py-3 border-b border-border/30">
- <div className="flex items-center gap-2">
- <Skeleton className="h-3.5 w-4 rounded shrink-0" />
- <Skeleton className={`h-3.5 rounded`} style={{ width: promptWidth }} />
- <Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" />
- </div>
- <div className="flex items-center gap-2 mt-1 ml-6">
- <Skeleton className="h-2.5 w-20 rounded-full" />
- <Skeleton className="h-2.5 w-8 rounded" />
- </div>
- </div>
- );
-}
-
-export default function AgentActivityPage() {
- const params = useParams();
- const router = useRouter();
- const searchParams = useSearchParams();
- const agentId = params.id as string;
-
- const owner = useWorkspaceOwner();
- const { slug, workspaceId } = owner;
- const statusFilter = searchParams.get("status") ?? "";
- const typeFilter = searchParams.get("type") ?? "";
- const source = useWorkspaceViewSource(owner, JSON.stringify(["agent-activity", agentId, statusFilter, typeFilter]), true);
- const activity = useInfiniteQuery({
- queryKey: owner.key("agent-activity", agentId, statusFilter, typeFilter),
- initialPageParam: null as { before: string; beforeId: string } | null,
- queryFn: ({ signal, pageParam }) => runWorkspaceRequest(owner, (options) => listAgentActivity(agentId, workspaceId, { limit: ACTIVITY_LIMIT, status: statusFilter || undefined, type: typeFilter || undefined, ...pageParam }, options), signal),
- getNextPageParam: (page) => page.has_more && page.tasks[0] ? { before: page.tasks[0].created_at, beforeId: page.tasks[0].id } : undefined,
- });
- const tasks = useMemo(() => [...new Map((activity.data?.pages.toReversed().flatMap((page) => page.tasks) ?? []).map((task) => [task.id, task])).values()], [activity.data]);
- const loading = activity.isPending;
- useObservedQueryRegion("activity", activity, tasks.length);
- const hasMore = activity.hasNextPage;
- const loadingMore = activity.isFetchingNextPage;
- const scrollRef = useRef<HTMLDivElement>(null);
- const initialScrollDone = useRef(false);
- const filterIdentity = JSON.stringify([agentId, statusFilter, typeFilter]);
-
- useEffect(() => { initialScrollDone.current = false; }, [filterIdentity]);
- useEffect(() => {
- if (!loading && !initialScrollDone.current && scrollRef.current) {
- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
- initialScrollDone.current = true;
- }
- }, [loading, tasks]);
-
- const loadInitial = useCallback(() => { void activity.refetch(); }, [activity]);
- const loadOlderTasks = useCallback(async () => {
- if (activity.isFetching || !hasMore || tasks.length === 0) return;
- const assertView = source.assertActive;
- const el = scrollRef.current;
- const previousHeight = el?.scrollHeight ?? 0;
- try {
- await activity.fetchNextPage({ cancelRefetch: false });
- assertView();
- requestAnimationFrame(() => {
- try { assertView(); } catch { return; }
- if (el?.isConnected && el === scrollRef.current) el.scrollTop = el.scrollHeight - previousHeight;
- });
- } catch { }
- }, [activity, hasMore, tasks.length, source.assertActive]);
- const handleScroll = useCallback(() => {
- const el = scrollRef.current;
- if (!el) return;
- if (!loadingMore && hasMore && el.scrollTop < 80) {
- loadOlderTasks();
- }
- }, [loadOlderTasks, loadingMore, hasMore]);
-
- const updateFilter = useCallback(
- (key: string, value: string) => {
- const newParams = new URLSearchParams(searchParams.toString());
- if (value) {
- newParams.set(key, value);
- } else {
- newParams.delete(key);
- }
- const pathname = `/w/${slug}/agents/${agentId}/activity`;
- const qs = newParams.toString();
- router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
- },
- [router, slug, agentId, searchParams]
- );
-
- return (
- <>
- {/* Filter bar */}
- <div className="sticky top-0 z-10 flex items-center gap-2 px-4 py-2">
- <Select value={statusFilter} onValueChange={(v) => updateFilter("status", v ?? "")}>
- <SelectTrigger className="w-35 border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
- <SelectValue placeholder="Status: All" />
- </SelectTrigger>
- <SelectContent>
- {STATUS_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label === "All" ? "Status: All" : opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- <Select value={typeFilter} onValueChange={(v) => updateFilter("type", v ?? "")}>
- <SelectTrigger className="w-32.5 border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
- <SelectValue placeholder="Type: All" />
- </SelectTrigger>
- <SelectContent>
- {TYPE_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label === "All" ? "Type: All" : opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
-
- {/* Scroll container */}
- <div className="relative flex-1 min-h-0">
- <div
- ref={scrollRef}
- className="h-full overflow-y-auto thin-scrollbar"
- onScroll={handleScroll}
- >
- {loading ? (
- <div className="flex flex-col">
- <SkeletonRow promptWidth="40%" />
- <SkeletonRow promptWidth="55%" />
- <SkeletonRow promptWidth="48%" />
- </div>
- ) : tasks.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]">
- <History className="size-8 text-muted-foreground mb-3" />
- <p className="text-sm text-muted-foreground">No activity yet</p>
- {(statusFilter || typeFilter) && (
- <p className="text-xs text-muted-foreground/60 mt-1">
- Try changing your filters
- </p>
- )}
- </div>
- ) : (
- <div className="flex flex-col animate-[fade-up_400ms_ease-out_both]">
- {loadingMore && (
- <>
- <SkeletonRow promptWidth="48%" />
- <SkeletonRow promptWidth="40%" />
- </>
- )}
- {tasks.map((task) => (
- <ActivityRow
- key={task.id}
- task={task}
- slug={slug}
- agentId={agentId}
- workspaceId={workspaceId}
- onRetry={loadInitial}
- />
- ))}
- </div>
- )}
- </div>
- <ScrollToBottomButton scrollRef={scrollRef} />
- </div>
- </>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/[convId]/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/[convId]/page.tsx
deleted file mode 100644
index a8fa89898..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/[convId]/page.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-"use client";
-
-import { useEffect } from "react";
-import { useParams, useRouter } from "next/navigation";
-import { useWorkspace } from "@/contexts/workspace-context";
-
-export default function AgentChatRedirect() {
- const params = useParams();
- const router = useRouter();
- const { slug } = useWorkspace();
- const agentId = params.id as string;
-
- useEffect(() => {
- router.replace(`/w/${slug}/agents/${agentId}/chat`);
- }, [router, slug, agentId]);
-
- return null;
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
deleted file mode 100644
index b8eada1b3..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/chat/page.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-"use client";
-
-import { AgentChatView } from "@/components/agent-chat/agent-chat-view";
-
-export default function AgentChatPage() {
- return <AgentChatView />;
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
deleted file mode 100644
index 5fde32059..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx
+++ /dev/null
@@ -1,849 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { FileDownloadButton } from "@/components/file-download-button"
-import { useEffect, useCallback, useMemo } from "react";
-import { useQuery, useMutation, type Query } from "@tanstack/react-query";
-import { useParams } from "next/navigation";
-import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { emailListOptions, emailThreadOptions, emailBodyOptions, emailEntityKey, useEmailRows } from "@/hooks/workspace/email-query-options";
-import { isAbortError } from "@/lib/errors";
-import { useAgentContext } from "@/contexts/agent-context";
-import { deleteEmail, sendEmail, listEmailAccounts, updateEmailStatus, trustEmail } from "@/lib/api";
-import { toAlookAddress } from "@alook/shared";
-import type { Email, EmailAttachment } from "@alook/shared";
-import { Button } from "@/components/ui/button";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-import { EmailCompose } from "@/components/email-compose";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { cn } from "@/lib/utils";
-import { toast } from "sonner";
-import { Skeleton } from "@/components/ui/skeleton";
-import { ArrowLeft, Loader2, Mail, Inbox, Send, Plus, Trash2, Forward, Reply, Paperclip, File as FileIcon, Copy, Check, ShieldAlert, ShieldCheck, ChevronDown } from "lucide-react";
-import { trackEmailComposed, trackEmailReceived } from "@/lib/analytics";
-import { useIsMobile } from "@/hooks/use-mobile";
-import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable";
-import { EmailBodyFrame } from "@/components/email-body-frame";
-
-type Folder = "inbox" | "sent" | "untrust";
-
-function relativeTime(dateStr: string): string {
- const date = new Date(dateStr);
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMin = Math.floor(diffMs / 60000);
- if (diffMin < 1) return "just now";
- if (diffMin < 60) return `${diffMin}m ago`;
- const diffHrs = Math.floor(diffMin / 60);
- if (diffHrs < 24) return `${diffHrs}h ago`;
- const diffDays = Math.floor(diffHrs / 24);
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
-}
-
-export default function AgentEmailPage() {
- const params = useParams();
- return <AgentEmailSurface key={params.id as string} agentId={params.id as string} />;
-}
-
-function AgentEmailSurface({ agentId }: { agentId: string }) {
- const owner = useWorkspaceOwner();
- const { workspaceId } = owner;
- const { agents, subscribeWs } = useAgentContext();
- const agent = agents.find((row) => row.id === agentId);
- const isMobile = useIsMobile();
- const [folder, _setFolder] = useAtom(useCreateAtom<Folder>("inbox"));
- const [selectedId, setSelectedId] = useAtom(useCreateAtom<string | null>(null));
- const [composing, setComposing] = useAtom(useCreateAtom(false));
- const [composeInitial, setComposeInitial] = useAtom(useCreateAtom<{
- to?: string; subject?: string; body?: string; attachments?: EmailAttachment[];
- inReplyTo?: string; references?: string;
- }>({}));
- const [expandedThreadId, setExpandedThreadId] = useAtom(useCreateAtom<string | null>(null));
- const [deleteConfirmOpen, setDeleteConfirmOpen] = useAtom(useCreateAtom(false));
- const [deleteTarget, setDeleteTarget] = useAtom(useCreateAtom<string | null>(null));
- const [mailboxOpen, setMailboxOpen] = useAtom(useCreateAtom(false));
- const accountsQuery = useQuery({ queryKey: owner.key("email-accounts", agentId), queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listEmailAccounts(agentId, workspaceId, options), signal) });
- const emailAccounts = accountsQuery.data ?? [];
- type Mailbox = { type: "alook"; address: string } | { type: "custom"; address: string; accountId: string };
- const alookAddress = agent?.email_handle ? toAlookAddress(agent.email_handle) : "";
- const mailboxes: Mailbox[] = [
- ...(alookAddress ? [{ type: "alook" as const, address: alookAddress }] : []),
- ...emailAccounts.map((row) => ({ type: "custom" as const, address: row.email_address, accountId: row.id })),
- ];
- const [activeMailboxIdx, setActiveMailboxIdx] = useAtom(useCreateAtom(0));
- const activeMailbox = mailboxes[activeMailboxIdx] ?? mailboxes[0] ?? null;
- const activeAddress = activeMailbox?.address ?? "";
- const activeAccountId = activeMailbox?.type === "custom" ? activeMailbox.accountId : undefined;
- const source = useWorkspaceViewSource(owner, JSON.stringify(["email", agentId, folder, activeAddress, selectedId, composing, deleteConfirmOpen, deleteTarget]), true);
- const list = useQuery(emailListOptions(owner, agentId, folder, activeAddress));
- const emails = useEmailRows(owner, list.data?.ids ?? []);
- const unreadCount = useMemo(() => emails.filter((email) => email.status === "unread").length, [emails]);
- const selected = emails.find((email) => email.id === selectedId) ?? null;
- const bodyQuery = useQuery({ ...emailBodyOptions(owner, selectedId ?? ""), enabled: !!selectedId, subscribed: !!selectedId });
- const threadQuery = useQuery({ ...emailThreadOptions(owner, selectedId ?? ""), enabled: !!selectedId, subscribed: !!selectedId });
- const thread = useEmailRows(owner, threadQuery.data?.ids ?? []);
- const expandedBody = useQuery({ ...emailBodyOptions(owner, expandedThreadId ?? ""), enabled: !!expandedThreadId, subscribed: !!expandedThreadId });
- const body = bodyQuery.data ?? (bodyQuery.isError ? { content: "(body not available)", isHtml: false } : null);
- const threadBodies = expandedThreadId && expandedBody.data ? { [expandedThreadId]: expandedBody.data } : {};
- const loading = list.isPending;
- useObservedQueryRegion("email", list, emails.length);
- useObservedQueryRegion("email_body", bodyQuery, undefined, !!selectedId);
- const bodyLoading = !!selectedId && bodyQuery.isPending;
- const switchFolder = useCallback((next: Folder) => {
- _setFolder(next);
- setSelectedId(null);
- setExpandedThreadId(null);
- setComposing(false);
- }, [_setFolder, setSelectedId, setExpandedThreadId, setComposing]);
- const commandKey = owner.key("email-command", agentId);
- type Action = { kind: "delete" | "read" | "trust"; id: string } | {
- kind: "send"; to: string; subject: string; htmlBody: string; attachments: EmailAttachment[];
- threading?: { inReplyTo?: string; references?: string }; accountId?: string;
- };
- type Input = { action: Action; token: ReturnType<typeof captureWorkspaceOwner> };
- type Intent = Input & { view: ReturnType<typeof source.capture>; resources: Query[] };
- const native = useMutation({ meta: { observabilityAction: "email.command" }, gcTime: 0, mutationKey: commandKey, scope: { id: JSON.stringify(commandKey) },
- mutationFn: async ({ action, token, view, resources }: Intent) => {
- const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert(); };
- assert();
- const allowed = (query: Query) => resources.includes(query);
- await owner.queryClient.cancelQueries({ queryKey: owner.key("email", "windows"), predicate: allowed });
- assert();
- const options = workspaceRequestOptions(token, view.signal, assert);
- const entityKey = action.kind === "send" ? null : emailEntityKey(owner, action.id);
- const entity = entityKey ? resources.find((query) => JSON.stringify(query.queryKey) === JSON.stringify(entityKey)) : undefined;
- const baseline = entity?.state.data as Email | null | undefined;
- const writes = entity?.state.dataUpdateCount;
- const originalEntity = () => entity && owner.queryClient.getQueryCache().find({ queryKey: entity.queryKey, exact: true }) === entity && entity.state.dataUpdateCount === writes;
- try {
- if (action.kind === "delete") {
- await deleteEmail(action.id, workspaceId, options);
- assert();
- if (originalEntity() && entity!.state.data === baseline) owner.queryClient.setQueryData<Email | null>(emailEntityKey(owner, action.id), null);
- owner.queryClient.removeQueries({ queryKey: emailBodyOptions(owner, action.id).queryKey, exact: true, predicate: allowed });
- } else if (action.kind === "read") {
- const before = baseline;
- const confirmed = await updateEmailStatus(action.id, workspaceId, "read", options);
- assert();
- if (originalEntity()) owner.queryClient.setQueryData<Email | null>(emailEntityKey(owner, action.id), (current) => current && current.status === before?.status ? { ...current, status: confirmed.status } : current);
- } else if (action.kind === "trust") {
- const result = await trustEmail(action.id, workspaceId, options);
- assert();
- if (originalEntity()) owner.queryClient.setQueryData<Email | null>(emailEntityKey(owner, action.id), (current) => current ? { ...current, ...Object.fromEntries(Object.entries(result.email).filter(([key]) => key !== "html_body" && current[key as keyof Email] === baseline?.[key as keyof Email])) } : current);
- } else if (action.kind === "send") {
- const result = await sendEmail(agentId, action.to, action.subject, action.htmlBody, workspaceId, action.attachments.length ? action.attachments : undefined, action.threading, action.accountId, options);
- assert();
- const canonical: Email = { ...result, html_body: "" };
- if (!owner.queryClient.getQueryData<Email | null>(emailEntityKey(owner, result.id))) owner.queryClient.setQueryData<Email | null>(emailEntityKey(owner, result.id), canonical);
- }
- assert();
- await owner.queryClient.invalidateQueries({ queryKey: owner.key("email", "windows"), predicate: allowed }, { cancelRefetch: false });
- assert();
- } catch (error) { assert(); throw error; }
- },
- });
- const capture = (input: Input): Intent => { const view = source.capture(); view.assert(); assertWorkspaceOwner(input.token, view.signal); return { ...input, view, resources: owner.queryClient.getQueryCache().findAll({ queryKey: owner.key("email") }) }; };
- const command = { ...native, mutate: (input: Input) => native.mutate(capture(input)), mutateAsync: (input: Input) => native.mutateAsync(capture(input)) };
- const deleting = command.isPending && command.variables?.action.kind === "delete";
- const trusting = command.isPending && command.variables?.action.kind === "trust";
- useEffect(() => {
- if (!list.error || isAbortError(list.error)) return;
- try { source.assertActive(); } catch { return; }
- toast.error("Failed to load emails");
- }, [list.error, source, source.assertActive]);
- useEffect(() => subscribeWs((message) => {
- if ((message.type !== "email.received" && message.type !== "email.sent") || message.agentId !== agentId) return;
- const token = captureWorkspaceOwner(owner);
- try { assertWorkspaceOwner(token); } catch { return; }
- if (message.type === "email.received") trackEmailReceived({ agent_id: agentId, mailbox_type: activeMailbox?.type === "custom" ? "imap" : "alook" });
- void owner.queryClient.cancelQueries({ queryKey: owner.key("email", "windows") }).then(() => {
- assertWorkspaceOwner(token);
- return owner.queryClient.invalidateQueries({ queryKey: owner.key("email", "windows") });
- }).catch(() => undefined);
- }), [owner, subscribeWs, agentId, activeMailbox?.type]);
- const mutateEmail = command.mutate;
- useEffect(() => {
- if (!selected || selected.status !== "unread" || !bodyQuery.data) return;
- mutateEmail({ action: { kind: "read", id: selected.id }, token: captureWorkspaceOwner(owner) });
- }, [selected, bodyQuery.data, owner, mutateEmail]);
- const handleSelect = (id: string) => { setComposing(false); setSelectedId(id); setExpandedThreadId(null); };
- const handleExpandThread = (id: string) => setExpandedThreadId((current) => current === id ? null : id);
- const handleDelete = async () => {
- if (!deleteTarget) return;
- const id = deleteTarget, assertView = source.capture().assert;
- assertView();
- try {
- await command.mutateAsync({ action: { kind: "delete", id }, token: captureWorkspaceOwner(owner) });
- assertView();
- if (selectedId === id) setSelectedId(null);
- toast.success("Email deleted");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to delete email");
- } finally {
- try { assertView(); setDeleteConfirmOpen(false); setDeleteTarget(null); } catch {}
- }
- };
- const handleSend = async (to: string, subject: string, htmlBody: string, attachments: EmailAttachment[], threading?: { inReplyTo?: string; references?: string }): Promise<boolean> => {
- if (owner.queryClient.isMutating({ mutationKey: commandKey, exact: true, predicate: (mutation) => (mutation.state.variables as Intent).action.kind === "send" })) return false;
- const assertView = source.capture().assert;
- assertView();
- try {
- await command.mutateAsync({ action: { kind: "send", to, subject, htmlBody, attachments, threading, accountId: activeAccountId }, token: captureWorkspaceOwner(owner) });
- assertView();
- trackEmailComposed({ agent_id: agentId, has_attachments: attachments.length > 0 });
- toast.success("Email sent");
- switchFolder("sent");
- return true;
- } catch (error) {
- try { assertView(); } catch { return false; }
- if (!isAbortError(error)) toast.error("Failed to send email");
- return false;
- }
- };
-
-
- const buildQuotedBody = (email: Email) => [
- `<br/><br/>`,
- `<div style="border-left: 2px solid #ccc; padding-left: 12px; margin-left: 0; color: #666;">`,
- `<p><strong>From:</strong> ${email.from_email}<br/>`,
- `<strong>To:</strong> ${email.to_email}<br/>`,
- `<strong>Date:</strong> ${new Date(email.created_at).toLocaleString()}<br/>`,
- `<strong>Subject:</strong> ${email.subject}</p>`,
- email.html_body ? email.html_body : body?.isHtml ? body.content : `<pre>${body?.content ?? ""}</pre>`,
- `</div>`,
- ].join("");
-
- const buildThreadingContext = (email: Email) => {
- const inReplyTo = email.message_id || undefined;
- const refs = [email.references, email.message_id].filter(Boolean).join(" ").trim() || undefined;
- return { inReplyTo, references: refs };
- };
-
- const handleReply = (email: Email) => {
- const reSubject = email.subject.startsWith("Re:") ? email.subject : `Re: ${email.subject}`;
- setSelectedId(null);
- setComposeInitial({
- to: email.from_email,
- subject: reSubject,
- body: buildQuotedBody(email),
- ...buildThreadingContext(email),
- });
- setComposing(true);
- };
-
- const handleForward = (email: Email) => {
- const fwdSubject = email.subject.startsWith("Fwd:") ? email.subject : `Fwd: ${email.subject}`;
- setSelectedId(null);
- setComposeInitial({
- subject: fwdSubject,
- body: buildQuotedBody(email),
- attachments: email.attachments ?? [],
- ...buildThreadingContext(email),
- });
- setComposing(true);
- };
-
- const handleTrust = async (email: Email) => {
- const assertView = source.capture().assert;
- assertView();
- try {
- await command.mutateAsync({ action: { kind: "trust", id: email.id }, token: captureWorkspaceOwner(owner) });
- assertView();
- toast.success("Email trusted and sent to agent");
- setSelectedId(null);
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to trust email");
- }
- };
-
-
- const [copied, setCopied] = useAtom(useCreateAtom(false));
-
- const handleCopyAddress = async () => {
- if (!activeAddress) return;
- try {
- await navigator.clipboard.writeText(activeAddress);
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
- } catch {
- toast.error("Failed to copy");
- }
- };
-
- const sidebarContent = (
- <div className="flex h-full flex-col">
- {mailboxes.length > 0 ? (
- <div className="px-3 pt-3 pb-1 relative">
- {mailboxes.length === 1 ? (
- <Tooltip>
- <TooltipTrigger render={<button
- type="button"
- onClick={handleCopyAddress}
- className="group flex items-center gap-2 text-left cursor-pointer w-full"
- />}>
- <span className="text-xs text-muted-foreground truncate">{activeAddress}</span>
- {copied ? (
- <Check className="size-2.5 text-green-500 shrink-0" />
- ) : (
- <Copy className="size-2.5 text-muted-foreground/0 group-hover:text-muted-foreground/60 shrink-0 transition-colors" />
- )}
- </TooltipTrigger>
- <TooltipContent>Click to copy</TooltipContent>
- </Tooltip>
- ) : (
- <>
- <div className="flex items-center gap-1 w-full">
- <button
- type="button"
- onClick={() => setMailboxOpen(!mailboxOpen)}
- className="flex items-center gap-1 text-left cursor-pointer min-w-0 flex-1"
- >
- <span className="text-xs text-muted-foreground truncate">{activeAddress}</span>
- <ChevronDown className="size-2.5 text-muted-foreground shrink-0" />
- </button>
- <Tooltip>
- <TooltipTrigger render={<button
- type="button"
- onClick={handleCopyAddress}
- className="shrink-0 p-1"
- />}>
- {copied ? (
- <Check className="size-2.5 text-green-500" />
- ) : (
- <Copy className="size-2.5 text-muted-foreground/40 hover:text-muted-foreground/80 transition-colors" />
- )}
- </TooltipTrigger>
- <TooltipContent>Copy address</TooltipContent>
- </Tooltip>
- </div>
- {mailboxOpen && (
- <div className="absolute left-2 right-2 top-full mt-1 z-10 rounded-lg border border-border bg-popover shadow-md py-1">
- {mailboxes.map((mb, i) => (
- <button
- key={mb.address}
- type="button"
- onClick={() => { setActiveMailboxIdx(i); setMailboxOpen(false); }}
- className={cn(
- "flex items-center gap-2 w-full px-2 py-2 text-left text-xs transition-colors",
- i === activeMailboxIdx ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50"
- )}
- >
- <Mail className="size-3 shrink-0" />
- <span className="truncate">{mb.address}</span>
- {mb.type === "custom" && (
- <span className="text-[9px] text-muted-foreground/60 shrink-0">IMAP</span>
- )}
- </button>
- ))}
- </div>
- )}
- </>
- )}
- </div>
- ) : (
- <div className="px-3 pt-3 pb-1">
- <p className="text-xs text-muted-foreground/60">No email configured</p>
- </div>
- )}
- <div className="p-2">
- <Tooltip>
- <TooltipTrigger render={<Button
- size="sm"
- className="w-full justify-start text-xs h-8 gap-2"
- onClick={() => { setComposeInitial({}); setComposing(true); setSelectedId(null); }}
- disabled={mailboxes.length === 0}
- />}>
- <Plus className="size-3.5" />
- New Email
- </TooltipTrigger>
- <TooltipContent>{mailboxes.length === 0 ? "Configure an email in agent settings to send emails" : "Compose new email"}</TooltipContent>
- </Tooltip>
- </div>
- <nav className="flex flex-col gap-1 px-2">
- <button
- type="button"
- onClick={() => switchFolder("inbox")}
- className={cn(
- "flex items-center gap-2 rounded-lg px-2 py-2 text-sm transition-colors cursor-pointer",
- folder === "inbox"
- ? "bg-accent text-foreground font-medium"
- : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
- )}
- >
- <Inbox className="size-4 shrink-0" />
- Inbox
- {folder === "inbox" && unreadCount > 0 && (
- <span className="ml-auto text-xs bg-blue-500 text-white rounded-full px-2 py-1 leading-none min-w-5 text-center">
- {unreadCount}
- </span>
- )}
- </button>
- <button
- type="button"
- onClick={() => switchFolder("sent")}
- className={cn(
- "flex items-center gap-2 rounded-lg px-2 py-2 text-sm transition-colors cursor-pointer",
- folder === "sent"
- ? "bg-accent text-foreground font-medium"
- : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
- )}
- >
- <Send className="size-4 shrink-0" />
- Sent
- </button>
- <button
- type="button"
- onClick={() => switchFolder("untrust")}
- className={cn(
- "flex items-center gap-2 rounded-lg px-2 py-2 text-sm transition-colors cursor-pointer",
- folder === "untrust"
- ? "bg-accent text-foreground font-medium"
- : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
- )}
- >
- <ShieldAlert className="size-4 shrink-0" />
- Untrust
- </button>
- </nav>
- </div>
- );
-
- const emailListContent = (
- <div className={cn("h-full thin-scrollbar", emails.length > 0 && !loading ? "overflow-y-auto" : "overflow-hidden")}>
- {loading ? (
- <>
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="px-4 py-3 border-b border-border/30">
- <div className="flex items-center justify-between gap-2 mb-2">
- <Skeleton className="h-3.5 w-32" />
- <Skeleton className="h-2.5 w-10" />
- </div>
- <Skeleton className="h-3.5 w-48 mb-2" />
- <Skeleton className="h-4 w-16 rounded-full" />
- </div>
- ))}
- </>
- ) : emails.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]">
- <Mail className="size-8 text-muted-foreground mb-3" />
- <p className="text-sm text-muted-foreground">
- {folder === "inbox" ? "No emails from trusted senders" : folder === "sent" ? "No emails sent yet" : "No untrusted emails"}
- </p>
- </div>
- ) : (
- emails.map((email) => (
- <button
- key={email.id}
- type="button"
- onClick={() => handleSelect(email.id)}
- className={cn(
- "w-full text-left px-4 py-3 border-b border-border/30 transition-colors duration-150 cursor-pointer",
- selectedId === email.id
- ? "bg-accent/60"
- : "hover:bg-accent/30"
- )}
- >
- <div className="flex items-center justify-between gap-2 mb-1">
- <p className={cn(
- "text-sm truncate",
- email.status === "unread" ? "font-semibold" : "font-medium text-muted-foreground"
- )}>
- {folder === "sent" ? email.to_email : email.from_email}
- </p>
- <div className="flex items-center gap-2 shrink-0">
- {folder === "sent" && email.status === "blocked" && (
- <Tooltip>
- <TooltipTrigger render={<span className="inline-flex items-center gap-1 text-[10px] rounded-full px-2 py-1 leading-none font-medium bg-destructive/10 text-destructive" />}>
- <ShieldAlert className="size-3" />
- Blocked
- </TooltipTrigger>
- <TooltipContent>Blocked — not sent</TooltipContent>
- </Tooltip>
- )}
- {folder !== "sent" && (
- <span className={cn(
- "text-[10px] rounded-full px-2 py-1 leading-none font-medium",
- email.status === "unread"
- ? "bg-blue-500/15 text-blue-600 dark:text-blue-400"
- : "bg-muted text-muted-foreground"
- )}>
- {email.status === "unread" ? "unread" : "read"}
- </span>
- )}
- <span className="text-xs text-muted-foreground">
- {relativeTime(email.created_at)}
- </span>
- </div>
- </div>
- <p className={cn(
- "text-[13px] truncate",
- email.status === "unread" ? "text-foreground" : "text-muted-foreground"
- )}>
- {email.subject || "(no subject)"}
- </p>
- </button>
- ))
- )}
- </div>
- );
-
- const readingPaneContent = (
- <div className="h-full overflow-auto flex flex-col min-w-0 thin-scrollbar">
- {composing ? (
- <EmailCompose
- key={JSON.stringify(composeInitial)}
- fromAddress={activeAddress}
- onSend={handleSend}
- onDiscard={() => { setComposing(false); setComposeInitial({}); }}
- initialTo={composeInitial.to}
- initialSubject={composeInitial.subject}
- initialBody={composeInitial.body}
- initialAttachments={composeInitial.attachments}
- inReplyTo={composeInitial.inReplyTo}
- references={composeInitial.references}
- />
- ) : !selected ? (
- <div className="flex items-center justify-center h-full text-sm text-muted-foreground">
- Select an email to view
- </div>
- ) : (
- <div className="flex flex-col h-full sm:min-w-100 max-w-3xl mx-auto w-full">
- {/* Detail toolbar */}
- <div className="flex items-center gap-1 border-b border-border/40 px-4 py-2">
- {folder === "untrust" && (
- <Tooltip>
- <TooltipTrigger render={<Button
- variant="ghost"
- size="icon"
- className="size-7 text-muted-foreground/60 hover:text-foreground"
- disabled={trusting}
- onClick={() => handleTrust(selected)}
- />}>
- {trusting ? <Loader2 className="size-3.5 animate-spin" /> : <ShieldCheck className="size-3.5" />}
- </TooltipTrigger>
- <TooltipContent>Trust this email</TooltipContent>
- </Tooltip>
- )}
- {folder !== "sent" && (
- <Tooltip>
- <TooltipTrigger render={<Button
- variant="ghost"
- size="icon"
- className="size-7 text-muted-foreground/60 hover:text-foreground"
- onClick={() => handleReply(selected)}
- />}>
- <Reply className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Reply</TooltipContent>
- </Tooltip>
- )}
- <Tooltip>
- <TooltipTrigger render={<Button
- variant="ghost"
- size="icon"
- className="size-7 text-muted-foreground/60 hover:text-foreground"
- onClick={() => handleForward(selected)}
- />}>
- <Forward className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Forward</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger render={<Button
- variant="ghost"
- size="icon"
- className="size-7 text-muted-foreground/60 hover:text-destructive"
- onClick={() => {
- setDeleteTarget(selected.id);
- setDeleteConfirmOpen(true);
- }}
- />}>
- <Trash2 className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Delete</TooltipContent>
- </Tooltip>
- </div>
-
- {/* Thread parents */}
- {thread.length > 0 && (
- <div className="border-b border-border/30">
- {thread.map((parent) => (
- <div key={parent.id} className="border-b border-border/20 last:border-b-0">
- <button
- type="button"
- onClick={() => handleExpandThread(parent.id)}
- className="w-full flex items-center gap-2 px-4 py-2 text-left hover:bg-accent/30 transition-colors cursor-pointer"
- >
- <span className="text-xs text-muted-foreground">
- {expandedThreadId === parent.id ? "▾" : "▸"}
- </span>
- <span className="text-sm font-medium truncate flex-1">
- {parent.from_email}
- </span>
- <span className="text-xs text-muted-foreground shrink-0">
- {relativeTime(parent.created_at)}
- </span>
- </button>
- {expandedThreadId === parent.id && (
- <div className="px-4 pb-3">
- <p className="text-xs text-muted-foreground mb-2">{parent.subject}</p>
- {threadBodies[parent.id] ? (
- threadBodies[parent.id].isHtml ? (
- <EmailBodyFrame
- html={threadBodies[parent.id].content}
- className="max-w-full text-sm"
- />
- ) : (
- <div className="text-sm whitespace-pre-wrap leading-[1.65] text-foreground">
- {threadBodies[parent.id].content}
- </div>
- )
- ) : (
- <Loader2 className="size-3 animate-spin text-muted-foreground" />
- )}
- </div>
- )}
- </div>
- ))}
- </div>
- )}
-
- {/* Email detail */}
- <div className="p-4">
- <h2 className="text-lg font-heading font-semibold tracking-tight mb-1">
- {selected.subject || "(no subject)"}
- </h2>
- <div className="text-sm space-y-1 mb-4">
- <div className="flex items-center gap-2">
- <span className="text-muted-foreground w-16 shrink-0">From</span>
- <span>{selected.from_email}</span>
- </div>
- <div className="flex items-center gap-2">
- <span className="text-muted-foreground w-16 shrink-0">To</span>
- <span>{selected.to_email}</span>
- </div>
- <div className="flex items-center gap-2">
- <span className="text-muted-foreground w-16 shrink-0">
- {folder === "sent" ? "Sent" : "Received"}
- </span>
- <span className="text-muted-foreground">
- {new Date(selected.created_at).toLocaleString()}
- </span>
- </div>
- </div>
-
- {bodyLoading ? (
- <div className="flex items-center justify-center py-8">
- <Loader2 className="size-4 animate-spin text-muted-foreground" />
- </div>
- ) : selected.html_body ? (
- <EmailBodyFrame
- html={selected.html_body}
- className="max-w-full"
- />
- ) : body?.isHtml ? (
- <EmailBodyFrame
- html={body.content}
- className="max-w-full"
- />
- ) : (
- <div className="text-sm whitespace-pre-wrap leading-[1.65] text-foreground">
- {body?.content}
- </div>
- )}
-
- {selected.attachments && selected.attachments.length > 0 && (
- <div className="mt-4">
- <div className="flex items-center gap-2 mb-2 text-xs text-muted-foreground">
- <Paperclip className="size-3" />
- {selected.attachments.length} attachment{selected.attachments.length > 1 ? "s" : ""}
- </div>
- <div className="flex flex-wrap gap-2">
- {selected.attachments.map((att, i) => (
- <FileDownloadButton
- key={att.key}
- url={`/api/email/${selected.id}/attachment/${i}?workspace_id=${workspaceId}`}
- filename={att.filename}
- className="flex items-center gap-2 rounded-md border border-border/50 bg-muted/50 px-2 py-2 text-xs hover:bg-muted transition-colors cursor-pointer"
- >
- <FileIcon className="size-3 text-muted-foreground shrink-0" />
- <span className="truncate max-w-45">{att.filename}</span>
- <span className="text-muted-foreground shrink-0">
- {att.size < 1024 ? `${att.size} B` : att.size < 1024 * 1024 ? `${(att.size / 1024).toFixed(1)} KB` : `${(att.size / (1024 * 1024)).toFixed(1)} MB`}
- </span>
- </FileDownloadButton>
- ))}
- </div>
- </div>
- )}
- </div>
- </div>
- )}
- </div>
- );
-
- const mobileContent = (() => {
- if (composing) {
- return (
- <div className="flex flex-col h-full">
- <div className="flex items-center gap-2 border-b border-border/50 px-3 py-2">
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => { setComposing(false); setComposeInitial({}); }}
- >
- <ArrowLeft className="size-4" />
- </Button>
- <span className="text-sm font-medium">New Email</span>
- </div>
- <div className="flex-1 min-h-0 overflow-auto">{readingPaneContent}</div>
- </div>
- );
- }
- if (selectedId && selected) {
- return (
- <div className="flex flex-col h-full">
- <div className="flex items-center gap-2 border-b border-border/50 px-3 py-2">
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setSelectedId(null)}
- >
- <ArrowLeft className="size-4" />
- </Button>
- <span className="text-sm font-medium truncate">{selected.subject || "(no subject)"}</span>
- </div>
- <div className="flex-1 min-h-0 overflow-auto">{readingPaneContent}</div>
- </div>
- );
- }
- return (
- <div className="flex flex-col h-full">
- {mailboxes.length > 1 && (
- <div className="relative px-3 pt-2 pb-1 border-b border-border/30">
- <div className="flex items-center gap-1">
- <button
- type="button"
- onClick={() => setMailboxOpen(!mailboxOpen)}
- className="flex items-center gap-1 text-left cursor-pointer min-w-0 flex-1"
- >
- <span className="text-xs text-muted-foreground truncate">{activeAddress}</span>
- <ChevronDown className="size-2.5 text-muted-foreground shrink-0" />
- </button>
- <Tooltip>
- <TooltipTrigger render={<button
- type="button"
- onClick={handleCopyAddress}
- className="shrink-0 p-1"
- />}>
- {copied ? (
- <Check className="size-2.5 text-green-500" />
- ) : (
- <Copy className="size-2.5 text-muted-foreground/40 hover:text-muted-foreground/80 transition-colors" />
- )}
- </TooltipTrigger>
- <TooltipContent>Copy address</TooltipContent>
- </Tooltip>
- </div>
- {mailboxOpen && (
- <div className="absolute left-2 right-2 top-full mt-1 z-10 rounded-lg border border-border bg-popover shadow-md py-1">
- {mailboxes.map((mb, i) => (
- <button
- key={mb.address}
- type="button"
- onClick={() => { setActiveMailboxIdx(i); setMailboxOpen(false); }}
- className={cn(
- "flex items-center gap-2 w-full px-2 py-2 text-left text-xs transition-colors",
- i === activeMailboxIdx ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50"
- )}
- >
- <Mail className="size-3 shrink-0" />
- <span className="truncate">{mb.address}</span>
- {mb.type === "custom" && (
- <span className="text-[9px] text-muted-foreground/60 shrink-0">IMAP</span>
- )}
- </button>
- ))}
- </div>
- )}
- </div>
- )}
- <div className="flex items-center gap-1 border-b border-border/50 px-3 py-2">
- <div className="flex items-center gap-1 flex-1 min-w-0">
- {([
- { id: "inbox" as Folder, label: "Inbox" },
- { id: "sent" as Folder, label: "Sent" },
- { id: "untrust" as Folder, label: "Untrust" },
- ]).map((f) => (
- <button
- key={f.id}
- type="button"
- onClick={() => switchFolder(f.id)}
- className={cn(
- "px-2 py-1 rounded-md text-xs font-medium transition-colors",
- folder === f.id
- ? "bg-accent text-foreground"
- : "text-muted-foreground hover:text-foreground"
- )}
- >
- {f.label}
- {f.id === "inbox" && folder === "inbox" && unreadCount > 0 && (
- <span className="ml-1 text-[10px] bg-blue-500 text-white rounded-full px-1 leading-none min-w-4 text-center">
- {unreadCount}
- </span>
- )}
- </button>
- ))}
- </div>
- <Button
- size="icon-sm"
- variant="ghost"
- onClick={() => { setComposeInitial({}); setComposing(true); setSelectedId(null); }}
- disabled={mailboxes.length === 0}
- >
- <Plus className="size-4" />
- </Button>
- </div>
- <div className="flex-1 min-h-0 overflow-auto">{emailListContent}</div>
- </div>
- );
- })();
-
- return (
- <>
- {isMobile ? (
- mobileContent
- ) : (
- <ResizablePanelGroup orientation="horizontal">
- <ResizablePanel defaultSize="15%" minSize="10%" maxSize="20%">
- {sidebarContent}
- </ResizablePanel>
- <ResizableHandle withHandle />
- <ResizablePanel defaultSize="30%" minSize="15%" maxSize="40%">
- {emailListContent}
- </ResizablePanel>
- <ResizableHandle withHandle />
- <ResizablePanel defaultSize="55%" minSize="25%">
- {readingPaneContent}
- </ResizablePanel>
- </ResizablePanelGroup>
- )}
-
- {/* Delete confirmation dialog */}
- <ConfirmDialog
- open={deleteConfirmOpen}
- onOpenChange={setDeleteConfirmOpen}
- title="Delete email"
- description="This will permanently delete this email."
- loading={deleting}
- onConfirm={handleDelete}
- />
- </>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx
deleted file mode 100644
index c97b9959b..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx
+++ /dev/null
@@ -1,329 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { useParams } from "next/navigation";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { workspaceFileOptions } from "@/hooks/workspace/file-query-options";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { ScrollArea } from "@/components/ui/scroll-area";
-import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable";
-import { useIsMobile } from "@/hooks/use-mobile";
-import { Streamdown } from "streamdown";
-import type { WorkspaceFileEntry } from "@alook/shared";
-import {
- ArrowLeft,
- ChevronRight,
- Copy,
- File,
- FileText,
- FileCode,
- Folder,
- FolderOpen,
- Loader2,
-} from "lucide-react";
-
-interface TreeNode {
- entry: WorkspaceFileEntry;
-}
-
-export default function AgentFilesPage() {
- const params = useParams();
- return <AgentFilesSurface key={params.id as string} agentId={params.id as string} />;
-}
-
-function AgentFilesSurface({ agentId }: { agentId: string }) {
- const owner = useWorkspaceOwner();
- const { workspaceId } = owner;
- const { subscribeWs, runtimes, agents } = useAgentContext();
- const isMobile = useIsMobile();
- const agent = agents.find((row) => row.id === agentId);
- const runtime = agent ? runtimes.find((row) => row.id === agent.runtime_id) : null;
- const isOnline = runtime?.status === "online";
- const [selectedFile, setSelectedFile] = useAtom(useCreateAtom<string | null>(null));
- const [viewMode, setViewMode] = useAtom(useCreateAtom<"raw" | "preview">("preview"));
- const rootQuery = useQuery({ ...workspaceFileOptions(owner, agentId, runtime?.id ?? null, "tree", ".", subscribeWs), enabled: isOnline });
- const fileQuery = useQuery({ ...workspaceFileOptions(owner, agentId, runtime?.id ?? null, "read", selectedFile ?? "", subscribeWs), enabled: isOnline && !!selectedFile });
- const rootNodes = (rootQuery.data?.entries ?? []).map((entry) => ({ entry }));
- const rootLoading = isOnline && rootQuery.isPending;
- useObservedQueryRegion("files", rootQuery, rootNodes.length, isOnline);
- useObservedQueryRegion("file_preview", fileQuery, undefined, isOnline && !!selectedFile);
- const rootError = rootQuery.error?.message ?? null;
- const fileContent = fileQuery.data?.content ?? null;
- const fileBinary = fileQuery.data?.isBinary ?? false;
- const fileLoading = !!selectedFile && fileQuery.isPending;
- const fileError = fileQuery.error?.message ?? null;
- const workspacesRoot = runtime?.metadata?.workspaces_root;
- const rootLabel = `${workspacesRoot || "~/.alook/workspaces"}/${workspaceId}/${agentId}/workdir`;
- const requestFile = useCallback((path: string) => { setSelectedFile(path); setViewMode("preview"); }, [setSelectedFile, setViewMode]);
- const handleCopyPath = () => { navigator.clipboard.writeText(rootLabel).catch(() => {}); };
-
-
- // --- Offline ---
-
- if (!isOnline) {
- return (
- <div className="flex-1 flex items-center justify-center text-muted-foreground text-sm p-8">
- <div className="text-center space-y-2">
- <FolderOpen className="size-8 mx-auto opacity-40" />
- <p>Agent runtime is offline</p>
- <p className="text-xs">File browsing requires the daemon to be running.</p>
- </div>
- </div>
- );
- }
-
- // --- Shared UI ---
-
- const pathBar = (
- <div className="flex items-center gap-2 px-4 py-2 border-b border-border/50 text-xs text-muted-foreground shrink-0 min-w-0">
- <Tooltip>
- <TooltipTrigger render={<button
- onClick={handleCopyPath}
- className="hover:text-foreground transition-colors shrink-0"
- />}>
- <Copy className="size-3" />
- </TooltipTrigger>
- <TooltipContent>Copy full path</TooltipContent>
- </Tooltip>
- <span className="truncate opacity-60">{rootLabel}</span>
- </div>
- );
-
- const treePanel = (
- <ScrollArea className="h-full">
- {rootLoading ? (
- <div className="p-3 space-y-1">
- {Array.from({ length: 6 }).map((_, i) => (
- <Skeleton key={i} className="h-6 w-full rounded" />
- ))}
- </div>
- ) : rootError ? (
- <div className="p-4 text-sm text-destructive">{rootError}</div>
- ) : rootNodes.length === 0 ? (
- <div className="p-4 text-sm text-muted-foreground">Empty directory</div>
- ) : (
- <div className="py-1">
- {rootNodes.map((node) => (
- <TreeNodeRow
- key={`${runtime?.id}:${node.entry.path}`}
- node={node}
- depth={0}
- selectedFile={selectedFile}
- agentId={agentId}
- runtimeId={runtime?.id ?? null}
- onSelectFile={requestFile}
- />
- ))}
- </div>
- )}
- </ScrollArea>
- );
-
- const selectedFileName = selectedFile?.split("/").pop() ?? "";
- const isMarkdown = selectedFileName.endsWith(".md");
-
- const fileViewer = selectedFile ? (
- <div className="flex-1 min-h-0 flex flex-col">
- <div className="flex items-center justify-between px-4 py-2 border-b border-border/50 shrink-0">
- <div className="flex items-center gap-2 min-w-0">
- {isMobile && (
- <button
- onClick={() => setSelectedFile(null)}
- className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
- >
- <ArrowLeft className="size-4" />
- </button>
- )}
- <span className="text-xs font-medium truncate">{selectedFileName}</span>
- </div>
- <div className="flex items-center gap-1 shrink-0 ml-2">
- {isMarkdown && !fileBinary && !fileError && !fileLoading && (
- <>
- <button
- onClick={() => setViewMode("raw")}
- className={`text-[10px] px-2 py-1 rounded transition-colors ${
- viewMode === "raw" ? "bg-muted text-foreground" : "text-muted-foreground hover:text-foreground"
- }`}
- >
- Raw
- </button>
- <button
- onClick={() => setViewMode("preview")}
- className={`text-[10px] px-2 py-1 rounded transition-colors ${
- viewMode === "preview" ? "bg-muted text-foreground" : "text-muted-foreground hover:text-foreground"
- }`}
- >
- Preview
- </button>
- </>
- )}
- </div>
- </div>
- <ScrollArea className="flex-1 min-h-0">
- {fileLoading ? (
- <div className="p-4 space-y-2">
- {Array.from({ length: 10 }).map((_, i) => (
- <Skeleton key={i} className="h-3.5 w-full rounded" />
- ))}
- </div>
- ) : fileError ? (
- <div className="p-4 text-sm text-destructive">{fileError}</div>
- ) : fileBinary ? (
- <div className="flex-1 flex items-center justify-center p-8 text-sm text-muted-foreground">
- Binary file — cannot display
- </div>
- ) : isMarkdown && viewMode === "preview" ? (
- <div className="markdown text-sm p-4">
- <Streamdown>{fileContent ?? ""}</Streamdown>
- </div>
- ) : (
- <pre className="p-4 text-[11px] font-mono whitespace-pre-wrap break-all leading-relaxed text-foreground/80">
- {fileContent}
- </pre>
- )}
- </ScrollArea>
- </div>
- ) : (
- <div className="flex-1 flex items-center justify-center text-muted-foreground text-xs h-full">
- Select a file to view
- </div>
- );
-
- // --- Layout ---
-
- if (isMobile) {
- if (selectedFile) {
- return <div className="flex-1 flex flex-col min-h-0 overflow-hidden">{fileViewer}</div>;
- }
- return (
- <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
- {pathBar}
- <div className="flex-1 min-h-0">{treePanel}</div>
- </div>
- );
- }
-
- return (
- <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
- {pathBar}
- <ResizablePanelGroup orientation="horizontal">
- <ResizablePanel defaultSize="25%" minSize="15%" maxSize="40%" className="overflow-hidden">
- {treePanel}
- </ResizablePanel>
- <ResizableHandle withHandle />
- <ResizablePanel defaultSize="75%" className="overflow-hidden flex flex-col">
- {fileViewer}
- </ResizablePanel>
- </ResizablePanelGroup>
- </div>
- );
-}
-
-// --- Tree node row ---
-
-function TreeNodeRow({
- node,
- depth,
- selectedFile,
- agentId,
- runtimeId,
- onSelectFile,
-}: {
- node: TreeNode;
- depth: number;
- selectedFile: string | null;
- agentId: string;
- runtimeId: string | null;
- onSelectFile: (path: string) => void;
-}) {
- const { entry } = node;
- const owner = useWorkspaceOwner();
- const { subscribeWs } = useAgentContext();
- const [expanded, setExpanded] = useAtom(useCreateAtom(false));
- const children = useQuery({ ...workspaceFileOptions(owner, agentId, runtimeId, "tree", entry.path, subscribeWs), enabled: entry.isDirectory && expanded });
- const paddingLeft = 12 + depth * 16;
-
-
- if (entry.isDirectory) {
- return (
- <>
- <button
- onClick={() => setExpanded((open) => !open)}
- className="w-full flex items-center gap-2 py-1 text-sm hover:bg-muted/50 transition-colors text-left"
- style={{ paddingLeft }}
- >
- <ChevronRight
- className={`size-3 text-muted-foreground/60 shrink-0 transition-transform duration-150 ${
- expanded ? "rotate-90" : ""
- }`}
- />
- {expanded ? (
- <FolderOpen className="size-3.5 text-blue-500/70 shrink-0" />
- ) : (
- <Folder className="size-3.5 text-blue-500/70 shrink-0" />
- )}
- <span className="truncate">{entry.name}</span>
- {expanded && children.isPending && <Loader2 className="size-3 text-muted-foreground animate-spin shrink-0 ml-auto mr-2" />}
- </button>
- {expanded && children.data?.entries?.map((child) => (
- <TreeNodeRow
- key={child.path}
- node={{ entry: child }}
- depth={depth + 1}
- selectedFile={selectedFile}
- agentId={agentId}
- runtimeId={runtimeId}
- onSelectFile={onSelectFile}
- />
- ))}
- {expanded && children.data?.entries?.length === 0 && (
- <div className="text-[10px] text-muted-foreground/50 py-1" style={{ paddingLeft: paddingLeft + 24 }}>
- empty
- </div>
- )}
- {expanded && children.error && <div className="text-xs text-destructive py-1" style={{ paddingLeft: paddingLeft + 24 }}>{children.error.message}</div>}
- </>
- );
- }
-
- return (
- <button
- onClick={() => onSelectFile(entry.path)}
- className={`w-full flex items-center gap-2 py-1 text-sm hover:bg-muted/50 transition-colors text-left ${
- selectedFile === entry.path ? "bg-muted text-foreground" : ""
- }`}
- style={{ paddingLeft: paddingLeft + 15 }}
- >
- <FileIcon name={entry.name} />
- <span className="truncate">{entry.name}</span>
- <span className="ml-auto text-[10px] text-muted-foreground/50 shrink-0 tabular-nums mr-2">
- {formatSize(entry.size)}
- </span>
- </button>
- );
-}
-
-
-// --- Misc helpers ---
-
-function FileIcon({ name }: { name: string }) {
- if (name.endsWith(".md") || name.endsWith(".txt")) {
- return <FileText className="size-3.5 text-muted-foreground shrink-0" />;
- }
- if (/\.(js|ts|tsx|jsx|py|sh|go|rs|rb|css|html|sql)$/.test(name)) {
- return <FileCode className="size-3.5 text-muted-foreground shrink-0" />;
- }
- return <File className="size-3.5 text-muted-foreground shrink-0" />;
-}
-
-function formatSize(bytes: number): string {
- if (bytes < 1024) return `${bytes}B`;
- if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)}K`;
- return `${(bytes / 1048576).toFixed(1)}M`;
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
deleted file mode 100644
index df79c0cde..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
+++ /dev/null
@@ -1,335 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { type ReactNode } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { modelCatalogOptions } from "@/hooks/workspace/settings-query-options";
-import { useParams, useRouter, usePathname, useSearchParams } from "next/navigation";
-import Link from "next/link";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { Button } from "@/components/ui/button";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-import { AgentEditForm } from "@/components/agent-edit-form";
-import { ChannelBar } from "@/components/channel-bar";
-import { Skeleton } from "@/components/ui/skeleton";
-import { AgentStatusBadge } from "@/components/agent-status-badge";
-import { FolderOpen, GitBranch, History, Mail, MessageSquare, MoreHorizontal, Pencil, Trash2, Video, X } from "lucide-react";
-import {
- DropdownMenu,
- DropdownMenuTrigger,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
-} from "@/components/ui/dropdown-menu";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-
-
-export default function AgentDetailLayout({ children }: { children: ReactNode }) {
- const params = useParams();
- const router = useRouter();
- const pathname = usePathname();
- const owner = useWorkspaceOwner();
- const { slug } = owner;
- const searchParams = useSearchParams();
- const agentId = params.id as string;
- const isActivityView = !!searchParams.get("conv");
- const currentTab = pathname.includes("/activity") || isActivityView
- ? "activity"
- : pathname.includes("/meetings")
- ? "meetings"
- : pathname.includes("/email")
- ? "email"
- : pathname.includes("/files")
- ? "files"
- : "chat";
- const tabLabels: Record<string, string> = { email: "Email", meetings: "Meetings", activity: "Activity", files: "Files" };
- const { agents, runtimes, handleDeleteAgent, handleUpdateAgent } = useAgentContext();
-
- const agent = agents.find((a) => a.id === agentId);
- const runtime = agent ? runtimes.find((r) => r.id === agent.runtime_id) : null;
- const isOnline = runtime?.status === "online";
- const { activeTaskCounts } = useAgentContext();
- const taskCount = activeTaskCounts[agentId] ?? 0;
-
- const [editing, setEditing] = useAtom(useCreateAtom(false));
- const [saving, setSaving] = useAtom(useCreateAtom(false));
- const [agentConfirmOpen, setAgentConfirmOpen] = useAtom(useCreateAtom(false));
- const [agentDeleting, setAgentDeleting] = useAtom(useCreateAtom(false));
- const modelOptions = useQuery(modelCatalogOptions(owner)).data ?? {};
-
- return (
- <>
- {/* Top navbar */}
- <div className="flex items-center justify-between border-b border-border/50 px-4 py-2">
- <div className="flex items-center gap-2 min-w-0">
- {agent ? (
- <AgentStatusBadge
- isOnline={isOnline}
- taskCount={taskCount}
- agentId={agentId}
- />
- ) : (
- <Skeleton className="size-2 rounded-full shrink-0" />
- )}
- {agent ? (
- <Tooltip>
- <TooltipTrigger render={
- <Link
- href={`/w/${slug}/agents/${agentId}`}
- onClick={() => setEditing(false)}
- className="text-sm font-medium truncate hover:text-foreground/80 transition-colors"
- />
- }>
- {agent.name}
- </TooltipTrigger>
- <TooltipContent>{agent.description || "No description"}</TooltipContent>
- </Tooltip>
- ) : (
- <Skeleton className="h-3.5 w-24" />
- )}
- <span className="text-xs text-muted-foreground">
- / {editing ? "Settings" : tabLabels[currentTab] ?? "Chat"}
- </span>
- </div>
- {agent ? (
- <div className="flex items-center gap-1 shrink-0">
- {editing ? (
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground h-7 gap-1 px-2"
- onClick={() => setEditing(false)}
- >
- <X className="size-3" />
- Cancel
- </Button>
- ) : (
- <>
- {/* Desktop: inline buttons */}
- <div className="hidden sm:flex items-center gap-1">
- <Link
- href={`/w/${slug}/agents/${agentId}`}
- className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
- currentTab === "chat"
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:bg-muted hover:text-foreground"
- }`}
- >
- <MessageSquare className="size-3 shrink-0" />
- <span className={`overflow-hidden transition-all duration-500 ease-out ${
- currentTab === "chat"
- ? "max-w-16 opacity-100 ml-1"
- : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
- }`}>Chat</span>
- </Link>
- <Link
- href={`/w/${slug}/agents/${agentId}/email`}
- className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
- currentTab === "email"
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:bg-muted hover:text-foreground"
- }`}
- >
- <Mail className="size-3 shrink-0" />
- <span className={`overflow-hidden transition-all duration-500 ease-out ${
- currentTab === "email"
- ? "max-w-16 opacity-100 ml-1"
- : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
- }`}>Email</span>
- </Link>
- <Link
- href={`/w/${slug}/agents/${agentId}/meetings`}
- className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
- currentTab === "meetings"
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:bg-muted hover:text-foreground"
- }`}
- >
- <Video className="size-3 shrink-0" />
- <span className={`overflow-hidden transition-all duration-500 ease-out ${
- currentTab === "meetings"
- ? "max-w-20 opacity-100 ml-1"
- : "max-w-0 opacity-0 group-hover:max-w-20 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
- }`}>Meetings</span>
- </Link>
- <Link
- href={`/w/${slug}/agents/${agentId}/activity`}
- className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
- currentTab === "activity"
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:bg-muted hover:text-foreground"
- }`}
- >
- <History className="size-3 shrink-0" />
- <span className={`overflow-hidden transition-all duration-500 ease-out ${
- currentTab === "activity"
- ? "max-w-16 opacity-100 ml-1"
- : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
- }`}>Activity</span>
- </Link>
- <Link
- href={`/w/${slug}/agents/${agentId}/files`}
- className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
- currentTab === "files"
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:bg-muted hover:text-foreground"
- }`}
- >
- <FolderOpen className="size-3 shrink-0" />
- <span className={`overflow-hidden transition-all duration-500 ease-out ${
- currentTab === "files"
- ? "max-w-16 opacity-100 ml-1"
- : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
- }`}>Files</span>
- </Link>
- <Link
- href={`/w/${slug}/traces?agentId=${agentId}`}
- className="group inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 px-2 hover:bg-muted hover:text-foreground transition-all"
- >
- <GitBranch className="size-3 shrink-0" />
- <span className="max-w-0 opacity-0 group-hover:max-w-20 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Traces</span>
- </Link>
- <div className="w-px h-4 bg-border mx-1" />
- <button
- className="group inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 px-2 hover:bg-muted hover:text-foreground transition-all"
- onClick={() => setEditing(true)}
- >
- <Pencil className="size-3 shrink-0" />
- <span className="max-w-0 opacity-0 group-hover:max-w-12 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Edit</span>
- </button>
- <button
- className="group inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 px-2 hover:bg-muted hover:text-destructive transition-all"
- onClick={() => setAgentConfirmOpen(true)}
- >
- <Trash2 className="size-3 shrink-0" />
- <span className="max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Remove</span>
- </button>
- </div>
-
- {/* Mobile: collapsed dropdown */}
- <div className="sm:hidden">
- <DropdownMenu>
- <DropdownMenuTrigger
- render={<Button variant="ghost" size="icon-sm" className="text-muted-foreground" />}
- >
- <MoreHorizontal className="size-4" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" sideOffset={6}>
- {currentTab !== "chat" && (
- <DropdownMenuItem
- onClick={() => router.push(`/w/${slug}/agents/${agentId}`)}
- >
- <MessageSquare className="size-3.5" /> Chat
- </DropdownMenuItem>
- )}
- {currentTab !== "email" && (
- <DropdownMenuItem
- onClick={() => router.push(`/w/${slug}/agents/${agentId}/email`)}
- >
- <Mail className="size-3.5" /> Email
- </DropdownMenuItem>
- )}
- {currentTab !== "meetings" && (
- <DropdownMenuItem
- onClick={() => router.push(`/w/${slug}/agents/${agentId}/meetings`)}
- >
- <Video className="size-3.5" /> Meetings
- </DropdownMenuItem>
- )}
- {currentTab !== "activity" && (
- <DropdownMenuItem
- onClick={() => router.push(`/w/${slug}/agents/${agentId}/activity`)}
- >
- <History className="size-3.5" /> Activity
- </DropdownMenuItem>
- )}
- {currentTab !== "files" && (
- <DropdownMenuItem
- onClick={() => router.push(`/w/${slug}/agents/${agentId}/files`)}
- >
- <FolderOpen className="size-3.5" /> Files
- </DropdownMenuItem>
- )}
- <DropdownMenuItem
- onClick={() =>
- router.push(`/w/${slug}/traces?agentId=${agentId}`)
- }
- >
- <GitBranch className="size-3.5" />
- Traces
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => setEditing(true)}>
- <Pencil className="size-3.5" />
- Edit
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setAgentConfirmOpen(true)}
- >
- <Trash2 className="size-3.5" />
- Remove
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </>
- )}
- </div>
- ) : (
- <div className="h-7 shrink-0" />
- )}
- </div>
-
- {/* Content: edit form OR full-width children */}
- {editing && agent ? (
- <AgentEditForm
- agent={agent}
- runtimes={runtimes}
- modelOptions={modelOptions}
- saving={saving}
- onCancel={() => setEditing(false)}
- onSave={async (data) => {
- setSaving(true);
- try {
- const ok = await handleUpdateAgent(agent.id, data);
- if (ok) setEditing(false);
- return ok;
- } finally {
- setSaving(false);
- }
- }}
- />
-
- ) : (
- <div className="flex-1 min-h-0 overflow-hidden flex flex-col">
- {currentTab === "chat" && <ChannelBar />}
- {children}
- </div>
- )}
-
- {/* Delete agent confirmation */}
- {agent && (
- <ConfirmDialog
- open={agentConfirmOpen}
- onOpenChange={setAgentConfirmOpen}
- title="Remove agent"
- description={`This will permanently delete "${agent.name}" and all its conversations.`}
- loading={agentDeleting}
- onConfirm={async () => {
- setAgentDeleting(true);
- try {
- const ok = await handleDeleteAgent(agent.id);
- if (ok) router.push(`/w/${slug}/home`);
- } finally {
- setAgentDeleting(false);
- setAgentConfirmOpen(false);
- }
- }}
- />
- )}
- </>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx
deleted file mode 100644
index 328c6b9d1..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx
+++ /dev/null
@@ -1,291 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect } from "react";
-import { useParams } from "next/navigation";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { useWorkspaceMeetings } from "@/hooks/workspace/use-workspace-meetings";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { isAbortError } from "@/lib/errors";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Sheet, SheetContent, SheetBody, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Video, Plus, Square, Check, Clock, AlertCircle, Loader2, Trash2, ShieldCheck } from "lucide-react";
-import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import type { MeetingSession } from "@alook/shared";
-
-const STATUS_CONFIG: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline"; icon: typeof Clock }> = {
- pending: { label: "Pending", variant: "outline", icon: Clock },
- scheduled: { label: "Scheduled", variant: "secondary", icon: Clock },
- joining: { label: "Joining...", variant: "default", icon: Loader2 },
- recording: { label: "Recording", variant: "default", icon: Video },
- completed: { label: "Completed", variant: "secondary", icon: Check },
- failed: { label: "Failed", variant: "destructive", icon: AlertCircle },
-};
-
-function MeetingStatusBadge({ status }: { status: string }) {
- const config = STATUS_CONFIG[status] ?? STATUS_CONFIG.pending!;
- const Icon = config.icon;
- return (
- <Badge variant={config.variant} className="gap-1 text-[10px]">
- <Icon className={cn("size-2.5", status === "joining" && "animate-spin", status === "recording" && "animate-pulse")} />
- {config.label}
- </Badge>
- );
-}
-
-function formatTime(iso: string | null) {
- if (!iso) return "";
- const d = new Date(iso);
- return d.toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
-}
-
-export default function AgentMeetingsPage() {
- const params = useParams();
- const owner = useWorkspaceOwner();
- return <AgentMeetingsView key={`${owner.workspaceId}:${params.id}`} agentId={params.id as string} />;
-}
-
-function AgentMeetingsView({ agentId }: { agentId: string }) {
- const owner = useWorkspaceOwner();
- const resource = useWorkspaceMeetings(agentId);
- const meetings = resource.data ?? [];
- const loading = resource.isPending;
- useObservedQueryRegion("meetings", resource);
- const [createOpen, setCreateOpen] = useAtom(useCreateAtom(false));
- const [deleteId, setDeleteId] = useAtom(useCreateAtom<string | null>(null));
- const deleteTarget = meetings.find((meeting) => meeting.id === deleteId);
- const creating = resource.mutation.isPending && resource.mutation.variables?.kind === "create";
- const deleting = resource.mutation.isPending && resource.mutation.variables?.kind === "delete";
- const [meetUrl, setMeetUrl] = useAtom(useCreateAtom(""));
- const [meetTitle, setMeetTitle] = useAtom(useCreateAtom(""));
- const [meetParticipants, setMeetParticipants] = useAtom(useCreateAtom(""));
- const source = useWorkspaceViewSource(owner, `meetings:${agentId}`, true);
- const creation = useWorkspaceViewSource(owner, `meetings:${agentId}:create`, createOpen);
- const deletion = useWorkspaceViewSource(owner, `meetings:${agentId}:delete:${deleteId}`, deleteId !== null);
- useEffect(() => {
- if (!resource.error || isAbortError(resource.error)) return;
- try { source.assertActive() } catch { return; }
- toast.error("Failed to load meetings");
- }, [resource.error, source, source.assertActive]);
- const handleCreate = async () => {
- if (!meetUrl || resource.isCommandPending()) return;
- const assertUI = creation.assertActive;
- try {
- assertUI();
- const participants = meetParticipants.split(/[,\n]/).map((value) => value.trim()).filter(Boolean);
- await resource.mutation.mutateAsync({ kind: "create", data: { meetingUrl: meetUrl, title: meetTitle || undefined, participants: participants.length ? participants : undefined }, assertUI });
- assertUI();
- toast.success("Meeting created");
- setCreateOpen(false);
- setMeetUrl(""); setMeetTitle(""); setMeetParticipants("");
- void resource.refetch();
- } catch (error) {
- try { assertUI() } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to create meeting");
- }
- };
- const changeMeeting = async (kind: "stop" | "approve", meeting: MeetingSession) => {
- if (resource.isCommandPending()) return;
- const assertUI = source.assertActive;
- try {
- assertUI();
- await resource.mutation.mutateAsync({ kind, id: meeting.id, assertUI });
- assertUI();
- toast.success(kind === "stop" ? "Meeting stopped" : "Meeting approved");
- void resource.refetch();
- } catch (error) {
- try { assertUI() } catch { return; }
- if (!isAbortError(error)) toast.error(kind === "stop" ? "Failed to stop meeting" : "Failed to approve meeting");
- }
- };
- const handleStop = (meeting: MeetingSession) => changeMeeting("stop", meeting);
- const handleApprove = (meeting: MeetingSession) => changeMeeting("approve", meeting);
- const handleDelete = async () => {
- if (!deleteId || resource.isCommandPending()) return;
- const assertUI = deletion.assertActive;
- try {
- assertUI();
- await resource.mutation.mutateAsync({ kind: "delete", id: deleteId, assertUI });
- assertUI();
- toast.success("Meeting deleted"); setDeleteId(null);
- void resource.refetch();
- } catch (error) {
- try { assertUI() } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to delete meeting");
- }
- };
-
- return (
- <div className="flex-1 flex flex-col min-h-0">
- {/* Header */}
- <div className="flex items-center justify-between px-4 py-3 border-b border-border/50">
- <h2 className="text-sm font-medium">Meetings</h2>
- <Button size="sm" onClick={() => setCreateOpen(true)} className="gap-1">
- <Plus className="size-3" />
- Join Meeting
- </Button>
- </div>
-
- {/* List */}
- <div className="flex-1 overflow-y-auto thin-scrollbar">
- {loading ? (
- <div className="p-4 space-y-3">
- {[1, 2, 3].map((i) => (
- <Skeleton key={i} className="h-16 w-full rounded-lg" />
- ))}
- </div>
- ) : meetings.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full text-muted-foreground gap-2 p-8">
- <Video className="size-8 opacity-40" />
- <p className="text-sm">No meetings yet</p>
- <p className="text-xs">Join a Google Meet to start recording transcripts.</p>
- </div>
- ) : (
- <div className="p-2 space-y-1">
- {meetings.map((meeting) => (
- <div
- key={meeting.id}
- className={cn(
- "flex items-center gap-3 rounded-lg border border-border/50 px-3 py-2 transition-colors",
- meeting.status === "pending" && !meeting.is_whitelisted && "opacity-60",
- )}
- >
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 mb-1">
- <span className="text-sm font-medium truncate">
- {meeting.title || "Untitled Meeting"}
- </span>
- <MeetingStatusBadge status={meeting.status} />
- </div>
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <span className="truncate">{meeting.meeting_url.replace("https://", "")}</span>
- {meeting.scheduled_at && (
- <span className="shrink-0">{formatTime(meeting.scheduled_at)}</span>
- )}
- {meeting.started_at && !meeting.completed_at && (
- <span className="shrink-0">Started {formatTime(meeting.started_at)}</span>
- )}
- {meeting.completed_at && (
- <span className="shrink-0">{formatTime(meeting.completed_at)}</span>
- )}
- {(meeting.participants as string[])?.length > 0 && (
- <span className="shrink-0">{(meeting.participants as string[]).length} participants</span>
- )}
- </div>
- {meeting.error && (
- <p className="text-xs text-destructive mt-1 truncate">{meeting.error}</p>
- )}
- </div>
- <div className="flex items-center gap-1 shrink-0">
- {meeting.status === "pending" && (
- <Button
- variant="outline"
- size="xs"
- className="gap-1"
- onClick={() => handleApprove(meeting)}
- >
- <ShieldCheck className="size-3" />
- Approve
- </Button>
- )}
- {(meeting.status === "recording" || meeting.status === "joining") && (
- <Button
- variant="outline"
- size="xs"
- className="gap-1 text-destructive"
- onClick={() => handleStop(meeting)}
- >
- <Square className="size-3" />
- Stop
- </Button>
- )}
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label={`Delete ${meeting.title || "meeting"}`}
- className="text-muted-foreground hover:text-destructive"
- onClick={() => setDeleteId(meeting.id)}
- >
- <Trash2 className="size-3" />
- </Button>
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
-
- {/* Create Meeting Sheet */}
- <Sheet open={createOpen} onOpenChange={setCreateOpen}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>Join a Meeting</SheetTitle>
- </SheetHeader>
- <SheetBody className="space-y-4">
- <div>
- <label className="text-xs font-medium text-muted-foreground mb-1 block">
- Google Meet URL *
- </label>
- <input
- type="url"
- placeholder="https://meet.google.com/abc-defg-hij"
- value={meetUrl}
- onChange={(e) => setMeetUrl(e.target.value)}
- className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"
- />
- </div>
- <div>
- <label className="text-xs font-medium text-muted-foreground mb-1 block">
- Title
- </label>
- <input
- type="text"
- placeholder="Weekly Standup"
- value={meetTitle}
- onChange={(e) => setMeetTitle(e.target.value)}
- className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"
- />
- </div>
- <div>
- <label className="text-xs font-medium text-muted-foreground mb-1 block">
- Participants (one email per line)
- </label>
- <textarea
- value={meetParticipants}
- onChange={(e) => setMeetParticipants(e.target.value)}
- rows={3}
- className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring resize-none"
- />
- </div>
- </SheetBody>
- <SheetFooter>
- <Button variant="outline" onClick={() => setCreateOpen(false)}>
- Cancel
- </Button>
- <Button onClick={handleCreate} disabled={creating || !meetUrl}>
- {creating && <Loader2 className="size-3 animate-spin" />}
- Join Meeting
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
-
- {/* Delete Confirmation */}
- <ConfirmDialog
- open={deleteId !== null}
- onOpenChange={(open) => !open && setDeleteId(null)}
- title="Delete meeting"
- description={`Remove "${deleteTarget?.title || "this meeting"}" and its transcript?`}
- loading={deleting}
- onConfirm={handleDelete}
- />
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/page.tsx
deleted file mode 100644
index 3d5062d54..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/page.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-"use client";
-
-import { AgentChatView } from "@/components/agent-chat/agent-chat-view";
-
-export default function AgentDetailPage() {
- return <AgentChatView />;
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx
deleted file mode 100644
index e66f61d7f..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions";
-
-import { useRef, useCallback, type ComponentProps } from "react";
-import { useRouter } from "next/navigation";
-import { useAgentContext } from "@/contexts/agent-context";
-import { assertWorkspaceOwner, captureWorkspaceOwner, runWorkspaceRequest, useWorkspaceOwner } from "@/contexts/workspace-context";
-import { useMutation, useQuery } from "@tanstack/react-query";
-import { isAbortError } from "@/lib/errors";
-import { runApplicationRequest } from "@/lib/application-owner";
-import { AgentCreateForm } from "@/components/agent-create-form";
-import { fetchModelOptions, createEmailAccount } from "@/lib/api";
-import { toast } from "sonner";
-import { CircleHelp } from "lucide-react";
-import { trackAgentCreated, trackSecondAgentCreated, trackCustomEmailConnected } from "@/lib/analytics";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-
-
-type CreateAgentInput = Parameters<ComponentProps<typeof AgentCreateForm>["onSave"]>[0];
-const EMPTY_MODELS: Record<string, string[]> = {};
-
-export default function CreateAgentPage() {
- const router = useRouter();
- const workspace = useWorkspaceOwner();
- const { slug, workspaceId } = workspace;
- const {
- agents,
- runtimes,
- handleCreateAgent,
- getFirstOnlineRuntimeId,
- } = useAgentContext();
-
- const startTourRef = useRef<(() => void) | null>(null);
- const modelQuery = useQuery({
- queryKey: ["application", workspace.application.userId, "model-options"],
- queryFn: ({ signal }) => runApplicationRequest(workspace.application, (options) => fetchModelOptions(options), signal),
- });
- const modelOptions = modelQuery.data ?? EMPTY_MODELS;
- useObservedQueryRegion("agents", modelQuery);
- const create = useMutation({ meta: { observabilityAction: "agent.create" },
- mutationKey: workspace.key("agents", "create-with-email"),
- mutationFn: async ({ data, token, agentCount }: { data: CreateAgentInput; token: ReturnType<typeof captureWorkspaceOwner>; agentCount: number }) => {
- assertWorkspaceOwner(token);
- const agent = await handleCreateAgent({
- name: data.name,
- description: data.description || undefined,
- instructions: data.instructions || undefined,
- runtime_id: data.runtime_id,
- email_handle: data.email_handle || undefined,
- runtime_config: data.runtime_config,
- avatar_url: data.avatar_url,
- });
- assertWorkspaceOwner(token);
- if (!agent) return false;
- trackAgentCreated({ is_first_agent: agentCount === 0, has_email: !!data.email_handle || !!data.custom_email });
- if (agentCount === 1) trackSecondAgentCreated({ total_agents: 2 });
- if (data.custom_email) {
- try {
- await runWorkspaceRequest(workspace, (options) => createEmailAccount(agent.id, data.custom_email!, workspaceId, options));
- assertWorkspaceOwner(token);
- toast.success("Custom email connected");
- trackCustomEmailConnected({ email_domain: data.custom_email.emailAddress?.split("@")[1] ?? "" });
- } catch (error) {
- assertWorkspaceOwner(token);
- if (isAbortError(error)) throw error;
- toast.error(error instanceof Error ? error.message : "Failed to connect custom email");
- }
- }
- assertWorkspaceOwner(token);
- router.push(`/w/${slug}/agents/${agent.id}/chat`);
- return true;
- },
- });
-
- const handleTourReady = useCallback((startTour: () => void) => {
- startTourRef.current = startTour;
- }, []);
-
- return (
- <>
- <div className="flex items-center gap-2 border-b border-border/50 px-3 sm:px-4 py-2">
- <h1 className="text-sm font-medium">Create Agent</h1>
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() => startTourRef.current?.()}
- className="text-muted-foreground"
- />
- }
- >
- <CircleHelp className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Show guided tour</TooltipContent>
- </Tooltip>
- </div>
-
- <AgentCreateForm
- runtimes={runtimes}
- defaultRuntimeId={getFirstOnlineRuntimeId()}
- modelOptions={modelOptions}
- guided={agents.length === 0}
- onTourReady={handleTourReady}
- saving={create.isPending}
- onCancel={() => router.back()}
- onSave={async (data) => {
- const token = captureWorkspaceOwner(workspace);
- try { return await create.mutateAsync({ data, token, agentCount: agents.length }); }
- catch (error) { if (isAbortError(error)) return false; throw error; }
- }}
- />
- </>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/page.tsx
deleted file mode 100644
index 4b4113aa6..000000000
--- a/src/web/src/app/(app)/w/[slug]/agents/page.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-"use client";
-
-import { useEffect } from "react";
-import { useRouter } from "next/navigation";
-import { useWorkspace } from "@/contexts/workspace-context";
-
-export default function AgentsRedirect() {
- const router = useRouter();
- const { slug } = useWorkspace();
-
- useEffect(() => {
- router.replace(`/w/${slug}/home`);
- }, [router, slug]);
-
- return null;
-}
diff --git a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx b/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
deleted file mode 100644
index 30459dc73..000000000
--- a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
+++ /dev/null
@@ -1,654 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useQuery, useMutation, skipToken, type QueryKey } from "@tanstack/react-query";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { captureApplicationOwner, assertApplicationOwner } from "@/lib/application-owner";
-import { isAbortError } from "@/lib/errors";
-import { useCallback, useEffect, useMemo, useRef } from "react";
-import { useRouter, useSearchParams, usePathname } from "next/navigation";
-import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { Button } from "@/components/ui/button";
-import { Plus } from "lucide-react";
-
-import {
- listCalendarEvents,
- createCalendarEvent,
- updateCalendarEvent,
- deleteCalendarEvent,
-} from "@/lib/api";
-import {
- CalendarMonthGrid,
- buildMonthCells,
- dateKey,
- stepDate,
-} from "@/components/calendar/calendar-month-grid";
-import { CalendarAgenda } from "@/components/calendar/calendar-agenda";
-import { CalendarWeekGrid } from "@/components/calendar/calendar-week-grid";
-import {
- CalendarViewSwitcher,
- parseCalendarView,
- type CalendarView,
-} from "@/components/calendar/calendar-view-switcher";
-import { CalendarAgentFilter } from "@/components/calendar/calendar-agent-filter";
-import { CalendarEventSheet } from "@/components/calendar/calendar-event-sheet";
-import { getWeekStart, weekRangeIso } from "@/components/calendar/calendar-week-utils";
-import type { CalendarEvent, UpdateCalendarEventRequest } from "@alook/shared";
-import { isTypingTarget } from "@/components/calendar/keyboard";
-import { useIsMobile } from "@/hooks/use-mobile";
-import { trackCalendarEventCreated } from "@/lib/analytics";
-
-/**
- * The month grid always renders six full weeks (42 cells), which means the
- * first and last rows usually include leading/trailing days from adjacent
- * months. Fetch for the full visible grid — otherwise recurring occurrences
- * that land on those out-of-month cells would silently not render.
- */
-function gridRangeIso(year: number, month: number) {
- const cells = buildMonthCells(year, month);
- const first = cells[0]!.date;
- const last = cells[cells.length - 1]!.date;
- const from = new Date(
- first.getFullYear(),
- first.getMonth(),
- first.getDate(),
- 0,
- 0,
- 0,
- 0
- );
- const to = new Date(
- last.getFullYear(),
- last.getMonth(),
- last.getDate(),
- 23,
- 59,
- 59,
- 999
- );
- return { from: from.toISOString(), to: to.toISOString() };
-}
-
-export default function CalendarPage() {
- const owner = useWorkspaceOwner();
- const { workspaceId } = owner;
- const { agents, subscribeWs } = useAgentContext();
- const router = useRouter();
- const pathname = usePathname();
- const searchParams = useSearchParams();
- const isMobile = useIsMobile();
-
- const now = new Date();
- const initialYear = Number(searchParams.get("y")) || now.getFullYear();
- const initialMonth = searchParams.has("m")
- ? Number(searchParams.get("m"))
- : now.getMonth();
- const initialView = parseCalendarView(searchParams.get("view"));
-
- const [year, setYear] = useAtom(useCreateAtom(initialYear));
- const [month, setMonth] = useAtom(useCreateAtom(initialMonth));
- const [view, setView] = useAtom(useCreateAtom<CalendarView>(initialView));
- const [selectedAgents, setSelectedAgents] = useAtom(useCreateAtom<Set<string>>(useMemo<Set<string>>(() => {
- const param = searchParams.get("agents");
- if (!param) return new Set();
- return new Set(param.split(",").filter(Boolean));
- }, [searchParams])));
- // Default focus to today when the current view contains today, otherwise the
- // 1st of the viewed month — keeps at least one day cell in the tab order.
- const [focusedDate, setFocusedDate] = useAtom(useCreateAtom<Date>(useMemo<Date>(() => {
- const t = new Date();
- if (t.getFullYear() === initialYear && t.getMonth() === initialMonth) return t;
- return new Date(initialYear, initialMonth, 1);
- }, [initialMonth, initialYear])));
- const [weekAnchor, setWeekAnchor] = useAtom(useCreateAtom<Date>(useMemo<Date>(() => {
- if (initialView === "week" && searchParams.has("d")) {
- const d = Number(searchParams.get("d"));
- return getWeekStart(new Date(initialYear, initialMonth, d));
- }
- return getWeekStart(new Date());
- }, [initialMonth, initialView, initialYear, searchParams])));
- const [openPopoverKey, setOpenPopoverKey] = useAtom(useCreateAtom<string | null>(null));
-
- const [createOpen, setCreateOpen] = useAtom(useCreateAtom(false));
- const [createDefault, setCreateDefault] = useAtom(useCreateAtom<Date | undefined>(undefined));
- const [detailSelection, setDetailSelection] = useAtom(useCreateAtom<{ key: QueryKey; id: string; occurrence: string | null } | null>(null));
- const [detailOpen, setDetailOpen] = useAtom(useCreateAtom(false));
-
- const syncUrl = useCallback(
- (
- nextYear: number,
- nextMonth: number,
- agentSet: Set<string>,
- nextView: CalendarView,
- weekAnchorDate?: Date | null
- ) => {
- const params = new URLSearchParams();
- params.set("y", String(nextYear));
- params.set("m", String(nextMonth));
- if (agentSet.size > 0) params.set("agents", [...agentSet].join(","));
- if (nextView !== "month") params.set("view", nextView);
- if (nextView === "week" && weekAnchorDate) {
- params.set("d", String(weekAnchorDate.getDate()));
- }
- router.replace(`${pathname}?${params.toString()}`, { scroll: false });
- },
- [pathname, router]
- );
-
- const range = useMemo(() => view === "week" ? weekRangeIso(weekAnchor) : gridRangeIso(year, month), [view, weekAnchor, year, month]);
- const source = useWorkspaceViewSource(owner, `calendar:${range.from}:${range.to}:${detailSelection?.id ?? ""}:${detailSelection?.occurrence ?? ""}:${detailOpen}:${createOpen}`, true);
- const eventsKey = useMemo(() => owner.key("calendar", "range", range.from, range.to), [owner, range.from, range.to]);
- const eventsQuery = useQuery({ queryKey: eventsKey, queryFn: ({ signal }) => listCalendarEvents(workspaceId, range, source.request(signal)) });
- const events = eventsQuery.data ?? EMPTY_EVENTS;
- const loading = eventsQuery.isPending;
- useObservedQueryRegion("calendar", eventsQuery, events.length);
- const detail = useQuery({ queryKey: detailSelection?.key ?? owner.key("calendar", "range", "__none__"), queryFn: detailSelection ? ({ signal, queryKey }) => listCalendarEvents(workspaceId, { from: String(queryKey[6]), to: String(queryKey[7]) }, source.request(signal)) : skipToken, enabled: false,
- select: (rows: CalendarEvent[]) => rows.find((row) => row.id === detailSelection?.id && (row.occurrence_at ?? null) === detailSelection?.occurrence) ?? null,
- }).data ?? null;
- const fetchEvents = useCallback(() => owner.queryClient.invalidateQueries({ queryKey: eventsKey, exact: true }), [owner, eventsKey]);
- useEffect(() => {
- if (!eventsQuery.error || eventsQuery.isFetching || isAbortError(eventsQuery.error)) return;
- try { source.assertActive(); } catch { return; }
- toast.error(eventsQuery.error instanceof Error ? eventsQuery.error.message : "Failed to load events");
- }, [eventsQuery.error, eventsQuery.isFetching, source, source.assertActive]);
- useEffect(() => subscribeWs((message) => {
- try { source.assertActive(); } catch { return; }
- if (message.type.startsWith("calendar.")) void owner.queryClient.invalidateQueries({ queryKey: owner.key("calendar") });
- }), [owner, subscribeWs, source.assertActive, source]);
- const calendarMutation = useMutation({ meta: { observabilityAction: "calendar.command" }, mutationFn: ({ operation }: { operation: () => Promise<unknown>; kind: "create" | "update" | "delete"; id?: string; assertActive: () => void }) => operation() });
- const currentMutation = calendarMutation.isPending && calendarMutation.variables.assertActive === source.assertActive;
- const submitting = currentMutation && calendarMutation.variables.kind === "create";
- const submittingEdit = currentMutation && calendarMutation.variables.kind === "update";
- const deletingId = currentMutation && calendarMutation.variables.kind === "delete" ? calendarMutation.variables.id : null;
- const mutateCalendar = calendarMutation.mutateAsync;
- const settleFacts = () => {
- const token = captureApplicationOwner(owner.application);
- const resource = owner.queryClient.getQueryCache().find({ queryKey: eventsKey, exact: true });
- return () => {
- try { assertApplicationOwner(token); } catch { return; }
- if (resource && owner.queryClient.getQueryCache().find({ queryKey: eventsKey, exact: true }) === resource) void owner.queryClient.invalidateQueries({ queryKey: eventsKey, exact: true, refetchType: "none" });
- };
- };
-
- const visibleEvents = useMemo(() => {
- if (selectedAgents.size === 0) return events;
- return events.filter((ev) => selectedAgents.has(ev.agent_id));
- }, [events, selectedAgents]);
-
- const handlePrev = useCallback(() => {
- const nm = month === 0 ? 11 : month - 1;
- const ny = month === 0 ? year - 1 : year;
- setMonth(nm);
- setYear(ny);
- setFocusedDate(new Date(ny, nm, 1));
- syncUrl(ny, nm, selectedAgents, view);
- }, [month, year, setMonth, setYear, setFocusedDate, syncUrl, selectedAgents, view]);
-
- const handleNext = useCallback(() => {
- const nm = month === 11 ? 0 : month + 1;
- const ny = month === 11 ? year + 1 : year;
- setMonth(nm);
- setYear(ny);
- setFocusedDate(new Date(ny, nm, 1));
- syncUrl(ny, nm, selectedAgents, view);
- }, [month, year, setMonth, setYear, setFocusedDate, syncUrl, selectedAgents, view]);
-
- const handlePrevWeek = useCallback(() => {
- const prev = new Date(weekAnchor);
- prev.setDate(prev.getDate() - 7);
- setWeekAnchor(prev);
- setFocusedDate(prev);
- syncUrl(prev.getFullYear(), prev.getMonth(), selectedAgents, "week", prev);
- }, [weekAnchor, setWeekAnchor, setFocusedDate, syncUrl, selectedAgents]);
-
- const handleNextWeek = useCallback(() => {
- const next = new Date(weekAnchor);
- next.setDate(next.getDate() + 7);
- setWeekAnchor(next);
- setFocusedDate(next);
- syncUrl(next.getFullYear(), next.getMonth(), selectedAgents, "week", next);
- }, [weekAnchor, setWeekAnchor, setFocusedDate, syncUrl, selectedAgents]);
-
- const handleToggleAgent = (agentId: string) => {
- const next = new Set(selectedAgents);
- if (next.has(agentId)) next.delete(agentId);
- else next.add(agentId);
- setSelectedAgents(next);
- syncUrl(year, month, next, view, view === "week" ? weekAnchor : null);
- };
-
- const handleSelectDay = (date: Date) => {
- setCreateDefault(date);
- setCreateOpen(true);
- setFocusedDate(date);
- };
-
- const handleSelectEvent = (ev: CalendarEvent) => {
- setDetailSelection({ key: eventsKey, id: ev.id, occurrence: ev.occurrence_at ?? null });
- setDetailOpen(true);
- };
-
- const jumpToDate = useCallback(
- (date: Date) => {
- const ny = date.getFullYear();
- const nm = date.getMonth();
- setYear(ny);
- setMonth(nm);
- setFocusedDate(date);
- if (view === "week") {
- const anchor = getWeekStart(date);
- setWeekAnchor(anchor);
- syncUrl(ny, nm, selectedAgents, view, anchor);
- } else {
- syncUrl(ny, nm, selectedAgents, view);
- }
- },
- [setYear, setMonth, setFocusedDate, view, setWeekAnchor, syncUrl, selectedAgents]
- );
-
- const handleJumpToToday = useCallback(() => {
- const today = new Date();
- if (view === "week") {
- const anchor = getWeekStart(today);
- setWeekAnchor(anchor);
- setFocusedDate(today);
- syncUrl(anchor.getFullYear(), anchor.getMonth(), selectedAgents, "week", anchor);
- } else {
- jumpToDate(today);
- }
- }, [view, setWeekAnchor, setFocusedDate, syncUrl, selectedAgents, jumpToDate]);
-
- const handleViewChange = useCallback(
- (v: CalendarView) => {
- setView(v);
- if (v === "week") {
- const anchor = getWeekStart(focusedDate);
- setWeekAnchor(anchor);
- syncUrl(year, month, selectedAgents, v, anchor);
- } else if (view === "week") {
- const ny = weekAnchor.getFullYear();
- const nm = weekAnchor.getMonth();
- setYear(ny);
- setMonth(nm);
- syncUrl(ny, nm, selectedAgents, v);
- } else {
- syncUrl(year, month, selectedAgents, v);
- }
- },
- [setView, view, focusedDate, setWeekAnchor, syncUrl, year, month, selectedAgents, weekAnchor, setYear, setMonth]
- );
-
- const handleCreate = async (values: {
- agent_id: string;
- title: string;
- description?: string;
- scheduled_at: string;
- repeat_interval?: string;
- repeat_stop_date?: string;
- }) => {
- const assertActive = source.assertActive; const settle = settleFacts();
- assertActive();
- try {
- const created = await mutateCalendar({ kind: "create", assertActive, operation: async () => { await owner.queryClient.cancelQueries({ queryKey: owner.key("calendar", "range") }); assertActive(); return createCalendarEvent(values, workspaceId, { assertActive }); } }) as CalendarEvent;
- assertActive();
- trackCalendarEventCreated({
- agent_id: values.agent_id,
- is_recurring: !!values.repeat_interval,
- });
- const { from, to } =
- view === "week"
- ? weekRangeIso(weekAnchor)
- : gridRangeIso(year, month);
- const createdAt = new Date(created.scheduled_at).getTime();
- if (
- createdAt >= new Date(from).getTime() &&
- createdAt <= new Date(to).getTime()
- ) {
- owner.queryClient.setQueryData<CalendarEvent[]>(eventsKey, (prev) => [...prev ?? [], created]);
- }
- setCreateOpen(false);
- toast.success("Event created");
- } catch (err) {
- if (isAbortError(err)) return;
- try { assertActive(); } catch { return; }
- toast.error(
- err instanceof Error ? err.message : "Failed to create event"
- );
- } finally {
- settle();
- }
- };
-
- const handleUpdate = async (
- event: CalendarEvent,
- patch: UpdateCalendarEventRequest
- ) => {
- const assertActive = source.assertActive; const settle = settleFacts();
- assertActive();
- try {
- await mutateCalendar({ kind: "update", id: event.id, assertActive, operation: async () => { await owner.queryClient.cancelQueries({ queryKey: owner.key("calendar", "range") }); assertActive(); return updateCalendarEvent(event.id, patch, workspaceId, { assertActive }); } });
- assertActive();
- // Recurring split may have created a detached row and advanced the
- // parent — simplest to re-fetch the visible range rather than merge.
- await fetchEvents();
- assertActive();
- setDetailOpen(false);
- setDetailSelection(null);
- toast.success("Event updated");
- } catch (err) {
- if (isAbortError(err)) return;
- try { assertActive(); } catch { return; }
- toast.error(
- err instanceof Error ? err.message : "Failed to update event"
- );
- } finally {
- settle();
- }
- };
-
- const handleDelete = async (
- event: CalendarEvent,
- args?: { scope?: "this" | "following"; occurrence_at?: string }
- ) => {
- const assertActive = source.assertActive; const settle = settleFacts();
- assertActive();
- try {
- await mutateCalendar({ kind: "delete", id: event.id, assertActive, operation: async () => { await owner.queryClient.cancelQueries({ queryKey: owner.key("calendar", "range") }); assertActive(); return deleteCalendarEvent(event.id, workspaceId, args, { assertActive }); } });
- assertActive();
- if (args?.scope) {
- // Scoped deletes may keep the parent row alive (advance scheduled_at,
- // append exception, clip repeat_stop_at) — refetch so the grid shows
- // the new series state instead of optimistically removing the row.
- await fetchEvents();
- assertActive();
- } else {
- owner.queryClient.setQueryData<CalendarEvent[]>(eventsKey, (prev) => prev?.filter((e) => e.id !== event.id));
- }
- setDetailOpen(false);
- setDetailSelection(null);
- toast.success("Event deleted");
- } catch (err) {
- if (isAbortError(err)) return;
- try { assertActive(); } catch { return; }
- toast.error(
- err instanceof Error ? err.message : "Failed to delete event"
- );
- } finally {
- settle();
- }
- };
-
- // Global keyboard handler — month view only. Page-level so `n`/`t` fire even
- // when the grid isn't focused. Arrow keys only move focus if it's already in
- // the grid.
- const createOpenRef = useRef(createOpen);
- const detailOpenRef = useRef(detailOpen);
- useEffect(() => {
- createOpenRef.current = createOpen;
- }, [createOpen]);
- useEffect(() => {
- detailOpenRef.current = detailOpen;
- }, [detailOpen]);
-
- // Memoize events-per-day for quick lookup in the keyboard handler.
- const hiddenCountForDate = useCallback(
- (d: Date) => {
- const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
- let count = 0;
- for (const ev of visibleEvents) {
- const ed = new Date(ev.scheduled_at);
- const k = `${ed.getFullYear()}-${String(ed.getMonth() + 1).padStart(2, "0")}-${String(ed.getDate()).padStart(2, "0")}`;
- if (k === key) count++;
- }
- return Math.max(0, count - 3);
- },
- [visibleEvents]
- );
-
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if (createOpenRef.current || detailOpenRef.current) return;
- if (isTypingTarget(e.target)) return;
-
- // `t` and `n` fire in every view.
- if (e.key === "t") {
- e.preventDefault();
- const today = new Date();
- if (view === "week") {
- const anchor = getWeekStart(today);
- setWeekAnchor(anchor);
- setFocusedDate(today);
- syncUrl(anchor.getFullYear(), anchor.getMonth(), selectedAgents, "week", anchor);
- } else if (today.getFullYear() !== year || today.getMonth() !== month) {
- jumpToDate(today);
- } else {
- setFocusedDate(today);
- }
- return;
- }
-
- if (e.key === "n") {
- e.preventDefault();
- const target = focusedDate;
- setCreateDefault(target);
- setCreateOpen(true);
- return;
- }
-
- // Arrow / Enter / Page / Home / End are for month and week views only.
- if (view !== "month" && view !== "week") return;
-
- if (view === "week") {
- if (e.key === "ArrowLeft") {
- e.preventDefault();
- const next = new Date(focusedDate);
- next.setDate(next.getDate() - 1);
- setFocusedDate(next);
- const anchor = getWeekStart(next);
- if (anchor.getTime() !== weekAnchor.getTime()) {
- setWeekAnchor(anchor);
- syncUrl(anchor.getFullYear(), anchor.getMonth(), selectedAgents, "week", anchor);
- }
- return;
- }
- if (e.key === "ArrowRight") {
- e.preventDefault();
- const next = new Date(focusedDate);
- next.setDate(next.getDate() + 1);
- setFocusedDate(next);
- const anchor = getWeekStart(next);
- if (anchor.getTime() !== weekAnchor.getTime()) {
- setWeekAnchor(anchor);
- syncUrl(anchor.getFullYear(), anchor.getMonth(), selectedAgents, "week", anchor);
- }
- return;
- }
- if (e.key === "ArrowUp") {
- e.preventDefault();
- const next = new Date(focusedDate);
- next.setHours(next.getHours() - 1);
- setFocusedDate(next);
- return;
- }
- if (e.key === "ArrowDown") {
- e.preventDefault();
- const next = new Date(focusedDate);
- next.setHours(next.getHours() + 1);
- setFocusedDate(next);
- return;
- }
- return;
- }
-
- const focusInGrid =
- document.activeElement?.getAttribute("role") === "gridcell";
-
- if (e.key === "Enter") {
- if (!focusInGrid) return;
- e.preventDefault();
- const hidden = hiddenCountForDate(focusedDate);
- if (hidden > 0) {
- const key = `${focusedDate.getFullYear()}-${String(focusedDate.getMonth() + 1).padStart(2, "0")}-${String(focusedDate.getDate()).padStart(2, "0")}`;
- setOpenPopoverKey(key);
- } else {
- setCreateDefault(focusedDate);
- setCreateOpen(true);
- }
- return;
- }
-
- // Escape is handled by base-ui popover / dialog primitives internally.
-
- if (!focusInGrid) return;
-
- const stepped = stepDate(focusedDate, e.key);
- if (!stepped) return;
- e.preventDefault();
- const inView =
- stepped.getFullYear() === year && stepped.getMonth() === month;
- if (inView) {
- setFocusedDate(stepped);
- } else {
- jumpToDate(stepped);
- }
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [view, year, month, focusedDate, jumpToDate, hiddenCountForDate, weekAnchor, selectedAgents, syncUrl, setWeekAnchor, setFocusedDate, setCreateDefault, setCreateOpen, setOpenPopoverKey]);
-
- // When focusedDate changes, move DOM focus onto that cell — but only if
- // focus is already inside the grid (don't steal focus on page load).
- useEffect(() => {
- if (view !== "month") return;
- const active = document.activeElement;
- if (!active || active.getAttribute("role") !== "gridcell") return;
- const sel = `[data-date="${dateKey(focusedDate)}"]`;
- const el = document.querySelector<HTMLElement>(sel);
- el?.focus();
- }, [focusedDate, view, year, month]);
-
- return (
- <>
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2 gap-3">
- <div className="flex items-center gap-3 min-w-0">
- <h1 className="text-sm font-medium">Calendar</h1>
- <p className="text-xs text-muted-foreground hidden sm:block">
- Schedule recurring and one-time tasks for your agents.
- </p>
- </div>
- <div className="flex items-center gap-2">
- <CalendarViewSwitcher view={view} onChange={handleViewChange} />
- <Button
- size="sm"
- variant="outline"
- onClick={() => {
- setCreateDefault(undefined);
- setCreateOpen(true);
- }}
- disabled={agents.length === 0}
- className="min-w-11 min-h-11 sm:min-w-0 sm:min-h-0"
- >
- <Plus className="size-3.5" />
- <span className="hidden sm:inline">New event</span>
- </Button>
- </div>
- </div>
-
- <div className={cn(
- "flex flex-1 flex-col gap-4 px-3 py-3 sm:px-4 sm:py-4",
- view === "week" ? "min-h-0 overflow-hidden" : "overflow-y-auto"
- )}>
- <CalendarAgentFilter
- agents={agents}
- selected={selectedAgents}
- onToggle={handleToggleAgent}
- />
-
- {view === "month" && (
- <CalendarMonthGrid
- year={year}
- month={month}
- events={visibleEvents}
- agents={agents}
- loading={loading}
- focusedDate={focusedDate}
- openPopoverKey={openPopoverKey}
- onPopoverChange={setOpenPopoverKey}
- onPrev={handlePrev}
- onNext={handleNext}
- onJumpToToday={handleJumpToToday}
- onJumpToDate={jumpToDate}
- onSelectDay={handleSelectDay}
- onSelectEvent={handleSelectEvent}
- />
- )}
-
- {view === "week" && (
- <CalendarWeekGrid
- weekStart={weekAnchor}
- events={visibleEvents}
- agents={agents}
- loading={loading}
- focusedDate={focusedDate}
- compact={isMobile}
- onPrevWeek={handlePrevWeek}
- onNextWeek={handleNextWeek}
- onJumpToToday={handleJumpToToday}
- onJumpToDate={jumpToDate}
- onSelectSlot={(date, hour) => {
- const target = new Date(date.getFullYear(), date.getMonth(), date.getDate(), hour);
- setCreateDefault(target);
- setCreateOpen(true);
- }}
- onSelectEvent={handleSelectEvent}
- />
- )}
-
- {view === "agenda" && (
- <CalendarAgenda
- events={visibleEvents}
- agents={agents}
- loading={loading}
- onSelectEvent={handleSelectEvent}
- />
- )}
-
- {(view === "month" || view === "week") &&
- !loading &&
- events.length > 0 &&
- visibleEvents.length === 0 && (
- <p className="text-center text-xs text-muted-foreground py-4">
- No events for selected agents.
- </p>
- )}
- </div>
-
- <CalendarEventSheet
- open={createOpen}
- onOpenChange={setCreateOpen}
- agents={agents}
- defaultDate={createDefault}
- submitting={submitting}
- onCreate={handleCreate}
- />
-
- <CalendarEventSheet
- event={detail}
- agents={agents}
- open={detailOpen}
- onOpenChange={setDetailOpen}
- onDelete={handleDelete}
- onUpdate={handleUpdate}
- deleting={deletingId === detail?.id}
- saving={submittingEdit}
- />
- </>
- );
-}
-
-const EMPTY_EVENTS: CalendarEvent[] = [];
diff --git a/src/web/src/app/(app)/w/[slug]/flags/page.tsx b/src/web/src/app/(app)/w/[slug]/flags/page.tsx
deleted file mode 100644
index 5345c83ee..000000000
--- a/src/web/src/app/(app)/w/[slug]/flags/page.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-"use client";
-
-import { useObservedRegion } from "@/lib/observability/regions";
-import { viewEvidence } from "@/lib/observability/data-source";
-
-import { useCallback, useRef } from "react";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { type FlaggedItem } from "@/lib/api";
-import { useUnflagWorkspaceMessage, useWorkspaceFlags } from "@/hooks/workspace/use-inbox";
-import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Button } from "@/components/ui/button";
-import { Flag, X } from "lucide-react";
-import { AgentAvatar } from "@/components/avatar";
-import { relativeTime } from "@/lib/time";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-
-
-function FlagRow({
- item,
- slug,
- onClick,
- onUnflag,
-}: {
- item: FlaggedItem;
- slug: string;
- onClick?: (e: React.MouseEvent) => void;
- onUnflag: () => void;
-}) {
- return (
- <a
- href={`/w/${slug}/agents/${item.agent_id}?conv=${item.conversation_id}`}
- onClick={onClick}
- className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
- >
- <div className="flex items-center gap-2">
- <AgentAvatar name={item.agent_name} avatarUrl={item.agent_avatar_url} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 min-w-0">
- <span className="text-sm text-foreground truncate flex-1 min-w-0">
- {item.message_content}
- </span>
- <Tooltip>
- <TooltipTrigger render={<span className="text-xs text-muted-foreground shrink-0 ml-2" />}>
- {relativeTime(item.flagged_at)}
- </TooltipTrigger>
- <TooltipContent>{new Date(item.flagged_at).toLocaleString()}</TooltipContent>
- </Tooltip>
- </div>
- <div className="flex items-center gap-2 mt-1">
- {item.agent_name && (
- <span className="text-xs font-medium text-muted-foreground">{item.agent_name}</span>
- )}
- {item.conversation_title && (
- <>
- <span className="text-muted-foreground/40">&middot;</span>
- <span className="text-xs text-muted-foreground">{item.conversation_title}</span>
- </>
- )}
- </div>
- </div>
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onUnflag();
- }}
- className="text-muted-foreground"
- />
- }
- >
- <X className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Unflag</TooltipContent>
- </Tooltip>
- </div>
- </a>
- );
-}
-
-function SkeletonRow({ promptWidth }: { promptWidth: string }) {
- return (
- <div className="px-4 py-3 border-b border-border/30">
- <div className="flex items-center gap-2">
- <Skeleton className="size-8 rounded-full shrink-0" />
- <div className="flex-1">
- <Skeleton className="h-3.5 rounded" style={{ width: promptWidth }} />
- <div className="flex items-center gap-2 mt-2">
- <Skeleton className="h-2.5 w-16 rounded" />
- <Skeleton className="h-2.5 w-8 rounded" />
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-export default function FlagsPage() {
- const { slug } = useWorkspace();
- const { openAgentChat } = useAgentChatSheet();
-
- const { items, isPending: loading, hasNextPage: hasMore, isFetchingNextPage: loadingMore, fetchNextPage } = useWorkspaceFlags();
- const remove = useUnflagWorkspaceMessage();
- useObservedRegion("inbox", !loading, viewEvidence(items));
- const scrollRef = useRef<HTMLDivElement>(null);
- const handleScroll = useCallback(() => {
- const el = scrollRef.current;
- if (el && el.scrollHeight - el.scrollTop - el.clientHeight < 200 && !loadingMore && hasMore) void fetchNextPage();
- }, [fetchNextPage, loadingMore, hasMore]);
- const handleUnflag = (item: FlaggedItem) => remove.mutate(item.message_id);
-
- return (
- <div className="flex flex-col h-full">
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2 gap-3">
- <div className="flex items-center gap-3 min-w-0">
- <h1 className="text-sm font-medium">Flagged</h1>
- <p className="text-xs text-muted-foreground hidden sm:block">
- Messages you flagged for later.
- </p>
- </div>
- </div>
-
- <div
- ref={scrollRef}
- onScroll={handleScroll}
- className="flex-1 overflow-y-auto thin-scrollbar"
- >
- {loading ? (
- <>
- <SkeletonRow promptWidth="60%" />
- <SkeletonRow promptWidth="45%" />
- <SkeletonRow promptWidth="70%" />
- <SkeletonRow promptWidth="55%" />
- </>
- ) : items.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full text-muted-foreground gap-3 py-20">
- <Flag className="size-10 opacity-30" />
- <p className="text-sm">No flagged messages</p>
- </div>
- ) : (
- <>
- {items.map((item) => (
- <FlagRow
- key={item.id}
- item={item}
- slug={slug}
- onClick={(e) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
- e.preventDefault();
- openAgentChat(item.agent_id, { conversationId: item.conversation_id, messageId: item.message_id });
- }}
- onUnflag={() => handleUnflag(item)}
- />
- ))}
- {loadingMore && <SkeletonRow promptWidth="50%" />}
- </>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx b/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx
deleted file mode 100644
index cd2903a4b..000000000
--- a/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx
+++ /dev/null
@@ -1,177 +0,0 @@
-"use client";
-import { ObservedStaticContent } from "@/lib/observability/regions";
-
-
-
-import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
-
-const PROVIDERS = [
- {
- id: "gmail",
- name: "Gmail",
- imap: { host: "imap.gmail.com", port: 993 },
- smtp: { host: "smtp.gmail.com", port: 587 },
- steps: [
- "Enable 2-Step Verification in your Google Account (Security > 2-Step Verification).",
- "Go to https://myaccount.google.com/apppasswords and generate an App Password.",
- 'Enter a name (e.g. "Alook") and click Generate.',
- "Copy the 16-character password — use this as both IMAP and SMTP password.",
- "Username is your full Gmail address (e.g. [email protected]).",
- ],
- note: "Gmail no longer supports regular passwords for third-party apps. You must use an App Password.",
- },
- {
- id: "outlook",
- name: "Outlook",
- imap: { host: "outlook.office365.com", port: 993 },
- smtp: { host: "smtp.office365.com", port: 587 },
- steps: [
- "Sign in at https://account.microsoft.com/security.",
- "Go to Security > Advanced Security Options > App Passwords.",
- "Generate an App Password and use it as both IMAP and SMTP password.",
- "Username is your full email address (e.g. [email protected]).",
- ],
- note: "If your organization uses Microsoft 365, your admin may need to enable App Passwords or IMAP access.",
- },
- {
- id: "yahoo",
- name: "Yahoo",
- imap: { host: "imap.mail.yahoo.com", port: 993 },
- smtp: { host: "smtp.mail.yahoo.com", port: 587 },
- steps: [
- "Go to https://login.yahoo.com/account/security.",
- 'Enable "Allow apps that use less secure sign in" or generate an App Password.',
- "Use the App Password as both IMAP and SMTP password.",
- "Username is your full Yahoo email address.",
- ],
- note: null,
- },
- {
- id: "icloud",
- name: "iCloud",
- imap: { host: "imap.mail.me.com", port: 993 },
- smtp: { host: "smtp.mail.me.com", port: 587 },
- steps: [
- "Go to https://appleid.apple.com and sign in.",
- "Navigate to Sign-In and Security > App-Specific Passwords.",
- "Generate an App-Specific Password.",
- "Use the generated password as both IMAP and SMTP password.",
- "Username is your full iCloud email address (e.g. [email protected]).",
- ],
- note: "Two-factor authentication must be enabled on your Apple ID.",
- },
- {
- id: "qq",
- name: "QQ",
- imap: { host: "imap.qq.com", port: 993 },
- smtp: { host: "smtp.qq.com", port: 587 },
- steps: [
- "Log in to QQ Mail (mail.qq.com).",
- "Go to Settings > Account > POP3/IMAP/SMTP/Exchange/CardDAV.",
- "Enable IMAP/SMTP service — you may need to send an SMS to verify.",
- "After verification, QQ Mail will display an authorization code.",
- "Use the authorization code as both IMAP and SMTP password (not your QQ password).",
- "Username is your full QQ email address (e.g. [email protected]).",
- ],
- note: null,
- },
- {
- id: "163",
- name: "163",
- imap: { host: "imap.163.com", port: 993 },
- smtp: { host: "smtp.163.com", port: 465 },
- steps: [
- "Log in to 163 Mail (mail.163.com).",
- "Go to Settings > POP3/SMTP/IMAP.",
- "Enable IMAP/SMTP service and set an authorization password.",
- "Use the authorization password as both IMAP and SMTP password.",
- "Username is your full 163 email address (e.g. [email protected]).",
- ],
- note: "SMTP uses port 465 with SSL instead of the typical 587.",
- },
- {
- id: "feishu",
- name: "Feishu",
- imap: { host: "imap.feishu.cn", port: 993 },
- smtp: { host: "smtp.feishu.cn", port: 465 },
- steps: [
- "Log in to Feishu Admin Console.",
- "Go to Security > Application Password, or ask your admin to enable IMAP/SMTP.",
- "Generate an application-specific password.",
- "Use the application password as both IMAP and SMTP password.",
- "Username is your full Feishu email address.",
- ],
- note: "SMTP uses port 465 with SSL. Your organization admin must enable IMAP access.",
- },
- {
- id: "other",
- name: "Other",
- imap: null,
- smtp: null,
- steps: [
- "Check your email provider's help docs for IMAP/SMTP server settings.",
- "IMAP is typically on port 993 (SSL/TLS), SMTP on port 587 (STARTTLS) or 465 (SSL).",
- "If your provider supports App Passwords, generate one and use it instead of your account password.",
- "Username is usually your full email address.",
- ],
- note: null,
- },
-];
-
-export default function EmailSetupHelpPage() {
- return (
- <><ObservedStaticContent /><>
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2 gap-3">
- <div className="flex items-center gap-3 min-w-0">
- <h1 className="text-sm font-medium">Email Setup Guide</h1>
- <p className="text-xs text-muted-foreground hidden sm:block">
- How to get IMAP/SMTP credentials for your email provider
- </p>
- </div>
- </div>
-
- <div className="flex-1 overflow-y-auto px-4 py-6">
- <div className="mx-auto max-w-2xl">
- <Tabs defaultValue="gmail">
- <TabsList className="flex-wrap h-auto gap-1">
- {PROVIDERS.map((p) => (
- <TabsTrigger key={p.id} value={p.id}>
- {p.name}
- </TabsTrigger>
- ))}
- </TabsList>
-
- {PROVIDERS.map((provider) => (
- <TabsContent key={provider.id} value={provider.id} className="space-y-4 pt-4">
- {provider.imap && provider.smtp && (
- <div className="grid grid-cols-2 gap-3 text-xs">
- <div className="rounded-md border border-border/50 px-3 py-2 space-y-1">
- <span className="font-medium text-muted-foreground">IMAP</span>
- <div className="font-mono">{provider.imap.host}:{provider.imap.port}</div>
- </div>
- <div className="rounded-md border border-border/50 px-3 py-2 space-y-1">
- <span className="font-medium text-muted-foreground">SMTP</span>
- <div className="font-mono">{provider.smtp.host}:{provider.smtp.port}</div>
- </div>
- </div>
- )}
-
- <ol className="list-decimal list-inside space-y-2 text-sm text-muted-foreground">
- {provider.steps.map((step, i) => (
- <li key={i}>{step}</li>
- ))}
- </ol>
-
- {provider.note && (
- <p className="text-xs text-amber-600 dark:text-amber-400 rounded-md bg-amber-500/5 border border-amber-500/10 px-3 py-2">
- {provider.note}
- </p>
- )}
- </TabsContent>
- ))}
- </Tabs>
- </div>
- </div>
- </></>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx
deleted file mode 100644
index 651862596..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-"use client";
-
-import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import type { WorkspaceOverview } from "@/lib/api";
-import type { Agent } from "@alook/shared";
-
-interface EmailSummaryProps {
- overview: WorkspaceOverview;
- agents: Agent[];
-}
-
-export function EmailSummary({ overview, agents }: EmailSummaryProps) {
- const { inbound, outbound, unread, rejected } = overview.email_stats;
-
- const agentMap = new Map(agents.map((a) => [a.id, a.name]));
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>Email Summary</CardTitle>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
- <div>
- <p className="text-xl font-semibold">{inbound}</p>
- <p className="text-xs text-muted-foreground">Received</p>
- </div>
- <div>
- <p className="text-xl font-semibold">{outbound}</p>
- <p className="text-xs text-muted-foreground">Sent</p>
- </div>
- <div>
- <p className={`text-xl font-semibold ${unread > 0 ? "text-primary" : ""}`}>{unread}</p>
- <p className="text-xs text-muted-foreground">Unread</p>
- </div>
- <div>
- <p className={`text-xl font-semibold ${rejected > 0 ? "text-amber-500" : ""}`}>{rejected}</p>
- <p className="text-xs text-muted-foreground">Untrust</p>
- </div>
- </div>
-
- {overview.email_accounts.length > 0 && (
- <div className="space-y-2 pt-2 border-t border-border/50">
- <p className="text-xs font-medium text-muted-foreground">Custom Mailboxes</p>
- {overview.email_accounts.map((acc) => (
- <div key={acc.id} className="flex items-center justify-between gap-2 text-xs">
- <div className="flex items-center gap-2 min-w-0">
- <Tooltip>
- <TooltipTrigger render={
- <span
- className={`size-1.5 shrink-0 rounded-full ${acc.status === "active" ? "bg-emerald-500" : "bg-destructive"}`}
- />
- } />
- <TooltipContent side="top">
- {acc.status === "active" ? "Active" : `Error: ${acc.error_message || "inactive"}`}
- </TooltipContent>
- </Tooltip>
- <span className="truncate">{acc.email_address}</span>
- </div>
- <span className="text-muted-foreground shrink-0">
- {agentMap.get(acc.agent_id) ?? "—"}
- </span>
- </div>
- ))}
- </div>
- )}
- </CardContent>
- </Card>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/quick-stats.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/quick-stats.tsx
deleted file mode 100644
index 4c263bb9d..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/quick-stats.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-"use client";
-
-import { Card, CardContent } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Bot, Mail, Send, Users, Monitor, Zap } from "lucide-react";
-import type { Agent, AgentRuntime } from "@alook/shared";
-import type { WorkspaceOverview } from "@/lib/api";
-
-interface QuickStatsProps {
- agents: Agent[];
- runtimes: AgentRuntime[];
- activeTaskCounts: Record<string, number>;
- overview: WorkspaceOverview;
-}
-
-function StatCard({
- icon: Icon,
- label,
- value,
- sub,
-}: {
- icon: React.ElementType;
- label: string;
- value: number | string;
- sub?: string;
-}) {
- return (
- <Card size="sm">
- <CardContent className="flex items-center gap-3">
- <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
- <Icon className="size-4" />
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex items-center justify-between gap-1">
- <p className="text-2xl font-semibold leading-none tracking-tight">{value}</p>
- {sub && <Badge variant="secondary" className="text-[10px] px-2 h-4 font-normal">{sub}</Badge>}
- </div>
- <p className="mt-1 text-xs text-muted-foreground truncate">{label}</p>
- </div>
- </CardContent>
- </Card>
- );
-}
-
-export function QuickStatsRow({ agents, runtimes, activeTaskCounts, overview }: QuickStatsProps) {
- const machineStatus = new Map<string, boolean>();
- for (const r of runtimes) {
- const key = r.daemon_id ?? r.id;
- machineStatus.set(key, machineStatus.get(key) || r.status === "online");
- }
- const totalMachines = machineStatus.size;
- const onlineMachines = [...machineStatus.values()].filter(Boolean).length;
- const totalActiveTasks = Object.values(activeTaskCounts).reduce((a, b) => a + b, 0);
- const onlineAgents = agents.filter((a) => {
- const rt = runtimes.find((r) => r.id === a.runtime_id);
- return rt?.status === "online";
- }).length;
-
- return (
- <div className="grid gap-3 grid-cols-2 sm:grid-cols-6">
- <StatCard
- icon={Monitor}
- label="Machines"
- value={`${onlineMachines}/${totalMachines}`}
- sub="online"
- />
- <StatCard
- icon={Bot}
- label="Agents"
- value={agents.length}
- sub={`${onlineAgents} online`}
- />
- <StatCard
- icon={Users}
- label="Members"
- value={overview.members.length}
- sub={overview.pending_invites > 0 ? `${overview.pending_invites} pending` : undefined}
- />
- <StatCard
- icon={Zap}
- label="Active Tasks"
- value={totalActiveTasks}
- sub={overview.task_stats.queued > 0 ? `${overview.task_stats.queued} queued` : undefined}
- />
- <StatCard
- icon={Send}
- label="Emails Sent"
- value={overview.email_stats.outbound}
- sub={`${overview.email_stats.unread} unread`}
- />
- <StatCard
- icon={Mail}
- label="Custom Emails"
- value={overview.email_accounts.length}
- />
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/runtime-health.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/runtime-health.tsx
deleted file mode 100644
index caec5c424..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/runtime-health.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { ArrowUpRight } from "lucide-react";
-import type { Agent, AgentRuntime } from "@alook/shared";
-
-interface RuntimeHealthProps {
- runtimes: AgentRuntime[];
- agents: Agent[];
-}
-
-function timeAgo(dateStr: string | null): string {
- if (!dateStr) return "never";
- const diff = Date.now() - new Date(dateStr).getTime();
- const secs = Math.floor(diff / 1000);
- if (secs < 60) return `${secs}s ago`;
- const mins = Math.floor(secs / 60);
- if (mins < 60) return `${mins}m ago`;
- const hours = Math.floor(mins / 60);
- if (hours < 24) return `${hours}h ago`;
- return `${Math.floor(hours / 24)}d ago`;
-}
-
-export function RuntimeHealth({ runtimes, agents }: RuntimeHealthProps) {
- const router = useRouter();
- const { slug } = useWorkspace();
- const machineMap = new Map<string, { runtimes: AgentRuntime[]; deviceInfo: string }>();
- for (const rt of runtimes) {
- const key = rt.daemon_id ?? rt.id;
- if (!machineMap.has(key)) {
- machineMap.set(key, { runtimes: [], deviceInfo: rt.device_info ?? "" });
- }
- machineMap.get(key)!.runtimes.push(rt);
- }
-
- const machines = [...machineMap.entries()];
-
- if (machines.length === 0) {
- return (
- <Card>
- <CardHeader>
- <CardTitle>Machines</CardTitle>
- <CardAction>
- <button
- type="button"
- onClick={() => router.push(`/w/${slug}/runtimes`)}
- className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
- >
- <ArrowUpRight className="size-4" />
- </button>
- </CardAction>
- </CardHeader>
- <CardContent>
- <p className="text-sm text-muted-foreground">No machines connected.</p>
- </CardContent>
- </Card>
- );
- }
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>Machines</CardTitle>
- </CardHeader>
- <CardContent className="space-y-3">
- {machines.map(([daemonId, machine]) => {
- const isOnline = machine.runtimes.some((r) => r.status === "online");
- const lastSeen = machine.runtimes
- .map((r) => r.last_seen_at)
- .filter(Boolean)
- .sort()
- .reverse()[0];
- const boundAgents = agents.filter((a) =>
- machine.runtimes.some((r) => r.id === a.runtime_id)
- );
- const hasPendingUpdate = machine.runtimes.some(
- (r) => r.pending_update_version
- );
- const updateVersion = machine.runtimes.find((r) => r.pending_update_version)?.pending_update_version;
-
- return (
- <div key={daemonId} className="flex items-start gap-3 text-xs">
- <Tooltip>
- <TooltipTrigger render={
- <span
- className={`mt-1 size-2 shrink-0 rounded-full ${isOnline ? "bg-emerald-500" : "bg-muted-foreground/30"}`}
- />
- } />
- <TooltipContent side="top">{isOnline ? "Online" : "Offline"}</TooltipContent>
- </Tooltip>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="font-medium truncate">
- {machine.deviceInfo || daemonId.slice(0, 12)}
- </span>
- {hasPendingUpdate && (
- <Tooltip>
- <TooltipTrigger render={
- <span>
- <Badge variant="outline" className="text-[10px] px-2 py-0 text-amber-500 border-amber-500/30">
- update
- </Badge>
- </span>
- } />
- <TooltipContent side="top">Pending update to v{updateVersion}</TooltipContent>
- </Tooltip>
- )}
- </div>
- <div className="text-muted-foreground mt-1">
- {boundAgents.length > 0
- ? boundAgents.map((a) => a.name).join(", ")
- : "No agents"}
- {" · "}
- {timeAgo(lastSeen ?? null)}
- </div>
- </div>
- </div>
- );
- })}
- </CardContent>
- </Card>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/task-health.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/task-health.tsx
deleted file mode 100644
index 9e78227c3..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/task-health.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-"use client";
-
-import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
-import type { WorkspaceOverview } from "@/lib/api";
-
-interface TaskHealthProps {
- overview: WorkspaceOverview;
-}
-
-export function TaskHealth({ overview }: TaskHealthProps) {
- const { completed, failed, cancelled, queued, stale } = overview.task_stats;
- const total = completed + failed;
- const failRate = total > 0 ? ((failed / total) * 100).toFixed(1) : "0";
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>Task Health (Today)</CardTitle>
- </CardHeader>
- <CardContent>
- <div className="grid grid-cols-2 gap-3">
- <Stat label="Completed" value={completed} />
- <Stat label="Failed" value={failed} className={failed > 0 ? "text-destructive" : undefined} />
- <Stat label="Cancelled" value={cancelled} />
- <Stat label="Failure Rate" value={`${failRate}%`} className={Number(failRate) > 10 ? "text-destructive" : undefined} />
- <Stat label="Queue Backlog" value={queued} className={queued > 10 ? "text-amber-500" : undefined} />
- <Stat label="Stale Tasks" value={stale} className={stale > 0 ? "text-destructive" : undefined} />
- </div>
- </CardContent>
- </Card>
- );
-}
-
-function Stat({ label, value, className }: { label: string; value: string | number; className?: string }) {
- return (
- <div>
- <p className={`text-xl font-semibold ${className ?? ""}`}>{value}</p>
- <p className="text-xs text-muted-foreground">{label}</p>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/team-access.test.ts b/src/web/src/app/(app)/w/[slug]/home/_components/team-access.test.ts
deleted file mode 100644
index e0aff3fb2..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/team-access.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { createElement } from "react"
-import { renderToStaticMarkup } from "react-dom/server"
-import { describe, expect, it, vi } from "vitest"
-import type { WorkspaceOverview } from "@/lib/api"
-import { serializeBeamSeed } from "@/lib/avatar/seed-url"
-import { TeamAccess } from "./team-access"
-
-vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }))
-vi.mock("@/contexts/workspace-context", () => ({ useWorkspace: () => ({ slug: "demo" }) }))
-
-function overview(): WorkspaceOverview {
- return {
- email_stats: { inbound: 0, outbound: 0, unread: 0, rejected: 0 },
- task_stats: { completed: 0, failed: 0, cancelled: 0, queued: 0, stale: 0 },
- recent_tasks: [],
- conversation_counts: {},
- pending_invites: 0,
- calendar_events: [],
- members: [
- {
- id: "membership_1",
- user_id: "user_beam",
- role: "owner",
- name: "Beam User",
- email: "[email protected]",
- image: serializeBeamSeed("stored-face"),
- created_at: "2026-08-14T00:00:00Z",
- },
- {
- id: "membership_2",
- user_id: "user_photo",
- role: "member",
- name: "Photo User",
- email: "[email protected]",
- image: "https://cdn.example.com/photo.png",
- created_at: "2026-08-14T00:00:00Z",
- },
- {
- id: "membership_3",
- user_id: "user_generated",
- role: "member",
- name: "Generated User",
- email: "[email protected]",
- image: null,
- created_at: "2026-08-14T00:00:00Z",
- },
- ],
- }
-}
-
-describe("TeamAccess avatars", () => {
- it("renders photo, stored beam, and stable-id avatars at the existing row size", () => {
- const html = renderToStaticMarkup(createElement(TeamAccess, { overview: overview() }))
-
- expect(html).toContain('data-testid="team-access-avatar-user_beam"')
- expect(html).toContain('data-testid="team-access-avatar-user_photo"')
- expect(html).toContain('data-testid="team-access-avatar-user_generated"')
- expect(html.match(/data-avatar-kind="beam"/g)).toHaveLength(2)
- expect(html).toContain('data-avatar-kind="photo"')
- expect(html).not.toContain('src="avatar:beam:stored-face"')
- expect(html).toContain("width:28px;height:28px")
- })
-})
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx
deleted file mode 100644
index dc9f1b34e..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { ArrowUpRight } from "lucide-react";
-import type { WorkspaceOverview } from "@/lib/api";
-import { displayName } from "@/lib/community/display-name";
-import { ProfileAvatar } from "@/components/avatar";
-
-interface TeamAccessProps {
- overview: WorkspaceOverview;
-}
-
-export function TeamAccess({ overview }: TeamAccessProps) {
- const router = useRouter();
- const { slug } = useWorkspace();
- const { members, pending_invites } = overview;
-
- return (
- <Card>
- <CardHeader>
- <CardAction>
- <button
- type="button"
- onClick={() => router.push(`/w/${slug}/settings`)}
- className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
- >
- <ArrowUpRight className="size-4" />
- </button>
- </CardAction>
- <CardTitle>
- Team
- {pending_invites > 0 && (
- <span className="ml-2 text-xs text-muted-foreground font-normal">
- ({pending_invites} pending invite{pending_invites > 1 ? "s" : ""})
- </span>
- )}
- </CardTitle>
- </CardHeader>
- <CardContent className="p-0">
- <div className="divide-y divide-border/50">
- {[...members].sort((a, b) => (a.role === "owner" ? -1 : b.role === "owner" ? 1 : 0)).map((m) => (
- <div key={m.id} className="flex items-center gap-3 px-4 py-2">
- <ProfileAvatar
- label={displayName(m)}
- seed={m.user_id}
- src={m.image}
- size={28}
- data-testid={`team-access-avatar-${m.user_id}`}
- />
- <div className="flex-1 min-w-0">
- <span className="text-sm font-medium truncate block">
- {displayName(m)}
- </span>
- {m.name && (
- <span className="text-xs text-muted-foreground truncate block">
- {m.email}
- </span>
- )}
- </div>
- <Badge
- variant={m.role === "owner" ? "default" : "secondary"}
- className="text-[10px] px-2 py-0 shrink-0"
- >
- {m.role}
- </Badge>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsx
deleted file mode 100644
index 04de0e322..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx
+++ /dev/null
@@ -1,781 +0,0 @@
-"use client";
-
-import { useObservedRegion } from "@/lib/observability/regions"
-import { viewEvidence, mergeEvidence } from "@/lib/observability/data-source"
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useEffect, useMemo, useRef } from "react";
-import { useMutation, useQuery } from "@tanstack/react-query";
-import { useRouter } from "next/navigation";
-import {
- ReactFlow,
- Background,
- BackgroundVariant,
- ReactFlowProvider,
- useReactFlow,
- type Node,
- type Edge,
- type OnConnect,
- type Connection,
- type NodeChange,
- type EdgeChange,
- applyNodeChanges,
- applyEdgeChanges,
-} from "@xyflow/react";
-import "@xyflow/react/dist/style.css";
-import {
- ZoomIn,
- ZoomOut,
- Maximize2,
- Loader2,
- Plus,
- LayoutGrid,
- Circle,
- GitBranch,
- ArrowRight,
- Check,
-} from "lucide-react";
-import type { Agent, AgentLink } from "@alook/shared";
-import { cn } from "@/lib/utils";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspace, useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { useIsMobile } from "@/hooks/use-mobile";
-import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
-import { AgentPreviewCard } from "@/components/agent-preview-card";
-import { AnimatedAvatar } from "@/components/avatar";
-import {
- createAgentLink,
- updateAgentLink,
- deleteAgentLink,
- createMachineToken,
-} from "@/lib/api";
-import { toast } from "sonner";
-import { cliCmd } from "@/lib/utils";
-import { ApiError, isAbortError } from "@/lib/errors";
-import { trackAgentLinkCreated, trackCanvasLayoutChanged } from "@/lib/analytics";
-import { AgentNode, type AgentNodeData } from "@/components/canvas/agent-node";
-import { LinkEdge } from "@/components/canvas/link-edge";
-import { LinkSidecar } from "@/components/canvas/link-sidecar";
-import { ActiveTasksFloat } from "@/components/canvas/active-tasks-float";
-import { UpcomingEventsFloat } from "@/components/canvas/upcoming-events-float";
-import { getAutoLayout, type LayoutType } from "@/components/canvas/auto-layout";
-
-const nodeTypes = { agent: AgentNode };
-const edgeTypes = { link: LinkEdge };
-
-function storageKey(workspaceId: string) {
- return `alook-canvas-positions-${workspaceId}`;
-}
-
-function layoutStorageKey(workspaceId: string) {
- return `alook-canvas-layout-${workspaceId}`;
-}
-
-function loadLayoutType(workspaceId: string): LayoutType {
- try {
- const raw = localStorage.getItem(layoutStorageKey(workspaceId));
- if (raw === "star" || raw === "tree" || raw === "flow") return raw;
- } catch {}
- return "tree";
-}
-
-function saveLayoutType(workspaceId: string, layout: LayoutType) {
- try {
- localStorage.setItem(layoutStorageKey(workspaceId), layout);
- } catch {}
-}
-
-function loadPositions(workspaceId: string): Record<string, { x: number; y: number }> {
- try {
- const raw = localStorage.getItem(storageKey(workspaceId));
- return raw ? JSON.parse(raw) : {};
- } catch {
- return {};
- }
-}
-
-function savePositions(workspaceId: string, nodes: Node[]) {
- const positions: Record<string, { x: number; y: number }> = {};
- for (const n of nodes) {
- positions[n.id] = n.position;
- }
- try {
- localStorage.setItem(storageKey(workspaceId), JSON.stringify(positions));
- } catch { }
-}
-
-function AgentCanvas({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }) {
- const router = useRouter();
- const { agents, runtimes, loading, activeTaskCounts, agentLinks, pendingNewAgent, clearPendingNewAgent } = useAgentContext();
- const owner = useWorkspaceOwner();
- useObservedRegion("agents", !loading, mergeEvidence([viewEvidence(agents), viewEvidence(agentLinks), viewEvidence(runtimes)]));
- const { slug, workspaceId } = owner;
- const source = useWorkspaceViewSource(owner, "canvas", true);
- const { zoomIn, zoomOut, fitView } = useReactFlow();
- const canvasRef = useRef<HTMLDivElement>(null);
- const canvasScope = `${owner.application.userId}:${workspaceId}`;
- const layoutTimers = useRef(new Set<ReturnType<typeof setTimeout>>());
- const laterLayout = useCallback((callback: () => void, delay: number) => {
- const assertView = source.assertActive;
- const timer = setTimeout(() => {
- layoutTimers.current.delete(timer);
- try { assertView(); } catch { return; }
- callback();
- }, delay);
- layoutTimers.current.add(timer);
- }, [source.assertActive]);
- useEffect(() => {
- const timers = layoutTimers.current;
- return () => { for (const timer of timers) clearTimeout(timer); timers.clear(); };
- }, []);
-
- const geometry = useCreateAtom<Node[]>([]);
- const [nodeGeometry, setGeometry] = useAtom(geometry);
- const nodes = useMemo<Node[]>(() => nodeGeometry.flatMap((node, index) => {
- const agent = agents.find((row) => row.id === node.id);
- return agent ? [{ ...node, data: { agent, runtimes, activeTaskCount: activeTaskCounts[node.id] ?? 0, slug, index } satisfies AgentNodeData }] : [];
- }), [nodeGeometry, agents, runtimes, activeTaskCounts, slug]);
- const setNodes = useCallback((update: Node[] | ((nodes: Node[]) => Node[])) => setGeometry((current) => {
- const next = typeof update === "function" ? update(current) : update;
- return next.map(({ data: _data, ...node }) => ({ ...node, data: {} }));
- }), [setGeometry]);
- const links = agentLinks;
- const linksLoaded = !loading;
- const [sidecarLinkId, setSidecarLinkId] = useAtom(useCreateAtom<string | null>(null));
- const sidecarLink = links.find((link) => link.id === sidecarLinkId) ?? null;
- const [sidecarOpen, setSidecarOpen] = useAtom(useCreateAtom(false));
- const showHint = linksLoaded && links.length === 0;
- const [layoutType, setLayoutType] = useAtom(useCreateAtom<LayoutType>("tree"));
- const initialLayoutDone = useRef(false);
- const [handles, setHandles] = useAtom(useCreateAtom<Record<string, { sourceHandle: string; targetHandle: string }>>({}));
- const [edgeView, setEdgeView] = useAtom(useCreateAtom<Record<string, { selected?: boolean; hidden?: boolean }>>({}));
- useEffect(() => { setLayoutType(loadLayoutType(`${owner.application.userId}:${workspaceId}`)); }, [owner, workspaceId, setLayoutType]);
-
- const edges = useMemo<Edge[]>(() => {
- if (!linksLoaded) return [];
-
- const nodeMap = new Map(nodes.map((n) => [n.id, n.position]));
-
- const newEdges: Edge[] = links.map((link) => {
- const stored = handles[link.id];
- let sourceHandle = stored?.sourceHandle;
- let targetHandle = stored?.targetHandle;
-
- if (!sourceHandle || !targetHandle) {
- const sp = nodeMap.get(link.source_agent_id);
- const tp = nodeMap.get(link.target_agent_id);
- if (sp && tp) {
- const dx = tp.x - sp.x;
- const dy = tp.y - sp.y;
- if (Math.abs(dx) >= Math.abs(dy)) {
- sourceHandle = dx >= 0 ? "right" : "left";
- targetHandle = dx >= 0 ? "target-left" : "target-right";
- } else {
- sourceHandle = dy >= 0 ? "bottom" : "top";
- targetHandle = dy >= 0 ? "target-top" : "target-bottom";
- }
- } else {
- sourceHandle = "right";
- targetHandle = "target-left";
- }
- }
-
- return {
- id: link.id,
- source: link.source_agent_id,
- target: link.target_agent_id,
- sourceHandle,
- targetHandle,
- type: "link",
- data: {
- instruction: link.instruction,
- onEdgeClick: (edgeId: string) => {
- const l = links.find((lk) => lk.id === edgeId);
- if (l) {
- setSidecarLinkId(l.id);
- setSidecarOpen(true);
- }
- },
- },
- selected: sidecarLink?.id === link.id && sidecarOpen,
- ...edgeView[link.id],
- };
- });
- return newEdges;
- }, [links, linksLoaded, sidecarLink, sidecarOpen, nodes, handles, edgeView, setSidecarLinkId, setSidecarOpen]);
-
- // Build nodes from agents
- useEffect(() => {
- if (loading || agents.length === 0) return;
-
- const saved = { ...loadPositions(canvasScope), ...Object.fromEntries(geometry.get().map((node) => [node.id, node.position])) };
- // Filter out stale positions
- const agentIds = new Set(agents.map((a) => a.id));
- const validPositions: Record<string, { x: number; y: number }> = {};
- for (const [id, pos] of Object.entries(saved)) {
- if (agentIds.has(id)) validPositions[id] = pos;
- }
-
- let newNodes: Node[] = agents.map((agent, index) => ({
- id: agent.id,
- type: "agent",
- position: validPositions[agent.id] ?? { x: 0, y: 0 },
- data: {
- agent,
- runtimes,
- activeTaskCount: activeTaskCounts[agent.id] ?? 0,
- slug,
- index,
- } satisfies AgentNodeData,
- }));
-
- const hasAnyPosition = Object.keys(validPositions).length > 0;
- const newAgentIds = agents.filter((a) => !validPositions[a.id]).map((a) => a.id);
-
- // Case 1: No saved positions and links not loaded yet — wait for links before setting nodes
- if (!hasAnyPosition && !linksLoaded) return;
-
- // Case 2: Some saved positions but new agents need layout — only show positioned nodes until links load
- if (hasAnyPosition && newAgentIds.length > 0 && !linksLoaded) {
- newNodes = newNodes.filter((n) => validPositions[n.id]);
- }
-
- if (!hasAnyPosition) {
- // First visit — auto-layout all
- if (linksLoaded) {
- const currentEdges: Edge[] = links.map((link) => ({
- id: link.id,
- source: link.source_agent_id,
- target: link.target_agent_id,
- }));
- newNodes = getAutoLayout(newNodes, currentEdges, layoutType);
- if (!initialLayoutDone.current) {
- initialLayoutDone.current = true;
- laterLayout(() => fitView({ padding: 0.4, duration: 400 }), 50);
- }
- if (pendingNewAgent) clearPendingNewAgent();
- }
- } else if (newAgentIds.length > 0 && linksLoaded) {
- // Existing positions + some new agents — position relative to parent
- newNodes = newNodes.map((n) => {
- if (validPositions[n.id]) return n;
-
- // Find parent: use pendingNewAgent hint or scan links
- let parentId: string | undefined;
- if (pendingNewAgent && n.id === pendingNewAgent.agentId) {
- parentId = pendingNewAgent.parentAgentId;
- }
- if (!parentId) {
- const linkedEdge = links.find(
- (l) => (l.source_agent_id === n.id && validPositions[l.target_agent_id]) ||
- (l.target_agent_id === n.id && validPositions[l.source_agent_id])
- );
- if (linkedEdge) {
- parentId = linkedEdge.source_agent_id === n.id
- ? linkedEdge.target_agent_id
- : linkedEdge.source_agent_id;
- }
- }
-
- const siblingIndex = newAgentIds.indexOf(n.id);
- if (parentId && validPositions[parentId]) {
- const pp = validPositions[parentId];
- let pos: { x: number; y: number };
- switch (layoutType) {
- case "tree":
- pos = { x: pp.x + siblingIndex * 300, y: pp.y + 200 };
- break;
- case "flow":
- pos = { x: pp.x + 350, y: pp.y + siblingIndex * 150 };
- break;
- default: // star
- pos = { x: pp.x + 300, y: pp.y + 100 + siblingIndex * 150 };
- break;
- }
- return { ...n, position: pos };
- }
-
- // Fallback: centroid of all existing nodes + offset
- const positions = Object.values(validPositions);
- const cx = positions.reduce((s, p) => s + p.x, 0) / positions.length;
- const cy = positions.reduce((s, p) => s + p.y, 0) / positions.length;
- return { ...n, position: { x: cx + 350 + siblingIndex * 300, y: cy } };
- });
-
- savePositions(canvasScope, newNodes);
- laterLayout(() => fitView({ padding: 0.4, duration: 400, includeHiddenNodes: false }), 50);
- if (pendingNewAgent) clearPendingNewAgent();
- }
-
- setNodes(newNodes);
- }, [agents, runtimes, activeTaskCounts, slug, loading, canvasScope, linksLoaded, links, fitView, layoutType, pendingNewAgent, clearPendingNewAgent, geometry, setNodes, laterLayout]);
-
- const onNodesChange = useCallback((changes: NodeChange[]) => {
- setNodes((nds) => applyNodeChanges(changes, nds));
- }, [setNodes]);
-
- const onEdgesChange = useCallback((changes: EdgeChange[]) => {
- const updated = applyEdgeChanges(changes, edges);
- setEdgeView(Object.fromEntries(updated.map((edge) => [edge.id, { selected: edge.selected, hidden: edge.hidden }])));
- }, [edges, setEdgeView]);
-
- const onNodeDragStop = useCallback(() => {
- setNodes((nds) => {
- savePositions(canvasScope, nds);
- return nds;
- });
- }, [canvasScope, setNodes]);
-
- const linkKey = owner.key("agent-links");
- const linkCommand = useMutation({ meta: { observabilityAction: "agent.link.command" }, mutationKey: owner.key("agent-link-command"), scope: { id: JSON.stringify(owner.key("agent-link-command")) },
- mutationFn: async ({ action, token }: { action: { kind: "create"; source: string; target: string } | { kind: "update"; id: string; instruction: string } | { kind: "delete"; id: string }; token: ReturnType<typeof captureWorkspaceOwner> }) => {
- const assert = () => assertWorkspaceOwner(token), qc = owner.queryClient;
- assert();
- await qc.cancelQueries({ queryKey: linkKey, exact: true });
- assert();
- const resource = qc.getQueryCache().find({ queryKey: linkKey, exact: true }), baseline = resource?.state.data as AgentLink[] | undefined;
- const original = () => resource && qc.getQueryCache().find({ queryKey: linkKey, exact: true }) === resource;
- const options = workspaceRequestOptions(token);
- let id: string;
- try {
- if (action.kind === "create") {
- const confirmed = await createAgentLink({ source_agent_id: action.source, target_agent_id: action.target }, workspaceId, options);
- assert();
- id = confirmed.id;
- if (original() && resource!.state.data === baseline) qc.setQueryData<AgentLink[]>(linkKey, (rows) => [...(rows ?? []).filter((row) => row.id !== confirmed.id), confirmed]);
- } else if (action.kind === "update") {
- const confirmed = await updateAgentLink(action.id, { instruction: action.instruction }, workspaceId, options);
- assert();
- id = action.id;
- const old = baseline?.find((row) => row.id === action.id);
- if (original()) qc.setQueryData<AgentLink[]>(linkKey, (rows) => rows?.map((row) => row.id === action.id && row.instruction === old?.instruction ? { ...row, instruction: confirmed.instruction } : row));
- } else {
- await deleteAgentLink(action.id, workspaceId, options);
- assert();
- id = action.id;
- if (original() && resource!.state.data === baseline) qc.setQueryData<AgentLink[]>(linkKey, (rows) => rows?.filter((row) => row.id !== action.id));
- }
- await qc.invalidateQueries({ queryKey: linkKey, exact: true });
- assert();
- return { id };
- } catch (error) { assert(); throw error; }
- },
- });
- const onConnect: OnConnect = useCallback(async (connection: Connection) => {
- if (!connection.source || !connection.target) return;
- const assertView = source.assertActive;
- try {
- const created = await linkCommand.mutateAsync({ action: { kind: "create", source: connection.source, target: connection.target }, token: captureWorkspaceOwner(owner) });
- assertView();
- trackAgentLinkCreated({ source_agent: connection.source, target_agent: connection.target });
- if (connection.sourceHandle || connection.targetHandle) setHandles((current) => ({ ...current, [created.id]: { sourceHandle: connection.sourceHandle ?? "right", targetHandle: connection.targetHandle ?? "target-left" } }));
- } catch (error) {
- try { assertView(); } catch { return; }
- if (isAbortError(error)) return;
- if (error instanceof ApiError && error.status === 409) toast.error("Link already exists");
- else if (error instanceof ApiError && error.status === 400) toast.error("Can't link an agent to itself");
- else toast.error("Failed to create link");
- }
- }, [source.assertActive, linkCommand, owner, setHandles]);
- const handleSidecarSave = useCallback(async (id: string, instruction: string) => {
- const assertView = source.assertActive;
- try {
- await linkCommand.mutateAsync({ action: { kind: "update", id, instruction }, token: captureWorkspaceOwner(owner) });
- assertView();
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to update link");
- }
- }, [source.assertActive, linkCommand, owner]);
- const handleSidecarDelete = useCallback(async (id: string) => {
- const assertView = source.assertActive;
- try {
- await linkCommand.mutateAsync({ action: { kind: "delete", id }, token: captureWorkspaceOwner(owner) });
- assertView();
- setSidecarOpen(false);
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to delete link");
- }
- }, [source.assertActive, linkCommand, owner, setSidecarOpen]);
-
-
- const handleLayoutChange = useCallback((newLayout: LayoutType) => {
- trackCanvasLayoutChanged({ layout_type: newLayout });
- setLayoutType(newLayout);
- saveLayoutType(canvasScope, newLayout);
- try {
- localStorage.removeItem(storageKey(canvasScope));
- } catch {}
- const currentEdges: Edge[] = links.map((link) => ({
- id: link.id,
- source: link.source_agent_id,
- target: link.target_agent_id,
- }));
- setNodes((prev) => {
- const laid = getAutoLayout(prev, currentEdges, newLayout);
- const animated = laid.map((n) => ({
- ...n,
- style: { ...n.style, transition: "transform 300ms ease-out" },
- }));
- laterLayout(() => {
- setNodes((nds) => {
- const final = nds.map((n) => ({
- ...n,
- style: { ...n.style, transition: undefined },
- }));
- savePositions(canvasScope, final);
- return final;
- });
- fitView({ padding: 0.4, duration: 400 });
- }, 350);
- return animated;
- });
- }, [links, canvasScope, fitView, setNodes, setLayoutType, laterLayout]);
-
- const onNodeClick = useCallback(
- (_event: React.MouseEvent, node: Node) => {
- const nodeData = node.data as unknown as AgentNodeData;
- setSidecarOpen(false);
- if (onAgentClick) {
- onAgentClick(nodeData.agent);
- } else {
- router.push(`/w/${slug}/agents/${nodeData.agent.id}`);
- }
- },
- [setSidecarOpen, onAgentClick, router, slug],
- );
-
- const connectionLineStyle = useMemo(
- () => ({
- stroke: "var(--color-primary)",
- strokeWidth: 1.5,
- strokeDasharray: "6 4",
- opacity: 0.5,
- }),
- [],
- );
-
- return (
- <div ref={canvasRef} className="flex-1 relative">
- <ReactFlow
- nodes={nodes}
- edges={edges}
- nodeTypes={nodeTypes}
- edgeTypes={edgeTypes}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- onConnect={onConnect}
- onNodeClick={onNodeClick}
- onNodeDragStop={onNodeDragStop}
- connectionLineStyle={connectionLineStyle}
- fitView
- fitViewOptions={{ padding: 0.4, maxZoom: 1 }}
- minZoom={0.25}
- maxZoom={2.5}
- zoomOnScroll
- panOnScroll={false}
- proOptions={{ hideAttribution: true }}
- >
- <Background variant={BackgroundVariant.Dots} gap={24} size={1.5} color="var(--color-border)" />
- </ReactFlow>
-
- {/* Custom floating toolbar */}
- <div
- className="absolute bottom-4 left-4 z-40 bg-background/80 backdrop-blur-sm rounded-lg ring-1 ring-foreground/5 p-1 flex gap-1 animate-[fade-up_300ms_ease-out_both]"
- style={{ animationDelay: "200ms" }}
- >
- <button
- type="button"
- className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- onClick={() => zoomIn()}
- >
- <ZoomIn className="size-4" />
- </button>
- <button
- type="button"
- className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- onClick={() => zoomOut()}
- >
- <ZoomOut className="size-4" />
- </button>
- <button
- type="button"
- className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- onClick={() => fitView({ padding: 0.4, duration: 400 })}
- >
- <Maximize2 className="size-4" />
- </button>
-
- <div className="w-px h-5 bg-foreground/10 mx-1 self-center" />
-
- <Popover>
- <Tooltip>
- <TooltipTrigger
- render={
- <PopoverTrigger
- render={
- <button
- type="button"
- className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- />
- }
- >
- <LayoutGrid className="size-3.5" />
- </PopoverTrigger>
- }
- />
- <TooltipContent side="top">Layout</TooltipContent>
- </Tooltip>
- <PopoverContent className="w-36 p-1" align="start" side="top" sideOffset={8}>
- {([
- { type: "star" as const, label: "Star", icon: Circle },
- { type: "tree" as const, label: "Tree", icon: GitBranch },
- { type: "flow" as const, label: "Flow", icon: ArrowRight },
- ]).map(({ type, label, icon: Icon }) => (
- <button
- key={type}
- type="button"
- className={cn(
- "w-full flex items-center gap-2 px-2 py-2 rounded-md text-sm transition-colors",
- layoutType === type
- ? "bg-accent text-foreground"
- : "text-muted-foreground hover:text-foreground hover:bg-accent/50",
- )}
- onClick={() => handleLayoutChange(type)}
- >
- <Icon className="size-3.5" />
- <span className="flex-1 text-left">{label}</span>
- {layoutType === type && <Check className="size-3.5" />}
- </button>
- ))}
- </PopoverContent>
- </Popover>
- </div>
-
- {/* No-links hint */}
- {showHint && (
- <div className="absolute bottom-14 left-4 z-40 text-xs text-muted-foreground bg-background/80 backdrop-blur-sm rounded-md px-3 py-2 ring-1 ring-foreground/5">
- Drag between agent handles to create relationships.
- </div>
- )}
-
- <LinkSidecar
- open={sidecarOpen}
- onOpenChange={setSidecarOpen}
- link={sidecarLink}
- agents={agents}
- onSave={handleSidecarSave}
- onDelete={handleSidecarDelete}
- />
-
- <div className="absolute bottom-4 right-4 z-10 flex flex-wrap justify-end items-end gap-2">
- <UpcomingEventsFloat />
- <ActiveTasksFloat />
- </div>
-
- {/* Create agent button */}
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- className="absolute top-4 right-4 z-40 size-8 rounded-lg bg-background/80 backdrop-blur-sm ring-1 ring-foreground/5 flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors animate-[fade-up_300ms_ease-out_both]"
- style={{ animationDelay: "200ms" }}
- onClick={() => router.push(`/w/${slug}/agents/new`)}
- />
- }
- >
- <Plus className="size-4" />
- </TooltipTrigger>
- <TooltipContent>Create new agent</TooltipContent>
- </Tooltip>
- </div>
- );
-}
-
-function MobileAgentList({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }) {
- const router = useRouter();
- const { agents, runtimes, loading, activeTaskCounts } = useAgentContext();
- const { slug } = useWorkspace();
-
- if (loading) {
- return (
- <div className="flex flex-col gap-1 p-4">
- {[...Array(4)].map((_, i) => (
- <div key={i} className="animate-pulse rounded-xl bg-muted h-15" />
- ))}
- </div>
- );
- }
-
- const handleClick = (agent: Agent) => {
- if (onAgentClick) {
- onAgentClick(agent);
- } else {
- router.push(`/w/${slug}/agents/${agent.id}`);
- }
- };
-
- return (
- <div className="relative flex-1 flex flex-col min-h-0">
- <div className="flex flex-col gap-1 p-4 overflow-y-auto thin-scrollbar flex-1 min-h-0">
- {agents.map((agent) => {
- const rt = runtimes.find((r) => r.id === agent.runtime_id);
- const isOnline = rt?.status === "online";
- return (
- <div
- key={agent.id}
- role="button"
- tabIndex={0}
- className="flex items-center gap-3 w-full rounded-xl px-3 py-2 hover:bg-accent/50 active:bg-accent/70 transition-colors cursor-pointer text-left"
- onClick={() => handleClick(agent)}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- handleClick(agent);
- }
- }}
- >
- <AnimatedAvatar seed={agent.id} avatarUrl={agent.avatar_url} size={36} className="shrink-0 rounded-xl" isHovered={false} isWorking={isOnline && (activeTaskCounts[agent.id] ?? 0) > 0} />
- <div className="min-w-0 flex-1">
- <AgentPreviewCard
- agent={agent}
- isOnline={isOnline}
- activeTaskCount={activeTaskCounts[agent.id] ?? 0}
- />
- </div>
- </div>
- );
- })}
- </div>
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- className="absolute top-4 right-4 size-8 rounded-lg bg-background/80 backdrop-blur-sm ring-1 ring-foreground/5 flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- onClick={() => router.push(`/w/${slug}/agents/new`)}
- />
- }
- >
- <Plus className="size-4" />
- </TooltipTrigger>
- <TooltipContent>Create new agent</TooltipContent>
- </Tooltip>
- </div>
- );
-}
-
-function ConnectComputerCard({ workspaceId }: { workspaceId: string }) {
- const owner = useWorkspaceOwner();
- const source = useWorkspaceViewSource(owner, "connect-computer", true);
- const pairing = useQuery({ queryKey: owner.key("machine-pairing", "cli"), gcTime: 0, staleTime: Infinity, retry: false,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => createMachineToken("cli", workspaceId, options), signal),
- });
- const command = `${cliCmd()} register --token ${pairing.data?.token ?? ""}`;
-
- const copy = async () => {
- const assertView = source.assertActive;
- try {
- assertView();
- await navigator.clipboard.writeText(command);
- assertView();
- toast.success("Copied to clipboard");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to copy command");
- }
- };
-
- return (
- <div className="rounded-xl bg-muted/40 p-4 space-y-3">
- <h3 className="text-sm font-semibold">Connect a computer</h3>
- <p className="text-xs text-muted-foreground">
- Run this command in your terminal to link your machine.
- </p>
- {pairing.isPending ? (
- <div className="rounded-md bg-muted p-2 font-mono text-xs text-muted-foreground animate-pulse">
- Generating token...
- </div>
- ) : pairing.isError ? (
- <Button size="sm" onClick={() => void pairing.refetch()}>Retry generating token</Button>
- ) : (
- <>
- <div
- className="rounded-md bg-muted p-2 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors break-all"
- onClick={copy}
- >
- {command}
- </div>
- <Button size="sm" onClick={copy} className="w-full">
- Copy Command
- </Button>
- </>
- )}
- </div>
- );
-}
-
-export default function HomePage() {
- const router = useRouter();
- const { agents, runtimes, loading } = useAgentContext();
- const { workspaceId } = useWorkspace();
- const isMobile = useIsMobile();
- const { openAgentChat } = useAgentChatSheet();
-
- const handleAgentClick = useCallback((agent: Agent) => {
- openAgentChat(agent.id);
- }, [openAgentChat]);
-
- if (loading) {
- return (
- <div className="flex flex-1 items-center justify-center">
- <Loader2 className="size-5 animate-spin text-muted-foreground" />
- </div>
- );
- }
-
- const onlineRuntimes = runtimes.filter((r) => r.status === "online");
- const hasComputer = onlineRuntimes.length > 0;
-
- if (agents.length === 0) {
- return (
- <div className="flex flex-1 items-center justify-center">
- <div className="w-full max-w-sm space-y-6 animate-[fade-up_400ms_ease-out_both]">
- {!hasComputer && (
- <ConnectComputerCard workspaceId={workspaceId} />
- )}
- <div className="text-center">
- <p className="text-muted-foreground text-sm">Build your AI company</p>
- <Button
- size="sm"
- className="mt-4 glow-border"
- onClick={() => router.push(`/studio/new?workspace_id=${workspaceId}`)}
- >
- Get Started
- </Button>
- </div>
- </div>
- </div>
- );
- }
-
- if (isMobile) {
- return <MobileAgentList onAgentClick={handleAgentClick} />;
- }
-
- return (
- <ReactFlowProvider>
- <AgentCanvas onAgentClick={handleAgentClick} />
- </ReactFlowProvider>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/issues/page.tsx b/src/web/src/app/(app)/w/[slug]/issues/page.tsx
deleted file mode 100644
index 93ec262e2..000000000
--- a/src/web/src/app/(app)/w/[slug]/issues/page.tsx
+++ /dev/null
@@ -1,588 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useArtifactClick } from "@/components/use-artifact-click";
-import { useCallback, useEffect, useMemo } from "react";
-import { useQuery, isCancelledError } from "@tanstack/react-query";
-import { workspaceIssueListOptions, workspaceIssueOptions, workspaceTaskOptions, workspaceTraceOptions } from "@/hooks/workspace/issue-query-options";
-import { useIssueCommand, usePendingIssueChanges } from "@/hooks/workspace/use-issue-command";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { ApiError, isAbortError } from "@/lib/errors";
-import { useLocalStorage } from "@/hooks/use-local-storage";
-import { CircleDot, Eye, EyeOff, Loader2, Plus, Trash2 } from "lucide-react";
-import type { Agent, Artifact, Issue } from "@alook/shared";
-import { useWorkspaceOwner, captureWorkspaceOwner } from "@/contexts/workspace-context";
-import { useAgentContext } from "@/contexts/agent-context";
-
-import type { IssueListItem } from "@/lib/api";
-
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Skeleton } from "@/components/ui/skeleton";
-import { AgentAvatar } from "@/components/avatar";
-import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { cn } from "@/lib/utils";
-import { toast } from "sonner";
-import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors, useDroppable, useDraggable, type DragEndEvent, type DragStartEvent } from "@dnd-kit/core";
-import { IssueSheet } from "@/components/issues/issue-sheet";
-import { trackIssueCreated, trackIssueStatusChanged } from "@/lib/analytics";
-import { ArtifactSheet } from "@/components/agent-chat/artifact-sheet";
-import { computeArtifactVersions } from "@/components/artifact-content-renderer";
-
-
-const COLUMNS = [
- { id: "todo", label: "Todo", statuses: ["todo"] },
- { id: "in_progress", label: "In Progress", statuses: ["in_progress"] },
- { id: "review", label: "Review", statuses: ["review"] },
- { id: "completed", label: "Completed", statuses: ["done", "closed", "canceled", "failed"] },
-] as const;
-
-function formatDate(value: string | null) {
- if (!value) return "";
- return new Date(value).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
-}
-
-function IssueCard({
- issue,
- selected,
- onClick,
- onDelete,
- agent,
- agentsById,
- compact = false,
-}: {
- issue: IssueListItem;
- selected: boolean;
- onClick: () => void;
- onDelete?: () => void;
- agent?: Agent | null;
- agentsById?: Map<string, Agent>;
- compact?: boolean;
-}) {
- const threadAgents = useMemo(() => {
- const ids = issue.thread_agent_ids;
- if (!ids || ids.length < 2 || !agentsById) return null;
- const assignedId = issue.agent_id;
- const sorted = assignedId
- ? [assignedId, ...ids.filter(id => id !== assignedId)]
- : ids;
- return sorted.map(id => agentsById.get(id)).filter((a): a is Agent => !!a);
- }, [issue.thread_agent_ids, issue.agent_id, agentsById]);
-
- return (
- <ContextMenu>
- <ContextMenuTrigger
- render={
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "w-full rounded-lg border bg-background/75 p-3 text-left transition-colors cursor-pointer",
- "hover:bg-accent/70 hover:border-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
- selected ? "border-foreground/30 bg-accent" : "border-border/60"
- )}
- />
- }
- >
- <div className="min-w-0">
- <div className="flex items-start justify-between gap-2">
- <div className="line-clamp-2 min-w-0 text-sm font-medium leading-5 text-foreground">{issue.title}</div>
- {issue.status === "in_progress" && (
- <span className="flex shrink-0 items-center gap-1 rounded bg-primary/10 px-2 py-1 text-[10px] font-medium text-primary">
- <Loader2 className="size-2.5 animate-spin" /> Working
- </span>
- )}
- {issue.status === "review" && (
- <span className="shrink-0 rounded bg-yellow-500/10 px-2 py-1 text-[10px] font-medium text-yellow-600 dark:text-yellow-400">Review</span>
- )}
- {issue.status === "failed" && (
- <span className="shrink-0 rounded bg-destructive/10 px-2 py-1 text-[10px] font-medium text-destructive">Failed</span>
- )}
- </div>
- {issue.description ? (
- <div className={cn("mt-1 text-xs leading-4 text-muted-foreground", compact ? "line-clamp-1" : "line-clamp-2")}>
- {issue.description}
- </div>
- ) : null}
- <div className="mt-2 flex min-w-0 items-center justify-between gap-2 text-[11px] text-muted-foreground">
- {threadAgents && threadAgents.length >= 2 ? (
- <span className="flex items-center">
- {threadAgents.slice(0, 3).map((a, i) => (
- <span key={a.id} className={cn("rounded-full border-2 border-background", i > 0 && "-ml-2")}>
- <AgentAvatar name={a.name} avatarUrl={a.avatar_url} seed={a.id} size={16} />
- </span>
- ))}
- {threadAgents.length > 3 && (
- <span className="flex items-center justify-center rounded-full border-2 border-background bg-muted text-[9px] font-medium text-muted-foreground -ml-2" style={{ width: 16, height: 16 }}>
- +{threadAgents.length - 3}
- </span>
- )}
- </span>
- ) : agent ? (
- <span className="flex items-center gap-1 truncate">
- <AgentAvatar name={agent.name} avatarUrl={agent.avatar_url} seed={agent.id} size={14} />
- <span className="truncate">{agent.name}</span>
- </span>
- ) : (
- <span className="truncate text-muted-foreground/60">{issue.agent_id ? "" : "Unassigned"}</span>
- )}
- <span className="shrink-0">{formatDate(issue.updated_at)}</span>
- </div>
- </div>
- </ContextMenuTrigger>
- {onDelete && (
- <ContextMenuContent>
- <ContextMenuItem className="text-destructive" onClick={onDelete}>
- <Trash2 className="size-3.5 mr-2" />
- Delete
- </ContextMenuItem>
- </ContextMenuContent>
- )}
- </ContextMenu>
- );
-}
-
-function DroppableColumn({ id, children, className }: { id: string; children: React.ReactNode; className?: string }) {
- const { isOver, setNodeRef } = useDroppable({ id });
- return (
- <div
- ref={setNodeRef}
- className={cn(
- "flex min-h-0 flex-col rounded-lg border bg-card/60 transition-colors",
- isOver ? "ring-2 ring-primary/40 bg-primary/5 border-primary/30" : "border-border/60",
- className
- )}
- >
- {children}
- </div>
- );
-}
-
-function CollapsedCompletedStrip({ activeDragId, completedCount, onExpand }: { activeDragId: string | null; completedCount: number; onExpand: () => void }) {
- const { isOver, setNodeRef } = useDroppable({ id: "completed" });
-
- return (
- <Tooltip>
- <TooltipTrigger
- render={
- <div
- ref={setNodeRef}
- role="button"
- tabIndex={0}
- aria-label="Show completed column"
- onClick={() => { if (!activeDragId) onExpand(); }}
- onKeyDown={(e) => { if ((e.key === "Enter" || e.key === " ") && !activeDragId) { e.preventDefault(); onExpand(); } }}
- className={cn(
- "flex h-full items-center justify-center rounded-lg border transition-colors",
- isOver
- ? "ring-2 ring-primary/40 bg-primary/5 border-primary/30"
- : "border-dashed border-border/60 bg-muted/20 cursor-pointer hover:bg-muted/40"
- )}
- />
- }
- >
- <div className="flex flex-col items-center justify-center gap-3 h-full py-3">
- <Eye className="size-3.5 text-muted-foreground/60 shrink-0" />
- <span className="text-xs font-medium text-muted-foreground" style={{ writingMode: "vertical-rl" }}>
- Completed ({completedCount})
- </span>
- </div>
- </TooltipTrigger>
- <TooltipContent>{activeDragId ? "Drop to complete" : "Show completed"}</TooltipContent>
- </Tooltip>
- );
-}
-
-function DraggableIssueCard({
- issue,
- selected,
- onClick,
- onDelete,
- agent,
- agentsById,
- compact = false,
-}: {
- issue: IssueListItem;
- selected: boolean;
- onClick: () => void;
- onDelete?: () => void;
- agent?: Agent | null;
- agentsById?: Map<string, Agent>;
- compact?: boolean;
-}) {
- const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: issue.id });
- const style: React.CSSProperties = {
- transform: transform ? `translate3d(${transform.x}px, ${transform.y}px, 0)` : undefined,
- opacity: isDragging ? 0.4 : 1,
- cursor: isDragging ? "grabbing" : "grab",
- };
-
- return (
- <div ref={setNodeRef} style={style} {...listeners} {...attributes}>
- <IssueCard issue={issue} selected={selected} onClick={onClick} onDelete={onDelete} agent={agent} agentsById={agentsById} compact={compact} />
- </div>
- );
-}
-
-export default function IssuesPage() {
-
- const owner = useWorkspaceOwner();
- const { workspaceId, slug } = owner;
- const { agents, loading: agentsLoading } = useAgentContext();
- const scope = owner.application.userId + ":" + workspaceId;
- const [recentAgentId, setRecentAgentId] = useLocalStorage<string>("issue-recent-agent-id-" + scope, "");
- const [draft, setDraft] = useLocalStorage<{ title: string; description: string; agentId: string }>("issue-draft-" + scope, { title: "", description: "", agentId: "" });
- const [showCompleted, setShowCompleted] = useLocalStorage<boolean>("issues-show-completed-" + owner.application.userId, true);
- const [sheetOpen, setSheetOpen] = useAtom(useCreateAtom(false));
- const selection = useCreateAtom<string | null>(null);
- const [selectedId, setSelectedId] = useAtom(selection);
- const [activeDragId, setActiveDragId] = useAtom(useCreateAtom<string | null>(null));
- const [artifactSheetOpen, setArtifactSheetOpen] = useAtom(useCreateAtom(false));
- const [selectedArtifactId, setSelectedArtifactId] = useAtom(useCreateAtom<string | null>(null));
- const source = useWorkspaceViewSource(owner, JSON.stringify(["issue-board", selectedId, sheetOpen]), true);
- const listQuery = useQuery(workspaceIssueListOptions(owner));
- const issueQuery = useQuery({ ...workspaceIssueOptions(owner, sheetOpen ? selectedId ?? "__none__" : "__none__"), enabled: sheetOpen && !!selectedId });
- const { mutateAsync: mutateIssue } = useIssueCommand(owner);
- const pending = usePendingIssueChanges(owner);
- const projectIssue = useCallback((issue: IssueListItem) => pending.reduce((current, action) => action.kind === "update" && action.id === current.id ? { ...current, ...action.patch } : current, issue), [pending]);
- const issues = useMemo(() => (listQuery.data ?? []).filter((row) => !pending.some((action) => action.kind === "delete" && action.id === row.id)).map(projectIssue), [listQuery.data, pending, projectIssue]);
- const detail = useMemo(() => issueQuery.data ? { ...issueQuery.data, issue: { ...issueQuery.data.issue, ...projectIssue(issueQuery.data.issue) } } : null, [issueQuery.data, projectIssue]);
- const detailLoading = issueQuery.isPending && !!selectedId && sheetOpen;
- const taskId = detail?.issue.latest_task_id;
- const traceId = detail?.issue.trace_id;
- const activeTask = useQuery({ ...workspaceTaskOptions(owner, taskId ?? "__none__"), enabled: sheetOpen && !!taskId }).data ?? null;
- const traceTasks = useQuery({ ...workspaceTraceOptions(owner, traceId ?? "__none__"), enabled: sheetOpen && !!traceId }).data?.tasks ?? null;
- const loading = listQuery.isPending;
- useObservedQueryRegion("issues", listQuery, issues.length);
- useObservedQueryRegion("issue_detail", issueQuery, undefined, sheetOpen && !!selectedId);
- const creating = pending.some((action) => action.kind === "create");
- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
- const agentsById = useMemo(() => new Map(agents.map((agent) => [agent.id, agent])), [agents]);
- const issueArtifacts = useMemo(() => detail?.artifacts ?? [], [detail?.artifacts]);
- const selectedArtifact = issueArtifacts.find((artifact) => artifact.id === selectedArtifactId) ?? null;
- const { versionMap: artifactVersionMap, duplicateFilenames: artifactDuplicateFilenames } = useMemo(() => computeArtifactVersions(issueArtifacts), [issueArtifacts]);
- const previewArtifact = useCallback((artifact: Artifact) => { setSelectedArtifactId(artifact.id); setArtifactSheetOpen(true); }, [setSelectedArtifactId, setArtifactSheetOpen]);
- const handleArtifactClick = useArtifactClick(workspaceId, previewArtifact);
-
- const openIssue = useCallback((id: string) => {
- source.assertActive();
- setSelectedId(id);
- setSheetOpen(true);
- }, [source, setSelectedId, setSheetOpen]);
- const handleSheetOpenChange = useCallback((open: boolean) => {
- setSheetOpen(open);
- if (!open) setSelectedId(null);
- }, [setSheetOpen, setSelectedId]);
- useEffect(() => {
- if (!issueQuery.error || isAbortError(issueQuery.error) || isCancelledError(issueQuery.error)) return;
- try { source.assertActive(); } catch { return; }
- if (issueQuery.error instanceof ApiError && issueQuery.error.status === 404) handleSheetOpenChange(false);
- else toast.error(issueQuery.error instanceof Error ? issueQuery.error.message : "Failed to load issue");
- }, [issueQuery.error, source.assertActive, handleSheetOpenChange, source]);
-
- const handleCreate = useCallback(async (values: { agent_id?: string; title: string; description: string }) => {
- const assertView = source.assertActive;
- try {
- assertView();
- const issue = await mutateIssue({ action: { kind: "create", values }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- if (!issue) return;
- trackIssueCreated({ agent_id: values.agent_id ?? "" });
- if (values.agent_id) setRecentAgentId(values.agent_id);
- setDraft({ title: "", description: "", agentId: "" });
- setSelectedId(issue.id);
- setSheetOpen(true);
- toast.success("Issue created");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to create issue");
- }
- }, [owner, source, mutateIssue, setRecentAgentId, setDraft, setSelectedId, setSheetOpen]);
-
- const handleUpdate = useCallback(async (id: string, patch: { title?: string; description?: string }) => {
- const assertView = source.assertActive;
- try {
- assertView();
- await mutateIssue({ action: { kind: "update", id, patch }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to update issue");
- }
- }, [owner, source, mutateIssue]);
-
- const handleStatusChange = useCallback(async (id: string, status: string, method: "button" | "drag" = "button") => {
- const issue = issues.find((row) => row.id === id);
- if (!issue || issue.status === status) return;
- const assertView = source.assertActive;
- try {
- assertView();
- trackIssueStatusChanged({ from: issue.status, to: status, method });
- await mutateIssue({ action: { kind: "update", id, patch: { status: status as Issue["status"] } }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to update issue status");
- }
- }, [owner, issues, source, mutateIssue]);
-
- const handleDeleteIssue = useCallback(async (id: string) => {
- const assertView = source.assertActive;
- try {
- assertView();
- await mutateIssue({ action: { kind: "delete", id }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- if (selection.get() === id) handleSheetOpenChange(false);
- toast.success("Issue deleted");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to delete issue");
- }
- }, [owner, source, mutateIssue, selection, handleSheetOpenChange]);
-
- function handleDragStart(event: DragStartEvent) { setActiveDragId(event.active.id as string); }
- async function handleDragEnd(event: DragEndEvent) {
- setActiveDragId(null);
- const { active, over } = event;
- if (!over) return;
- const issue = issues.find((row) => row.id === active.id), column = COLUMNS.find((row) => row.id === over.id);
- if (!issue || !column || (column.statuses as readonly string[]).includes(issue.status)) return;
- if (issue.status === "todo" && !issue.agent_id && column.id !== "todo" && column.id !== "completed") { toast.error("Assign an agent first to run this issue"); return; }
- await handleStatusChange(issue.id, column.id === "completed" ? "done" : column.id, "drag");
- }
- const boardLoading = loading || agentsLoading;
- const selectedIssue = selectedId ? detail?.issue ?? issues.find((i) => i.id === selectedId) ?? null : null;
-
- return (
- <div className="relative flex h-full min-h-0 flex-col bg-background/30">
- <div className="flex shrink-0 flex-col gap-3 border-b border-border/60 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-4 sm:py-4">
- <div className="min-w-0">
- <h1 className="text-base font-semibold tracking-normal">Issues</h1>
- </div>
- <div className="flex items-center gap-2">
- <Button size="sm" className="w-full sm:w-auto" onClick={() => { setSelectedId(null); setSheetOpen(true); }}>
- <Plus className="size-4" />
- New issue
- </Button>
- </div>
- </div>
-
- <div className="hidden min-h-0 flex-1 lg:block overflow-y-auto thin-scrollbar p-4">
- {boardLoading ? (
- <div className={cn("grid h-full gap-4", showCompleted ? "grid-cols-4" : "grid-cols-[1fr_1fr_1fr_36px]")}>
- {[3, 2, 2, ...(showCompleted ? [2] : [])].map((cardCount, colIdx) => (
- <div key={colIdx} className="flex min-h-0 flex-col rounded-lg border border-border/60 bg-card/60">
- <div className="border-b border-border/60 bg-muted/30 px-3 py-2">
- <Skeleton className="h-3 w-16" />
- </div>
- <div className="min-h-0 flex-1 space-y-2 p-2">
- {Array.from({ length: cardCount }).map((_, i) => (
- <div key={i} className="rounded-lg border bg-background/75 p-3">
- <Skeleton className="h-4 w-3/4" />
- <Skeleton className="mt-1 h-3 w-1/2" />
- <Skeleton className="mt-2 h-3 w-1/3" />
- </div>
- ))}
- </div>
- </div>
- ))}
- {!showCompleted && (
- <div className="h-full rounded-lg border border-dashed border-border/60 bg-muted/20" />
- )}
- </div>
- ) : issues.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]">
- <CircleDot className="size-8 text-muted-foreground mb-3" />
- <p className="text-sm text-muted-foreground">No issues</p>
- <p className="text-xs text-muted-foreground/60 mt-1">Create one to get started.</p>
- </div>
- ) : (
- <DndContext sensors={sensors} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
- <div className={cn("grid h-full gap-4 animate-[fade-up_200ms_ease-out_both]", showCompleted ? "grid-cols-4" : "grid-cols-[1fr_1fr_1fr_36px]")}>
- {COLUMNS.filter(col => col.id !== "completed" || showCompleted).map((col) => {
- const columnIssues = issues.filter((issue) => (col.statuses as readonly string[]).includes(issue.status));
- return (
- <DroppableColumn key={col.id} id={col.id}>
- <div className="flex shrink-0 items-center justify-between border-b border-border/60 bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">
- <span>{col.label}</span>
- <div className="flex items-center gap-2">
- <span>{columnIssues.length}</span>
- {col.id === "completed" && (
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- aria-label="Hide completed column"
- disabled={!!activeDragId}
- onClick={() => setShowCompleted(false)}
- className="rounded p-1 text-muted-foreground/60 transition-colors hover:bg-muted hover:text-muted-foreground disabled:opacity-40"
- />
- }
- >
- <EyeOff className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Hide completed</TooltipContent>
- </Tooltip>
- )}
- </div>
- </div>
- <div className={cn("min-h-0 flex-1 space-y-2 overflow-y-auto thin-scrollbar p-2", col.id === "completed" && "animate-[fade-up_300ms_ease-out_both]")}>
- {columnIssues.length === 0 ? (
- <div className="flex h-full min-h-20 items-center justify-center rounded-lg border border-dashed border-border/45 text-xs text-muted-foreground/70">
- Empty
- </div>
- ) : (
- columnIssues.map((issue) => (
- <DraggableIssueCard key={issue.id} issue={issue} selected={selectedId === issue.id} onClick={() => openIssue(issue.id)} onDelete={() => handleDeleteIssue(issue.id)} agent={agentsById.get(issue.agent_id ?? "") ?? null} agentsById={agentsById} />
- ))
- )}
- </div>
- </DroppableColumn>
- );
- })}
- {!showCompleted && (
- <CollapsedCompletedStrip
- activeDragId={activeDragId}
- completedCount={issues.filter(i => (COLUMNS[3].statuses as readonly string[]).includes(i.status)).length}
- onExpand={() => setShowCompleted(true)}
- />
- )}
- </div>
- <DragOverlay style={{ zIndex: 9999 }}>
- {activeDragId ? (() => {
- const dragIssue = issues.find((i) => i.id === activeDragId);
- if (!dragIssue) return null;
- return <IssueCard issue={dragIssue} selected={false} onClick={() => {}} agent={agentsById.get(dragIssue.agent_id ?? "") ?? null} agentsById={agentsById} />;
- })() : null}
- </DragOverlay>
- </DndContext>
- )}
- </div>
-
- <div className="min-h-0 flex-1 overflow-y-auto thin-scrollbar p-3 lg:hidden">
- {boardLoading ? (
- <div className="space-y-4">
- {[0, 1, 2].map((i) => (
- <div key={i} className="rounded-lg border border-border/60 bg-card/60">
- <div className="border-b border-border/50 px-3 py-2">
- <Skeleton className="h-4 w-20" />
- </div>
- <div className="space-y-2 p-3">
- {Array.from({ length: 2 }).map((_, j) => (
- <div key={j} className="rounded-lg border bg-background/75 p-3">
- <Skeleton className="h-4 w-3/4" />
- <Skeleton className="mt-1 h-3 w-1/2" />
- <Skeleton className="mt-2 h-3 w-1/3" />
- </div>
- ))}
- </div>
- </div>
- ))}
- <div className="rounded-lg border border-dashed border-border/60 px-3 py-2">
- <Skeleton className="h-4 w-32" />
- </div>
- </div>
- ) : issues.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]">
- <CircleDot className="size-8 text-muted-foreground mb-3" />
- <p className="text-sm text-muted-foreground">No issues yet</p>
- <p className="text-xs text-muted-foreground/60 mt-1">Create one to get started.</p>
- </div>
- ) : (
- <div className="space-y-4 animate-[fade-up_200ms_ease-out_both]">
- {COLUMNS.map((col) => {
- if (col.id === "completed" && !showCompleted) return null;
- const columnIssues = issues.filter((issue) => (col.statuses as readonly string[]).includes(issue.status));
- if (columnIssues.length === 0) return null;
- return (
- <section key={col.id} className="rounded-lg border border-border/60 bg-card/60">
- <div className="flex items-center justify-between border-b border-border/50 px-3 py-2 text-sm font-medium">
- <span>{col.label}</span>
- <div className="flex items-center gap-2">
- <Badge variant="outline">{columnIssues.length}</Badge>
- {col.id === "completed" && (
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- aria-label="Hide completed column"
- onClick={() => setShowCompleted(false)}
- className="rounded p-1 text-muted-foreground/60 transition-colors hover:bg-muted hover:text-muted-foreground"
- />
- }
- >
- <EyeOff className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Hide completed</TooltipContent>
- </Tooltip>
- )}
- </div>
- </div>
- <div className="space-y-2 p-3">
- {columnIssues.map((issue) => (
- <IssueCard key={issue.id} issue={issue} selected={selectedId === issue.id} onClick={() => openIssue(issue.id)} onDelete={() => handleDeleteIssue(issue.id)} agent={agentsById.get(issue.agent_id ?? "") ?? null} agentsById={agentsById} compact />
- ))}
- </div>
- </section>
- );
- })}
- {!showCompleted && (
- <div
- role="button"
- tabIndex={0}
- aria-label="Show completed issues"
- onClick={() => setShowCompleted(true)}
- onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setShowCompleted(true); } }}
- className="flex cursor-pointer items-center gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-sm text-muted-foreground transition-colors hover:bg-muted/30"
- >
- <Eye className="size-3.5" />
- <span>Show Completed ({issues.filter(i => (COLUMNS[3].statuses as readonly string[]).includes(i.status)).length})</span>
- </div>
- )}
- </div>
- )}
- </div>
-
- <IssueSheet
- open={sheetOpen}
- onOpenChange={handleSheetOpenChange}
- agents={agents}
- issue={selectedIssue}
- detail={detail ? { messages: detail.messages, comments: detail.comments, artifacts: detail.artifacts, traceId: detail.issue.trace_id } : null}
- detailLoading={detailLoading}
- activeTask={activeTask}
- traceTasks={traceTasks}
- submitting={creating}
- defaultAgentId={recentAgentId}
- slug={slug}
- workspaceId={workspaceId}
- draft={draft}
- onDraftChange={setDraft}
- onCreate={handleCreate}
- onUpdate={handleUpdate}
- onStatusChange={handleStatusChange}
- onCommented={() => selectedId && openIssue(selectedId)}
- onDispatched={openIssue}
- onArtifactClick={handleArtifactClick}
- />
-
- <ArtifactSheet
- open={artifactSheetOpen}
- onOpenChange={(v) => {
- setArtifactSheetOpen(v);
- if (!v) setSelectedArtifactId(null);
- }}
- artifacts={issueArtifacts}
- workspaceId={workspaceId}
- initialArtifact={selectedArtifact}
- versionMap={artifactVersionMap}
- duplicateFilenames={artifactDuplicateFilenames}
- />
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/layout.tsx b/src/web/src/app/(app)/w/[slug]/layout.tsx
deleted file mode 100644
index b1094b012..000000000
--- a/src/web/src/app/(app)/w/[slug]/layout.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { redirect } from "next/navigation"
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
-import { getSession } from "@/lib/session"
-import { WorkspaceProvider } from "@/contexts/workspace-context"
-import { AgentProvider } from "@/contexts/agent-context"
-import { ChannelProvider } from "@/contexts/channel-context"
-import { InboxCountProvider } from "@/contexts/inbox-count-context"
-import { FlagCountProvider } from "@/contexts/flag-count-context"
-import { WorkspaceShell } from "@/components/workspace-shell"
-
-export default async function WorkspaceLayout({
- children,
- params,
-}: {
- children: React.ReactNode
- params: Promise<{ slug: string }>
-}) {
- const session = await getSession()
- if (!session) redirect("/sign-in")
-
- const { slug } = await params
- const { env } = await getCloudflareContext({ async: true })
- const db = getDb((env as Env).DB)
-
- const ws = await queries.workspace.getWorkspaceBySlug(db, slug)
- if (!ws) redirect("/workspaces")
-
- const membership = await queries.member.getMemberByUserAndWorkspace(
- db,
- session.user.id,
- ws.id
- )
- if (!membership) redirect("/workspaces")
-
- if (!ws.onboarded) {
- redirect(`/studio/new?workspace_id=${ws.id}`)
- }
-
- return (
- <WorkspaceProvider workspaceId={ws.id} slug={slug}>
- <AgentProvider workspaceId={ws.id}>
- <InboxCountProvider>
- <FlagCountProvider>
- <ChannelProvider workspaceId={ws.id}>
- <WorkspaceShell>{children}</WorkspaceShell>
- </ChannelProvider>
- </FlagCountProvider>
- </InboxCountProvider>
- </AgentProvider>
- </WorkspaceProvider>
- )
-}
diff --git a/src/web/src/app/(app)/w/[slug]/loading.tsx b/src/web/src/app/(app)/w/[slug]/loading.tsx
deleted file mode 100644
index df0fa73c1..000000000
--- a/src/web/src/app/(app)/w/[slug]/loading.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { Loader2 } from "lucide-react"
-import { GradientBackground } from "@/components/gradient-background"
-
-export default function WorkspaceLoading() {
- return (
- <div className="flex h-dvh items-center justify-center relative">
- <GradientBackground />
- <Loader2 className="size-5 animate-spin text-muted-foreground" />
- </div>
- )
-}
diff --git a/src/web/src/app/(app)/w/[slug]/page.tsx b/src/web/src/app/(app)/w/[slug]/page.tsx
deleted file mode 100644
index e2002be17..000000000
--- a/src/web/src/app/(app)/w/[slug]/page.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { redirect } from "next/navigation"
-
-export default async function WorkspaceRootPage({
- params,
-}: {
- params: Promise<{ slug: string }>
-}) {
- const { slug } = await params
- redirect(`/w/${slug}/home`)
-}
diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
deleted file mode 100644
index cdefbc02b..000000000
--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
+++ /dev/null
@@ -1,526 +0,0 @@
-"use client";
-
-import { useObservedRegion } from "@/lib/observability/regions"
-import { viewEvidence } from "@/lib/observability/data-source"
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useQuery } from "@tanstack/react-query";
-import { useMemo, useRef, useEffect, useCallback } from "react";
-import { useSearchParams, useRouter, usePathname } from "next/navigation";
-import { useAgentContext } from "@/contexts/agent-context";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import {
- Card,
- CardHeader,
- CardTitle,
- CardContent,
-} from "@/components/ui/card";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetDescription,
- SheetBody,
-} from "@/components/ui/sheet";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { toast } from "sonner";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Monitor, Plus } from "lucide-react";
-
-import type { AgentRuntime as Runtime } from "@alook/shared";
-import { semverGte } from "@alook/shared";
-import { cliCmd, getAppMode } from "@/lib/utils";
-import { ProviderLogo } from "@/components/provider-logo";
-import { createMachineToken } from "@/lib/api";
-import { captureWorkspaceOwner, runWorkspaceRequest, useWorkspaceOwner } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { useRuntimeCommand, usePendingRuntimeCommands } from "@/hooks/workspace/use-runtime-command";
-import { latestCliVersionOptions } from "@/hooks/workspace/settings-query-options";
-import { Loader2, RefreshCw } from "lucide-react";
-
-import { ConnectMachineSteps } from "@/components/connect-machine-steps";
-import { trackRuntimeConnected } from "@/lib/analytics";
-
-export default function RuntimesPage() {
- const { runtimes, loading, handleDeleteMachine, subscribeWs, workspaceId } =
- useAgentContext();
- const owner = useWorkspaceOwner();
- useObservedRegion("runtimes", !loading, viewEvidence(runtimes));
- const pageSource = useWorkspaceViewSource(owner, "runtimes", true);
- const searchParams = useSearchParams();
- const router = useRouter();
- const pathname = usePathname();
- const mode = getAppMode();
- const isMobileApp = mode === "mobile";
- const hideNewMachine = isMobileApp;
-
- const initialSheetOpen = useMemo(() => searchParams.has("connect"), [searchParams]);
- const [sheetOpen, setSheetOpen] = useAtom(useCreateAtom(initialSheetOpen));
- const registeredDaemon = useCreateAtom<string | null>(null);
- const [registeredDaemonId, setRegisteredDaemonId] = useAtom(registeredDaemon);
- const sheetSource = useWorkspaceViewSource(owner, "runtime-pairing", sheetOpen);
- const pairing = useQuery({
- queryKey: owner.key("machine-pairing", "runtime-page", sheetOpen ? "open" : "closed"),
- enabled: false, gcTime: 0, retry: false,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => createMachineToken("cli", workspaceId, options), signal),
- });
- const generatedToken = sheetOpen ? pairing.data?.token ?? "" : "";
- const generatingToken = pairing.isFetching;
- const daemonOnline = runtimes.some((runtime) => runtime.daemon_id === registeredDaemonId && runtime.status === "online");
- const latestCliVersion = useQuery(latestCliVersionOptions(owner)).data?.version ?? null;
- const runtimeCommand = useRuntimeCommand(owner);
- const pendingCommands = usePendingRuntimeCommands(owner);
- const updatingDaemons = new Set(pendingCommands.filter((intent) => intent.kind === "update").map((intent) => runtimes.find((runtime) => runtime.id === intent.id)?.daemon_id ?? intent.id));
- const rescanningDaemons = new Set(pendingCommands.filter((intent) => intent.kind === "rescan").map((intent) => runtimes.find((runtime) => runtime.id === intent.id)?.daemon_id ?? intent.id));
-
- const [confirmOpen, setConfirmOpen] = useAtom(useCreateAtom(false));
- const [confirmTitle, setConfirmTitle] = useAtom(useCreateAtom(""));
- const [confirmDescription, setConfirmDescription] = useAtom(useCreateAtom(""));
- const [confirmLabel, setConfirmLabel] = useAtom(useCreateAtom("Remove"));
- const [confirmLoadingLabel, setConfirmLoadingLabel] = useAtom(useCreateAtom<string | undefined>(undefined));
- const [confirmVariant, setConfirmVariant] = useAtom(useCreateAtom<"destructive" | "default">("destructive"));
- const [confirmLoading, setConfirmLoading] = useAtom(useCreateAtom(false));
- const confirmAction = useRef<(() => Promise<void>) | null>(null);
-
- // Clean up ?connect query param after initial open
- useEffect(() => {
- if (searchParams.has("connect")) {
- router.replace(pathname, { scroll: false });
- }
- }, [searchParams, router, pathname]);
-
- // Listen for registration + online events while the sheet is open.
- useEffect(() => {
- if (!sheetOpen) return;
- const assert = sheetSource.assertActive;
- return subscribeWs((msg) => {
- try { assert(); } catch { return; }
- if (msg.type === "runtime.registered" && msg.workspaceId === workspaceId) {
- setRegisteredDaemonId(msg.daemonId);
- }
- if (
- msg.type === "runtime.status" &&
- msg.workspaceId === workspaceId &&
- msg.status === "online" &&
- registeredDaemon.get() &&
- msg.daemonId === registeredDaemon.get()
- ) {
- trackRuntimeConnected({ runtime_type: "desktop" });
- setSheetOpen(false);
- setRegisteredDaemonId(null);
- toast.success("Machine connected");
- if (owner.queryClient.getQueryData<unknown[]>(owner.key("agents"))?.length === 0) {
- router.push(`/w/${owner.slug}/agents/new`);
- }
- }
- });
- }, [subscribeWs, workspaceId, owner, router, sheetOpen, sheetSource.assertActive, registeredDaemon, setRegisteredDaemonId, setSheetOpen]);
-
- const openConfirm = (
- title: string,
- description: string,
- action: () => Promise<void>,
- opts?: { label?: string; loadingLabel?: string; variant?: "destructive" | "default" }
- ) => {
- setConfirmTitle(title);
- setConfirmDescription(description);
- setConfirmLabel(opts?.label ?? "Remove");
- setConfirmLoadingLabel(opts?.loadingLabel);
- setConfirmVariant(opts?.variant ?? "destructive");
- confirmAction.current = action;
- setConfirmOpen(true);
- };
-
- const handleConfirm = async () => {
- if (!confirmAction.current) return;
- const assert = pageSource.assertActive;
- const action = confirmAction.current;
- assert();
- setConfirmLoading(true);
- try {
- await action();
- } catch (error) {
- try { assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error("Failed to update machine");
- } finally {
- try {
- assert();
- if (confirmAction.current === action) {
- setConfirmLoading(false);
- setConfirmOpen(false);
- confirmAction.current = null;
- }
- } catch {}
- }
- };
-
- const onGenerateToken = useCallback(async () => {
- const assert = sheetSource.assertActive;
- try {
- assert();
- await pairing.refetch({ throwOnError: true });
- assert();
- } catch (error) {
- try { assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error("Failed to generate token");
- }
- }, [pairing, sheetSource.assertActive]);
-
- const handleUpdate = async (runtimeId: string) => {
- const assert = pageSource.assertActive;
- const token = captureWorkspaceOwner(owner);
- try {
- assert();
- await runtimeCommand.mutateAsync({ kind: "update", id: runtimeId, token, assertActive: Object.assign(() => assert(), { signal: pageSource.signal }) });
- assert();
- toast.success("Update triggered");
- } catch (error) {
- try { assert(); } catch { return; }
- if (error instanceof DOMException && error.name === "AbortError") return;
- toast.error("Failed to trigger update");
- }
- };
-
- const handleRescan = async (runtimeId: string) => {
- const assert = pageSource.assertActive;
- const token = captureWorkspaceOwner(owner);
- try {
- assert();
- await runtimeCommand.mutateAsync({ kind: "rescan", id: runtimeId, token, assertActive: Object.assign(() => assert(), { signal: pageSource.signal }) });
- assert();
- toast.success("Rescan triggered — daemon will restart to detect runtimes");
- } catch (error) {
- try { assert(); } catch { return; }
- if (error instanceof DOMException && error.name === "AbortError") return;
- toast.error("Failed to trigger rescan");
- }
- };
-
- // Group runtimes by machine
- const machines = new Map<
- string,
- { deviceInfo: string; status: string; lastSeenAt: string | null; pendingUpdateVersion: string | null; pendingRescan: boolean; cliVersion: string | null; runtimes: Runtime[] }
- >();
- for (const rt of runtimes) {
- const key = rt.daemon_id || rt.id;
- if (!machines.has(key)) {
- const meta = rt.metadata as Record<string, unknown> | null;
- machines.set(key, {
- deviceInfo: typeof rt.device_info === "string" ? rt.device_info : "",
- status: rt.status,
- lastSeenAt: rt.last_seen_at,
- pendingUpdateVersion: rt.pending_update_version ?? null,
- pendingRescan: !!rt.pending_rescan,
- cliVersion: (meta?.cli_version as string) ?? null,
- runtimes: [],
- });
- }
- machines.get(key)!.runtimes.push(rt);
- }
-
- if (loading) {
- return (
- <>
- {/* Skeleton title bar */}
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2">
- <div className="flex items-center gap-3">
-
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-3 w-52" />
- </div>
- <Skeleton className="h-8 w-29 rounded-md" />
- </div>
- {/* Skeleton card grid */}
- <div className="flex-1 overflow-y-auto thin-scrollbar px-4 py-4">
- <div className="grid gap-4 sm:grid-cols-3">
- {Array.from({ length: 3 }).map((_, i) => (
- <div
- key={i}
- className="rounded-xl border border-border/50 bg-card p-4 space-y-3"
- >
- <div className="flex items-center gap-2">
- <Skeleton className="size-4 rounded" />
- <Skeleton className="h-4 w-28" />
- </div>
- <div className="space-y-2">
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <Skeleton className="h-3 w-20" />
- <Skeleton className="h-3 w-28" />
- </div>
- <Skeleton className="h-5 w-14 rounded-full" />
- </div>
- </div>
- </div>
- ))}
- </div>
- </div>
- </>
- );
- }
-
- return (
- <>
- {/* Title bar */}
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2">
- <div className="flex items-center gap-3">
- <h1 className="text-sm font-medium">Runtimes</h1>
- <p className="text-xs text-muted-foreground">
- Your machines and their agent runtimes.
- </p>
- </div>
- {!hideNewMachine && (
- <Button
- size="sm"
- variant="outline"
- onClick={() => {
- setRegisteredDaemonId(null);
- setSheetOpen(true);
- }}
- disabled={generatingToken}
- >
- <Plus className="size-3.5" />
- New machine
- </Button>
- )}
- </div>
-
- <div className="flex-1 overflow-y-auto thin-scrollbar px-4 py-4">
- {runtimes.length === 0 ? (
- <div className="flex flex-1 items-center justify-center min-h-[60vh]">
- <div className="text-center animate-[fade-up_400ms_ease-out_both]">
- <p className="text-muted-foreground text-sm">
- {hideNewMachine
- ? "No machines connected. Use the desktop app or CLI to connect a machine."
- : "Connect a machine to start running agents locally."}
- </p>
- {!hideNewMachine && (
- <Button
- size="sm"
- className="mt-4 glow-border"
- onClick={() => {
- setRegisteredDaemonId(null);
- setSheetOpen(true);
- }}
- >
- Connect Machine
- </Button>
- )}
- </div>
- </div>
- ) : (
- <div className="grid gap-4 sm:grid-cols-3">
- {Array.from(machines.entries()).map(([daemonId, machine]) => {
- const displayName =
- machine.deviceInfo || daemonId;
- return (
- <Card key={daemonId} size="sm">
- <CardHeader>
- <div className="flex items-center gap-2 min-w-0">
- <Monitor className="size-4 text-muted-foreground shrink-0" />
- <CardTitle className="truncate">
- {displayName}
- </CardTitle>
- {machine.cliVersion && (
- <span className="text-xs text-muted-foreground/60 shrink-0">v{machine.cliVersion}</span>
- )}
- <Badge
- variant={
- machine.status === "online"
- ? "default"
- : "outline"
- }
- className="shrink-0"
- >
- {machine.status}
- </Badge>
- </div>
- </CardHeader>
- <CardContent>
- <div className="space-y-2">
- <div className="flex items-center justify-between">
- <span className="text-xs text-muted-foreground tabular-nums">
- {machine.lastSeenAt ? new Date(
- machine.lastSeenAt
- ).toLocaleString() : "Never seen"}
- </span>
- <div className="flex items-center gap-1">
- {(() => {
- const isUpdating = !!machine.pendingUpdateVersion || updatingDaemons.has(daemonId);
- const needsUpdate = machine.status === "online" && latestCliVersion && (!machine.cliVersion || !semverGte(machine.cliVersion, latestCliVersion));
- if (isUpdating) {
- return (
- <Button variant="ghost" size="sm" disabled className="text-xs h-6 px-2">
- <Loader2 className="size-3 animate-spin mr-1" />
- Updating...
- </Button>
- );
- }
- if (needsUpdate) {
- return (
- <Button
- variant="ghost"
- size="sm"
- className="text-xs h-6 px-2"
- onClick={() => openConfirm(
- "Update daemon",
- `This will update the daemon on "${displayName}" to the latest CLI version. The daemon will restart during the update.`,
- async () => { await handleUpdate(machine.runtimes[0].id); },
- { label: "Update", loadingLabel: "Updating...", variant: "default" }
- )}
- >
- Update
- </Button>
- );
- }
- return null;
- })()}
- {(() => {
- const isRescanning = machine.pendingRescan || rescanningDaemons.has(daemonId);
- if (machine.status !== "online") return null;
- if (isRescanning) {
- return (
- <Button variant="ghost" size="sm" disabled className="text-xs h-6 px-2">
- <RefreshCw className="size-3 animate-spin mr-1" />
- Rescanning...
- </Button>
- );
- }
- return (
- <Button
- variant="ghost"
- size="sm"
- className="text-xs h-6 px-2"
- onClick={() => openConfirm(
- "Rescan runtimes",
- `This will restart the daemon on "${displayName}" to re-detect available runtimes (Claude Code, Codex, OpenCode).`,
- async () => { await handleRescan(machine.runtimes[0].id); },
- { label: "Rescan", loadingLabel: "Triggering...", variant: "default" }
- )}
- >
- <RefreshCw className="size-3 mr-1" />
- Rescan
- </Button>
- );
- })()}
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground h-6 px-2 hover:text-destructive"
- onClick={() => {
- openConfirm(
- "Remove machine",
- `This will remove "${displayName}" and all its runtimes. Agents using these runtimes will be unlinked.`,
- async () => {
- await handleDeleteMachine(daemonId);
- }
- );
- }}
- >
- Remove
- </Button>
- </div>
- </div>
- <div className="flex flex-wrap gap-2">
- {machine.runtimes.map((runtime) => (
- <Badge
- key={runtime.id}
- variant="secondary"
- className="gap-2"
- >
- <ProviderLogo provider={runtime.provider} className="h-3.5 w-3.5" />
- {runtime.provider}
- {runtime.metadata?.version ? (
- <span className="text-muted-foreground font-normal">
- {String(runtime.metadata.version)}
- </span>
- ) : null}
- </Badge>
- ))}
- </div>
- {machine.status !== "online" && (
- <div className="pt-1.5 border-t border-border/50">
- <p className="text-[11px] text-muted-foreground mb-2">
- Bring this machine online:
- </p>
- <Tooltip>
- <TooltipTrigger
- render={
- <div
- className="relative overflow-hidden rounded-md bg-muted px-2 py-2 font-mono text-[11px] text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={async () => {
- const assert = pageSource.assertActive;
- try {
- assert();
- await navigator.clipboard.writeText(`${cliCmd()} daemon start`);
- assert();
- toast.success("Copied to clipboard");
- } catch (error) {
- try { assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error("Failed to copy command");
- }
- }}
- />
- }
- >
- <span className="absolute inset-0 -translate-x-full animate-[shimmer_2.5s_infinite] bg-linear-to-r from-transparent via-(--shimmer-peak) to-transparent" />
- <span className="relative">{cliCmd()} daemon start</span>
- </TooltipTrigger>
- <TooltipContent>Click to copy</TooltipContent>
- </Tooltip>
- </div>
- )}
- </div>
- </CardContent>
- </Card>
- );
- })}
- </div>
- )}
- </div>
-
- {/* Connect machine sheet */}
- <Sheet
- open={sheetOpen}
- onOpenChange={(open) => {
- setSheetOpen(open);
- if (!open) setRegisteredDaemonId(null);
- }}
- >
- <SheetContent className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border">
- <SheetHeader>
- <SheetTitle>Connect a machine</SheetTitle>
- <SheetDescription>
- Your machine runs AI agents locally using Claude Code, Codex, or
- OpenCode.
- </SheetDescription>
- </SheetHeader>
- <SheetBody>
- <ConnectMachineSteps
- generatedToken={generatedToken}
- generatingToken={generatingToken}
- onGenerateToken={onGenerateToken}
- registered={!!registeredDaemonId}
- daemonOnline={daemonOnline}
- />
- </SheetBody>
- </SheetContent>
- </Sheet>
-
- <ConfirmDialog
- open={confirmOpen}
- onOpenChange={setConfirmOpen}
- title={confirmTitle}
- description={confirmDescription}
- confirmLabel={confirmLabel}
- loadingLabel={confirmLoadingLabel}
- confirmVariant={confirmVariant}
- loading={confirmLoading}
- onConfirm={handleConfirm}
- />
- </>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx
deleted file mode 100644
index 6ff210d63..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx
+++ /dev/null
@@ -1,237 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-
-import { toast } from "sonner";
-import { useRouter } from "next/navigation";
-import { sanitizeSlug } from "@alook/shared";
-import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { useObservedRegion } from "@/lib/observability/regions";
-import { mergeEvidence, valueEvidence } from "@/lib/observability/data-source";
-import { useQuery, useMutation, type Query } from "@tanstack/react-query";
-import { applicationWorkspacesOptions, workspaceMembersOptions } from "@/hooks/workspace/settings-query-options";
-
-import { updateWorkspace, deleteWorkspace, listWorkspaces } from "@/lib/api";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Skeleton } from "@/components/ui/skeleton";
-import {
- type WorkspaceFormErrors,
- hasWorkspaceFormErrors,
- validateWorkspaceForm,
-} from "@/lib/form-validation";
-import { trackSettingsUpdated } from "@/lib/analytics";
-
-export function GeneralTab() {
- const owner = useWorkspaceOwner();
- const { workspaceId, slug } = owner;
- const source = useWorkspaceViewSource(owner, "workspace-general", true);
- const router = useRouter();
- const membersQuery = useQuery(workspaceMembersOptions(owner));
- const workspacesQuery = useQuery(applicationWorkspacesOptions(owner.application));
- const current = workspacesQuery.data?.find((workspace) => workspace.id === workspaceId);
- const memberRole = membersQuery.data?.find((member) => member.user_id === owner.application.userId)?.role ?? "";
- const loading = membersQuery.isPending || workspacesQuery.isPending;
- useObservedRegion("settings", !loading && !membersQuery.isError && !workspacesQuery.isError, mergeEvidence([valueEvidence(owner.queryClient, membersQuery.data), valueEvidence(owner.queryClient, workspacesQuery.data)]));
- const [nameDraft, setWorkspaceName] = useAtom(useCreateAtom<string | null>(null));
- const [slugDraft, setWorkspaceSlug] = useAtom(useCreateAtom<string | null>(null));
- const workspaceName = nameDraft ?? current?.name ?? "";
- const workspaceSlug = slugDraft ?? current?.slug ?? "";
- const savedWorkspaceName = current?.name ?? "";
- const savedWorkspaceSlug = current?.slug ?? "";
- const [workspaceErrors, setWorkspaceErrors] = useAtom(useCreateAtom<WorkspaceFormErrors>({}));
- const [deleteConfirm, setDeleteConfirm] = useAtom(useCreateAtom(""));
- type OriginalIntent = { token: ReturnType<typeof captureWorkspaceOwner>; view: ReturnType<typeof source.capture>; resources: Query[] };
- const native = useMutation({ meta: { observabilityAction: "workspace.settings.command" }, mutationKey: owner.key("workspace-settings-command"), scope: { id: JSON.stringify(owner.key("workspace-settings-command")) }, gcTime: 0,
- mutationFn: async ({ action, token, view, resources }: { action: { kind: "update"; name: string; slug: string } | { kind: "delete"; name: string }; token: ReturnType<typeof captureWorkspaceOwner> } & OriginalIntent) => {
- const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert(); };
- const key = applicationWorkspacesOptions(owner.application).queryKey;
- assert();
- const original = resources.find((query) => JSON.stringify(query.queryKey) === JSON.stringify(key));
- if (original && owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === original) await owner.queryClient.cancelQueries({ queryKey: key, exact: true });
- assert();
- const before = owner.queryClient.getQueryData<Awaited<ReturnType<typeof listWorkspaces>>>(key)?.find((row) => row.id === workspaceId);
- const writes = original?.state.dataUpdateCount;
- const options = workspaceRequestOptions(token, view.signal, assert);
- try {
- const updated = action.kind === "update" ? await updateWorkspace(workspaceId, { name: action.name, slug: action.slug }, options)
- : (await deleteWorkspace(workspaceId, action.name, options), null);
- assert();
- if (original && owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === original && original.state.dataUpdateCount === writes) {
- owner.queryClient.setQueryData<Awaited<ReturnType<typeof listWorkspaces>>>(key, (rows) => action.kind === "delete" ? rows?.filter((row) => row.id !== workspaceId)
- : rows?.map((row) => row.id !== workspaceId ? row : { ...row, name: row.name === before?.name ? updated!.name : row.name, slug: row.slug === before?.slug ? updated!.slug : row.slug }));
- }
- if (action.kind === "delete") for (const query of resources.filter((query) => owner.key().every((part, index) => Object.is(part, query.queryKey[index])))) {
- if (owner.queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query) owner.queryClient.removeQueries({ queryKey: query.queryKey, exact: true });
- }
- if (original && owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === original) await owner.queryClient.invalidateQueries({ queryKey: key, exact: true }, { cancelRefetch: false });
- assert();
- return updated && original && owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === original ? owner.queryClient.getQueryData<Awaited<ReturnType<typeof listWorkspaces>>>(key)?.find((row) => row.id === workspaceId) ?? null : null;
- } catch (error) { assert(); throw error; }
- },
- });
- const capture = (input: Omit<Parameters<typeof native.mutate>[0], "view" | "resources">) => { const view = source.capture(); view.assert(); assertWorkspaceOwner(input.token, view.signal); return { ...input, view, resources: [...new Set([...owner.queryClient.getQueryCache().findAll({ queryKey: owner.key() }), ...owner.queryClient.getQueryCache().findAll({ queryKey: applicationWorkspacesOptions(owner.application).queryKey, exact: true })])] }; };
- const command = { ...native, mutate: (input: Omit<Parameters<typeof native.mutate>[0], "view" | "resources">) => native.mutate(capture(input)), mutateAsync: (input: Omit<Parameters<typeof native.mutate>[0], "view" | "resources">) => native.mutateAsync(capture(input)) };
- const savingWorkspace = command.isPending && command.variables?.action.kind === "update";
- const deleting = command.isPending && command.variables?.action.kind === "delete";
- const isOwner = memberRole === "owner";
- const isWorkspaceDirty = workspaceName !== savedWorkspaceName || workspaceSlug !== savedWorkspaceSlug;
-
- const handleSaveWorkspace = async () => {
- if (owner.queryClient.isMutating({ mutationKey: owner.key("workspace-settings-command"), exact: true })) return;
- const cleanSlug = sanitizeSlug(workspaceSlug);
- setWorkspaceSlug(cleanSlug);
- const values = { name: workspaceName.trim(), slug: cleanSlug };
- const nextErrors = validateWorkspaceForm(values);
- setWorkspaceErrors(nextErrors);
- if (hasWorkspaceFormErrors(nextErrors)) return;
- const assert = source.capture().assert;
- assert();
- try {
- const updated = await command.mutateAsync({ action: { kind: "update", ...values }, token: captureWorkspaceOwner(owner) });
- assert();
- trackSettingsUpdated({ setting_tab: "general" });
- setWorkspaceName((value) => value?.trim() === values.name ? null : value);
- setWorkspaceSlug((value) => value === cleanSlug ? null : value);
- toast.success("Workspace updated");
- if (updated && updated.slug !== slug) router.replace(`/w/${updated.slug}/settings`);
- } catch (error) {
- try { assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(error instanceof Error ? error.message : "Failed to update workspace");
- }
- };
-
- const handleDelete = async () => {
- if (owner.queryClient.isMutating({ mutationKey: owner.key("workspace-settings-command"), exact: true })) return;
- if (deleteConfirm !== savedWorkspaceName) return;
- const assert = source.capture().assert;
- assert();
- try {
- await command.mutateAsync({ action: { kind: "delete", name: savedWorkspaceName }, token: captureWorkspaceOwner(owner) });
- assert();
- toast.success("Workspace deleted");
- router.replace("/workspaces");
- } catch (error) {
- try { assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(error instanceof Error ? error.message : "Failed to delete workspace");
- }
- };
-
- if (membersQuery.isError || workspacesQuery.isError) {
- return <div role="alert" className="space-y-3"><p className="text-sm text-destructive">Could not load workspace settings.</p><Button size="sm" variant="outline" onClick={() => { if (membersQuery.isError) void membersQuery.refetch(); if (workspacesQuery.isError) void workspacesQuery.refetch(); }}>Retry</Button></div>;
- }
-
- if (loading) {
- return (
- <div className="space-y-4">
- <Skeleton className="h-4 w-32" />
- <Skeleton className="h-10 w-full" />
- <Skeleton className="h-10 w-full" />
- </div>
- );
- }
-
- if (!isOwner) {
- return (
- <p className="text-sm text-muted-foreground">
- Only workspace owners can edit workspace settings.
- </p>
- );
- }
-
- return (
- <div className="space-y-10">
- <section className="space-y-4">
- <h2 className="text-sm font-medium">Workspace</h2>
- <div className="space-y-3">
- <div className="space-y-2">
- <Label htmlFor="workspace-name">Name</Label>
- <Input
- id="workspace-name"
- value={workspaceName}
- onChange={(e) => {
- const nextName = e.target.value;
- setWorkspaceName(nextName);
- if (workspaceErrors.name && nextName.trim()) {
- setWorkspaceErrors((prev) => ({ ...prev, name: undefined }));
- }
- }}
- placeholder="Workspace name"
- aria-invalid={Boolean(workspaceErrors.name)}
- aria-describedby={workspaceErrors.name ? "workspace-name-error" : undefined}
- />
- {workspaceErrors.name && (
- <p id="workspace-name-error" className="text-xs text-destructive">
- {workspaceErrors.name}
- </p>
- )}
- </div>
- <div className="space-y-2">
- <Label htmlFor="workspace-slug">Slug</Label>
- <Input
- id="workspace-slug"
- value={workspaceSlug}
- onChange={(e) => {
- const nextSlug = e.target.value.toLowerCase().replace(/[^a-z0-9-]+/g, "-");
- setWorkspaceSlug(nextSlug);
- if (workspaceErrors.slug && nextSlug.trim()) {
- setWorkspaceErrors((prev) => ({ ...prev, slug: undefined }));
- }
- }}
- onBlur={() => setWorkspaceSlug(sanitizeSlug(workspaceSlug))}
- placeholder="workspace-slug"
- aria-invalid={Boolean(workspaceErrors.slug)}
- aria-describedby={workspaceErrors.slug ? "workspace-slug-error" : undefined}
- />
- {workspaceErrors.slug && (
- <p id="workspace-slug-error" className="text-xs text-destructive">
- {workspaceErrors.slug}
- </p>
- )}
- <p className="text-xs text-muted-foreground/70">
- Used in URLs: /w/{workspaceSlug}/
- </p>
- </div>
- </div>
- <Button
- size="sm"
- onClick={handleSaveWorkspace}
- disabled={!isWorkspaceDirty || savingWorkspace}
- >
- {savingWorkspace ? "Saving…" : "Save"}
- </Button>
- </section>
-
- <section className="space-y-4">
- <h2 className="text-sm font-medium text-destructive">Danger Zone</h2>
- <div className="rounded-md border border-destructive/30 p-4 space-y-3">
- <p className="text-sm text-muted-foreground">
- Deleting this workspace is permanent and cannot be undone. All agents,
- conversations, and data will be lost.
- </p>
- <div className="space-y-2">
- <Label htmlFor="delete-confirm" className="text-xs">
- Type <span className="font-medium text-foreground">{savedWorkspaceName}</span> to confirm
- </Label>
- <Input
- id="delete-confirm"
- value={deleteConfirm}
- onChange={(e) => setDeleteConfirm(e.target.value)}
- placeholder={savedWorkspaceName}
- />
- </div>
- <Button
- size="sm"
- variant="destructive"
- onClick={handleDelete}
- disabled={deleteConfirm !== savedWorkspaceName || deleting}
- >
- {deleting ? "Deleting…" : "Delete Workspace"}
- </Button>
- </div>
- </section>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx
deleted file mode 100644
index b78bea1e6..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { createStore, useSelector } from "@tanstack/react-store";
-import { useQuery, useMutation, type Query } from "@tanstack/react-query";
-import { useCallback, useEffect, useMemo, useLayoutEffect } from "react";
-import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import { isAbortError } from "@/lib/errors";
-import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { getMemberMe, updateMemberMe } from "@/lib/api";
-import { MarkdownEditor } from "@/components/ui/markdown-editor";
-import { Skeleton } from "@/components/ui/skeleton";
-import { cn } from "@/lib/utils";
-
-const MAX_LENGTH = 50_000;
-const DEBOUNCE_MS = 500;
-
-function UsageRing({ ratio, size = 16, stroke = 1.5 }: { ratio: number; size?: number; stroke?: number }) {
- const r = (size - stroke) / 2;
- const circ = 2 * Math.PI * r;
- const visual = ratio <= 0 ? 0 : ratio >= 1 ? 1 : Math.log1p(ratio * 99) / Math.log(100);
- const filled = visual * circ;
- return (
- <svg width={size} height={size} className="shrink-0 -rotate-90" aria-hidden>
- <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="currentColor" strokeWidth={stroke} className="text-border" />
- <circle
- cx={size / 2}
- cy={size / 2}
- r={r}
- fill="none"
- stroke="currentColor"
- strokeWidth={stroke}
- strokeDasharray={`${filled} ${circ - filled}`}
- strokeLinecap="round"
- className={cn(
- "transition-all duration-300",
- ratio > 0.9 ? "text-destructive/70" : ratio > 0.7 ? "text-yellow-500/50" : "text-muted-foreground/30"
- )}
- />
- </svg>
- );
-}
-
-export function InstructionTab() {
- const owner = useWorkspaceOwner();
- const { workspaceId } = owner;
- const source = useWorkspaceViewSource(owner, "workspace-instruction", true);
- const key = owner.key("member-instruction");
- const query = useQuery({ queryKey: key, queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => getMemberMe(workspaceId, options), signal) });
- useObservedQueryRegion("settings", query);
- type SaveIntent = { value: string; token: ReturnType<typeof captureWorkspaceOwner>; assertView: () => void; signal: AbortSignal; resource: Query | undefined };
- const draft = useMemo(() => {
- const draftKey = JSON.stringify(owner.key("instruction-draft"));
- const create = () => createStore<{ value: string | null; pending: SaveIntent | null }>({ value: null, pending: null });
- const saved = owner.application.preferences.get().localValues.get(draftKey) as ReturnType<typeof create> | undefined;
- if (saved) return saved;
- const store = create();
- owner.application.preferences.setState((state) => ({ ...state, localValues: new Map(state.localValues).set(draftKey, store) }));
- return store;
- }, [owner]);
- const edits = useSelector(draft, (state) => state);
- const value = edits.value ?? query.data?.global_instruction ?? "";
- const loading = query.isPending;
- const command = useMutation({ meta: { observabilityAction: "workspace.instruction.save" }, mutationKey: [...key, "command"], scope: { id: JSON.stringify(key) }, gcTime: 0,
- mutationFn: async ({ value, token, assertView, signal, resource: original }: SaveIntent) => {
- const assert = () => { assertWorkspaceOwner(token, signal); assertView(); };
- assert();
- if (original && owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === original) await owner.queryClient.cancelQueries({ queryKey: key, exact: true });
- assert();
- const before = original?.state.data as { global_instruction: string } | undefined;
- const writes = original?.state.dataUpdateCount;
- try {
- const data = await updateMemberMe(workspaceId, value, { ...workspaceRequestOptions(token, signal, assert), keepalive: true });
- assert();
- if (original && owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === original && original.state.dataUpdateCount === writes) {
- owner.queryClient.setQueryData<{ global_instruction: string }>(key, (current) => current?.global_instruction === before?.global_instruction ? data : current);
- }
- return data;
- } catch (error) { assert(); throw error; }
- },
- onSuccess: (_data, intent) => {
- try { intent.assertView(); } catch { return; }
- const confirmed = owner.queryClient.getQueryData<{ global_instruction: string }>(key)?.global_instruction;
- draft.setState((state) => state.value === intent.value && confirmed === intent.value ? { ...state, value: null } : state);
- },
- onError: (error, intent) => {
- try { intent.assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to save");
- },
- });
- const mutateInstruction = command.mutate;
- const flush = useCallback(() => {
- const intent = draft.get().pending;
- if (!intent) return;
- try { intent.assertView(); assertWorkspaceOwner(intent.token, intent.signal); } catch { return; }
- draft.setState((state) => state.pending === intent ? { ...state, pending: null } : state);
- mutateInstruction(intent);
- }, [draft, mutateInstruction]);
- useEffect(() => {
- if (!edits.pending) return;
- const timer = setTimeout(flush, DEBOUNCE_MS);
- return () => clearTimeout(timer);
- }, [edits.pending, flush]);
- const handleChange = (value: string) => {
- source.assertActive();
- draft.setState((state) => ({ value, pending: {
- value, token: state.pending?.token ?? captureWorkspaceOwner(owner), assertView: state.pending?.assertView ?? source.assertActive, signal: state.pending?.signal ?? source.signal, resource: state.pending?.resource ?? owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }),
- } }));
- };
- useEffect(() => {
- const onBeforeUnload = () => flush();
- window.addEventListener("beforeunload", onBeforeUnload);
- return () => window.removeEventListener("beforeunload", onBeforeUnload);
- }, [flush]);
- useLayoutEffect(() => () => draft.setState((state) => ({ ...state, pending: null })), [draft]);
- useEffect(() => {
- if (query.data?.global_instruction !== edits.value || edits.pending || command.isPending) return;
- draft.setState((state) => state.value === query.data?.global_instruction ? { ...state, value: null } : state);
- }, [query.data, edits.value, edits.pending, command.isPending, draft]);
-
- const ratio = value.length / MAX_LENGTH;
-
- if (loading) {
- return (
- <div className="px-6 py-6 space-y-4">
- <Skeleton className="h-4 w-48" />
- <Skeleton className="h-40 w-full" />
- </div>
- );
- }
-
- if (query.isError && !query.data) return <div role="alert" className="px-6 py-6 space-y-3">
- <p>Couldn’t load instructions.</p>
- <Button variant="outline" onClick={() => { source.assertActive(); void query.refetch({ cancelRefetch: false }); }}>Try again</Button>
- </div>;
-
- return (
- <div className="flex flex-col h-full">
- <div className="flex-1 px-6 pt-4 pb-4">
- <MarkdownEditor
- value={value}
- onChange={handleChange}
- placeholder="Write instructions that every agent you own will follow..."
- minHeight="calc(100vh - 240px)"
- contentType="markdown"
- variant="seamless"
- />
- </div>
- <div className="flex items-center gap-2 px-6 py-3">
- {edits.value !== null && !edits.pending && !command.isPending && <Button size="sm" variant="outline" onClick={() => { handleChange(value); }}>Save changes</Button>}
- <UsageRing ratio={ratio} />
- <p className="text-xs text-muted-foreground">
- This instruction is prepended to every agent&apos;s individual instruction.
- </p>
- </div>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/settings/members-tab.dom.test.ts b/src/web/src/app/(app)/w/[slug]/settings/members-tab.dom.test.ts
deleted file mode 100644
index 1793c13c9..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/members-tab.dom.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import "fake-indexeddb/auto"
-import React from "react"
-import { beforeEach, describe, expect, it, vi } from "vitest"
-import { render as renderLeaf, waitFor } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider } from "@/contexts/workspace-context"
-import { serializeBeamSeed } from "@/lib/avatar/seed-url"
-import { MembersTab } from "./members-tab"
-
-const render: typeof renderLeaf = (node, options) => renderLeaf(node, { ...options, wrapper: ({ children }) => React.createElement(ApplicationQueryProvider, { userId: "user_beam" }, React.createElement(WorkspaceProvider, { workspaceId: "workspace_1", slug: "workspace" }, children)) })
-
-const mocks = vi.hoisted(() => ({
- listMembers: vi.fn(),
- listInvites: vi.fn(),
- avatars: [] as Array<{ src?: string | null; seed?: string | null; size?: number }>,
-}))
-vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }) }))
-
-vi.mock("@/components/avatar", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@/components/avatar")>()
- return {
- ...actual,
- ProfileAvatar: (props: React.ComponentProps<typeof actual.ProfileAvatar>) => {
- mocks.avatars.push(props)
- return React.createElement(actual.ProfileAvatar, props)
- },
- }
-})
-
-vi.mock("@/contexts/workspace-context", async (importOriginal) => ({ ...await importOriginal<typeof import("@/contexts/workspace-context")>(),
- useWorkspace: () => ({ workspaceId: "workspace_1" }),
-}))
-
-vi.mock("@/lib/auth-client", () => { const sessionSDK = {
- useSession: () => ({ data: { user: { id: "user_beam" } } }),
-}; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-
-vi.mock("@/lib/api", () => ({
- listMembers: mocks.listMembers,
- listInvites: mocks.listInvites,
- removeMember: vi.fn(),
- createInvite: vi.fn(),
- revokeInvite: vi.fn(),
-}))
-
-vi.mock("@/lib/analytics", () => ({ trackTeamMemberInvited: vi.fn() }))
-vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }))
-vi.mock("@/components/ui/tooltip", () => ({
- Tooltip: ({ children }: React.PropsWithChildren) => React.createElement("div", null, children),
- TooltipTrigger: ({ children }: React.PropsWithChildren) => React.createElement("div", null, children),
- TooltipContent: ({ children }: React.PropsWithChildren) => React.createElement("span", null, children),
-}))
-
-describe("MembersTab avatars", () => {
- beforeEach(() => {
- mocks.avatars.length = 0
- mocks.listInvites.mockResolvedValue([])
- mocks.listMembers.mockResolvedValue([
- {
- id: "membership_1",
- user_id: "user_beam",
- role: "owner",
- name: "Beam User",
- email: "[email protected]",
- image: serializeBeamSeed("stored-face"),
- },
- {
- id: "membership_2",
- user_id: "user_photo",
- role: "member",
- name: "Photo User",
- email: "[email protected]",
- image: "https://cdn.example.com/photo.png",
- },
- {
- id: "membership_3",
- user_id: "user_generated",
- role: "member",
- name: "Generated User",
- email: "[email protected]",
- image: null,
- },
- ])
- })
-
- it("passes each member image and stable id through ProfileAvatar", async () => {
- const rendered = render(React.createElement(MembersTab))
-
- await waitFor(() => expect(mocks.avatars).toHaveLength(3))
- expect(mocks.avatars.map(({ src, seed, size }) => ({ src, seed, size }))).toEqual([
- { src: serializeBeamSeed("stored-face"), seed: "user_beam", size: 28 },
- { src: "https://cdn.example.com/photo.png", seed: "user_photo", size: 28 },
- { src: null, seed: "user_generated", size: 28 },
- ])
-
- expect(rendered.container.querySelectorAll('[data-avatar-kind="beam"]')).toHaveLength(2)
- expect(rendered.container.querySelector('[data-avatar-kind="photo"]')).toBeInTheDocument()
- })
-})
diff --git a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx
deleted file mode 100644
index 52f5c19b2..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx
+++ /dev/null
@@ -1,289 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-
-import { useQuery, useMutation, type Query } from "@tanstack/react-query";
-import { toast } from "sonner";
-import { Copy, Trash2, Plus, UserMinus } from "lucide-react";
-import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions } from "@/contexts/workspace-context";
-import { workspaceMembersOptions, workspaceInvitesOptions } from "@/hooks/workspace/settings-query-options";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { isAbortError } from "@/lib/errors";
-import { removeMember, createInvite, revokeInvite, type MemberEntry, type InviteEntry } from "@/lib/api";
-import { Button } from "@/components/ui/button";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { cn } from "@/lib/utils";
-import { trackTeamMemberInvited } from "@/lib/analytics";
-import { displayName } from "@/lib/community/display-name";
-import { ProfileAvatar } from "@/components/avatar";
-
-function getInviteLink(token: string) {
- return `${window.location.origin}/invite/${token}`;
-}
-
-export function MembersTab() {
- const owner = useWorkspaceOwner();
- const { workspaceId } = owner;
- const source = useWorkspaceViewSource(owner, "workspace-members", true);
- const currentUserId = owner.application.userId;
- const memberQuery = useQuery(workspaceMembersOptions(owner));
- const members = memberQuery.data ?? [];
- useObservedQueryRegion("settings", memberQuery, members.length);
- const isOwner = members.find((member) => member.user_id === currentUserId)?.role === "owner";
- const invitesQuery = useQuery({ ...workspaceInvitesOptions(owner), enabled: isOwner, subscribed: isOwner, gcTime: 0 });
- const invites = isOwner ? invitesQuery.data ?? [] : [];
- const loading = memberQuery.isPending || isOwner && invitesQuery.isPending;
- type OriginalIntent = { token: ReturnType<typeof captureWorkspaceOwner>; view: ReturnType<typeof source.capture>; resources: Query[] };
- const native = useMutation({ meta: { observabilityAction: "workspace.members.command" }, mutationKey: owner.key("workspace-members-command"), scope: { id: JSON.stringify(owner.key("workspace-members-command")) }, gcTime: 0,
- mutationFn: async ({ action, token, view, resources }: { action: { kind: "create-invite" } | { kind: "revoke-invite" | "remove-member"; id: string }; token: ReturnType<typeof captureWorkspaceOwner> } & OriginalIntent) => {
- const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert(); }, qc = owner.queryClient;
- const key = action.kind === "remove-member" ? workspaceMembersOptions(owner).queryKey : workspaceInvitesOptions(owner).queryKey;
- assert();
- const resource = resources.find((query) => JSON.stringify(query.queryKey) === JSON.stringify(key));
- if (resource && qc.getQueryCache().find({ queryKey: key, exact: true }) === resource) await qc.cancelQueries({ queryKey: key, exact: true });
- assert();
- const writes = resource?.state.dataUpdateCount;
- const qualified = () => resource && qc.getQueryCache().find({ queryKey: key, exact: true }) === resource && resource.state.dataUpdateCount === writes;
- const options = workspaceRequestOptions(token, view.signal, assert);
- let invite: InviteEntry | undefined;
- try {
- if (action.kind === "create-invite") {
- invite = await createInvite(workspaceId, options);
- assert();
- if (qualified()) { const row = invite; qc.setQueryData<InviteEntry[]>(key, (rows) => [...(rows ?? []).filter((entry) => entry.id !== row.id), row]); }
- } else if (action.kind === "revoke-invite") {
- await revokeInvite(workspaceId, action.id, options);
- assert();
- if (qualified()) qc.setQueryData<InviteEntry[]>(key, (rows) => rows?.filter((entry) => entry.id !== action.id));
- } else {
- await removeMember(workspaceId, action.id, options);
- assert();
- if (qualified()) qc.setQueryData<MemberEntry[]>(key, (rows) => rows?.filter((entry) => entry.id !== action.id));
- }
- assert();
- if (resource && qc.getQueryCache().find({ queryKey: key, exact: true }) === resource) await qc.invalidateQueries({ queryKey: key, exact: true }, { cancelRefetch: false });
- assert();
- return invite;
- } catch (error) { assert(); throw error; }
- },
- });
- const capture = (input: Omit<Parameters<typeof native.mutate>[0], "view" | "resources">) => { const view = source.capture(); view.assert(); assertWorkspaceOwner(input.token, view.signal); return { ...input, view, resources: [...new Set([workspaceMembersOptions(owner).queryKey, workspaceInvitesOptions(owner).queryKey].flatMap((queryKey) => owner.queryClient.getQueryCache().findAll({ queryKey, exact: true })))] }; };
- const command = { ...native, mutate: (input: Omit<Parameters<typeof native.mutate>[0], "view" | "resources">) => native.mutate(capture(input)), mutateAsync: (input: Omit<Parameters<typeof native.mutate>[0], "view" | "resources">) => native.mutateAsync(capture(input)) };
- const generatingInvite = command.isPending && command.variables?.action.kind === "create-invite";
- const handleGenerateInvite = async () => {
- if (owner.queryClient.isMutating({ mutationKey: owner.key("workspace-members-command"), exact: true })) return;
- const assertView = source.capture().assert;
- assertView();
- try {
- const invite = await command.mutateAsync({ action: { kind: "create-invite" }, token: captureWorkspaceOwner(owner) });
- assertView();
- if (!invite) return;
- trackTeamMemberInvited({ workspace_id: workspaceId });
- await navigator.clipboard.writeText(getInviteLink(invite.token));
- assertView();
- toast.success("Invite link copied to clipboard");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to generate invite");
- }
- };
- const handleCopyInvite = async (token: string) => {
- const assertView = source.capture().assert;
- assertView();
- try {
- await navigator.clipboard.writeText(getInviteLink(token));
- assertView();
- toast.success("Invite link copied");
- } catch {
- try { assertView(); } catch { return; }
- toast.error("Failed to copy link");
- }
- };
- const handleRevokeInvite = async (id: string) => {
- const assertView = source.capture().assert;
- assertView();
- try {
- await command.mutateAsync({ action: { kind: "revoke-invite", id }, token: captureWorkspaceOwner(owner) });
- assertView();
- toast.success("Invite revoked");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to revoke invite");
- }
- };
- const handleRemoveMember = async (id: string) => {
- const assertView = source.capture().assert;
- assertView();
- try {
- await command.mutateAsync({ action: { kind: "remove-member", id }, token: captureWorkspaceOwner(owner) });
- assertView();
- toast.success("Member removed");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to remove member");
- }
- };
-
-
- if (memberQuery.isError || isOwner && invitesQuery.isError) {
- return <div role="alert" className="space-y-3"><p className="text-sm text-destructive">Could not load workspace members.</p><Button size="sm" variant="outline" onClick={() => { if (memberQuery.isError) void memberQuery.refetch(); if (isOwner && invitesQuery.isError) void invitesQuery.refetch(); }}>Retry</Button></div>;
- }
-
- if (loading) {
- return (
- <div className="space-y-4">
- <Skeleton className="h-4 w-24" />
- <Skeleton className="h-10 w-full" />
- <Skeleton className="h-10 w-full" />
- <Skeleton className="h-4 w-24 mt-6" />
- <Skeleton className="h-10 w-full" />
- <Skeleton className="h-10 w-full" />
- </div>
- );
- }
-
- return (
- <div className="space-y-8">
- {/* Pending invites — owner only */}
- {isOwner && (
- <section className="space-y-3">
- <div className="flex items-center justify-between">
- <h2 className="text-sm font-medium">Pending Invites</h2>
- <Button
- size="sm"
- variant="outline"
- onClick={handleGenerateInvite}
- disabled={generatingInvite}
- >
- <Plus className="size-3.5 mr-1" />
- {generatingInvite ? "Generating…" : "Generate invite link"}
- </Button>
- </div>
-
- {invites.length === 0 ? (
- <p className="text-xs text-muted-foreground py-2">
- No active invite links. Generate one to invite someone to this workspace.
- </p>
- ) : (
- <div className="space-y-2">
- {invites.map((invite) => {
- const expiresAt = new Date(invite.expires_at);
- const isExpired = expiresAt < new Date();
- return (
- <div
- key={invite.id}
- className="flex items-center justify-between rounded-md border border-border/50 px-3 py-2 text-xs"
- >
- <div className="min-w-0 flex-1">
- <p className={cn("font-mono truncate", isExpired && "text-muted-foreground line-through")}>
- /invite/{invite.token.slice(0, 12)}…
- </p>
- <p className={cn("text-muted-foreground/70 mt-1", isExpired && "text-destructive/70")}>
- {isExpired
- ? "Expired"
- : `Expires ${expiresAt.toLocaleDateString()}`}
- </p>
- </div>
- <div className="flex items-center gap-1 ml-2 shrink-0">
- {!isExpired && (
- <Tooltip>
- <TooltipTrigger render={<Button
- size="sm"
- variant="ghost"
- className="h-7 w-7 p-0"
- onClick={() => handleCopyInvite(invite.token)}
- />}>
- <Copy className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Copy invite link</TooltipContent>
- </Tooltip>
- )}
- <Tooltip>
- <TooltipTrigger render={<Button
- size="sm"
- variant="ghost"
- className="h-7 w-7 p-0 text-destructive hover:text-destructive"
- onClick={() => handleRevokeInvite(invite.id)}
- />}>
- <Trash2 className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Revoke invite</TooltipContent>
- </Tooltip>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </section>
- )}
-
- {/* Member list */}
- <section className="space-y-3">
- <h2 className="text-sm font-medium">Members</h2>
- <div className="space-y-2">
- {members.map((member) => {
- const isSelf = member.user_id === currentUserId;
-
- return (
- <div
- key={member.id}
- className="flex items-center gap-3 rounded-md border border-border/50 px-3 py-2"
- >
- <ProfileAvatar
- label={displayName(member)}
- seed={member.user_id}
- src={member.image}
- size={28}
- data-testid={`members-avatar-${member.user_id}`}
- />
-
- {/* Name / email */}
- <div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate leading-tight">
- {displayName(member)}
- {isSelf && (
- <span className="ml-2 text-xs text-muted-foreground font-normal">(you)</span>
- )}
- </p>
- {member.name && (
- <p className="text-xs text-muted-foreground truncate">{member.email}</p>
- )}
- </div>
-
- {/* Role badge */}
- <span
- className={cn(
- "text-xs px-2 py-1 rounded shrink-0",
- member.role === "owner"
- ? "bg-primary/10 text-primary"
- : "bg-muted text-muted-foreground"
- )}
- >
- {member.role}
- </span>
-
- {/* Remove button — owner only, not on self */}
- {isOwner && !isSelf && (
- <Tooltip>
- <TooltipTrigger render={<Button
- size="sm"
- variant="ghost"
- className="h-7 w-7 p-0 text-muted-foreground hover:text-destructive shrink-0"
- onClick={() => handleRemoveMember(member.id)}
- />}>
- <UserMinus className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Remove member</TooltipContent>
- </Tooltip>
- )}
- </div>
- );
- })}
- </div>
- </section>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx
deleted file mode 100644
index 4ac7e2b38..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-"use client";
-import { useObservedRegion } from "@/lib/observability/regions";
-import { mergeEvidence, sourceEvidence, valueEvidence } from "@/lib/observability/data-source";
-
-import { useSelector } from "@tanstack/react-store";
-import { useQuery, useMutation } from "@tanstack/react-query";
-import { applicationKey, useApplicationOwner } from "@/lib/application-owner";
-import { useApplicationViewSource } from "@/hooks/use-application-view-source";
-import { toast } from "sonner";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Switch } from "@/components/ui/switch";
-import { isNotificationSupported, setNotificationEnabled, setNotificationEvents, requestNotificationPermission, NOTIFICATION_EVENTS, NOTIFICATION_EVENT_LABELS, type NotificationEvent } from "@/lib/browser-notification";
-
-export function NotificationTab() {
- const owner = useApplicationOwner();
- const source = useApplicationViewSource("workspace-notifications");
- const preferences = useSelector(owner.preferences, (state) => state.browserNotifications);
- const notifEnabled = preferences.enabled;
- const notifEvents = preferences.events;
- const permission = useQuery({
- queryKey: applicationKey(owner, "browser-notification-permission"),
- queryFn: () => ({ supported: isNotificationSupported(), denied: isNotificationSupported() && Notification.permission === "denied" }),
- staleTime: 0,
- });
- const notifSupported = permission.data?.supported ?? true;
- const notifDenied = permission.data?.denied ?? false;
- useObservedRegion("settings", !permission.isPending, { ...mergeEvidence([sourceEvidence(preferences, "unknown"), valueEvidence(owner.queryClient, permission.data)]), count: 1 });
- const command = useMutation({ meta: { observabilityAction: "notification.permission.request" }, mutationKey: applicationKey(owner, "browser-notification-permission", "request"),
- mutationFn: async (original: ReturnType<typeof source.capture>) => {
- original.assert();
- const granted = await requestNotificationPermission();
- original.assert();
- owner.queryClient.setQueryData(applicationKey(owner, "browser-notification-permission"), { supported: isNotificationSupported(), denied: !granted });
- if (granted) {
- setNotificationEnabled(true, owner.userId);
- owner.preferences.setState((state) => ({ ...state, browserNotifications: { ...state.browserNotifications, enabled: true } }));
- }
- return granted;
- },
- });
-
- const handleToggleNotification = async (checked: boolean) => {
- const original = source.capture();
- original.assert();
- if (!checked) {
- setNotificationEnabled(false, owner.userId);
- owner.preferences.setState((state) => ({ ...state, browserNotifications: { ...state.browserNotifications, enabled: false } }));
- return;
- }
- try {
- const granted = await command.mutateAsync(original);
- original.assert();
- if (!granted) toast.error("Notification permission denied. Please enable it in browser settings.");
- } catch (error) {
- try { original.assert(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(error instanceof Error ? error.message : "Failed to enable notifications");
- }
- };
-
- const handleToggleEvent = (event: NotificationEvent) => {
- source.capture().assert();
- const current = owner.preferences.get().browserNotifications;
- const events = current.events.includes(event) ? current.events.filter((value) => value !== event) : [...current.events, event];
- setNotificationEvents(events, owner.userId);
- owner.preferences.setState((state) => ({ ...state, browserNotifications: { ...state.browserNotifications, events } }));
- };
-
- if (!notifSupported) {
- return (
- <p className="text-sm text-muted-foreground">
- Your browser does not support notifications.
- </p>
- );
- }
-
- return (
- <div className="space-y-6">
- <section className="space-y-4">
- <h2 className="text-sm font-medium">Browser Notifications</h2>
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <p className="text-sm">Enable notifications</p>
- <p className="text-xs text-muted-foreground">
- Get notified when tasks finish while the tab is in the background
- </p>
- </div>
- <Switch
- checked={notifEnabled}
- onCheckedChange={handleToggleNotification}
- disabled={command.isPending || (notifDenied && !notifEnabled)}
- />
- </div>
- {notifDenied && !notifEnabled && (
- <p className="text-xs text-destructive">
- Notification permission was denied. Please allow it in your browser settings.
- </p>
- )}
- {notifEnabled && (
- <div className="space-y-2 pl-0.5">
- <p className="text-xs text-muted-foreground">Notify me when:</p>
- {NOTIFICATION_EVENTS.map((event) => (
- <label key={event} className="flex items-center gap-2 text-sm cursor-pointer select-none">
- <Checkbox
- checked={notifEvents.includes(event)}
- onCheckedChange={() => handleToggleEvent(event)}
- />
- {NOTIFICATION_EVENT_LABELS[event]}
- </label>
- ))}
- </div>
- )}
- </div>
- </section>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/settings/page.tsx b/src/web/src/app/(app)/w/[slug]/settings/page.tsx
deleted file mode 100644
index 5d9afbd8d..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/page.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-
-
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { cn } from "@/lib/utils";
-import { GeneralTab } from "./general-tab";
-import { InstructionTab } from "./instruction-tab";
-import { MembersTab } from "./members-tab";
-import { NotificationTab } from "./notification-tab";
-import { PetTab } from "./pet-tab";
-import { UsagesTab } from "./usages-tab";
-
-const TABS = [
- { id: "general", label: "General" },
- { id: "pet", label: "Pet" },
- { id: "instruction", label: "Global Instruction" },
- { id: "notifications", label: "Notifications" },
- { id: "members", label: "Members" },
- { id: "usages", label: "Usages" },
-] as const;
-
-type TabId = (typeof TABS)[number]["id"];
-
-export default function SettingsPage() {
- const [activeTab, setActiveTab] = useAtom(useCreateAtom<TabId>("general"));
-
- return (
- <>
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2 gap-3">
- <div className="flex items-center gap-3 min-w-0">
- <h1 className="text-sm font-medium">Settings</h1>
- </div>
- </div>
-
- <div className="flex flex-1 min-h-0">
- <nav className="w-48 shrink-0 border-r border-border/50 py-3 px-2 hidden sm:flex sm:flex-col">
- <div className="flex-1">
- {TABS.map((tab) => (
- <button
- key={tab.id}
- onClick={() => setActiveTab(tab.id)}
- className={cn(
- "w-full rounded-md px-2 py-2 text-left text-sm transition-colors",
- activeTab === tab.id
- ? "bg-accent text-foreground font-medium"
- : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
- )}
- >
- {tab.label}
- </button>
- ))}
- </div>
- {process.env.NEXT_PUBLIC_APP_VERSION && (
- <div className="px-2 pt-3 border-t border-border/50 text-[11px] text-muted-foreground/60">
- v{process.env.NEXT_PUBLIC_APP_VERSION}
- </div>
- )}
- </nav>
-
- <div className="flex-1 min-w-0 flex flex-col">
- <div className="px-4 pt-2 sm:hidden">
- <Tabs className="items-center" value={activeTab} onValueChange={(v) => setActiveTab(v as TabId)}>
- <TabsList className="h-auto gap-1">
- {TABS.map((tab) => (
- <TabsTrigger key={tab.id} value={tab.id}>
- {tab.label}
- </TabsTrigger>
- ))}
- </TabsList>
- </Tabs>
- </div>
-
- <div className={cn(
- "flex-1 overflow-y-auto thin-scrollbar",
- activeTab !== "instruction" && "px-4 py-4"
- )}>
- {activeTab === "instruction" ? (
- <InstructionTab />
- ) : activeTab === "usages" ? (
- <UsagesTab />
- ) : (
- <div className="mx-auto max-w-md">
- {activeTab === "general" && <GeneralTab />}
- {activeTab === "pet" && <PetTab />}
- {activeTab === "notifications" && <NotificationTab />}
- {activeTab === "members" && <MembersTab />}
- </div>
- )}
- </div>
- {process.env.NEXT_PUBLIC_APP_VERSION && (
- <div className="px-4 py-2 text-[11px] text-muted-foreground/60 sm:hidden">
- v{process.env.NEXT_PUBLIC_APP_VERSION}
- </div>
- )}
- </div>
- </div>
- </>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx
deleted file mode 100644
index 3cadca0e8..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-"use client";
-import { useMemo } from "react";
-import { useObservedRegion } from "@/lib/observability/regions";
-import { sourceEvidence } from "@/lib/observability/data-source";
-
-import { Sparkles } from "lucide-react";
-
-import {
- CLOUD_CODE_MONSTER_PET_PRESETS,
- getCloudCodeMonsterPreset,
- useCloudCodeMonsterPetPresetId,
- writeCloudCodeMonsterPetPresetId,
-} from "@/components/home-pet/cloud-code-monster-pet-presets";
-import { CloudCodeMonsterPresetPreview } from "@/components/home-pet/cloud-code-monster-pet-pixel-parts";
-import { Label } from "@/components/ui/label";
-import { Switch } from "@/components/ui/switch";
-import {
- useHomePetSettings,
- writeHomePetSettings,
-} from "@/lib/home-pet-settings";
-import { cn } from "@/lib/utils";
-
-export function PetTab() {
- const { enabled } = useHomePetSettings();
- const selectedPresetId = useCloudCodeMonsterPetPresetId();
- const selectedPreset = getCloudCodeMonsterPreset(selectedPresetId);
- const observedPreferences = useMemo(() => ({ enabled, selectedPresetId }), [enabled, selectedPresetId]);
- useObservedRegion("settings", true, sourceEvidence(observedPreferences, "unknown"));
- const handleEnabledChange = (checked: boolean) => writeHomePetSettings({ enabled: checked });
-
- return (
- <div className="space-y-8">
- <section className="space-y-4">
- <h2 className="text-sm font-medium">Pet</h2>
- <div className="space-y-4">
- <div className="flex items-center justify-between gap-4">
- <div className="space-y-1">
- <Label htmlFor="pet-enabled" className="text-sm">
- Enable pet
- </Label>
- <p className="text-xs text-muted-foreground">
- Off by default. Turn it on when you want the workspace companion.
- </p>
- </div>
- <Switch
- id="pet-enabled"
- checked={enabled}
- onCheckedChange={handleEnabledChange}
- />
- </div>
- </div>
- </section>
-
- {enabled ? (
- <section className="space-y-4">
- <div className="flex items-center justify-between gap-3">
- <div>
- <h2 className="text-sm font-medium">Preset</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- {selectedPreset.name}
- </p>
- </div>
- <div className="grid size-14 place-items-center rounded-md bg-card ring-1 ring-border/60">
- <CloudCodeMonsterPresetPreview
- preset={selectedPreset}
- className="size-11"
- />
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
- {CLOUD_CODE_MONSTER_PET_PRESETS.map((preset) => {
- const isSelected = preset.id === selectedPreset.id;
-
- return (
- <button
- key={preset.id}
- type="button"
- aria-pressed={isSelected}
- onClick={() => {
- writeCloudCodeMonsterPetPresetId(
- preset.id
- );
- }}
- className={cn(
- "group grid h-28 min-w-0 grid-rows-[1fr_auto] rounded-md border bg-card/60 p-2 text-left transition-all hover:border-foreground/20 hover:bg-accent/55 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70",
- isSelected
- ? "border-primary/50 bg-accent text-foreground"
- : "border-border/50 text-muted-foreground"
- )}
- >
- <div className="grid place-items-center rounded bg-background/70 ring-1 ring-border/35">
- <CloudCodeMonsterPresetPreview
- preset={preset}
- className="size-14 transition-transform duration-200 group-hover:scale-105"
- />
- </div>
- <div className="mt-2 flex min-w-0 items-center justify-between gap-1 text-[10px] leading-none">
- <span className="truncate font-medium text-foreground">
- {preset.name}
- </span>
- {isSelected ? (
- <Sparkles className="size-3 shrink-0 text-primary" />
- ) : (
- <span className="shrink-0 text-muted-foreground">
- {preset.id.replace("pet-", "#")}
- </span>
- )}
- </div>
- </button>
- );
- })}
- </div>
- </section>
- ) : null}
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/settings/usages-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/usages-tab.tsx
deleted file mode 100644
index 85547683b..000000000
--- a/src/web/src/app/(app)/w/[slug]/settings/usages-tab.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions";
-
-import { useQuery } from "@tanstack/react-query";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceOwner, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { Skeleton } from "@/components/ui/skeleton";
-import { getWorkspaceOverview } from "@/lib/api";
-import { QuickStatsRow } from "../home/_components/quick-stats";
-import { TaskHealth } from "../home/_components/task-health";
-import { EmailSummary } from "../home/_components/email-summary";
-import { RuntimeHealth } from "../home/_components/runtime-health";
-import { TeamAccess } from "../home/_components/team-access";
-
-export function UsagesTab() {
- const { agents, runtimes, loading, activeTaskCounts } = useAgentContext();
- const owner = useWorkspaceOwner();
- const overviewQuery = useQuery({ queryKey: owner.key("overview"), enabled: !loading,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => getWorkspaceOverview(owner.workspaceId, options), signal),
- });
- useObservedQueryRegion("settings", overviewQuery);
- const overview = overviewQuery.data;
- const overviewLoading = overviewQuery.isPending;
-
- if (overviewLoading || !overview) {
- return (
- <div className="space-y-4">
- <Skeleton className="h-44 rounded-xl" />
- <Skeleton className="h-44 rounded-xl" />
- <Skeleton className="h-44 rounded-xl" />
- <Skeleton className="h-44 rounded-xl" />
- </div>
- );
- }
-
- return (
- <div className="space-y-4">
- <QuickStatsRow
- agents={agents}
- runtimes={runtimes}
- activeTaskCounts={activeTaskCounts}
- overview={overview}
- />
- <div className="grid gap-4 lg:grid-cols-2">
- <TaskHealth overview={overview} />
- <EmailSummary overview={overview} agents={agents} />
- </div>
- <div className="grid gap-4 lg:grid-cols-2">
- <RuntimeHealth runtimes={runtimes} agents={agents} />
- <TeamAccess overview={overview} />
- </div>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx
deleted file mode 100644
index 9b0ccd0e2..000000000
--- a/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx
+++ /dev/null
@@ -1,223 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useEffect } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { workspaceTraceOptions } from "@/hooks/workspace/issue-query-options";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { useParams } from "next/navigation";
-import Link from "next/link";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import type { TraceTask } from "@/lib/api";
-import { trackThreadViewed } from "@/lib/analytics";
-import { Skeleton } from "@/components/ui/skeleton";
-import { ArrowLeft } from "lucide-react";
-import { AgentAvatar } from "@/components/avatar";
-
-function relativeTime(dateStr: string): string {
- const date = new Date(dateStr);
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMin = Math.floor(diffMs / 60000);
- if (diffMin < 1) return "just now";
- if (diffMin < 60) return `${diffMin}m ago`;
- const diffHrs = Math.floor(diffMin / 60);
- if (diffHrs < 24) return `${diffHrs}h ago`;
- const diffDays = Math.floor(diffHrs / 24);
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
-}
-
-function formatDuration(createdAt: string, completedAt: string | null): string | null {
- if (!completedAt) return null;
- const ms = new Date(completedAt).getTime() - new Date(createdAt).getTime();
- const totalSeconds = Math.max(0, Math.floor(ms / 1000));
- if (totalSeconds >= 3600) {
- const h = Math.floor(totalSeconds / 3600);
- const m = Math.floor((totalSeconds % 3600) / 60);
- return `${h}h ${m}m`;
- }
- if (totalSeconds >= 60) {
- const m = Math.floor(totalSeconds / 60);
- const s = totalSeconds % 60;
- return `${m}m ${s}s`;
- }
- return `${totalSeconds}s`;
-}
-
-function StatusDot({ status }: { status: string }) {
- const colorClass =
- status === "completed"
- ? "bg-[oklch(0.72_0.19_145)]"
- : status === "failed"
- ? "bg-destructive"
- : status === "running"
- ? "bg-primary animate-pulse"
- : "bg-muted-foreground/40";
- return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;
-}
-
-const STATUS_LABELS: Record<string, string> = {
- queued: "Queued",
- dispatched: "Queued",
- running: "Running",
- completed: "Completed",
- failed: "Failed",
- cancelled: "Cancelled",
- superseded: "Cancelled",
-};
-
-interface TreeNode extends TraceTask {
- children: TreeNode[];
- depth: number;
-}
-
-function buildTree(tasks: TraceTask[]): TreeNode[] {
- const nodeMap = new Map<string, TreeNode>();
- for (const t of tasks) {
- nodeMap.set(t.id, { ...t, children: [], depth: 0 });
- }
-
- const roots: TreeNode[] = [];
- for (const node of nodeMap.values()) {
- if (node.parent_task_id && nodeMap.has(node.parent_task_id)) {
- const parent = nodeMap.get(node.parent_task_id)!;
- parent.children.push(node);
- } else {
- roots.push(node);
- }
- }
-
- function setDepth(node: TreeNode, depth: number) {
- node.depth = depth;
- for (const child of node.children) {
- setDepth(child, depth + 1);
- }
- }
- for (const root of roots) setDepth(root, 0);
-
- return roots;
-}
-
-function flattenTree(nodes: TreeNode[]): TreeNode[] {
- const result: TreeNode[] = [];
- function walk(node: TreeNode) {
- result.push(node);
- for (const child of node.children) walk(child);
- }
- for (const n of nodes) walk(n);
- return result;
-}
-
-function TaskNode({ node, slug }: { node: TreeNode; slug: string }) {
- const duration = formatDuration(node.created_at, node.completed_at);
-
- return (
- <Link
- href={`/w/${slug}/agents/${node.agent_id}?task=${node.id}&conv=${node.conversation_id}`}
- className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
- style={{ paddingLeft: `${1 + node.depth * 1.5}rem` }}
- >
- <div className="flex items-center gap-2">
- <AgentAvatar name={node.agent?.name} avatarUrl={node.agent?.avatarUrl} seed={node.agent_id} size={32} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 min-w-0">
- <span className="text-sm text-foreground truncate flex-1 min-w-0">
- {node.prompt.split("\n")[0]}
- </span>
- <Tooltip>
- <TooltipTrigger render={<span className="text-xs text-muted-foreground shrink-0 ml-2" />}>
- {relativeTime(node.created_at)}
- </TooltipTrigger>
- <TooltipContent>{new Date(node.created_at).toLocaleString()}</TooltipContent>
- </Tooltip>
- </div>
- <div className="flex items-center gap-2">
- {node.agent?.name && (
- <>
- <span className="text-xs font-medium text-muted-foreground">{node.agent.name}</span>
- <span className="text-muted-foreground/40">&middot;</span>
- </>
- )}
- <StatusDot status={node.status} />
- <span className="text-xs text-muted-foreground">{STATUS_LABELS[node.status] ?? node.status}</span>
- {duration && (
- <>
- <span className="text-muted-foreground/40">&middot;</span>
- <span className="text-xs text-muted-foreground">{duration}</span>
- </>
- )}
- </div>
- </div>
- </div>
- </Link>
- );
-}
-
-export default function TraceDetailPage() {
- const params = useParams();
- const owner = useWorkspaceOwner();
- const { slug } = owner;
- const traceId = params.traceId as string;
- const source = useWorkspaceViewSource(owner, traceId, true);
- const resource = useQuery(workspaceTraceOptions(owner, traceId));
- useObservedQueryRegion("trace_detail", resource);
- const tasks = resource.data?.tasks ?? [];
- const channel = resource.data?.channel ?? "default";
- const loading = resource.isPending;
- useEffect(() => {
- if (!resource.data) return;
- try { source.assertActive() } catch { return; }
- const agentIds = new Set(resource.data.tasks.map((task) => task.agent_id));
- const rootStatus = resource.data.tasks.find((task) => !task.parent_task_id)?.status ?? "unknown";
- trackThreadViewed({ agent_count: agentIds.size, status: rootStatus });
- }, [resource.data, resource.dataUpdatedAt, source, source.assertActive]);
-
- const tree = buildTree(tasks);
- const flat = flattenTree(tree);
-
- return (
- <div className="flex flex-col h-full">
- <div className="sticky top-0 z-10 flex items-center gap-2 px-4 py-2 border-b border-border/30">
- <Link
- href={`/w/${slug}/traces`}
- className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors"
- >
- <ArrowLeft className="size-3.5" />
- </Link>
- <span className="text-xs text-muted-foreground">#{channel}</span>
- </div>
-
- <div className="flex-1 overflow-y-auto thin-scrollbar">
- {loading ? (
- <div className="flex flex-col">
- {[40, 55, 48].map((w, i) => (
- <div key={i} className="px-4 py-3 border-b border-border/30">
- <div className="flex items-center gap-2">
- <Skeleton className="h-3.5 w-4 rounded-full shrink-0" />
- <Skeleton className="h-3.5 rounded" style={{ width: `${w}%` }} />
- <Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" />
- </div>
- <div className="flex items-center gap-2 mt-1 ml-6">
- <Skeleton className="h-2.5 w-20 rounded-full" />
- </div>
- </div>
- ))}
- </div>
- ) : flat.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full">
- <p className="text-sm text-muted-foreground">Trace not found</p>
- </div>
- ) : (
- <div className="flex flex-col animate-[fade-up_400ms_ease-out_both]">
- {flat.map((node) => (
- <TaskNode key={node.id} node={node} slug={slug} />
- ))}
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/traces/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/page.tsx
deleted file mode 100644
index 3d3e17e0a..000000000
--- a/src/web/src/app/(app)/w/[slug]/traces/page.tsx
+++ /dev/null
@@ -1,315 +0,0 @@
-"use client";
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useCallback, useRef } from "react";
-import { useInfiniteQuery } from "@tanstack/react-query";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { workspaceTracesOptions } from "@/hooks/workspace/trace-query-options";
-import { useRouter, useSearchParams } from "next/navigation";
-import Link from "next/link";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { useChannel } from "@/contexts/channel-context";
-import type { TraceListItem } from "@/lib/api";
-import { Skeleton } from "@/components/ui/skeleton";
-import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectContent,
- SelectItem,
-} from "@/components/ui/select";
-import { GitBranch, RefreshCw } from "lucide-react";
-import { AgentAvatar } from "@/components/avatar";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-
-const STATUS_OPTIONS = [
- { label: "All", value: "all" },
- { label: "Active", value: "active" },
- { label: "Completed", value: "completed" },
- { label: "Failed", value: "failed" },
-];
-
-function relativeTime(dateStr: string): string {
- const date = new Date(dateStr);
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMin = Math.floor(diffMs / 60000);
- if (diffMin < 1) return "just now";
- if (diffMin < 60) return `${diffMin}m ago`;
- const diffHrs = Math.floor(diffMin / 60);
- if (diffHrs < 24) return `${diffHrs}h ago`;
- const diffDays = Math.floor(diffHrs / 24);
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
-}
-
-function formatDuration(startedAt: string, completedAt: string | null): string | null {
- if (!completedAt) return null;
- const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime();
- const totalSeconds = Math.max(0, Math.floor(ms / 1000));
- if (totalSeconds >= 3600) {
- const h = Math.floor(totalSeconds / 3600);
- const m = Math.floor((totalSeconds % 3600) / 60);
- return `${h}h ${m}m`;
- }
- if (totalSeconds >= 60) {
- const m = Math.floor(totalSeconds / 60);
- const s = totalSeconds % 60;
- return `${m}m ${s}s`;
- }
- return `${totalSeconds}s`;
-}
-
-function StatusDot({ status }: { status: string }) {
- const colorClass =
- status === "completed"
- ? "bg-[oklch(0.72_0.19_145)]"
- : status === "failed"
- ? "bg-destructive"
- : status === "active"
- ? "bg-primary animate-pulse"
- : "bg-muted-foreground/40";
- return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;
-}
-
-function TraceRow({ trace, slug }: { trace: TraceListItem; slug: string }) {
- const duration = formatDuration(trace.started_at, trace.completed_at);
- const statusLabel = trace.status === "active" ? "Active" : trace.status === "failed" ? "Failed" : "Completed";
-
- return (
- <Link
- href={`/w/${slug}/traces/${trace.trace_id}`}
- className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
- >
- <div className="flex items-center gap-2">
- <AgentAvatar name={trace.root_agent?.name} avatarUrl={trace.root_agent?.avatarUrl} size={32} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 min-w-0">
- <span className="text-sm text-foreground truncate flex-1 min-w-0">
- {trace.root_prompt.split("\n")[0]}
- </span>
- <Tooltip>
- <TooltipTrigger render={<span className="text-xs text-muted-foreground shrink-0 ml-2" />}>
- {relativeTime(trace.started_at)}
- </TooltipTrigger>
- <TooltipContent>{new Date(trace.started_at).toLocaleString()}</TooltipContent>
- </Tooltip>
- </div>
- <div className="flex items-center gap-2">
- {trace.root_agent?.name && (
- <>
- <span className="text-xs font-medium text-muted-foreground">{trace.root_agent.name}</span>
- <span className="text-muted-foreground/40">&middot;</span>
- </>
- )}
- <span className="text-xs text-muted-foreground">#{trace.channel}</span>
- <span className="text-muted-foreground/40">&middot;</span>
- <StatusDot status={trace.status} />
- <span className="text-xs text-muted-foreground">{statusLabel}</span>
- {duration && (
- <>
- <span className="text-muted-foreground/40">&middot;</span>
- <span className="text-xs text-muted-foreground">{duration}</span>
- </>
- )}
- {trace.helper_agents.length > 0 && (
- <>
- <span className="text-muted-foreground/40">&middot;</span>
- <span className="flex items-center">
- {trace.helper_agents.map((h, i) => (
- <span key={h.id} className={i > 0 ? "-ml-1" : ""}>
- <AgentAvatar name={h.name} avatarUrl={h.avatarUrl} seed={h.id} />
- </span>
- ))}
- </span>
- </>
- )}
- </div>
- </div>
- </div>
- </Link>
- );
-}
-
-function SkeletonRow({ promptWidth }: { promptWidth: string }) {
- return (
- <div className="px-4 py-3 border-b border-border/30">
- <div className="flex items-center gap-2">
- <Skeleton className="h-3.5 w-4 rounded-full shrink-0" />
- <Skeleton className="h-3.5 rounded" style={{ width: promptWidth }} />
- <Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" />
- </div>
- <div className="flex items-center gap-2 mt-1 ml-6">
- <Skeleton className="h-2.5 w-20 rounded-full" />
- <Skeleton className="h-2.5 w-8 rounded" />
- </div>
- </div>
- );
-}
-
-export default function TracesPage() {
- const router = useRouter();
- const searchParams = useSearchParams();
- const owner = useWorkspaceOwner();
- const { slug } = owner;
- const { channels } = useChannel();
- const { agents } = useAgentContext();
- const scrollRef = useRef<HTMLDivElement>(null);
- const statusFilter = searchParams.get("status") ?? "active";
- const agentFilter = searchParams.get("agentId") ?? "";
- const channelFilter = searchParams.get("channel") ?? "";
- const source = useWorkspaceViewSource(owner, JSON.stringify([statusFilter, agentFilter, channelFilter]), true);
- const resource = useInfiniteQuery(workspaceTracesOptions(owner, { status: statusFilter, agentId: agentFilter, channel: channelFilter }));
- const seen = new Set<string>();
- const traces = (resource.data?.pages ?? []).flatMap((page) => page.traces).filter((trace) => {
- if (seen.has(trace.trace_id)) return false;
- seen.add(trace.trace_id); return true;
- });
- const loading = resource.isPending;
- useObservedQueryRegion("traces", resource, traces.length);
- const hasMore = resource.hasNextPage;
- const loadingMore = resource.isFetchingNextPage;
- const loadInitial = async () => {
- try { source.assertActive(); await resource.refetch(); } catch {}
- };
- const loadOlderTraces = async () => {
- try { source.assertActive(); await resource.fetchNextPage({ cancelRefetch: false }); } catch {}
- };
- const handleScroll = () => {
- const el = scrollRef.current;
- if (el && !loadingMore && hasMore && el.scrollHeight - el.scrollTop - el.clientHeight < 200) void loadOlderTraces();
- };
-
- const updateFilter = useCallback(
- (key: string, value: string) => {
- const newParams = new URLSearchParams(searchParams.toString());
- if (value) {
- newParams.set(key, value);
- } else {
- newParams.delete(key);
- }
- const pathname = `/w/${slug}/traces`;
- const qs = newParams.toString();
- router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
- },
- [router, slug, searchParams]
- );
-
- return (
- <div className="flex flex-col h-full">
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2 gap-3">
- <div className="flex items-center gap-3 min-w-0">
- <h1 className="text-sm font-medium">Traces</h1>
- <p className="text-xs text-muted-foreground hidden sm:block">
- Execution traces across your agents.
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={loadInitial}
- className="text-muted-foreground"
- />
- }
- >
- <RefreshCw className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>Refresh</TooltipContent>
- </Tooltip>
- </div>
- </div>
-
- <div className="flex items-center gap-2 px-4 py-2">
- <Select value={statusFilter} onValueChange={(v) => updateFilter("status", v ?? "")}>
- <SelectTrigger className="w-35 border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
- <SelectValue placeholder="Status: All" />
- </SelectTrigger>
- <SelectContent>
- {STATUS_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label === "All" ? "Status: All" : opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- <Select value={agentFilter} onValueChange={(v) => updateFilter("agentId", v ?? "")}>
- <SelectTrigger className="w-40 border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
- {agentFilter ? agents.find((a) => a.id === agentFilter)?.name ?? agentFilter : "Agent: All"}
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">Agent: All</SelectItem>
- {agents.map((a) => (
- <SelectItem key={a.id} value={a.id}>
- <span className="flex items-center gap-2">
- <AgentAvatar name={a.name} avatarUrl={a.avatar_url} seed={a.id} />
- {a.name}
- </span>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
-
- <Select value={channelFilter} onValueChange={(v) => updateFilter("channel", v ?? "")}>
- <SelectTrigger className="w-40 border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
- <SelectValue placeholder="Channel: All" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">Channel: All</SelectItem>
- {channels.map((ch) => (
- <SelectItem key={ch.id} value={ch.name}>
- #{ch.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
-
- <div
- ref={scrollRef}
- className="flex-1 overflow-y-auto thin-scrollbar"
- onScroll={handleScroll}
- >
- {loading ? (
- <div className="flex flex-col">
- <SkeletonRow promptWidth="40%" />
- <SkeletonRow promptWidth="55%" />
- <SkeletonRow promptWidth="48%" />
- </div>
- ) : traces.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]">
- <GitBranch className="size-8 text-muted-foreground mb-3" />
- <p className="text-sm text-muted-foreground">No traces yet</p>
- <p className="text-xs text-muted-foreground/60 mt-1">
- Only tasks involving multiple agents appear here.
- </p>
- {(statusFilter || agentFilter || channelFilter) && (
- <p className="text-xs text-muted-foreground/60 mt-1">
- Try changing your filter
- </p>
- )}
- </div>
- ) : (
- <div className="flex flex-col animate-[fade-up_400ms_ease-out_both]">
- {traces.map((trace) => (
- <TraceRow key={trace.trace_id} trace={trace} slug={slug} />
- ))}
- {loadingMore && (
- <>
- <SkeletonRow promptWidth="48%" />
- <SkeletonRow promptWidth="40%" />
- </>
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/unread/page.tsx b/src/web/src/app/(app)/w/[slug]/unread/page.tsx
deleted file mode 100644
index b0c216075..000000000
--- a/src/web/src/app/(app)/w/[slug]/unread/page.tsx
+++ /dev/null
@@ -1,235 +0,0 @@
-"use client";
-
-import { useObservedRegion } from "@/lib/observability/regions";
-import { viewEvidence } from "@/lib/observability/data-source";
-
-import { useSelector } from "@tanstack/react-store";
-import { useApplicationOwner } from "@/lib/application-owner";
-import { useCallback, useRef } from "react";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { type InboxItem } from "@/lib/api";
-import { useInboxCount } from "@/contexts/inbox-count-context";
-import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Button } from "@/components/ui/button";
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Inbox, ListFilter, CheckCheck } from "lucide-react";
-import { AgentAvatar } from "@/components/avatar";
-import { relativeTime } from "@/lib/time";
-import {
- INBOX_FILTER_TYPES,
- INBOX_FILTER_LABELS,
- MANDATORY_INBOX_TYPES,
- setInboxFilterTypes,
- type InboxFilterType,
-} from "@/lib/inbox-filter";
-import { useMarkAllInboxRead, useWorkspaceInbox } from "@/hooks/workspace/use-inbox";
-
-
-function StatusDot({ status }: { status: string | null }) {
- const colorClass =
- status === "completed"
- ? "bg-[oklch(0.72_0.19_145)]"
- : status === "failed"
- ? "bg-destructive"
- : "bg-muted-foreground/40";
- return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;
-}
-
-const TYPE_LABELS: Record<string, string> = {
- user_dm_message: "DM",
- calendar_event: "Calendar",
- email_notification: "Email",
-};
-
-function TypeBadge({ type }: { type: string | null }) {
- if (!type) return null;
- const label = TYPE_LABELS[type] ?? type;
- return (
- <span className="text-[10px] leading-none px-2 py-1 rounded-full bg-muted text-muted-foreground font-medium">
- {label}
- </span>
- );
-}
-
-function InboxRow({ item, slug, onClick }: { item: InboxItem; slug: string; onClick?: (e: React.MouseEvent) => void }) {
- const statusLabel = item.root_task_status === "failed" ? "Failed" : "Completed";
-
- return (
- <a
- href={`/w/${slug}/agents/${item.agent_id}?conv=${item.id}`}
- onClick={onClick}
- className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
- >
- <div className="flex items-center gap-2">
- <AgentAvatar name={item.agent_name} avatarUrl={item.agent_avatar_url} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 min-w-0">
- <span className="text-sm text-foreground truncate flex-1 min-w-0">
- {item.root_prompt ?? item.title}
- </span>
- <Tooltip>
- <TooltipTrigger render={<span className="text-xs text-muted-foreground shrink-0 ml-2" />}>
- {relativeTime(item.latest_response_at)}
- </TooltipTrigger>
- <TooltipContent>{new Date(item.latest_response_at).toLocaleString()}</TooltipContent>
- </Tooltip>
- </div>
- <div className="flex items-center gap-2 mt-1">
- {item.agent_name && (
- <>
- <span className="text-xs font-medium text-muted-foreground">{item.agent_name}</span>
- <span className="text-muted-foreground/40">&middot;</span>
- </>
- )}
- <StatusDot status={item.root_task_status} />
- <span className="text-xs text-muted-foreground">{statusLabel}</span>
- <TypeBadge type={item.root_task_type} />
- </div>
- <p className="text-xs text-muted-foreground/70 mt-1 line-clamp-1">
- {item.latest_response}
- </p>
- </div>
- </div>
- </a>
- );
-}
-
-function SkeletonRow({ promptWidth }: { promptWidth: string }) {
- return (
- <div className="px-4 py-3 border-b border-border/30">
- <div className="flex items-center gap-2">
- <Skeleton className="size-8 rounded-full shrink-0" />
- <div className="flex-1">
- <Skeleton className="h-3.5 rounded" style={{ width: promptWidth }} />
- <div className="flex items-center gap-2 mt-2">
- <Skeleton className="h-2.5 w-16 rounded" />
- <Skeleton className="h-2.5 w-8 rounded" />
- </div>
- <Skeleton className="h-2.5 w-3/4 rounded mt-2" />
- </div>
- </div>
- </div>
- );
-}
-
-export default function InboxPage() {
- const { slug } = useWorkspace();
- const { decrement: decrementInboxCount } = useInboxCount();
- const { openAgentChat } = useAgentChatSheet();
-
- const { items, isPending: loading, hasNextPage: hasMore, isFetchingNextPage: loadingMore, fetchNextPage } = useWorkspaceInbox();
- const markAll = useMarkAllInboxRead();
- const application = useApplicationOwner();
- const filterTypes = useSelector(application.preferences, (state) => state.inboxFilterTypes);
- useObservedRegion("inbox", !loading, viewEvidence(items));
- const scrollRef = useRef<HTMLDivElement>(null);
- const handleScroll = useCallback(() => {
- const el = scrollRef.current;
- if (el && el.scrollHeight - el.scrollTop - el.clientHeight < 200 && !loadingMore && hasMore) void fetchNextPage();
- }, [fetchNextPage, loadingMore, hasMore]);
- const handleMarkAllRead = () => markAll.mutate();
- const handleFilterToggle = (type: InboxFilterType, checked: boolean) => {
- const next = checked ? [...filterTypes, type] : filterTypes.filter((value) => value !== type);
- setInboxFilterTypes(application, next);
- };
-
- const activeFilterCount = filterTypes.length - MANDATORY_INBOX_TYPES.length;
-
- return (
- <div className="flex flex-col h-full">
- <div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2 gap-3">
- <div className="flex items-center gap-3 min-w-0">
- <h1 className="text-sm font-medium">Unread</h1>
- <p className="text-xs text-muted-foreground hidden sm:block">
- Unread responses from your agents.
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Popover>
- <PopoverTrigger
- className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
- >
- <ListFilter className="size-3.5" />
- <span>Filter</span>
- {activeFilterCount > 0 && (
- <span className="size-4 flex items-center justify-center rounded-full bg-primary text-primary-foreground text-[10px] font-medium leading-none">
- {activeFilterCount}
- </span>
- )}
- </PopoverTrigger>
- <PopoverContent side="bottom" align="end" className="w-48">
- <p className="text-xs font-medium text-muted-foreground mb-2">Show in inbox:</p>
- <div className="flex flex-col gap-2">
- {INBOX_FILTER_TYPES.map((type) => {
- const isMandatory = MANDATORY_INBOX_TYPES.includes(type);
- const isChecked = filterTypes.includes(type);
- return (
- <label key={type} className="flex items-center gap-2 cursor-pointer">
- <Checkbox
- checked={isChecked}
- disabled={isMandatory}
- onCheckedChange={(checked) => handleFilterToggle(type, !!checked)}
- />
- <span className="text-sm">{INBOX_FILTER_LABELS[type]}</span>
- </label>
- );
- })}
- </div>
- </PopoverContent>
- </Popover>
- {!loading && items.length > 0 && (
- <Button
- variant="ghost"
- size="sm"
- onClick={handleMarkAllRead}
- className="text-xs text-muted-foreground"
- >
- <CheckCheck className="size-3.5" />
- <span>Mark all as read</span>
- </Button>
- )}
- </div>
- </div>
-
- <div
- ref={scrollRef}
- onScroll={handleScroll}
- className="flex-1 overflow-y-auto thin-scrollbar"
- >
- {loading ? (
- <>
- <SkeletonRow promptWidth="60%" />
- <SkeletonRow promptWidth="45%" />
- <SkeletonRow promptWidth="70%" />
- <SkeletonRow promptWidth="55%" />
- </>
- ) : items.length === 0 ? (
- <div className="flex flex-col items-center justify-center h-full text-muted-foreground gap-3 py-20">
- <Inbox className="size-10 opacity-30" />
- <p className="text-sm">No unread messages</p>
- </div>
- ) : (
- <>
- {items.map((item) => (
- <InboxRow
- key={item.id}
- item={item}
- slug={slug}
- onClick={(e) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
- e.preventDefault();
- decrementInboxCount();
- openAgentChat(item.agent_id, { conversationId: item.id });
- }}
- />
- ))}
- {loadingMore && <SkeletonRow promptWidth="50%" />}
- </>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/workspaces/client.tsx b/src/web/src/app/(app)/workspaces/client.tsx
deleted file mode 100644
index 919747374..000000000
--- a/src/web/src/app/(app)/workspaces/client.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-"use client"
-
-import { useObservedQueryRegion } from "@/lib/observability/query-regions"
-
-import { useMutation, useQuery, type Query } from "@tanstack/react-query"
-import type { Workspace } from "@alook/shared"
-import { applicationWorkspacesOptions } from "@/hooks/workspace/settings-query-options"
-import { useApplicationViewSource } from "@/hooks/use-application-view-source"
-import { useRouter } from "next/navigation"
-import { Button } from "@/components/ui/button"
-import { Card, CardContent } from "@/components/ui/card"
-import { GradientBackground } from "@/components/gradient-background"
-import { Logo } from "@/components/logo"
-import { Plus, ArrowRight, LogOut, Loader2 } from "lucide-react"
-import { useApplicationSignOut } from "@/hooks/use-application-sign-out"
-import { useApplicationOwner } from "@/lib/application-owner";
-import { assertApplicationOwner, captureApplicationOwner, invalidateApplicationAuthentication } from "@/lib/application-owner"
-import { apiFetch, toastApiError } from "@/lib/api/client"
-
-export function WorkspaceListClient({
- workspaces: initialWorkspaces,
-}: {
- workspaces: Workspace[]
-}) {
- const applicationOwner = useApplicationOwner();
- const logout = useApplicationSignOut();
- const router = useRouter()
- const source = useApplicationViewSource("workspace-list")
- const options = applicationWorkspacesOptions(applicationOwner)
- const resource = useQuery({ ...options, initialData: initialWorkspaces, initialDataUpdatedAt: 0 })
- useObservedQueryRegion("workspaces", resource)
- const workspaces = resource.data
- type Intent = { original: ReturnType<typeof source.capture>; resource: Query | undefined }
- const command = useMutation({ meta: { observabilityAction: "workspace.create" }, mutationKey: [...options.queryKey, "create"], gcTime: 0,
- mutationFn: async ({ original, resource }: Intent) => {
- original.assert()
- const current = () => resource && applicationOwner.queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true }) === resource
- if (current()) await applicationOwner.queryClient.cancelQueries({ queryKey: options.queryKey, exact: true })
- original.assert()
- const result = await apiFetch<Workspace>("/api/workspaces", {
- method: "POST", body: JSON.stringify({ name: "Personal", slug: "" }),
- authenticationAccount: applicationOwner.userId, signal: original.signal, assertActive: original.assert,
- onUnauthorized: () => { original.assert(); return invalidateApplicationAuthentication(original.token, original.signal) },
- })
- original.assert()
- if (current()) {
- await applicationOwner.queryClient.cancelQueries({ queryKey: options.queryKey, exact: true })
- original.assert()
- if (current()) applicationOwner.queryClient.setQueryData<Workspace[]>(options.queryKey, (rows) => rows ? [...rows.filter((row) => row.id !== result.id), result] : rows)
- }
- return result
- },
- })
- const creating = command.isPending
- const handleNewWorkspace = async () => {
- const original = source.capture()
- original.assert()
- if (applicationOwner.queryClient.getMutationCache().findAll({ mutationKey: [...options.queryKey, "create"], status: "pending" }).length) return
- try {
- const data = await command.mutateAsync({ original, resource: applicationOwner.queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true }) })
- original.assert()
- router.push(`/studio/new?workspace_id=${data.id}`)
- } catch (error) { toastApiError(error, "Failed to create workspace", original.assert) }
- }
-
- return (
- <div className="relative flex min-h-dvh flex-col items-center justify-center p-6">
- <GradientBackground />
-
- <Button
- variant="ghost"
- size="sm"
- className="absolute top-4 right-4 text-muted-foreground"
- onClick={async () => {
- const token = captureApplicationOwner(applicationOwner)
- try { if (await logout.mutateAsync()) router.push("/sign-in") }
- catch (error) { toastApiError(error, "Failed to log out", () => assertApplicationOwner(token)) }
- }}
- >
- <LogOut className="size-4" />
- Log out
- </Button>
-
- <div className="w-full max-w-md space-y-8">
- <div className="flex flex-col items-center gap-3">
- <Logo size="lg" />
- <p className="text-sm text-muted-foreground">
- Choose a workspace to continue.
- </p>
- </div>
-
- <div className="space-y-3">
- {workspaces.map((ws) => (
- <Card
- key={ws.id}
- className="cursor-pointer transition-colors duration-200 hover:bg-accent/50"
- onClick={() => router.push(`/w/${ws.slug}/home`)}
- >
- <CardContent className="flex items-center justify-between px-3 py-2">
- <div className="flex items-center gap-2 min-w-0">
- <p className="text-sm font-medium truncate">{ws.name}</p>
- <p className="text-xs text-muted-foreground">{ws.slug}</p>
- </div>
- <ArrowRight className="size-3.5 text-muted-foreground shrink-0" />
- </CardContent>
- </Card>
- ))}
- </div>
-
- <Button
- variant="outline"
- className="w-full"
- onClick={handleNewWorkspace}
- disabled={creating}
- >
- {creating ? (
- <><Loader2 className="size-4 animate-spin" /> Creating...</>
- ) : (
- <><Plus className="size-4" /> New workspace</>
- )}
- </Button>
- </div>
- </div>
- )
-}
diff --git a/src/web/src/app/(app)/workspaces/page.tsx b/src/web/src/app/(app)/workspaces/page.tsx
deleted file mode 100644
index 71a096755..000000000
--- a/src/web/src/app/(app)/workspaces/page.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { redirect } from "next/navigation";
-
-export default function WorkspacesPage() {
- redirect("/c/me");
-}
diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
index d77301059..0ea89d30a 100644
--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
@@ -27,6 +27,7 @@ import {
import galleryStyles from "@/components/home/landing-shell-motion.module.css"
import { DEV_PASSWORD } from "@alook/shared"
import { CircleCheck } from "lucide-react"
+import { safeRedirectPath } from "@/lib/safe-redirect"
// Default post-login landing when no explicit `?redirect=` is present. Points
// at the community home (/c/me); the old `/workspaces` target was the legacy
@@ -34,10 +35,7 @@ import { CircleCheck } from "lucide-react"
const DEFAULT_POST_LOGIN = "/c/me"
function safeRedirectUrl(redirect: string | null): string {
- if (redirect && redirect.startsWith("/") && !redirect.startsWith("//")) {
- return redirect
- }
- return DEFAULT_POST_LOGIN
+ return safeRedirectPath(redirect, DEFAULT_POST_LOGIN)
}
function SignInForm({
diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
index 3a264ec38..4968c2861 100644
--- a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
@@ -4,7 +4,8 @@ import { startAction, finishAction, type Action } from "@/lib/observability/cont
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useEffect, useRef } from "react"
-import { isTauri, safeRedirectPath, type NativeOauthProvider } from "@alook/shared"
+import { safeRedirectPath } from "@/lib/safe-redirect"
+import { isTauri, type NativeOauthProvider } from "@alook/shared"
import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"
import Image from "next/image"
import { Button } from "@/components/ui/button"
diff --git a/src/web/src/app/c/QueryProvider.lifecycle.dom.test.tsx b/src/web/src/app/c/QueryProvider.lifecycle.dom.test.tsx
index 54b1a605d..4c08c7ad7 100644
--- a/src/web/src/app/c/QueryProvider.lifecycle.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.lifecycle.dom.test.tsx
@@ -1,3 +1,4 @@
+import { get, set } from "idb-keyval"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -80,10 +81,10 @@ describe("actual native community account provider", () => {
})
it("current 401 retires canonical native facts and both disk domains before navigation", async () => {
render(<App />); await waitFor(() => expect(registry?.authenticationView.get().active).toBe(true)); await waitFor(() => expect(restoring).toBe(false)); await act(async () => { await registry.preload() })
- const old = registry, community = createIdbPersister("A"), application = createIdbPersister("A", "application"); await act(async () => { await community.persistClient(payload); }) ; await act(async () => { await application.persistClient(payload) })
+ const old = registry, community = createIdbPersister("A"); await act(async () => { await community.persistClient(payload); }) ; await act(async () => { await set("alook:qc:v3:A:application:client", JSON.stringify(payload)) })
let done!: ReturnType<typeof command>; await act(async () => { done = command().catch((error) => error) }) ; await waitFor(() => expect(complete).toBeTypeOf("function")); await act(async () => { complete(new Response("{}", { status: 401 })); await done })
await waitFor(() => expect(assign).toHaveBeenCalledOnce()); expect(old.runtime.lifecycle.get().active).toBe(false); expect(old.queryClient.getQueryCache().getAll()).toHaveLength(0)
- expect(await community.isCurrent()).toBe(false); expect(await application.isCurrent()).toBe(false); expect(reload).not.toHaveBeenCalled()
+ expect(await community.isCurrent()).toBe(false); expect(await get("alook:qc:v3:A:application:client")).toBeUndefined(); expect(reload).not.toHaveBeenCalled()
})
it("direct provider identity change creates B rather than reusing A's native instances", async () => {
const mounted = render(<App />); await waitFor(() => expect(registry?.authenticationView.get().active).toBe(true)); await waitFor(() => expect(restoring).toBe(false)); await act(async () => { await registry.preload() }); const old = registry
diff --git a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx b/src/web/src/app/c/invite/[token]/invite-accept-client.tsx
index 67f9eb019..433c064e7 100644
--- a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx
+++ b/src/web/src/app/c/invite/[token]/invite-accept-client.tsx
@@ -16,6 +16,7 @@ import { apiFetch } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { ServerIcon } from "@/components/community/server-icon"
import { Avatar } from "@/components/community/avatar"
+import { tid } from "@/lib/community/testids"
type InviteInfo = {
serverId: string
@@ -148,7 +149,7 @@ function InviteAcceptInner({ token }: { token: string }) {
<div className="grid size-16 place-items-center rounded-full bg-destructive/10 text-destructive">
<CircleAlert className="size-7" />
</div>
- <h1 className="mt-5 text-2xl font-semibold">
+ <h1 data-testid={error.dead ? tid.inviteExpiredTitle : undefined} className="mt-5 text-2xl font-semibold">
{error.dead ? "This invite has expired" : "This invite isn't working"}
</h1>
<p className="mt-2 text-sm text-muted-foreground">
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index b26a721cb..ad3307903 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -1427,15 +1427,6 @@ body.driver-active .community-ws-reconnect-overlay * {
}
}
-@keyframes calendar-progress {
- 0% {
- transform: translateX(-100%);
- }
-
- 100% {
- transform: translateX(400%);
- }
-}
/* iMessage-style typing dots for the presence line. */
@keyframes typing-dot {
@@ -1625,14 +1616,6 @@ body.driver-active .community-ws-reconnect-overlay * {
scrollbar-width: none;
}
-/* Backdrop scrollbar: takes same space as thin-scrollbar but invisible */
-.mention-backdrop.thin-scrollbar {
- scrollbar-color: transparent transparent;
-}
-
-.mention-backdrop.thin-scrollbar::-webkit-scrollbar-thumb {
- background: transparent;
-}
@layer base {
@@ -1946,21 +1929,6 @@ body.driver-active .community-ws-reconnect-overlay * {
font-style: italic;
}
-/* Textarea mention backdrop */
-.caret-foreground {
- caret-color: var(--foreground);
-}
-
-.textarea-text-hidden {
- -webkit-text-fill-color: transparent;
- color: transparent;
- -webkit-font-smoothing: antialiased;
-}
-
-.textarea-text-hidden::placeholder {
- -webkit-text-fill-color: var(--muted-foreground);
- color: var(--muted-foreground);
-}
.chat-input-line-height {
line-height: 24px;
@@ -2966,29 +2934,9 @@ html.dark .blog-content [data-rehype-pretty-code-figure] span {
animation: avatar-nod 500ms ease-in-out infinite;
}
-/* ── Sidebar easter egg: logo click → agents pop ── */
-@keyframes sidebar-agent-pop {
- 0% {
- transform: translateX(0) scale(1) rotate(0);
- }
-
- 28% {
- transform: translateX(25px) scale(1.08) rotate(-6deg);
- }
-
- 100% {
- transform: translateX(0) scale(1) rotate(0);
- }
-}
-
-.sidebar-agent-pop {
- animation: sidebar-agent-pop 500ms cubic-bezier(0.34, 1.56, 0.64, 1) both;
-}
@media (prefers-reduced-motion: reduce) {
- .sidebar-agent-pop {
- animation: none !important;
- }
+
.avatar-anim-shape-bounce [data-avatar-shape],
.avatar-anim-head-tilt [data-avatar-shape],
diff --git a/src/web/src/app/onboard.md/route.test.ts b/src/web/src/app/onboard.md/route.test.ts
index 4387cfe95..6f1646430 100644
--- a/src/web/src/app/onboard.md/route.test.ts
+++ b/src/web/src/app/onboard.md/route.test.ts
@@ -34,7 +34,10 @@ describe("GET /onboard.md", () => {
const body = await response.text();
expect(body).toContain("npx @alook/cli login");
expect(body).toContain("https://alook.ai/templates");
- expect(body).toContain("https://alook.ai/w/{slug}/home");
+ expect(body).toContain("https://alook.ai/c/me");
+ expect(body).toContain("workspace init --json-file");
+ expect(body).toContain("old workspace web interface has been retired");
+ expect(body).not.toContain("/w/{slug}/home");
});
it("uses localhost in development mode when no URLs are set", async () => {
@@ -57,6 +60,6 @@ describe("GET /onboard.md", () => {
const body = await response.text();
expect(body).toContain("npx @alook/app cli login");
expect(body).toContain("http://localhost:15210/templates");
- expect(body).toContain("http://localhost:15210/w/{slug}/home");
+ expect(body).toContain("http://localhost:15210/c/me");
});
});
diff --git a/src/web/src/app/onboard.md/route.ts b/src/web/src/app/onboard.md/route.ts
index 3f56ffec2..d2243c1fe 100644
--- a/src/web/src/app/onboard.md/route.ts
+++ b/src/web/src/app/onboard.md/route.ts
@@ -70,13 +70,9 @@ ${cliPrefix} workspace init --json-file <path_to_json>
If the current workspace already has agents, a new workspace is created automatically.
-Your workspace is ready. Open it at:
+Workspace commands remain available in the CLI. The old workspace web interface has been retired.
-\`\`\`
-${baseUrl}/w/{slug}/home
-\`\`\`
-
-(Use the workspace slug from the \`workspace init\` output above.)
+Open the community at ${baseUrl}/c/me. Public template JSON remains available for reference.
`;
}
diff --git a/src/web/src/app/robots.txt/route.ts b/src/web/src/app/robots.txt/route.ts
index 00e055047..8592b830a 100644
--- a/src/web/src/app/robots.txt/route.ts
+++ b/src/web/src/app/robots.txt/route.ts
@@ -3,6 +3,8 @@ export function GET() {
"User-agent: *",
"Allow: /",
"Disallow: /w/",
+ "Disallow: /studio/new",
+ "Disallow: /invite/",
"Disallow: /workspaces",
"Disallow: /api/",
"",
diff --git a/src/web/src/app/templates/[id]/client.tsx b/src/web/src/app/templates/[id]/client.tsx
index 04360342f..c8082f860 100644
--- a/src/web/src/app/templates/[id]/client.tsx
+++ b/src/web/src/app/templates/[id]/client.tsx
@@ -2,7 +2,6 @@
import Link from "next/link";
import { Check } from "lucide-react";
-import { buttonVariants } from "@/components/ui/button";
import { PublicLayout } from "@/components/public-layout";
import { MemberCard } from "./_components/member-card";
import type { TemplatePreset } from "@/lib/templates";
@@ -17,19 +16,10 @@ const ROLE_LABELS: Record<string, string> = {
export function TemplateDetailClient({
template,
isLoggedIn,
- workspaceId,
}: {
template: TemplatePreset;
isLoggedIn: boolean;
- workspaceId?: string;
}) {
- const getUrl = workspaceId
- ? `/studio/new?template=${template.id}&workspace_id=${workspaceId}`
- : `/studio/new?template=${template.id}`;
- const href = isLoggedIn
- ? getUrl
- : `/sign-in?redirect=${encodeURIComponent(getUrl)}`;
-
return (
<PublicLayout
maxWidth="4xl"
@@ -106,15 +96,6 @@ export function TemplateDetailClient({
</div>
</div>
- {/* CTA */}
- <div className="shrink-0 sm:ml-8 sm:pt-2">
- <Link href={href} className={buttonVariants({ size: "default" }) + " w-full sm:w-auto"}>
- Use This Template
- </Link>
- <p className="mt-2 text-center text-xs text-muted-foreground sm:text-right">
- Free to deploy
- </p>
- </div>
</div>
{/* Divider */}
@@ -166,18 +147,6 @@ export function TemplateDetailClient({
</div>
</section>
- {/* Bottom CTA */}
- <div className="mt-16 flex items-center justify-between rounded-xl bg-muted/40 p-6">
- <div>
- <p className="text-sm font-medium">Ready to deploy?</p>
- <p className="mt-1 text-xs text-muted-foreground">
- Customize the agent instructions after setup.
- </p>
- </div>
- <Link href={href} className={buttonVariants({ size: "sm" })}>
- Get Started
- </Link>
- </div>
</div>
</PublicLayout>
);
diff --git a/src/web/src/app/templates/[id]/page.tsx b/src/web/src/app/templates/[id]/page.tsx
index 3ef11f935..d22e5bd78 100644
--- a/src/web/src/app/templates/[id]/page.tsx
+++ b/src/web/src/app/templates/[id]/page.tsx
@@ -44,17 +44,14 @@ export async function generateMetadata({
export default async function TemplateDetailPage({
params,
- searchParams,
}: {
params: Promise<{ id: string }>;
- searchParams: Promise<Record<string, string | undefined>>;
}) {
const { id } = await params;
const template = getTemplateById(id);
if (!template) notFound();
const session = await getSession();
- const sp = await searchParams;
const jsonLd = [
{
@@ -87,7 +84,6 @@ export default async function TemplateDetailPage({
<TemplateDetailClient
template={template}
isLoggedIn={!!session}
- workspaceId={sp.workspace_id}
/>
</></>
);
diff --git a/src/web/src/app/templates/_components/template-card.tsx b/src/web/src/app/templates/_components/template-card.tsx
index a47476f3b..e8562ce16 100644
--- a/src/web/src/app/templates/_components/template-card.tsx
+++ b/src/web/src/app/templates/_components/template-card.tsx
@@ -1,10 +1,7 @@
"use client";
-import { useRouter } from "next/navigation";
import Link from "next/link";
-import { ArrowUpRight } from "lucide-react";
import type { TemplatePreset } from "@/lib/templates";
-import { trackTemplateUsed } from "@/lib/analytics";
const ROLE_DOT_COLORS: Record<string, string> = {
leader: "bg-amber-500/70 dark:bg-amber-400/60",
@@ -15,28 +12,12 @@ const ROLE_DOT_COLORS: Record<string, string> = {
export function TemplateCard({
template,
- isLoggedIn,
- workspaceId,
}: {
template: TemplatePreset;
- isLoggedIn: boolean;
- workspaceId?: string;
}) {
- const router = useRouter();
- const getUrl = workspaceId
- ? `/studio/new?template=${template.id}&workspace_id=${workspaceId}`
- : `/studio/new?template=${template.id}`;
- const href = isLoggedIn
- ? getUrl
- : `/sign-in?redirect=${encodeURIComponent(getUrl)}`;
-
- const detailUrl = workspaceId
- ? `/templates/${template.id}?workspace_id=${workspaceId}`
- : `/templates/${template.id}`;
-
return (
<Link
- href={detailUrl}
+ href={`/templates/${template.id}`}
className="group relative flex flex-col rounded-xl bg-card p-4 transition-all duration-200 hover:bg-accent/40 border border-transparent hover:border-border"
>
{/* Icon */}
@@ -68,19 +49,6 @@ export function TemplateCard({
</span>
</div>
- <button
- type="button"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- trackTemplateUsed({ template_id: template.id, template_name: template.name });
- router.push(href);
- }}
- className="flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground opacity-0 transition-all duration-150 group-hover:opacity-100 group-hover:bg-foreground group-hover:text-background"
- >
- Use
- <ArrowUpRight className="size-3" />
- </button>
</div>
</Link>
);
diff --git a/src/web/src/app/templates/client.dom.test.ts b/src/web/src/app/templates/client.dom.test.ts
index 46966ff45..02f06f93a 100644
--- a/src/web/src/app/templates/client.dom.test.ts
+++ b/src/web/src/app/templates/client.dom.test.ts
@@ -6,7 +6,6 @@ import { devopsMonitor } from "@/lib/templates/presets/devops-monitor"
vi.mock("@/lib/analytics", () => ({
trackTemplatesBrowsed: vi.fn(),
- trackTemplateUsed: vi.fn(),
}))
vi.mock("@/components/public-layout", () => ({
diff --git a/src/web/src/app/templates/client.tsx b/src/web/src/app/templates/client.tsx
index 1d30f1199..7afdf903b 100644
--- a/src/web/src/app/templates/client.tsx
+++ b/src/web/src/app/templates/client.tsx
@@ -12,12 +12,10 @@ export function TemplatesClient({
templates,
categories,
isLoggedIn,
- workspaceId,
}: {
templates: TemplatePreset[];
categories: TemplateCategory[];
isLoggedIn: boolean;
- workspaceId?: string;
}) {
const [activeCategory, setActiveCategory] = useAtom(useCreateAtom<"All" | TemplateCategory>("All"));
const tracked = useRef(false);
@@ -116,8 +114,6 @@ export function TemplatesClient({
<TemplateCard
key={template.id}
template={template}
- isLoggedIn={isLoggedIn}
- workspaceId={workspaceId}
/>
))}
</div>
diff --git a/src/web/src/app/templates/page.tsx b/src/web/src/app/templates/page.tsx
index 7e886703d..3c4c298d6 100644
--- a/src/web/src/app/templates/page.tsx
+++ b/src/web/src/app/templates/page.tsx
@@ -38,13 +38,8 @@ const itemListJsonLd = {
})),
};
-export default async function TemplatesPage({
- searchParams,
-}: {
- searchParams: Promise<Record<string, string | undefined>>;
-}) {
+export default async function TemplatesPage() {
const session = await getSession();
- const params = await searchParams;
return (
<><ObservedStaticContent /><>
<script
@@ -55,7 +50,6 @@ export default async function TemplatesPage({
templates={TEMPLATES}
categories={TEMPLATE_CATEGORIES}
isLoggedIn={!!session}
- workspaceId={params.workspace_id}
/>
</></>
);
diff --git a/src/web/src/app/templates/retirement.dom.test.tsx b/src/web/src/app/templates/retirement.dom.test.tsx
new file mode 100644
index 000000000..3da97100a
--- /dev/null
+++ b/src/web/src/app/templates/retirement.dom.test.tsx
@@ -0,0 +1,24 @@
+import { expect, it, vi } from "vitest"
+import { render } from "@/test/react-dom-harness"
+import { TEMPLATES } from "@/lib/templates"
+import { TemplateCard } from "./_components/template-card"
+import { TemplateDetailClient } from "./[id]/client"
+
+vi.mock("@/components/public-layout", () => ({ PublicLayout: ({ children, rightSlot }: { children: React.ReactNode; rightSlot: React.ReactNode }) => <main>{rightSlot}{children}</main> }))
+vi.mock("next/link", () => ({ default: ({ children, href, ...props }: React.ComponentProps<"a">) => <a href={href} {...props}>{children}</a> }))
+
+it("keeps public template content and canonical detail navigation", () => {
+ const template = TEMPLATES[0]!
+ const view = render(<TemplateCard template={template} />)
+ expect(view.getByRole("heading")).toHaveTextContent(template.name)
+ expect(view.getByRole("link")).toHaveAttribute("href", `/templates/${template.id}`)
+ expect(view.queryByRole("button", { name: "Use" })).toBeNull()
+})
+it.each([true, false])("retains readable details and public entry links for logged-in=%s without a Studio CTA", isLoggedIn => {
+ const template = TEMPLATES[0]!
+ const view = render(<TemplateDetailClient template={template} isLoggedIn={isLoggedIn} />)
+ expect(view.getByRole("heading", { name: template.name })).toBeVisible()
+ expect(view.getByText(template.longDescription)).toBeVisible()
+ expect(view.getAllByRole("link").map(link => link.getAttribute("href"))).not.toEqual(expect.arrayContaining([expect.stringContaining("/studio/new")]))
+ expect(view.queryByRole("link", { name: "Use This Template" })).toBeNull()
+})
diff --git a/src/web/src/components/agent-chat/agent-chat-view.test.ts b/src/web/src/components/agent-chat/agent-chat-view.test.ts
deleted file mode 100644
index 77d75aaf3..000000000
--- a/src/web/src/components/agent-chat/agent-chat-view.test.ts
+++ /dev/null
@@ -1,766 +0,0 @@
-import { describe, it, expect } from "vitest";
-import type { Message, Artifact } from "@alook/shared";
-import { sortMessages, mergeMessages, buildTimeline, computeGroupPositions, getEventIconType, eventTypeFromMessage, shouldPersistPointerForLoad, pointerRefreshTargetForTaskCreated } from "./chat-message-utils";
-import type { NapMarker } from "./chat-message-utils";
-
-function msg(id: string, created_at: string, role: "user" | "assistant" | "event" = "user", content = ""): Message {
- return { id, conversation_id: "conv1", role, content, task_id: null, attachment_ids: null, created_at };
-}
-
-describe("sortMessages", () => {
- it("sorts messages by created_at ascending", () => {
- const msgs = [
- msg("m3", "2024-01-03T00:00:00Z"),
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m2", "2024-01-02T00:00:00Z"),
- ];
- const sorted = sortMessages(msgs);
- expect(sorted.map((m) => m.id)).toEqual(["m1", "m2", "m3"]);
- });
-
- it("breaks ties by id when created_at is identical", () => {
- const msgs = [
- msg("b", "2024-01-01T00:00:00Z"),
- msg("a", "2024-01-01T00:00:00Z"),
- msg("c", "2024-01-01T00:00:00Z"),
- ];
- const sorted = sortMessages(msgs);
- expect(sorted.map((m) => m.id)).toEqual(["a", "b", "c"]);
- });
-
- it("does not mutate the original array", () => {
- const msgs = [
- msg("m2", "2024-01-02T00:00:00Z"),
- msg("m1", "2024-01-01T00:00:00Z"),
- ];
- sortMessages(msgs);
- expect(msgs[0].id).toBe("m2");
- });
-
- it("returns empty array for empty input", () => {
- expect(sortMessages([])).toEqual([]);
- });
-});
-
-describe("mergeMessages", () => {
- it("merges two arrays and sorts chronologically", () => {
- const existing = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m3", "2024-01-03T00:00:00Z"),
- ];
- const incoming = [
- msg("m2", "2024-01-02T00:00:00Z"),
- msg("m4", "2024-01-04T00:00:00Z"),
- ];
- const result = mergeMessages(existing, incoming);
- expect(result.map((m) => m.id)).toEqual(["m1", "m2", "m3", "m4"]);
- });
-
- it("deduplicates by id — incoming wins", () => {
- const existing = [
- msg("m1", "2024-01-01T00:00:00Z", "user", "old content"),
- ];
- const incoming = [
- msg("m1", "2024-01-01T00:00:00Z", "user", "updated content"),
- ];
- const result = mergeMessages(existing, incoming);
- expect(result).toHaveLength(1);
- expect(result[0].content).toBe("updated content");
- });
-
- it("replaces optimistic temp message with server message", () => {
- const existing = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("temp-123", "2024-01-02T00:00:00Z", "user", "hello"),
- ];
- // After sendMessage replaces temp, but server also returns the real message
- const serverState = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m2", "2024-01-02T00:00:00Z", "user", "hello"),
- msg("m3", "2024-01-02T00:01:00Z", "assistant", "hi there"),
- ];
- // In the real flow, temp-123 is already replaced by m2 before merge.
- // But even if it weren't, merge produces correct chronological order.
- const existing2 = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m2", "2024-01-02T00:00:00Z", "user", "hello"),
- ];
- const result = mergeMessages(existing2, serverState);
- expect(result.map((m) => m.id)).toEqual(["m1", "m2", "m3"]);
- });
-
- it("preserves older pagination messages not in server window", () => {
- // User scrolled up and loaded old messages (m1-m5)
- // Current state has m1..m10 + m11 (user just sent)
- const existing = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m2", "2024-01-02T00:00:00Z"),
- msg("m3", "2024-01-03T00:00:00Z"),
- msg("m4", "2024-01-04T00:00:00Z"),
- msg("m5", "2024-01-05T00:00:00Z"),
- msg("m6", "2024-01-06T00:00:00Z"),
- msg("m7", "2024-01-07T00:00:00Z"),
- msg("m8", "2024-01-08T00:00:00Z"),
- msg("m9", "2024-01-09T00:00:00Z"),
- msg("m10", "2024-01-10T00:00:00Z"),
- msg("m11", "2024-01-11T00:00:00Z", "user", "new message"),
- ];
- // Server returns latest 20 — but conversation only has 12 messages total
- const incoming = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m2", "2024-01-02T00:00:00Z"),
- msg("m3", "2024-01-03T00:00:00Z"),
- msg("m4", "2024-01-04T00:00:00Z"),
- msg("m5", "2024-01-05T00:00:00Z"),
- msg("m6", "2024-01-06T00:00:00Z"),
- msg("m7", "2024-01-07T00:00:00Z"),
- msg("m8", "2024-01-08T00:00:00Z"),
- msg("m9", "2024-01-09T00:00:00Z"),
- msg("m10", "2024-01-10T00:00:00Z"),
- msg("m11", "2024-01-11T00:00:00Z", "user", "new message"),
- msg("m12", "2024-01-12T00:00:00Z", "assistant", "response"),
- ];
- const result = mergeMessages(existing, incoming);
- expect(result.map((m) => m.id)).toEqual([
- "m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8", "m9", "m10", "m11", "m12",
- ]);
- // User message and assistant response are adjacent at the end
- expect(result[10].role).toBe("user");
- expect(result[11].role).toBe("assistant");
- });
-
- it("fixes the original bug — append-dedup produced misordered array", () => {
- // Reproduce the exact bug scenario:
- // Initial load: latest 10 messages (m11..m20)
- const existing = Array.from({ length: 10 }, (_, i) =>
- msg(`m${i + 11}`, `2024-01-${String(i + 11).padStart(2, "0")}T00:00:00Z`)
- );
- // User sends m21
- existing.push(msg("m21", "2024-01-21T00:00:00Z", "user", "what we have done yesterday"));
-
- // Server returns latest 20 (m3..m22) — includes older messages m3-m10 not in state
- const incoming = Array.from({ length: 20 }, (_, i) =>
- msg(`m${i + 3}`, `2024-01-${String(i + 3).padStart(2, "0")}T00:00:00Z`)
- );
- // m22 is the assistant response
- incoming.push(msg("m22", "2024-01-22T00:00:00Z", "assistant", "Here's what we did"));
-
- const result = mergeMessages(existing, incoming);
-
- // All messages must be in strict chronological order
- for (let i = 1; i < result.length; i++) {
- expect(result[i].created_at >= result[i - 1].created_at).toBe(true);
- }
-
- // User message (m21) and assistant response (m22) must be adjacent at the end
- const userIdx = result.findIndex((m) => m.id === "m21");
- const assistantIdx = result.findIndex((m) => m.id === "m22");
- expect(assistantIdx).toBe(userIdx + 1);
- expect(result[result.length - 1].id).toBe("m22");
- expect(result[result.length - 2].id).toBe("m21");
- });
-
- it("handles empty existing array", () => {
- const incoming = [msg("m1", "2024-01-01T00:00:00Z")];
- const result = mergeMessages([], incoming);
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe("m1");
- });
-
- it("handles empty incoming array", () => {
- const existing = [msg("m1", "2024-01-01T00:00:00Z")];
- const result = mergeMessages(existing, []);
- expect(result).toHaveLength(1);
- expect(result[0].id).toBe("m1");
- });
-
- it("handles rapid messages — two sends don't corrupt order", () => {
- // State after two rapid sends
- const existing = [
- msg("m1", "2024-01-01T00:00:00Z", "user"),
- msg("m2", "2024-01-01T00:00:01Z", "assistant"),
- msg("m3", "2024-01-01T00:00:02Z", "user", "first rapid"),
- msg("m4", "2024-01-01T00:00:03Z", "user", "second rapid"),
- ];
- // Server returns with both responses
- const incoming = [
- msg("m1", "2024-01-01T00:00:00Z", "user"),
- msg("m2", "2024-01-01T00:00:01Z", "assistant"),
- msg("m3", "2024-01-01T00:00:02Z", "user", "first rapid"),
- msg("m4", "2024-01-01T00:00:03Z", "user", "second rapid"),
- msg("m5", "2024-01-01T00:00:04Z", "assistant", "response to first"),
- msg("m6", "2024-01-01T00:00:05Z", "assistant", "response to second"),
- ];
- const result = mergeMessages(existing, incoming);
- expect(result.map((m) => m.id)).toEqual(["m1", "m2", "m3", "m4", "m5", "m6"]);
- });
-});
-
-describe("getEventIconType", () => {
- it("uses the issue icon for issue conversations", () => {
- expect(getEventIconType("Error: failed to download attachments", "issue_event")).toBe("issue");
- });
-
- it("uses the issue icon for issue event content", () => {
- expect(getEventIconType("Issue status changed: todo -> done", "user_dm_message")).toBe("issue");
- });
-
- it("keeps email and calendar event icons for existing channels", () => {
- expect(getEventIconType("New email from [email protected]", "email_notification")).toBe("email");
- expect(getEventIconType("Calendar event started", "calendar_event")).toBe("calendar");
- });
-
- it("lets explicit channel type win over event content", () => {
- expect(getEventIconType("Issue mentioned in an email subject", "email_notification")).toBe("email");
- });
-});
-
-// Card type is metadata-driven first (robust if copy changes), content heuristic
-// only as a fallback when no resource id is present.
-describe("eventTypeFromMessage (metadata-driven)", () => {
- it("uses the metadata resource id over the content heuristic", () => {
- // Content says "email" but the metadata carries an issueId → issue wins.
- expect(eventTypeFromMessage({ issueId: "iss_1" }, "email-ish text", null)).toBe("issue");
- expect(eventTypeFromMessage({ emailId: "em_1" }, "no keywords here", null)).toBe("email");
- expect(eventTypeFromMessage({ calendarEventId: "cal_1" }, "no keywords here", null)).toBe("calendar");
- });
-
- it("falls back to the content/conversation heuristic when metadata is absent", () => {
- expect(eventTypeFromMessage(null, "Issue created: foo", "issue_event")).toBe("issue");
- expect(eventTypeFromMessage(undefined, "New email from [email protected]: hi", "email_notification")).toBe("email");
- expect(eventTypeFromMessage({}, "Standup reminder", "calendar_event")).toBe("calendar");
- });
-});
-
-function artifact(id: string, created_at: string): Artifact {
- return {
- id,
- conversation_id: "conv1",
- agent_id: "agent1",
- filename: "file.txt",
- content_type: "text/plain",
- size: 100,
- source: "agent",
- has_thumbnail: false,
- created_at,
- };
-}
-
-function nap(id: string, created_at: string, agentName = "Luna"): NapMarker {
- return { id, created_at, agentName };
-}
-
-describe("buildTimeline", () => {
- it("interleaves messages, artifacts, and nap markers chronologically", () => {
- const msgs = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m3", "2024-01-03T00:00:00Z"),
- ];
- const arts = [artifact("a1", "2024-01-02T00:00:00Z")];
- const naps: NapMarker[] = [];
-
- const result = buildTimeline(msgs, arts, naps);
- // Strictly chronological now (no artifact reorder): the file at 00:00:02
- // sits between the two messages where it actually happened.
- expect(result.map((i) => i.data.id)).toEqual(["m1", "a1", "m3"]);
- });
-
- it("places nap marker after messages at the same timestamp", () => {
- const msgs = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m2", "2024-01-03T00:00:00Z"),
- ];
- const napTs = "2024-01-02T00:00:00Z";
- const naps = [nap("nap-1", napTs)];
-
- const result = buildTimeline(msgs, [], naps);
- expect(result.map((i) => i.kind)).toEqual(["message", "nap", "message"]);
- });
-
- it("nap marker sorts after messages with the same created_at", () => {
- const ts = "2024-01-02T00:00:00Z";
- const msgs = [msg("m1", ts)];
- const naps = [nap("nap-1", ts)];
-
- const result = buildTimeline(msgs, [], naps);
- expect(result[0].kind).toBe("message");
- expect(result[1].kind).toBe("nap");
- });
-
- it("renders multiple nap markers between multiple conversations", () => {
- const msgs = [
- msg("m1", "2024-01-01T00:00:00Z"),
- msg("m2", "2024-01-03T00:00:00Z"),
- msg("m3", "2024-01-05T00:00:00Z"),
- ];
- const naps = [
- nap("nap-1", "2024-01-02T00:00:00Z"),
- nap("nap-2", "2024-01-04T00:00:00Z"),
- ];
-
- const result = buildTimeline(msgs, [], naps);
- expect(result.map((i) => i.kind)).toEqual([
- "message", "nap", "message", "nap", "message",
- ]);
- expect(result.map((i) => i.data.id)).toEqual([
- "m1", "nap-1", "m2", "nap-2", "m3",
- ]);
- });
-
- it("handles empty messages with nap markers only", () => {
- const naps = [nap("nap-1", "2024-01-01T00:00:00Z")];
- const result = buildTimeline([], [], naps);
- expect(result).toHaveLength(1);
- expect(result[0].kind).toBe("nap");
- });
-
- it("preserves agent name on nap markers", () => {
- const naps = [nap("nap-1", "2024-01-01T00:00:00Z", "TestBot")];
- const result = buildTimeline([], [], naps);
- expect(result[0].kind).toBe("nap");
- if (result[0].kind === "nap") {
- expect(result[0].data.agentName).toBe("TestBot");
- }
- });
-
- it("returns empty timeline when all inputs are empty", () => {
- expect(buildTimeline([], [], [])).toEqual([]);
- });
-
- it("handles mixed roles (user + assistant + event) without errors", () => {
- const msgs = [
- msg("m1", "2024-01-01T00:00:00Z", "user", "hello"),
- msg("m2", "2024-01-02T00:00:00Z", "event", "New email from [email protected]: Subject"),
- msg("m3", "2024-01-03T00:00:00Z", "assistant", "response"),
- ];
- const result = buildTimeline(msgs, [], []);
- expect(result).toHaveLength(3);
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m2", "m3"]);
- expect(result.every((i) => i.kind === "message")).toBe(true);
- });
-});
-
-function msgInConv(id: string, created_at: string, conversation_id: string): Message {
- return { id, conversation_id, role: "user", content: "", task_id: null, attachment_ids: null, created_at };
-}
-
-function artifactInConv(id: string, created_at: string, conversation_id: string): Artifact {
- return { id, conversation_id, agent_id: "agent1", filename: "file.txt", content_type: "text/plain", size: 100, source: "agent", has_thumbnail: false, created_at };
-}
-
-describe("buildTimeline — conversation grouping", () => {
- it("groups messages from multiple conversations correctly", () => {
- const msgs = [
- msgInConv("a1", "2024-01-01T00:00:00Z", "convA"),
- msgInConv("a2", "2024-01-01T01:00:00Z", "convA"),
- msgInConv("b1", "2024-01-02T00:00:00Z", "convB"),
- msgInConv("b2", "2024-01-02T01:00:00Z", "convB"),
- ];
- const naps = [nap("nap-convA", "2024-01-01T12:00:00Z")];
-
- const result = buildTimeline(msgs, [], naps, "convB");
- expect(result.map((i) => i.data.id)).toEqual(["a1", "a2", "nap-convA", "b1", "b2"]);
- });
-
- it("new message in old conversation stays in its section", () => {
- const msgs = [
- msgInConv("a1", "2024-01-01T00:00:00Z", "convA"),
- msgInConv("a2", "2024-01-01T01:00:00Z", "convA"),
- msgInConv("b1", "2024-01-02T00:00:00Z", "convB"),
- msgInConv("b2", "2024-01-02T01:00:00Z", "convB"),
- msgInConv("a3", "2024-01-03T00:00:00Z", "convA"), // newer than everything but belongs to old conv
- ];
- const naps = [nap("nap-convA", "2024-01-01T12:00:00Z")];
-
- const result = buildTimeline(msgs, [], naps, "convB");
- expect(result.map((i) => i.data.id)).toEqual(["a1", "a2", "a3", "nap-convA", "b1", "b2"]);
- });
-
- it("artifacts are grouped within their conversation section", () => {
- const msgs = [
- msgInConv("a1", "2024-01-01T00:00:00Z", "convA"),
- msgInConv("a2", "2024-01-01T02:00:00Z", "convA"),
- msgInConv("b1", "2024-01-02T00:00:00Z", "convB"),
- ];
- const arts = [artifactInConv("art1", "2024-01-01T01:00:00Z", "convA")];
- const naps = [nap("nap-convA", "2024-01-01T12:00:00Z")];
-
- const result = buildTimeline(msgs, arts, naps, "convB");
- // Chronological within the conversation section: art1 at 01:00 sits between
- // a1 (00:00) and a2 (02:00). No artifact reorder.
- expect(result.map((i) => i.data.id)).toEqual(["a1", "art1", "a2", "nap-convA", "b1"]);
- });
-
- it("single conversation (no nap markers) behaves as before", () => {
- const msgs = [
- msgInConv("m2", "2024-01-02T00:00:00Z", "convA"),
- msgInConv("m1", "2024-01-01T00:00:00Z", "convA"),
- ];
- const result = buildTimeline(msgs, [], [], "convA");
- expect(result.map((i) => i.data.id)).toEqual(["m1", "m2"]);
- });
-
- it("currentConversationId is null → fallback to global sort", () => {
- const msgs = [
- msgInConv("a1", "2024-01-01T00:00:00Z", "convA"),
- msgInConv("b1", "2024-01-02T00:00:00Z", "convB"),
- ];
- const naps = [nap("nap-convA", "2024-01-01T12:00:00Z")];
-
- const result = buildTimeline(msgs, [], naps, null);
- // falls back to global timestamp sort
- expect(result.map((i) => i.data.id)).toEqual(["a1", "nap-convA", "b1"]);
- });
-
- it("empty messages array returns only nap markers", () => {
- const naps = [nap("nap-convA", "2024-01-01T00:00:00Z")];
- const result = buildTimeline([], [], naps, "convB");
- expect(result).toHaveLength(1);
- expect(result[0].kind).toBe("nap");
- });
-
- it("nap marker ID parsing handles expected format", () => {
- const msgs = [
- msgInConv("m1", "2024-01-01T00:00:00Z", "conv_abc123"),
- msgInConv("m2", "2024-01-02T00:00:00Z", "conv_xyz"),
- ];
- const naps = [nap("nap-conv_abc123", "2024-01-01T12:00:00Z")];
-
- const result = buildTimeline(msgs, [], naps, "conv_xyz");
- expect(result.map((i) => i.data.id)).toEqual(["m1", "nap-conv_abc123", "m2"]);
- });
-
- it("multiple nap markers order sections correctly", () => {
- const msgs = [
- msgInConv("a1", "2024-01-01T00:00:00Z", "convA"),
- msgInConv("b1", "2024-01-02T00:00:00Z", "convB"),
- msgInConv("c1", "2024-01-03T00:00:00Z", "convC"),
- ];
- const naps = [
- nap("nap-convA", "2024-01-01T12:00:00Z"),
- nap("nap-convB", "2024-01-02T12:00:00Z"),
- ];
-
- const result = buildTimeline(msgs, [], naps, "convC");
- expect(result.map((i) => i.data.id)).toEqual(["a1", "nap-convA", "b1", "nap-convB", "c1"]);
- });
-
- it("orphan messages (unknown conversation_id) are placed before first nap marker", () => {
- const msgs = [
- msgInConv("a1", "2024-01-01T00:00:00Z", "convA"),
- msgInConv("x1", "2024-01-01T06:00:00Z", "convX"), // unknown
- msgInConv("b1", "2024-01-02T00:00:00Z", "convB"),
- ];
- const naps = [nap("nap-convA", "2024-01-01T12:00:00Z")];
-
- const result = buildTimeline(msgs, [], naps, "convB");
- // orphan x1 is placed before the first nap marker
- expect(result.map((i) => i.data.id)).toEqual(["a1", "x1", "nap-convA", "b1"]);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Wrong-conversation flash fix: per-channel "latest-created" pointer semantics.
-//
-// These cover the pure decision logic the fix is built on. The full component
-// load/swap flow (paint → check-fresh → swap) cannot be rendered in this
-// node-env Vitest suite (no jsdom/RTL), so the FLOW-level cases from the plan
-// (TC2/TC3/TC7/TC10) are exercised through the pure predicates the flow now
-// delegates to, plus the IndexedDB round-trip in chat-cache.test.ts (TC1).
-// ---------------------------------------------------------------------------
-
-describe("shouldPersistPointerForLoad (TODO-1: slow-path-only write gate)", () => {
- it("TC9 — fast path (targetConvId present) does NOT write the pointer", () => {
- // Opening ?conv=<old-id>: targetConvId is the explicit, possibly-old conv.
- expect(shouldPersistPointerForLoad("conv_old")).toBe(false);
- });
-
- it("TC2/TC3 — slow path (no targetConvId) DOES write the pointer", () => {
- // Param-less open: convId is server-resolved (latest-created) → persist it.
- expect(shouldPersistPointerForLoad(null)).toBe(true);
- expect(shouldPersistPointerForLoad(undefined)).toBe(true);
- });
-
- it("treats empty string targetConvId as no explicit target (slow path)", () => {
- // `?conv=` with an empty value never resolves a real conversation; the load
- // falls through to the slow path, so writing the resolved latest is correct.
- expect(shouldPersistPointerForLoad("")).toBe(true);
- });
-});
-
-describe("pointerRefreshTargetForTaskCreated (TODO-2: WS-driven refresh scope)", () => {
- const base = {
- agentId: "agent_a",
- activeChannel: "default",
- currentPointerConvId: "conv_current",
- };
- const task = (over: Partial<{ agent_id: string; channel: string | null; conversation_id: string }>) => ({
- agent_id: over.agent_id ?? "agent_a",
- channel: over.channel === undefined ? null : over.channel,
- conversation_id: over.conversation_id ?? "conv_new",
- });
-
- it("TC4 — newer conversation for this agent+channel → returns the new conv id", () => {
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- task: task({ agent_id: "agent_a", channel: "default", conversation_id: "conv_new" }),
- }),
- ).toBe("conv_new");
- });
-
- it("TC4 — null event channel normalizes to 'default' and matches the active default channel", () => {
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- task: task({ channel: null, conversation_id: "conv_new" }),
- }),
- ).toBe("conv_new");
- });
-
- it("matches a non-default named channel", () => {
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- activeChannel: "ops",
- task: task({ channel: "ops", conversation_id: "conv_new" }),
- }),
- ).toBe("conv_new");
- });
-
- it("TC5 — different agent → SKIP (returns null, never touches this pointer)", () => {
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- task: task({ agent_id: "agent_b", conversation_id: "conv_new" }),
- }),
- ).toBeNull();
- });
-
- it("TC5 — different channel → SKIP", () => {
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- activeChannel: "default",
- task: task({ channel: "ops", conversation_id: "conv_new" }),
- }),
- ).toBeNull();
- });
-
- it("no-op when the event already points at the current pointer conversation", () => {
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- currentPointerConvId: "conv_new",
- task: task({ conversation_id: "conv_new" }),
- }),
- ).toBeNull();
- });
-
- it("writes even when there is no current pointer yet (null current)", () => {
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- currentPointerConvId: null,
- task: task({ conversation_id: "conv_new" }),
- }),
- ).toBe("conv_new");
- });
-
- it("TC6 — undefined channel on the event normalizes to 'default' (no incorrect cross-channel write)", () => {
- // An event with no channel info is treated as the default channel, so it only
- // affects the default-channel pointer — never a named channel's pointer.
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- activeChannel: "ops",
- task: { agent_id: "agent_a", channel: undefined, conversation_id: "conv_new" },
- }),
- ).toBeNull();
- expect(
- pointerRefreshTargetForTaskCreated({
- ...base,
- activeChannel: "default",
- task: { agent_id: "agent_a", channel: undefined, conversation_id: "conv_new" },
- }),
- ).toBe("conv_new");
- });
-});
-
-// TC1 — grouping: same-role + <60s clusters into first/middle/last/solo;
-// event messages never group (stay null).
-describe("computeGroupPositions (TC1)", () => {
- const positionsFor = (msgs: Message[]) =>
- computeGroupPositions(buildTimeline(msgs, [], []));
-
- it("groups three same-role messages within 60s as first/middle/last", () => {
- const msgs = [
- msg("a", "2024-01-01T00:00:00Z", "user", "1"),
- msg("b", "2024-01-01T00:00:30Z", "user", "2"),
- msg("c", "2024-01-01T00:00:50Z", "user", "3"),
- ];
- expect(positionsFor(msgs)).toEqual(["first", "middle", "last"]);
- });
-
- it("breaks a cluster when the gap exceeds 60s", () => {
- const msgs = [
- msg("a", "2024-01-01T00:00:00Z", "user", "1"),
- msg("b", "2024-01-01T00:02:00Z", "user", "2"),
- ];
- expect(positionsFor(msgs)).toEqual(["solo", "solo"]);
- });
-
- it("breaks a cluster when the role changes", () => {
- const msgs = [
- msg("a", "2024-01-01T00:00:00Z", "user", "hi"),
- msg("b", "2024-01-01T00:00:10Z", "assistant", "hello"),
- ];
- expect(positionsFor(msgs)).toEqual(["solo", "solo"]);
- });
-
- it("groups events into the agent cluster (assistant + event share one header)", () => {
- const msgs = [
- msg("a", "2024-01-01T00:00:00Z", "assistant", "1"),
- msg("e", "2024-01-01T00:00:10Z", "event", "Email received"),
- msg("c", "2024-01-01T00:00:20Z", "assistant", "2"),
- ];
- // assistant + event are all the AGENT side → one cluster (Slack/Discord
- // model: a single avatar+name header, the rest continue in the gutter).
- expect(positionsFor(msgs)).toEqual(["first", "middle", "last"]);
- });
-
- it("keeps user and agent as separate clusters", () => {
- const msgs = [
- msg("u", "2024-01-01T00:00:00Z", "user", "hi"),
- msg("a", "2024-01-01T00:00:10Z", "assistant", "hello"),
- msg("e", "2024-01-01T00:00:20Z", "event", "Email sent"),
- ];
- // user is its own side; assistant+event group together.
- expect(positionsFor(msgs)).toEqual(["solo", "first", "last"]);
- });
-
- it("returns solo for a single message", () => {
- expect(positionsFor([msg("a", "2024-01-01T00:00:00Z", "user", "1")])).toEqual(["solo"]);
- });
-});
-
-// Planner's strengthened TODO-3 acceptance (cache-chat-cards): caching the
-// artifacts so they're present from the INSTANT paint fixes not just the
-// file-card pop-in but ALSO the event-card displacement. The event cards move
-// as a CONSEQUENCE of un-cached artifacts being inserted into the timeline on
-// the network response — same root cause. These tests prove that behavior
-// against the pure timeline/grouping functions (the render-timing assertions
-// remain QA browser checks since src/web has no jsdom/RTL harness).
-describe("cache-chat-cards: event cards don't reflow when artifacts are cached (TODO-3)", () => {
- // An agent-side cluster: assistant → event(email) → assistant, all within
- // 60s. Grouped alone, the event card is the MIDDLE of one cluster.
- const agentCluster: Message[] = [
- msg("a1", "2024-01-01T00:00:00Z", "assistant", "working on it"),
- msg("e1", "2024-01-01T00:00:20Z", "event", "New email from [email protected]: Subject"),
- msg("a2", "2024-01-01T00:00:40Z", "assistant", "done"),
- ];
- // An artifact uploaded chronologically BETWEEN the assistant and the event.
- // On the network response this inserts into the timeline next to the event.
- const arts = [artifact("art1", "2024-01-01T00:00:10Z")];
-
- it("ROOT CAUSE: an un-cached instant paint (artifacts=[]) yields a DIFFERENT timeline order than post-network", () => {
- const instantPaintUncached = buildTimeline(agentCluster, [], []);
- const postNetwork = buildTimeline(agentCluster, arts, []);
-
- // Without caching, the instant paint has no artifact; the network response
- // inserts it between a1 and e1 → the timeline restructures (reflow).
- expect(instantPaintUncached.map((i) => i.data.id)).toEqual(["a1", "e1", "a2"]);
- expect(postNetwork.map((i) => i.data.id)).toEqual(["a1", "art1", "e1", "a2"]);
- expect(instantPaintUncached.map((i) => i.data.id)).not.toEqual(
- postNetwork.map((i) => i.data.id),
- );
- });
-
- it("ROOT CAUSE: the inserted artifact flips the event card's cluster-header (group position) state", () => {
- const uncachedPositions = computeGroupPositions(buildTimeline(agentCluster, [], []));
- const postNetworkPositions = computeGroupPositions(buildTimeline(agentCluster, arts, []));
-
- // Uncached: [assistant, event, assistant] = one agent cluster → first/middle/last.
- expect(uncachedPositions).toEqual(["first", "middle", "last"]);
- // Post-network: [assistant, artifact, event, assistant] — the artifact is
- // still the same agent side, so it joins the cluster and the event card
- // shifts from "middle" to a later middle; the positions array changes shape
- // (now 4 items), so the per-card header state is NOT preserved across the
- // resolve. This is the visible displacement Gus reported.
- expect(postNetworkPositions).toEqual(["first", "middle", "middle", "last"]);
- expect(uncachedPositions).not.toEqual(postNetworkPositions);
- });
-
- it("FIX: a cached instant paint (artifacts present from frame 1) is IDENTICAL to the post-network timeline — no reflow", () => {
- // With conv_extras caching, setArtifacts(extras.artifacts) runs on the
- // instant paint, so buildTimeline sees the artifacts immediately. That
- // instant-paint timeline must equal the post-network one (same artifacts,
- // same conversation) → the network resolve causes ZERO structural change.
- const cachedInstantPaint = buildTimeline(agentCluster, arts, []);
- const postNetwork = buildTimeline(agentCluster, arts, []);
-
- expect(cachedInstantPaint.map((i) => i.data.id)).toEqual(
- postNetwork.map((i) => i.data.id),
- );
- expect(cachedInstantPaint.map((i) => i.kind)).toEqual(
- postNetwork.map((i) => i.kind),
- );
- });
-
- it("FIX: event-card group positions are stable across the resolve when artifacts are cached", () => {
- const cachedInstantPositions = computeGroupPositions(buildTimeline(agentCluster, arts, []));
- const postNetworkPositions = computeGroupPositions(buildTimeline(agentCluster, arts, []));
-
- // Identical group positions → no event card gains/loses its avatar+name
- // header when the network lands (the exact stability planner asked for).
- expect(cachedInstantPositions).toEqual(postNetworkPositions);
- });
-
- it("FIX: an event card that is first/solo on the cached paint stays first/solo after the network lands", () => {
- // A standalone event card (its own cluster: a different role/side neighbor
- // keeps it solo). An artifact landing in the SAME cluster window would flip
- // it from solo→first; caching the artifact means it's already accounted for
- // on the instant paint, so the position never changes.
- const msgs: Message[] = [
- msg("u1", "2024-01-01T00:00:00Z", "user", "hi"),
- msg("e1", "2024-01-01T00:05:00Z", "event", "Calendar event: standup"),
- ];
- const lateArt = [artifact("art2", "2024-01-01T00:05:10Z")];
-
- const cachedInstant = computeGroupPositions(buildTimeline(msgs, lateArt, []));
- const postNetwork = computeGroupPositions(buildTimeline(msgs, lateArt, []));
- expect(cachedInstant).toEqual(postNetwork);
-
- // And contrast: WITHOUT the cached artifact the event is solo, but WITH it
- // the event becomes "first" of a 2-card agent cluster — the very flip
- // caching prevents from happening after the network resolve.
- const uncached = computeGroupPositions(buildTimeline(msgs, [], []));
- expect(uncached).toEqual(["solo", "solo"]);
- expect(postNetwork).toEqual(["solo", "first", "last"]);
- });
-
- it("FIX: caching conversation_type keeps a metadata-less event card's icon stable (no heuristic→type flip)", () => {
- // Metadata-less event message: the icon/label is resolved by
- // eventTypeFromMessage → falls back to getEventIconType(content, type).
- // On a cached paint conversation_type is seeded, so the type-driven icon is
- // correct from frame 1 and does NOT change when the network confirms it.
- // Content whose keyword heuristic ("email") DISAGREES with the real
- // conversation type (calendar_event) — e.g. a calendar invite whose text
- // mentions email. This is exactly the metadata-less case where the icon
- // would flip if conversation.type isn't known on the instant paint.
- const content = "Calendar invite — reply via email to confirm";
- // Instant paint with cached conversation_type → correct (calendar) icon:
- const cachedIcon = eventTypeFromMessage({}, content, "calendar_event");
- // Post-network with the authoritative conversation_type → same icon:
- const networkIcon = eventTypeFromMessage({}, content, "calendar_event");
- expect(cachedIcon).toBe(networkIcon);
- expect(cachedIcon).toBe("calendar");
-
- // Without a cached type (conversation === null on the un-cached instant
- // paint), the keyword heuristic picks "email" for this content → the flip
- // to the type-driven "calendar" only happens after the network lands.
- const uncachedIcon = eventTypeFromMessage({}, content, undefined);
- expect(uncachedIcon).toBe("email");
- expect(uncachedIcon).not.toBe(networkIcon);
- });
-});
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
deleted file mode 100644
index 1fee65682..000000000
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ /dev/null
@@ -1,1201 +0,0 @@
-"use client";
-
-import { useObservedRegion } from "@/lib/observability/regions";
-import { viewEvidence } from "@/lib/observability/data-source";
-import { useArtifactClick } from "@/components/use-artifact-click";
-import { useMutation, useIsMutating } from "@tanstack/react-query";
-import { captureQueryReceipt, isQueryReceiptCurrent, type QueryReceipt } from "@/lib/query-receipt";
-import { captureChatIntent, assertChatIntent, runChatIntentRequest } from "@/hooks/workspace/use-chat-data";
-import { isAbortError } from "@/lib/errors";
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useMountedClock } from "@/hooks/use-mounted-clock";
-import { useEffect, useCallback, useMemo } from "react";
-import { useParams, useSearchParams } from "next/navigation";
-import { useWorkspaceOwner, useWorkspace } from "@/contexts/workspace-context";
-import { Button } from "@/components/ui/button";
-import { TaskStream } from "@/components/task-stream";
-import { cancelActiveTask, createThread } from "@/lib/api";
-import type { Artifact, Issue, SkillEntry } from "@alook/shared";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useInboxCount } from "@/contexts/inbox-count-context";
-import { useChannel } from "@/contexts/channel-context";
-import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import { Skeleton } from "@/components/ui/skeleton";
-import {
- Tooltip,
- TooltipTrigger,
- TooltipContent,
-} from "@/components/ui/tooltip";
-import {
- ArrowUp,
- BedDouble,
- FileText,
- Loader2,
- Mail,
- MessageSquareQuote,
- Paperclip,
- Square,
- X,
-} from "lucide-react";
-import { useChatThreadResources } from "@/hooks/workspace/use-chat-thread-resources";
-import { useAgentChat } from "@/hooks/use-agent-chat";
-import { useMessageFlags } from "@/hooks/use-message-flags";
-import { useChatSheets } from "@/hooks/use-chat-sheets";
-import { useChatArtifactSelection } from "@/hooks/workspace/use-chat-artifact-selection";
-import { useFileAttachments } from "@/hooks/use-file-attachments";
-import { useTextSelectionQuote } from "@/hooks/use-text-selection-quote";
-import { useSlashCommand } from "@/hooks/use-slash-command";
-import { SlashCommandPopup } from "@/components/agent-chat/slash-command-popup";
-import {
- ChatComposer,
- RotatingPlaceholderOverlay,
-} from "@/components/agent-chat/chat-composer";
-import { useRotatingPlaceholder } from "@/components/agent-chat/use-rotating-placeholder";
-import {
- ArtifactSheet,
- formatSize,
-} from "@/components/agent-chat/artifact-sheet";
-import { EmailEventSheet } from "@/components/agent-chat/email-event-sheet";
-import { ImageLightbox } from "@/components/agent-chat/image-lightbox";
-import { CalendarEventSheet } from "@/components/calendar/calendar-event-sheet";
-import { IssueSheet } from "@/components/issues/issue-sheet";
-import {
- computeArtifactVersions,
-} from "@/components/artifact-content-renderer";
-import { ScrollToBottomButton } from "@/components/ui/scroll-to-bottom-button";
-import { MessageItem, AgentRow } from "@/components/agent-chat/message-list";
-import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
-import { PresenceLine } from "@/components/agent-chat/presence-line";
-import { MenuToggleIcon } from "@/components/agent-chat/menu-toggle-icon";
-import {
- MENTION_COMPONENTS,
- NapSeparator,
- ArtifactCard,
-} from "@/components/agent-chat/chat-view-parts";
-import {
- Popover,
- PopoverTrigger,
- PopoverContent,
-} from "@/components/ui/popover";
-
-export function AgentChatView({
- agentId: propAgentId,
- targetConvId: propTargetConvId,
- scrollToTaskId: propScrollToTaskId,
- scrollToMessageId: propScrollToMessageId,
-}: {
- agentId?: string;
- targetConvId?: string | null;
- scrollToTaskId?: string | null;
- scrollToMessageId?: string | null;
-}) {
- const params = useParams();
- const searchParams = useSearchParams();
- const workspaceOwner = useWorkspaceOwner();
- const { workspaceId, slug } = useWorkspace();
- const {
- agents,
- runtimes,
- agentLinks,
- activeTaskCounts,
- subscribeWs,
- subscribeReconnect,
- } = useAgentContext();
- const { refresh: refreshInboxCount } = useInboxCount();
- const {
- activeChannel,
- readActiveChannel,
- loading: channelLoading,
- setAgentId: setChannelAgentId,
- } = useChannel();
- const agentId = propAgentId ?? (params.id as string);
- // Resolve the conversation agent's runtime provider so runtime errors can be
- // attributed to the runtime CLI (Claude Code / Codex / OpenCode) — issue #236.
- const activeAgent = agents.find((a) => a.id === agentId);
- const activeRuntime = activeAgent?.runtime_id
- ? runtimes.find((r) => r.id === activeAgent.runtime_id)
- : null;
- const runtimeProvider = activeRuntime?.provider ?? null;
- const scrollToTaskId =
- propScrollToTaskId !== undefined
- ? propScrollToTaskId
- : searchParams.get("task");
- const scrollToMessageId =
- propScrollToMessageId !== undefined
- ? propScrollToMessageId
- : searchParams.get("msg");
- const targetConvId =
- propTargetConvId !== undefined
- ? propTargetConvId
- : searchParams.get("conv");
-
- const inputAtom = useCreateAtom(useMemo(() => {
- if (typeof window === "undefined") return "";
- return (
- localStorage.getItem(
- `chat-draft:${workspaceOwner.application.userId}:${workspaceId}:${agentId}:${targetConvId ?? "default"}`,
- ) ?? ""
- );
- }, [agentId, targetConvId, workspaceId, workspaceOwner.application.userId]));
- const [input, setInput] = useAtom(inputAtom);
- const [composerFocused, setComposerFocused] = useAtom(useCreateAtom(false));
- const [lightboxLocalUrl, setLightboxLocalUrl] = useAtom(useCreateAtom<{ url: string; filename: string } | null>(null));
- const {
- pendingFiles,
- readPendingFiles,
- setPendingFiles,
- fileInputRef,
- addPendingFiles,
- handleFileSelect,
- removePendingFile,
- dragging,
- handleDragEnter,
- handleDragLeave,
- handleDragOver,
- handleDrop,
- } = useFileAttachments();
- const [caretIndex, setCaretIndex] = useAtom(useCreateAtom<number | null>(null));
- const [renderNow] = useMountedClock();
-
- const quotedMessageAtom = useCreateAtom<{ id: string; excerpt: string } | null>(useMemo<{ id: string; excerpt: string } | null>(() => {
- if (typeof window === "undefined") return null;
- try {
- const meta = JSON.parse(
- localStorage.getItem(
- `chat-draft-meta:${workspaceOwner.application.userId}:${workspaceId}:${agentId}:${targetConvId ?? "default"}`,
- ) ?? "null",
- );
- const q = meta?.quote;
- return q && typeof q === "object" && q.id ? q : null;
- } catch {
- return null;
- }
- }, [agentId, targetConvId, workspaceId, workspaceOwner.application.userId]));
- const [quotedMessage, setQuotedMessage] = useAtom(quotedMessageAtom);
- const [isMultiLine, setIsMultiLine] = useAtom(useCreateAtom(false));
-
- // Thread state
- const { openAgentChat } = useAgentChatSheet();
-
- useEffect(() => {
- setChannelAgentId(agentId);
- }, [agentId, setChannelAgentId]);
-
- const draftRestored = useCreateAtom(false);
- const activeSkillNameAtom = useCreateAtom<string | null>(useMemo<string | null>(() => {
- try { return JSON.parse(localStorage.getItem(`chat-draft-meta:${workspaceOwner.application.userId}:${workspaceId}:${agentId}:${targetConvId ?? "default"}`) ?? "null")?.skill?.name ?? null; } catch { return null; }
- }, [agentId, targetConvId, workspaceId, workspaceOwner.application.userId]));
-
- const chat = useAgentChat(
- {
- agentId,
- targetConvId,
- scrollToTaskId,
- scrollToMessageId,
- propTargetConvId,
- workspaceId,
- agents,
- activeChannel,
- readActiveChannel,
- channelLoading,
- subscribeWs,
- subscribeReconnect,
- refreshInboxCount,
- },
- {
- setPendingFiles,
- setInput,
- setQuotedMessage,
- setActiveSkill: (skill: SkillEntry | null) => activeSkillNameAtom.set(skill?.name ?? null),
- clearActiveSkill: () => activeSkillNameAtom.set(null),
- readInput: inputAtom.get,
- readQuotedMessage: quotedMessageAtom.get,
- readPendingFiles,
- readActiveSkill: () => workspaceOwner.queryClient.getQueryData<SkillEntry[]>(workspaceOwner.key("agent-skills", agentId))?.find((skill) => skill.name === activeSkillNameAtom.get()) ?? null,
- markDraftRestored: () => draftRestored.set(true),
- },
- );
-
- const {
- conversation,
- messages,
- sending,
- activeTask,
- taskMessages,
- messagesLoading,
- connectionLost,
- loadingMore,
- artifacts,
- napping,
- pendingFilesByMessage,
- failedSends,
- stableKeyMap,
- agentArtifacts,
- agentName,
- timeline,
- groupPositions,
- activeTaskStreamMsgId,
- canLoadMore,
- currentConvHasMessages,
- scrollRef,
- composerRef,
- loadOlderMessages,
- handleScroll,
- handleSend,
- handleRetrySend,
- handleRetryTask,
- handleNap,
- } = chat;
-
- const {
- artifactSheetOpen,
- setArtifactSheetOpen,
- selectedArtifact,
- setSelectedArtifact,
- emailSheetOpen,
- setEmailSheetOpen,
- selectedEmailId,
- setSelectedEmailId,
- calendarEventSheetOpen,
- setCalendarEventSheetOpen,
- selectedCalendarEventId,
- setSelectedCalendarEventId,
- issueSheetOpen,
- setIssueSheetOpen,
- selectedIssueId,
- issueDetail,
- issueDetailLoading,
- issueTraceTasks,
- issueActiveTask,
- openIssue,
- updateSelectedIssue,
- } = useChatSheets(workspaceOwner, chat.chatView);
- const [lightboxArtifact, setLightboxArtifact] = useChatArtifactSelection(workspaceOwner, chat.chatView, selectedIssueId);
-
- const { flaggedIds, handleToggleFlag } = useMessageFlags(workspaceOwner, chat.chatView, conversation?.id ?? null);
-
- const chatActionKey = useMemo(() => workspaceOwner.key("chat", "action", crypto.randomUUID()), [workspaceOwner]);
- type ChatAction = { original: ReturnType<typeof captureChatIntent>; conversationId: string; resources: Map<string, QueryReceipt> } & ({ kind: "thread"; messageId: string } | { kind: "stop" });
- const chatAction = useMutation({ meta: { observabilityAction: "chat.control.command" }, mutationKey: chatActionKey, gcTime: 0, scope: { id: JSON.stringify(chatActionKey) },
- mutationFn: async (action: ChatAction) => {
- assertChatIntent(action.original);
- return runChatIntentRequest(action.original, async (options) => {
- if (action.kind === "thread") return createThread(action.conversationId, action.messageId, "", workspaceId, options);
- const task = await cancelActiveTask(action.conversationId, workspaceId, options);
- assertChatIntent(action.original);
- const key = workspaceOwner.key("chat", "task", task.id), ticket = action.resources.get(JSON.stringify(key));
- if (ticket ? isQueryReceiptCurrent(ticket) : !workspaceOwner.queryClient.getQueryCache().find({ queryKey: key, exact: true })) workspaceOwner.queryClient.setQueryData(key, task);
- return task;
- });
- },
- });
- const stopping = useIsMutating({ mutationKey: chatActionKey, exact: true, predicate: (mutation) => (mutation.state.variables as ChatAction).kind === "stop" }) > 0;
- const captureChatAction = () => {
- const original = captureChatIntent(workspaceOwner, chat.chatView); assertChatIntent(original);
- return { original, resources: new Map(workspaceOwner.queryClient.getQueryCache().findAll({ queryKey: workspaceOwner.key("chat", "task") }).map((query) => [JSON.stringify(query.queryKey), captureQueryReceipt(workspaceOwner.queryClient, query.queryKey)])) };
- };
-
- const { versionMap, duplicateFilenames } = useMemo(
- () => computeArtifactVersions(agentArtifacts),
- [agentArtifacts],
- );
-
- const { threadRootMessage, threadSummaries, readThreadSummary, summariesKey, agentSkills } = useChatThreadResources(workspaceOwner, chat.chatView, conversation, agentId, subscribeWs);
-
- const agentAvatarUrl = useMemo(
- () => agents.find((a) => a.id === agentId)?.avatar_url ?? null,
- [agents, agentId],
- );
- // First name only — presence copy reads socially ("Maya is typing…").
- const agentFirstName = useMemo(() => agentName.split(/\s+/)[0] || agentName, [agentName]);
-
- const handlePendingImageClick = useCallback(
- (file: File) => {
- const url = URL.createObjectURL(file);
- setLightboxLocalUrl({ url, filename: file.name });
- },
- [setLightboxLocalUrl],
- );
-
- const previewArtifact = useCallback((artifact: Artifact) => {
- setSelectedArtifact(artifact);
- setArtifactSheetOpen(true);
- }, [setSelectedArtifact, setArtifactSheetOpen]);
- const handleArtifactClick = useArtifactClick(workspaceId, previewArtifact, setLightboxArtifact, JSON.stringify([agentId, targetConvId, activeChannel, selectedIssueId]));
- const handleIssueArtifactClick = useArtifactClick(workspaceId, previewArtifact, setLightboxArtifact, JSON.stringify([agentId, targetConvId, activeChannel, selectedIssueId]));
-
- // Editor plain text + caret, reported up from the composer, drive the
- // slash-command popup (mentions are handled natively inside the composer).
- const [editorText, setEditorText] = useAtom(useCreateAtom(""));
-
- const otherAgents = useMemo(
- () => agents.filter((a) => a.id !== agentId),
- [agents, agentId],
- );
-
- const slashCommand = useSlashCommand({
- input: editorText,
- caretIndex,
- skills: agentSkills,
- onInputChange: () => composerRef.current?.clear(),
- activeSkillNameAtom,
- getAnchorPos: useCallback(
- (triggerStart: number) =>
- composerRef.current?.coordsAtTextIndex(triggerStart) ?? null,
- // eslint-disable-next-line react-hooks/exhaustive-deps -- composerRef is stable
- [],
- ),
- onAfterSelect: useCallback(() => {
- requestAnimationFrame(() => composerRef.current?.focus());
- // eslint-disable-next-line react-hooks/exhaustive-deps -- composerRef is stable
- }, []),
- });
-
- useEffect(() => {
- if (agentSkills.length === 0 || !slashCommand.activeSkill) return;
- const exists = agentSkills.some(
- (s) => s.name === slashCommand.activeSkill!.name,
- );
- if (!exists) slashCommand.setActiveSkill(null);
- // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally omits slashCommand; only re-validate when the skills list itself changes
- }, [agentSkills]);
-
- useEffect(() => {
- const key = `chat-draft:${workspaceOwner.application.userId}:${workspaceId}:${agentId}:${targetConvId ?? "default"}`;
- if (input) {
- localStorage.setItem(key, input);
- } else {
- localStorage.removeItem(key);
- }
- }, [input, agentId, targetConvId, workspaceOwner.application.userId, workspaceId]);
-
- useEffect(() => {
- if (!draftRestored.get()) return;
- const key = `chat-draft-meta:${workspaceOwner.application.userId}:${workspaceId}:${agentId}:${targetConvId ?? "default"}`;
- const meta: {
- skill?: { name: string; description: string } | null;
- quote?: { id: string; excerpt: string } | null;
- } = {};
- if (slashCommand.activeSkill) {
- meta.skill = {
- name: slashCommand.activeSkill.name,
- description: slashCommand.activeSkill.description,
- };
- }
- if (quotedMessage) {
- meta.quote = quotedMessage;
- }
- if (meta.skill || meta.quote) {
- localStorage.setItem(key, JSON.stringify(meta));
- } else {
- localStorage.removeItem(key);
- }
- }, [slashCommand.activeSkill, quotedMessage, agentId, targetConvId, draftRestored, workspaceOwner.application.userId, workspaceId]);
-
- useEffect(() => {
- if (!sending) {
- composerRef.current?.focus();
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps -- composerRef is stable
- }, [sending]);
-
-
- const { selectionPopup, setSelectionPopup } = useTextSelectionQuote();
-
- const handleQuoteSelection = useCallback(() => {
- if (selectionPopup) {
- const excerpt = selectionPopup.text.slice(0, 100);
- setQuotedMessage(
- selectionPopup.messageId
- ? { id: selectionPopup.messageId, excerpt }
- : null,
- );
- setSelectionPopup(null);
- window.getSelection()?.removeAllRanges();
- composerRef.current?.focus();
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps -- composerRef and setSelectionPopup are stable
- }, [selectionPopup]);
-
- const handleQuoteMessage = useCallback((messageId: string, excerpt: string) => {
- setQuotedMessage({ id: messageId, excerpt });
- composerRef.current?.focus();
- // eslint-disable-next-line react-hooks/exhaustive-deps -- composerRef is stable
- }, []);
-
- const handleEmailClick = useCallback((emailId: string) => {
- setSelectedEmailId(emailId);
- setEmailSheetOpen(true);
- // eslint-disable-next-line react-hooks/exhaustive-deps -- setState fns are stable
- }, []);
-
- const handleCalendarEventClick = useCallback((id: string) => {
- setSelectedCalendarEventId(id);
- setCalendarEventSheetOpen(true);
- // eslint-disable-next-line react-hooks/exhaustive-deps -- setState fns are stable
- }, []);
-
- const handleIssueClick = useCallback((issueId: string) => {
- openIssue(issueId);
- }, [openIssue]);
-
- const handleAgentChatOpen = useCallback((agId: string, convId: string) => {
- openAgentChat(agId, { conversationId: convId });
- }, [openAgentChat]);
-
- const handleReplyInThread = async (msgId: string) => {
- const action = captureChatAction(), current = chat.readConversation();
- const summary = readThreadSummary(msgId);
- if (summary?.thread_id) { openAgentChat(agentId, { conversationId: summary.thread_id }); return; }
- if (!current || workspaceOwner.queryClient.isMutating({ mutationKey: chatActionKey, exact: true })) return;
- const summaryResource = workspaceOwner.queryClient.getQueryCache().find({ queryKey: summariesKey, exact: true });
- try {
- const result = await chatAction.mutateAsync({ ...action, kind: "thread", conversationId: current.id, messageId: msgId }) as Awaited<ReturnType<typeof createThread>>;
- assertChatIntent(action.original);
- if (summaryResource && workspaceOwner.queryClient.getQueryCache().find({ queryKey: summariesKey, exact: true }) === summaryResource) void workspaceOwner.queryClient.invalidateQueries({ queryKey: summariesKey, exact: true }).catch(() => undefined);
- openAgentChat(agentId, { conversationId: result.conversation.id });
- } catch (error) {
- try { assertChatIntent(action.original); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to create thread");
- }
- };
-
- const [menuOpen, setMenuOpen] = useAtom(useCreateAtom(false));
- const isTaskActive = !!activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
- const handleStop = async () => {
- const action = captureChatAction(), current = chat.readConversation();
- if (!current || workspaceOwner.queryClient.isMutating({ mutationKey: chatActionKey, exact: true, predicate: (mutation) => (mutation.state.variables as ChatAction).kind === "stop" })) return;
- try { await chatAction.mutateAsync({ ...action, kind: "stop", conversationId: current.id }); }
- catch (error) {
- try { assertChatIntent(action.original); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to stop the task");
- }
- };
-
- // Rotating capability-hint placeholder for the idle, empty composer. Freezes
- // on focus/typing, resumes on empty blur; never rotates while a task is
- // active (that path shows the static "Message {Name}" overlay below instead).
- const rotatingPlaceholder = useRotatingPlaceholder({
- isEmpty: input.trim() === "",
- isFocused: composerFocused,
- isTaskActive,
- });
-
- useObservedRegion("chat", !messagesLoading, viewEvidence(messages));
- if (messagesLoading) {
- return (
- <>
- <div className="flex-1 overflow-y-auto px-3 sm:px-4">
- <div className="mx-auto max-w-3xl py-6 space-y-6 motion-safe:animate-[fade-up_200ms_ease-out_both]">
- {/* Agent cluster — top [avatar][name] header, bubbles stacked below
- in the gutter (mirrors AgentRow's Slack/Discord layout). */}
- <div className="flex justify-start items-start gap-2">
- <Skeleton className="size-7.5 shrink-0 rounded-md" />
- <div className="flex flex-col items-start gap-1 max-w-[86%]">
- <Skeleton className="h-3 w-20 rounded mb-1" />
- <Skeleton className="h-9 w-64 rounded-[1.05rem]" />
- <Skeleton className="h-9 w-48 rounded-[1.05rem]" />
- </div>
- </div>
- {/* User cluster — right pills, no avatar/name */}
- <div className="flex flex-col items-end gap-1">
- <Skeleton className="h-9 w-44 rounded-[1.05rem]" />
- <Skeleton className="h-9 w-32 rounded-[1.05rem]" />
- </div>
- {/* Another agent cluster */}
- <div className="flex justify-start items-start gap-2">
- <Skeleton className="size-7.5 shrink-0 rounded-md" />
- <div className="flex flex-col items-start gap-1 max-w-[86%]">
- <Skeleton className="h-3 w-20 rounded mb-1" />
- <Skeleton className="h-9 w-56 rounded-[1.05rem]" />
- </div>
- </div>
- </div>
- </div>
- {/* Presence line + input — mirror the real layout exactly so nothing
- shifts on load: presence row (h-5 + mb-2) above, then the composer
- row of [overflow button][pill][symmetric spacer]. */}
- <div data-keyboard-offset className="relative z-10 px-3 sm:px-4 pt-3 pb-[max(1.25rem,env(safe-area-inset-bottom))] sm:pb-6">
- <div className="mx-auto max-w-3xl">
- <div className="h-5 px-1 mb-2 flex items-center">
- <Skeleton className="h-3.5 w-28 rounded" />
- </div>
- <div className="flex items-center gap-2">
- <Skeleton className="size-8 shrink-0 rounded-full" />
- <Skeleton className="h-10 flex-1 rounded-3xl" />
- </div>
- </div>
- </div>
- </>
- );
- }
-
- if (!messagesLoading && !conversation && messages.length === 0) {
- return (
- <div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
- Failed to load conversation
- </div>
- );
- }
-
- return (
- <>
- {/* Floating quote button on text selection */}
- {selectionPopup && (
- <button
- type="button"
- className="fixed z-50 flex items-center gap-1 px-2 py-1 rounded-md bg-popover border shadow-md text-xs text-popover-foreground hover:bg-accent transition-colors"
- style={{
- left: selectionPopup.x,
- top: selectionPopup.y,
- transform: "translate(-100%, -100%)",
- }}
- onMouseDown={(e) => e.preventDefault()}
- onClick={handleQuoteSelection}
- >
- <MessageSquareQuote className="size-3" />
- Quote
- </button>
- )}
- {/* Messages */}
- <div className="relative flex-1 min-h-0">
- <div
- className="h-full overflow-y-auto overflow-x-hidden px-3 sm:px-4 thin-scrollbar"
- ref={scrollRef}
- onScroll={handleScroll}
- onClick={(e) => {
- const btn = (e.target as HTMLElement).closest(
- '[data-streamdown="code-block-actions"] button',
- );
- if (btn) toast.success("Copied to clipboard");
- }}
- >
- <div className="mx-auto max-w-3xl pt-6 pb-15 min-w-0">
- {/* Root message for thread conversations — rendered as a normal MessageItem with flagged emphasis + corner icon, no actions */}
- {threadRootMessage && (
- <div className="mb-2">
- <MessageItem
- msg={threadRootMessage}
- agents={agents}
- artifacts={[]}
- activeTask={null}
- taskMessages={[]}
- connectionLost={false}
- pendingFilesByMessage={new Map()}
- workspaceId={workspaceId}
- onArtifactClick={() => {}}
- onEmailClick={() => {}}
- onIssueClick={() => {}}
- onCalendarEventClick={() => {}}
- mentionComponents={MENTION_COMPONENTS}
- groupPosition="solo"
- agentName={agentName}
- agentAvatarSeed={agentId} agentAvatarUrl={agentAvatarUrl}
- isThreadRoot
- />
- </div>
- )}
- {conversation && canLoadMore && !loadingMore && (
- <div className="flex justify-center py-2">
- <button
- onClick={() => loadOlderMessages()}
- className="text-xs text-muted-foreground hover:text-foreground transition-colors"
- >
- Load earlier messages
- </button>
- </div>
- )}
- {loadingMore && (
- <div className="flex justify-center py-2">
- <Loader2 className="size-4 animate-spin text-muted-foreground" />
- </div>
- )}
-
- {messages.length === 0 &&
- !activeTask &&
- (() => {
- const agent = agents.find((a) => a.id === agentId);
- const isNewAgent =
- agent?.created_at &&
- renderNow - new Date(agent.created_at).getTime() <
- 5 * 60 * 1000;
- const hasEmailTask = (activeTaskCounts[agentId] ?? 0) > 0;
-
- if (isNewAgent && hasEmailTask && activeChannel === "default") {
- return (
- <div className="flex flex-col items-center justify-center py-20 gap-3 animate-[fade-up_400ms_ease-out_both]">
- <div className="relative animate-bounce">
- <Mail className="size-8 text-primary" />
- <span className="absolute -top-1 -right-1 flex size-3">
- <span className="animate-ping absolute inline-flex size-full rounded-full bg-primary/60" />
- <span className="relative inline-flex size-3 rounded-full bg-primary" />
- </span>
- </div>
- <p className="text-sm text-muted-foreground text-center max-w-xs">
- Your agent is sending you a welcome email.
- </p>
- <p className="text-xs text-muted-foreground/60 text-center max-w-xs">
- Wait for the email task in the top-left to complete,
- then check your inbox. Or send a message below to start
- chatting.
- </p>
- </div>
- );
- }
-
- return (
- <p className="text-center text-muted-foreground py-20 text-base animate-[fade-up_400ms_ease-out_both]">
- Say hi to {agentFirstName}.
- </p>
- );
- })()}
-
- {timeline.map((item, idx) => {
- const pos = groupPositions[idx];
- const isGroupStart =
- pos === "first" || pos === "solo" || pos === null;
- // mt-6 between clusters, mt-2 between grouped bubbles within a cluster.
- const spacing = idx === 0 ? "" : isGroupStart ? "mt-6" : "mt-2";
-
- if (item.kind === "nap") {
- return (
- <div key={item.data.id} className={spacing}>
- <NapSeparator agentName={agentName} />
- </div>
- );
- }
-
- if (item.kind === "artifact") {
- // A file card is part of the agent's cluster (computeGroupPositions
- // groups it with adjacent agent items). It shows the avatar + name
- // only when it's the cluster HEAD (first/solo) — e.g. a file
- // uploaded mid-task before any reply exists; otherwise a spacer, so
- // it never renders as an orphaned, avatar-less "empty file" state.
- const artifactPos = pos ?? "solo";
- const isHead = artifactPos === "first" || artifactPos === "solo";
- return (
- <div key={`artifact-${item.data.id}`} className={spacing}>
- <AgentRow
- groupPosition={artifactPos}
- agentName={agentName}
- seed={agentId} avatarUrl={agentAvatarUrl}
- forceSpacer={!isHead}
- >
- <ArtifactCard
- artifact={item.data}
- version={versionMap.get(item.data.id) ?? 1}
- hasDuplicates={duplicateFilenames.has(item.data.filename)}
- onClick={handleArtifactClick}
- workspaceId={workspaceId}
- />
- </AgentRow>
- </div>
- );
- }
-
- const msg = item.data;
- // Use the original optimistic ID as the React key when available,
- // so replacing "temp-xxx" → "msg_abc" is an in-place UPDATE (same
- // key, new props) instead of an unmount+remount — eliminating the
- // visual flicker that occurred when the entire message row was torn
- // down and rebuilt with a different key.
- const stableKey = stableKeyMap.get(msg.id) ?? msg.id;
- return (
- <div key={stableKey} className={spacing}>
- <MessageItem
- msg={msg}
- agents={agents}
- artifacts={artifacts}
- activeTask={activeTask}
- activeTaskStreamMsgId={activeTaskStreamMsgId}
- taskMessages={taskMessages}
- connectionLost={connectionLost}
- conversationType={conversation?.type}
- pendingFilesByMessage={pendingFilesByMessage}
- workspaceId={workspaceId}
- onArtifactClick={handleArtifactClick}
- onPendingImageClick={handlePendingImageClick}
- onEmailClick={handleEmailClick}
- onCalendarEventClick={handleCalendarEventClick}
- onIssueClick={handleIssueClick}
- onRetry={handleRetryTask}
- mentionComponents={MENTION_COMPONENTS}
- isFlagged={flaggedIds.has(msg.id)}
- onToggleFlag={
- msg.role === "assistant" ? handleToggleFlag : undefined
- }
- groupPosition={pos ?? "solo"}
- provider={runtimeProvider}
- agentName={agentName}
- agentAvatarSeed={agentId} agentAvatarUrl={agentAvatarUrl}
- isSendFailed={failedSends.has(msg.id)}
- onRetrySend={handleRetrySend}
- onQuote={handleQuoteMessage}
- onReplyInThread={conversation?.parent_message_id ? undefined : handleReplyInThread}
- threadSummary={conversation?.parent_message_id ? null : threadSummaries.get(msg.id) ?? null}
- onAgentChatOpen={handleAgentChatOpen}
- />
- </div>
- );
- })}
-
- {/* Show trace while task is in progress (no assistant message yet).
- Once a send-dm reply exists, the designated last message
- (activeTaskStreamMsgId) owns the error surface — suppress this
- standalone block then, so an error never renders twice (QA AC4). */}
- {activeTask &&
- activeTask.conversation_id === conversation?.id &&
- activeTaskStreamMsgId == null &&
- !["completed", "failed", "cancelled", "superseded"].includes(
- activeTask.status,
- ) && (
- <div className="mt-4">
- <TaskStream
- task={activeTask}
- messages={taskMessages}
- connectionLost={connectionLost}
- provider={runtimeProvider}
- />
- </div>
- )}
- </div>
- </div>
- <ScrollToBottomButton scrollRef={scrollRef} />
- </div>
-
- {/* Input */}
- <div data-keyboard-offset className="relative z-10 px-3 sm:px-4 pt-3 pb-[max(1.25rem,env(safe-area-inset-bottom))] sm:pb-6">
- <div className="mx-auto max-w-3xl relative">
- {/* Social presence line — "{Name} is typing…" while this conversation
- has a live task (dispatched / queued / running), else nothing. */}
- {conversation && (
- <PresenceLine
- agentFirstName={agentFirstName}
- taskStatus={isTaskActive ? activeTask?.status : null}
- />
- )}
- <div className="flex items-end gap-2">
- {/* Overflow menu */}
- {!targetConvId && (
- <Popover open={menuOpen} onOpenChange={setMenuOpen}>
- <PopoverTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- className="shrink-0 self-end mb-2 size-8 rounded-full text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
- />
- }
- >
- <MenuToggleIcon open={menuOpen} />
- </PopoverTrigger>
- <PopoverContent
- side="top"
- align="start"
- className="w-auto p-2 flex flex-col gap-1"
- >
- <Tooltip>
- <TooltipTrigger
- render={(props) => (
- <span
- {...props}
- className={cn("inline-flex", props.className)}
- >
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- setMenuOpen(false);
- handleNap();
- }}
- disabled={
- napping ||
- !conversation ||
- !currentConvHasMessages ||
- isTaskActive
- }
- className="w-full justify-start gap-2 rounded-md text-muted-foreground hover:text-foreground"
- >
- {napping ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <BedDouble className="size-3.5" />
- )}
- <span className="text-xs">Nap</span>
- </Button>
- </span>
- )}
- />
- <TooltipContent side="right">
- {isTaskActive
- ? "Wait for the task to finish"
- : currentConvHasMessages
- ? "Take a nap and reset the current session"
- : `${agentName} is well-rested and ready to go`}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(props) => (
- <span
- {...props}
- className={cn("inline-flex", props.className)}
- >
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- setMenuOpen(false);
- handleStop();
- }}
- disabled={stopping || !isTaskActive}
- className="w-full justify-start gap-2 rounded-md text-muted-foreground hover:text-foreground"
- >
- {stopping ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <Square className="size-3.5" />
- )}
- <span className="text-xs">Stop</span>
- </Button>
- </span>
- )}
- />
- <TooltipContent side="right">
- {isTaskActive
- ? "Stop the running task"
- : "No task running"}
- </TooltipContent>
- </Tooltip>
- </PopoverContent>
- </Popover>
- )}
-
- {/* Pill container */}
- <div
- className={cn(
- "relative flex-1 min-w-0 flex flex-col rounded-3xl border border-border/50 bg-background/90 transition-[border-radius] duration-200",
- "focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",
- (isMultiLine || quotedMessage || slashCommand.activeSkill) &&
- "rounded-2xl",
- sending && "opacity-50",
- dragging && "border-ring ring-3 ring-ring/50",
- )}
- onDragEnter={handleDragEnter}
- onDragLeave={handleDragLeave}
- onDragOver={handleDragOver}
- onDrop={handleDrop}
- >
- {dragging && (
- <div
- className={cn(
- "absolute inset-0 z-10 flex items-center justify-center bg-background/80 border-2 border-dashed border-ring pointer-events-none",
- isMultiLine || quotedMessage || slashCommand.activeSkill
- ? "rounded-2xl"
- : "rounded-3xl",
- )}
- >
- <p className="text-sm text-muted-foreground font-medium">
- Drop files here
- </p>
- </div>
- )}
- {slashCommand.activeSkill && (
- <div className="flex items-center gap-2 px-4 pt-2.5 pb-1 border-b border-border/50">
- <div className="flex-1 min-w-0 flex items-center gap-2">
- <span className="shrink-0 text-xs font-medium text-primary">
- /{slashCommand.activeSkill.name}
- </span>
- {slashCommand.activeSkill.isGlobal && (
- <span className="text-[10px] font-medium text-muted-foreground bg-muted rounded px-1 py-1">
- Global
- </span>
- )}
- <span className="text-xs text-muted-foreground truncate">
- {slashCommand.activeSkill.description}
- </span>
- </div>
- <button
- type="button"
- onClick={slashCommand.clearActiveSkill}
- className="shrink-0 p-1 rounded-sm hover:bg-muted-foreground/20 transition-colors text-muted-foreground"
- >
- <X className="size-3.5" />
- </button>
- </div>
- )}
- {quotedMessage && (
- <div className="flex items-center gap-2 px-4 pt-2.5 pb-1 border-b border-border/50">
- <div className="flex-1 min-w-0 flex items-start gap-2">
- <MessageSquareQuote className="size-3.5 shrink-0 mt-1 text-muted-foreground" />
- <p className="text-xs text-muted-foreground truncate max-w-50">
- {quotedMessage.excerpt}
- </p>
- </div>
- <button
- type="button"
- onClick={() => setQuotedMessage(null)}
- className="shrink-0 p-1 rounded-sm hover:bg-muted-foreground/20 transition-colors text-muted-foreground"
- >
- <X className="size-3.5" />
- </button>
- </div>
- )}
- <SlashCommandPopup
- isOpen={slashCommand.isOpen}
- skills={slashCommand.skills}
- selectedIndex={slashCommand.selectedIndex}
- onSelect={slashCommand.selectSkill}
- getAnchorRect={slashCommand.getAnchorRect}
- />
- {/* Pending file previews — images and non-images in separate rows */}
- {pendingFiles.length > 0 && (() => {
- const images = pendingFiles.map((pf, i) => ({ pf, i })).filter(({ pf }) => pf.thumbnailUrl);
- const others = pendingFiles.map((pf, i) => ({ pf, i })).filter(({ pf }) => !pf.thumbnailUrl);
- return (
- <div className="px-4 pt-3 pb-0.5 space-y-2">
- {images.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {images.map(({ pf, i }) => (
- <div key={`${pf.file.name}-${i}`} className="relative group">
- <button
- type="button"
- onClick={() => {
- const url = URL.createObjectURL(pf.file);
- setLightboxLocalUrl({ url, filename: pf.file.name });
- }}
- className="cursor-pointer"
- >
- <img
- src={pf.thumbnailUrl!}
- alt={pf.file.name}
- className="h-12 w-auto rounded-md object-cover"
- />
- </button>
- <button
- type="button"
- onClick={() => removePendingFile(i)}
- className="absolute -top-2 -right-2 size-4 rounded-full bg-muted-foreground text-background flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
- >
- <X className="size-2.5" />
- </button>
- </div>
- ))}
- </div>
- )}
- {others.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {others.map(({ pf, i }) => (
- <span
- key={`${pf.file.name}-${i}`}
- className="inline-flex items-center gap-2 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground"
- >
- <FileText className="size-3 shrink-0" />
- <span className="truncate max-w-30">{pf.file.name}</span>
- <span className="text-muted-foreground/60">
- {formatSize(pf.file.size)}
- </span>
- <button
- type="button"
- onClick={() => removePendingFile(i)}
- className="ml-1 rounded-sm p-1 hover:bg-muted-foreground/20 transition-colors"
- >
- <X className="size-3" />
- </button>
- </span>
- ))}
- </div>
- )}
- </div>
- );
- })()}
- {/* Composer + absolutely-positioned buttons */}
- <div className="relative">
- <input
- ref={fileInputRef}
- type="file"
- multiple
- className="hidden"
- onChange={handleFileSelect}
- />
- {/* Padding wrapper: vertical breathing room lives here so it
- survives editor scrolling — the .tiptap element owns no padding. */}
- <div className="px-13 py-3">
- <ChatComposer
- ref={composerRef}
- value={input}
- onChange={setInput}
- onEditorState={(text, caret) => {
- setEditorText(text);
- setCaretIndex(caret);
- }}
- onSend={handleSend}
- onFocus={() => setComposerFocused(true)}
- onBlur={() => setComposerFocused(false)}
- // The overlay is the SOLE placeholder renderer (TipTap's own
- // placeholder stays "" — it can't reactively update post-init,
- // which is what caused the active↔idle double-image). Shown
- // whenever the field is empty, in both states:
- // • active task → static "Message {Name}" (no rotation). Warm,
- // no period (Priya); reads the same whether or not a task runs.
- // • idle → the rotating capability hint.
- overlay={
- input.trim() === "" ? (
- isTaskActive ? (
- <RotatingPlaceholderOverlay
- hint={`Message ${agentFirstName}`}
- animate={false}
- />
- ) : (
- <RotatingPlaceholderOverlay
- hint={rotatingPlaceholder.hint}
- animate={rotatingPlaceholder.isRotating}
- />
- )
- ) : undefined
- }
- disabled={sending}
- onMultiLineChange={setIsMultiLine}
- onFiles={addPendingFiles}
- agents={otherAgents}
- agentLinks={agentLinks}
- currentAgentId={agentId}
- slashIsOpen={slashCommand.isOpen}
- onSlashKeyDown={slashCommand.handleSlashKeyDown}
- />
- </div>
- {/* Attach button — fixed bottom-left */}
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- onPointerDown={(e) => e.preventDefault()}
- onClick={() => fileInputRef.current?.click()}
- disabled={sending}
- className="absolute left-2 bottom-2 size-8 rounded-full text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
- />
- }
- >
- <Paperclip className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent side="top">Attach files</TooltipContent>
- </Tooltip>
- {/* Send button — fixed bottom-right. Always Send; never a
- Stop/pause affordance (task-lifecycle chrome is gone). The
- spinner is only the sub-second in-flight double-submit guard. */}
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="icon-sm"
- onClick={handleSend}
- disabled={!input.trim() || sending}
- className={cn(
- "absolute right-2 bottom-2 size-8 rounded-full bg-primary text-primary-foreground transition-opacity duration-200",
- !input.trim() && "opacity-30",
- )}
- />
- }
- >
- {sending ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <ArrowUp className="size-3.5" />
- )}
- </TooltipTrigger>
- <TooltipContent side="top">Send</TooltipContent>
- </Tooltip>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <ImageLightbox
- open={lightboxArtifact != null}
- onClose={() => setLightboxArtifact(null)}
- artifact={lightboxArtifact}
- workspaceId={workspaceId}
- />
- {lightboxLocalUrl && (
- <ImageLightbox
- open
- onClose={() => {
- URL.revokeObjectURL(lightboxLocalUrl.url);
- setLightboxLocalUrl(null);
- }}
- imageUrl={lightboxLocalUrl.url}
- filename={lightboxLocalUrl.filename}
- />
- )}
-
- <ArtifactSheet
- open={artifactSheetOpen}
- onOpenChange={(v) => {
- setArtifactSheetOpen(v);
-
- }}
- artifacts={selectedArtifact ? [selectedArtifact] : agentArtifacts}
- workspaceId={workspaceId}
- initialArtifact={selectedArtifact}
- versionMap={versionMap}
- duplicateFilenames={duplicateFilenames}
- />
-
- <EmailEventSheet
- open={emailSheetOpen}
- onOpenChange={(v) => {
- setEmailSheetOpen(v);
-
- }}
- emailId={selectedEmailId}
- workspaceId={workspaceId}
- />
-
- <CalendarEventSheet
- readonly
- open={calendarEventSheetOpen}
- onOpenChange={(v) => {
- setCalendarEventSheetOpen(v);
-
- }}
- calendarEventId={selectedCalendarEventId}
- workspaceId={workspaceId}
- />
-
- <IssueSheet
- open={issueSheetOpen}
- onOpenChange={(v) => {
- setIssueSheetOpen(v);
-
- }}
- agents={agents}
- issue={issueDetail?.issue ?? null}
- detail={
- issueDetail
- ? {
- messages: issueDetail.messages,
- comments: issueDetail.comments,
- artifacts: issueDetail.artifacts,
- traceId: issueDetail.issue.trace_id,
- }
- : null
- }
- detailLoading={issueDetailLoading}
- activeTask={issueActiveTask}
- traceTasks={issueTraceTasks}
- slug={slug}
- workspaceId={workspaceId}
- onUpdate={updateSelectedIssue}
- onStatusChange={(issueId, status) => updateSelectedIssue(issueId, { status: status as Issue["status"] })}
- onCommented={() => {
- if (selectedIssueId) openIssue(selectedIssueId);
- }}
- onArtifactClick={handleIssueArtifactClick}
- />
- </>
- );
-}
diff --git a/src/web/src/components/agent-chat/artifact-sheet.tsx b/src/web/src/components/agent-chat/artifact-sheet.tsx
deleted file mode 100644
index ddf791d4a..000000000
--- a/src/web/src/components/agent-chat/artifact-sheet.tsx
+++ /dev/null
@@ -1,163 +0,0 @@
-"use client";
-
-import { FileDownloadButton } from "@/components/file-download-button"
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useRef } from "react";
-import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetBody,
-} from "@/components/ui/sheet";
-import type { Artifact } from "@alook/shared";
-import { FileText, Download, ArrowLeft } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { ArtifactContentRenderer, getArtifactUrl, isHtmlType } from "@/components/artifact-content-renderer";
-import { cn } from "@/lib/utils";
-
-export function formatSize(bytes: number): string {
- if (bytes < 1024) return `${bytes} B`;
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
-}
-
-interface ArtifactSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- artifacts: Artifact[];
- workspaceId: string;
- initialArtifact?: Artifact | null;
- versionMap: Map<string, number>;
- duplicateFilenames: Set<string>;
-}
-
-const MIN_WIDTH = 320;
-const MAX_WIDTH_RATIO = 0.8;
-const DEFAULT_WIDTH = 448;
-
-export function ArtifactSheet({ open, onOpenChange, artifacts, workspaceId, initialArtifact = null, versionMap, duplicateFilenames }: ArtifactSheetProps) {
- const [selectedId, setSelectedId] = useAtom(useCreateAtom<string | null>(null));
- const selectedArtifact = artifacts.find((row) => row.id === selectedId) ?? (initialArtifact?.id === selectedId ? initialArtifact : null);
- const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- const { width, onPointerDown, onPointerMove, onPointerUp } = useSheetResize({
- defaultWidth: DEFAULT_WIDTH,
- minWidth: MIN_WIDTH,
- maxWidthRatio: MAX_WIDTH_RATIO,
- });
-
- useEffect(() => {
- if (open && closeTimer.current !== null) { clearTimeout(closeTimer.current); closeTimer.current = null; }
- if (open && initialArtifact) setSelectedId(initialArtifact.id);
- }, [open, initialArtifact, setSelectedId]);
-
- useEffect(() => () => { if (closeTimer.current !== null) clearTimeout(closeTimer.current); }, []);
-
- const handleOpenChange = (v: boolean) => {
- onOpenChange(v);
- if (!v) {
- // Defer clearing selected artifact until sheet closing animation completes
- closeTimer.current = setTimeout(() => { closeTimer.current = null; setSelectedId(null); }, 300);
- }
- };
-
-
- return (
- <Sheet open={open} onOpenChange={handleOpenChange}>
- <SheetContent
- side="right"
- showCloseButton={false}
- style={{ width: `min(${width}px, 100vw)`, maxWidth: "none" }}
- className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border"
- >
- <SheetResizeHandle onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />
- {selectedArtifact ? (
- <>
- <SheetHeader>
- <div className="flex items-center gap-2">
- <Button
- variant="ghost"
- size="icon-sm"
- className="shrink-0 sm:hidden"
- onClick={() => handleOpenChange(false)}
- >
- <ArrowLeft className="size-4" />
- </Button>
- <SheetTitle className="truncate flex-1">
- {selectedArtifact.filename}
- {duplicateFilenames.has(selectedArtifact.filename) && (
- <span className="ml-2 text-xs text-muted-foreground bg-muted rounded-full px-2 py-1 font-normal">
- v{versionMap.get(selectedArtifact.id) ?? 1}
- </span>
- )}
- </SheetTitle>
- <FileDownloadButton
- className="shrink-0 inline-flex size-8 items-center justify-center rounded-md hover:bg-accent"
- url={getArtifactUrl(selectedArtifact.id, workspaceId, true)}
- filename={selectedArtifact.filename}
- >
- <Download className="size-4" />
- </FileDownloadButton>
- </div>
- </SheetHeader>
- <SheetBody className={cn(
- "thin-scrollbar",
- isHtmlType(selectedArtifact.content_type) && "p-0! overflow-hidden!"
- )}>
- <ArtifactContentRenderer artifact={selectedArtifact} workspaceId={workspaceId} />
- </SheetBody>
- </>
- ) : (
- <>
- <SheetHeader>
- <div className="flex items-center gap-2">
- <Button
- variant="ghost"
- size="icon-sm"
- className="shrink-0 sm:hidden"
- onClick={() => handleOpenChange(false)}
- >
- <ArrowLeft className="size-4" />
- </Button>
- <SheetTitle className="flex-1">Artifacts</SheetTitle>
- </div>
- </SheetHeader>
- <SheetBody className="thin-scrollbar">
- {artifacts.length === 0 ? (
- <p className="text-sm text-muted-foreground py-8 text-center">
- No artifacts uploaded yet.
- </p>
- ) : (
- <div className="space-y-1">
- {artifacts.map((a) => (
- <button
- key={a.id}
- onClick={() => setSelectedId(a.id)}
- className="flex items-center gap-3 w-full rounded-lg px-3 py-2 text-left hover:bg-muted/50 transition-colors"
- >
- <FileText className="size-4 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate">
- {a.filename}
- {duplicateFilenames.has(a.filename) && (
- <span className="ml-2 text-xs text-muted-foreground bg-muted rounded-full px-2 py-1 font-normal">
- v{versionMap.get(a.id) ?? 1}
- </span>
- )}
- </p>
- <p className="text-xs text-muted-foreground">
- {formatSize(a.size)} &middot; {new Date(a.created_at).toLocaleString()}
- </p>
- </div>
- </button>
- ))}
- </div>
- )}
- </SheetBody>
- </>
- )}
- </SheetContent>
- </Sheet>
- );
-}
diff --git a/src/web/src/components/agent-chat/chat-composer.tsx b/src/web/src/components/agent-chat/chat-composer.tsx
deleted file mode 100644
index 389cb5741..000000000
--- a/src/web/src/components/agent-chat/chat-composer.tsx
+++ /dev/null
@@ -1,535 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import {
- forwardRef,
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
- type ReactNode,
-} from "react";
-import { useKeyboardScroll } from "@/hooks/use-keyboard-scroll";
-import {
- anchoredPopoverStyle,
- useAnchoredPopover,
- type AnchorRect,
-} from "@/hooks/use-anchored-popover";
-import { useEditor, EditorContent } from "@tiptap/react";
-import StarterKit from "@tiptap/starter-kit";
-import Placeholder from "@tiptap/extension-placeholder";
-import { Markdown } from "@tiptap/markdown";
-import { createPortal } from "react-dom";
-import { cn } from "@/lib/utils";
-import { rankMentionAgents } from "@/lib/mention-agents";
-import { buildChatMentionExtension, mentionTokensToHtml } from "@/lib/chat-mention-extension";
-import { decodeChatEntities } from "@/lib/chat-markdown";
-import { toAlookAddress } from "@alook/shared";
-import type { Agent, AgentLink } from "@alook/shared";
-import type { PopupKeyEvent } from "@/hooks/use-slash-command";
-
-/**
- * Imperative handle the parent (agent-chat-view) drives. The parent keeps
- * owning send / banners / persistence / slash-command state; the composer only
- * owns the TipTap editor and surfaces just enough to anchor the slash popup.
- */
-export interface ChatComposerHandle {
- focus: () => void;
- clear: () => void;
- isEmpty: () => boolean;
- /** Viewport caret rect for a plain-text index — used to anchor the slash popup. */
- coordsAtTextIndex: (index: number) => AnchorRect | null;
-}
-
-interface ChatComposerProps {
- /** Markdown string — the controlled source of truth (parent's `input`). */
- value: string;
- onChange: (markdown: string) => void;
- /** Reports the editor's plain text + caret index so the parent can drive slash. */
- onEditorState: (plainText: string, caretIndex: number) => void;
- /** Enter-to-send (only fires in a top-level paragraph, no popup open). */
- onSend: () => void;
- /** Editor gained focus (forwarded live via useEditor's onFocus — no re-mount). */
- onFocus?: () => void;
- /** Editor lost focus (forwarded live via useEditor's onBlur — no re-mount). */
- onBlur?: () => void;
- /**
- * The placeholder, rendered as a decorative overlay over the empty editor.
- * This is the SOLE placeholder renderer — TipTap's own Placeholder is kept
- * permanently "" because its decoration is captured at plugin-init and does
- * NOT re-read updated options in this @tiptap/extensions version (so it goes
- * stale on the in-place active↔idle settle). The parent drives the text + fade
- * for BOTH the idle rotating hint and the active static "Message {Name}".
- */
- overlay?: ReactNode;
- disabled?: boolean;
- /** Drives the rounded-3xl ↔ rounded-2xl pill switch. */
- onMultiLineChange?: (multiline: boolean) => void;
- /** Files extracted from paste/drop — parent validates + stages them. */
- onFiles?: (files: File[]) => void;
-
- // Mentions
- agents: Agent[];
- agentLinks: AgentLink[];
- currentAgentId: string;
-
- // Slash command (state owned by the parent's useSlashCommand)
- slashIsOpen: boolean;
- onSlashKeyDown: (e: PopupKeyEvent) => boolean;
-}
-
-// ── Mention suggestion popup (self-contained, mirrors markdown-editor.tsx) ──
-
-type MentionSuggestionProps = {
- items: Agent[];
- command: (props: { id: string; label: string }) => void;
- clientRect?: (() => DOMRect | null) | null;
-};
-
-interface MentionPopupState {
- items: Agent[];
- selectedIndex: number;
- command: ((props: { id: string; label: string }) => void) | null;
- getRect: (() => DOMRect | null) | null;
-}
-
-const EMPTY_MENTION_STATE: MentionPopupState = {
- items: [],
- selectedIndex: 0,
- command: null,
- getRect: null,
-};
-
-function MentionList({ state }: { state: MentionPopupState }) {
- const listRef = useRef<HTMLDivElement>(null);
- const { items, selectedIndex, command, getRect } = state;
- const geometry = useAnchoredPopover(getRect, items.length > 0 && command !== null);
-
- useEffect(() => {
- if (!listRef.current) return;
- const el = listRef.current.children[selectedIndex] as HTMLElement | undefined;
- el?.scrollIntoView({ block: "nearest" });
- }, [selectedIndex]);
-
- if (!geometry || items.length === 0 || !command) return null;
-
- return createPortal(
- <div
- className="fixed z-100 w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"
- style={anchoredPopoverStyle(geometry.rect, geometry.viewport, 256, 200)}
- >
- <div
- ref={listRef}
- className="overflow-y-auto py-1 thin-scrollbar"
- style={{ maxHeight: "var(--anchored-popover-max-height)" }}
- >
- {items.map((agent, i) => (
- <button
- key={agent.id}
- type="button"
- className={cn(
- "flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors",
- i === selectedIndex ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",
- )}
- onMouseDown={(e) => {
- e.preventDefault();
- command({ id: agent.id, label: agent.name });
- }}
- >
- <span className="truncate font-medium">{agent.name}</span>
- {agent.email_handle && (
- <span className="truncate text-xs text-muted-foreground">
- {toAlookAddress(agent.email_handle)}
- </span>
- )}
- </button>
- ))}
- </div>
- </div>,
- document.body,
- );
-}
-
-/** fade duration each way; total swap = 2× this. Matches the spec (200/200). */
-const PLACEHOLDER_FADE_MS = 200;
-
-/**
- * Decorative overlay for the rotating capability-hint placeholder. Rendered as
- * a sibling of <EditorContent> inside `.chat-composer` (which is `relative`),
- * absolutely positioned at the editor's text origin so it overlaps the empty
- * first paragraph exactly and adds zero layout height.
- *
- * Cross-fade: on `hint` change, fade the current text OUT (200ms), swap the
- * text at zero opacity, then fade the new text IN — so the text never snaps
- * mid-opacity (the flicker the overlay exists to avoid). With `animate=false`
- * (reduced motion) the hint swaps instantly, no transition.
- *
- * aria-hidden: this is purely visual — the editor keeps its real accessible
- * name and screen readers must NOT announce hint rotation.
- */
-export function RotatingPlaceholderOverlay({
- hint,
- animate,
-}: {
- hint: string;
- /** false → reduced-motion: render the single hint with no fade. */
- animate: boolean;
-}) {
- // `shown` is the text currently painted; `visible` drives opacity. On a hint
- // change we fade out, then swap `shown` + fade back in.
- const [shown, setShown] = useAtom(useCreateAtom(hint));
- const [visible, setVisible] = useAtom(useCreateAtom(true));
-
- useEffect(() => {
- if (!animate) {
- // Reduced motion: no fade, just show the latest hint.
- setShown(hint);
- setVisible(true);
- return;
- }
- if (hint === shown) return;
- setVisible(false); // fade out
- const id = setTimeout(() => {
- setShown(hint); // swap at opacity 0
- setVisible(true); // fade in
- }, PLACEHOLDER_FADE_MS);
- return () => clearTimeout(id);
- }, [hint, shown, animate, setVisible, setShown]);
-
- return (
- <div className="chat-placeholder-overlay" aria-hidden="true">
- <span
- className={animate ? "chat-placeholder-fade" : undefined}
- style={animate ? { opacity: visible ? 1 : 0 } : undefined}
- >
- {shown}
- </span>
- </div>
- );
-}
-
-export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
- function ChatComposer(
- {
- value,
- onChange,
- onEditorState,
- onSend,
- onFocus,
- onBlur,
- overlay,
- disabled,
- onMultiLineChange,
- onFiles,
- agents,
- agentLinks,
- currentAgentId,
- slashIsOpen,
- onSlashKeyDown,
- },
- ref,
- ) {
- const [editorFocused, setEditorFocused] = useAtom(useCreateAtom(false));
- const [mentionPopup, setMentionPopup] = useAtom(useCreateAtom<MentionPopupState>(EMPTY_MENTION_STATE));
- const mentionPopupRef = useRef(mentionPopup);
- useEffect(() => {
- mentionPopupRef.current = mentionPopup;
- }, [mentionPopup]);
-
- // The editor is built once, so anything its callbacks read must be a ref.
- const agentsRef = useRef(agents);
- const agentLinksRef = useRef(agentLinks);
- const currentAgentIdRef = useRef(currentAgentId);
- const onSendRef = useRef(onSend);
- const onEditorStateRef = useRef(onEditorState);
- const onChangeRef = useRef(onChange);
- const onFilesRef = useRef(onFiles);
- const onFocusRef = useRef(onFocus);
- const onBlurRef = useRef(onBlur);
- const slashIsOpenRef = useRef(slashIsOpen);
- const onSlashKeyDownRef = useRef(onSlashKeyDown);
- useEffect(() => { agentsRef.current = agents; }, [agents]);
- useEffect(() => { agentLinksRef.current = agentLinks; }, [agentLinks]);
- useEffect(() => { currentAgentIdRef.current = currentAgentId; }, [currentAgentId]);
- useEffect(() => { onSendRef.current = onSend; }, [onSend]);
- useEffect(() => { onEditorStateRef.current = onEditorState; }, [onEditorState]);
- useEffect(() => { onChangeRef.current = onChange; }, [onChange]);
- useEffect(() => { onFilesRef.current = onFiles; }, [onFiles]);
- useEffect(() => { onFocusRef.current = onFocus; }, [onFocus]);
- useEffect(() => { onBlurRef.current = onBlur; }, [onBlur]);
- useEffect(() => { slashIsOpenRef.current = slashIsOpen; }, [slashIsOpen]);
- useEffect(() => { onSlashKeyDownRef.current = onSlashKeyDown; }, [onSlashKeyDown]);
-
- // Report plain text + caret to the parent (it drives the slash-command
- // popup). NOTE: `selection.from - 1` only equals the true plain-text index
- // in a single-paragraph doc — it diverges across block boundaries. The only
- // consumer (slash commands, which trigger ONLY at the start of input) is in
- // a top-level paragraph, so the mapping holds there. Don't trust this index
- // for multi-block positions without revisiting.
- const reportState = (editor: NonNullable<ReturnType<typeof useEditor>>) => {
- onEditorStateRef.current(editor.getText(), editor.state.selection.from - 1);
- };
-
- // The mention extension is built once (refs read inside its callbacks fire
- // at suggestion-time, not render-time). Keeping it in a lazy state init
- // also stops it being rebuilt on every render. The .current reads below are
- // all inside suggestion callbacks invoked at runtime, never during render.
- // eslint-disable-next-line react-hooks/refs -- refs read in runtime callbacks, not render
- const [mentionExtension] = useState(() =>
- buildChatMentionExtension().configure({
- HTMLAttributes: { class: "mention-highlight" },
- renderText: ({ node }) => `@${node.attrs.label ?? node.attrs.id}`,
- suggestion: {
- char: "@",
- items: ({ query }: { query: string }) =>
- rankMentionAgents(
- agentsRef.current,
- agentLinksRef.current,
- currentAgentIdRef.current,
- query,
- ),
- render: () => ({
- onStart: (props: MentionSuggestionProps) => {
- setMentionPopup({
- items: props.items ?? [],
- selectedIndex: 0,
- command: props.command,
- getRect: props.clientRect ?? null,
- });
- },
- onUpdate: (props: MentionSuggestionProps) => {
- setMentionPopup((cur) => ({
- items: props.items ?? [],
- selectedIndex:
- cur.selectedIndex < (props.items?.length ?? 0) ? cur.selectedIndex : 0,
- command: props.command,
- getRect: props.clientRect ?? null,
- }));
- },
- onKeyDown: ({ event }: { event: KeyboardEvent }) => {
- // IME guard: while composing (CJK), Enter confirms the
- // composition — it must not select a mention. Mirrors the Enter
- // guards in the slash hook and the send path.
- if (event.isComposing) return false;
- const cur = mentionPopupRef.current;
- if (cur.items.length === 0) return false;
- if (event.key === "ArrowDown") {
- event.preventDefault();
- setMentionPopup((s) => ({
- ...s,
- selectedIndex: (s.selectedIndex + 1) % s.items.length,
- }));
- return true;
- }
- if (event.key === "ArrowUp") {
- event.preventDefault();
- setMentionPopup((s) => ({
- ...s,
- selectedIndex: (s.selectedIndex - 1 + s.items.length) % s.items.length,
- }));
- return true;
- }
- if (event.key === "Enter") {
- event.preventDefault();
- const agent = cur.items[cur.selectedIndex];
- if (agent && cur.command) cur.command({ id: agent.id, label: agent.name });
- setMentionPopup(EMPTY_MENTION_STATE);
- return true;
- }
- if (event.key === "Escape") {
- setMentionPopup(EMPTY_MENTION_STATE);
- return true;
- }
- return false;
- },
- onExit: () => setMentionPopup(EMPTY_MENTION_STATE),
- }),
- },
- }),
- );
-
- const editor = useEditor({
- immediatelyRender: false,
- content: value ? value.replaceAll("\n", "<br>") : undefined,
- editable: !disabled,
- extensions: [
- StarterKit.configure({
- heading: false,
- blockquote: false,
- codeBlock: false,
- horizontalRule: false,
- bold: false,
- italic: false,
- strike: false,
- code: false,
- link: false,
- bulletList: false,
- orderedList: false,
- listItem: false,
- listKeymap: false,
- }),
- // TipTap's own placeholder is permanently empty: its decoration value is
- // captured at plugin-init and does NOT re-read updated options in this
- // @tiptap/extensions version, so a reactive value goes stale on the
- // in-place active↔idle settle (the double-image). The `overlay` prop is
- // the single source of truth for the placeholder instead — see below.
- Placeholder.configure({ placeholder: "" }),
- Markdown,
- mentionExtension,
- ],
- editorProps: {
- attributes: {
- class: "outline-none",
- enterkeyhint: "send",
- },
- handleKeyDown: (_view, event) => {
- // Precedence: mention suggestion > slash popup > Enter-to-send.
- //
- // editorProps.handleKeyDown runs BEFORE plugin keymaps in
- // ProseMirror, so the @tiptap/suggestion mention plugin does NOT get
- // first crack at Enter — we must explicitly bail here while the
- // mention popup is open, or Enter would send instead of selecting the
- // highlighted agent. (Arrow/Esc fall through fine; only Enter clashes.)
- const mentionOpen =
- mentionPopupRef.current.items.length > 0 && mentionPopupRef.current.command !== null;
- if (mentionOpen) return false;
-
- if (
- slashIsOpenRef.current &&
- onSlashKeyDownRef.current({
- key: event.key,
- isComposing: event.isComposing,
- preventDefault: () => event.preventDefault(),
- })
- ) {
- return true;
- }
-
- if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
- if (!slashIsOpenRef.current) {
- event.preventDefault();
- onSendRef.current();
- return true;
- }
- }
- return false;
- },
- handlePaste: (view, event) => {
- const items = event.clipboardData?.items;
- if (!items) return false;
- const files: File[] = [];
- for (let i = 0; i < items.length; i++) {
- if (items[i].kind === "file") {
- const f = items[i].getAsFile();
- if (f) files.push(f);
- }
- }
- if (files.length > 0) {
- event.preventDefault();
- onFilesRef.current?.(files);
- return true;
- }
- const text = event.clipboardData?.getData("text/plain");
- if (text) {
- event.preventDefault();
- view.dispatch(view.state.tr.insertText(text));
- return true;
- }
- return false;
- },
- handleDrop: () => false,
- },
- onFocus: () => { setEditorFocused(true); onFocusRef.current?.(); },
- onBlur: () => { setEditorFocused(false); onBlurRef.current?.(); },
- onUpdate: ({ editor }) => {
- onChangeRef.current(decodeChatEntities(editor.getMarkdown()));
- reportState(editor);
- },
- onSelectionUpdate: ({ editor }) => {
- reportState(editor);
- },
- });
-
- // Keep editable in sync with disabled.
- useEffect(() => {
- editor?.setEditable(!disabled);
- }, [editor, disabled]);
-
- // Controlled value: push external changes (draft restore /
- // conversation switch / clear-after-send) into the editor.
- // emitUpdate:false avoids a feedback loop.
- useEffect(() => {
- if (!editor) return;
- const incoming = (value || "").trim();
- // Decode so this matches the (decoded) markdown the parent stored via
- // onChange — otherwise text with < > & always mismatches and we'd reset
- // content (and the caret) on every keystroke.
- const current = decodeChatEntities(editor.getMarkdown() || "").trim();
- if (incoming === current) return;
- if (!incoming) {
- editor.commands.clearContent();
- } else {
- editor.commands.setContent(mentionTokensToHtml((value || "").replaceAll("\n", "<br>")), { emitUpdate: false });
- }
- onEditorStateRef.current(editor.getText(), editor.state.selection.from - 1);
- }, [value, editor]);
-
- // Multi-line detection drives the pill rounding.
- const contentRef = useRef<HTMLDivElement>(null);
- useEffect(() => {
- if (!editor || !onMultiLineChange) return;
- const el = contentRef.current?.querySelector(".ProseMirror") as HTMLElement | null;
- if (!el) return;
- const check = () => onMultiLineChange(el.scrollHeight > 32);
- check();
- const observer = new ResizeObserver(check);
- observer.observe(el);
- return () => observer.disconnect();
- }, [editor, onMultiLineChange]);
-
- // iOS Safari fallback: scroll composer into view when the virtual keyboard resizes
- // the visual viewport.
- useKeyboardScroll(contentRef, editorFocused);
-
- useImperativeHandle(
- ref,
- () => ({
- focus: () => editor?.commands.focus(),
- clear: () => editor?.commands.clearContent(),
- isEmpty: () => editor?.isEmpty ?? true,
- coordsAtTextIndex: (index: number) => {
- if (!editor) return null;
- try {
- // +1: plain-text index is 0-based; PM positions start at 1.
- const coords = editor.view.coordsAtPos(index + 1);
- return {
- top: coords.top,
- bottom: coords.bottom,
- left: coords.left,
- right: coords.right,
- };
- } catch {
- return null;
- }
- },
- }),
- [editor],
- );
-
- return (
- <div ref={contentRef} className="chat-composer relative">
- <EditorContent
- editor={editor}
- className="max-h-44 overflow-y-auto thin-scrollbar pr-2 text-base chat-input-line-height"
- />
- {/* Decorative rotating-placeholder overlay. Renders over the empty
- editor's text origin (mirrors the ::before float:left;height:0
- position) so it adds zero layout height. aria-hidden — never
- announced; the editor keeps its own accessible name. The parent
- only mounts this while the field is empty + unfocused + idle. */}
- {overlay}
- <MentionList state={mentionPopup} />
- </div>
- );
- },
-);
diff --git a/src/web/src/components/agent-chat/chat-message-utils.ts b/src/web/src/components/agent-chat/chat-message-utils.ts
deleted file mode 100644
index 14d6e6a06..000000000
--- a/src/web/src/components/agent-chat/chat-message-utils.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-import type { Artifact,Message,TaskApi as Task } from "@alook/shared";
-
-type EventIconType = "issue" | "email" | "calendar";
-
-export function getEventIconType(
- content: string,
- conversationType?: string | null,
-): EventIconType {
- if (conversationType === "issue_event") return "issue";
- if (conversationType === "email_notification") return "email";
- if (conversationType === "calendar_event") return "calendar";
-
- const lower = content.toLowerCase();
- if (lower.startsWith("issue ") || lower.startsWith("issue:")) return "issue";
- if (lower.includes("email")) return "email";
- return "calendar";
-}
-
-/**
- * Classify a system-event message by its metadata resource id first (reliable,
- * stamped at all creation sites), falling back to the content/conversationType
- * heuristic only when no id is present. Drives both the card icon and label.
- */
-export function eventTypeFromMessage(
- metadata: Record<string, unknown> | null | undefined,
- content: string,
- conversationType?: string | null,
-): EventIconType {
- if (metadata?.issueId) return "issue";
- if (metadata?.emailId) return "email";
- if (metadata?.calendarEventId) return "calendar";
- return getEventIconType(content, conversationType);
-}
-
-/** Sort messages by (created_at, id) ascending — guarantees chronological order. */
-export function sortMessages(msgs: Message[]): Message[] {
- return msgs.slice().sort((a, b) => {
- const cmp = a.created_at.localeCompare(b.created_at);
- if (cmp !== 0) return cmp;
- return a.id.localeCompare(b.id);
- });
-}
-
-/** Merge two message arrays by ID (latest wins), then sort chronologically. */
-export function mergeMessages(
- existing: Message[],
- incoming: Message[],
-): Message[] {
- const merged = new Map<string, Message>();
- for (const m of existing) merged.set(m.id, m);
- for (const m of incoming) merged.set(m.id, m);
- return sortMessages([...merged.values()]);
-}
-
-export type NapMarker = { agentName: string; created_at: string; id: string };
-
-type TimelineItem =
- | { kind: "message"; data: Message }
- | { kind: "artifact"; data: Artifact }
- | { kind: "nap"; data: NapMarker };
-
-export type GroupPosition = "first" | "middle" | "last" | "solo";
-
-// Which conversational SIDE a timeline item belongs to. Items on the same side
-// that are adjacent (within the time threshold, no nap between) form one
-// Slack/Discord-style cluster sharing a single avatar + name header. The agent
-// side intentionally includes event cards (email/issue/calendar) and artifacts
-// (files), so a run like "card → reply → card → reply" reads as ONE Gwennie
-// cluster with one header — not four separate avatars.
-type GroupSide = "user" | "agent" | null;
-
-function groupSideOf(item: TimelineItem): GroupSide {
- if (item.kind === "artifact") return "agent"; // files come from the agent
- if (item.kind !== "message") return null; // nap markers break clusters
- const role = item.data.role;
- if (role === "user") return "user";
- if (role === "assistant" || role === "event") return "agent";
- return null;
-}
-
-function itemCreatedAt(item: TimelineItem): string | undefined {
- return item.data.created_at;
-}
-
-export function computeGroupPositions(
- timeline: TimelineItem[],
-): (GroupPosition | null)[] {
- const positions: (GroupPosition | null)[] = new Array(timeline.length).fill(
- null,
- );
- const GROUP_THRESHOLD_MS = 60_000;
-
- const adjacentSameCluster = (a: TimelineItem | null, b: TimelineItem | null) => {
- if (!a || !b) return false;
- const sa = groupSideOf(a);
- const sb = groupSideOf(b);
- if (sa === null || sa !== sb) return false;
- const ta = itemCreatedAt(a);
- const tb = itemCreatedAt(b);
- if (!ta || !tb) return true; // missing timestamp → don't split the cluster
- return Math.abs(new Date(ta).getTime() - new Date(tb).getTime()) < GROUP_THRESHOLD_MS;
- };
-
- for (let i = 0; i < timeline.length; i++) {
- const item = timeline[i];
- if (groupSideOf(item) === null) continue; // nap → leave null
-
- const prev = i > 0 ? timeline[i - 1] : null;
- const next = i < timeline.length - 1 ? timeline[i + 1] : null;
-
- const sameAsPrev = adjacentSameCluster(prev, item);
- const sameAsNext = adjacentSameCluster(item, next);
-
- if (sameAsPrev && sameAsNext) positions[i] = "middle";
- else if (sameAsPrev && !sameAsNext) positions[i] = "last";
- else if (!sameAsPrev && sameAsNext) positions[i] = "first";
- else positions[i] = "solo";
- }
-
- return positions;
-}
-
-export function buildTimeline(
- messages: Message[],
- artifacts: Artifact[],
- napMarkers: NapMarker[],
- currentConversationId?: string | null,
-): TimelineItem[] {
- if (!currentConversationId || napMarkers.length === 0) {
- const items: TimelineItem[] = [
- ...messages.map((m): TimelineItem => ({ kind: "message", data: m })),
- ...artifacts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
- ...napMarkers.map((n): TimelineItem => ({ kind: "nap", data: n })),
- ];
- items.sort((a, b) => {
- const cmp = a.data.created_at.localeCompare(b.data.created_at);
- if (cmp !== 0) return cmp;
- if (a.kind === "nap" || b.kind === "nap") {
- if (a.kind === "nap" && b.kind !== "nap") return 1;
- if (a.kind !== "nap" && b.kind === "nap") return -1;
- }
- if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
- return a.data.id.localeCompare(b.data.id);
- });
- // Strictly chronological — a file uploaded mid-task stays where it appeared
- // and the agent's reply follows below it in the same cluster (no reorder, so
- // nothing jumps when the reply lands). Gus's call, 2026-06-01.
- return items;
- }
-
- const napConvIds = new Set(napMarkers.map((n) => n.id.replace(/^nap-/, "")));
- const sortedNaps = [...napMarkers].sort((a, b) =>
- a.created_at.localeCompare(b.created_at),
- );
-
- const groupItems = (convId: string): TimelineItem[] => {
- const msgs: TimelineItem[] = messages
- .filter((m) => m.conversation_id === convId)
- .map((m) => ({ kind: "message" as const, data: m }));
- const arts: TimelineItem[] = artifacts
- .filter((a) => a.conversation_id === convId)
- .map((a) => ({ kind: "artifact" as const, data: a }));
- const sorted = [...msgs, ...arts].sort((a, b) => {
- const cmp = a.data.created_at.localeCompare(b.data.created_at);
- if (cmp !== 0) return cmp;
- if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
- return a.data.id.localeCompare(b.data.id);
- });
- return sorted; // chronological, no artifact reorder (see above)
- };
-
- const result: TimelineItem[] = [];
-
- for (const nap of sortedNaps) {
- const convId = nap.id.replace(/^nap-/, "");
- result.push(...groupItems(convId));
- result.push({ kind: "nap", data: nap });
- }
-
- result.push(...groupItems(currentConversationId));
-
- const knownConvIds = new Set([...napConvIds, currentConversationId]);
- const orphanMsgs = messages.filter(
- (m) => !knownConvIds.has(m.conversation_id),
- );
- const orphanArts = artifacts.filter(
- (a) => !knownConvIds.has(a.conversation_id),
- );
- if (orphanMsgs.length > 0 || orphanArts.length > 0) {
- const orphanItems: TimelineItem[] = [
- ...orphanMsgs.map((m): TimelineItem => ({ kind: "message", data: m })),
- ...orphanArts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
- ];
- orphanItems.sort((a, b) => {
- const cmp = a.data.created_at.localeCompare(b.data.created_at);
- if (cmp !== 0) return cmp;
- if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
- return a.data.id.localeCompare(b.data.id);
- });
- const napIdx = result.findIndex((item) => item.kind === "nap");
- if (napIdx >= 0) {
- result.splice(napIdx, 0, ...orphanItems);
- } else {
- result.push(...orphanItems);
- }
- }
-
- return result;
-}
-
-/**
- * Whether a completed conversation load may persist the per-channel `last_open`
- * pointer. Only the SLOW path (param-less open, `targetConvId` absent) resolves
- * the channel's latest-created conversation; the FAST path (`?conv=<id>`) loads
- * an explicit, possibly old conversation and must NOT touch the pointer (doing
- * so reintroduces the wrong-conversation flash). See {@link LastOpenEntry}.
- *
- * Pure mirror of the inline Phase B write guard, exported for unit testing the
- * fast-vs-slow decision without rendering the component.
- */
-export function shouldPersistPointerForLoad(
- targetConvId: string | null | undefined,
-): boolean {
- return !targetConvId;
-}
-
-/**
- * Decide whether a `task.created` WS event should refresh this view's
- * per-channel `last_open` pointer, and to which conversation.
- *
- * The `last_open` pointer carries "latest-created conversation for this
- * agent+channel" semantics (see {@link setLastOpenConversation}). A
- * `task.created` event is the client learning of a (possibly newer)
- * conversation in real time, so it is a valid moment to refresh the pointer —
- * but ONLY when the event belongs to exactly this agent + active channel.
- *
- * Returns the conversation id to point at, or `null` to skip the write
- * (different agent, different channel, or the pointer already points there).
- *
- * Pure so the scoping logic is unit-testable in the node-env web test suite
- * (no component render). The caller supplies `serverMessageCount` separately
- * (A1: derived from the locally-cached message count) when it performs the
- * actual `setLastOpenConversation` write.
- */
-export function pointerRefreshTargetForTaskCreated(args: {
- /** The TaskApi from the `task.created` event. */
- task: Pick<Task, "agent_id" | "channel" | "conversation_id">;
- /** The agent this view is rendering. */
- agentId: string;
- /** The active channel string (never null — null maps to "default"). */
- activeChannel: string;
- /** The conversation id the pointer currently references, if known. */
- currentPointerConvId: string | null;
-}): string | null {
- const { task, agentId, activeChannel, currentPointerConvId } = args;
- // Scope guard: never touch another agent's or channel's pointer. The event's
- // null channel normalizes to "default" to match the UI's channel string
- // (channel-context.tsx). activeChannel is always a non-null string.
- if (task.agent_id !== agentId) return null;
- if ((task.channel ?? "default") !== activeChannel) return null;
- // Already pointing here — nothing to do.
- if (task.conversation_id === currentPointerConvId) return null;
- return task.conversation_id;
-}
diff --git a/src/web/src/components/agent-chat/chat-view-parts.dom.test.ts b/src/web/src/components/agent-chat/chat-view-parts.dom.test.ts
deleted file mode 100644
index c07acdd8b..000000000
--- a/src/web/src/components/agent-chat/chat-view-parts.dom.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import React, { createElement } from "react"
-import { renderToStaticMarkup } from "react-dom/server"
-import { describe, expect, it, vi } from "vitest"
-import { fireEvent, render as renderDom, screen } from "@/test/react-dom-harness"
-import type { Agent, Artifact } from "@alook/shared"
-import { RemoteMarkdownImage } from "@/components/remote-image/remote-markdown-image"
-import { ArtifactCard, MENTION_COMPONENTS } from "./chat-view-parts"
-
-const agents: Agent[] = []
-
-vi.mock("@/contexts/agent-context", () => ({
- useAgentContext: () => ({ agents }),
-}))
-
-vi.mock("@/components/agent-preview-card", () => ({
- AgentPreviewCard: ({ agent }: { agent: { id: string } }) =>
- createElement("div", { "data-preview-agent-id": agent.id }),
-}))
-
-const agent = (id: string, name: string): Agent => ({
- id,
- workspace_id: "ws_1",
- runtime_id: "rt_1",
- name,
- description: "",
- instructions: "",
- runtime_mode: "daemon",
- runtime_config: {},
- status: "active",
- max_concurrent_tasks: 1,
- email_handle: null,
- avatar_url: null,
- visibility: "public",
- owner_id: null,
- created_at: "2024-01-01T00:00:00Z",
- updated_at: "2024-01-01T00:00:00Z",
-})
-
-function renderMention(props: Record<string, unknown>): string {
- const Mention = MENTION_COMPONENTS.mention
- return renderToStaticMarkup(createElement(Mention, props))
-}
-
-// The popover content (with the preview card carrying the resolved id) is lazy
-// under SSR, so the load-bearing signal is the trigger: a resolved agent renders
-// a clickable popover trigger, an unresolved one a plain text span.
-const isClickable = (html: string) =>
- html.includes("cursor-pointer") && html.includes('data-slot="popover-trigger"')
-
-describe("MentionHighlight", () => {
- it("resolves a same-name agent by data-agent-id (clickable), unaffected by a duplicate name", () => {
- agents.length = 0
- agents.push(agent("ag_ada1", "Ada"), agent("ag_ada2", "Ada"))
- expect(isClickable(renderMention({ "data-agent-id": "ag_ada2", children: "@Ada" }))).toBe(true)
- })
-
- it("falls back to name only when there is no agent id (historic bare mention)", () => {
- agents.length = 0
- agents.push(agent("ag_bob", "Bob"))
- expect(isClickable(renderMention({ children: "@Bob" }))).toBe(true)
- })
-
- it("does not name-fallback when an id is present — a gone agent renders non-clickable text", () => {
- agents.length = 0
- // A same-name agent exists under a different id; it must NOT be matched,
- // proving resolution is strictly by id, never by name, when an id is present.
- agents.push(agent("ag_other", "Ada"))
- const html = renderMention({ "data-agent-id": "ag_gone", children: "@Ada" })
- expect(isClickable(html)).toBe(false)
- expect(html).toContain("@Ada")
- })
-})
-
-const IMAGE_ARTIFACT: Artifact = {
- id: "artifact-1",
- conversation_id: "conversation-1",
- agent_id: "agent-1",
- filename: "diagram.png",
- content_type: "image/png",
- size: 128,
- source: "agent",
- has_thumbnail: true,
- created_at: "2026-01-01T00:00:00Z",
-}
-
-describe("Agent Chat remote images", () => {
- it("uses the shared Markdown image adapter", () => {
- expect(MENTION_COMPONENTS.img).toBe(RemoteMarkdownImage)
- })
-
- it("keeps a failed artifact thumbnail as an explicit retryable image card", async () => {
- const onClick = vi.fn()
- const rendered = renderDom(React.createElement(ArtifactCard, {
- artifact: IMAGE_ARTIFACT,
- version: 1,
- hasDuplicates: false,
- onClick,
- workspaceId: "workspace-1",
- }))
-
- const image = rendered.container.querySelector<HTMLImageElement>('[data-remote-image-kind="content"]')!
- const originalSrc = image.src
- fireEvent.error(image)
-
- const retry = screen.getByRole("button", { name: "Retry" })
- fireEvent.click(retry)
- expect(rendered.container.querySelector<HTMLImageElement>('[data-remote-image-kind="content"]')?.src)
- .toBe(originalSrc)
- expect(onClick).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/components/agent-chat/chat-view-parts.tsx b/src/web/src/components/agent-chat/chat-view-parts.tsx
deleted file mode 100644
index a5fbe4fb9..000000000
--- a/src/web/src/components/agent-chat/chat-view-parts.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-"use client";
-
-import React from "react";
-import type { Artifact } from "@alook/shared";
-import { useAgentContext } from "@/contexts/agent-context";
-import { AgentPreviewCard } from "@/components/agent-preview-card";
-import {
- Popover,
- PopoverTrigger,
- PopoverContent,
-} from "@/components/ui/popover";
-import { FileCard } from "@/components/agent-chat/event-cards/file-card";
-import { getArtifactThumbnailUrl } from "@/components/artifact-content-renderer";
-import { RemoteContentImage } from "@/components/remote-image/remote-image";
-import { RemoteMarkdownImage } from "@/components/remote-image/remote-markdown-image";
-
-function MentionHighlight(
- props: Record<string, unknown> & { children?: React.ReactNode },
-) {
- const { children, ...rest } = props;
- const { agents } = useAgentContext();
- const agentId = (rest["data-agent-id"] ?? rest.dataAgentId) as
- | string
- | undefined;
- let agent = agentId ? agents.find((a) => a.id === agentId) : undefined;
- if (!agent && !agentId && typeof children === "string") {
- const nameToMatch = children.startsWith("@") ? children.slice(1) : children;
- agent = agents.find(
- (a) => a.name.toLowerCase() === nameToMatch.toLowerCase(),
- );
- }
- if (agent) {
- return (
- <Popover>
- <PopoverTrigger
- openOnHover
- delay={300}
- nativeButton={false}
- render={<span className="mention-highlight cursor-pointer" />}
- >
- {children}
- </PopoverTrigger>
- <PopoverContent side="top" className="w-fit max-w-80">
- <AgentPreviewCard agent={agent} />
- </PopoverContent>
- </Popover>
- );
- }
- return <span className="mention-highlight">{children}</span>;
-}
-
-export const MENTION_COMPONENTS: Record<
- string,
- React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>
-> = {
- img: RemoteMarkdownImage,
- mention: MentionHighlight,
- p: ({
- children,
- node,
- ...rest
- }: Record<string, unknown> & { children?: React.ReactNode }) => {
- void node;
- return (
- <div data-md-p="" {...rest}>
- {children}
- </div>
- );
- },
-};
-
-export function NapSeparator({ agentName }: { agentName: string }) {
- return (
- <div className="flex items-center gap-3 py-4 select-none" aria-hidden>
- <div className="flex-1 border-t border-border/40" />
- <span className="text-xs text-muted-foreground/60 whitespace-nowrap">
- {agentName} took a nap 💤
- </span>
- <div className="flex-1 border-t border-border/40" />
- </div>
- );
-}
-
-export function ArtifactCard({
- artifact,
- version,
- hasDuplicates,
- onClick,
- workspaceId,
-}: {
- artifact: Artifact;
- version: number;
- hasDuplicates: boolean;
- onClick: (a: Artifact) => void;
- workspaceId: string;
-}) {
- const thumbnailUrl = artifact.has_thumbnail
- ? getArtifactThumbnailUrl(artifact.id, workspaceId)
- : undefined;
-
- if (thumbnailUrl) {
- return (
- <RemoteContentImage
- src={thumbnailUrl}
- alt={artifact.filename}
- loading="lazy"
- onActivate={() => onClick(artifact)}
- frameClassName="w-64 max-w-full rounded-(--radius) border border-(--border) [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 hover:[box-shadow:var(--e2)] [box-shadow:var(--e1)]"
- frameStyle={{ aspectRatio: "8/5" }}
- imageClassName="object-contain"
- errorLabel="Preview failed to load"
- />
- );
- }
-
- return (
- <FileCard
- filename={artifact.filename}
- size={artifact.size}
- contentType={artifact.content_type ?? undefined}
- version={version}
- hasDuplicates={hasDuplicates}
- onClick={() => onClick(artifact)}
- />
- );
-}
diff --git a/src/web/src/components/agent-chat/email-event-sheet.tsx b/src/web/src/components/agent-chat/email-event-sheet.tsx
deleted file mode 100644
index 6563ca256..000000000
--- a/src/web/src/components/agent-chat/email-event-sheet.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-"use client";
-
-import { FileDownloadButton } from "@/components/file-download-button"
-import { useEffect, useRef } from "react";
-import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetBody,
-} from "@/components/ui/sheet";
-import { Button } from "@/components/ui/button";
-import { X, Mail, Loader2, Paperclip, File as FileIcon } from "lucide-react";
-import { toast } from "sonner";
-import { getEmail, getEmailBody } from "@/lib/api";
-import { EmailBodyFrame } from "@/components/email-body-frame";
-import { useQuery } from "@tanstack/react-query";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { isAbortError } from "@/lib/errors";
-
-interface EmailEventSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- emailId: string | null;
- workspaceId: string;
-}
-
-const MIN_WIDTH = 320;
-const MAX_WIDTH_RATIO = 0.8;
-const DEFAULT_WIDTH = 500;
-
-export function EmailEventSheet({ open, onOpenChange, emailId, workspaceId }: EmailEventSheetProps) {
- const owner = useWorkspaceOwner();
- const source = useWorkspaceViewSource(owner, emailId ?? "__none__", open && !!emailId && workspaceId === owner.workspaceId);
- const emailQuery = useQuery({ queryKey: owner.key("emails", "detail", source.active ? emailId! : "__none__"), enabled: source.active,
- meta: { workspaceView: source.view },
- queryFn: ({ signal }) => getEmail(emailId!, owner.workspaceId, source.request(signal)),
- });
- const bodyQuery = useQuery({ queryKey: owner.key("emails", "body", source.active ? emailId! : "__none__"), enabled: source.active,
- meta: { workspaceView: source.view },
- queryFn: ({ signal }) => getEmailBody(emailId!, owner.workspaceId, source.request(signal)),
- });
- const email = emailQuery.data;
- const body = bodyQuery.data;
- const loading = source.active && (emailQuery.isPending || bodyQuery.isPending);
- const { width, onPointerDown, onPointerMove, onPointerUp } = useSheetResize({
- defaultWidth: DEFAULT_WIDTH,
- minWidth: MIN_WIDTH,
- maxWidthRatio: MAX_WIDTH_RATIO,
- });
- const onOpenChangeRef = useRef(onOpenChange);
- useEffect(() => { onOpenChangeRef.current = onOpenChange; });
-
- useEffect(() => {
- const error = emailQuery.error ?? bodyQuery.error;
- if (!error || emailQuery.isFetching || bodyQuery.isFetching || isAbortError(error)) return;
- try { source.assertActive(); } catch { return; }
- toast.error("Email not found");
- onOpenChangeRef.current(false);
- }, [emailQuery.error, bodyQuery.error, emailQuery.isFetching, bodyQuery.isFetching, source.assertActive, source]);
- const handleOpenChange = onOpenChange;
-
-
- return (
- <Sheet open={open} onOpenChange={handleOpenChange}>
- <SheetContent
- side="right"
- showCloseButton={false}
- style={{ width: `min(${width}px, 100vw)`, maxWidth: "none" }}
- className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border"
- >
- <SheetResizeHandle onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />
- <SheetHeader>
- <div className="flex items-center gap-2">
- <Mail className="h-4 w-4 shrink-0 text-muted-foreground" />
- <SheetTitle className="truncate flex-1">
- {loading ? "Loading..." : email?.subject || "Email"}
- </SheetTitle>
- <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleOpenChange(false)}>
- <X className="h-4 w-4" />
- </Button>
- </div>
- </SheetHeader>
-
- <SheetBody className="flex-1 overflow-y-auto thin-scrollbar">
- {loading ? (
- <div className="flex items-center justify-center py-12">
- <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
- </div>
- ) : email ? (
- <div className="flex flex-col gap-4">
- <div className="text-sm space-y-1 border-b pb-3">
- <div className="flex gap-2">
- <span className="text-muted-foreground shrink-0">From:</span>
- <span className="truncate">{email.from_email}</span>
- </div>
- <div className="flex gap-2">
- <span className="text-muted-foreground shrink-0">To:</span>
- <span className="truncate">{email.to_email}</span>
- </div>
- <div className="flex gap-2">
- <span className="text-muted-foreground shrink-0">Date:</span>
- <span>{new Date(email.created_at).toLocaleString()}</span>
- </div>
- </div>
-
- {body?.isHtml ? (
- <EmailBodyFrame html={body.content} className="max-w-full" />
- ) : (
- <pre className="whitespace-pre-wrap text-sm font-mono">{body?.content}</pre>
- )}
-
- {email.attachments && email.attachments.length > 0 && (
- <div className="border-t pt-3">
- <div className="flex items-center gap-2 mb-2 text-xs text-muted-foreground">
- <Paperclip className="size-3" />
- {email.attachments.length} attachment{email.attachments.length > 1 ? "s" : ""}
- </div>
- <div className="flex flex-wrap gap-2">
- {email.attachments.map((att, i) => (
- <FileDownloadButton
- key={att.key}
- url={`/api/email/${email.id}/attachment/${i}?workspace_id=${workspaceId}`}
- filename={att.filename}
- className="flex items-center gap-2 rounded-md border border-border/50 bg-muted/50 px-2 py-2 text-xs hover:bg-muted transition-colors cursor-pointer"
- >
- <FileIcon className="size-3 text-muted-foreground shrink-0" />
- <span className="truncate max-w-45">{att.filename}</span>
- <span className="text-muted-foreground shrink-0">
- {att.size < 1024 ? `${att.size} B` : att.size < 1024 * 1024 ? `${(att.size / 1024).toFixed(1)} KB` : `${(att.size / (1024 * 1024)).toFixed(1)} MB`}
- </span>
- </FileDownloadButton>
- ))}
- </div>
- </div>
- )}
- </div>
- ) : null}
- </SheetBody>
- </SheetContent>
- </Sheet>
- );
-}
diff --git a/src/web/src/components/agent-chat/event-cards/calendar-card.tsx b/src/web/src/components/agent-chat/event-cards/calendar-card.tsx
deleted file mode 100644
index 03ada8404..000000000
--- a/src/web/src/components/agent-chat/event-cards/calendar-card.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import React from "react";
-
-const REPEAT_LABELS: Record<string, string> = {
- "1day": "Daily",
- "1week": "Weekly",
- "1month": "Monthly",
-};
-
-function humanizeRepeat(interval: string): string {
- if (REPEAT_LABELS[interval]) return REPEAT_LABELS[interval];
- const m = /^(\d+)(hour|day|week|month)s?$/.exec(interval);
- if (m) return `Every ${m[1]} ${m[2]}${Number(m[1]) > 1 ? "s" : ""}`;
- return interval;
-}
-
-export function CalendarCard({
- title,
- scheduledAt,
- repeatInterval,
- onClick,
-}: {
- title: string;
- scheduledAt?: string;
- repeatInterval?: string;
- onClick?: () => void;
-}) {
- const date = scheduledAt ? new Date(scheduledAt) : null;
- const dayOfWeek = date
- ? date.toLocaleDateString("en-US", { weekday: "short" })
- : null;
- const monthStr = date
- ? date.toLocaleDateString("en-US", { month: "short" })
- : null;
- const dayNum = date ? date.getDate() : null;
- const timeStr = date
- ? date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" })
- : null;
-
- return (
- <button
- type="button"
- onClick={onClick}
- disabled={!onClick}
- className="card-grain w-104 max-w-full overflow-hidden rounded-(--radius) border border-(--border) text-left cursor-pointer [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 [box-shadow:var(--e1)] hover:[box-shadow:var(--e2)]"
- >
- <span className="h-6 bg-(--tc) flex items-center px-3">
- {date ? (
- <span className="text-[0.62rem] font-semibold uppercase tracking-[0.06em] text-white/85">
- {dayOfWeek} {monthStr} {dayNum}
- </span>
- ) : (
- <span className="text-[0.62rem] font-semibold uppercase tracking-[0.06em] text-white/85">
- Calendar
- </span>
- )}
- {repeatInterval && (
- <span className="ml-auto text-[0.52rem] font-semibold uppercase tracking-[0.04em] px-1 py-px rounded-full bg-white/20 text-white/90">
- {humanizeRepeat(repeatInterval)}
- </span>
- )}
- </span>
- <span className="bg-(--paper) p-3 flex gap-3 items-start">
- {dayNum != null && (
- <span className="text-[1.8rem] font-bold leading-none tracking-[-0.02em] opacity-80 min-w-8 text-center shrink-0">
- {dayNum}
- </span>
- )}
- <span className="min-w-0 flex-1 flex flex-col">
- <span className="text-[0.92rem] font-semibold tracking-[-0.01em] leading-[1.3]">
- {title}
- </span>
- {timeStr && (
- <span className="text-[0.72rem] text-(--muted-foreground) mt-1 font-mono">
- {timeStr}
- </span>
- )}
- </span>
- </span>
- </button>
- );
-}
diff --git a/src/web/src/components/agent-chat/event-cards/file-card.tsx b/src/web/src/components/agent-chat/event-cards/file-card.tsx
deleted file mode 100644
index ec90ca782..000000000
--- a/src/web/src/components/agent-chat/event-cards/file-card.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import React from "react";
-import { formatSize } from "@/components/agent-chat/artifact-sheet";
-
-function getExtension(filename: string, contentType?: string): string {
- const dot = filename.lastIndexOf(".");
- if (dot > -1) return filename.slice(dot + 1).toUpperCase();
- if (contentType) {
- const sub = contentType.split("/")[1];
- if (sub) return sub.split(";")[0].toUpperCase();
- }
- return "FILE";
-}
-
-export function FileCard({
- filename,
- size,
- contentType,
- version,
- hasDuplicates,
- onClick,
-}: {
- filename: string;
- size: number;
- contentType?: string;
- version?: number;
- hasDuplicates?: boolean;
- onClick?: () => void;
-}) {
- const ext = getExtension(filename, contentType);
-
- return (
- <button
- type="button"
- onClick={onClick}
- disabled={!onClick}
- className="card-grain w-104 max-w-full overflow-hidden rounded-(--radius) border border-(--border) bg-(--paper) text-left grid grid-cols-[44px_1fr] cursor-pointer [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 [box-shadow:var(--e1)] hover:[box-shadow:var(--e2)]"
- >
- <span className="flex flex-col items-center justify-center border-r border-(--border) bg-[oklch(from_var(--tf)_l_c_h/0.08)] gap-1 p-2">
- <span className="flex flex-col gap-1 w-4.5">
- <i className="h-[1.5px] rounded-sm bg-(--tf) opacity-[0.28] w-full" />
- <i className="h-[1.5px] rounded-sm bg-(--tf) opacity-[0.28] w-[78%]" />
- <i className="h-[1.5px] rounded-sm bg-(--tf) opacity-[0.28] w-[55%]" />
- </span>
- <span className="font-mono text-[0.44rem] font-semibold uppercase text-(--tf) mt-px tracking-[0.02em]">
- {ext}
- </span>
- </span>
- <span className="p-3 min-w-0 flex flex-col justify-center gap-1">
- <span className="flex items-center gap-2 min-w-0">
- <span className="text-[0.9rem] font-semibold tracking-[-0.01em] truncate">
- {filename}
- </span>
- {hasDuplicates && version != null && (
- <span className="shrink-0 text-xs text-(--muted-foreground) bg-(--muted) rounded-full px-2 py-1 font-normal">
- v{version}
- </span>
- )}
- </span>
- <span className="text-[0.7rem] text-(--muted-foreground) font-mono">
- {formatSize(size)}
- </span>
- </span>
- </button>
- );
-}
diff --git a/src/web/src/components/agent-chat/event-cards/issue-card.tsx b/src/web/src/components/agent-chat/event-cards/issue-card.tsx
deleted file mode 100644
index 62abe69a1..000000000
--- a/src/web/src/components/agent-chat/event-cards/issue-card.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import React from "react";
-
-const EVENT_LABELS: Record<string, string> = {
- created: "Issue created",
- status_changed: "Issue updated",
- dispatch_failed: "Dispatch failed",
-};
-
-function stampText(
- event: string,
- toStatus?: string,
-): string | null {
- if (event === "created") return "New";
- if (event === "status_changed") return toStatus ?? "Done";
- return null;
-}
-
-export function IssueCard({
- title,
- event,
- fromStatus,
- toStatus,
- assigneeName,
- onClick,
-}: {
- title: string;
- event: "created" | "status_changed" | "dispatch_failed";
- fromStatus?: string;
- toStatus?: string;
- assigneeName?: string;
- onClick?: () => void;
-}) {
- const stamp = stampText(event, toStatus);
- const meta =
- event === "created" && assigneeName
- ? `assigned to ${assigneeName}`
- : event === "status_changed" && fromStatus && toStatus
- ? `${fromStatus} → ${toStatus}`
- : null;
-
- return (
- <button
- type="button"
- onClick={onClick}
- disabled={!onClick}
- className="card-grain w-104 max-w-full overflow-hidden rounded-(--radius) border border-(--border) bg-(--paper) text-left flex cursor-pointer [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 [box-shadow:var(--e1)] hover:[box-shadow:var(--e2)]"
- >
- <span className="w-1 bg-(--ti) shrink-0 self-stretch" />
- <span className="flex-1 p-3 min-w-0 flex flex-col gap-1 relative">
- <span className="text-[0.62rem] font-semibold uppercase tracking-wider text-(--ti) leading-none">
- {EVENT_LABELS[event] ?? event}
- </span>
- <span className="text-[0.92rem] font-semibold tracking-[-0.01em] leading-[1.3] line-clamp-2 pr-8">
- {title}
- </span>
- {meta && (
- <span className="text-[0.75rem] text-(--muted-foreground) leading-[1.2]">
- {meta}
- </span>
- )}
- {stamp && (
- <span className="absolute top-3 right-3 text-[0.5rem] font-bold uppercase tracking-wider text-(--ti) border-[1.5px] border-(--ti) opacity-45 rotate-[4deg] rounded-[3px] px-1 py-1">
- {stamp}
- </span>
- )}
- </span>
- </button>
- );
-}
diff --git a/src/web/src/components/agent-chat/fast-load-gate.test.ts b/src/web/src/components/agent-chat/fast-load-gate.test.ts
deleted file mode 100644
index 597a7d328..000000000
--- a/src/web/src/components/agent-chat/fast-load-gate.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- createFastLoadGateState,
- fastLoadKey,
- shouldSkipFastLoad,
- markFastLoadCompleted,
-} from "./fast-load-gate";
-
-const ID = { workspaceId: "w1", agentId: "a1", targetConvId: "c1", scrollToTaskId: null };
-
-describe("fastLoadKey", () => {
- it("returns null on the slow path (no targetConvId)", () => {
- expect(fastLoadKey({ ...ID, targetConvId: null })).toBeNull();
- expect(fastLoadKey({ ...ID, targetConvId: undefined })).toBeNull();
- });
-
- it("excludes channel — same identity always yields the same key", () => {
- const k1 = fastLoadKey(ID);
- const k2 = fastLoadKey(ID);
- expect(k1).toBe(k2);
- expect(k1).toContain("w1");
- expect(k1).toContain("a1");
- expect(k1).toContain("c1");
- });
-
- it("changes when agent / conv / scroll target change", () => {
- const base = fastLoadKey(ID);
- expect(fastLoadKey({ ...ID, agentId: "a2" })).not.toBe(base);
- expect(fastLoadKey({ ...ID, targetConvId: "c2" })).not.toBe(base);
- expect(fastLoadKey({ ...ID, scrollToTaskId: "t9" })).not.toBe(base);
- });
-});
-
-describe("fast-load gate lifecycle", () => {
- it("TODO 6: same key re-fire AFTER completion is skipped (no flash / no re-fetch)", () => {
- const state = createFastLoadGateState();
- const key = fastLoadKey(ID)!;
-
- // Run #1 starts then completes.
- expect(shouldSkipFastLoad(key, state)).toBe(false);
- markFastLoadCompleted(key, state);
-
- // Re-fire from a pure channel-dep change → same key, already completed → skip.
- expect(shouldSkipFastLoad(key, state)).toBe(true);
- });
-
- it("REGRESSION: cancelled-mid-flight run does NOT strand the skeleton — recovery run proceeds", () => {
- const state = createFastLoadGateState();
- const key = fastLoadKey(ID)!;
-
- // Run #1 starts (does NOT complete — it gets cancelled mid-load, so
- // markFastLoadCompleted is never called for it).
- expect(shouldSkipFastLoad(key, state)).toBe(false);
-
- // Run #2 (recovery) fires with the SAME key while #1 is still in flight.
- // It must NOT be skipped — otherwise nobody clears messagesLoading.
- expect(shouldSkipFastLoad(key, state)).toBe(false);
-
- // Run #2 completes and records the marker.
- markFastLoadCompleted(key, state);
-
- // Now a later pure channel re-fire is correctly deduped.
- expect(shouldSkipFastLoad(key, state)).toBe(true);
- });
-
- it("a cancelled run that already marked nothing leaves completedKey null", () => {
- const state = createFastLoadGateState();
- const key = fastLoadKey(ID)!;
- shouldSkipFastLoad(key, state); // start, clears marker
- // (run cancelled — markFastLoadCompleted NOT called)
- expect(state.completedKey).toBeNull();
- });
-
- it("starting a load clears a stale completed marker (different identity)", () => {
- const state = createFastLoadGateState();
- const k1 = fastLoadKey(ID)!;
- const k2 = fastLoadKey({ ...ID, targetConvId: "c2" })!;
-
- shouldSkipFastLoad(k1, state);
- markFastLoadCompleted(k1, state);
- expect(state.completedKey).toBe(k1);
-
- // Switching to a different conversation starts a new load → marker cleared
- // until the new run finishes (no false dedup across identities).
- expect(shouldSkipFastLoad(k2, state)).toBe(false);
- expect(state.completedKey).toBeNull();
- });
-
- it("slow path (null key) never skips and never records a marker", () => {
- const state = createFastLoadGateState();
- expect(shouldSkipFastLoad(null, state)).toBe(false);
- markFastLoadCompleted(null, state);
- expect(state.completedKey).toBeNull();
- // A subsequent null run also proceeds.
- expect(shouldSkipFastLoad(null, state)).toBe(false);
- });
-});
diff --git a/src/web/src/components/agent-chat/fast-load-gate.ts b/src/web/src/components/agent-chat/fast-load-gate.ts
deleted file mode 100644
index 1bab9af5d..000000000
--- a/src/web/src/components/agent-chat/fast-load-gate.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * Dedup gate for the fast-path chat load (TODO 6 / stuck-skeleton regression fix).
- *
- * The chat load effect re-fires on channel-dep changes (activeChannel /
- * channelLoading). For a known conversation (fast path) those deps are
- * irrelevant, so a re-fire with the same identity should be skipped to avoid a
- * skeleton flash + re-fetch. BUT skipping must never strand the UI on the
- * loading skeleton: if the previous run for that identity was cancelled before
- * it finished, the re-fire is a *recovery* run and MUST proceed.
- *
- * The invariant: a fast-load key is recorded as "completed" only AFTER its
- * load() resolves (not when it starts). So:
- * - same key, prior run completed → skip (steady-state channel change)
- * - same key, prior run cancelled → do NOT skip (recovery; clears skeleton)
- *
- * This module is the pure decision logic, extracted so the lifecycle can be
- * unit-tested without rendering the component (the web test env is node-only,
- * no jsdom/RTL).
- */
-
-export interface FastLoadGateState {
- /** The fast-load key whose load() has fully COMPLETED, or null. */
- completedKey: string | null;
-}
-
-export function createFastLoadGateState(): FastLoadGateState {
- return { completedKey: null };
-}
-
-/**
- * Build the fast-path key for a load identity, or null for the slow path
- * (no targetConvId). Channel is intentionally excluded — channel changes must
- * not change the key.
- */
-export function fastLoadKey(opts: {
- workspaceId: string;
- agentId: string;
- targetConvId: string | null | undefined;
- scrollToTaskId: string | null | undefined;
-}): string | null {
- if (!opts.targetConvId) return null;
- return `${opts.workspaceId}::${opts.agentId}::${opts.targetConvId}::${opts.scrollToTaskId ?? ""}`;
-}
-
-/**
- * Decide whether this effect run should skip starting a load. Returns true only
- * when a load for the same fast key has already completed. Mutates state to
- * clear the completed marker when a run is about to start (so an in-flight run
- * leaves no "done" marker if it gets cancelled).
- */
-export function shouldSkipFastLoad(key: string | null, state: FastLoadGateState): boolean {
- if (key && state.completedKey === key) return true;
- // A new / recovery run is starting — until it finishes, nothing is "completed".
- state.completedKey = null;
- return false;
-}
-
-/**
- * Record that a load fully completed (call from the finally block when the run
- * was NOT superseded). A cancelled run must not call this.
- */
-export function markFastLoadCompleted(key: string | null, state: FastLoadGateState): void {
- if (key) state.completedKey = key;
-}
diff --git a/src/web/src/components/agent-chat/image-lightbox.tsx b/src/web/src/components/agent-chat/image-lightbox.tsx
deleted file mode 100644
index 9b769f6c2..000000000
--- a/src/web/src/components/agent-chat/image-lightbox.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-"use client";
-
-import { FileDownloadButton } from "@/components/file-download-button"
-import React, { useEffect, useCallback } from "react";
-import { createPortal } from "react-dom";
-import type { Artifact } from "@alook/shared";
-import { X, Download } from "lucide-react";
-import { getArtifactUrl } from "@/components/artifact-content-renderer";
-import { RemoteContentImage } from "@/components/remote-image/remote-image";
-
-type LightboxProps = {
- open: boolean;
- onClose: () => void;
-} & (
- | { artifact: Artifact | null; workspaceId: string; imageUrl?: undefined }
- | { imageUrl: string; filename: string; artifact?: undefined; workspaceId?: undefined }
-);
-
-export function ImageLightbox(props: LightboxProps) {
- const { open, onClose } = props;
-
- const handleKeyDown = useCallback(
- (e: KeyboardEvent) => {
- if (e.key === "Escape") onClose();
- },
- [onClose],
- );
-
- useEffect(() => {
- if (!open) return;
- document.addEventListener("keydown", handleKeyDown);
- return () => document.removeEventListener("keydown", handleKeyDown);
- }, [open, handleKeyDown]);
-
- let src: string;
- let alt: string;
- let downloadUrl: string | undefined;
-
- if (props.imageUrl) {
- if (!open) return null;
- src = props.imageUrl;
- alt = props.filename;
- } else {
- if (!open || !props.artifact) return null;
- src = getArtifactUrl(props.artifact.id, props.workspaceId);
- alt = props.artifact.filename;
- downloadUrl = getArtifactUrl(props.artifact.id, props.workspaceId, true);
- }
-
- return createPortal(
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-md animate-in fade-in duration-150"
- onClick={onClose}
- >
- <div className="absolute top-4 right-4 flex items-center gap-2">
- {downloadUrl && (
- <FileDownloadButton
- url={downloadUrl}
- filename={alt}
- aria-label={`Download ${alt}`}
- onClick={(e) => e.stopPropagation()}
- className="rounded-full p-2 text-white/70 hover:text-white hover:bg-white/10 transition-colors"
- >
- <Download className="size-5" />
- </FileDownloadButton>
- )}
- <button
- type="button"
- aria-label="Close image"
- onClick={onClose}
- className="rounded-full p-2 text-white/70 hover:text-white hover:bg-white/10 transition-colors"
- >
- <X className="size-5" />
- </button>
- </div>
- {props.imageUrl ? (
- <img
- src={src}
- alt={alt}
- onClick={(e) => e.stopPropagation()}
- className="max-h-[90vh] max-w-[90vw] rounded-lg object-contain"
- />
- ) : (
- <div onClick={(event) => event.stopPropagation()}>
- <RemoteContentImage
- src={src}
- alt={alt}
- loading="eager"
- loadingLabel="Loading image"
- frameClassName="h-[min(75vh,48rem)] w-[min(90vw,64rem)] rounded-lg bg-background/10"
- imageClassName="rounded-lg object-contain"
- errorLabel="Image failed to load"
- />
- </div>
- )}
- </div>,
- document.body,
- );
-}
diff --git a/src/web/src/components/agent-chat/menu-toggle-icon.test.ts b/src/web/src/components/agent-chat/menu-toggle-icon.test.ts
deleted file mode 100644
index ecc5507f6..000000000
--- a/src/web/src/components/agent-chat/menu-toggle-icon.test.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { MenuToggleIcon } from "./menu-toggle-icon";
-
-describe("MenuToggleIcon", () => {
- it("exports a function component", () => {
- expect(typeof MenuToggleIcon).toBe("function");
- });
-});
diff --git a/src/web/src/components/agent-chat/menu-toggle-icon.tsx b/src/web/src/components/agent-chat/menu-toggle-icon.tsx
deleted file mode 100644
index e54cc2ce5..000000000
--- a/src/web/src/components/agent-chat/menu-toggle-icon.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { Menu, X } from "lucide-react";
-import { cn } from "@/lib/utils";
-
-export function MenuToggleIcon({ open }: { open: boolean }) {
- return (
- <span className="relative size-4">
- <Menu
- className={cn(
- "size-4 absolute transition-all duration-200",
- open
- ? "opacity-0 rotate-90 scale-75"
- : "opacity-100 rotate-0 scale-100",
- )}
- />
- <X
- className={cn(
- "size-4 absolute transition-all duration-200",
- open
- ? "opacity-100 rotate-0 scale-100"
- : "opacity-0 -rotate-90 scale-75",
- )}
- />
- </span>
- );
-}
diff --git a/src/web/src/components/agent-chat/message-list.test.ts b/src/web/src/components/agent-chat/message-list.test.ts
deleted file mode 100644
index d999ab806..000000000
--- a/src/web/src/components/agent-chat/message-list.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { shouldRenderAssistantBody } from "./message-list";
-
-// AC4 regression guard: a send-dm reply that is ALSO the message carrying the
-// live error stream must still render its own text bubble (error is additive),
-// while a runtime-error message stays surfaced by the stream alone when live.
-describe("shouldRenderAssistantBody", () => {
- it("renders a normal text reply that carries the error stream (the AC4 fix)", () => {
- // designated last send-dm message + an error stream attached
- expect(
- shouldRenderAssistantBody({ hasTaskStream: true, isRuntimeError: false }),
- ).toBe(true);
- });
-
- it("renders a normal text reply with no stream (unchanged clean case)", () => {
- expect(
- shouldRenderAssistantBody({ hasTaskStream: false, isRuntimeError: false }),
- ).toBe(true);
- });
-
- it("suppresses a runtime-error message's own block while the stream owns it", () => {
- // The stream surfaces the error; rendering the block too would double it.
- expect(
- shouldRenderAssistantBody({ hasTaskStream: true, isRuntimeError: true }),
- ).toBe(false);
- });
-
- it("renders a runtime-error message's block when no stream owns it", () => {
- expect(
- shouldRenderAssistantBody({ hasTaskStream: false, isRuntimeError: true }),
- ).toBe(true);
- });
-});
diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsx
deleted file mode 100644
index 78a4acb6e..000000000
--- a/src/web/src/components/agent-chat/message-list.tsx
+++ /dev/null
@@ -1,870 +0,0 @@
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import React, { memo } from "react";
-import { parseEmailHandle, stripMentionTokens, type Agent, type Artifact, type Message, type TaskApi as Task, type TaskMessageResponse } from "@alook/shared";
-
-import { cn } from "@/lib/utils";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { Sheet, SheetContent } from "@/components/ui/sheet";
-import { Streamdown } from "streamdown";
-import { mermaid, cjk, math } from "@/lib/streamdown-plugins";
-import { highlightMentions } from "@/lib/highlight-mentions";
-import { TaskStream } from "@/components/task-stream";
-import { RuntimeErrorBlock } from "@/components/agent-chat/runtime-error-block";
-import { AnimatedAvatar } from "@/components/avatar";
-import { FileText, Flag, Copy, Check, MessageSquareQuote, MessageSquare, Image as ImageIcon } from "lucide-react";
-import { getArtifactThumbnailUrl } from "@/components/artifact-content-renderer";
-import type { PendingFile } from "@/hooks/use-file-attachments";
-import { EmailCard } from "@/components/agent-chat/event-cards/email-card";
-import { CalendarCard } from "@/components/agent-chat/event-cards/calendar-card";
-import { IssueCard } from "@/components/agent-chat/event-cards/issue-card";
-import { MessageBubble, MessageCluster, AVATAR_SIZE, type BubblePosition } from "@/components/chat-primitives";
-
-import { eventTypeFromMessage, type GroupPosition } from "@/components/agent-chat/chat-message-utils";
-import { toast } from "sonner";
-import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
-import { useHoverCapable } from "@/hooks/use-hover-capable";
-import { useLongPress } from "@/hooks/use-long-press";
-import { RemoteContentImage } from "@/components/remote-image/remote-image";
-
-const MENTION_ALLOWED_TAGS = { mention: ["data-agent-id"] };
-const MENTION_LITERAL_TAGS = ["mention"];
-
-function toBubblePosition(gp: GroupPosition): BubblePosition {
- return gp === "solo" ? "single" : gp;
-}
-
-/**
- * Whether an assistant message renders its own body (text bubble or, for a
- * runtime-error message, its RuntimeErrorBlock) — independent of the live error
- * stream wrapper, which is ADDITIVE.
- *
- * The AC4 fix: a normal `send-dm` text reply must paint even when it's the
- * message designated to carry the live error stream (`hasTaskStream`), so its
- * text is never swallowed. The one exception is a runtime-error message: it IS
- * the error and is already surfaced by the stream while live, so it only renders
- * its own block when no stream owns it (`!hasTaskStream`) — avoiding a double
- * error render.
- */
-export function shouldRenderAssistantBody(opts: {
- hasTaskStream: boolean;
- isRuntimeError: boolean;
-}): boolean {
- return !opts.hasTaskStream || !opts.isRuntimeError;
-}
-
-export interface MessageItemProps {
- msg: Message;
- agents: Agent[];
- artifacts: Artifact[];
- activeTask: Task | null;
- /**
- * Id of the single assistant message for the active task that should carry the
- * live error-surface (TaskStream). When a task emits multiple `send-dm`
- * replies, only this one (the last) gets the stream wrapper — the rest fall to
- * the clean bubble path. Null when there's no active-task assistant message.
- */
- activeTaskStreamMsgId?: string | null;
- taskMessages: TaskMessageResponse[];
- connectionLost: boolean;
- conversationType?: string | null;
- pendingFilesByMessage: Map<string, PendingFile[]>;
- workspaceId: string;
- onArtifactClick: (a: Artifact) => void;
- onEmailClick: (emailId: string) => void;
- onIssueClick: (issueId: string) => void;
- onCalendarEventClick: (calendarEventId: string) => void;
- onRetry?: () => void;
- mentionComponents: Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>>;
- isFlagged?: boolean;
- onToggleFlag?: (messageId: string) => void;
- groupPosition?: GroupPosition;
- /** Provider of the conversation's agent runtime, used to attribute runtime errors (issue #236). */
- provider?: string | null;
- /** Agent display name + avatar, for the agent-side IM bubbles and system cards. */
- agentName: string;
- agentAvatarSeed: string;
- agentAvatarUrl?: string | null;
- /** This optimistic user message failed to send — show the inline retry affordance. */
- isSendFailed?: boolean;
- onRetrySend?: (messageId: string) => void;
- onPendingImageClick?: (file: File) => void;
- onQuote?: (messageId: string, excerpt: string) => void;
- onReplyInThread?: (messageId: string) => void;
- threadSummary?: { thread_id: string; reply_count: number; last_reply_at: string | null; thread_title: string } | null;
- isThreadRoot?: boolean;
- onAgentChatOpen?: (agentId: string, targetConvId: string) => void;
-}
-
-type EmailData = {
- type: "email";
- subject: string;
- address: string;
- direction: "inbound" | "outbound";
-};
-type CalendarData = {
- type: "calendar";
- title: string;
- scheduledAt?: string;
- repeatInterval?: string;
-};
-type IssueData = {
- type: "issue";
- title: string;
- event: "created" | "status_changed" | "dispatch_failed";
- fromStatus?: string;
- toStatus?: string;
- agentId?: string;
-};
-type EventData = EmailData | CalendarData | IssueData;
-
-function parseEventData(
- metadata: Record<string, unknown> | null | undefined,
- content: string,
- conversationType?: string | null,
-): EventData {
- const type = eventTypeFromMessage(metadata, content, conversationType);
-
- if (type === "email") {
- if (metadata?.subject) {
- return {
- type: "email",
- subject: metadata.subject as string,
- address: (metadata.direction === "inbound" ? metadata.from : metadata.to) as string,
- direction: metadata.direction as "inbound" | "outbound",
- };
- }
- const sent = /^Email sent to (.+?): ([\s\S]+)$/.exec(content);
- if (sent) return { type: "email", subject: sent[2], address: sent[1], direction: "outbound" };
- const inbound = /^New email from (.+?): ([\s\S]+)$/.exec(content);
- if (inbound) return { type: "email", subject: inbound[2], address: inbound[1], direction: "inbound" };
- const colon = content.indexOf(": ");
- return {
- type: "email",
- subject: colon > -1 ? content.slice(colon + 2) : content,
- address: "",
- direction: "inbound",
- };
- }
-
- if (type === "issue") {
- if (metadata?.event) {
- return {
- type: "issue",
- title: (metadata.title as string) ?? content.replace(/^Issue (?:created|opened|status changed):?\s*/i, ""),
- event: metadata.event as "created" | "status_changed" | "dispatch_failed",
- fromStatus: metadata.fromStatus as string | undefined,
- toStatus: metadata.toStatus as string | undefined,
- agentId: metadata.agentId as string | undefined,
- };
- }
- const status = /^Issue status changed: ([\s\S]+?) -> ([\s\S]+)$/.exec(content);
- if (status) return { type: "issue", title: `${status[1]} → ${status[2]}`, event: "status_changed", fromStatus: status[1], toStatus: status[2] };
- const created = /^Issue (?:created|opened): ([\s\S]+)$/.exec(content);
- if (created) return { type: "issue", title: created[1], event: "created" };
- if (/dispatch failed/i.test(content)) return { type: "issue", title: content.replace(/^Issue dispatch failed:?\s*/i, ""), event: "dispatch_failed" };
- return { type: "issue", title: content.replace(/^Issue:?\s*/i, ""), event: "created" };
- }
-
- // calendar
- if (metadata?.title) {
- return {
- type: "calendar",
- title: metadata.title as string,
- scheduledAt: metadata.scheduledAt as string | undefined,
- repeatInterval: metadata.repeatInterval as string | undefined,
- };
- }
- return { type: "calendar", title: content.replace(/^Calendar event:\s*/i, "") };
-}
-
-function AttachmentChips({
- attachmentIds,
- artifacts,
- onArtifactClick,
-}: {
- attachmentIds: string[];
- artifacts: Artifact[];
- onArtifactClick: (a: Artifact) => void;
-}) {
- const matched = attachmentIds
- .map((id) => artifacts.find((a) => a.id === id))
- .filter((a): a is Artifact => !!a)
- .filter((a) => !a.content_type.startsWith("image/"));
-
- if (matched.length === 0) return null;
-
- return (
- <div className="flex flex-wrap gap-2 mt-2">
- {matched.map((a) => (
- <button
- key={a.id}
- type="button"
- onClick={(e) => { e.stopPropagation(); onArtifactClick(a); }}
- className="inline-flex items-center gap-1 rounded-md bg-primary-foreground/10 border border-primary-foreground/20 px-2 py-1 text-xs text-primary-foreground/80 hover:bg-primary-foreground/20 transition-colors cursor-pointer"
- >
- <FileText className="size-3 shrink-0" />
- <span className="truncate max-w-37.5">{a.filename}</span>
- </button>
- ))}
- </div>
- );
-}
-
-function ImageAttachmentCards({
- attachmentIds,
- artifacts,
- workspaceId,
- onArtifactClick,
-}: {
- attachmentIds: string[];
- artifacts: Artifact[];
- workspaceId: string;
- onArtifactClick: (a: Artifact) => void;
-}) {
- const images = attachmentIds
- .map((id) => artifacts.find((a) => a.id === id))
- .filter((a): a is Artifact => !!a && a.content_type.startsWith("image/"));
-
- if (images.length === 0) return null;
-
- return (
- <div className="flex flex-wrap gap-2 mt-2">
- {images.map((a) => {
- const thumbUrl = a.has_thumbnail
- ? getArtifactThumbnailUrl(a.id, workspaceId)
- : undefined;
- return thumbUrl ? (
- <RemoteContentImage
- key={a.id}
- src={thumbUrl}
- alt={a.filename}
- loading="lazy"
- onActivate={(event) => { event.stopPropagation(); onArtifactClick(a); }}
- frameClassName="w-48 max-w-full rounded-(--radius) border border-(--border) [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 hover:[box-shadow:var(--e2)] [box-shadow:var(--e1)]"
- frameStyle={{ aspectRatio: "8/5" }}
- imageClassName="object-contain"
- errorLabel="Preview failed to load"
- />
- ) : (
- <button
- key={a.id}
- type="button"
- onClick={(e) => { e.stopPropagation(); onArtifactClick(a); }}
- className="inline-flex items-center gap-1 rounded-md bg-primary-foreground/10 border border-primary-foreground/20 px-2 py-1 text-xs text-primary-foreground/80 hover:bg-primary-foreground/20 transition-colors cursor-pointer"
- >
- <ImageIcon className="size-3 shrink-0" />
- <span className="truncate max-w-37.5">{a.filename}</span>
- </button>
- );
- })}
- </div>
- );
-}
-
-// Slack/Discord cluster model: delegates to <MessageCluster> from
-// chat-primitives. This wrapper adapts the product's AnimatedAvatar + the
-// `forceSpacer` concept into the primitive's props interface.
-
-export function AgentRow({
- groupPosition,
- agentName,
- seed,
- avatarUrl,
- forceSpacer = false,
- children,
-}: {
- groupPosition: GroupPosition;
- agentName: string;
- seed: string;
- avatarUrl?: string | null;
- forceSpacer?: boolean;
- children: React.ReactNode;
-}) {
- const effectivePosition: GroupPosition = forceSpacer ? "middle" : groupPosition;
- return (
- <MessageCluster
- avatar={
- <AnimatedAvatar
- seed={seed}
- avatarUrl={avatarUrl}
- size={AVATAR_SIZE}
- className="rounded-md"
- isHovered={false}
- />
- }
- name={agentName}
- position={effectivePosition}
- >
- {children}
- </MessageCluster>
- );
-}
-
-// One per-message action (Copy / Flag / …). Rendered as a toolbar icon button
-// (desktop hover) or a sheet row (touch long-press) — same descriptor, two
-// presentations.
-interface MessageAction {
- key: string;
- label: string;
- icon: React.ReactNode;
- onClick: () => void;
- /** Persistent on-state (e.g. flagged) — shown full-contrast in both surfaces. */
- active?: boolean;
-}
-
-// Desktop: a small horizontal toolbar pinned to the bubble's TOP-RIGHT corner,
-// overlapping it (sits above the bubble top so it never covers text), fading in
-// on hover. Always right-anchored regardless of message role.
-function MessageActionsToolbar({
- actions,
-}: {
- actions: MessageAction[];
-}) {
- if (actions.length === 0) return null;
- return (
- <div
- className={cn(
- "absolute -top-3 right-0 z-10 flex items-center gap-1 rounded-lg border bg-card p-1 shadow-sm",
- // Fade-only reveal (reduced-motion safe — no transform/lift).
- "opacity-0 transition-opacity duration-150 group-hover/msg:opacity-100 focus-within:opacity-100",
- )}
- >
- {actions.map((a) => (
- <Tooltip key={a.key}>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label={a.label}
- onClick={(e) => {
- e.stopPropagation();
- a.onClick();
- }}
- className={cn(
- a.active ? "text-foreground" : "text-muted-foreground",
- )}
- />
- }
- >
- {a.icon}
- </TooltipTrigger>
- <TooltipContent>{a.label}</TooltipContent>
- </Tooltip>
- ))}
- </div>
- );
-}
-
-// Touch: the same actions as a bottom action sheet, opened by long-pressing the
-// bubble. No persistently-visible on-bubble controls (the clutter we removed).
-function MessageActionsSheet({
- open,
- onOpenChange,
- actions,
-}: {
- open: boolean;
- onOpenChange: (o: boolean) => void;
- actions: MessageAction[];
-}) {
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent side="bottom" showCloseButton={false} className="rounded-t-2xl p-2">
- <div className="flex flex-col">
- {actions.map((a) => (
- <button
- key={a.key}
- type="button"
- onClick={() => {
- a.onClick();
- onOpenChange(false);
- }}
- className={cn(
- "flex items-center gap-3 rounded-lg px-3 py-3 text-left text-[0.95rem] active:bg-muted",
- a.active ? "text-foreground" : "text-foreground",
- )}
- >
- <span className="text-muted-foreground">{a.icon}</span>
- {a.label}
- </button>
- ))}
- </div>
- </SheetContent>
- </Sheet>
- );
-}
-
-// Persistent, glanceable flagged marker that lives on the BUBBLE itself (not in
-// the action UI), so a flagged message reads as flagged whether or not the
-// toolbar/sheet is open. Monochrome corner dot; paired with an inset left rail
-// on the bubble. Bubble-only — non-bubble cases (runtime error / failed stream)
-// use the existing row-tint instead.
-function FlagDot() {
- return (
- <span
- aria-hidden
- className="absolute -left-2 -top-2 z-10 flex size-3.5 items-center justify-center rounded-full border-2 border-background bg-foreground text-background"
- >
- <Flag className="size-2 fill-current" />
- </span>
- );
-}
-
-function ThreadRootDot() {
- return (
- <span
- aria-hidden
- className="absolute -left-2 -top-2 z-10 flex size-3.5 items-center justify-center rounded-full border-2 border-background bg-foreground text-background"
- >
- <MessageSquare className="size-2" />
- </span>
- );
-}
-
-export const MessageItem = memo(function MessageItem({
- msg,
- agents,
- artifacts,
- activeTask,
- activeTaskStreamMsgId,
- taskMessages,
- connectionLost,
- conversationType,
- pendingFilesByMessage,
- workspaceId,
- onArtifactClick,
- onEmailClick,
- onIssueClick,
- onCalendarEventClick,
- onRetry,
- mentionComponents,
- isFlagged,
- onToggleFlag,
- groupPosition = "solo",
- provider,
- agentName,
- agentAvatarSeed,
- agentAvatarUrl,
- isSendFailed,
- onPendingImageClick,
- onRetrySend,
- onQuote,
- onReplyInThread,
- threadSummary,
- isThreadRoot,
- onAgentChatOpen,
-}: MessageItemProps) {
- const { copy, copied } = useCopyToClipboard();
-
- // TaskStream owns this assistant message only while the task is still live OR
- // it failed (it surfaces stream/task-level errors + Retry). A COMPLETED reply
- // — and a cancelled/superseded notice — falls through to the clean bubble
- // path below; otherwise the finished reply would render nowhere (TaskStream
- // no longer renders success text).
- const hasTaskStream =
- !!activeTask &&
- msg.role === "assistant" &&
- msg.task_id === activeTask.id &&
- msg.conversation_id === activeTask.conversation_id &&
- // Only the designated (last) assistant message of the active task carries
- // the stream — so multiple `send-dm` replies don't each wrap it. When the
- // parent didn't compute an id (legacy callers), fall back to per-message.
- (activeTaskStreamMsgId == null || msg.id === activeTaskStreamMsgId) &&
- taskMessages.length > 0 &&
- !["completed", "cancelled", "superseded"].includes(activeTask.status);
-
- // TaskStream renders only errors / connection-lost now. When it has nothing to
- // show (a plain running task), skip its wrapper entirely so we don't paint a
- // lone avatar in an empty gutter void.
- const streamHasContent =
- hasTaskStream &&
- (taskMessages.some((m) => m.type === "error") ||
- (activeTask!.status === "failed" && !!activeTask!.error) ||
- connectionLost);
-
- const isTaskDone = hasTaskStream && activeTask?.status === "failed";
-
- // Lifecycle notice (cancelled/superseded) — a system line, not agent speech.
- // Match the durable metadata flag, with a content fallback for older rows.
- const isLifecycleNote =
- msg.role === "assistant" &&
- (msg.metadata?.kind === "lifecycle" ||
- msg.content === "Task cancelled by you" ||
- msg.content === "Task cancelled by user");
-
- // Per-message actions: one descriptor list, two presentations (hover toolbar
- // on hover-capable devices, long-press action sheet on touch). Copy is
- // available on both user and assistant messages; Flag is assistant-only
- // (flagging your own message is meaningless). Capability is detected, not
- // viewport-sized, so a touch laptop gets the sheet and a desktop stays hover.
- const hoverCapable = useHoverCapable();
- const [actionSheetOpen, setActionSheetOpen] = useAtom(useCreateAtom(false));
-
- const doCopy = React.useCallback(async () => {
- const ok = await copy(stripMentionTokens(msg.content));
- if (ok) toast.success("Copied to clipboard");
- else toast.error("Failed to copy");
- }, [copy, msg.content]);
-
- const canCopy = msg.role === "assistant" || msg.role === "user";
- const messageActions: MessageAction[] = [];
- if (canCopy) {
- messageActions.push({
- key: "copy",
- label: copied ? "Copied" : "Copy",
- icon: copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />,
- onClick: doCopy,
- });
- }
- if (onQuote && (msg.role === "assistant" || msg.role === "user")) {
- messageActions.push({
- key: "quote",
- label: "Quote",
- icon: <MessageSquareQuote className="size-3.5" />,
- onClick: () => onQuote(msg.id, stripMentionTokens(msg.content).slice(0, 50)),
- });
- }
- if (onReplyInThread && (msg.role === "assistant" || msg.role === "user")) {
- messageActions.push({
- key: "thread",
- label: "Reply in thread",
- icon: <MessageSquare className="size-3.5" />,
- onClick: () => onReplyInThread(msg.id),
- });
- }
- if (msg.role === "assistant" && onToggleFlag) {
- messageActions.push({
- key: "flag",
- label: isFlagged ? "Unflag" : "Flag",
- icon: <Flag className={cn("size-3.5", isFlagged && "fill-current")} />,
- onClick: () => onToggleFlag(msg.id),
- active: isFlagged,
- });
- }
-
- // Long-press (touch only) opens the action sheet. Cancels on movement so it
- // never hijacks text selection. Spread onto the bubble's interactive surface.
- const longPress = useLongPress(() => {
- if (messageActions.length > 0) setActionSheetOpen(true);
- });
- // On hover-capable devices, no long-press handlers (mouse keeps select/click).
- const bubblePressHandlers = !hoverCapable && messageActions.length > 0 ? longPress : {};
-
- // The shared touch sheet — rendered once per message, opened by long-press.
- const actionSheet =
- !hoverCapable && messageActions.length > 0 ? (
- <MessageActionsSheet
- open={actionSheetOpen}
- onOpenChange={setActionSheetOpen}
- actions={messageActions}
- />
- ) : null;
-
- // The desktop hover toolbar for a given side. Only on hover-capable devices.
- const toolbar =
- hoverCapable && messageActions.length > 0 ? (
- <MessageActionsToolbar actions={messageActions} />
- ) : null;
-
- return (
- <React.Fragment>
- {hasTaskStream && streamHasContent && (
- <div
- className={cn("group/msg", isFlagged && "bg-muted/30 rounded-lg px-2 -mx-2")}
- {...(isTaskDone ? { "data-quote-source": true } : {})}
- >
- <AgentRow groupPosition={groupPosition} agentName={agentName} seed={agentAvatarSeed} avatarUrl={agentAvatarUrl}>
- <div
- className="relative min-w-0 w-fit max-w-full"
- {...(isTaskDone ? bubblePressHandlers : {})}
- >
- <TaskStream
- task={activeTask}
- messages={taskMessages}
- connectionLost={connectionLost}
- onRetry={onRetry}
- provider={provider}
- />
- {isTaskDone && toolbar}
- {isTaskDone && actionSheet}
- </div>
- </AgentRow>
- </div>
- )}
- {msg.role === "user" ? (() => {
- const slashMatch = msg.content.match(/^\/(\S+)\s?([\s\S]*)$/);
- const skillName = slashMatch?.[1] ?? null;
- const messageBody = slashMatch ? (slashMatch[2] || "") : msg.content;
- return (
- <div className="group/msg flex flex-col items-end" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
- {(() => {
- const quote = msg.metadata?.quote as { messageId?: string; excerpt?: string } | undefined;
- const quoteId = quote?.messageId;
- if (!quoteId) return null;
- return (
- <button
- type="button"
- onClick={() => {
- const target = document.querySelector(`[data-message-id="${CSS.escape(quoteId)}"]`);
- target?.scrollIntoView({ behavior: "smooth", block: "center" });
- }}
- className="max-w-[50%] mb-1 flex items-center gap-2 rounded-lg bg-muted/60 px-2 py-1 text-left"
- >
- <MessageSquareQuote className="size-3 shrink-0 text-muted-foreground" />
- <span className="text-xs text-muted-foreground truncate">{quote.excerpt}</span>
- </button>
- );
- })()}
- <MessageBubble
- variant="user"
- position={toBubblePosition(groupPosition)}
- className={cn(
- "max-w-[80%] relative",
- isSendFailed && "opacity-60",
- )}
- {...bubblePressHandlers}
- >
- {skillName && (
- <span className="inline-flex items-center rounded px-2 py-1 text-xs font-medium bg-primary-foreground/15 text-primary-foreground mb-1">
- /{skillName}
- </span>
- )}
- {messageBody && (
- <div className="markdown markdown-user">
- <Streamdown plugins={{ mermaid, cjk, math }} controls={{ code: { copy: true, download: false }, table: { copy: false, download: false, fullscreen: false } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={mentionComponents}>{highlightMentions(messageBody, agents)}</Streamdown>
- </div>
- )}
- {(() => {
- // Non-image file chips inside the bubble.
- // Prefer local pending pills (instant) to avoid flash on transition.
- const pfs = pendingFilesByMessage.get(msg.id);
- const nonImagePfs = pfs?.filter((pf) => !pf.thumbnailUrl);
- if (nonImagePfs && nonImagePfs.length > 0) {
- return (
- <div className="flex flex-wrap gap-2 mt-2">
- {nonImagePfs.map((pf, i) => (
- <span key={i} className="inline-flex items-center gap-1 rounded-md bg-primary-foreground/10 border border-primary-foreground/20 px-2 py-1 text-xs text-primary-foreground/80">
- <FileText className="size-3 shrink-0" />
- <span className="truncate max-w-37.5">{pf.file.name}</span>
- </span>
- ))}
- </div>
- );
- }
- const ids = msg.attachment_ids;
- if (ids && ids.length > 0) {
- const resolved = ids.map((id: string) => artifacts.find((a) => a.id === id)).filter((a): a is Artifact => !!a);
- const nonImageResolved = resolved.filter((a) => !a.content_type.startsWith("image/"));
- if (nonImageResolved.length > 0) return <AttachmentChips attachmentIds={nonImageResolved.map((a) => a.id)} artifacts={artifacts} onArtifactClick={onArtifactClick} />;
- }
- return null;
- })()}
- {toolbar}
- </MessageBubble>
- {(() => {
- // Image thumbnail cards below the bubble.
- // Prefer local blob thumbnails (instant, no network fetch) over
- // server thumbnails to avoid a flash when transitioning sources.
- const pfs = pendingFilesByMessage.get(msg.id);
- const imagePfs = pfs?.filter((pf) => pf.thumbnailUrl);
- if (imagePfs && imagePfs.length > 0) {
- return (
- <div className="flex flex-wrap gap-2 mt-2">
- {imagePfs.map((pf, i) => (
- <button
- key={i}
- type="button"
- onClick={(e) => { e.stopPropagation(); onPendingImageClick?.(pf.file); }}
- className="max-w-48 overflow-hidden rounded-(--radius) border border-(--border) cursor-pointer [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 [box-shadow:var(--e1)] hover:[box-shadow:var(--e2)]"
- >
- <img src={pf.thumbnailUrl!} alt={pf.file.name} className="block w-full h-auto" />
- </button>
- ))}
- </div>
- );
- }
- const ids = msg.attachment_ids;
- if (ids && ids.length > 0) {
- const resolved = ids.map((id: string) => artifacts.find((a) => a.id === id)).filter((a): a is Artifact => !!a);
- const imageResolved = resolved.filter((a) => a.content_type.startsWith("image/"));
- if (imageResolved.length > 0) return <ImageAttachmentCards attachmentIds={imageResolved.map((a) => a.id)} artifacts={artifacts} workspaceId={workspaceId} onArtifactClick={onArtifactClick} />;
- }
- return null;
- })()}
- {actionSheet}
- {isSendFailed && (
- <button
- type="button"
- onClick={() => onRetrySend?.(msg.id)}
- className="mt-1 px-1 text-xs text-destructive hover:underline"
- >
- Not delivered · tap to retry
- </button>
- )}
- {threadSummary && threadSummary.reply_count > 0 && (
- <button
- type="button"
- onClick={() => onReplyInThread?.(msg.id)}
- className="flex items-center gap-2 pt-1 cursor-pointer hover:opacity-75 transition-opacity"
- >
- <span className="text-[11px] font-semibold text-[oklch(0.72_0.19_145)]">
- {threadSummary.reply_count} {threadSummary.reply_count === 1 ? "reply" : "replies"}
- </span>
- {threadSummary.last_reply_at && (
- <span className="text-[10px] text-muted-foreground">
- last reply {new Date(threadSummary.last_reply_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
- </span>
- )}
- </button>
- )}
- </div>
- );
- })() : msg.role === "event" ? (() => {
- const eventEmailId = msg.metadata?.emailId as string | undefined;
- const eventIssueId = msg.metadata?.issueId as string | undefined;
- const eventCalendarEventId = msg.metadata?.calendarEventId as string | undefined;
- const onClick = eventEmailId
- ? () => onEmailClick(eventEmailId)
- : eventIssueId
- ? () => onIssueClick(eventIssueId)
- : eventCalendarEventId
- ? () => onCalendarEventClick(eventCalendarEventId)
- : undefined;
- const data = parseEventData(msg.metadata, msg.content, conversationType);
- let card: React.ReactNode;
- if (data.type === "email") {
- const handle = parseEmailHandle(data.address);
- const targetConvId = msg.metadata?.targetConversationId as string | undefined;
- const targetAgentId = msg.metadata?.targetAgentId as string | undefined;
- const isInternalEmail = !!handle;
- let touchAction: { label: string; onClick: () => void } | null = null;
- if (isInternalEmail && !hoverCapable && targetConvId && targetAgentId && onAgentChatOpen) {
- const agentName = agents.find(a => a.email_handle === handle)?.name;
- if (agentName) {
- touchAction = {
- label: `View ${agentName}'s conversation`,
- onClick: () => onAgentChatOpen(targetAgentId, targetConvId),
- };
- }
- }
- card = (
- <EmailCard
- subject={data.subject}
- address={data.address}
- direction={data.direction}
- onClick={onClick}
- timestamp={msg.created_at}
- {...(hoverCapable && isInternalEmail ? {
- isInternal: true,
- internalHandle: handle || undefined,
- targetConvId,
- targetAgentId,
- agents,
- onAgentChatOpen,
- } : {})}
- touchAction={touchAction}
- />
- );
- } else if (data.type === "calendar") {
- card = <CalendarCard title={data.title} scheduledAt={data.scheduledAt} repeatInterval={data.repeatInterval} onClick={onClick} />;
- } else {
- card = <IssueCard title={data.title} event={data.event} fromStatus={data.fromStatus} toStatus={data.toStatus} assigneeName={data.agentId ? agents.find(a => a.id === data.agentId)?.name : undefined} onClick={onClick} />;
- }
- return (
- <div data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
- <AgentRow groupPosition={groupPosition} agentName={agentName} seed={agentAvatarSeed} avatarUrl={agentAvatarUrl}>
- {card}
- </AgentRow>
- </div>
- );
- })() : isLifecycleNote && msg.metadata?.error_source !== "runtime" ? (
- // Lifecycle note (e.g. "Task cancelled by user") — a quiet centered
- // system line, not agent speech. No bubble, no avatar gutter.
- <div className="flex justify-center" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
- <span className="text-xs text-muted-foreground/70 text-center px-2 py-1">
- {msg.content}
- </span>
- </div>
- ) : shouldRenderAssistantBody({
- hasTaskStream,
- isRuntimeError: msg.metadata?.error_source === "runtime",
- }) ? (
- // The agent's own send-dm text bubble renders even when this message is
- // the one carrying the live error stream (hasTaskStream) — the error
- // block above is ADDITIVE, not a replacement, so the reply text is never
- // swallowed (QA AC4). A runtime-error message is the exception: it IS the
- // error, surfaced by the TaskStream above while live, so it still only
- // renders its own RuntimeErrorBlock when no stream owns it (!hasTaskStream).
- <div
- className={cn(
- "group/msg overflow-x-clip",
- // Non-bubble flagged case (runtime error) → row-tint, since the
- // rail/dot is bubble-only. The normal text bubble uses the rail+dot
- // instead, so it must NOT get the tint.
- isFlagged && msg.metadata?.error_source === "runtime" && "bg-muted/30 rounded-lg px-2 -mx-2",
- )}
- data-message-id={msg.id}
- data-quote-source
- {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}
- >
- <AgentRow groupPosition={groupPosition} agentName={agentName} seed={agentAvatarSeed} avatarUrl={agentAvatarUrl}>
- {msg.metadata?.error_source === "runtime" ? (
- // A failure is a real message, not a bubble — surface it plainly
- // with Retry. The action toolbar pins to the OPEN-side (left) top
- // corner; no on-block flag rail/dot (that's bubble-only) — a
- // flagged error uses the row-tint instead (see wrapper below).
- <div
- className="relative min-w-0 w-fit max-w-full"
- {...bubblePressHandlers}
- >
- <RuntimeErrorBlock
- provider={(msg.metadata.provider as string | null | undefined) ?? provider}
- message={msg.content}
- />
- {toolbar}
- {actionSheet}
- </div>
- ) : (
- <div
- className="relative min-w-0 w-fit max-w-full"
- {...bubblePressHandlers}
- >
- <MessageBubble
- variant="agent"
- position={toBubblePosition(groupPosition)}
- className={cn(
- "markdown min-w-0 max-w-full",
- (isFlagged || isThreadRoot) && "shadow-[inset_2px_0_0_var(--foreground)]",
- )}
- >
- <Streamdown plugins={{ mermaid, cjk, math }} controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={mentionComponents}>{highlightMentions(msg.content, agents)}</Streamdown>
- </MessageBubble>
- {isFlagged && !isThreadRoot && <FlagDot />}
- {isThreadRoot && <ThreadRootDot />}
- {toolbar}
- {actionSheet}
- </div>
- )}
- {threadSummary && threadSummary.reply_count > 0 && (
- <button
- type="button"
- onClick={() => onReplyInThread?.(msg.id)}
- className="flex items-center gap-2 pt-1 cursor-pointer hover:opacity-75 transition-opacity"
- >
- <span className="text-[11px] font-semibold text-[oklch(0.72_0.19_145)]">
- {threadSummary.reply_count} {threadSummary.reply_count === 1 ? "reply" : "replies"}
- </span>
- {threadSummary.last_reply_at && (
- <span className="text-[10px] text-muted-foreground">
- last reply {new Date(threadSummary.last_reply_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
- </span>
- )}
- </button>
- )}
- </AgentRow>
- </div>
- ) : null}
- </React.Fragment>
- );
-});
diff --git a/src/web/src/components/agent-chat/runtime-error-block.tsx b/src/web/src/components/agent-chat/runtime-error-block.tsx
deleted file mode 100644
index 54f1eceee..000000000
--- a/src/web/src/components/agent-chat/runtime-error-block.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-
-import { AlertCircle, RotateCw, Loader2 } from "lucide-react";
-import { runtimeDisplayName } from "@/lib/runtime-display";
-
-/**
- * A visually distinct error block that attributes a runtime error to the agent
- * runtime CLI (Claude Code / Codex / OpenCode) on the user's machine, making it
- * clear the error did NOT originate from Alook. See issue #236.
- *
- * Shared by message-list (failed-task chat message) and task-stream (in-stream
- * + task-level errors) so the presentation is identical everywhere.
- */
-export function RuntimeErrorBlock({
- provider,
- message,
- onRetry,
- retrying: retryingProp,
-}: {
- provider?: string | null;
- message: string;
- onRetry?: () => void | Promise<void>;
- retrying?: boolean;
-}) {
- const [retryingLocal, setRetryingLocal] = useAtom(useCreateAtom(false));
- const retrying = retryingProp ?? retryingLocal;
-
- const handleRetry = async () => {
- if (!onRetry) return;
- setRetryingLocal(true);
- try {
- await onRetry();
- } finally {
- setRetryingLocal(false);
- }
- };
-
- return (
- <div className="rounded-md border border-destructive/30 bg-destructive/5 p-2 max-w-full overflow-hidden">
- <div className="flex items-center gap-2">
- <p className="flex items-center gap-2 text-sm font-semibold text-destructive min-w-0">
- <AlertCircle className="size-3.5 shrink-0" />
- <span>Error from {runtimeDisplayName(provider)}</span>
- </p>
- {onRetry && (
- <button
- type="button"
- onClick={handleRetry}
- disabled={retrying}
- className="ml-auto shrink-0 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer disabled:opacity-50 flex items-center gap-1"
- >
- {retrying ? <Loader2 className="size-3 animate-spin" /> : <RotateCw className="size-3" />}
- Retry
- </button>
- )}
- </div>
- <p className="mt-2 text-sm text-destructive/90 wrap-anywhere whitespace-pre-wrap">{message}</p>
- <p className="mt-2 text-xs text-muted-foreground">
- This came from the agent runtime on your machine, not from Alook.
- </p>
- </div>
- );
-}
diff --git a/src/web/src/components/agent-chat/slash-command-popup.tsx b/src/web/src/components/agent-chat/slash-command-popup.tsx
deleted file mode 100644
index 030616c2c..000000000
--- a/src/web/src/components/agent-chat/slash-command-popup.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import React, { useRef, useEffect } from "react"
-import { createPortal } from "react-dom"
-import type { SkillEntry } from "@alook/shared"
-import { cn } from "@/lib/utils"
-import {
- anchoredPopoverStyle,
- useAnchoredPopover,
- type AnchorRectResolver,
-} from "@/hooks/use-anchored-popover"
-
-interface SlashCommandPopupProps {
- isOpen: boolean
- skills: SkillEntry[]
- selectedIndex: number
- onSelect: (skill: SkillEntry) => void
- getAnchorRect: AnchorRectResolver
-}
-
-function SkillRow({
- skill,
- isSelected,
- onSelect,
-}: {
- skill: SkillEntry
- isSelected: boolean
- onSelect: (skill: SkillEntry) => void
-}) {
- return (
- <button
- type="button"
- data-slash-item
- className={cn(
- "flex w-full flex-col gap-1 px-3 py-2 text-left text-sm transition-colors",
- isSelected ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",
- )}
- onMouseDown={(e) => {
- e.preventDefault()
- onSelect(skill)
- }}
- >
- <span className="flex w-full items-center gap-2">
- <span className="min-w-0 flex-1 truncate font-medium">/{skill.name}</span>
- {skill.isGlobal && (
- <span className="shrink-0 rounded px-1 py-1 text-[10px] font-medium bg-muted text-muted-foreground">
- Global
- </span>
- )}
- </span>
- {skill.description && (
- <span className="truncate text-xs text-muted-foreground">
- {skill.description.slice(0, 80)}
- </span>
- )}
- </button>
- )
-}
-
-export function SlashCommandPopup({ isOpen, skills, selectedIndex, onSelect, getAnchorRect }: SlashCommandPopupProps) {
- const listRef = useRef<HTMLDivElement>(null)
- const geometry = useAnchoredPopover(getAnchorRect, isOpen && skills.length > 0)
-
- useEffect(() => {
- if (!listRef.current) return
- const items = listRef.current.querySelectorAll("[data-slash-item]")
- const selected = items[selectedIndex] as HTMLElement | undefined
- selected?.scrollIntoView({ block: "nearest" })
- }, [selectedIndex])
-
- if (!isOpen || skills.length === 0 || !geometry) return null
-
- return createPortal(
- <div
- className="fixed z-100 w-70 rounded-lg border border-border bg-popover text-popover-foreground shadow-md transition-opacity duration-150"
- style={anchoredPopoverStyle(geometry.rect, geometry.viewport, 280, 240)}
- >
- <div
- ref={listRef}
- className="overflow-y-auto py-1 thin-scrollbar"
- style={{ maxHeight: "var(--anchored-popover-max-height)" }}
- >
- {skills.map((skill, i) => (
- <SkillRow
- key={skill.name}
- skill={skill}
- isSelected={i === selectedIndex}
- onSelect={onSelect}
- />
- ))}
- </div>
- </div>,
- document.body,
- )
-}
diff --git a/src/web/src/components/agent-chat/use-rotating-placeholder.test.ts b/src/web/src/components/agent-chat/use-rotating-placeholder.test.ts
deleted file mode 100644
index 0a4764594..000000000
--- a/src/web/src/components/agent-chat/use-rotating-placeholder.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- CHAT_PLACEHOLDER_HINTS,
- HINT_HOLD_MS,
- randomStartIndex,
- nextIndex,
- shouldRotate,
-} from "./use-rotating-placeholder";
-
-// The web suite runs node-env (no jsdom/RTL — see agent-chat-view.test.ts), so
-// the hook itself can't be rendered here. All testable logic was extracted into
-// the pure helpers below, which is where every behavioral assertion lives.
-// Component-render / layout / aria checks are QA'd in a real browser.
-
-describe("CHAT_PLACEHOLDER_HINTS", () => {
- it("contains the 5 LOCKED copy strings in order", () => {
- expect([...CHAT_PLACEHOLDER_HINTS]).toEqual([
- "Email the team this week's launch update",
- "Recruit a QA agent to review my PRs",
- "Remind me to follow up with Acme on Thursday",
- "What did we ship last week?",
- "Fix the failing test in the checkout flow",
- ]);
- });
-
- it("keeps every hint ≤ 45 chars (guards mobile truncation)", () => {
- for (const hint of CHAT_PLACEHOLDER_HINTS) {
- expect(hint.length, hint).toBeLessThanOrEqual(45);
- }
- });
-
- it("holds each hint ~6s", () => {
- expect(HINT_HOLD_MS).toBe(6000);
- });
-});
-
-describe("randomStartIndex", () => {
- it("returns an index within [0, len)", () => {
- const len = CHAT_PLACEHOLDER_HINTS.length;
- // sweep rand across [0,1) and assert every result is a valid index
- for (let r = 0; r < 1; r += 0.01) {
- const i = randomStartIndex(len, () => r);
- expect(i).toBeGreaterThanOrEqual(0);
- expect(i).toBeLessThan(len);
- }
- });
-
- it("maps rand=0 to the first and rand→1 to the last", () => {
- const len = 5;
- expect(randomStartIndex(len, () => 0)).toBe(0);
- expect(randomStartIndex(len, () => 0.999999)).toBe(len - 1);
- });
-
- it("returns 0 for an empty list (defensive)", () => {
- expect(randomStartIndex(0, () => 0.5)).toBe(0);
- });
-});
-
-describe("nextIndex", () => {
- it("advances sequentially", () => {
- expect(nextIndex(0, 5)).toBe(1);
- expect(nextIndex(1, 5)).toBe(2);
- expect(nextIndex(3, 5)).toBe(4);
- });
-
- it("wraps to 0 after the last", () => {
- expect(nextIndex(4, 5)).toBe(0);
- });
-
- it("cycles the full sequence back to start", () => {
- const len = CHAT_PLACEHOLDER_HINTS.length;
- let i = 2;
- const seen: number[] = [i];
- for (let n = 0; n < len; n++) {
- i = nextIndex(i, len);
- seen.push(i);
- }
- // after len steps we're back where we started
- expect(seen[seen.length - 1]).toBe(2);
- // and we visited every index exactly once along the way
- expect(new Set(seen.slice(0, len)).size).toBe(len);
- });
-
- it("returns 0 for an empty list (defensive)", () => {
- expect(nextIndex(0, 0)).toBe(0);
- });
-});
-
-describe("shouldRotate", () => {
- const base = {
- isEmpty: true,
- isFocused: false,
- isTaskActive: false,
- reducedMotion: false,
- };
-
- it("rotates only when empty, unfocused, idle, and motion allowed", () => {
- expect(shouldRotate(base)).toBe(true);
- });
-
- it("freezes when focused", () => {
- expect(shouldRotate({ ...base, isFocused: true })).toBe(false);
- });
-
- it("freezes when the field is non-empty (typing)", () => {
- expect(shouldRotate({ ...base, isEmpty: false })).toBe(false);
- });
-
- it("freezes when a task is active", () => {
- expect(shouldRotate({ ...base, isTaskActive: true })).toBe(false);
- });
-
- it("does not rotate under reduced motion", () => {
- expect(shouldRotate({ ...base, reducedMotion: true })).toBe(false);
- });
-
- it("blur with an empty field re-enables rotation", () => {
- // focused → frozen, then blur (isFocused:false) with empty field → rotates
- expect(shouldRotate({ ...base, isFocused: true })).toBe(false);
- expect(shouldRotate({ ...base, isFocused: false })).toBe(true);
- });
-});
diff --git a/src/web/src/components/agent-chat/use-rotating-placeholder.ts b/src/web/src/components/agent-chat/use-rotating-placeholder.ts
deleted file mode 100644
index f26cb7d9b..000000000
--- a/src/web/src/components/agent-chat/use-rotating-placeholder.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useMemo } from "react";
-
-import { useEffect, useRef } from "react";
-
-/**
- * Rotating capability hints for the main chat composer's empty-state
- * placeholder. Each maps to a REAL Alook capability — the placeholder teaches
- * by example. Copy LOCKED by Gus 2026-06-01 (natural-imperative voice).
- *
- * This is the ONE place to edit the copy. Keep every entry ≤ ~45 chars so the
- * overlay never wraps / truncates at the smallest mobile width.
- */
-export const CHAT_PLACEHOLDER_HINTS = [
- "Email the team this week's launch update",
- "Recruit a QA agent to review my PRs",
- "Remind me to follow up with Acme on Thursday",
- "What did we ship last week?",
- "Fix the failing test in the checkout flow",
-] as const;
-
-/** Hold each hint ~6s before cross-fading to the next. */
-export const HINT_HOLD_MS = 6000;
-
-const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
-
-/**
- * Random start index in [0, len). Kept pure + exported so the "random start"
- * behavior is unit-testable without rendering the hook (web suite is node-env,
- * no jsdom/RTL). Pass a custom `rand` (defaulting to Math.random) in tests.
- */
-export function randomStartIndex(
- len: number,
- rand: () => number = Math.random,
-): number {
- if (len <= 0) return 0;
- return Math.floor(rand() * len) % len;
-}
-
-/** Next index in a sequential cycle, wrapping to 0 after the last. */
-export function nextIndex(current: number, len: number): number {
- if (len <= 0) return 0;
- return (current + 1) % len;
-}
-
-/**
- * The placeholder rotates ONLY when the field is empty, unfocused, not in a
- * task-in-progress state, and reduced-motion is not requested. Pure predicate,
- * exported for direct unit testing.
- */
-export function shouldRotate(state: {
- isEmpty: boolean;
- isFocused: boolean;
- isTaskActive: boolean;
- reducedMotion: boolean;
-}): boolean {
- return (
- state.isEmpty &&
- !state.isFocused &&
- !state.isTaskActive &&
- !state.reducedMotion
- );
-}
-
-/**
- * Reads + subscribes to `prefers-reduced-motion`. Inlines the same matchMedia
- * convention used elsewhere in the codebase (home/feature-showcase.tsx) rather
- * than adding a shared hook. SSR-safe (defaults to false when no window).
- */
-function usePrefersReducedMotion(): boolean {
- const [reduced, setReduced] = useAtom(useCreateAtom(false));
-
- useEffect(() => {
- if (typeof window === "undefined" || !window.matchMedia) return;
- const mq = window.matchMedia(REDUCED_MOTION_QUERY);
- setReduced(mq.matches);
- const onChange = (e: MediaQueryListEvent) => setReduced(e.matches);
- mq.addEventListener("change", onChange);
- return () => mq.removeEventListener("change", onChange);
- }, [setReduced]);
-
- return reduced;
-}
-
-export interface RotatingPlaceholderState {
- isEmpty: boolean;
- isFocused: boolean;
- isTaskActive: boolean;
-}
-
-export interface RotatingPlaceholder {
- /** The hint to show right now. */
- hint: string;
- /** True while the placeholder should actively cross-fade between hints. */
- isRotating: boolean;
-}
-
-/**
- * Owns the rotating-placeholder state: a random start index, a sequential
- * ~3.5s cycle, freeze-on-focus/typing, resume-on-empty-blur, and the
- * reduced-motion short-circuit (one static hint, never advances).
- *
- * NO TipTap / DOM dependency beyond matchMedia — the overlay rendering and
- * cross-fade live in chat-composer.tsx.
- */
-export function useRotatingPlaceholder(
- state: RotatingPlaceholderState,
-): RotatingPlaceholder {
- const reducedMotion = usePrefersReducedMotion();
- const [index, setIndex] = useAtom(useCreateAtom(useMemo(() =>
- randomStartIndex(CHAT_PLACEHOLDER_HINTS.length), [])));
-
- const rotating = shouldRotate({ ...state, reducedMotion });
-
- // Advance on a fixed interval only while rotating. Re-arming on `rotating`
- // change means focus/typing freezes immediately and empty-blur resumes.
- // The latest index is read from a ref so the effect doesn't re-run (and
- // reset the timer) on every advance.
- const indexRef = useRef(index);
- indexRef.current = index; // eslint-disable-line react-hooks/refs -- sync ref to avoid stale closure in interval
-
- useEffect(() => {
- if (!rotating) return;
- const id = setInterval(() => {
- setIndex(nextIndex(indexRef.current, CHAT_PLACEHOLDER_HINTS.length));
- }, HINT_HOLD_MS);
- return () => clearInterval(id);
- }, [rotating, setIndex]);
-
- return {
- hint: CHAT_PLACEHOLDER_HINTS[index] ?? CHAT_PLACEHOLDER_HINTS[0],
- isRotating: rotating,
- };
-}
diff --git a/src/web/src/components/agent-create-form-validation.test.ts b/src/web/src/components/agent-create-form-validation.test.ts
deleted file mode 100644
index 2ccfcd278..000000000
--- a/src/web/src/components/agent-create-form-validation.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- hasAgentCreateFieldErrors,
- validateAgentCreateRequiredFields,
-} from "./agent-create-form-validation";
-
-describe("validateAgentCreateRequiredFields", () => {
- it("requires a non-empty name", () => {
- const errors = validateAgentCreateRequiredFields({
- name: " ",
- runtimeId: "rt_1",
- });
-
- expect(errors).toEqual({ name: "Name is required" });
- expect(hasAgentCreateFieldErrors(errors)).toBe(true);
- });
-
- it("requires a runtime", () => {
- const errors = validateAgentCreateRequiredFields({
- name: "Maddox",
- runtimeId: "",
- });
-
- expect(errors).toEqual({ runtimeId: "Select an online runtime" });
- expect(hasAgentCreateFieldErrors(errors)).toBe(true);
- });
-
- it("passes when required fields are present", () => {
- const errors = validateAgentCreateRequiredFields({
- name: "Maddox",
- runtimeId: "rt_1",
- });
-
- expect(errors).toEqual({});
- expect(hasAgentCreateFieldErrors(errors)).toBe(false);
- });
-});
diff --git a/src/web/src/components/agent-create-form-validation.ts b/src/web/src/components/agent-create-form-validation.ts
deleted file mode 100644
index 45adcc955..000000000
--- a/src/web/src/components/agent-create-form-validation.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-export interface AgentCreateRequiredFields {
- name: string;
- runtimeId: string;
-}
-
-export interface AgentCreateFieldErrors {
- name?: string;
- runtimeId?: string;
-}
-
-export function validateAgentCreateRequiredFields({
- name,
- runtimeId,
-}: AgentCreateRequiredFields): AgentCreateFieldErrors {
- const errors: AgentCreateFieldErrors = {};
-
- if (!name.trim()) {
- errors.name = "Name is required";
- }
-
- if (!runtimeId) {
- errors.runtimeId = "Select an online runtime";
- }
-
- return errors;
-}
-
-export function hasAgentCreateFieldErrors(
- errors: AgentCreateFieldErrors,
-): boolean {
- return Boolean(errors.name || errors.runtimeId);
-}
diff --git a/src/web/src/components/agent-create-form.tsx b/src/web/src/components/agent-create-form.tsx
deleted file mode 100644
index f293ec348..000000000
--- a/src/web/src/components/agent-create-form.tsx
+++ /dev/null
@@ -1,266 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useRef, useEffect, useCallback } from "react";
-import { Button } from "@/components/ui/button";
-import type { AgentRuntime as Runtime } from "@alook/shared";
-import {
- GeneralFields,
- EmailHandleField,
- nameToHandle,
- getHandleError,
-} from "@/components/agent-form-fields";
-import {
- CustomEmailForm,
- type CustomEmailData,
-} from "@/components/custom-email-form";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { AvatarPickerDialog } from "@/components/avatar";
-import { serializeBeamSeed } from "@/lib/avatar/seed-url";
-import { uniqueNamesGenerator, names } from "unique-names-generator";
-import {
- type AgentCreateFieldErrors,
- hasAgentCreateFieldErrors,
- validateAgentCreateRequiredFields,
-} from "@/components/agent-create-form-validation";
-
-interface AgentCreateFormProps {
- runtimes: Runtime[];
- defaultRuntimeId?: string;
- modelOptions?: Record<string, string[]>;
- guided?: boolean;
- onTourReady?: (startTour: () => void) => void;
- onSave: (data: {
- name: string;
- description: string;
- instructions: string;
- runtime_id: string;
- email_handle?: string;
- runtime_config?: Record<string, unknown>;
- custom_email?: CustomEmailData;
- avatar_url?: string | null;
- }) => Promise<boolean>;
- onCancel: () => void;
- saving: boolean;
-}
-
-// Stable initial seed to avoid hydration mismatch (real seed is rerolled on mount)
-const INITIAL_AVATAR = serializeBeamSeed("initial");
-
-async function runTour() {
- const waitForElement = (selector: string, timeout = 3000) =>
- new Promise<Element | null>((resolve) => {
- const el = document.querySelector(selector);
- if (el) { resolve(el); return; }
- const ob = new MutationObserver(() => {
- const found = document.querySelector(selector);
- if (found) { ob.disconnect(); resolve(found); }
- });
- ob.observe(document.body, { childList: true, subtree: true });
- setTimeout(() => { ob.disconnect(); resolve(null); }, timeout);
- });
-
- const el = await waitForElement("#agent-name");
- if (!el) return;
-
- // Wait for layout to stabilize after navigation
- await new Promise<void>((resolve) => {
- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
- });
-
- // Verify element has dimensions (painted)
- if (!el.getBoundingClientRect().height) return;
-
- const { driver } = await import("driver.js");
- await import("driver.js/dist/driver.css");
-
- const d = driver({
- showProgress: true,
- animate: true,
- allowClose: true,
- overlayClickBehavior: () => {},
- overlayColor: "black",
- overlayOpacity: 0.4,
- popoverClass: "agent-tour-popover",
- steps: [
- {
- element: "#agent-name",
- popover: {
- title: "Name your agent",
- description: "Give your agent a name — this is how you'll identify it.",
- side: "bottom" as const,
- align: "start" as const,
- },
- },
- {
- element: "#agent-runtime-select",
- disableActiveInteraction: false,
- popover: {
- title: "Choose a runtime",
- description: "Select which machine and provider will run this agent.",
- side: "bottom" as const,
- align: "start" as const,
- },
- },
- ],
- });
- d.drive();
-}
-
-export function AgentCreateForm({
- runtimes,
- defaultRuntimeId = "",
- modelOptions,
- guided = false,
- onTourReady,
- onSave,
- onCancel,
- saving,
-}: AgentCreateFormProps) {
- const { workspaceId } = useWorkspace();
- const [name, setName] = useAtom(useCreateAtom(""));
- const [description, setDescription] = useAtom(useCreateAtom(""));
- const [instructions, setInstructions] = useAtom(useCreateAtom(""));
- const [runtimeId, setRuntimeId] = useAtom(useCreateAtom(defaultRuntimeId));
- const [emailHandle, setEmailHandle] = useAtom(useCreateAtom(""));
- const [fieldErrors, setFieldErrors] = useAtom(useCreateAtom<AgentCreateFieldErrors>({}));
- const [customEmailData, setCustomEmailData] =
- useAtom(useCreateAtom<CustomEmailData | null>(null));
- const customEmailGetDataRef = useRef<(() => CustomEmailData | null) | null>(
- null
- );
- const [model, setModel] = useAtom(useCreateAtom(""));
- const [avatarUrl, setAvatarUrl] = useAtom(useCreateAtom<string>(INITIAL_AVATAR));
-
- // Randomize avatar and name on client mount to avoid hydration mismatch
- const avatarInitialized = useRef(false);
- useEffect(() => {
- if (!avatarInitialized.current) {
- avatarInitialized.current = true;
- setAvatarUrl(serializeBeamSeed(crypto.randomUUID()));
- setName(uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" }));
- }
- }, [setAvatarUrl, setName]);
-
- const shuffleName = useCallback(() => {
- setName(uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" }));
- setFieldErrors((prev) => ({ ...prev, name: undefined }));
- }, [setFieldErrors, setName]);
-
- const selectedRuntime = runtimes.find((r) => r.id === runtimeId);
- const providerModels =
- selectedRuntime && modelOptions
- ? (modelOptions[selectedRuntime.provider] ?? [])
- : [];
-
- const derivedHandle = nameToHandle(name);
- const effectiveHandle = emailHandle || derivedHandle;
- const handleError = getHandleError(effectiveHandle);
-
- // Driver.js guided tour for first-time agent creation
- const driverStarted = useRef(false);
- useEffect(() => {
- onTourReady?.(() => runTour());
- }, [onTourReady]);
- useEffect(() => {
- if (!guided || driverStarted.current) return;
- driverStarted.current = true;
- runTour();
- }, [guided]);
-
- const updateName = (value: string) => {
- setName(value);
- if (fieldErrors.name && value.trim()) {
- setFieldErrors((prev) => ({ ...prev, name: undefined }));
- }
- };
-
- const updateRuntimeId = (value: string) => {
- const oldProvider = runtimes.find((r) => r.id === runtimeId)?.provider;
- const newProvider = runtimes.find((r) => r.id === value)?.provider;
- setRuntimeId(value);
- if (oldProvider && oldProvider !== newProvider) {
- setModel("");
- }
- if (fieldErrors.runtimeId && value) {
- setFieldErrors((prev) => ({ ...prev, runtimeId: undefined }));
- }
- };
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- const nextErrors = validateAgentCreateRequiredFields({ name, runtimeId });
- setFieldErrors(nextErrors);
-
- if (hasAgentCreateFieldErrors(nextErrors)) {
- return;
- }
-
- await onSave({
- name: name.trim(),
- description,
- instructions,
- runtime_id: runtimeId,
- email_handle: emailHandle || derivedHandle || undefined,
- runtime_config: model ? { model } : {},
- custom_email:
- customEmailGetDataRef.current?.() ?? customEmailData ?? undefined,
- avatar_url: avatarUrl,
- });
- };
-
- return (
- <div className="flex-1 min-h-0 overflow-y-auto thin-scrollbar">
- <form onSubmit={handleSubmit} noValidate className="mx-auto max-w-md flex flex-col gap-4 px-8 pt-8 pb-6">
- <AvatarPickerDialog
- value={avatarUrl}
- onChange={setAvatarUrl}
- />
- <GeneralFields
- name={name}
- setName={updateName}
- description={description}
- setDescription={setDescription}
- instructions={instructions}
- setInstructions={setInstructions}
- model={model}
- setModel={setModel}
- runtimeId={runtimeId}
- setRuntimeId={updateRuntimeId}
- runtimes={runtimes}
- providerModels={providerModels}
- errors={fieldErrors}
- runtimeAsRadio
- onShuffle={shuffleName}
- emailHandleSlot={
- <EmailHandleField
- emailHandle={emailHandle}
- setEmailHandle={setEmailHandle}
- derivedHandle={derivedHandle}
- />
- }
- advancedSection={
- <CustomEmailForm
- workspaceId={workspaceId}
- onDataChange={setCustomEmailData}
- getDataRef={customEmailGetDataRef}
- />
- }
- />
-
- <div className="flex items-center gap-2 pt-2">
- <Button type="button" variant="ghost" size="sm" onClick={onCancel}>
- Cancel
- </Button>
- <Button
- type="submit"
- size="sm"
- disabled={saving || !!handleError}
- >
- {saving ? "Creating..." : "Create"}
- </Button>
- </div>
- </form>
- </div>
- );
-}
diff --git a/src/web/src/components/agent-edit-form.tsx b/src/web/src/components/agent-edit-form.tsx
deleted file mode 100644
index 44175135b..000000000
--- a/src/web/src/components/agent-edit-form.tsx
+++ /dev/null
@@ -1,431 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useRef, useMemo, useLayoutEffect } from "react";
-import { useAtom, useCreateAtom, createStore, useSelector } from "@tanstack/react-store";
-import { useMutation, useQuery, type Query } from "@tanstack/react-query";
-import { Button } from "@/components/ui/button";
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import type { Agent } from "@alook/shared";
-import type { AgentRuntime as Runtime } from "@alook/shared";
-import { toAlookAddress } from "@alook/shared";
-import { cn } from "@/lib/utils";
-import { LockIcon } from "lucide-react";
-import { CustomEmailForm } from "@/components/custom-email-form";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { MarkdownEditor } from "@/components/ui/markdown-editor";
-import { RuntimeSelect } from "@/components/runtime-select";
-import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { isAbortError } from "@/lib/errors";
-import { useAgentContext } from "@/contexts/agent-context";
-import { getAgent as getAgentApi, updateAgent as updateAgentApi } from "@/lib/api";
-import { toast } from "sonner";
-import {
- GeneralFields,
- AllowedSendersTab,
- AgentAccessTab,
-} from "@/components/agent-form-fields";
-import { AvatarPickerDialog } from "@/components/avatar";
-import { serializeBeamSeed, parseBeamSeed } from "@/lib/avatar/seed-url";
-
-const MAX_INSTRUCTION_LENGTH = 50_000;
-const DEBOUNCE_MS = 500;
-
-function UsageRing({ ratio, size = 16, stroke = 1.5 }: { ratio: number; size?: number; stroke?: number }) {
- const r = (size - stroke) / 2;
- const circ = 2 * Math.PI * r;
- const visual = ratio <= 0 ? 0 : ratio >= 1 ? 1 : Math.log1p(ratio * 99) / Math.log(100);
- const filled = visual * circ;
- return (
- <svg width={size} height={size} className="shrink-0 -rotate-90" aria-hidden>
- <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="currentColor" strokeWidth={stroke} className="text-border" />
- <circle
- cx={size / 2}
- cy={size / 2}
- r={r}
- fill="none"
- stroke="currentColor"
- strokeWidth={stroke}
- strokeDasharray={`${filled} ${circ - filled}`}
- strokeLinecap="round"
- className={cn(
- "transition-all duration-300",
- ratio > 0.9 ? "text-destructive/70" : ratio > 0.7 ? "text-yellow-500/50" : "text-muted-foreground/30"
- )}
- />
- </svg>
- );
-}
-
-function RuntimeTab({
- model,
- setModel,
- runtimeId,
- setRuntimeId,
- runtimes,
- providerModels,
-}: {
- model: string;
- setModel: (v: string) => void;
- runtimeId: string;
- setRuntimeId: (v: string) => void;
- runtimes: Runtime[];
- providerModels: string[];
-}) {
- return (
- <>
- <div className="space-y-2">
- <Label className="text-xs text-muted-foreground">Runtime</Label>
- <RuntimeSelect
- value={runtimeId}
- onValueChange={(newId) => {
- const oldProvider = runtimes.find((r) => r.id === runtimeId)?.provider;
- const newProvider = runtimes.find((r) => r.id === newId)?.provider;
- setRuntimeId(newId);
- if (oldProvider && oldProvider !== newProvider) {
- setModel("");
- }
- }}
- runtimes={runtimes}
- />
- </div>
-
- <div className="space-y-2">
- <Label className="text-xs text-muted-foreground">Model</Label>
- <Input
- value={model}
- onChange={(e) => setModel(e.target.value)}
- placeholder="Default (runtime model)"
- list="agent-model-options-edit"
- />
- {providerModels.length > 0 && (
- <datalist id="agent-model-options-edit">
- {providerModels.map((m) => (
- <option key={m} value={m} />
- ))}
- </datalist>
- )}
- <p className="text-xs text-muted-foreground/70">
- Optional. Leave blank to use the runtime&apos;s default model.
- </p>
- </div>
- </>
- );
-}
-
-interface AgentEditFormProps {
- agent: Agent;
- runtimes: Runtime[];
- modelOptions?: Record<string, string[]>;
- onSave: (data: {
- name: string;
- description: string;
- runtime_id: string;
- runtime_config?: Record<string, unknown>;
- avatar_url?: string | null;
- }) => Promise<boolean>;
- onCancel: () => void;
- saving: boolean;
-}
-
-type TabId = "general" | "instruction" | "runtime" | "email" | "permission";
-
-export function AgentEditForm({
- agent,
- runtimes,
- modelOptions,
- onSave,
- onCancel,
- saving,
-}: AgentEditFormProps) {
- const owner = useWorkspaceOwner();
- const { workspaceId } = owner;
- const { agents } = useAgentContext();
- const canonicalAgent = agents.find((row) => row.id === agent.id);
- const source = useWorkspaceViewSource(owner, `agent-edit:${agent.id}`, true);
- const [activeTab, setActiveTab] = useAtom(useCreateAtom<TabId>("general"));
- const [name, setName] = useAtom(useCreateAtom(agent.name ?? ""));
- const [description, setDescription] = useAtom(useCreateAtom(agent.description ?? ""));
- const [runtimeId, setRuntimeId] = useAtom(useCreateAtom(agent.runtime_id ?? ""));
- const [avatarUrl, setAvatarUrl] = useAtom(useCreateAtom<string>(
- parseBeamSeed(agent.avatar_url) ? agent.avatar_url! : serializeBeamSeed(agent.id),
- ));
- const [model, setModel] = useAtom(useCreateAtom(typeof agent.runtime_config?.model === "string" ? agent.runtime_config.model : ""));
-
- type InstructionIntent = { value: string; token: ReturnType<typeof captureWorkspaceOwner>; assertView: () => void; signal: AbortSignal; resource: Query | undefined };
- const draft = useMemo(() => {
- const key = JSON.stringify(owner.key("agent-instruction-draft", agent.id));
- const create = () => createStore<{ value: string | null; pending: InstructionIntent | null }>({ value: null, pending: null });
- const saved = owner.application.preferences.get().localValues.get(key) as ReturnType<typeof create> | undefined;
- if (saved) return saved;
- const store = create();
- owner.application.preferences.setState((state) => ({ ...state, localValues: new Map(state.localValues).set(key, store) }));
- return store;
- }, [owner, agent.id]);
- const instructionDraft = useSelector(draft, (state) => state.value);
- const pendingInstruction = useSelector(draft, (state) => state.pending);
- const instructions = instructionDraft ?? canonicalAgent?.instructions ?? "";
- const agentsKey = owner.key("agents");
- useQuery({ queryKey: owner.key("agent-refresh", agent.id),
- queryFn: async ({ signal }) => {
- const token = captureWorkspaceOwner(owner);
- assertWorkspaceOwner(token, signal);
- const original = owner.queryClient.getQueryCache().find({ queryKey: agentsKey, exact: true });
- const baseline = owner.queryClient.getQueryData<Agent[]>(agentsKey)?.find((row) => row.id === agent.id);
- const writes = original?.state.dataUpdateCount;
- const fresh = await getAgentApi(agent.id, workspaceId, workspaceRequestOptions(token, signal));
- assertWorkspaceOwner(token, signal);
- if (owner.queryClient.getQueryCache().find({ queryKey: agentsKey, exact: true }) === original && original?.state.dataUpdateCount === writes) {
- owner.queryClient.setQueryData<Agent[]>(agentsKey, (rows) => rows?.map((row) => {
- if (row.id !== fresh.id) return row;
- const fields = Object.fromEntries(Object.entries(fresh).filter(([key]) => row[key as keyof Agent] === baseline?.[key as keyof Agent]));
- return { ...row, ...fields };
- }));
- }
- return { id: fresh.id };
- },
- });
- const instructionMutation = useMutation({ meta: { observabilityAction: "agent.instruction.save" },
- mutationKey: owner.key("agent-instruction-command", agent.id),
- scope: { id: JSON.stringify(owner.key("agent-instruction-command", agent.id)) }, gcTime: 0,
- mutationFn: async ({ value, token, assertView, signal, resource: original }: InstructionIntent) => {
- const assert = () => { assertWorkspaceOwner(token, signal); assertView(); };
- assert();
- if (original && owner.queryClient.getQueryCache().find({ queryKey: agentsKey, exact: true }) === original) await owner.queryClient.cancelQueries({ queryKey: agentsKey, exact: true });
- assert();
- const before = owner.queryClient.getQueryData<Agent[]>(agentsKey)?.find((row) => row.id === agent.id)?.instructions;
- const writes = original?.state.dataUpdateCount;
- try {
- const confirmed = await updateAgentApi(agent.id, { instructions: value }, workspaceId, { ...workspaceRequestOptions(token, signal, assert), keepalive: true });
- assert();
- if (original && owner.queryClient.getQueryCache().find({ queryKey: agentsKey, exact: true }) === original && original.state.dataUpdateCount === writes) {
- owner.queryClient.setQueryData<Agent[]>(agentsKey, (rows) => rows?.map((row) => row.id === agent.id && row.instructions === before ? { ...row, instructions: confirmed.instructions } : row));
- }
- } catch (error) { assert(); throw error; }
- },
- onSuccess: (_data, intent) => {
- try { intent.assertView(); } catch { return; }
- const confirmed = owner.queryClient.getQueryData<Agent[]>(agentsKey)?.find((row) => row.id === agent.id)?.instructions;
- draft.setState((state) => state.value === intent.value && confirmed === intent.value ? { ...state, value: null } : state);
- },
- onError: (error, intent) => {
- try { intent.assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to save instructions");
- },
- });
- const flush = useCallback(() => {
- const intent = draft.get().pending;
- if (!intent) return;
- try { intent.assertView(); assertWorkspaceOwner(intent.token, intent.signal); } catch { return; }
- draft.setState((state) => state.pending === intent ? { ...state, pending: null } : state);
- instructionMutation.mutate(intent);
- }, [draft, instructionMutation]);
- const flushRef = useRef(flush);
- useEffect(() => { flushRef.current = flush; }, [flush]);
- useEffect(() => {
- if (!pendingInstruction) return;
- const timer = setTimeout(() => flushRef.current(), DEBOUNCE_MS);
- return () => clearTimeout(timer);
- }, [pendingInstruction]);
- const handleInstructionChange = (value: string) => {
- source.assertActive();
- draft.setState((state) => ({ value, pending: {
- value, token: state.pending?.token ?? captureWorkspaceOwner(owner), assertView: state.pending?.assertView ?? source.assertActive, signal: state.pending?.signal ?? source.signal, resource: state.pending?.resource ?? owner.queryClient.getQueryCache().find({ queryKey: agentsKey, exact: true }),
- } }));
- };
- useEffect(() => {
- const onBeforeUnload = () => flushRef.current();
- window.addEventListener("beforeunload", onBeforeUnload);
- return () => {
- window.removeEventListener("beforeunload", onBeforeUnload);
- };
- }, [owner, agent.id]);
- useLayoutEffect(() => () => draft.setState((state) => ({ ...state, pending: null })), [draft]);
-
-
- const selectedRuntime = runtimes.find((r) => r.id === runtimeId);
- const providerModels =
- selectedRuntime && modelOptions
- ? (modelOptions[selectedRuntime.provider] ?? [])
- : [];
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- await onSave({
- name,
- description,
- runtime_id: runtimeId,
- runtime_config: model ? { model } : {},
- avatar_url: avatarUrl,
- });
- };
-
- const tabs: { id: TabId; label: string }[] = [
- { id: "general", label: "General" },
- { id: "instruction", label: "Instruction" },
- { id: "runtime", label: "Runtime" },
- { id: "email", label: "Email" },
- { id: "permission", label: "Permission" },
- ];
-
- const isFormTab = activeTab === "general" || activeTab === "runtime" || activeTab === "email";
- const instructionRatio = instructions.length / MAX_INSTRUCTION_LENGTH;
-
- return (
- <div className="flex flex-1 min-h-0">
- <nav className="w-48 shrink-0 border-r border-border/50 py-3 px-2 hidden sm:block">
- {tabs.map((tab) => (
- <button
- key={tab.id}
- type="button"
- onClick={() => setActiveTab(tab.id)}
- className={cn(
- "w-full rounded-md px-2 py-2 text-left text-sm transition-colors",
- activeTab === tab.id
- ? "bg-accent text-foreground font-medium"
- : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
- )}
- >
- {tab.label}
- </button>
- ))}
- </nav>
-
- <div className="flex-1 min-w-0 flex flex-col">
- <div className="px-4 pt-2 sm:hidden">
- <Tabs
- className="items-center"
- value={activeTab}
- onValueChange={(v) => setActiveTab(v as TabId)}
- >
- <TabsList className="h-auto gap-1">
- {tabs.map((tab) => (
- <TabsTrigger key={tab.id} value={tab.id}>
- {tab.label}
- </TabsTrigger>
- ))}
- </TabsList>
- </Tabs>
- </div>
-
- {activeTab === "instruction" ? (
- <div className="flex flex-col flex-1 min-h-0">
- <div className="flex-1 px-6 pt-4 pb-4 overflow-y-auto thin-scrollbar">
- <MarkdownEditor
- value={instructions}
- onChange={handleInstructionChange}
- placeholder="Write instructions for this agent..."
- minHeight="calc(100vh - 240px)"
- contentType="markdown"
- variant="seamless"
- />
- </div>
- <div className="flex items-center gap-2 px-6 py-3 border-t border-border/50">
- <UsageRing ratio={instructionRatio} />
- <p className="text-xs text-muted-foreground">
- Agent-specific instruction. Your global instruction is prepended automatically.
- </p>
- {instructionDraft !== null && (
- <Button type="button" size="sm" variant="outline" className="ml-auto shrink-0" disabled={instructionMutation.isPending} onClick={() => { handleInstructionChange(instructions); flushRef.current(); }}>
- {instructionMutation.isPending ? "Saving…" : "Save changes"}
- </Button>
- )}
- </div>
- </div>
- ) : (
- <div className="flex-1 overflow-y-auto thin-scrollbar px-4 py-6">
- {isFormTab ? (
- <form
- onSubmit={handleSubmit}
- className="mx-auto max-w-md space-y-4"
- >
- {activeTab === "general" && (
- <>
- <AvatarPickerDialog
- value={avatarUrl}
- onChange={setAvatarUrl}
- />
- <GeneralFields
- name={name}
- setName={setName}
- description={description}
- setDescription={setDescription}
- model={model}
- setModel={setModel}
- runtimeId={runtimeId}
- setRuntimeId={setRuntimeId}
- runtimes={[]}
- providerModels={[]}
- />
- </>
- )}
-
- {activeTab === "runtime" && (
- <RuntimeTab
- model={model}
- setModel={setModel}
- runtimeId={runtimeId}
- setRuntimeId={setRuntimeId}
- runtimes={runtimes}
- providerModels={providerModels}
- />
- )}
-
- {activeTab === "email" && (
- <>
- <div className="rounded-lg border border-border/50 bg-muted/30 px-4 py-3">
- <div className="mb-2 flex items-center gap-2">
- <LockIcon className="size-3 text-muted-foreground/60" />
- <span className="text-xs font-medium text-muted-foreground/60">
- Set at creation
- </span>
- </div>
- <div className="flex items-center justify-between">
- <span className="text-xs text-muted-foreground">
- Email
- </span>
- <span className="text-xs text-muted-foreground">
- {agent.email_handle
- ? toAlookAddress(agent.email_handle)
- : "Not configured"}
- </span>
- </div>
- </div>
-
- <CustomEmailForm
- agentId={agent.id}
- workspaceId={agent.workspace_id}
- />
-
- {agent.email_handle && (
- <div className="border-t border-border/50 pt-4 mt-4">
- <AllowedSendersTab agentId={agent.id} />
- </div>
- )}
- </>
- )}
-
- <div className="flex items-center gap-2 pt-2">
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={onCancel}
- >
- Cancel
- </Button>
- <Button type="submit" size="sm" disabled={saving || !name}>
- {saving ? "Saving..." : "Save"}
- </Button>
- </div>
- </form>
- ) : (
- <AgentAccessTab agentId={agent.id} ownerId={agent.owner_id} />
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/agent-form-fields.tsx b/src/web/src/components/agent-form-fields.tsx
deleted file mode 100644
index f1fc8884f..000000000
--- a/src/web/src/components/agent-form-fields.tsx
+++ /dev/null
@@ -1,687 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useQuery } from "@tanstack/react-query";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { onEnterSubmit } from "@/lib/ime";
-import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectContent,
- SelectItem,
-} from "@/components/ui/select";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
- DialogFooter,
- DialogClose,
-} from "@/components/ui/dialog";
-import { RuntimeSelect } from "@/components/runtime-select";
-import { ProviderLogo } from "@/components/provider-logo";
-import { isValidHandle, isPublic, isPrivate } from "@alook/shared";
-import type { AgentRuntime as Runtime } from "@alook/shared";
-import { cn } from "@/lib/utils";
-import { InfoIcon, XIcon, Dices, ChevronDown } from "lucide-react";
-import { useWorkspaceOwner, captureWorkspaceOwner } from "@/contexts/workspace-context";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { agentWhitelistOptions, agentAccessOptions, workspaceMembersOptions } from "@/hooks/workspace/settings-query-options";
-import { useAgentPermissionCommand, usePendingAgentPermissions } from "@/hooks/workspace/use-agent-permission-command";
-import { type AgentAccessEntry } from "@/lib/api";
-import { isAbortError } from "@/lib/errors";
-import { toast } from "sonner";
-import { Switch } from "@/components/ui/switch";
-import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea";
-
-export function nameToHandle(name: string): string {
- return name
- .toLowerCase()
- .replace(/[^a-z0-9-]/g, "-")
- .replace(/-{2,}/g, "-")
- .replace(/^-|-$/g, "");
-}
-
-// --- General Fields ---
-
-interface GeneralFieldsProps {
- name: string;
- setName: (v: string) => void;
- description: string;
- setDescription: (v: string) => void;
- instructions?: string;
- setInstructions?: (v: string) => void;
- model: string;
- setModel: (v: string) => void;
- runtimeId: string;
- setRuntimeId: (v: string) => void;
- runtimes: Runtime[];
- providerModels: string[];
- errors?: {
- name?: string;
- runtimeId?: string;
- };
- runtimeAsRadio?: boolean;
- onShuffle?: () => void;
- emailHandleSlot?: React.ReactNode;
- advancedSection?: React.ReactNode;
-}
-
-export function GeneralFields({
- name,
- setName,
- description,
- setDescription,
- instructions,
- setInstructions,
- model,
- setModel,
- runtimeId,
- setRuntimeId,
- runtimes,
- providerModels,
- errors,
- runtimeAsRadio = false,
- onShuffle,
- emailHandleSlot,
- advancedSection,
-}: GeneralFieldsProps) {
- return (
- <>
- {/* Name — large frameless input */}
- <div>
- <div className="relative">
- <input
- id="agent-name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="Agent name"
- required
- autoFocus
- aria-invalid={Boolean(errors?.name)}
- aria-describedby={errors?.name ? "agent-name-error" : undefined}
- className="w-full border-0 bg-transparent px-0 py-1 text-2xl font-medium leading-[1.2] tracking-tight shadow-none outline-none placeholder:text-muted-foreground/40 placeholder:font-normal focus-visible:ring-0"
- />
- {onShuffle && (
- <button
- type="button"
- onClick={onShuffle}
- aria-label="Randomize name"
- className="absolute right-0 top-1/2 -translate-y-1/2 rounded p-2 text-muted-foreground/50 hover:text-foreground hover:bg-accent transition-colors"
- >
- <Dices className="size-4" />
- </button>
- )}
- </div>
- {errors?.name && (
- <p id="agent-name-error" className="text-xs text-destructive mt-1">
- {errors.name}
- </p>
- )}
- </div>
-
- {/* Description — frameless, auto-growing */}
- <AutoResizeTextarea
- id="agent-description"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- placeholder="Add a description…"
- rows={1}
- className="w-full border-0 bg-transparent px-0 py-1 text-sm text-foreground shadow-none outline-none placeholder:text-muted-foreground/40 focus-visible:ring-0"
- />
-
- {emailHandleSlot}
-
- {/* Runtime */}
- {(runtimeAsRadio || runtimes.length > 0) && <div id="agent-runtime-select" className="space-y-2">
- <Label className="text-xs text-muted-foreground">Runtime</Label>
- {runtimeAsRadio ? (
- <div className="space-y-2" role="radiogroup" aria-label="Runtime">
- {runtimes.length === 0 ? (
- <p className="text-xs text-muted-foreground">No runtimes — start a daemon first</p>
- ) : (
- runtimes.map((rt) => {
- const isOnline = rt.status === "online";
- const isSelected = runtimeId === rt.id;
- const machine = typeof rt.device_info === "string" ? rt.device_info : "";
- return (
- <label
- key={rt.id}
- className={cn(
- "flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-colors",
- isSelected
- ? "border-primary bg-primary/5"
- : "border-border/50 hover:border-foreground/20",
- !isOnline && "opacity-40 pointer-events-none"
- )}
- >
- <input
- type="radio"
- name="runtime"
- value={rt.id}
- checked={isSelected}
- disabled={!isOnline}
- onChange={() => {
- const oldProvider = runtimes.find((r) => r.id === runtimeId)?.provider;
- const newProvider = rt.provider;
- setRuntimeId(rt.id);
- if (oldProvider && oldProvider !== newProvider) {
- setModel("");
- }
- }}
- className="accent-primary size-3.5"
- />
- <ProviderLogo provider={rt.provider} className="h-4 w-4 shrink-0" />
- <span className="text-sm">{rt.provider}</span>
- {machine && (
- <span className="text-xs text-muted-foreground">{machine}</span>
- )}
- {!isOnline && (
- <span className="text-xs text-muted-foreground ml-auto">offline</span>
- )}
- </label>
- );
- })
- )}
- </div>
- ) : (
- <RuntimeSelect
- value={runtimeId}
- onValueChange={(newId) => {
- const oldProvider = runtimes.find((r) => r.id === runtimeId)?.provider;
- const newProvider = runtimes.find((r) => r.id === newId)?.provider;
- setRuntimeId(newId);
- if (oldProvider && oldProvider !== newProvider) {
- setModel("");
- }
- }}
- runtimes={runtimes}
- triggerProps={{
- "aria-invalid": Boolean(errors?.runtimeId),
- "aria-describedby": errors?.runtimeId
- ? "agent-runtime-error"
- : undefined,
- }}
- />
- )}
- {errors?.runtimeId && (
- <p id="agent-runtime-error" className="text-xs text-destructive">
- {errors.runtimeId}
- </p>
- )}
- </div>}
-
- {/* Advanced — collapsible */}
- {(setInstructions || advancedSection) && (
- <AdvancedSection>
- {setInstructions && (
- <div className="space-y-1">
- <Label className="text-xs text-muted-foreground">Instructions</Label>
- <AutoResizeTextarea
- id="agent-instructions"
- value={instructions ?? ""}
- onChange={(e) => setInstructions(e.target.value)}
- placeholder="System prompt or instructions..."
- rows={3}
- className="w-full border-0 bg-transparent px-0 py-1 text-sm text-foreground shadow-none outline-none placeholder:text-muted-foreground/40 focus-visible:ring-0"
- />
- </div>
- )}
-
- <div className="space-y-1">
- <Label className="text-xs text-muted-foreground">Model</Label>
- <input
- id="agent-model"
- value={model}
- onChange={(e) => setModel(e.target.value)}
- placeholder="Default (runtime model)"
- list="agent-model-options"
- className="w-full border-0 bg-transparent px-0 py-1 text-sm text-foreground shadow-none outline-none placeholder:text-muted-foreground/40 focus-visible:ring-0"
- />
- {providerModels.length > 0 && (
- <datalist id="agent-model-options">
- {providerModels.map((m) => (
- <option key={m} value={m} />
- ))}
- </datalist>
- )}
- </div>
-
- {advancedSection}
- </AdvancedSection>
- )}
- </>
- );
-}
-
-// --- Advanced Section (collapsible) ---
-
-function AdvancedSection({ children }: { children: React.ReactNode }) {
- const [open, setOpen] = useAtom(useCreateAtom(false));
- return (
- <div className="pt-1">
- <button
- type="button"
- onClick={() => setOpen(!open)}
- className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors"
- >
- <ChevronDown className={cn("size-3.5 transition-transform", open && "rotate-180")} />
- Advanced
- </button>
- {open && <div className="mt-3 space-y-4">{children}</div>}
- </div>
- );
-}
-
-// --- Email Handle Field ---
-
-interface EmailHandleFieldProps {
- emailHandle: string;
- setEmailHandle: (v: string) => void;
- derivedHandle: string;
-}
-
-export function EmailHandleField({
- emailHandle,
- setEmailHandle,
- derivedHandle,
-}: EmailHandleFieldProps) {
- const effectiveHandle = emailHandle || derivedHandle;
- const handleError =
- effectiveHandle && !isValidHandle(effectiveHandle)
- ? "Must be 3+ characters, letters/numbers/hyphens only"
- : "";
-
- return (
- <div className="space-y-1">
- <Label className="text-xs text-muted-foreground">Email</Label>
- <div className="flex items-center">
- <input
- id="agent-handle"
- value={emailHandle}
- onChange={(e) => setEmailHandle(e.target.value.toLowerCase())}
- placeholder={derivedHandle || "my-agent"}
- className="w-full border-0 bg-transparent px-0 py-1 text-sm text-foreground shadow-none outline-none placeholder:text-muted-foreground/40 focus-visible:ring-0"
- />
- <span className="shrink-0 text-sm text-muted-foreground/70">
- @alook.ai
- </span>
- </div>
- {handleError && (
- <p className="text-xs text-destructive">{handleError}</p>
- )}
- </div>
- );
-}
-
-export function getHandleError(effectiveHandle: string): string {
- if (effectiveHandle && !isValidHandle(effectiveHandle)) {
- return "Must be 3+ characters, letters/numbers/hyphens only";
- }
- return "";
-}
-
-
-// --- Allowed Senders (inline tab content) ---
-
-export function AllowedSendersTab({ agentId }: { agentId: string }) {
- const owner = useWorkspaceOwner();
- const { agents } = useAgentContext();
- const source = useWorkspaceViewSource(owner, `whitelist:${agentId}`, true);
- const query = useQuery(agentWhitelistOptions(owner, agentId));
- const command = useAgentPermissionCommand(owner, agentId);
- const pending = usePendingAgentPermissions(owner, agentId);
- const removed = new Set(pending.flatMap((action) => action.kind === "whitelist-remove" ? [action.id] : []));
- const whitelist = (query.data ?? []).filter((entry) => !removed.has(entry.id));
- const [newEmail, setNewEmail] = useAtom(useCreateAtom(""));
- const [actionError, setActionError] = useAtom(useCreateAtom<string | null>(null));
- const loading = query.isPending;
- const adding = pending.some((action) => action.kind === "whitelist-add");
- const error = actionError ?? query.error?.message ?? null;
- const hasSiblingAgents = agents.some((agent) => agent.id !== agentId && !!agent.email_handle);
- const isValidEmail = newEmail.includes("@") && newEmail.trim().length > 0;
- const handleAdd = async () => {
- if (!isValidEmail || adding) return;
- const assertView = source.assertActive;
- setActionError(null);
- try {
- await command.mutateAsync({ action: { kind: "whitelist-add", email: newEmail.toLowerCase() }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- setNewEmail("");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) setActionError(error instanceof Error ? error.message : "Failed to add email");
- }
- };
- const handleRemove = async (id: string) => {
- const assertView = source.assertActive;
- setActionError(null);
- try {
- await command.mutateAsync({ action: { kind: "whitelist-remove", id }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) setActionError("Failed to remove email");
- }
- };
-
-
- return (
- <div className="mx-auto max-w-md space-y-4">
- <div>
- <h3 className="text-sm font-medium">Allowed Senders</h3>
- <p className="text-xs text-muted-foreground mt-1">
- Only emails from these addresses will trigger this agent. Applies to
- all configured email addresses (alook.ai handle and custom email).
- </p>
- {hasSiblingAgents && (
- <p className="text-xs text-muted-foreground/70 mt-2 flex items-center gap-1">
- <InfoIcon className="size-3 shrink-0" />
- Agents in this workspace can already email each other — no whitelist
- entry needed.
- </p>
- )}
- </div>
-
- <div className="flex items-center gap-2">
- <Input
- value={newEmail}
- onChange={(e) => setNewEmail(e.target.value)}
- onKeyDown={onEnterSubmit(handleAdd)}
- placeholder="[email protected]"
- type="email"
- className="flex-1"
- />
- <Button
- type="button"
- size="sm"
- variant="secondary"
- disabled={!isValidEmail || adding}
- onClick={handleAdd}
- >
- {adding ? "Adding..." : "Add"}
- </Button>
- </div>
-
- {error && <p className="text-xs text-destructive">{error}</p>}
-
- {loading ? (
- <div className="space-y-2">
- {[1, 2, 3].map((i) => (
- <span
- key={i}
- className="block h-8 animate-pulse rounded-md bg-muted"
- />
- ))}
- </div>
- ) : whitelist.length === 0 ? (
- <p className="text-sm text-muted-foreground py-4 text-center">
- No allowed senders — all inbound emails will be rejected.
- </p>
- ) : (
- <div className="space-y-2">
- {whitelist.map((entry) => (
- <div
- key={entry.id}
- className="flex items-center justify-between rounded-md border border-border/50 px-3 py-2"
- >
- <span className="text-sm">{entry.email}</span>
- <button
- type="button"
- onClick={() => handleRemove(entry.id)}
- className="rounded-full p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
- >
- <XIcon className="size-3.5" />
- </button>
- </div>
- ))}
- </div>
- )}
- </div>
- );
-}
-
-// --- Agent Access Tab ---
-
-export function AgentAccessTab({
- agentId,
- ownerId,
-}: {
- agentId: string;
- ownerId: string | null;
-}) {
- const owner = useWorkspaceOwner();
- const { agents } = useAgentContext();
- const source = useWorkspaceViewSource(owner, `agent-access:${agentId}`, true);
- const access = useQuery(agentAccessOptions(owner, agentId));
- const memberQuery = useQuery(workspaceMembersOptions(owner));
- const command = useAgentPermissionCommand(owner, agentId);
- const pending = usePendingAgentPermissions(owner, agentId);
- const [actionError, setActionError] = useAtom(useCreateAtom<string | null>(null));
- const [selectedUserId, setSelectedUserId] = useAtom(useCreateAtom(""));
- const [revokeUserId, setRevokeUserId] = useAtom(useCreateAtom<string | null>(null));
- const [removeWhitelist, setRemoveWhitelist] = useAtom(useCreateAtom(true));
- const members = memberQuery.data ?? [];
- const removed = new Set(pending.flatMap((action) => action.kind === "revoke" ? [action.userId] : []));
- const accessList = (access.data ?? []).filter((entry) => !removed.has(entry.user_id));
- const revokeTarget = access.data?.find((entry) => entry.user_id === revokeUserId) ?? null;
- const setRevokeTarget = (entry: AgentAccessEntry | null) => setRevokeUserId(entry?.user_id ?? null);
- const visibilityIntent = pending.findLast((action) => action.kind === "visibility");
- const visibility = visibilityIntent?.kind === "visibility" ? visibilityIntent.value : agents.find((agent) => agent.id === agentId)?.visibility ?? "private";
- const savingVisibility = pending.some((action) => action.kind === "visibility");
- const adding = pending.some((action) => action.kind === "grant");
- const loading = access.isPending || memberQuery.isPending;
- const error = actionError ?? access.error?.message ?? memberQuery.error?.message ?? null;
- const ownerMember = members.find((member) => member.user_id === ownerId);
- const authorizedUserIds = new Set(accessList.map((entry) => entry.user_id));
- for (const action of pending) if (action.kind === "grant") authorizedUserIds.add(action.userId);
- const availableMembers = members.filter((member) => !authorizedUserIds.has(member.user_id) && member.user_id !== ownerId);
- const handleVisibilityChange = async (value: string) => {
- const assertView = source.assertActive;
- try {
- await command.mutateAsync({ action: { kind: "visibility", value }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- toast.success(isPublic(value) ? "Agent is now public" : "Agent is now private");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error("Failed to update visibility");
- }
- };
- const handleGrant = async (userId: string) => {
- if (!userId || adding) return;
- const assertView = source.assertActive;
- setActionError(null);
- try {
- await command.mutateAsync({ action: { kind: "grant", userId }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- setSelectedUserId("");
- toast.success("Access granted");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) setActionError(error instanceof Error ? error.message : "Failed to grant access");
- }
- };
- const handleRevoke = (userId: string) => { setRevokeUserId(userId); setRemoveWhitelist(true); };
- const confirmRevoke = async () => {
- if (!revokeTarget) return;
- const userId = revokeTarget.user_id, remove = removeWhitelist, assertView = source.assertActive;
- setRevokeUserId(null);
- setActionError(null);
- try {
- await command.mutateAsync({ action: { kind: "revoke", userId, removeWhitelist: remove }, token: captureWorkspaceOwner(owner), assertActive: Object.assign(() => assertView(), { signal: source.signal }) });
- assertView();
- toast.success(remove ? "Access revoked and removed from whitelist" : "Access revoked");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) setActionError("Failed to revoke access");
- }
- };
-
-
- return (
- <div className="mx-auto max-w-md space-y-6">
- <div className="space-y-4 rounded-lg border border-border/50 p-4">
- <div className="flex items-center justify-between">
- <div>
- <h3 className="text-sm font-medium">Visibility</h3>
- <p className="text-xs text-muted-foreground mt-1">
- {isPublic(visibility)
- ? "All workspace members can use this agent"
- : "Only authorized members can use this agent"}
- </p>
- </div>
- <div className="flex items-center gap-2">
- <span className="text-xs text-muted-foreground">
- {savingVisibility
- ? "Saving…"
- : isPublic(visibility)
- ? "Public"
- : "Private"}
- </span>
- <Switch
- checked={isPublic(visibility)}
- onCheckedChange={(checked) =>
- handleVisibilityChange(checked ? "public" : "private")
- }
- disabled={savingVisibility}
- />
- </div>
- </div>
- </div>
-
- {isPrivate(visibility) && (
- <div className="space-y-3">
- <h3 className="text-sm font-medium">Authorized Members</h3>
- {error && <p className="text-xs text-destructive">{error}</p>}
-
- {loading ? (
- <div className="space-y-2">
- {[1, 2].map((i) => (
- <span
- key={i}
- className="block h-10 animate-pulse rounded-md bg-muted"
- />
- ))}
- </div>
- ) : (
- <>
- <div className="space-y-2">
- {ownerMember && (
- <div className="flex items-center justify-between rounded-md border border-border/50 px-3 py-2">
- <div className="min-w-0">
- <p className="text-xs font-medium truncate">
- {ownerMember.name || ownerMember.email}
- </p>
- {ownerMember.name && (
- <p className="text-xs text-muted-foreground truncate">
- {ownerMember.email}
- </p>
- )}
- </div>
- <span className="ml-2 shrink-0 text-xs text-muted-foreground">
- Owner
- </span>
- </div>
- )}
- {accessList.map((entry) => (
- <div
- key={entry.user_id}
- className="flex items-center justify-between rounded-md border border-border/50 px-3 py-2"
- >
- <div className="min-w-0">
- <p className="text-xs font-medium truncate">
- {entry.name || entry.email}
- </p>
- {entry.name && (
- <p className="text-xs text-muted-foreground truncate">
- {entry.email}
- </p>
- )}
- </div>
- <button
- type="button"
- onClick={() => handleRevoke(entry.user_id)}
- className="ml-2 shrink-0 rounded-full p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
- >
- <XIcon className="size-3.5" />
- </button>
- </div>
- ))}
- </div>
-
- {availableMembers.length > 0 ? (
- <div className="flex items-center gap-2">
- <Select
- value={selectedUserId}
- onValueChange={(val) => {
- if (!val) return;
- setSelectedUserId(val);
- handleGrant(val);
- }}
- >
- <SelectTrigger className="flex-1 text-xs">
- <SelectValue placeholder="Add a member..." />
- </SelectTrigger>
- <SelectContent>
- {availableMembers.map((m) => (
- <SelectItem key={m.user_id} value={m.user_id}>
- {m.name || m.email}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- ) : (
- <p className="text-xs text-muted-foreground">
- All workspace members have been added. Invite new members from workspace settings.
- </p>
- )}
- </>
- )}
- </div>
- )}
-
- <Dialog
- open={!!revokeTarget}
- onOpenChange={(open) => {
- if (!open) setRevokeTarget(null);
- }}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Remove Member Access</DialogTitle>
- <DialogDescription>
- Remove{" "}
- <span className="font-medium text-foreground">
- {revokeTarget?.name || revokeTarget?.email}
- </span>{" "}
- from this agent?
- </DialogDescription>
- </DialogHeader>
- <label className="flex items-center gap-2 cursor-pointer px-1">
- <input
- type="checkbox"
- checked={removeWhitelist}
- onChange={(e) => setRemoveWhitelist(e.target.checked)}
- className="size-4 rounded border-border accent-primary"
- />
- <span className="text-sm">Also remove from email whitelist</span>
- </label>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" size="sm" />}>
- Cancel
- </DialogClose>
- <Button size="sm" variant="destructive" onClick={confirmRevoke}>
- Remove
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/src/web/src/components/agent-preview-card.tsx b/src/web/src/components/agent-preview-card.tsx
deleted file mode 100644
index 78fd1f5e8..000000000
--- a/src/web/src/components/agent-preview-card.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback } from "react";
-import { toAlookAddress } from "@alook/shared";
-import type { Agent } from "@alook/shared";
-import { Check, Copy } from "lucide-react";
-import { toast } from "sonner";
-import { AnimatedAvatar } from "@/components/avatar";
-import { AgentStatusBadge } from "@/components/agent-status-badge";
-import { cn } from "@/lib/utils";
-
-interface AgentPreviewCardProps {
- agent: Agent;
- isOnline?: boolean;
- activeTaskCount?: number;
- variant?: "default" | "compact";
- isHovered?: boolean;
-}
-
-export function AgentPreviewCard({
- agent,
- isOnline,
- activeTaskCount,
- variant = "default",
- isHovered,
-}: AgentPreviewCardProps) {
- const [copied, setCopied] = useAtom(useCreateAtom(false));
- const email = agent.email_handle ? toAlookAddress(agent.email_handle) : null;
- const isCompact = variant === "compact";
-
- const handleCopy = useCallback(async () => {
- if (!email) return;
- try {
- await navigator.clipboard.writeText(email);
- setCopied(true);
- toast.success("Email copied to clipboard");
- setTimeout(() => setCopied(false), 2000);
- } catch {
- toast.error("Failed to copy email");
- }
- }, [email, setCopied]);
-
- if (isCompact) {
- return (
- <div className="flex items-center gap-2 p-0">
- {(() => {
- return <AnimatedAvatar seed={agent.id} avatarUrl={agent.avatar_url} size={32} className="shrink-0 rounded-xl" isHovered={isHovered ?? false} isWorking={!!isOnline && (activeTaskCount ?? 0) > 0} />;
- })()}
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <p className="text-sm font-medium truncate max-w-35">{agent.name}</p>
- {email && (
- <span className="text-xs text-muted-foreground truncate">{email}</span>
- )}
- </div>
- {isOnline !== undefined && (
- <div className="pointer-events-none mt-1">
- <AgentStatusBadge
- isOnline={isOnline}
- taskCount={activeTaskCount ?? 0}
- agentId={agent.id}
- />
- </div>
- )}
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex flex-col gap-2 p-1">
- <div className="flex items-center gap-2">
- <p className="text-sm font-medium truncate">{agent.name}</p>
- <span className="flex-1" />
- {isOnline !== undefined && (
- <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">
- <span className={cn(
- "size-1.5 rounded-full",
- !isOnline ? "bg-status-offline" : "bg-status-online"
- )} />
- {!isOnline ? "Offline" : (activeTaskCount ?? 0) > 0 ? "Working" : null}
- </span>
- )}
- </div>
- {email && (
- <div className="flex items-center gap-1">
- <span className="text-xs text-muted-foreground truncate">{email}</span>
- <button
- type="button"
- onClick={(e) => { e.stopPropagation(); handleCopy(); }}
- className="shrink-0 p-1 rounded-sm text-muted-foreground/60 hover:text-foreground transition-colors cursor-pointer"
- >
- {copied ? (
- <Check className="size-3 text-green-500" />
- ) : (
- <Copy className="size-3" />
- )}
- </button>
- </div>
- )}
- {agent.description && (
- <p className="text-xs text-muted-foreground line-clamp-2">{agent.description}</p>
- )}
- </div>
- );
-}
diff --git a/src/web/src/components/agent-status-badge.tsx b/src/web/src/components/agent-status-badge.tsx
deleted file mode 100644
index 83bd5a137..000000000
--- a/src/web/src/components/agent-status-badge.tsx
+++ /dev/null
@@ -1,149 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useQuery } from "@tanstack/react-query";
-import Link from "next/link";
-import { badgeVariants } from "@/components/ui/badge";
-import { Badge } from "@/components/ui/badge";
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { Skeleton } from "@/components/ui/skeleton";
-import { cn } from "@/lib/utils";
-import { listWorkspaceActiveTasks, type WorkspaceActiveTask } from "@/lib/api";
-import { useWorkspaceOwner, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { relativeTime } from "@/lib/time";
-
-interface AgentStatusBadgeProps {
- isOnline: boolean;
- taskCount: number;
- agentId: string;
-}
-
-function StatusDot({ online }: { online: boolean }) {
- return (
- <span
- className={cn(
- "size-1.5 rounded-full shrink-0",
- online ? "bg-status-online" : "bg-status-offline"
- )}
- />
- );
-}
-
-function taskDisplayTitle(prompt: string): string {
- const match = prompt.match(/^Issue\s+iss_\w+:\s*(.+)/);
- if (match) return match[1].split("\n")[0];
- return prompt.split("\n")[0];
-}
-
-function TaskRow({ task, slug, agentId }: { task: WorkspaceActiveTask; slug: string; agentId: string }) {
- const isRunning = task.status === "running";
- return (
- <Link
- href={`/w/${slug}/agents/${agentId}?task=${task.id}&conv=${task.conversation_id}`}
- className="flex items-center gap-2 w-full py-2 px-2 hover:bg-muted rounded-md transition-colors cursor-pointer"
- >
- <span
- className={cn(
- "size-1.5 rounded-full shrink-0",
- isRunning ? "bg-primary animate-pulse" : "bg-muted-foreground/40"
- )}
- />
- <div className="flex-1 min-w-0">
- <p className="text-xs truncate">{taskDisplayTitle(task.prompt)}</p>
- </div>
- <span className="text-[10px] text-muted-foreground whitespace-nowrap shrink-0">
- {relativeTime(task.created_at)}
- </span>
- </Link>
- );
-}
-
-const MAX_VISIBLE_TASKS = 6;
-const badgeBase = "gap-2 text-muted-foreground hover:text-foreground cursor-pointer";
-
-export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBadgeProps) {
- const owner = useWorkspaceOwner();
- const { slug, workspaceId } = owner;
- const [open, setOpen] = useAtom(useCreateAtom(false));
- const query = useQuery({ queryKey: owner.key("active-tasks"), enabled: open, subscribed: open,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listWorkspaceActiveTasks(workspaceId, options), signal),
- select: (data) => data.tasks.filter((task) => task.agent_id === agentId),
- });
- const tasks = query.data;
- const loadingTasks = query.isPending;
- const error = query.isError;
-
- if (!isOnline) {
- return (
- <Tooltip>
- <TooltipTrigger render={
- <Badge
- variant="outline"
- render={<Link href={`/w/${slug}/runtimes`} />}
- className={badgeBase}
- >
- <StatusDot online={false} />
- <span className="hidden sm:inline">Offline</span>
- </Badge>
- } />
- <TooltipContent>Runtime offline — click to manage runtimes</TooltipContent>
- </Tooltip>
- );
- }
-
- return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- render={
- <button
- type="button"
- className={cn(badgeVariants({ variant: "outline" }), badgeBase)}
- onClick={(e: React.MouseEvent) => e.stopPropagation()}
- />
- }
- >
- <StatusDot online />
- {taskCount > 0 ? (
- <span className="hidden sm:inline">Working</span>
- ) : (
- <span className="hidden sm:inline text-muted-foreground/40">Online</span>
- )}
- </PopoverTrigger>
- <PopoverContent className="w-72 p-1">
- {loadingTasks ? (
- <div className="p-2 space-y-1">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex items-center gap-2 py-2 px-2">
- <Skeleton className="size-1.5 rounded-full" />
- <div className="flex-1 space-y-1">
- <Skeleton className="h-2.5 w-10" />
- <Skeleton className="h-3 w-full" />
- </div>
- <Skeleton className="h-2.5 w-8" />
- </div>
- ))}
- </div>
- ) : error ? (
- <div className="p-3 text-xs text-muted-foreground">Failed to load</div>
- ) : !tasks || tasks.length === 0 ? (
- <div className="p-3 text-xs text-muted-foreground">No active tasks</div>
- ) : (
- <div className="max-h-75 overflow-y-auto thin-scrollbar">
- {tasks.slice(0, MAX_VISIBLE_TASKS).map((task) => (
- <TaskRow key={task.id} task={task} slug={slug} agentId={agentId} />
- ))}
- {tasks.length > MAX_VISIBLE_TASKS && (
- <Link
- href={`/w/${slug}/agents/${agentId}/activity?status=running`}
- className="block text-xs text-muted-foreground hover:text-foreground text-center py-2 transition-colors"
- >
- View all {tasks.length} tasks
- </Link>
- )}
- </div>
- )}
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsx
deleted file mode 100644
index 56a8ca64e..000000000
--- a/src/web/src/components/app-sidebar.tsx
+++ /dev/null
@@ -1,743 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useRef, useEffect } from "react";
-import { useRouter, usePathname, useSearchParams } from "next/navigation";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspace } from "@/contexts/workspace-context";
-import type { Agent } from "@alook/shared";
-import { InboxPopover } from "@/components/inbox-popover";
-import { FlagPopover } from "@/components/flag-popover";
-import { Logo } from "@/components/logo";
-import { cn } from "@/lib/utils";
-import { Monitor, SunMoon, Plus, CalendarDays, Settings, ArrowLeftRight, Home, CircleDot, Folder, Ungroup, ArrowRightToLine } from "lucide-react";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { useTheme } from "next-themes";
-import { NavUser } from "@/components/nav-user";
-import {
- ContextMenu,
- ContextMenuTrigger,
- ContextMenuContent,
- ContextMenuItem,
- ContextMenuSeparator,
-} from "@/components/ui/context-menu";
-import { AnimatedAvatar } from "@/components/avatar/animated-avatar";
-import { DndContext, closestCenter, MouseSensor, TouchSensor, useSensor, useSensors, DragOverlay, type DragEndEvent, type DragStartEvent, type DragOverEvent } from "@dnd-kit/core";
-import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
-import { SortableContext, verticalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { useAgentFolders } from "@/hooks/use-agent-folders";
-import { AgentSidebarButton } from "@/components/sidebar/agent-sidebar-button";
-import { SortableFolderItem } from "@/components/sidebar/sortable-folder-item";
-import { FolderCollapsed } from "@/components/sidebar/folder-collapsed";
-import { FolderPopover } from "@/components/sidebar/folder-popover";
-
-function SortableAgentButton({ id, children }: { id: string; children: React.ReactNode }) {
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id });
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- opacity: isDragging ? 0.5 : 1,
- zIndex: isDragging ? 10 : undefined,
- };
- return (
- <div ref={setNodeRef} style={style} {...attributes} {...listeners}>
- {children}
- </div>
- );
-}
-
-export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {
- const router = useRouter();
- const pathname = usePathname();
- const searchParams = useSearchParams();
- const { agents, runtimes, loading, pins, unpinnedOrder, handlePinAgent, handleUnpinAgent, handleReorderPins, handleReorderUnpinned } = useAgentContext();
- const { slug, workspaceId } = useWorkspace();
-
- const { resolvedTheme, setTheme } = useTheme();
- const { activeTaskCounts: taskCounts } = useAgentContext();
-
- // --- Folder state (applies to unpinned section only) ---
- const {
- folders,
- expandedFolderId,
- setExpandedFolderId,
- createFolder,
- addToFolder,
- removeFromFolder,
- dissolveFolder,
- reorderInFolder,
- cleanupStaleAgents,
- getTopLevelItems,
- removeAgentFromAnyFolder,
- mergeFolders,
- } = useAgentFolders(workspaceId);
-
- // --- Selection mode for "Create group" ---
- const [selectionMode, setSelectionMode] = useAtom(useCreateAtom(false));
- const [selectedAgentIds, setSelectedAgentIds] = useAtom(useCreateAtom<Set<string>>(new Set<string>()));
-
- const pinned = agents
- .filter((a) => pins.has(a.id))
- .sort((a, b) => pins.get(a.id)!.position - pins.get(b.id)!.position);
- const unpinned = agents
- .filter((a) => !pins.has(a.id))
- .sort((a, b) => {
- const posA = unpinnedOrder.get(a.id);
- const posB = unpinnedOrder.get(b.id);
- if (posA !== undefined && posB !== undefined) return posA - posB;
- if (posA !== undefined) return -1;
- if (posB !== undefined) return 1;
- return a.name.localeCompare(b.name);
- });
-
- // Folders apply to the unpinned section
- const unpinnedIds = unpinned.map((a) => a.id);
- const topLevelUnpinnedItems = getTopLevelItems(unpinnedIds);
-
- // Cleanup stale agents when workspace agents change
- useEffect(() => {
- if (agents.length > 0) {
- cleanupStaleAgents(agents.map((a) => a.id));
- }
- }, [agents, cleanupStaleAgents]);
-
- // --- Drag-hold merge state (unpinned section) ---
- const [dragActiveId, setDragActiveId] = useAtom(useCreateAtom<string | null>(null));
- const [mergeTargetId, setMergeTargetId] = useAtom(useCreateAtom<string | null>(null));
- const [sortingDisabled, setSortingDisabled] = useAtom(useCreateAtom(false));
- const hoverTimerRef = useRef<ReturnType<typeof setTimeout>>(null);
- const hoverTargetRef = useRef<string | null>(null);
-
- useEffect(() => {
- return () => {
- if (hoverTimerRef.current) clearTimeout(hoverTimerRef.current);
- };
- }, []);
-
- // --- Folder anchor refs for popover positioning ---
- const folderAnchorRefs = useRef<Map<string, HTMLElement | null>>(new Map());
-
- const sensors = useSensors(
- useSensor(MouseSensor, { activationConstraint: { distance: 5 } }),
- useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } })
- );
-
- // Build sortable IDs for unpinned: mix of agent IDs and folder IDs
- const unpinnedSortableIds = topLevelUnpinnedItems.map((item) =>
- item.type === "agent" ? item.id : item.folder.id
- );
-
- // --- Pinned section drag (unchanged, simple reorder) ---
- function handlePinnedDragEnd(event: DragEndEvent) {
- const { active, over } = event;
- if (!over || active.id === over.id) return;
- const oldIndex = pinned.findIndex((a) => a.id === active.id);
- const newIndex = pinned.findIndex((a) => a.id === over.id);
- const reordered = arrayMove(pinned, oldIndex, newIndex);
- handleReorderPins(reordered.map((a) => a.id));
- }
-
- // --- Unpinned section drag (with folder merge support) ---
- function handleUnpinnedDragStart(event: DragStartEvent) {
- setDragActiveId(event.active.id as string);
- setExpandedFolderId(null);
- }
-
- function handleUnpinnedDragOver(event: DragOverEvent) {
- const { over } = event;
- if (!over) {
- clearMergeTimer();
- return;
- }
-
- const overId = over.id as string;
- if (overId === dragActiveId) {
- clearMergeTimer();
- return;
- }
-
- if (hoverTargetRef.current !== overId) {
- clearMergeTimer();
- hoverTargetRef.current = overId;
- hoverTimerRef.current = setTimeout(() => {
- setSortingDisabled(true);
- setMergeTargetId(overId);
- }, 300);
- }
- }
-
- function clearMergeTimer() {
- if (hoverTimerRef.current) {
- clearTimeout(hoverTimerRef.current);
- hoverTimerRef.current = null;
- }
- hoverTargetRef.current = null;
- setMergeTargetId(null);
- setSortingDisabled(false);
- }
-
- function handleUnpinnedDragEnd(event: DragEndEvent) {
- const { active, over } = event;
- clearMergeTimer();
- setDragActiveId(null);
-
- if (!over || active.id === over.id) return;
-
- const activeId = active.id as string;
- const overId = over.id as string;
-
- if (mergeTargetId === overId) {
- handleMerge(activeId, overId);
- setMergeTargetId(null);
- return;
- }
-
- const oldIndex = unpinnedSortableIds.indexOf(activeId);
- const newIndex = unpinnedSortableIds.indexOf(overId);
- if (oldIndex === -1 || newIndex === -1) return;
-
- const reordered = arrayMove(topLevelUnpinnedItems, oldIndex, newIndex);
- const flatIds: string[] = [];
- for (const item of reordered) {
- if (item.type === "agent") {
- flatIds.push(item.id);
- } else {
- flatIds.push(...item.folder.agentIds);
- }
- }
- handleReorderUnpinned(flatIds);
- }
-
- function handleUnpinnedDragCancel() {
- clearMergeTimer();
- setDragActiveId(null);
- }
-
- function handleMerge(draggedId: string, targetId: string) {
- const targetFolder = folders.find((f) => f.id === targetId);
- if (targetFolder) {
- const draggedFolder = folders.find((f) => f.id === draggedId);
- if (draggedFolder) {
- mergeFolders(draggedId, targetId);
- } else {
- removeAgentFromAnyFolder(draggedId);
- addToFolder(targetId, draggedId);
- }
- } else {
- const draggedFolder = folders.find((f) => f.id === draggedId);
- if (draggedFolder) {
- addToFolder(draggedId, targetId);
- } else {
- createFolder([targetId, draggedId]);
- }
- }
- }
-
- // Wrapped pin handler: removes agent from folder before pinning
- const handlePinWithFolderCleanup = useCallback(
- (agentId: string) => {
- removeAgentFromAnyFolder(agentId);
- handlePinAgent(agentId);
- },
- [removeAgentFromAnyFolder, handlePinAgent]
- );
-
- const prefix = `/w/${slug}`;
- const isHome = pathname === `${prefix}/home`;
- const isRuntimes = pathname === `${prefix}/runtimes`;
- const isCalendar = pathname === `${prefix}/calendar`;
- const isInbox = pathname.startsWith(`${prefix}/unread`);
- const isFlags = pathname.startsWith(`${prefix}/flags`);
- const isIssues = pathname.startsWith(`${prefix}/issues`);
- const isSettings = pathname === `${prefix}/settings`;
- const isCreateAgent = pathname === `${prefix}/agents/new`;
-
- const urlAgentId = searchParams.get("agent");
- const pathnameAgentMatch = pathname.match(/^\/w\/[^/]+\/agents\/([^/]+)/);
- const activeAgentId = urlAgentId ?? pathnameAgentMatch?.[1] ?? null;
-
- const handleAgentClick = (agentId: string) => {
- router.push(`${prefix}/agents/${agentId}`);
- onNavigate?.();
- };
-
- const hasOnlineRuntime = runtimes.some((r) => r.status === "online");
-
- const [wiggling, setWiggling] = useAtom(useCreateAtom(false));
- const wiggleRef = useRef(false);
- const wiggleTimerRef = useRef<ReturnType<typeof setTimeout>>(null);
-
- useEffect(() => {
- return () => {
- if (wiggleTimerRef.current) clearTimeout(wiggleTimerRef.current);
- };
- }, []);
-
- const triggerWiggle = useCallback(() => {
- if (wiggleRef.current) return;
- wiggleRef.current = true;
- setWiggling(true);
- const count = pinned.length + unpinned.length;
- const total = Math.max(0, count - 1) * 60 + 250;
- wiggleTimerRef.current = setTimeout(() => {
- wiggleRef.current = false;
- setWiggling(false);
- }, total);
- }, [pinned.length, setWiggling, unpinned.length]);
-
- // Get the drag overlay content for the unpinned section
- const dragActiveAgent = dragActiveId
- ? agents.find((a) => a.id === dragActiveId)
- : null;
- const dragActiveFolder = dragActiveId
- ? folders.find((f) => f.id === dragActiveId)
- : null;
-
- const renderAgentButton = (agent: typeof agents[number], animIndex: number, extraContextMenuItems?: React.ReactNode) => (
- <div
- className={cn(wiggling && "sidebar-agent-pop")}
- style={wiggling ? { animationDelay: `${animIndex * 60}ms` } : undefined}
- >
- <AgentSidebarButton
- agent={agent}
- isActive={activeAgentId === agent.id}
- isPinned={pins.has(agent.id)}
- isOnline={hasOnlineRuntime}
- taskCount={taskCounts[agent.id] ?? 0}
- onClick={() => handleAgentClick(agent.id)}
- onPin={() => handlePinWithFolderCleanup(agent.id)}
- onUnpin={() => handleUnpinAgent(agent.id)}
- extraContextMenuItems={extraContextMenuItems}
- isDragActive={!!dragActiveId}
- />
- </div>
- );
-
- // Build folder-related context menu items for a standalone unpinned agent
- const buildUnpinnedAgentContextMenu = (agentId: string) => (
- <>
- <ContextMenuSeparator />
- <ContextMenuItem
- onClick={() => {
- setSelectedAgentIds(new Set([agentId]));
- setSelectionMode(true);
- }}
- >
- <Folder className="size-3.5 mr-2" />
- Create group
- </ContextMenuItem>
- {folders.length > 0 && (
- <>
- {folders.map((f) => {
- const folderAgents = f.agentIds
- .map((id) => agents.find((a) => a.id === id))
- .filter(Boolean) as Agent[];
- const label = folderAgents
- .slice(0, 2)
- .map((a) => a.name)
- .join(", ");
- return (
- <ContextMenuItem
- key={f.id}
- onClick={() => addToFolder(f.id, agentId)}
- >
- <ArrowRightToLine className="size-3.5 mr-2" />
- Move to {label}{folderAgents.length > 2 ? "…" : ""}
- </ContextMenuItem>
- );
- })}
- </>
- )}
- </>
- );
-
- const handleSelectionConfirm = () => {
- if (selectedAgentIds.size >= 2) {
- createFolder(Array.from(selectedAgentIds));
- }
- setSelectionMode(false);
- setSelectedAgentIds(new Set<string>());
- };
-
- const handleSelectionCancel = () => {
- setSelectionMode(false);
- setSelectedAgentIds(new Set<string>());
- };
-
- const toggleAgentSelection = (agentId: string) => {
- setSelectedAgentIds((prev) => {
- const next = new Set(prev);
- if (next.has(agentId)) next.delete(agentId);
- else next.add(agentId);
- return next;
- });
- };
-
- const closeFolderPopover = useCallback(() => setExpandedFolderId(null), [setExpandedFolderId]);
-
- const expandedFolder = expandedFolderId
- ? folders.find((f) => f.id === expandedFolderId) ?? null
- : null;
-
- return (
- <nav className={cn("flex h-full w-14 flex-col items-center pt-1 pb-2 gap-1", wiggling && "relative z-10")}>
- {/* Top — logo */}
- <div className="pb-1.5 mb-1">
- <div
- className="flex shrink-0 items-center justify-center size-8 [&>button]:pointer-events-none cursor-pointer active:scale-90 transition-transform"
- onClick={triggerWiggle}
- >
- <Logo size="sm" iconOnly />
- </div>
- </div>
-
- {/* Main navigation */}
- <div className="flex flex-col items-center gap-2 pb-1.5 border-b border-border/50 mb-1">
- <Tooltip>
- <TooltipTrigger render={
- <button
- type="button"
- onClick={() => { router.push(`${prefix}/home`); onNavigate?.(); }}
- className={cn(
- "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "text-muted-foreground hover:text-foreground hover:bg-accent",
- isHome && "bg-accent text-foreground"
- )}
- />
- }>
- <Home className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right">Home</TooltipContent>
- </Tooltip>
-
- <InboxPopover isActive={isInbox} onNavigate={onNavigate} />
-
- <FlagPopover isActive={isFlags} onNavigate={onNavigate} />
-
- <Tooltip>
- <TooltipTrigger render={
- <button
- type="button"
- onClick={() => { router.push(`${prefix}/issues`); onNavigate?.(); }}
- className={cn(
- "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "text-muted-foreground hover:text-foreground hover:bg-accent",
- isIssues && "bg-accent text-foreground"
- )}
- />
- }>
- <CircleDot className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right">Issues</TooltipContent>
- </Tooltip>
-
- <Tooltip>
- <TooltipTrigger render={
- <button
- type="button"
- onClick={() => { router.push(`${prefix}/calendar`); onNavigate?.(); }}
- className={cn(
- "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "text-muted-foreground hover:text-foreground hover:bg-accent",
- isCalendar && "bg-accent text-foreground"
- )}
- />
- }>
- <CalendarDays className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right">Calendar</TooltipContent>
- </Tooltip>
-
- </div>
-
- {/* Agent avatars */}
- <div className={cn("flex flex-1 w-full flex-col items-center gap-2 py-1 scrollbar-none", wiggling ? "overflow-visible" : "overflow-y-auto")}>
- {loading ? (
- <Skeleton className="size-10 rounded-xl" />
- ) : (
- <>
- {/* Pinned section (flat, no folders) */}
- <DndContext sensors={sensors} collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} onDragEnd={handlePinnedDragEnd}>
- <SortableContext items={pinned.map((a) => a.id)} strategy={verticalListSortingStrategy}>
- {pinned.map((agent, i) => (
- <SortableAgentButton key={agent.id} id={agent.id}>
- {renderAgentButton(agent, i)}
- </SortableAgentButton>
- ))}
- </SortableContext>
- </DndContext>
-
- {pinned.length > 0 && unpinned.length > 0 && (
- <div className="w-6 border-t border-border/50" />
- )}
-
- {/* Unpinned section with folders */}
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- modifiers={[restrictToVerticalAxis]}
- onDragStart={handleUnpinnedDragStart}
- onDragOver={handleUnpinnedDragOver}
- onDragEnd={handleUnpinnedDragEnd}
- onDragCancel={handleUnpinnedDragCancel}
- >
- <SortableContext items={unpinnedSortableIds} strategy={sortingDisabled ? undefined : verticalListSortingStrategy}>
- {topLevelUnpinnedItems.map((item, i) => {
- if (item.type === "folder") {
- const folder = item.folder;
- const isAnyActive = folder.agentIds.includes(activeAgentId ?? "");
- return (
- <ContextMenu key={folder.id}>
- <ContextMenuTrigger render={<div />}>
- <SortableFolderItem
- folder={folder}
- agents={agents}
- isActive={isAnyActive}
- isMergeTarget={mergeTargetId === folder.id}
- dragActiveId={dragActiveId}
- onExpand={() =>
- setExpandedFolderId(
- expandedFolderId === folder.id ? null : folder.id
- )
- }
- nodeRefCallback={(el) =>
- folderAnchorRefs.current.set(folder.id, el)
- }
- />
- </ContextMenuTrigger>
- <ContextMenuContent>
- <ContextMenuItem onClick={() => dissolveFolder(folder.id)}>
- <Ungroup className="size-3.5 mr-2" />
- Ungroup agents
- </ContextMenuItem>
- </ContextMenuContent>
- </ContextMenu>
- );
- }
-
- // Standalone unpinned agent in selection mode
- if (selectionMode) {
- const agent = agents.find((a) => a.id === item.id);
- if (!agent) return null;
- const isSelected = selectedAgentIds.has(agent.id);
- return (
- <div
- key={agent.id}
- className="relative cursor-pointer"
- onClick={() => toggleAgentSelection(agent.id)}
- >
- <div className={cn(
- "transition-all duration-150",
- isSelected && "ring-2 ring-primary/50 rounded-xl"
- )}>
- {renderAgentButton(agent, pinned.length + i)}
- </div>
- {isSelected && (
- <span className="absolute -top-1 -right-1 size-3 rounded-full bg-primary ring-2 ring-background" />
- )}
- </div>
- );
- }
-
- // Standalone unpinned agent (normal mode)
- const agent = agents.find((a) => a.id === item.id);
- if (!agent) return null;
- return (
- <SortableAgentButton key={agent.id} id={agent.id}>
- {mergeTargetId === agent.id && dragActiveId ? (
- <FolderCollapsed
- folder={{ id: "merge-preview", agentIds: [agent.id, dragActiveId] }}
- agents={agents}
- isActive={false}
- onClick={() => {}}
- />
- ) : (
- renderAgentButton(agent, pinned.length + i, buildUnpinnedAgentContextMenu(agent.id))
- )}
- </SortableAgentButton>
- );
- })}
- </SortableContext>
-
- <DragOverlay>
- {dragActiveAgent ? (
- <div className="opacity-80">
- {(() => {
- return <AnimatedAvatar seed={dragActiveAgent.id} avatarUrl={dragActiveAgent.avatar_url} size={40} className="rounded-xl" isHovered={false} />;
- })()}
- </div>
- ) : dragActiveFolder ? (
- <div className="opacity-80">
- <FolderCollapsed
- folder={dragActiveFolder}
- agents={agents}
- isActive={false}
- onClick={() => {}}
- />
- </div>
- ) : null}
- </DragOverlay>
- </DndContext>
-
- {/* Selection mode confirmation bar */}
- {selectionMode && (
- <div className="flex flex-col gap-1 w-full px-1">
- <button
- type="button"
- onClick={handleSelectionConfirm}
- disabled={selectedAgentIds.size < 2}
- className="flex items-center justify-center h-7 rounded-lg bg-primary text-primary-foreground text-xs font-medium disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
- >
- Done ({selectedAgentIds.size})
- </button>
- <button
- type="button"
- onClick={handleSelectionCancel}
- className="flex items-center justify-center h-7 rounded-lg bg-secondary text-secondary-foreground text-xs cursor-pointer hover:bg-accent"
- >
- Cancel
- </button>
- </div>
- )}
- </>
- )}
-
- {/* Create agent */}
- {!loading && agents.length === 0 && runtimes.some(r => r.status === "online") ? (
- <Tooltip open>
- <TooltipTrigger
- render={
- <button
- type="button"
- onClick={() => { router.push(`${prefix}/agents/new`); onNavigate?.(); }}
- className={cn(
- "relative flex shrink-0 items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "border border-dashed border-primary/50 text-primary",
- "hover:border-primary hover:bg-primary/10",
- "animate-pulse",
- isCreateAgent && "border-solid border-primary bg-primary/10 animate-none"
- )}
- />
- }
- >
- <Plus className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right" sideOffset={8}>
- Create your first agent
- </TooltipContent>
- </Tooltip>
- ) : (
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- onClick={() => { router.push(`${prefix}/agents/new`); onNavigate?.(); }}
- className={cn(
- "flex shrink-0 items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "border border-dashed border-foreground/15 text-muted-foreground",
- "hover:border-foreground/30 hover:text-foreground hover:bg-accent",
- isCreateAgent &&
- "border-solid border-foreground/25 bg-accent text-foreground"
- )}
- />
- }
- >
- <Plus className="size-4" />
- </TooltipTrigger>
- <TooltipContent>New agent</TooltipContent>
- </Tooltip>
- )}
- </div>
-
- {/* Folder popover */}
- {expandedFolder && (
- <FolderPopover
- folder={expandedFolder}
- agents={agents}
- activeAgentId={activeAgentId}
- isOnline={hasOnlineRuntime}
- taskCounts={taskCounts}
- // eslint-disable-next-line react-hooks/refs -- stable DOM ref read, useEffect would cause anchor flash
- anchorRef={folderAnchorRefs.current.get(expandedFolder.id) ?? null}
- onAgentClick={handleAgentClick}
- onRemoveFromFolder={(agentId) =>
- removeFromFolder(expandedFolder.id, agentId)
- }
- onPinAgent={handlePinWithFolderCleanup}
- onReorder={(ordered) =>
- reorderInFolder(expandedFolder.id, ordered)
- }
- onClose={closeFolderPopover}
- />
- )}
-
- {/* Bottom section */}
- <div className="flex flex-col items-center gap-1 pt-2 border-t border-border/50 mt-1">
- <Tooltip>
- <TooltipTrigger render={
- <button
- type="button"
- onClick={() => { router.push(`${prefix}/runtimes`); onNavigate?.(); }}
- className={cn(
- "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "text-muted-foreground hover:text-foreground hover:bg-accent",
- isRuntimes && "bg-accent text-foreground"
- )}
- />
- }>
- <Monitor className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right">Runtimes</TooltipContent>
- </Tooltip>
-
- <Tooltip>
- <TooltipTrigger render={
- <button
- type="button"
- onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
- className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"
- />
- }>
- <SunMoon className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right">Toggle theme</TooltipContent>
- </Tooltip>
-
- <Tooltip>
- <TooltipTrigger render={
- <button
- type="button"
- onClick={() => { router.push(`${prefix}/settings`); onNavigate?.(); }}
- className={cn(
- "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "text-muted-foreground hover:text-foreground hover:bg-accent",
- isSettings && "bg-accent text-foreground"
- )}
- />
- }>
- <Settings className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right">Settings</TooltipContent>
- </Tooltip>
-
- <Tooltip>
- <TooltipTrigger render={
- <button
- type="button"
- onClick={() => { router.push("/workspaces"); onNavigate?.(); }}
- className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"
- />
- }>
- <ArrowLeftRight className="size-4" />
- </TooltipTrigger>
- <TooltipContent side="right">Switch workspace</TooltipContent>
- </Tooltip>
-
- <NavUser />
- </div>
- </nav>
- );
-}
diff --git a/src/web/src/components/artifact-content-renderer.tsx b/src/web/src/components/artifact-content-renderer.tsx
deleted file mode 100644
index 9cfce6ef9..000000000
--- a/src/web/src/components/artifact-content-renderer.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-"use client";
-
-import { useQuery } from "@tanstack/react-query";
-import { runWorkspaceRequest, useWorkspaceOwner } from "@/contexts/workspace-context";
-import { FileDownloadButton } from "@/components/file-download-button"
-
-import { getArtifactContent } from "@/lib/api";
-import type { Artifact } from "@alook/shared";
-import { Loader2, Download } from "lucide-react";
-import { Streamdown } from "streamdown";
-import { mermaid, cjk } from "@/lib/streamdown-plugins";
-import { RemoteContentImage } from "@/components/remote-image/remote-image";
-
-const TEXT_TYPES = new Set([
- "application/json",
- "application/xml",
- "application/javascript",
- "application/typescript",
- "application/x-yaml",
- "application/toml",
- "application/sql",
-]);
-
-function isTextType(contentType: string): boolean {
- if (contentType.startsWith("text/")) return true;
- if (TEXT_TYPES.has(contentType)) return true;
- return false;
-}
-
-export function isHtmlType(contentType: string): boolean {
- return contentType.startsWith("text/html");
-}
-
-function isImageType(contentType: string): boolean {
- return contentType.startsWith("image/");
-}
-
-export function isPreviewable(artifact: Artifact): boolean {
- return isTextType(artifact.content_type) || isImageType(artifact.content_type);
-}
-
-export function getArtifactUrl(id: string, workspaceId: string, download?: boolean): string {
- const params = new URLSearchParams({ workspace_id: workspaceId });
- if (download) params.set("download", "1");
- return `/api/artifacts/${id}/content?${params}`;
-}
-
-export function getArtifactThumbnailUrl(id: string, workspaceId: string): string {
- const params = new URLSearchParams({ workspace_id: workspaceId });
- return `/api/artifacts/${id}/thumbnail?${params}`;
-}
-
-export function computeArtifactVersions(artifacts: Artifact[]): { versionMap: Map<string, number>; duplicateFilenames: Set<string> } {
- const groups = new Map<string, Artifact[]>();
- for (const a of artifacts) {
- const group = groups.get(a.filename) || [];
- group.push(a);
- groups.set(a.filename, group);
- }
- const versionMap = new Map<string, number>();
- const duplicateFilenames = new Set<string>();
- for (const [filename, group] of groups) {
- group.sort((a, b) => a.created_at.localeCompare(b.created_at));
- if (group.length > 1) duplicateFilenames.add(filename);
- group.forEach((a, i) => versionMap.set(a.id, i + 1));
- }
- return { versionMap, duplicateFilenames };
-}
-
-function isMarkdown(filename: string): boolean {
- return /\.md$/i.test(filename);
-}
-
-interface ArtifactContentRendererProps {
- artifact: Artifact;
- workspaceId: string;
-}
-
-export function ArtifactContentRenderer({ artifact, workspaceId }: ArtifactContentRendererProps) {
- const owner = useWorkspaceOwner();
- const query = useQuery({
- queryKey: owner.key("artifact-content", artifact.id), gcTime: 0, staleTime: Infinity, retry: false,
- enabled: owner.workspaceId === workspaceId && isTextType(artifact.content_type) && !isHtmlType(artifact.content_type),
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => getArtifactContent(artifact.id, workspaceId, options), signal),
- });
- const content = query.isError ? "(failed to load content)" : query.data ?? null;
- const loading = query.isLoading;
-
- if (owner.workspaceId !== workspaceId) return null;
-
- const url = getArtifactUrl(artifact.id, workspaceId);
-
- if (loading) {
- return (
- <div className="flex justify-center py-8">
- <Loader2 className="size-5 animate-spin text-muted-foreground" />
- </div>
- );
- }
-
- if (isImageType(artifact.content_type)) {
- return (
- <div className="flex justify-center">
- <RemoteContentImage
- src={url}
- alt={artifact.filename}
- loading="eager"
- loadingLabel="Loading image"
- frameClassName="w-full max-w-3xl rounded-md"
- frameStyle={{ aspectRatio: "4/3" }}
- imageClassName="rounded-md object-contain"
- errorLabel="Image preview failed to load"
- />
- </div>
- );
- }
-
- if (isHtmlType(artifact.content_type)) {
- return <HtmlArtifactFrame url={url} title={artifact.filename} />;
- }
-
- if (isTextType(artifact.content_type)) {
- if (isMarkdown(artifact.filename)) {
- return (
- <div className="markdown text-sm">
- <Streamdown plugins={{ mermaid, cjk }}>{content ?? ""}</Streamdown>
- </div>
- );
- }
- return (
- <pre className="whitespace-pre-wrap text-sm font-mono text-foreground">{content}</pre>
- );
- }
-
- return (
- <div className="flex flex-col items-center gap-3 py-8 text-center">
- <p className="text-sm text-muted-foreground">
- This file type cannot be previewed.
- </p>
- <FileDownloadButton
- url={getArtifactUrl(artifact.id, workspaceId, true)}
- filename={artifact.filename}
- className="inline-flex items-center gap-2 rounded-md border border-input bg-background px-3 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-colors"
- >
- <Download className="size-3.5" />
- Download
- </FileDownloadButton>
- </div>
- );
-}
-
-function HtmlArtifactFrame({ url, title }: { url: string; title: string }) {
- return (
- <iframe
- src={url}
- sandbox="allow-same-origin"
- className="w-full h-full rounded-b-xl overflow-hidden"
- style={{ border: "none", display: "block" }}
- title={title}
- />
- );
-}
diff --git a/src/web/src/components/avatar/avatar-picker-dialog.tsx b/src/web/src/components/avatar/avatar-picker-dialog.tsx
deleted file mode 100644
index 3b845b81f..000000000
--- a/src/web/src/components/avatar/avatar-picker-dialog.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-"use client";
-
-import { useMemo } from "react";
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-
-import { Shuffle } from "lucide-react";
-import { GeneratedAvatar } from "./generated-avatar";
-import { serializeBeamSeed, parseBeamSeed } from "@/lib/avatar/seed-url";
-
-interface AvatarPickerDialogProps {
- /** Stored avatar value (`avatar:beam:{seed}` or a photo URL). */
- value: string | null;
- /** Emits the new stored value (`avatar:beam:{seed}`). */
- onChange: (value: string) => void;
-}
-
-function randomSeed(): string {
- return crypto.randomUUID();
-}
-
-/**
- * Generated avatar picker: a preview and Shuffle control that rerolls the stored seed.
- */
-export function AvatarPickerDialog({ value, onChange }: AvatarPickerDialogProps) {
- const [seed, setSeed] = useAtom(useCreateAtom<string>(useMemo<string>(() => parseBeamSeed(value) ?? randomSeed(), [value])));
-
- const shuffle = () => {
- const next = randomSeed();
- setSeed(next);
- onChange(serializeBeamSeed(next));
- };
-
- return (
- <div className="flex flex-col items-center gap-3">
- <div
- aria-label="Workspace agent avatar preview"
- data-testid="workspace-agent-avatar-preview"
- className="rounded-2xl bg-background p-2 shadow-sm border border-border"
- >
- <span className="block size-20 overflow-hidden rounded-2xl">
- <GeneratedAvatar seed={seed} size={80} className="size-full" />
- </span>
- </div>
- <button
- type="button"
- onClick={shuffle}
- className="inline-flex items-center gap-1.5 rounded-lg border border-border bg-background px-3 py-1.5 text-sm font-medium hover:bg-accent transition-colors cursor-pointer"
- >
- <Shuffle className="size-3.5" />
- Shuffle
- </button>
- </div>
- );
-}
diff --git a/src/web/src/components/avatar/index.ts b/src/web/src/components/avatar/index.ts
index 6b05031fa..68fd4f04c 100644
--- a/src/web/src/components/avatar/index.ts
+++ b/src/web/src/components/avatar/index.ts
@@ -3,7 +3,6 @@ export { type AvatarDraft, isPhotoAvatarUrl } from "@/lib/avatar/model";
export { GeneratedAvatar } from "./generated-avatar";
export { SeededBackdrop } from "./seeded-backdrop";
export { AnimatedAvatar } from "./animated-avatar";
-export { AvatarPickerDialog } from "./avatar-picker-dialog";
export { BotAvatarPickerDialog } from "./bot-avatar-picker-dialog";
export { AgentAvatar } from "./agent-avatar";
export { ProfileAvatar } from "./profile-avatar";
diff --git a/src/web/src/components/calendar/calendar-agenda.test.ts b/src/web/src/components/calendar/calendar-agenda.test.ts
deleted file mode 100644
index b383bb47f..000000000
--- a/src/web/src/components/calendar/calendar-agenda.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { groupByDay } from "./calendar-agenda";
-import type { CalendarEvent } from "@alook/shared";
-
-function mkEvent(over: Partial<CalendarEvent> & { scheduled_at: string }): CalendarEvent {
- return {
- id: over.id ?? Math.random().toString(36).slice(2),
- agent_id: over.agent_id ?? "ag_1",
- workspace_id: over.workspace_id ?? "ws_1",
- title: over.title ?? "test",
- repeat_interval: over.repeat_interval ?? null,
- repeat_stop_at: over.repeat_stop_at ?? null,
- last_triggered_at: over.last_triggered_at ?? null,
- created_at: over.created_at ?? "2026-04-01T00:00:00Z",
- updated_at: over.updated_at ?? "2026-04-01T00:00:00Z",
- ...over,
- };
-}
-
-describe("groupByDay", () => {
- it("returns an empty array for no events", () => {
- expect(groupByDay([])).toEqual([]);
- });
-
- it("groups events falling on the same local day", () => {
- const events = [
- mkEvent({ id: "e1", scheduled_at: "2026-04-17T09:00:00.000Z" }),
- mkEvent({ id: "e2", scheduled_at: "2026-04-17T15:30:00.000Z" }),
- mkEvent({ id: "e3", scheduled_at: "2026-04-18T09:00:00.000Z" }),
- ];
- const g = groupByDay(events);
- expect(g).toHaveLength(2);
- expect(g[0]!.items.map((e) => e.id)).toEqual(["e1", "e2"]);
- expect(g[1]!.items.map((e) => e.id)).toEqual(["e3"]);
- });
-
- it("orders groups chronologically", () => {
- const events = [
- mkEvent({ id: "late", scheduled_at: "2026-04-20T09:00:00.000Z" }),
- mkEvent({ id: "early", scheduled_at: "2026-04-17T09:00:00.000Z" }),
- mkEvent({ id: "mid", scheduled_at: "2026-04-18T09:00:00.000Z" }),
- ];
- const g = groupByDay(events);
- const dates = g.map((x) => x.day.getDate());
- expect(dates).toEqual([17, 18, 20]);
- });
-
- it("sorts items within a group by time", () => {
- const events = [
- mkEvent({ id: "pm", scheduled_at: "2026-04-17T15:30:00.000Z" }),
- mkEvent({ id: "am", scheduled_at: "2026-04-17T09:00:00.000Z" }),
- mkEvent({ id: "noon", scheduled_at: "2026-04-17T12:00:00.000Z" }),
- ];
- const g = groupByDay(events);
- expect(g).toHaveLength(1);
- expect(g[0]!.items.map((e) => e.id)).toEqual(["am", "noon", "pm"]);
- });
-
- it("omits days that have no events", () => {
- const events = [
- mkEvent({ id: "e1", scheduled_at: "2026-04-17T09:00:00.000Z" }),
- mkEvent({ id: "e2", scheduled_at: "2026-04-20T09:00:00.000Z" }),
- ];
- const g = groupByDay(events);
- expect(g).toHaveLength(2);
- expect(g.map((x) => x.day.getDate())).toEqual([17, 20]);
- });
-});
diff --git a/src/web/src/components/calendar/calendar-agenda.tsx b/src/web/src/components/calendar/calendar-agenda.tsx
deleted file mode 100644
index 90e03f27a..000000000
--- a/src/web/src/components/calendar/calendar-agenda.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import type { CalendarEvent, Agent } from "@alook/shared";
-import { Skeleton } from "@/components/ui/skeleton";
-import { agentColor } from "./calendar-colors";
-import { dateKey } from "./calendar-month-grid";
-import { formatRepeatDisplay } from "./repeat-interval-utils";
-
-export interface CalendarAgendaProps {
- events: CalendarEvent[];
- agents: Agent[];
- loading: boolean;
- onSelectEvent: (event: CalendarEvent) => void;
-}
-
-export function groupByDay(
- events: CalendarEvent[]
-): { day: Date; items: CalendarEvent[] }[] {
- const groups = new Map<string, { day: Date; items: CalendarEvent[] }>();
- for (const ev of events) {
- const d = new Date(ev.scheduled_at);
- const key = dateKey(d);
- if (!groups.has(key)) {
- const base = new Date(d.getFullYear(), d.getMonth(), d.getDate());
- groups.set(key, { day: base, items: [] });
- }
- groups.get(key)!.items.push(ev);
- }
- const sorted = [...groups.values()].sort(
- (a, b) => a.day.getTime() - b.day.getTime()
- );
- for (const g of sorted) {
- g.items.sort(
- (a, b) =>
- new Date(a.scheduled_at).getTime() -
- new Date(b.scheduled_at).getTime()
- );
- }
- return sorted;
-}
-
-function formatDay(d: Date): string {
- return d.toLocaleDateString(undefined, {
- weekday: "short",
- month: "short",
- day: "numeric",
- });
-}
-
-function formatTime(iso: string): string {
- return new Date(iso).toLocaleTimeString(undefined, {
- hour: "2-digit",
- minute: "2-digit",
- hour12: false,
- });
-}
-
-export function CalendarAgenda({
- events,
- agents,
- loading,
- onSelectEvent,
-}: CalendarAgendaProps) {
- const groups = groupByDay(events);
- const agentNameById = new Map<string, string>();
- for (const a of agents) agentNameById.set(a.id, a.name);
- const today = new Date();
-
- if (loading && events.length === 0) {
- return (
- <div className="flex flex-col gap-4">
- {Array.from({ length: 4 }).map((_, g) => (
- <div key={g} className="flex flex-col gap-2">
- <Skeleton className="h-3 w-24" />
- {Array.from({ length: 2 }).map((_, r) => (
- <Skeleton key={r} className="h-8 w-full rounded-md" />
- ))}
- </div>
- ))}
- </div>
- );
- }
-
- if (groups.length === 0) {
- return (
- <div className="flex flex-1 items-center justify-center py-12">
- <div className="text-center">
- <p className="text-sm text-muted-foreground">No events in view.</p>
- <p className="mt-2 text-xs text-muted-foreground">
- Switch to month view or create a new event above.
- </p>
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex flex-col gap-4" data-testid="calendar-agenda">
- {groups.map((g) => {
- const isToday =
- today.getFullYear() === g.day.getFullYear() &&
- today.getMonth() === g.day.getMonth() &&
- today.getDate() === g.day.getDate();
- return (
- <div key={dateKey(g.day)} className="flex flex-col gap-2">
- <h3
- className={cn(
- "sticky top-0 z-10 py-1 text-[11px] font-medium text-muted-foreground",
- isToday && "text-foreground"
- )}
- >
- {formatDay(g.day)}
- {isToday && (
- <span className="ml-2 rounded-full bg-foreground text-background px-2 py-1 text-[10px]">
- Today
- </span>
- )}
- </h3>
- <ul className="flex flex-col gap-1">
- {g.items.map((ev) => (
- <li key={`${ev.id}@${ev.occurrence_at}`}>
- <button
- type="button"
- onClick={() => onSelectEvent(ev)}
- className="flex w-full items-center gap-3 rounded-md border border-border/50 bg-background px-3 py-2 text-left transition-colors hover:bg-accent"
- >
- <span className="shrink-0 text-xs text-muted-foreground tabular-nums w-16">
- {formatTime(ev.scheduled_at)}
- </span>
- <span
- className={cn(
- "shrink-0 rounded-sm px-2 py-1 text-[10px] font-medium",
- agentColor(ev.agent_id)
- )}
- >
- {agentNameById.get(ev.agent_id) ?? ev.agent_id}
- </span>
- <span className="flex-1 truncate text-sm">{ev.title}</span>
- {ev.repeat_interval && (
- <span className="shrink-0 text-[10px] text-muted-foreground">
- {formatRepeatDisplay(ev.repeat_interval!)}
- </span>
- )}
- {ev.collapsed_count != null && ev.collapsed_count > 1 && (
- <span className="shrink-0 rounded-full bg-muted px-2 py-1 text-[10px] font-medium text-muted-foreground">
- &times; {ev.collapsed_count} today
- </span>
- )}
- </button>
- </li>
- ))}
- </ul>
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/src/web/src/components/calendar/calendar-agent-filter.tsx b/src/web/src/components/calendar/calendar-agent-filter.tsx
deleted file mode 100644
index a1c9e8bf6..000000000
--- a/src/web/src/components/calendar/calendar-agent-filter.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import type { Agent } from "@alook/shared";
-import { Skeleton } from "@/components/ui/skeleton";
-import { agentColor } from "./calendar-month-grid";
-
-export interface CalendarAgentFilterProps {
- agents: Agent[];
- selected: Set<string>;
- onToggle: (agentId: string) => void;
-}
-
-/**
- * Chip row height is pinned (`h-6` + flex container) so the filter reserves the
- * same vertical space whether loading, empty, or populated — avoids layout
- * drift that would push the calendar grid down on load.
- */
-export function CalendarAgentFilter({
- agents,
- selected,
- onToggle,
-}: CalendarAgentFilterProps) {
- return (
- <div className="flex min-h-6 items-center gap-2 overflow-x-auto flex-nowrap scrollbar-none sm:flex-wrap sm:overflow-x-visible">
- {agents.length === 0 ? (
- <>
- <Skeleton className="h-6 w-20 rounded-full" />
- <Skeleton className="h-6 w-24 rounded-full" />
- <Skeleton className="h-6 w-16 rounded-full" />
- </>
- ) : (
- agents.map((a) => {
- const on = selected.has(a.id);
- return (
- <button
- type="button"
- key={a.id}
- onClick={() => onToggle(a.id)}
- className={cn(
- "flex h-6 shrink-0 items-center gap-2 rounded-full px-2 text-[11px] font-medium transition-colors",
- on
- ? "bg-foreground text-background"
- : "bg-transparent text-muted-foreground border border-border hover:bg-accent"
- )}
- >
- <span
- className={cn("size-2 rounded-full", agentColor(a.id).split(" ")[0])}
- />
- <span className="max-w-30 truncate sm:max-w-none">{a.name}</span>
- </button>
- );
- })
- )}
- </div>
- );
-}
diff --git a/src/web/src/components/calendar/calendar-colors.ts b/src/web/src/components/calendar/calendar-colors.ts
deleted file mode 100644
index e0e0a7099..000000000
--- a/src/web/src/components/calendar/calendar-colors.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-export function agentColor(agentId: string): string {
- const palette = [
- "bg-[oklch(0.78_0.08_60)] text-[oklch(0.25_0.05_60)]",
- "bg-[oklch(0.80_0.07_120)] text-[oklch(0.25_0.05_120)]",
- "bg-[oklch(0.80_0.06_220)] text-[oklch(0.25_0.05_220)]",
- "bg-[oklch(0.80_0.07_30)] text-[oklch(0.25_0.05_30)]",
- "bg-[oklch(0.80_0.06_280)] text-[oklch(0.25_0.05_280)]",
- "bg-[oklch(0.80_0.07_160)] text-[oklch(0.25_0.05_160)]",
- ];
- let h = 0;
- for (let i = 0; i < agentId.length; i++) h = (h * 31 + agentId.charCodeAt(i)) | 0;
- return palette[Math.abs(h) % palette.length]!;
-}
-
-export function agentDot(agentId: string): string {
- const palette = [
- "bg-[oklch(0.62_0.13_60)] dark:bg-[oklch(0.72_0.11_60)]",
- "bg-[oklch(0.62_0.12_120)] dark:bg-[oklch(0.72_0.10_120)]",
- "bg-[oklch(0.62_0.12_220)] dark:bg-[oklch(0.72_0.10_220)]",
- "bg-[oklch(0.62_0.13_30)] dark:bg-[oklch(0.72_0.11_30)]",
- "bg-[oklch(0.62_0.12_280)] dark:bg-[oklch(0.72_0.10_280)]",
- "bg-[oklch(0.62_0.12_160)] dark:bg-[oklch(0.72_0.10_160)]",
- ];
- let h = 0;
- for (let i = 0; i < agentId.length; i++) h = (h * 31 + agentId.charCodeAt(i)) | 0;
- return palette[Math.abs(h) % palette.length]!;
-}
-
-export function agentInk(agentId: string): string {
- const palette = [
- "text-[oklch(0.52_0.14_60)] dark:text-[oklch(0.78_0.11_60)]",
- "text-[oklch(0.52_0.13_120)] dark:text-[oklch(0.78_0.10_120)]",
- "text-[oklch(0.52_0.13_220)] dark:text-[oklch(0.78_0.10_220)]",
- "text-[oklch(0.52_0.14_30)] dark:text-[oklch(0.78_0.11_30)]",
- "text-[oklch(0.52_0.13_280)] dark:text-[oklch(0.78_0.10_280)]",
- "text-[oklch(0.52_0.13_160)] dark:text-[oklch(0.78_0.10_160)]",
- ];
- let h = 0;
- for (let i = 0; i < agentId.length; i++) h = (h * 31 + agentId.charCodeAt(i)) | 0;
- return palette[Math.abs(h) % palette.length]!;
-}
diff --git a/src/web/src/components/calendar/calendar-date-picker.tsx b/src/web/src/components/calendar/calendar-date-picker.tsx
deleted file mode 100644
index 811800a69..000000000
--- a/src/web/src/components/calendar/calendar-date-picker.tsx
+++ /dev/null
@@ -1,197 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-
-import {
- Popover,
- PopoverTrigger,
- PopoverContent,
-} from "@/components/ui/popover";
-import { cn } from "@/lib/utils";
-import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
-import { buildMonthCells, sameDay } from "./calendar-month-grid";
-
-export interface CalendarDatePickerProps {
- value: Date | null;
- onChange: (date: Date) => void;
- placeholder?: string;
- min?: Date;
- className?: string;
- ariaLabel?: string;
- /** Suppress the built-in CalendarDays icon in the trigger. */
- hideIcon?: boolean;
- /**
- * When provided, the footer shows a "Clear" action while a value is set.
- * Picks are still delivered through `onChange`; clearing is separate so
- * required pickers (no clear affordance) can stay non-nullable.
- */
- onClear?: () => void;
-}
-
-function formatDisplay(d: Date): string {
- return d.toLocaleDateString(undefined, {
- month: "short",
- day: "numeric",
- year: "numeric",
- });
-}
-
-function monthYearLabel(y: number, m: number): string {
- return new Date(y, m, 1).toLocaleDateString(undefined, {
- month: "long",
- year: "numeric",
- });
-}
-
-export function CalendarDatePicker({
- value,
- onChange,
- placeholder = "Jump to date",
- min,
- className,
- ariaLabel = "Pick a date",
- hideIcon = false,
- onClear,
-}: CalendarDatePickerProps) {
- const [open, setOpen] = useAtom(useCreateAtom(false));
- const initial = value ?? new Date();
- const [viewYear, setViewYear] = useAtom(useCreateAtom(initial.getFullYear()));
- const [viewMonth, setViewMonth] = useAtom(useCreateAtom(initial.getMonth()));
-
- const cells = buildMonthCells(viewYear, viewMonth);
- const today = new Date();
-
- const handleSelect = (d: Date) => {
- if (min && d < stripTime(min)) return;
- onChange(d);
- setOpen(false);
- };
-
- const label = value ? formatDisplay(value) : placeholder;
-
- return (
- <Popover
- open={open}
- onOpenChange={(o) => {
- setOpen(o);
- if (o) {
- const anchor = value ?? new Date();
- setViewYear(anchor.getFullYear());
- setViewMonth(anchor.getMonth());
- }
- }}
- >
- <PopoverTrigger
- aria-label={ariaLabel}
- className={cn(
- "flex h-7 items-center gap-2 rounded-md border border-input bg-transparent px-2 text-xs outline-none transition-colors",
- "hover:bg-accent hover:text-foreground",
- "focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
- value ? "text-foreground" : "text-muted-foreground",
- className
- )}
- >
- {!hideIcon && <CalendarDays className="size-3.5 opacity-70" />}
- <span className="hidden sm:inline tabular-nums">{label}</span>
- </PopoverTrigger>
- <PopoverContent align="end" className="w-64 p-3">
- <div className="flex items-center justify-between pb-2">
- <button
- type="button"
- aria-label="Previous month"
- onClick={() => {
- setViewMonth((m) => (m === 0 ? 11 : m - 1));
- if (viewMonth === 0) setViewYear((y) => y - 1);
- }}
- className="flex size-6 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
- >
- <ChevronLeft className="size-3.5" />
- </button>
- <span className="text-xs font-medium tabular-nums">
- {monthYearLabel(viewYear, viewMonth)}
- </span>
- <button
- type="button"
- aria-label="Next month"
- onClick={() => {
- setViewMonth((m) => (m === 11 ? 0 : m + 1));
- if (viewMonth === 11) setViewYear((y) => y + 1);
- }}
- className="flex size-6 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
- >
- <ChevronRight className="size-3.5" />
- </button>
- </div>
-
- <div className="grid grid-cols-7 pb-1 text-[10px] text-muted-foreground">
- {["S", "M", "T", "W", "T", "F", "S"].map((d, i) => (
- <div
- key={i}
- className="flex h-6 items-center justify-center font-medium"
- >
- {d}
- </div>
- ))}
- </div>
-
- <div className="grid grid-cols-7 gap-1">
- {cells.map((cell, i) => {
- const isToday = sameDay(today, cell.date);
- const isSelected = value ? sameDay(value, cell.date) : false;
- const isDisabled = !!min && cell.date < stripTime(min);
- return (
- <button
- key={i}
- type="button"
- disabled={isDisabled}
- onClick={() => handleSelect(cell.date)}
- aria-pressed={isSelected}
- className={cn(
- "flex h-7 w-full items-center justify-center rounded text-[11px] tabular-nums transition-colors outline-none",
- "focus-visible:ring-2 focus-visible:ring-ring/60",
- !cell.inMonth && "text-muted-foreground/50",
- cell.inMonth && !isSelected && "hover:bg-accent",
- isToday && !isSelected &&
- "text-foreground font-medium ring-1 ring-inset ring-border",
- isSelected &&
- "bg-foreground text-background font-medium",
- isDisabled && "opacity-30 cursor-not-allowed hover:bg-transparent"
- )}
- >
- {cell.date.getDate()}
- </button>
- );
- })}
- </div>
-
- <div className="flex items-center justify-between gap-3 pt-2 mt-1 border-t border-border/50">
- {onClear && value ? (
- <button
- type="button"
- onClick={() => {
- onClear();
- setOpen(false);
- }}
- className="text-[11px] text-muted-foreground hover:text-foreground transition-colors"
- >
- Clear
- </button>
- ) : (
- <span aria-hidden />
- )}
- <button
- type="button"
- onClick={() => handleSelect(new Date())}
- className="text-[11px] text-muted-foreground hover:text-foreground transition-colors"
- >
- Today
- </button>
- </div>
- </PopoverContent>
- </Popover>
- );
-}
-
-function stripTime(d: Date): Date {
- return new Date(d.getFullYear(), d.getMonth(), d.getDate());
-}
diff --git a/src/web/src/components/calendar/calendar-day-popover.tsx b/src/web/src/components/calendar/calendar-day-popover.tsx
deleted file mode 100644
index dff91656b..000000000
--- a/src/web/src/components/calendar/calendar-day-popover.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-"use client";
-
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import { cn } from "@/lib/utils";
-import type { CalendarEvent, Agent } from "@alook/shared";
-import { Repeat } from "lucide-react";
-import { agentDot, agentInk } from "./calendar-month-grid";
-
-export interface CalendarDayPopoverProps {
- events: CalendarEvent[];
- agents: Agent[];
- date: Date;
- hiddenCount: number;
- open: boolean;
- onOpenChange: (open: boolean) => void;
- onSelectEvent: (event: CalendarEvent) => void;
-}
-
-function timeLabel(iso: string) {
- return new Date(iso).toLocaleTimeString(undefined, {
- hour: "2-digit",
- minute: "2-digit",
- hour12: false,
- });
-}
-
-export function CalendarDayPopover({
- events,
- agents,
- date,
- hiddenCount,
- open,
- onOpenChange,
- onSelectEvent,
-}: CalendarDayPopoverProps) {
- const agentNameById = new Map<string, string>();
- for (const a of agents) agentNameById.set(a.id, a.name);
-
- const sorted = [...events].sort(
- (a, b) =>
- new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime()
- );
-
- const dateLabel = date.toLocaleDateString(undefined, {
- weekday: "short",
- month: "short",
- day: "numeric",
- });
-
- return (
- <Popover open={open} onOpenChange={onOpenChange}>
- <PopoverTrigger
- aria-label={`${hiddenCount} more event${hiddenCount === 1 ? "" : "s"}`}
- onClick={(e) => e.stopPropagation()}
- className="w-full truncate rounded-sm px-2 py-1 text-left text-[10px] text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
- >
- +{hiddenCount} more
- </PopoverTrigger>
- <PopoverContent className="w-64" align="start">
- <div className="flex flex-col gap-2">
- <p className="px-1 pb-1 text-[11px] font-medium text-muted-foreground">
- {dateLabel}
- </p>
- <div className="flex flex-col gap-1">
- {sorted.map((ev) => {
- const isRecurring = Boolean(ev.repeat_interval);
- return (
- <button
- key={`${ev.id}@${ev.occurrence_at}`}
- type="button"
- onClick={() => {
- onOpenChange(false);
- onSelectEvent(ev);
- }}
- className="flex items-center gap-2 rounded-sm px-2 py-1 text-left text-[11px] font-medium text-foreground/85 hover:bg-accent/60 transition-colors"
- title={`${isRecurring ? "Recurring · " : ""}${ev.title}${
- agentNameById.get(ev.agent_id)
- ? ` — ${agentNameById.get(ev.agent_id)}`
- : ""
- }`}
- >
- {isRecurring ? (
- <Repeat
- aria-hidden
- className={cn("size-3 shrink-0", agentInk(ev.agent_id))}
- />
- ) : (
- <span
- aria-hidden
- className={cn(
- "size-1.5 shrink-0 rounded-full",
- agentDot(ev.agent_id)
- )}
- />
- )}
- <span className="shrink-0 text-[10px] text-muted-foreground tabular-nums">
- {timeLabel(ev.scheduled_at)}
- </span>
- <span className="truncate">{ev.title}</span>
- </button>
- );
- })}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/src/web/src/components/calendar/calendar-event-sheet.tsx b/src/web/src/components/calendar/calendar-event-sheet.tsx
deleted file mode 100644
index d1838e561..000000000
--- a/src/web/src/components/calendar/calendar-event-sheet.tsx
+++ /dev/null
@@ -1,884 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useQuery } from "@tanstack/react-query";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { isAbortError } from "@/lib/errors";
-import { useEffect, useMemo, useRef } from "react";
-import { toast } from "sonner";
-import { getCalendarEvent } from "@/lib/api";
-import {
- Sheet,
- SheetContent,
- SheetTitle,
- SheetBody,
- SheetFooter,
-} from "@/components/ui/sheet";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { MarkdownEditor } from "@/components/ui/markdown-editor";
-import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectContent,
- SelectItem,
-} from "@/components/ui/select";
-import {
- CalendarDays,
- CalendarOff,
- Loader2,
- Repeat as RepeatIcon,
- User,
- X,
-} from "lucide-react";
-import { cn } from "@/lib/utils";
-import type {
- Agent,
- CalendarEvent,
- UpdateCalendarEventRequest,
-} from "@alook/shared";
-import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea";
-import { Kbd } from "@/components/ui/kbd";
-import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle";
-import { CalendarDatePicker } from "./calendar-date-picker";
-import { CalendarTimePicker } from "./calendar-time-picker";
-import {
- type RepeatUnit,
- parseRepeatInterval,
- formatRepeatInterval,
- unitLabel,
- isValidUnit,
- REPEAT_UNITS,
- PRESET_INTERVALS,
-} from "./repeat-interval-utils";
-
-interface CreateFormValues {
- agent_id: string;
- title: string;
- description?: string;
- scheduled_at: string;
- repeat_interval?: string;
- repeat_stop_date?: string;
-}
-
-export interface CalendarEventSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- agents?: Agent[];
- /** When provided, the sheet is in edit mode. */
- event?: CalendarEvent | null;
- /** When provided (without `event`), the sheet self-fetches the event data. */
- calendarEventId?: string | null;
- workspaceId?: string;
- /** When true, all fields render as non-editable display. */
- readonly?: boolean;
- defaultDate?: Date;
- defaultAgentId?: string;
- submitting?: boolean;
- saving?: boolean;
- deleting?: boolean;
- onCreate?: (values: CreateFormValues) => Promise<void> | void;
- onUpdate?: (
- event: CalendarEvent,
- patch: UpdateCalendarEventRequest
- ) => Promise<void>;
- onDelete?: (
- event: CalendarEvent,
- args?: { scope?: "this" | "following"; occurrence_at?: string }
- ) => void;
-}
-
-function pad(n: number) {
- return String(n).padStart(2, "0");
-}
-
-function nextSlotTime(d: Date, stepMin = 30): string {
- const total = d.getHours() * 60 + d.getMinutes();
- const next = Math.ceil((total + 1) / stepMin) * stepMin;
- const h = Math.floor(next / 60) % 24;
- const m = next % 60;
- return `${pad(h)}:${pad(m)}`;
-}
-
-function combineDateTime(date: Date, time: string): Date {
- const match = /^(\d{2}):(\d{2})$/.exec(time);
- const h = match ? Number(match[1]) : date.getHours();
- const m = match ? Number(match[2]) : date.getMinutes();
- const out = new Date(date);
- out.setHours(h, m, 0, 0);
- return out;
-}
-
-function toYYYYMMDD(d: Date): string {
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
-}
-
-function parseTime(d: Date): string {
- return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
-}
-
-function normalizedDescription(value: string | null | undefined): string {
- return value?.trim() || "";
-}
-
-const GHOST_CONTROL =
- "h-7 border-0 bg-transparent px-2 text-sm text-foreground hover:bg-accent transition-colors -ml-2";
-
-
-const TIME_INPUT =
- "h-7 w-12 border-0 bg-transparent px-1 text-sm tabular-nums text-foreground rounded-md outline-none focus-visible:ring-0";
-
-interface PropertyRowProps {
- icon?: React.ReactNode;
- children: React.ReactNode;
-}
-
-function PropertyRow({ icon, children }: PropertyRowProps) {
- return (
- <div className="group flex items-center gap-2">
- <span className="inline-flex size-6 shrink-0 items-center justify-center text-muted-foreground">
- {icon}
- </span>
- <div className="flex min-w-0 flex-wrap items-center gap-1">{children}</div>
- </div>
- );
-}
-
-interface RecurringScopeDialogProps {
- open: boolean;
- onOpenChange: (o: boolean) => void;
- onConfirm: (scope: "this" | "following") => void;
- loading?: boolean;
- title: string;
- description: string;
- confirmLabel: string;
- loadingLabel: string;
- confirmVariant?: "default" | "destructive";
-}
-
-function RecurringScopeDialog({
- open,
- onOpenChange,
- onConfirm,
- loading,
- title,
- description,
- confirmLabel,
- loadingLabel,
- confirmVariant = "default",
-}: RecurringScopeDialogProps) {
- const [scope, setScope] = useAtom(useCreateAtom<"this" | "following">("this"));
- useEffect(() => {
- if (open) setScope("this");
- }, [open, setScope]);
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent showCloseButton={false}>
- <DialogHeader>
- <DialogTitle>{title}</DialogTitle>
- <DialogDescription>{description}</DialogDescription>
- </DialogHeader>
- <div className="flex flex-col gap-2 py-1">
- {(
- [
- { value: "this", label: "This event only" },
- { value: "following", label: "This and following events" },
- ] as const
- ).map((opt) => {
- const selected = scope === opt.value;
- return (
- <button
- key={opt.value}
- type="button"
- onClick={() => setScope(opt.value)}
- className={cn(
- "flex items-center gap-2 rounded-md border px-3 py-2 text-left text-sm transition-colors",
- selected
- ? "border-ring bg-accent/40"
- : "border-border/60 hover:bg-accent/30"
- )}
- >
- <span
- className={cn(
- "inline-flex size-4 items-center justify-center rounded-full border",
- selected ? "border-foreground" : "border-border"
- )}
- aria-hidden
- >
- {selected && <span className="size-2 rounded-full bg-foreground" />}
- </span>
- <span>{opt.label}</span>
- </button>
- );
- })}
- </div>
- <DialogFooter>
- <Button
- variant="outline"
- size="sm"
- onClick={() => onOpenChange(false)}
- disabled={loading}
- >
- Cancel
- </Button>
- <Button
- size="sm"
- variant={confirmVariant}
- onClick={() => onConfirm(scope)}
- disabled={loading}
- >
- {loading ? loadingLabel : confirmLabel}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
-
-const DRAG_MIN_WIDTH = 320;
-const DRAG_MAX_WIDTH_RATIO = 0.8;
-const DRAG_DEFAULT_WIDTH = 500;
-
-export function CalendarEventSheet({
- open,
- onOpenChange,
- agents = [],
- event,
- calendarEventId,
- workspaceId,
- readonly,
- defaultDate,
- defaultAgentId,
- submitting,
- saving,
- deleting,
- onCreate,
- onUpdate,
- onDelete,
-}: CalendarEventSheetProps) {
- const owner = useWorkspaceOwner();
- const source = useWorkspaceViewSource(owner, calendarEventId ?? "__none__", open && !!calendarEventId && !event && workspaceId === owner.workspaceId);
- const eventQuery = useQuery({ queryKey: owner.key("calendar", "detail", source.active ? calendarEventId! : "__none__"), enabled: source.active,
- meta: { workspaceView: source.view },
- queryFn: ({ signal }) => getCalendarEvent(calendarEventId!, owner.workspaceId, source.request(signal)),
- });
- const onOpenChangeRef = useRef(onOpenChange);
- useEffect(() => { onOpenChangeRef.current = onOpenChange; });
- useEffect(() => {
- if (!eventQuery.error || eventQuery.isFetching || isAbortError(eventQuery.error)) return;
- try { source.assertActive(); } catch { return; }
- toast.error("Calendar event not found");
- onOpenChangeRef.current(false);
- }, [eventQuery.error, eventQuery.isFetching, source, source.assertActive]);
- const resolvedEvent = event ?? eventQuery.data ?? null;
- const fetchLoading = source.active && eventQuery.isPending;
- const handleOpenChange = onOpenChange;
-
- // --- Resizable drag handle ---
- const { width: sheetWidth, onPointerDown: onDragPointerDown, onPointerMove: onDragPointerMove, onPointerUp: onDragPointerUp } = useSheetResize({
- defaultWidth: DRAG_DEFAULT_WIDTH,
- minWidth: DRAG_MIN_WIDTH,
- maxWidthRatio: DRAG_MAX_WIDTH_RATIO,
- });
-
- const mode = resolvedEvent ? "edit" : "create";
-
- const [agentId, setAgentId] = useAtom(useCreateAtom(""));
- const [title, setTitle] = useAtom(useCreateAtom(""));
- const [description, setDescription] = useAtom(useCreateAtom(""));
- const [dateValue, setDateValue] = useAtom(useCreateAtom<Date>(new Date()));
- const [timeValue, setTimeValue] = useAtom(useCreateAtom<string>("09:00"));
- const [repeatEnabled, setRepeatEnabled] = useAtom(useCreateAtom(false));
- const [repeatCount, setRepeatCount] = useAtom(useCreateAtom("1"));
- const [repeatUnit, setRepeatUnit] = useAtom(useCreateAtom<RepeatUnit>("day"));
-
- const repeat = useMemo(() => {
- if (!repeatEnabled) return "";
- const n = parseInt(repeatCount, 10);
- if (!n || n < 1) return "";
- return formatRepeatInterval(n, repeatUnit);
- }, [repeatEnabled, repeatCount, repeatUnit]);
- const [stopDate, setStopDate] = useAtom(useCreateAtom<Date | null>(null));
- const [scopeOpen, setScopeOpen] = useAtom(useCreateAtom(false));
- const [deleteScopeOpen, setDeleteScopeOpen] = useAtom(useCreateAtom(false));
- const descriptionRef = useRef<HTMLDivElement | null>(null);
- const formRef = useRef<HTMLFormElement | null>(null);
-
- const focusDescription = () => {
- // TipTap renders its ProseMirror root as [contenteditable="true"] inside
- // the wrapper — there's no public ref, so query for it on demand.
- const node = descriptionRef.current?.querySelector<HTMLElement>(
- '[contenteditable="true"]'
- );
- node?.focus();
- };
-
- useEffect(() => {
- if (!open) return;
- if (resolvedEvent) {
- const scheduled = new Date(resolvedEvent.scheduled_at);
- setAgentId(resolvedEvent.agent_id);
- setTitle(resolvedEvent.title);
- setDescription(resolvedEvent.description ?? "");
- setDateValue(scheduled);
- setTimeValue(parseTime(scheduled));
- const parsed = parseRepeatInterval(resolvedEvent.repeat_interval ?? "");
- if (parsed) {
- setRepeatEnabled(true);
- setRepeatCount(String(parsed.count));
- setRepeatUnit(parsed.unit);
- } else {
- setRepeatEnabled(false);
- setRepeatCount("1");
- setRepeatUnit("day");
- }
- setStopDate(
- resolvedEvent.repeat_stop_at ? new Date(resolvedEvent.repeat_stop_at) : null
- );
- } else {
- setAgentId(defaultAgentId || agents[0]?.id || "");
- setTitle("");
- setDescription("");
- setDateValue(defaultDate ?? new Date());
- setTimeValue(nextSlotTime(new Date()));
- setRepeatEnabled(false);
- setRepeatCount("1");
- setRepeatUnit("day");
- setStopDate(null);
- }
- // Seed only on open transition / event id change.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [open, resolvedEvent?.id]);
-
- const dirty = useMemo(() => {
- if (!resolvedEvent) return true;
- const scheduled = new Date(resolvedEvent.scheduled_at);
- return (
- title.trim() !== resolvedEvent.title ||
- normalizedDescription(description) !==
- normalizedDescription(resolvedEvent.description) ||
- agentId !== resolvedEvent.agent_id ||
- dateValue.getFullYear() !== scheduled.getFullYear() ||
- dateValue.getMonth() !== scheduled.getMonth() ||
- dateValue.getDate() !== scheduled.getDate() ||
- timeValue !== parseTime(scheduled) ||
- repeat !== (resolvedEvent.repeat_interval ?? "") ||
- (stopDate ? toYYYYMMDD(stopDate) : null) !==
- (resolvedEvent.repeat_stop_at ? toYYYYMMDD(new Date(resolvedEvent.repeat_stop_at)) : null)
- );
- }, [agentId, title, description, dateValue, timeValue, repeat, stopDate, resolvedEvent]);
-
- function validate(): string | null {
- if (!agentId) return "Select an agent";
- if (!title.trim()) return "Title is required";
- if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(timeValue)) {
- return "Time must be HH:MM in 24-hour format";
- }
- if (repeatEnabled) {
- const n = parseInt(repeatCount, 10);
- if (!n || n < 1) return "Repeat count must be a positive number";
- }
- if (stopDate && !repeat) {
- return "Stop date requires a repeat interval";
- }
- const scheduled = combineDateTime(dateValue, timeValue);
- if (stopDate) {
- const stopEnd = new Date(stopDate);
- stopEnd.setHours(23, 59, 59, 999);
- if (stopEnd < scheduled) {
- return "Stop date must be on or after the first occurrence";
- }
- }
- return null;
- }
-
- const handleCreateSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- const err = validate();
- if (err) return toast.error(err);
- const scheduled = combineDateTime(dateValue, timeValue);
- const desc = description?.trim() || undefined;
- await onCreate?.({
- agent_id: agentId,
- title: title.trim(),
- description: desc,
- scheduled_at: scheduled.toISOString(),
- repeat_interval: repeat || undefined,
- repeat_stop_date: stopDate ? toYYYYMMDD(stopDate) : undefined,
- });
- };
-
- function buildEditPatch(): UpdateCalendarEventRequest | null {
- if (!resolvedEvent) return null;
- const patch: UpdateCalendarEventRequest = {};
- const scheduled = combineDateTime(dateValue, timeValue);
- const scheduledIso = scheduled.toISOString();
- const nextTitle = title.trim();
- if (nextTitle !== resolvedEvent.title) patch.title = nextTitle;
- const nextDesc = normalizedDescription(description);
- const prevDesc = normalizedDescription(resolvedEvent.description);
- if (nextDesc !== prevDesc) patch.description = nextDesc === "" ? null : nextDesc;
- if (agentId !== resolvedEvent.agent_id) patch.agent_id = agentId;
- if (
- scheduledIso !== new Date(resolvedEvent.scheduled_at).toISOString()
- ) {
- patch.scheduled_at = scheduledIso;
- }
- const prevRepeat = resolvedEvent.repeat_interval ?? "";
- if (repeat !== prevRepeat) {
- patch.repeat_interval = repeat === "" ? null : repeat;
- }
- const nextStop = stopDate ? toYYYYMMDD(stopDate) : null;
- const prevStop = resolvedEvent.repeat_stop_at
- ? toYYYYMMDD(new Date(resolvedEvent.repeat_stop_at))
- : null;
- if (nextStop !== prevStop) {
- patch.repeat_stop_date = nextStop;
- }
- if (
- patch.title === undefined &&
- patch.description === undefined &&
- patch.agent_id === undefined &&
- patch.scheduled_at === undefined &&
- patch.repeat_interval === undefined &&
- patch.repeat_stop_date === undefined
- ) {
- return null;
- }
- return patch;
- }
-
- const commitEdit = async (patch: UpdateCalendarEventRequest) => {
- if (!resolvedEvent) return;
- await onUpdate?.(resolvedEvent, patch);
- };
-
- const handleEditSave = async () => {
- if (!resolvedEvent) return;
- const err = validate();
- if (err) return toast.error(err);
- const patch = buildEditPatch();
- if (!patch) return;
- if (resolvedEvent.repeat_interval) {
- setScopeOpen(true);
- return;
- }
- await commitEdit(patch);
- };
-
- const handleScopeConfirm = async (scope: "this" | "following") => {
- const patch = buildEditPatch();
- if (!patch) {
- setScopeOpen(false);
- return;
- }
- patch.scope = scope;
- if (scope === "this" && resolvedEvent?.occurrence_at) {
- patch.occurrence_at = resolvedEvent.occurrence_at;
- }
- await commitEdit(patch);
- setScopeOpen(false);
- };
-
- const handleDeleteClick = () => {
- if (!resolvedEvent) return;
- if (resolvedEvent.repeat_interval) {
- setDeleteScopeOpen(true);
- return;
- }
- onDelete?.(resolvedEvent);
- };
-
- const handleDeleteScopeConfirm = (scope: "this" | "following") => {
- if (!resolvedEvent) return;
- onDelete?.(resolvedEvent, {
- scope,
- occurrence_at: resolvedEvent.occurrence_at ?? undefined,
- });
- setDeleteScopeOpen(false);
- };
-
- // Shift+Enter submits from anywhere in the sheet — including inside the
- // description editor, where TipTap would otherwise insert a hard break.
- // Capture-phase so we beat the editor's keydown handler.
- const handleSubmitShortcut = (e: React.KeyboardEvent) => {
- if (e.key !== "Enter" || !e.shiftKey) return;
- e.preventDefault();
- e.stopPropagation();
- if (mode === "create") {
- formRef.current?.requestSubmit();
- } else {
- void handleEditSave();
- }
- };
-
- // Inline kbd hint rendered inside the submit button. Uses the button's own
- // foreground colour at reduced opacity so it reads on the primary fill in
- // both themes without needing a separate palette.
- const inlineSubmitHint = (
- <Kbd aria-hidden className="mr-1 hidden sm:inline-flex bg-background/20 text-inherit opacity-60">⇧ + ⏎</Kbd>
- );
-
- const a11yTitle = mode === "edit"
- ? title.trim() || "Untitled event"
- : title.trim() || "New calendar event";
-
- const titleInput = readonly ? (
- <p className="w-full px-0 py-1 font-news text-xl sm:text-2xl sm:text-3xl font-medium leading-[1.2] tracking-tight">
- {title || "Untitled event"}
- </p>
- ) : (
- <AutoResizeTextarea
- aria-label="Event title"
- value={title}
- onChange={(e) => setTitle(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- focusDescription();
- }
- }}
- placeholder={mode === "edit" ? "Untitled event" : "New event"}
- autoFocus={mode === "create"}
- rows={1}
- className={cn(
- "w-full rounded-none border-0 bg-transparent px-0 py-1 font-news text-xl sm:text-2xl sm:text-3xl font-medium leading-[1.2] tracking-tight",
- "shadow-none outline-none focus-visible:border-0 focus-visible:ring-0 focus-visible:ring-offset-0",
- "placeholder:text-muted-foreground/40 placeholder:font-normal"
- )}
- />
- );
-
- const properties = readonly ? (
- <div className="flex flex-col gap-2">
- <PropertyRow icon={<CalendarDays className="size-3.5" />}>
- <span className="text-sm text-foreground">
- {dateValue.toLocaleDateString(undefined, { weekday: "short", year: "numeric", month: "short", day: "numeric" })}
- </span>
- </PropertyRow>
- <PropertyRow icon={<CalendarDays className="size-3.5" />}>
- <span className="text-sm text-foreground">{timeValue}</span>
- </PropertyRow>
- <PropertyRow icon={<RepeatIcon className="size-3.5" />}>
- <span className="text-sm text-foreground">
- {repeatEnabled ? `Every ${repeatCount} ${unitLabel(repeatUnit, parseInt(repeatCount, 10) || 1)}` : "Does not repeat"}
- </span>
- </PropertyRow>
- {repeatEnabled && stopDate && (
- <PropertyRow icon={<CalendarOff className="size-3.5" />}>
- <span className="text-sm text-foreground">
- Until {stopDate.toLocaleDateString()}
- </span>
- </PropertyRow>
- )}
- </div>
- ) : (
- <div className="flex flex-col gap-2">
- <PropertyRow icon={<User className="size-3.5" />}>
- <Select
- value={agentId}
- onValueChange={(val) => { if (val) setAgentId(val); }}
- items={agents.map((a) => ({ value: a.id, label: a.name }))}
- >
- <SelectTrigger className="h-7 w-auto border-none bg-transparent px-2 shadow-none text-sm text-foreground hover:bg-accent transition-colors rounded-md">
- <SelectValue placeholder={agents.length === 0 ? "No agents" : "Select agent"} />
- </SelectTrigger>
- <SelectContent>
- {agents.map((a) => (
- <SelectItem key={a.id} value={a.id}>
- {a.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </PropertyRow>
-
- <PropertyRow icon={<CalendarDays className="size-3.5" />}>
- <CalendarDatePicker
- value={dateValue}
- onChange={(d) => setDateValue(d)}
- ariaLabel="Event date"
- hideIcon
- className={GHOST_CONTROL}
- />
- </PropertyRow>
-
- <PropertyRow
- icon={
- <CalendarTimePicker
- value={timeValue}
- onChange={setTimeValue}
- iconOnly
- ariaLabel="Pick time slot"
- className="inline-flex size-6 items-center justify-center rounded-md border-0 bg-transparent p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground group-hover:bg-accent group-hover:text-foreground"
- />
- }
- >
- <input
- type="text"
- inputMode="numeric"
- pattern="([01]\d|2[0-3]):[0-5]\d"
- maxLength={5}
- value={timeValue}
- onChange={(e) => setTimeValue(e.target.value)}
- placeholder="HH:MM"
- aria-label="Event time (24-hour)"
- className={TIME_INPUT}
- />
- </PropertyRow>
-
- <PropertyRow icon={<RepeatIcon className="size-3.5" />}>
- {!repeatEnabled ? (
- <Select
- value=""
- onValueChange={(val) => {
- if (!val) return;
- if (val === "__custom__") {
- setRepeatEnabled(true);
- setRepeatCount("1");
- setRepeatUnit("day");
- } else {
- const parsed = parseRepeatInterval(val);
- if (parsed) {
- setRepeatEnabled(true);
- setRepeatCount(String(parsed.count));
- setRepeatUnit(parsed.unit);
- }
- }
- }}
- items={[
- { value: "", label: "Does not repeat" },
- ...PRESET_INTERVALS.map((o) => ({ value: o.value, label: o.label })),
- { value: "__custom__", label: "Custom…" },
- ]}
- >
- <SelectTrigger className="h-7 w-auto border-none bg-transparent px-2 shadow-none text-sm text-foreground hover:bg-accent transition-colors rounded-md">
- <SelectValue placeholder="Does not repeat" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">Does not repeat</SelectItem>
- {PRESET_INTERVALS.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- <SelectItem value="__custom__">Custom…</SelectItem>
- </SelectContent>
- </Select>
- ) : (
- <div className="-ml-2 flex items-center gap-1">
- <span className="px-1 text-sm text-foreground">Every</span>
- <input
- type="text"
- inputMode="numeric"
- aria-label="Repeat count"
- value={repeatCount}
- onChange={(e) => {
- setRepeatCount(e.target.value.replace(/[^\d]/g, ""));
- }}
- onBlur={() => {
- const n = parseInt(repeatCount, 10);
- if (!n || n < 1) setRepeatCount("1");
- }}
- maxLength={4}
- style={{ width: `${Math.max(1, repeatCount.length) + 1.5}ch` }}
- className="h-7 shrink-0 border-0 bg-transparent px-0 text-center text-sm tabular-nums text-foreground rounded-md outline-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0 transition-colors"
- />
- <Select
- value={repeatUnit}
- onValueChange={(val) => { if (val && isValidUnit(val)) setRepeatUnit(val); }}
- items={REPEAT_UNITS.map((u) => ({ value: u, label: unitLabel(u, parseInt(repeatCount, 10) || 1) }))}
- >
- <SelectTrigger className="h-7 w-auto border-none bg-transparent px-1 shadow-none text-sm text-foreground hover:bg-accent transition-colors rounded-md">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {REPEAT_UNITS.map((u) => (
- <SelectItem key={u} value={u}>
- {unitLabel(u, parseInt(repeatCount, 10) || 1)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <button
- type="button"
- aria-label="Remove repeat"
- onClick={() => {
- setRepeatEnabled(false);
- setRepeatCount("1");
- setRepeatUnit("day");
- setStopDate(null);
- }}
- className="inline-flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
- >
- <X className="size-3" />
- </button>
- </div>
- )}
- </PropertyRow>
-
- {repeat && (
- <PropertyRow icon={<CalendarOff className="size-3.5" />}>
- <CalendarDatePicker
- value={stopDate}
- onChange={(d) => setStopDate(d)}
- onClear={() => setStopDate(null)}
- placeholder="No end date"
- min={dateValue}
- ariaLabel="Stop date"
- hideIcon
- className={GHOST_CONTROL}
- />
- </PropertyRow>
- )}
- </div>
- );
-
- const descriptionEditor = readonly ? (
- description ? (
- <pre className="whitespace-pre-wrap font-sans text-sm">{description}</pre>
- ) : null
- ) : (
- <div ref={descriptionRef}>
- <MarkdownEditor
- key={resolvedEvent?.id ?? "new"}
- contentType="markdown"
- value={description}
- onChange={setDescription}
- placeholder="Add a description…"
- className="markdown"
- minHeight={mode === "edit" ? "10rem" : "8rem"}
- variant="seamless"
- agents={agents}
- />
- </div>
- );
-
- const dragHandle = (
- <SheetResizeHandle onPointerDown={onDragPointerDown} onPointerMove={onDragPointerMove} onPointerUp={onDragPointerUp} />
- );
-
- const sheetBody = fetchLoading ? (
- <SheetBody className="flex items-center justify-center py-12">
- <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
- </SheetBody>
- ) : (
- <SheetBody className="flex flex-col gap-6 px-4 pt-6 pb-4 sm:px-8 sm:pt-10 sm:pb-6">
- {titleInput}
- {properties}
- {descriptionEditor}
- </SheetBody>
- );
-
- return (
- <>
- <Sheet open={open} onOpenChange={handleOpenChange}>
- <SheetContent
- style={{ width: `min(${sheetWidth}px, 100vw)`, maxWidth: "none" }}
- className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border"
- >
- {dragHandle}
- <SheetTitle className="sr-only">{a11yTitle}</SheetTitle>
- {readonly ? (
- <div className="flex flex-1 flex-col min-h-0">
- {sheetBody}
- </div>
- ) : mode === "create" ? (
- <form
- ref={formRef}
- onSubmit={handleCreateSubmit}
- onKeyDownCapture={handleSubmitShortcut}
- className="flex flex-1 flex-col min-h-0"
- >
- {sheetBody}
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => handleOpenChange(false)}
- >
- Cancel
- </Button>
- <Button type="submit" disabled={submitting || !agents.length}>
- {submitting ? "Creating..." : (
- <>
- {inlineSubmitHint}
- Create event
- </>
- )}
- </Button>
- </SheetFooter>
- </form>
- ) : (
- <div
- onKeyDownCapture={handleSubmitShortcut}
- className="flex flex-1 flex-col min-h-0"
- >
- {sheetBody}
- <SheetFooter className="sm:justify-between">
- <Button
- variant="destructive"
- onClick={handleDeleteClick}
- disabled={deleting || saving}
- >
- {deleting ? "Deleting..." : "Delete"}
- </Button>
- <div className="flex items-center gap-2 sm:justify-end">
- <Button
- variant="outline"
- onClick={() => handleOpenChange(false)}
- disabled={saving}
- >
- Cancel
- </Button>
- <Button
- onClick={handleEditSave}
- disabled={saving || !dirty}
- >
- {saving ? "Saving..." : (
- <>
- {inlineSubmitHint}
- Save
- </>
- )}
- </Button>
- </div>
- </SheetFooter>
- </div>
- )}
- </SheetContent>
- </Sheet>
- <RecurringScopeDialog
- open={scopeOpen}
- onOpenChange={setScopeOpen}
- onConfirm={handleScopeConfirm}
- loading={saving}
- title="Update recurring event"
- description="How should this change apply?"
- confirmLabel="Update"
- loadingLabel="Saving..."
- />
- <RecurringScopeDialog
- open={deleteScopeOpen}
- onOpenChange={setDeleteScopeOpen}
- onConfirm={handleDeleteScopeConfirm}
- loading={deleting}
- title="Delete recurring event"
- description="How much of the series should be removed?"
- confirmLabel="Delete"
- loadingLabel="Deleting..."
- confirmVariant="destructive"
- />
- </>
- );
-}
diff --git a/src/web/src/components/calendar/calendar-month-grid.test.ts b/src/web/src/components/calendar/calendar-month-grid.test.ts
deleted file mode 100644
index c65933750..000000000
--- a/src/web/src/components/calendar/calendar-month-grid.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- buildMonthCells,
- agentColor,
- agentDot,
- agentInk,
- dateKey,
- sameDay,
- isTodayMonth,
- stepDate,
-} from "./calendar-month-grid";
-
-describe("buildMonthCells", () => {
- it("always returns 42 cells (six-week grid)", () => {
- for (const [y, m] of [
- [2026, 0],
- [2026, 1],
- [2026, 3],
- [2026, 11],
- [2028, 1], // leap year February
- ] as const) {
- const cells = buildMonthCells(y, m);
- expect(cells).toHaveLength(42);
- }
- });
-
- it("starts on Sunday of the week containing the 1st of the month", () => {
- // April 2026: April 1 is a Wednesday, so the grid should start Sunday March 29.
- const cells = buildMonthCells(2026, 3);
- expect(cells[0]!.date.getDay()).toBe(0);
- expect(cells[0]!.inMonth).toBe(false);
- // First in-month cell should be April 1 at position 3 (Sun, Mon, Tue, Wed).
- expect(cells[3]!.inMonth).toBe(true);
- expect(cells[3]!.date.getDate()).toBe(1);
- expect(cells[3]!.date.getMonth()).toBe(3);
- });
-
- it("marks trailing days as out-of-month", () => {
- const cells = buildMonthCells(2026, 3); // April 2026 (30 days)
- const trailing = cells.filter((c) => !c.inMonth);
- expect(trailing.length).toBeGreaterThan(0);
- // Last cell is always after the 30th in April
- const last = cells[41]!;
- expect(last.inMonth).toBe(false);
- });
-
- it("handles February in a leap year", () => {
- const cells = buildMonthCells(2028, 1); // Feb 2028 is a leap year
- const inMonth = cells.filter((c) => c.inMonth);
- expect(inMonth).toHaveLength(29);
- });
-
- it("handles February in a non-leap year", () => {
- const cells = buildMonthCells(2026, 1); // Feb 2026
- const inMonth = cells.filter((c) => c.inMonth);
- expect(inMonth).toHaveLength(28);
- });
-});
-
-describe("agentColor", () => {
- it("returns a stable class string for the same agent id", () => {
- const a = agentColor("ag_1");
- const b = agentColor("ag_1");
- expect(a).toBe(b);
- });
-
- it("returns different classes for sufficiently different ids", () => {
- const classes = new Set([
- agentColor("ag_a"),
- agentColor("ag_bbb"),
- agentColor("ag_zzz"),
- agentColor("ag_1234567"),
- ]);
- expect(classes.size).toBeGreaterThan(1);
- });
-
- it("first space-separated token is a bg- class (agent filter dot regression)", () => {
- expect(agentColor("ag_1").split(" ")[0]).toMatch(/^bg-/);
- });
-});
-
-describe("agentDot", () => {
- it("is deterministic for the same id", () => {
- expect(agentDot("ag_1")).toBe(agentDot("ag_1"));
- });
-
- it("cycles through the palette", () => {
- const set = new Set([
- agentDot("ag_a"),
- agentDot("ag_bbb"),
- agentDot("ag_zzz"),
- agentDot("ag_1234567"),
- ]);
- expect(set.size).toBeGreaterThan(1);
- });
-
- it("first space-separated token is a bg- class", () => {
- expect(agentDot("ag_1").split(" ")[0]).toMatch(/^bg-/);
- });
-});
-
-describe("agentInk", () => {
- it("is deterministic for the same id", () => {
- expect(agentInk("ag_1")).toBe(agentInk("ag_1"));
- });
-
- it("cycles through the palette", () => {
- const set = new Set([
- agentInk("ag_a"),
- agentInk("ag_bbb"),
- agentInk("ag_zzz"),
- agentInk("ag_1234567"),
- ]);
- expect(set.size).toBeGreaterThan(1);
- });
-
- it("first space-separated token is a text- class", () => {
- expect(agentInk("ag_1").split(" ")[0]).toMatch(/^text-/);
- });
-});
-
-describe("dateKey", () => {
- it("formats to YYYY-MM-DD with zero-padding", () => {
- expect(dateKey(new Date(2026, 0, 5))).toBe("2026-01-05");
- expect(dateKey(new Date(2026, 11, 31))).toBe("2026-12-31");
- });
-});
-
-describe("sameDay", () => {
- it("ignores time-of-day", () => {
- const a = new Date(2026, 3, 17, 9, 0);
- const b = new Date(2026, 3, 17, 23, 59);
- expect(sameDay(a, b)).toBe(true);
- });
- it("false for different days", () => {
- expect(
- sameDay(new Date(2026, 3, 17), new Date(2026, 3, 18))
- ).toBe(false);
- });
-});
-
-describe("isTodayMonth", () => {
- it("true when year+month match the reference", () => {
- const ref = new Date(2026, 3, 17);
- expect(isTodayMonth(2026, 3, ref)).toBe(true);
- });
- it("false when year or month differ", () => {
- const ref = new Date(2026, 3, 17);
- expect(isTodayMonth(2026, 4, ref)).toBe(false);
- expect(isTodayMonth(2025, 3, ref)).toBe(false);
- });
-});
-
-describe("stepDate", () => {
- const base = new Date(2026, 3, 17); // Fri Apr 17 2026
-
- it("ArrowRight → +1 day", () => {
- expect(dateKey(stepDate(base, "ArrowRight")!)).toBe("2026-04-18");
- });
- it("ArrowLeft → -1 day", () => {
- expect(dateKey(stepDate(base, "ArrowLeft")!)).toBe("2026-04-16");
- });
- it("ArrowDown → +7 days", () => {
- expect(dateKey(stepDate(base, "ArrowDown")!)).toBe("2026-04-24");
- });
- it("ArrowUp → -7 days", () => {
- expect(dateKey(stepDate(base, "ArrowUp")!)).toBe("2026-04-10");
- });
- it("Home snaps to Sunday of the same week", () => {
- // Fri Apr 17 2026 → Sun Apr 12
- expect(dateKey(stepDate(base, "Home")!)).toBe("2026-04-12");
- });
- it("End snaps to Saturday of the same week", () => {
- expect(dateKey(stepDate(base, "End")!)).toBe("2026-04-18");
- });
- it("PageDown → next month, clamps day", () => {
- // Jan 31 + PageDown → Feb 28 (2026 not leap)
- const jan31 = new Date(2026, 0, 31);
- expect(dateKey(stepDate(jan31, "PageDown")!)).toBe("2026-02-28");
- });
- it("PageUp → previous month, clamps day", () => {
- // Mar 31 - PageUp → Feb 28
- const mar31 = new Date(2026, 2, 31);
- expect(dateKey(stepDate(mar31, "PageUp")!)).toBe("2026-02-28");
- });
- it("returns null for unrecognized keys", () => {
- expect(stepDate(base, "x")).toBeNull();
- expect(stepDate(base, "Escape")).toBeNull();
- expect(stepDate(base, " ")).toBeNull();
- });
- it("crosses month boundary: Apr 30 + ArrowRight → May 1", () => {
- const apr30 = new Date(2026, 3, 30);
- expect(dateKey(stepDate(apr30, "ArrowRight")!)).toBe("2026-05-01");
- });
-});
diff --git a/src/web/src/components/calendar/calendar-month-grid.tsx b/src/web/src/components/calendar/calendar-month-grid.tsx
deleted file mode 100644
index ac9abf165..000000000
--- a/src/web/src/components/calendar/calendar-month-grid.tsx
+++ /dev/null
@@ -1,323 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import type { CalendarEvent, Agent } from "@alook/shared";
-import { ChevronLeft, ChevronRight, Repeat } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { CalendarDayPopover } from "./calendar-day-popover";
-import { CalendarDatePicker } from "./calendar-date-picker";
-import { agentColor, agentDot, agentInk } from "./calendar-colors";
-
-export function buildMonthCells(year: number, month: number): { date: Date; inMonth: boolean }[] {
- const first = new Date(year, month, 1);
- const startDow = first.getDay();
- const cells: { date: Date; inMonth: boolean }[] = [];
- for (let i = 0; i < 42; i++) {
- const d = new Date(year, month, 1 - startDow + i);
- cells.push({ date: d, inMonth: d.getMonth() === month });
- }
- return cells;
-}
-
-export function dateKey(d: Date): string {
- const y = d.getFullYear();
- const m = String(d.getMonth() + 1).padStart(2, "0");
- const day = String(d.getDate()).padStart(2, "0");
- return `${y}-${m}-${day}`;
-}
-
-export function sameDay(a: Date, b: Date): boolean {
- return (
- a.getFullYear() === b.getFullYear() &&
- a.getMonth() === b.getMonth() &&
- a.getDate() === b.getDate()
- );
-}
-
-export function isTodayMonth(year: number, month: number, ref: Date = new Date()): boolean {
- return ref.getFullYear() === year && ref.getMonth() === month;
-}
-
-/** Returns the new focused date when the given keyboard key is pressed. */
-export function stepDate(
- date: Date,
- key: string
-): Date | null {
- const d = new Date(date.getFullYear(), date.getMonth(), date.getDate());
- switch (key) {
- case "ArrowLeft":
- d.setDate(d.getDate() - 1);
- return d;
- case "ArrowRight":
- d.setDate(d.getDate() + 1);
- return d;
- case "ArrowUp":
- d.setDate(d.getDate() - 7);
- return d;
- case "ArrowDown":
- d.setDate(d.getDate() + 7);
- return d;
- case "Home":
- d.setDate(d.getDate() - d.getDay()); // snap to Sunday
- return d;
- case "End":
- d.setDate(d.getDate() + (6 - d.getDay())); // snap to Saturday
- return d;
- case "PageUp": {
- const targetYear = d.getMonth() === 0 ? d.getFullYear() - 1 : d.getFullYear();
- const targetMonth = (d.getMonth() - 1 + 12) % 12;
- const lastDay = new Date(targetYear, targetMonth + 1, 0).getDate();
- d.setFullYear(targetYear, targetMonth, Math.min(d.getDate(), lastDay));
- return d;
- }
- case "PageDown": {
- const targetYear = d.getMonth() === 11 ? d.getFullYear() + 1 : d.getFullYear();
- const targetMonth = (d.getMonth() + 1) % 12;
- const lastDay = new Date(targetYear, targetMonth + 1, 0).getDate();
- d.setFullYear(targetYear, targetMonth, Math.min(d.getDate(), lastDay));
- return d;
- }
- default:
- return null;
- }
-}
-
-export interface CalendarMonthGridProps {
- year: number;
- month: number; // 0-indexed
- events: CalendarEvent[];
- agents: Agent[];
- loading: boolean;
- focusedDate: Date;
- openPopoverKey: string | null;
- onPopoverChange: (key: string | null) => void;
- onPrev: () => void;
- onNext: () => void;
- onJumpToToday: () => void;
- onJumpToDate: (date: Date) => void;
- onSelectDay: (date: Date) => void;
- onSelectEvent: (event: CalendarEvent) => void;
- headerExtras?: React.ReactNode;
-}
-
-export function CalendarMonthGrid({
- year,
- month,
- events,
- agents,
- loading,
- focusedDate,
- openPopoverKey,
- onPopoverChange,
- onPrev,
- onNext,
- onJumpToToday,
- onJumpToDate,
- onSelectDay,
- onSelectEvent,
- headerExtras,
-}: CalendarMonthGridProps) {
- const cells = buildMonthCells(year, month);
- const monthLabel = new Date(year, month, 1).toLocaleDateString(undefined, {
- month: "long",
- year: "numeric",
- });
-
- const eventsByDay = new Map<string, CalendarEvent[]>();
- for (const ev of events) {
- const key = dateKey(new Date(ev.scheduled_at));
- if (!eventsByDay.has(key)) eventsByDay.set(key, []);
- eventsByDay.get(key)!.push(ev);
- }
-
- const agentNameById = new Map<string, string>();
- for (const a of agents) agentNameById.set(a.id, a.name);
-
- const today = new Date();
- const todayDisabled = isTodayMonth(year, month, today);
-
- return (
- <div className="flex flex-col gap-3">
- <div className="flex items-center justify-between flex-wrap gap-2">
- <div className="flex items-center gap-2">
- <h2 className="text-sm font-medium tabular-nums">{monthLabel}</h2>
- </div>
- <div className="flex items-center gap-2">
- {headerExtras}
- <div className="flex items-center gap-1">
- <button
- type="button"
- aria-label="Previous month"
- onClick={onPrev}
- className="flex size-9 sm:size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
- >
- <ChevronLeft className="size-4" />
- </button>
- <Button
- variant="outline"
- size="sm"
- onClick={onJumpToToday}
- disabled={todayDisabled}
- className="h-7 px-2 text-xs"
- >
- Today
- </Button>
- <button
- type="button"
- aria-label="Next month"
- onClick={onNext}
- className="flex size-9 sm:size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
- >
- <ChevronRight className="size-4" />
- </button>
- </div>
- <CalendarDatePicker
- value={focusedDate}
- onChange={onJumpToDate}
- ariaLabel="Jump to date"
- />
- </div>
- </div>
-
- <div className="grid grid-cols-7 text-[11px] text-muted-foreground">
- {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((d) => (
- <div key={d} className="px-1 sm:px-2 py-1 font-medium">
- <span className="sm:hidden">{d[0]}</span>
- <span className="hidden sm:inline">{d}</span>
- </div>
- ))}
- </div>
-
- <div className="relative">
- {loading && (
- <div
- aria-hidden
- className="pointer-events-none absolute inset-x-0 top-0 z-20 h-0.5 overflow-hidden rounded-t-lg"
- >
- <div className="h-full w-1/3 animate-[calendar-progress_1.2s_ease-in-out_infinite] bg-foreground/40" />
- </div>
- )}
- <div
- role="grid"
- aria-label={`Calendar ${monthLabel}`}
- aria-busy={loading || undefined}
- className={cn(
- "grid grid-cols-7 gap-px rounded-lg border border-border/50 bg-border/40 overflow-hidden transition-opacity",
- loading && "opacity-70"
- )}
- data-testid="calendar-month-grid"
- >
- {cells.map((cell, i) => {
- const key = dateKey(cell.date);
- const dayEvents = eventsByDay.get(key) ?? [];
- const isToday = sameDay(today, cell.date);
- const isFocused = sameDay(focusedDate, cell.date);
- const hiddenCount = Math.max(0, dayEvents.length - 3);
-
- return (
- <div
- role="gridcell"
- key={i}
- data-date={key}
- data-focused={isFocused ? "true" : undefined}
- aria-current={isToday ? "date" : undefined}
- tabIndex={isFocused ? 0 : -1}
- onClick={() => onSelectDay(cell.date)}
- onKeyDown={(e) => {
- // Enter/Space on the cell opens the create dialog when no
- // popover trigger is present; the overflow popover owns Enter
- // if the day has hidden events (handled by the trigger itself).
- if ((e.key === "Enter" || e.key === " ") && e.target === e.currentTarget) {
- e.preventDefault();
- onSelectDay(cell.date);
- }
- }}
- className={cn(
- "group flex min-h-16 sm:min-h-24 flex-col gap-1 p-1 sm:p-2 text-left transition-colors bg-background outline-none cursor-pointer",
- !cell.inMonth && "bg-muted/40 text-muted-foreground",
- isFocused &&
- "ring-2 ring-inset ring-ring/60 relative z-10"
- )}
- >
- <div className="flex items-center justify-between">
- <span
- className={cn(
- "text-[11px] tabular-nums",
- isToday &&
- "flex size-5 items-center justify-center rounded-full bg-foreground text-background font-medium"
- )}
- >
- {cell.date.getDate()}
- </span>
- </div>
- <div className="flex flex-col gap-1 [&>:nth-child(3)]:hidden [&>:nth-child(3)]:sm:flex">
- {dayEvents.slice(0, 3).map((ev) => {
- const isRecurring = Boolean(ev.repeat_interval);
- return (
- <span
- key={`${ev.id}@${ev.occurrence_at}`}
- role="button"
- tabIndex={-1}
- onClick={(e) => {
- e.stopPropagation();
- onSelectEvent(ev);
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.stopPropagation();
- onSelectEvent(ev);
- }
- }}
- className="flex items-center gap-2 rounded-sm px-1 py-1 text-[9px] sm:text-[10px] font-medium text-foreground/85 hover:bg-accent/60 transition-colors cursor-pointer"
- title={`${isRecurring ? "Recurring · " : ""}${ev.title}${
- agentNameById.get(ev.agent_id)
- ? ` — ${agentNameById.get(ev.agent_id)}`
- : ""
- }`}
- >
- {isRecurring ? (
- <Repeat
- aria-hidden
- className={cn(
- "size-2.5 shrink-0",
- agentInk(ev.agent_id)
- )}
- />
- ) : (
- <span
- aria-hidden
- className={cn(
- "size-1.5 shrink-0 rounded-full",
- agentDot(ev.agent_id)
- )}
- />
- )}
- <span className="truncate">{ev.title}</span>
- {ev.collapsed_count != null && ev.collapsed_count > 1 && (
- <span className="shrink-0 text-[9px] text-muted-foreground">&times;{ev.collapsed_count}</span>
- )}
- </span>
- );
- })}
- {hiddenCount > 0 && (
- <CalendarDayPopover
- date={cell.date}
- hiddenCount={hiddenCount}
- events={dayEvents}
- agents={agents}
- open={openPopoverKey === key}
- onOpenChange={(o) => onPopoverChange(o ? key : null)}
- onSelectEvent={onSelectEvent}
- />
- )}
- </div>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- );
-}
-
-export { agentColor, agentDot, agentInk };
diff --git a/src/web/src/components/calendar/calendar-time-picker.tsx b/src/web/src/components/calendar/calendar-time-picker.tsx
deleted file mode 100644
index 4d20f3811..000000000
--- a/src/web/src/components/calendar/calendar-time-picker.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useRef } from "react";
-import { Clock } from "lucide-react";
-import {
- Popover,
- PopoverTrigger,
- PopoverContent,
-} from "@/components/ui/popover";
-import { cn } from "@/lib/utils";
-
-export interface CalendarTimePickerProps {
- /** Value as "HH:MM" (24h). */
- value: string;
- onChange: (value: string) => void;
- className?: string;
- ariaLabel?: string;
- /** Minute step for the scrollable list. Default 30. */
- step?: number;
- /** Render only the clock icon as the trigger (no time label). */
- iconOnly?: boolean;
-}
-
-function pad(n: number) {
- return String(n).padStart(2, "0");
-}
-
-/** Return the time as 24-hour "HH:MM". */
-function formatTimeDisplay(hhmm: string): string {
- const match = /^(\d{2}):(\d{2})$/.exec(hhmm);
- if (!match) return hhmm;
- return `${match[1]}:${match[2]}`;
-}
-
-function buildSlots(step: number): string[] {
- const slots: string[] = [];
- for (let mins = 0; mins < 24 * 60; mins += step) {
- slots.push(`${pad(Math.floor(mins / 60))}:${pad(mins % 60)}`);
- }
- return slots;
-}
-
-export function CalendarTimePicker({
- value,
- onChange,
- className,
- ariaLabel = "Pick a time",
- step = 30,
- iconOnly = false,
-}: CalendarTimePickerProps) {
- const [open, setOpen] = useAtom(useCreateAtom(false));
- const listRef = useRef<HTMLDivElement | null>(null);
- const slots = buildSlots(step);
-
- // Scroll the selected slot into view when the popover opens.
- useEffect(() => {
- if (!open) return;
- const id = setTimeout(() => {
- const el = listRef.current?.querySelector<HTMLElement>(
- `[data-selected="true"]`
- );
- el?.scrollIntoView({ block: "center" });
- }, 0);
- return () => clearTimeout(id);
- }, [open]);
-
- return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- aria-label={ariaLabel}
- className={cn(
- iconOnly
- ? "inline-flex size-8 shrink-0 items-center justify-center rounded-lg border border-input bg-transparent text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
- : "flex h-7 items-center gap-2 rounded-md border border-input bg-transparent px-2 text-xs text-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
- className
- )}
- >
- <Clock className={iconOnly ? "size-3.5" : "size-3.5 opacity-70"} />
- {!iconOnly && (
- <span className="tabular-nums">{formatTimeDisplay(value)}</span>
- )}
- </PopoverTrigger>
- <PopoverContent align="start" className="w-36 p-1">
- <div
- ref={listRef}
- className="flex max-h-60 flex-col overflow-y-auto scrollbar-none"
- role="listbox"
- >
- {slots.map((slot) => {
- const selected = slot === value;
- return (
- <button
- key={slot}
- type="button"
- role="option"
- aria-selected={selected}
- data-selected={selected}
- onClick={() => {
- onChange(slot);
- setOpen(false);
- }}
- className={cn(
- "flex h-7 shrink-0 items-center rounded px-2 text-[11px] tabular-nums transition-colors outline-none",
- "focus-visible:bg-accent",
- selected
- ? "bg-foreground text-background font-medium"
- : "text-foreground hover:bg-accent"
- )}
- >
- {formatTimeDisplay(slot)}
- </button>
- );
- })}
- </div>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/src/web/src/components/calendar/calendar-view-switcher.test.ts b/src/web/src/components/calendar/calendar-view-switcher.test.ts
deleted file mode 100644
index d561a28e1..000000000
--- a/src/web/src/components/calendar/calendar-view-switcher.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { parseCalendarView } from "./calendar-view-switcher";
-
-describe("parseCalendarView", () => {
- it("returns 'month' for null/undefined/empty", () => {
- expect(parseCalendarView(null)).toBe("month");
- expect(parseCalendarView(undefined)).toBe("month");
- expect(parseCalendarView("")).toBe("month");
- });
-
- it("returns 'agenda' when explicitly set", () => {
- expect(parseCalendarView("agenda")).toBe("agenda");
- });
-
- it("returns 'week' when explicitly set", () => {
- expect(parseCalendarView("week")).toBe("week");
- });
-
- it("clamps unknown values to 'month'", () => {
- expect(parseCalendarView("bogus")).toBe("month");
- expect(parseCalendarView("MONTH")).toBe("month");
- expect(parseCalendarView("WEEK")).toBe("month");
- });
-});
diff --git a/src/web/src/components/calendar/calendar-view-switcher.tsx b/src/web/src/components/calendar/calendar-view-switcher.tsx
deleted file mode 100644
index faa1a64f1..000000000
--- a/src/web/src/components/calendar/calendar-view-switcher.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-
-export type CalendarView = "month" | "week" | "agenda";
-
-export function parseCalendarView(raw: string | null | undefined): CalendarView {
- if (raw === "week") return "week";
- if (raw === "agenda") return "agenda";
- return "month";
-}
-
-export interface CalendarViewSwitcherProps {
- view: CalendarView;
- onChange: (view: CalendarView) => void;
-}
-
-export function CalendarViewSwitcher({ view, onChange }: CalendarViewSwitcherProps) {
- return (
- <div
- role="radiogroup"
- aria-label="Calendar view"
- className="inline-flex items-center rounded-md border border-border bg-background p-1"
- >
- {(["month", "week", "agenda"] as const).map((v) => {
- const active = view === v;
- return (
- <button
- key={v}
- type="button"
- role="radio"
- aria-checked={active}
- onClick={() => onChange(v)}
- className={cn(
- "h-6 px-2 rounded text-xs font-medium transition-colors capitalize",
- active
- ? "bg-foreground text-background"
- : "text-muted-foreground hover:text-foreground"
- )}
- >
- {v}
- </button>
- );
- })}
- </div>
- );
-}
diff --git a/src/web/src/components/calendar/calendar-week-grid.tsx b/src/web/src/components/calendar/calendar-week-grid.tsx
deleted file mode 100644
index c9e9332a0..000000000
--- a/src/web/src/components/calendar/calendar-week-grid.tsx
+++ /dev/null
@@ -1,391 +0,0 @@
-"use client";
-
-import { useEffect, useRef, useMemo } from "react";
-import { cn } from "@/lib/utils";
-import type { CalendarEvent, Agent } from "@alook/shared";
-import { ChevronLeft, ChevronRight } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Skeleton } from "@/components/ui/skeleton";
-import { CalendarDatePicker } from "./calendar-date-picker";
-import { agentColor } from "./calendar-colors";
-import {
- getWeekLabel,
- getLocalFractionalHour,
- computeEventLayout,
- type LayoutEvent,
-} from "./calendar-week-utils";
-import { dateKey, sameDay } from "./calendar-month-grid";
-
-const HOUR_HEIGHT_DEFAULT = 48;
-const HOUR_HEIGHT_COMPACT = 36;
-const EVENT_HEIGHT = 24;
-const HOURS = Array.from({ length: 24 }, (_, i) => i);
-
-function formatHourLabel(hour: number, compact: boolean): string {
- if (compact) {
- if (hour === 0) return "12a";
- if (hour < 12) return `${hour}a`;
- if (hour === 12) return "12p";
- return `${hour - 12}p`;
- }
- return `${String(hour).padStart(2, "0")}:00`;
-}
-
-function formatDayHeader(date: Date, compact: boolean): string {
- if (compact) {
- return ["S", "M", "T", "W", "T", "F", "S"][date.getDay()]!;
- }
- const weekday = date.toLocaleDateString("en-US", { weekday: "short" });
- return `${weekday} ${date.getDate()}`;
-}
-
-export interface CalendarWeekGridProps {
- weekStart: Date;
- events: CalendarEvent[];
- agents: Agent[];
- loading: boolean;
- focusedDate: Date;
- compact?: boolean;
- onPrevWeek: () => void;
- onNextWeek: () => void;
- onJumpToToday: () => void;
- onJumpToDate: (date: Date) => void;
- onSelectSlot: (date: Date, hour: number) => void;
- onSelectEvent: (event: CalendarEvent) => void;
- headerExtras?: React.ReactNode;
-}
-
-export function CalendarWeekGrid({
- weekStart,
- events,
- agents,
- loading,
- focusedDate,
- compact = false,
- onPrevWeek,
- onNextWeek,
- onJumpToToday,
- onJumpToDate,
- onSelectSlot,
- onSelectEvent,
- headerExtras,
-}: CalendarWeekGridProps) {
- const hourHeight = compact ? HOUR_HEIGHT_COMPACT : HOUR_HEIGHT_DEFAULT;
- const gutterWidth = compact ? "2.5rem" : "3.5rem";
- const scrollRef = useRef<HTMLDivElement>(null);
- const didAutoScroll = useRef(false);
-
- const today = new Date();
- const weekEnd = new Date(weekStart);
- weekEnd.setDate(weekEnd.getDate() + 6);
-
- const weekLabel = getWeekLabel(weekStart, weekEnd);
- const isCurrentWeek =
- today >= weekStart &&
- today <=
- new Date(
- weekEnd.getFullYear(),
- weekEnd.getMonth(),
- weekEnd.getDate(),
- 23,
- 59,
- 59,
- 999
- );
-
- const days = useMemo(() => {
- const arr: Date[] = [];
- for (let i = 0; i < 7; i++) {
- const d = new Date(weekStart);
- d.setDate(weekStart.getDate() + i);
- arr.push(d);
- }
- return arr;
- }, [weekStart]);
-
- const eventsByDay = useMemo(() => {
- const map = new Map<string, CalendarEvent[]>();
- for (const ev of events) {
- const key = dateKey(new Date(ev.scheduled_at));
- if (!map.has(key)) map.set(key, []);
- map.get(key)!.push(ev);
- }
- return map;
- }, [events]);
-
- const layoutByDay = useMemo(() => {
- const map = new Map<string, LayoutEvent[]>();
- for (const [key, dayEvents] of eventsByDay) {
- map.set(key, computeEventLayout(dayEvents));
- }
- return map;
- }, [eventsByDay]);
-
- const agentNameById = useMemo(() => {
- const map = new Map<string, string>();
- for (const a of agents) map.set(a.id, a.name);
- return map;
- }, [agents]);
-
- useEffect(() => {
- if (didAutoScroll.current) return;
- if (!scrollRef.current) return;
- const now = new Date();
- const scrollTo = Math.max(0, (now.getHours() - 1) * hourHeight);
- scrollRef.current.scrollTop = scrollTo;
- didAutoScroll.current = true;
- }, [hourHeight]);
-
- const currentFractionalHour = useMemo(() => {
- const now = new Date();
- return now.getHours() + now.getMinutes() / 60;
- }, []);
-
- if (loading && events.length === 0) {
- const skelCols = `${gutterWidth} repeat(7, 1fr)`;
- return (
- <div className="flex flex-1 flex-col gap-3 min-h-0">
- <div className="flex items-center justify-between flex-wrap gap-2 shrink-0">
- <Skeleton className="h-5 w-48" />
- <Skeleton className="h-7 w-32" />
- </div>
- <div className="flex-1 min-h-0 flex flex-col rounded-lg border border-border/50 overflow-hidden">
- <div className="border-b border-border/30 shrink-0" style={{ display: "grid", gridTemplateColumns: skelCols }}>
- <div className="h-8" />
- {Array.from({ length: 7 }).map((_, i) => (
- <Skeleton key={i} className="h-5 mx-2 my-2" />
- ))}
- </div>
- <div className="flex-1 min-h-0 overflow-hidden">
- {Array.from({ length: 12 }).map((_, i) => (
- <div
- key={i}
- className="border-b border-border/10"
- style={{ display: "grid", gridTemplateColumns: skelCols, height: hourHeight }}
- >
- <Skeleton className="h-3 w-8 mx-1 my-2" />
- {Array.from({ length: 7 }).map((_, j) => (
- <div key={j} className="relative">
- {i % 4 === j % 3 && (
- <Skeleton
- className="absolute left-1 right-1 top-2 rounded-sm"
- style={{ height: EVENT_HEIGHT }}
- />
- )}
- </div>
- ))}
- </div>
- ))}
- </div>
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex flex-1 flex-col gap-3 min-h-0">
- <div className="flex items-center justify-between flex-wrap gap-2 shrink-0">
- <h2 className="text-sm font-medium tabular-nums">{weekLabel}</h2>
- <div className="flex items-center gap-2">
- {headerExtras}
- <div className="flex items-center gap-1">
- <button
- type="button"
- aria-label="Previous week"
- onClick={onPrevWeek}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
- >
- <ChevronLeft className="size-4" />
- </button>
- <Button
- variant="outline"
- size="sm"
- onClick={onJumpToToday}
- disabled={isCurrentWeek}
- className="h-7 px-2 text-xs"
- >
- Today
- </Button>
- <button
- type="button"
- aria-label="Next week"
- onClick={onNextWeek}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
- >
- <ChevronRight className="size-4" />
- </button>
- </div>
- <CalendarDatePicker
- value={focusedDate}
- onChange={onJumpToDate}
- ariaLabel="Jump to date"
- />
- </div>
- </div>
-
- <div className="relative flex-1 min-h-0 flex flex-col rounded-lg border border-border/50 overflow-hidden">
- {loading && (
- <div
- aria-hidden
- className="pointer-events-none absolute inset-x-0 top-0 z-20 h-0.5 overflow-hidden rounded-t-lg"
- >
- <div className="h-full w-1/3 animate-[calendar-progress_1.2s_ease-in-out_infinite] bg-foreground/40" />
- </div>
- )}
-
- <div
- role="grid"
- aria-label={`Week of ${weekLabel}`}
- aria-busy={loading || undefined}
- className={cn(
- "flex flex-1 flex-col min-h-0 transition-opacity",
- loading && "opacity-70"
- )}
- >
- {/* Sticky day headers */}
- <div
- role="row"
- className="sticky top-0 z-10 border-b border-border/30 bg-background"
- style={{ display: "grid", gridTemplateColumns: `${gutterWidth} repeat(7, 1fr)` }}
- >
- <div role="columnheader" className="h-8" />
- {days.map((day) => {
- const isToday = sameDay(day, today);
- return (
- <div
- key={dateKey(day)}
- role="columnheader"
- aria-current={isToday ? "date" : undefined}
- className={cn(
- "flex items-center justify-center h-8 text-xs font-medium",
- isToday
- ? "text-foreground"
- : "text-muted-foreground"
- )}
- >
- <span
- className={cn(
- "px-2 py-1 rounded-md",
- isToday && "bg-foreground text-background"
- )}
- >
- {formatDayHeader(day, compact)}
- </span>
- </div>
- );
- })}
- </div>
-
- {/* Scrollable time grid */}
- <div
- ref={scrollRef}
- className="flex-1 min-h-0 overflow-y-auto thin-scrollbar"
- >
- <div className="relative" style={{ display: "grid", gridTemplateColumns: `${gutterWidth} repeat(7, 1fr)` }}>
- {/* Time gutter */}
- <div role="rowheader" className="relative">
- {HOURS.map((hour) => (
- <div
- key={hour}
- className="flex items-start justify-end pr-2 text-[10px] text-muted-foreground tabular-nums"
- style={{ height: hourHeight }}
- >
- <span className="-mt-2">
- {hour === 0 ? "" : formatHourLabel(hour, compact)}
- </span>
- </div>
- ))}
- </div>
-
- {/* Day columns */}
- {days.map((day) => {
- const key = dateKey(day);
- const isToday = sameDay(day, today);
- const layoutEvents = layoutByDay.get(key) ?? [];
-
- return (
- <div
- key={key}
- className="relative border-l border-border/20"
- style={{ height: hourHeight * 24 }}
- >
- {/* Hour slots */}
- {HOURS.map((hour) => (
- <div
- key={hour}
- className="absolute inset-x-0 border-t border-border/15 cursor-pointer hover:bg-accent/30 transition-colors"
- style={{ top: hour * hourHeight, height: hourHeight }}
- onClick={() => onSelectSlot(day, hour)}
- />
- ))}
-
- {/* Current time indicator */}
- {isToday && (
- <div
- className="absolute inset-x-0 z-10 pointer-events-none"
- style={{ top: currentFractionalHour * hourHeight }}
- >
- <div className="h-px bg-foreground/40" />
- <div className="absolute -left-1 -top-0.75 size-1.75 rounded-full bg-foreground/40" />
- </div>
- )}
-
- {/* Events */}
- {layoutEvents.map(({ event, columnIndex, columnCount }) => {
- const fracHour = getLocalFractionalHour(
- event.scheduled_at
- );
- const top = fracHour * hourHeight;
- const widthPercent = 100 / columnCount;
- const leftPercent = columnIndex * widthPercent;
- const agentName = agentNameById.get(event.agent_id);
- const timeStr = new Date(
- event.scheduled_at
- ).toLocaleTimeString(undefined, {
- hour: "2-digit",
- minute: "2-digit",
- hour12: false,
- });
-
- return (
- <button
- key={`${event.id}@${event.occurrence_at}`}
- type="button"
- role="button"
- aria-label={`${event.title} at ${timeStr}${agentName ? ` \u2014 ${agentName}` : ""}`}
- onClick={(e) => {
- e.stopPropagation();
- onSelectEvent(event);
- }}
- className={cn(
- "absolute rounded-sm font-medium truncate text-left transition-colors hover:opacity-80 cursor-pointer",
- compact ? "text-[9px] px-1" : "text-[10px] px-2",
- agentColor(event.agent_id)
- )}
- style={{
- top,
- height: EVENT_HEIGHT,
- left: `${leftPercent}%`,
- width: `calc(${widthPercent}% - 2px)`,
- marginLeft: 1,
- lineHeight: `${EVENT_HEIGHT}px`,
- }}
- title={`${event.title}${agentName ? ` \u2014 ${agentName}` : ""}`}
- >
- {event.title}
- {event.collapsed_count != null && event.collapsed_count > 1 && (
- <span className="ml-1 opacity-70">&times;{event.collapsed_count}</span>
- )}
- </button>
- );
- })}
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/calendar/calendar-week-utils.test.ts b/src/web/src/components/calendar/calendar-week-utils.test.ts
deleted file mode 100644
index 8c94ea2db..000000000
--- a/src/web/src/components/calendar/calendar-week-utils.test.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- getWeekStart,
- getWeekEnd,
- getWeekLabel,
- getLocalFractionalHour,
- computeEventLayout,
- weekRangeIso,
-} from "./calendar-week-utils";
-import type { CalendarEvent } from "@alook/shared";
-
-function makeEvent(scheduled_at: string, id = "ev_1"): CalendarEvent {
- return {
- id,
- workspace_id: "ws_1",
- agent_id: "ag_1",
- title: "Test",
- description: null,
- scheduled_at,
- repeat_interval: null,
- repeat_stop_date: null,
- occurrence_at: scheduled_at,
- created_at: scheduled_at,
- updated_at: scheduled_at,
- } as CalendarEvent;
-}
-
-describe("getWeekStart", () => {
- it("returns Sunday for any input date (Thu Apr 23 → Sun Apr 19)", () => {
- const result = getWeekStart(new Date(2026, 3, 23));
- expect(result.getDay()).toBe(0);
- expect(result.getFullYear()).toBe(2026);
- expect(result.getMonth()).toBe(3);
- expect(result.getDate()).toBe(19);
- });
-
- it("returns the same day if already Sunday", () => {
- const sunday = new Date(2026, 3, 19);
- const result = getWeekStart(sunday);
- expect(result.getDay()).toBe(0);
- expect(result.getDate()).toBe(19);
- });
-
- it("handles month boundaries (Wed Apr 1 → Sun Mar 29)", () => {
- const result = getWeekStart(new Date(2026, 3, 1));
- expect(result.getDay()).toBe(0);
- expect(result.getMonth()).toBe(2); // March
- expect(result.getDate()).toBe(29);
- });
-
- it("handles year boundaries (Thu Jan 1, 2026 → Sunday Dec 28, 2025)", () => {
- const result = getWeekStart(new Date(2026, 0, 1));
- expect(result.getDay()).toBe(0);
- expect(result.getFullYear()).toBe(2025);
- expect(result.getMonth()).toBe(11); // December
- expect(result.getDate()).toBe(28);
- });
-
- it("sets time to 00:00:00.000", () => {
- const result = getWeekStart(new Date(2026, 3, 23, 15, 30, 45));
- expect(result.getHours()).toBe(0);
- expect(result.getMinutes()).toBe(0);
- expect(result.getSeconds()).toBe(0);
- expect(result.getMilliseconds()).toBe(0);
- });
-});
-
-describe("getWeekEnd", () => {
- it("returns Saturday 23:59:59.999 for any input", () => {
- const result = getWeekEnd(new Date(2026, 3, 23));
- expect(result.getDay()).toBe(6); // Saturday
- expect(result.getHours()).toBe(23);
- expect(result.getMinutes()).toBe(59);
- expect(result.getSeconds()).toBe(59);
- expect(result.getMilliseconds()).toBe(999);
- });
-
- it("handles month boundaries", () => {
- // Week containing Mar 30, 2026 (Sunday): ends Apr 4 (Saturday)
- const result = getWeekEnd(new Date(2026, 2, 30));
- expect(result.getDay()).toBe(6);
- expect(result.getMonth()).toBe(3); // April
- expect(result.getDate()).toBe(4);
- });
-});
-
-describe("getWeekLabel", () => {
- it("formats same-month weeks", () => {
- const start = new Date(2026, 3, 20); // Apr 20
- const end = new Date(2026, 3, 26); // Apr 26
- expect(getWeekLabel(start, end)).toBe("Apr 20\u201326, 2026");
- });
-
- it("formats cross-month weeks", () => {
- const start = new Date(2026, 2, 30); // Mar 30
- const end = new Date(2026, 3, 5); // Apr 5
- expect(getWeekLabel(start, end)).toBe("Mar 30\u2013Apr 5, 2026");
- });
-
- it("formats cross-year weeks", () => {
- const start = new Date(2025, 11, 28); // Dec 28, 2025
- const end = new Date(2026, 0, 3); // Jan 3, 2026
- expect(getWeekLabel(start, end)).toBe("Dec 28, 2025\u2013Jan 3, 2026");
- });
-});
-
-describe("getLocalFractionalHour", () => {
- it("returns correct fractional hour for full hour", () => {
- const d = new Date(2026, 3, 20, 10, 0, 0);
- expect(getLocalFractionalHour(d.toISOString())).toBe(10);
- });
-
- it("returns correct fractional hour for half-hour", () => {
- const d = new Date(2026, 3, 20, 10, 30, 0);
- expect(getLocalFractionalHour(d.toISOString())).toBe(10.5);
- });
-
- it("returns correct fractional hour for midnight", () => {
- const d = new Date(2026, 3, 20, 0, 0, 0);
- expect(getLocalFractionalHour(d.toISOString())).toBe(0);
- });
-
- it("returns correct fractional hour for 23:45", () => {
- const d = new Date(2026, 3, 20, 23, 45, 0);
- expect(getLocalFractionalHour(d.toISOString())).toBe(23.75);
- });
-});
-
-describe("computeEventLayout", () => {
- it("returns empty array for empty input", () => {
- expect(computeEventLayout([])).toEqual([]);
- });
-
- it("single event gets columnIndex=0, columnCount=1", () => {
- const events = [makeEvent("2026-04-20T10:00:00.000Z")];
- const result = computeEventLayout(events);
- expect(result).toHaveLength(1);
- expect(result[0]!.columnIndex).toBe(0);
- expect(result[0]!.columnCount).toBe(1);
- });
-
- it("non-overlapping events each get columnCount=1", () => {
- const events = [
- makeEvent("2026-04-20T10:00:00.000Z", "ev_1"),
- makeEvent("2026-04-20T14:00:00.000Z", "ev_2"),
- ];
- const result = computeEventLayout(events);
- expect(result).toHaveLength(2);
- expect(result[0]!.columnCount).toBe(1);
- expect(result[1]!.columnCount).toBe(1);
- });
-
- it("2 overlapping events get columnCount=2, indices 0 and 1", () => {
- const events = [
- makeEvent("2026-04-20T10:00:00.000Z", "ev_1"),
- makeEvent("2026-04-20T10:15:00.000Z", "ev_2"),
- ];
- const result = computeEventLayout(events);
- expect(result).toHaveLength(2);
- expect(result[0]!.columnCount).toBe(2);
- expect(result[1]!.columnCount).toBe(2);
- expect(result[0]!.columnIndex).toBe(0);
- expect(result[1]!.columnIndex).toBe(1);
- });
-
- it("3 events where only 2 overlap: correct grouping", () => {
- const events = [
- makeEvent("2026-04-20T10:00:00.000Z", "ev_1"),
- makeEvent("2026-04-20T10:15:00.000Z", "ev_2"),
- makeEvent("2026-04-20T14:00:00.000Z", "ev_3"),
- ];
- const result = computeEventLayout(events);
- expect(result).toHaveLength(3);
- // First two overlap
- const group1 = result.filter((r) => r.event.id === "ev_1" || r.event.id === "ev_2");
- expect(group1[0]!.columnCount).toBe(2);
- expect(group1[1]!.columnCount).toBe(2);
- // Third is separate
- const group2 = result.find((r) => r.event.id === "ev_3")!;
- expect(group2.columnCount).toBe(1);
- expect(group2.columnIndex).toBe(0);
- });
-});
-
-describe("weekRangeIso", () => {
- it("returns correct ISO range for a given Sunday anchor", () => {
- const anchor = new Date(2026, 3, 19); // Sunday Apr 19
- const { from, to } = weekRangeIso(anchor);
- const fromDate = new Date(from);
- const toDate = new Date(to);
- expect(fromDate.getDay()).toBe(0); // Sunday
- expect(toDate.getDay()).toBe(6); // Saturday
- expect(toDate.getHours()).toBe(23);
- expect(toDate.getMinutes()).toBe(59);
- });
-
- it("handles month/year boundaries", () => {
- // Thursday Jan 1, 2026 → week starts Dec 28, 2025
- const anchor = new Date(2026, 0, 1);
- const { from, to } = weekRangeIso(anchor);
- const fromDate = new Date(from);
- expect(fromDate.getFullYear()).toBe(2025);
- expect(fromDate.getMonth()).toBe(11);
- expect(fromDate.getDate()).toBe(28);
- const toDate = new Date(to);
- expect(toDate.getFullYear()).toBe(2026);
- expect(toDate.getMonth()).toBe(0);
- expect(toDate.getDate()).toBe(3);
- });
-});
diff --git a/src/web/src/components/calendar/calendar-week-utils.ts b/src/web/src/components/calendar/calendar-week-utils.ts
deleted file mode 100644
index 98eb2595a..000000000
--- a/src/web/src/components/calendar/calendar-week-utils.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import type { CalendarEvent } from "@alook/shared";
-
-export function getWeekStart(date: Date): Date {
- const d = new Date(date.getFullYear(), date.getMonth(), date.getDate());
- d.setDate(d.getDate() - d.getDay());
- return d;
-}
-
-export function getWeekEnd(date: Date): Date {
- const start = getWeekStart(date);
- const end = new Date(start);
- end.setDate(end.getDate() + 6);
- end.setHours(23, 59, 59, 999);
- return end;
-}
-
-export function getWeekLabel(start: Date, end: Date): string {
- const startMonth = start.toLocaleDateString("en-US", { month: "short" });
- const endMonth = end.toLocaleDateString("en-US", { month: "short" });
- const startYear = start.getFullYear();
- const endYear = end.getFullYear();
-
- if (startYear !== endYear) {
- return `${startMonth} ${start.getDate()}, ${startYear}\u2013${endMonth} ${end.getDate()}, ${endYear}`;
- }
- if (startMonth !== endMonth) {
- return `${startMonth} ${start.getDate()}\u2013${endMonth} ${end.getDate()}, ${endYear}`;
- }
- return `${startMonth} ${start.getDate()}\u2013${end.getDate()}, ${startYear}`;
-}
-
-export function getLocalFractionalHour(iso: string): number {
- const d = new Date(iso);
- return d.getHours() + d.getMinutes() / 60;
-}
-
-export interface LayoutEvent {
- event: CalendarEvent;
- columnIndex: number;
- columnCount: number;
-}
-
-export function computeEventLayout(events: CalendarEvent[]): LayoutEvent[] {
- if (events.length === 0) return [];
-
- const sorted = [...events].sort(
- (a, b) =>
- new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime()
- );
-
- const OVERLAP_THRESHOLD_MS = 30 * 60 * 1000;
-
- const groups: CalendarEvent[][] = [];
- let currentGroup: CalendarEvent[] = [sorted[0]!];
- let groupEnd = new Date(sorted[0]!.scheduled_at).getTime() + OVERLAP_THRESHOLD_MS;
-
- for (let i = 1; i < sorted.length; i++) {
- const evTime = new Date(sorted[i]!.scheduled_at).getTime();
- if (evTime < groupEnd) {
- currentGroup.push(sorted[i]!);
- const newEnd = evTime + OVERLAP_THRESHOLD_MS;
- if (newEnd > groupEnd) groupEnd = newEnd;
- } else {
- groups.push(currentGroup);
- currentGroup = [sorted[i]!];
- groupEnd = evTime + OVERLAP_THRESHOLD_MS;
- }
- }
- groups.push(currentGroup);
-
- const result: LayoutEvent[] = [];
- for (const group of groups) {
- const count = group.length;
- for (let idx = 0; idx < group.length; idx++) {
- result.push({
- event: group[idx]!,
- columnIndex: idx,
- columnCount: count,
- });
- }
- }
-
- return result;
-}
-
-export function weekRangeIso(anchor: Date): { from: string; to: string } {
- const start = getWeekStart(anchor);
- const end = getWeekEnd(anchor);
- return { from: start.toISOString(), to: end.toISOString() };
-}
diff --git a/src/web/src/components/calendar/keyboard.test.ts b/src/web/src/components/calendar/keyboard.test.ts
deleted file mode 100644
index 1b7e5ee75..000000000
--- a/src/web/src/components/calendar/keyboard.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { isTypingTarget } from "./keyboard";
-
-function mkEl(tag: string, contentEditable = false): HTMLElement {
- return {
- tagName: tag.toUpperCase(),
- isContentEditable: contentEditable,
- } as unknown as HTMLElement;
-}
-
-describe("isTypingTarget", () => {
- it("true for INPUT / TEXTAREA / SELECT", () => {
- expect(isTypingTarget(mkEl("input"))).toBe(true);
- expect(isTypingTarget(mkEl("textarea"))).toBe(true);
- expect(isTypingTarget(mkEl("select"))).toBe(true);
- });
-
- it("true for contenteditable elements", () => {
- expect(isTypingTarget(mkEl("div", true))).toBe(true);
- });
-
- it("false for buttons, divs, spans without contenteditable", () => {
- expect(isTypingTarget(mkEl("button"))).toBe(false);
- expect(isTypingTarget(mkEl("div"))).toBe(false);
- expect(isTypingTarget(mkEl("span"))).toBe(false);
- });
-
- it("false for null / missing target", () => {
- expect(isTypingTarget(null)).toBe(false);
- expect(isTypingTarget({} as unknown as EventTarget)).toBe(false);
- });
-});
diff --git a/src/web/src/components/calendar/keyboard.ts b/src/web/src/components/calendar/keyboard.ts
deleted file mode 100644
index d05e92fe1..000000000
--- a/src/web/src/components/calendar/keyboard.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/** Inputs/textareas/contenteditable should not trigger page-level shortcuts. */
-export function isTypingTarget(target: EventTarget | null): boolean {
- if (!target || typeof (target as Element).tagName !== "string") return false;
- const el = target as HTMLElement;
- const tag = el.tagName;
- if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return true;
- if (el.isContentEditable) return true;
- return false;
-}
diff --git a/src/web/src/components/calendar/repeat-interval-utils.test.ts b/src/web/src/components/calendar/repeat-interval-utils.test.ts
deleted file mode 100644
index 62ae4d082..000000000
--- a/src/web/src/components/calendar/repeat-interval-utils.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- parseRepeatInterval,
- formatRepeatInterval,
- unitLabel,
- formatRepeatDisplay,
- isValidUnit,
-} from "./repeat-interval-utils";
-
-describe("parseRepeatInterval", () => {
- it("parses valid intervals", () => {
- expect(parseRepeatInterval("1day")).toEqual({ count: 1, unit: "day" });
- expect(parseRepeatInterval("30min")).toEqual({ count: 30, unit: "min" });
- expect(parseRepeatInterval("2week")).toEqual({ count: 2, unit: "week" });
- expect(parseRepeatInterval("12month")).toEqual({ count: 12, unit: "month" });
- expect(parseRepeatInterval("24hour")).toEqual({ count: 24, unit: "hour" });
- });
-
- it("returns null for invalid inputs", () => {
- expect(parseRepeatInterval("")).toBeNull();
- expect(parseRepeatInterval("weekly")).toBeNull();
- expect(parseRepeatInterval("1year")).toBeNull();
- expect(parseRepeatInterval("0day")).toBeNull();
- expect(parseRepeatInterval("day")).toBeNull();
- expect(parseRepeatInterval("1 day")).toBeNull();
- });
-});
-
-describe("formatRepeatInterval", () => {
- it("composes count and unit", () => {
- expect(formatRepeatInterval(1, "day")).toBe("1day");
- expect(formatRepeatInterval(30, "min")).toBe("30min");
- expect(formatRepeatInterval(12, "month")).toBe("12month");
- });
-
- it("round-trips with parse", () => {
- for (const raw of ["1day", "2week", "30min", "12month", "24hour"]) {
- const parsed = parseRepeatInterval(raw)!;
- expect(formatRepeatInterval(parsed.count, parsed.unit)).toBe(raw);
- }
- });
-});
-
-describe("unitLabel", () => {
- it("returns singular for count=1", () => {
- expect(unitLabel("day", 1)).toBe("day");
- expect(unitLabel("min", 1)).toBe("minute");
- expect(unitLabel("hour", 1)).toBe("hour");
- expect(unitLabel("week", 1)).toBe("week");
- expect(unitLabel("month", 1)).toBe("month");
- });
-
- it("returns plural for count>1", () => {
- expect(unitLabel("day", 3)).toBe("days");
- expect(unitLabel("min", 30)).toBe("minutes");
- expect(unitLabel("hour", 24)).toBe("hours");
- expect(unitLabel("week", 2)).toBe("weeks");
- expect(unitLabel("month", 12)).toBe("months");
- });
-});
-
-describe("formatRepeatDisplay", () => {
- it("formats count=1 without number", () => {
- expect(formatRepeatDisplay("1day")).toBe("Every day");
- expect(formatRepeatDisplay("1hour")).toBe("Every hour");
- expect(formatRepeatDisplay("1week")).toBe("Every week");
- expect(formatRepeatDisplay("1month")).toBe("Every month");
- expect(formatRepeatDisplay("1min")).toBe("Every minute");
- });
-
- it("formats count>1 with number and plural", () => {
- expect(formatRepeatDisplay("2week")).toBe("Every 2 weeks");
- expect(formatRepeatDisplay("30min")).toBe("Every 30 minutes");
- expect(formatRepeatDisplay("12month")).toBe("Every 12 months");
- });
-
- it("returns raw string for unparseable input", () => {
- expect(formatRepeatDisplay("weekly")).toBe("weekly");
- expect(formatRepeatDisplay("")).toBe("");
- });
-});
-
-describe("isValidUnit", () => {
- it("accepts valid units", () => {
- expect(isValidUnit("min")).toBe(true);
- expect(isValidUnit("hour")).toBe(true);
- expect(isValidUnit("day")).toBe(true);
- expect(isValidUnit("week")).toBe(true);
- expect(isValidUnit("month")).toBe(true);
- });
-
- it("rejects invalid units", () => {
- expect(isValidUnit("year")).toBe(false);
- expect(isValidUnit("")).toBe(false);
- expect(isValidUnit("days")).toBe(false);
- });
-});
diff --git a/src/web/src/components/calendar/repeat-interval-utils.ts b/src/web/src/components/calendar/repeat-interval-utils.ts
deleted file mode 100644
index 07dc3e703..000000000
--- a/src/web/src/components/calendar/repeat-interval-utils.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-export type RepeatUnit = "min" | "hour" | "day" | "week" | "month";
-
-export interface ParsedInterval {
- count: number;
- unit: RepeatUnit;
-}
-
-const INTERVAL_RE = /^(\d+)(min|hour|day|week|month)$/;
-
-export function parseRepeatInterval(raw: string): ParsedInterval | null {
- const m = INTERVAL_RE.exec(raw);
- if (!m) return null;
- const count = parseInt(m[1]!, 10);
- if (count < 1) return null;
- return { count, unit: m[2]! as RepeatUnit };
-}
-
-export function formatRepeatInterval(count: number, unit: RepeatUnit): string {
- return `${count}${unit}`;
-}
-
-const UNIT_LABELS: Record<RepeatUnit, [string, string]> = {
- min: ["minute", "minutes"],
- hour: ["hour", "hours"],
- day: ["day", "days"],
- week: ["week", "weeks"],
- month: ["month", "months"],
-};
-
-export function unitLabel(unit: RepeatUnit, count: number): string {
- return count === 1 ? UNIT_LABELS[unit][0] : UNIT_LABELS[unit][1];
-}
-
-export function formatRepeatDisplay(raw: string): string {
- const parsed = parseRepeatInterval(raw);
- if (!parsed) return raw;
- const { count, unit } = parsed;
- if (count === 1) return `Every ${UNIT_LABELS[unit][0]}`;
- return `Every ${count} ${UNIT_LABELS[unit][1]}`;
-}
-
-const VALID_UNITS: Set<string> = new Set([
- "min",
- "hour",
- "day",
- "week",
- "month",
-]);
-
-export function isValidUnit(s: string): s is RepeatUnit {
- return VALID_UNITS.has(s);
-}
-
-export const REPEAT_UNITS: RepeatUnit[] = [
- "min",
- "hour",
- "day",
- "week",
- "month",
-];
-
-export const PRESET_INTERVALS = [
- { value: "1hour", label: "Every hour" },
- { value: "1day", label: "Every day" },
- { value: "1week", label: "Every week" },
- { value: "1month", label: "Every month" },
-] as const;
diff --git a/src/web/src/components/canvas/active-tasks-float.tsx b/src/web/src/components/canvas/active-tasks-float.tsx
deleted file mode 100644
index fbced4fae..000000000
--- a/src/web/src/components/canvas/active-tasks-float.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom, useCreateStore } from "@tanstack/react-store";
-import { useEffect, useCallback } from "react";
-import Link from "next/link";
-import { X } from "lucide-react";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { useIsMobile } from "@/hooks/use-mobile";
-import { AgentAvatar } from "@/components/avatar";
-import type { WorkspaceActiveTask } from "@/lib/api";
-import { relativeTime } from "@/lib/time";
-import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
-
-function TaskRow({
- task,
- slug,
- onOpenChat,
-}: {
- task: WorkspaceActiveTask;
- slug: string;
- onOpenChat: (agentId: string, opts: { conversationId?: string; taskId?: string }) => void;
-}) {
- const isRunning = task.status === "running";
- const href = `/w/${slug}/agents/${task.agent_id}?task=${task.id}&conv=${task.conversation_id}`;
-
- const handleClick = useCallback((e: React.MouseEvent) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
- e.preventDefault();
- onOpenChat(task.agent_id, {
- conversationId: task.conversation_id,
- taskId: task.id,
- });
- }, [task.agent_id, task.conversation_id, task.id, onOpenChat]);
-
- return (
- <a
- href={href}
- onClick={handleClick}
- className="flex items-center gap-2 px-3 py-2 hover:bg-accent/50 transition-colors cursor-pointer rounded-md"
- >
- <div className="relative shrink-0">
- <AgentAvatar name={task.agent?.name} avatarUrl={task.agent?.avatarUrl} seed={task.agent_id} size={24} />
- <span
- className={`absolute -bottom-1 -right-1 size-2 rounded-full ring-2 ring-background ${
- isRunning ? "bg-primary animate-pulse" : "bg-muted-foreground/40"
- }`}
- />
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 leading-tight">
- <span className="text-sm font-medium truncate">
- {task.agent?.name ?? "Agent unavailable"}
- </span>
- <span className="text-xs text-muted-foreground shrink-0">
- #{task.channel}
- </span>
- </div>
- <p className="text-xs text-muted-foreground truncate leading-tight">
- {task.prompt}
- </p>
- </div>
- <span className="text-xs text-muted-foreground whitespace-nowrap shrink-0">
- {relativeTime(task.created_at)}
- </span>
- </a>
- );
-}
-
-export function ActiveTasksFloat() {
- const { activeTaskDetails } = useAgentContext();
- const { slug } = useWorkspace();
- const isMobile = useIsMobile();
- const { openAgentChat } = useAgentChatSheet();
- const [expanded, setExpanded] = useAtom(useCreateAtom(false));
- const seen = useCreateStore<ReadonlySet<string>>(new Set<string>());
-
- const tasks = activeTaskDetails;
- const taskCount = tasks.length;
-
- useEffect(() => {
- if (taskCount === 0) {
- seen.setState(() => new Set<string>());
- return;
- }
- const currentIds = new Set(tasks.map((t) => t.id));
- const hasNewTask = tasks.some((t) => !seen.get().has(t.id));
- if (hasNewTask && !expanded) {
- setExpanded(true);
- }
- seen.setState(() => currentIds);
- }, [tasks, taskCount, expanded, seen, setExpanded]);
-
- if (isMobile || taskCount === 0) return null;
-
- if (!expanded) {
- return (
- <button
- type="button"
- onClick={() => setExpanded(true)}
- className="flex items-center gap-2 px-2 py-1 rounded-full bg-background/90 backdrop-blur-sm ring-1 ring-foreground/8 shadow-sm text-xs font-medium text-muted-foreground hover:text-foreground transition-colors animate-[fade-up_300ms_ease-out_both]"
- >
- <span className="size-1.5 rounded-full bg-primary animate-pulse" />
- {taskCount} active
- </button>
- );
- }
-
- return (
- <div
- role="region"
- aria-label="Active tasks"
- className="w-80 rounded-lg ring-1 ring-foreground/8 shadow-sm bg-background/90 backdrop-blur-sm animate-[fade-up_300ms_ease-out_both]"
- >
- <div className="flex items-center justify-between px-3 py-2 border-b border-border/50">
- <div className="flex items-center gap-2 text-sm font-medium" aria-live="polite">
- <span className="size-1.5 rounded-full bg-primary animate-pulse" />
- <span>
- {taskCount} task{taskCount !== 1 ? "s" : ""} active
- </span>
- </div>
- <button
- type="button"
- aria-label="Collapse tasks panel"
- className="size-6 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- onClick={() => setExpanded(false)}
- >
- <X className="size-3.5" />
- </button>
- </div>
-
- <div className="max-h-75 overflow-y-auto thin-scrollbar py-1">
- {tasks.slice(0, 8).map((task) => (
- <TaskRow key={task.id} task={task} slug={slug} onOpenChat={openAgentChat} />
- ))}
- {taskCount > 8 && (
- <Link
- href={`/w/${slug}/traces?status=active`}
- className="block text-xs text-muted-foreground hover:text-foreground text-center py-2 transition-colors"
- >
- View all {taskCount} tasks
- </Link>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/canvas/agent-chat-sheet.tsx b/src/web/src/components/canvas/agent-chat-sheet.tsx
deleted file mode 100644
index 2ae9ea082..000000000
--- a/src/web/src/components/canvas/agent-chat-sheet.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-"use client";
-
-import React from "react";
-import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle";
-import { useRouter } from "next/navigation";
-import {
- Sheet,
- SheetClose,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@/components/ui/sheet";
-import { toAlookAddress } from "@alook/shared";
-import type { Agent } from "@alook/shared";
-import { AnimatedAvatar } from "@/components/avatar";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { ChannelBar } from "@/components/channel-bar";
-import { AgentChatView } from "@/components/agent-chat/agent-chat-view";
-import { ArrowUpRight, XIcon } from "lucide-react";
-import { Button, buttonVariants } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-
-interface AgentChatSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- /**
- * Raw agent id — known before the resolved `agent` object. The chat body
- * mounts on this so it paints from cache without waiting for the agents array
- * to load (Part 2-b). The `agent` object is only used for the header.
- */
- agentId: string | null;
- agent: Agent | null;
- targetConvId?: string | null;
- scrollToTaskId?: string | null;
- scrollToMessageId?: string | null;
-}
-
-const MIN_WIDTH = 320;
-const MAX_WIDTH_RATIO = 0.8;
-const DEFAULT_WIDTH = 480;
-
-export function AgentChatSheet({ open, onOpenChange, agentId, agent, targetConvId, scrollToTaskId, scrollToMessageId }: AgentChatSheetProps) {
- const { runtimes, activeTaskCounts } = useAgentContext();
- const { slug } = useWorkspace();
- const router = useRouter();
- const { width, onPointerDown, onPointerMove, onPointerUp } = useSheetResize({
- defaultWidth: DEFAULT_WIDTH,
- minWidth: MIN_WIDTH,
- maxWidthRatio: MAX_WIDTH_RATIO,
- });
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent
- side="right"
- showCloseButton={false}
- style={{ width: `min(${width}px, 100vw)`, maxWidth: "none" }}
- className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border flex flex-col"
- >
- <SheetResizeHandle onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />
-
- {/* Top-right action buttons */}
- <div className="absolute top-3 right-3 z-10 flex items-center gap-1">
- {agentId && (() => {
- const params = new URLSearchParams();
- if (scrollToTaskId) params.set("task", scrollToTaskId);
- if (scrollToMessageId) params.set("msg", scrollToMessageId);
- if (targetConvId) params.set("conv", targetConvId);
- const qs = params.toString();
- const fullPageUrl = `/w/${slug}/agents/${agentId}${qs ? `?${qs}` : ""}`;
- return (
- <Tooltip>
- <TooltipTrigger
- render={
- <a
- href={fullPageUrl}
- onClick={(e) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey) return;
- e.preventDefault();
- onOpenChange(false);
- router.push(fullPageUrl);
- }}
- className={buttonVariants({ variant: "ghost", size: "icon-sm" })}
- />
- }
- >
- <ArrowUpRight />
- </TooltipTrigger>
- <TooltipContent>Open full page</TooltipContent>
- </Tooltip>
- );
- })()}
- <SheetClose
- render={<Button variant="ghost" size="icon-sm" />}
- >
- <XIcon />
- <span className="sr-only">Close</span>
- </SheetClose>
- </div>
-
- <SheetHeader>
- <div className="flex items-center gap-3 pr-16">
- {agent && (() => {
- const rt = runtimes.find((r) => r.id === agent.runtime_id);
- const isOnline = rt?.status === "online";
- const isWorking = !!isOnline && (activeTaskCounts[agent.id] ?? 0) > 0;
- return <AnimatedAvatar seed={agent.id} avatarUrl={agent.avatar_url} size={28} className="shrink-0 rounded-lg" isHovered={false} isWorking={isWorking} />;
- })()}
- <div className="flex items-baseline gap-2 min-w-0">
- <SheetTitle className="truncate shrink-0">
- {agent?.name ?? "Chat"}
- </SheetTitle>
- {agent?.email_handle && (
- <span className="text-xs text-muted-foreground truncate">{toAlookAddress(agent.email_handle)}</span>
- )}
- </div>
- </div>
- </SheetHeader>
-
- {!targetConvId && (
- <div className="px-4 pb-2">
- <ChannelBar />
- </div>
- )}
-
- {agentId && (
- <div className="flex-1 overflow-hidden flex flex-col">
- <AgentChatView
- key={`${agentId}-${targetConvId ?? ""}`}
- agentId={agentId}
- targetConvId={targetConvId}
- scrollToTaskId={scrollToTaskId}
- scrollToMessageId={scrollToMessageId}
- />
- </div>
- )}
- </SheetContent>
- </Sheet>
- );
-}
diff --git a/src/web/src/components/canvas/agent-node.tsx b/src/web/src/components/canvas/agent-node.tsx
deleted file mode 100644
index ca871c3dd..000000000
--- a/src/web/src/components/canvas/agent-node.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { memo } from "react";
-import { Handle, Position, type NodeProps } from "@xyflow/react";
-import type { Agent, AgentRuntime } from "@alook/shared";
-import { AgentPreviewCard } from "@/components/agent-preview-card";
-import { cn } from "@/lib/utils";
-
-export interface AgentNodeData {
- agent: Agent;
- runtimes: AgentRuntime[];
- activeTaskCount: number;
- slug: string;
- index: number;
- [key: string]: unknown;
-}
-
-const handleClass =
- "!opacity-0 !size-3 !bg-muted-foreground/40 !rounded-full group-hover:!opacity-100 hover:!bg-primary hover:!scale-125 !transition-all !border-none";
-
-function AgentNodeInner({ data, selected, dragging }: NodeProps) {
- const { agent, runtimes, activeTaskCount, index } = data as unknown as AgentNodeData;
-
- const rt = runtimes.find((r: AgentRuntime) => r.id === agent.runtime_id);
- const isOnline = rt?.status === "online";
- const [isHovered, setIsHovered] = useAtom(useCreateAtom(false));
-
- return (
- <div
- data-agent-node-id={agent.id}
- data-agent-working={activeTaskCount > 0 ? "true" : "false"}
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={() => setIsHovered(false)}
- className={cn(
- "bg-background rounded-xl ring-1 ring-foreground/8 shadow-sm transition-[box-shadow,ring-color,opacity,transform] duration-200 py-3 px-4 group",
- selected && "ring-2 ring-primary/20 shadow-md",
- !selected && "hover:ring-foreground/15 hover:shadow-md",
- dragging && "shadow-lg scale-[1.02] cursor-grabbing",
- )}
- style={{ animationDelay: `${index * 60}ms` }}
- >
- <Handle type="source" id="right" position={Position.Right} className={handleClass} />
- <Handle type="source" id="left" position={Position.Left} className={handleClass} />
- <Handle type="source" id="top" position={Position.Top} className={handleClass} />
- <Handle type="source" id="bottom" position={Position.Bottom} className={handleClass} />
-
- <Handle type="target" id="target-right" position={Position.Right} className={handleClass} />
- <Handle type="target" id="target-left" position={Position.Left} className={handleClass} />
- <Handle type="target" id="target-top" position={Position.Top} className={handleClass} />
- <Handle type="target" id="target-bottom" position={Position.Bottom} className={handleClass} />
-
- <AgentPreviewCard
- agent={agent}
- isOnline={isOnline}
- activeTaskCount={activeTaskCount}
- variant="compact"
- isHovered={isHovered}
- />
- </div>
- );
-}
-
-export const AgentNode = memo(AgentNodeInner);
diff --git a/src/web/src/components/canvas/auto-layout.test.ts b/src/web/src/components/canvas/auto-layout.test.ts
deleted file mode 100644
index ff463af02..000000000
--- a/src/web/src/components/canvas/auto-layout.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { describe, it, expect } from "vitest";
-import type { Node, Edge } from "@xyflow/react";
-import { getAutoLayout } from "./auto-layout";
-
-function makeNodes(count: number): Node[] {
- return Array.from({ length: count }, (_, i) => ({
- id: `n${i}`,
- type: "agent",
- position: { x: 0, y: 0 },
- data: {},
- }));
-}
-
-describe("getAutoLayout", () => {
- it("assigns valid positions with no overlaps", () => {
- const nodes = makeNodes(4);
- const edges: Edge[] = [
- { id: "e1", source: "n0", target: "n1" },
- { id: "e2", source: "n1", target: "n2" },
- { id: "e3", source: "n2", target: "n3" },
- ];
- const laid = getAutoLayout(nodes, edges);
- expect(laid).toHaveLength(4);
- for (const n of laid) {
- expect(typeof n.position.x).toBe("number");
- expect(typeof n.position.y).toBe("number");
- expect(Number.isFinite(n.position.x)).toBe(true);
- expect(Number.isFinite(n.position.y)).toBe(true);
- }
- // No two nodes should have the same exact position
- const posKeys = new Set(laid.map((n) => `${n.position.x},${n.position.y}`));
- expect(posKeys.size).toBe(4);
- });
-
- it("positions nodes in a row when there are no edges", () => {
- const nodes = makeNodes(3);
- const laid = getAutoLayout(nodes, []);
- expect(laid).toHaveLength(3);
- // All nodes should have valid positions, not stacked at origin
- const posKeys = new Set(laid.map((n) => `${n.position.x},${n.position.y}`));
- expect(posKeys.size).toBeGreaterThanOrEqual(1);
- for (const n of laid) {
- expect(Number.isFinite(n.position.x)).toBe(true);
- expect(Number.isFinite(n.position.y)).toBe(true);
- }
- });
-});
diff --git a/src/web/src/components/canvas/auto-layout.ts b/src/web/src/components/canvas/auto-layout.ts
deleted file mode 100644
index 8a00198e9..000000000
--- a/src/web/src/components/canvas/auto-layout.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import dagre from "@dagrejs/dagre";
-import type { Node, Edge } from "@xyflow/react";
-
-export type LayoutType = "star" | "tree" | "flow";
-
-const NODE_WIDTH = 280;
-const NODE_HEIGHT = 100;
-
-export function getAutoLayout(
- nodes: Node[],
- edges: Edge[],
- layout: LayoutType = "tree",
-): Node[] {
- if (nodes.length === 0) return nodes;
-
- switch (layout) {
- case "star":
- return getConcentricLayout(nodes, edges);
- case "tree":
- return getDagreLayout(nodes, edges, "TB");
- case "flow":
- return getDagreLayout(nodes, edges, "LR");
- }
-}
-
-function getDagreLayout(
- nodes: Node[],
- edges: Edge[],
- direction: "LR" | "TB",
-): Node[] {
- const g = new dagre.graphlib.Graph();
- g.setDefaultEdgeLabel(() => ({}));
- g.setGraph({
- rankdir: direction,
- nodesep: 80,
- ranksep: 180,
- marginx: 40,
- marginy: 40,
- });
-
- for (const node of nodes) {
- g.setNode(node.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
- }
- for (const edge of edges) {
- g.setEdge(edge.source, edge.target);
- }
-
- dagre.layout(g);
-
- return nodes.map((node) => {
- const pos = g.node(node.id);
- return {
- ...node,
- position: {
- x: pos.x - NODE_WIDTH / 2,
- y: pos.y - NODE_HEIGHT / 2,
- },
- };
- });
-}
-
-function getConcentricLayout(nodes: Node[], edges: Edge[]): Node[] {
- if (nodes.length === 1) {
- return [{ ...nodes[0], position: { x: -NODE_WIDTH / 2, y: -NODE_HEIGHT / 2 } }];
- }
-
- const degree: Record<string, number> = {};
- const outDegree: Record<string, number> = {};
- const adjacency: Record<string, Set<string>> = {};
-
- for (const node of nodes) {
- degree[node.id] = 0;
- outDegree[node.id] = 0;
- adjacency[node.id] = new Set();
- }
-
- for (const edge of edges) {
- if (degree[edge.source] !== undefined && degree[edge.target] !== undefined) {
- degree[edge.source]++;
- degree[edge.target]++;
- outDegree[edge.source]++;
- adjacency[edge.source].add(edge.target);
- adjacency[edge.target].add(edge.source);
- }
- }
-
- const sortedNodes = [...nodes].sort((a, b) => {
- const degDiff = (degree[b.id] ?? 0) - (degree[a.id] ?? 0);
- if (degDiff !== 0) return degDiff;
- const outDiff = (outDegree[b.id] ?? 0) - (outDegree[a.id] ?? 0);
- if (outDiff !== 0) return outDiff;
- return a.id.localeCompare(b.id);
- });
-
- const centerId = sortedNodes[0].id;
- const centerNeighbors = adjacency[centerId] ?? new Set();
-
- const firstRing: Node[] = [];
- const outerRing: Node[] = [];
-
- for (const node of nodes) {
- if (node.id === centerId) continue;
- if (centerNeighbors.has(node.id)) {
- firstRing.push(node);
- } else {
- outerRing.push(node);
- }
- }
-
- const FIRST_RADIUS = 250;
- const OUTER_RADIUS = 450;
-
- const positioned: Record<string, { x: number; y: number }> = {};
- positioned[centerId] = { x: -NODE_WIDTH / 2, y: -NODE_HEIGHT / 2 };
-
- for (let i = 0; i < firstRing.length; i++) {
- const angle = (2 * Math.PI * i) / firstRing.length - Math.PI / 2;
- positioned[firstRing[i].id] = {
- x: Math.cos(angle) * FIRST_RADIUS - NODE_WIDTH / 2,
- y: Math.sin(angle) * FIRST_RADIUS - NODE_HEIGHT / 2,
- };
- }
-
- for (let i = 0; i < outerRing.length; i++) {
- const angle = (2 * Math.PI * i) / outerRing.length - Math.PI / 2;
- positioned[outerRing[i].id] = {
- x: Math.cos(angle) * OUTER_RADIUS - NODE_WIDTH / 2,
- y: Math.sin(angle) * OUTER_RADIUS - NODE_HEIGHT / 2,
- };
- }
-
- return nodes.map((node) => ({
- ...node,
- position: positioned[node.id] ?? { x: 0, y: 0 },
- }));
-}
diff --git a/src/web/src/components/canvas/link-edge.tsx b/src/web/src/components/canvas/link-edge.tsx
deleted file mode 100644
index 8634d9184..000000000
--- a/src/web/src/components/canvas/link-edge.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { memo, useCallback } from "react";
-import {
- getSmoothStepPath,
- EdgeLabelRenderer,
- type EdgeProps,
-} from "@xyflow/react";
-
-interface LinkEdgeData {
- instruction?: string;
- onEdgeClick?: (edgeId: string) => void;
- [key: string]: unknown;
-}
-
-function LinkEdgeInner({
- id,
- sourceX,
- sourceY,
- targetX,
- targetY,
- sourcePosition,
- targetPosition,
- selected,
- data,
-}: EdgeProps) {
- const { instruction, onEdgeClick } = (data ?? {}) as LinkEdgeData;
- const [hovered, setHovered] = useAtom(useCreateAtom(false));
-
- const [edgePath, labelX, labelY] = getSmoothStepPath({
- sourceX,
- sourceY,
- targetX,
- targetY,
- sourcePosition,
- targetPosition,
- borderRadius: 16,
- });
-
- const strokeColor = selected
- ? "var(--color-primary)"
- : hovered
- ? "var(--color-muted-foreground)"
- : "var(--color-border)";
- const strokeWidth = selected || hovered ? 2 : 1.5;
-
- const handleLabelClick = useCallback((e: React.MouseEvent) => {
- e.stopPropagation();
- onEdgeClick?.(id);
- }, [onEdgeClick, id]);
-
- const hasInstruction = !!instruction && instruction !== "" && instruction !== "<p></p>";
-
- return (
- <>
- <path
- d={edgePath}
- fill="none"
- stroke={strokeColor}
- strokeWidth={strokeWidth}
- style={{ transition: "stroke 150ms, stroke-width 150ms" }}
- onMouseEnter={() => setHovered(true)}
- onMouseLeave={() => setHovered(false)}
- />
- <EdgeLabelRenderer>
- <button
- type="button"
- style={{
- position: "absolute",
- transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
- pointerEvents: "auto",
- }}
- className={`text-[11px] leading-tight bg-background/90 px-2 py-1 rounded-md truncate cursor-pointer transition-colors italic ${hovered ? "text-muted-foreground" : "text-muted-foreground/40"
- }`}
- onClick={handleLabelClick}
- onMouseEnter={() => setHovered(true)}
- onMouseLeave={() => setHovered(false)}
- >
- {hasInstruction ? "edit" : "define"}
- </button>
- </EdgeLabelRenderer>
- </>
- );
-}
-
-export const LinkEdge = memo(LinkEdgeInner);
diff --git a/src/web/src/components/canvas/link-sidecar.tsx b/src/web/src/components/canvas/link-sidecar.tsx
deleted file mode 100644
index b5f21b510..000000000
--- a/src/web/src/components/canvas/link-sidecar.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useCallback, useRef } from "react";
-import type { Agent, AgentLink } from "@alook/shared";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@/components/ui/sheet";
-import { Button } from "@/components/ui/button";
-import { MarkdownEditor } from "@/components/ui/markdown-editor";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { Trash2 } from "lucide-react";
-import { AgentAvatar } from "@/components/avatar";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-
-const DEBOUNCE_MS = 500;
-
-interface LinkSidecarProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- link: AgentLink | null;
- agents: Agent[];
- onSave: (id: string, instruction: string) => void;
- onDelete: (id: string) => void;
-}
-
-export function LinkSidecar({
- open,
- onOpenChange,
- link,
- agents,
- onSave,
- onDelete,
-}: LinkSidecarProps) {
- const [instruction, setInstruction] = useAtom(useCreateAtom(""));
- const [confirmOpen, setConfirmOpen] = useAtom(useCreateAtom(false));
-
- const instructionRef = useRef(instruction);
- useEffect(() => {
- instructionRef.current = instruction;
- }, [instruction]);
- const savedInstructionRef = useRef("");
- const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const linkRef = useRef(link);
- useEffect(() => {
- linkRef.current = link;
- }, [link]);
-
- const sourceAgent = agents.find((a) => a.id === link?.source_agent_id);
- const targetAgent = agents.find((a) => a.id === link?.target_agent_id);
-
- useEffect(() => {
- if (link) {
- setInstruction(link.instruction);
- savedInstructionRef.current = link.instruction;
- }
- }, [link, setInstruction]);
-
- const flushSave = useCallback(() => {
- const current = instructionRef.current;
- const l = linkRef.current;
- if (!l || current === savedInstructionRef.current) return;
- savedInstructionRef.current = current;
- onSave(l.id, current);
- }, [onSave]);
-
- const scheduleSave = useCallback(() => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- debounceRef.current = setTimeout(flushSave, DEBOUNCE_MS);
- }, [flushSave]);
-
- const handleChange = useCallback(
- (next: string) => {
- setInstruction(next);
- scheduleSave();
- },
- [scheduleSave, setInstruction],
- );
-
- useEffect(() => {
- return () => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- flushSave();
- };
- }, [flushSave]);
-
- const handleOpenChange = useCallback(
- (nextOpen: boolean) => {
- if (!nextOpen) {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- flushSave();
- }
- onOpenChange(nextOpen);
- },
- [onOpenChange, flushSave],
- );
-
- const handleDeleteConfirm = useCallback(() => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- if (link) onDelete(link.id);
- setConfirmOpen(false);
- }, [link, onDelete, setConfirmOpen]);
-
- const renderAvatar = (agent: Agent | undefined) => {
- if (!agent) return null;
- return <AgentAvatar name={agent.name} avatarUrl={agent.avatar_url} seed={agent.id} size={32} className="rounded-xl" />;
- };
-
- return (
- <Sheet open={open} onOpenChange={handleOpenChange}>
- <SheetContent
- side="right"
- showCloseButton={false}
- className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border data-[side=right]:sm:max-w-md"
- >
- <SheetTitle className="sr-only">
- Edit relationship between {sourceAgent?.name} and {targetAgent?.name}
- </SheetTitle>
-
- <SheetHeader className="border-b px-4 py-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <div className="flex items-center">
- {renderAvatar(sourceAgent)}
- <div className="-ml-2 ring-2 ring-background rounded-xl">
- {renderAvatar(targetAgent)}
- </div>
- </div>
- </div>
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- className="text-destructive hover:text-destructive hover:bg-destructive/10"
- onClick={() => setConfirmOpen(true)}
- />
- }
- >
- <Trash2 className="size-4" />
- </TooltipTrigger>
- <TooltipContent>Remove connection</TooltipContent>
- </Tooltip>
- </div>
- <p className="text-sm font-medium">
- {sourceAgent?.name ?? "Agent"} and {targetAgent?.name ?? "Agent"}
- </p>
- <p className="text-xs font-medium text-muted-foreground tracking-wide mb-2">
- use @ to mention agent
- </p>
- </SheetHeader>
-
- <div className="flex-1 overflow-y-auto thin-scrollbar px-4 py-4">
- <MarkdownEditor
- variant="seamless"
- contentType="markdown"
- placeholder="Describe how these agents should collaborate. This instruction is shared with both agents when they receive tasks."
- value={instruction}
- onChange={handleChange}
- minHeight="12rem"
- agents={agents}
- />
- </div>
- </SheetContent>
-
- <ConfirmDialog
- open={confirmOpen}
- onOpenChange={setConfirmOpen}
- title="Remove connection"
- description={`This will remove the connection between "${sourceAgent?.name ?? "Agent"}" and "${targetAgent?.name ?? "Agent"}".`}
- onConfirm={handleDeleteConfirm}
- />
- </Sheet>
- );
-}
diff --git a/src/web/src/components/canvas/upcoming-events-float.tsx b/src/web/src/components/canvas/upcoming-events-float.tsx
deleted file mode 100644
index 7d6266b19..000000000
--- a/src/web/src/components/canvas/upcoming-events-float.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useQuery } from "@tanstack/react-query";
-import Link from "next/link";
-import { CalendarDays, X } from "lucide-react";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceOwner, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { useIsMobile } from "@/hooks/use-mobile";
-import { AgentAvatar } from "@/components/avatar";
-import { listCalendarEvents } from "@/lib/api";
-
-
-interface AgentEventSummary {
- agentId: string;
- agentName: string;
- avatarUrl: string | null;
- count: number;
-}
-
-export function UpcomingEventsFloat() {
- const { agents } = useAgentContext();
- const owner = useWorkspaceOwner();
- const { slug, workspaceId } = owner;
- const isMobile = useIsMobile();
- const [expanded, setExpanded] = useAtom(useCreateAtom(false));
-
- const agentMap = new Map(agents.map((a) => [a.id, a]));
-
- const query = useQuery({ queryKey: owner.key("calendar", "upcoming"), refetchInterval: 60_000,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => {
- const now = new Date(), todayEnd = new Date(now);
- todayEnd.setHours(23, 59, 59, 999);
- return listCalendarEvents(workspaceId, { from: now.toISOString(), to: todayEnd.toISOString() }, options);
- }, signal),
- select: (rows) => rows.filter((event) => new Date(event.occurrence_at).getTime() >= Date.now()),
- });
- const events = query.data ?? [];
-
-
- const count = events.reduce((sum, e) => sum + (e.collapsed_count ?? 1), 0);
-
- if (isMobile || count === 0) return null;
-
- // Group events by agent
- const agentSummaries: AgentEventSummary[] = [];
- const countByAgent = new Map<string, number>();
- for (const e of events) {
- countByAgent.set(e.agent_id, (countByAgent.get(e.agent_id) ?? 0) + (e.collapsed_count ?? 1));
- }
- for (const [agentId, eventCount] of countByAgent) {
- const agent = agentMap.get(agentId);
- agentSummaries.push({
- agentId,
- agentName: agent?.name ?? "Agent unavailable",
- avatarUrl: agent?.avatar_url ?? null,
- count: eventCount,
- });
- }
- agentSummaries.sort((a, b) => b.count - a.count);
-
- if (!expanded) {
- return (
- <button
- type="button"
- onClick={() => setExpanded(true)}
- className="flex items-center gap-2 px-2 py-1 rounded-full bg-background/90 backdrop-blur-sm ring-1 ring-foreground/8 shadow-sm text-xs font-medium text-muted-foreground hover:text-foreground transition-colors animate-[fade-up_300ms_ease-out_both]"
- >
- <CalendarDays className="size-3" />
- {count} upcoming
- </button>
- );
- }
-
- return (
- <div
- role="region"
- aria-label="Upcoming events"
- className="w-72 rounded-lg ring-1 ring-foreground/8 shadow-sm bg-background/90 backdrop-blur-sm animate-[fade-up_300ms_ease-out_both]"
- >
- <div className="flex items-center justify-between px-3 py-2 border-b border-border/50">
- <div className="flex items-center gap-2 text-sm font-medium">
- <CalendarDays className="size-3.5 text-muted-foreground" />
- <span>{count} events today</span>
- </div>
- <button
- type="button"
- aria-label="Collapse events panel"
- className="size-6 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- onClick={() => setExpanded(false)}
- >
- <X className="size-3.5" />
- </button>
- </div>
-
- <div className="max-h-52 overflow-y-auto thin-scrollbar py-1">
- {agentSummaries.map((summary) => (
- <Link
- key={summary.agentId}
- href={`/w/${slug}/calendar`}
- className="flex items-center gap-2 px-3 py-2 hover:bg-accent/50 transition-colors cursor-pointer rounded-md"
- >
- <AgentAvatar name={summary.agentName} avatarUrl={summary.avatarUrl} seed={summary.agentId} size={22} />
- <span className="flex-1 text-sm truncate">{summary.agentName}</span>
- <span className="text-xs text-muted-foreground shrink-0">
- {summary.count} event{summary.count !== 1 ? "s" : ""}
- </span>
- </Link>
- ))}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/channel-bar.tsx b/src/web/src/components/channel-bar.tsx
deleted file mode 100644
index c12631cac..000000000
--- a/src/web/src/components/channel-bar.tsx
+++ /dev/null
@@ -1,435 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useRef, useEffect, useCallback } from "react";
-import { Plus, Pencil, Trash2, Loader2 } from "lucide-react";
-import {
- DndContext,
- closestCenter,
- PointerSensor,
- useSensor,
- useSensors,
- type DragEndEvent,
-} from "@dnd-kit/core";
-import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
-import {
- SortableContext,
- horizontalListSortingStrategy,
- useSortable,
- arrayMove,
-} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { useChannel } from "@/contexts/channel-context";
-import { cn } from "@/lib/utils";
-import { isImeConfirming } from "@/lib/ime";
-import {
- ContextMenu,
- ContextMenuContent,
- ContextMenuItem,
- ContextMenuSeparator,
- ContextMenuTrigger,
-} from "@/components/ui/context-menu";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { Button } from "@/components/ui/button";
-import { toast } from "sonner";
-
-export function ChannelBar() {
- const {
- channels,
- activeChannel,
- loading,
- creating: channelCreating,
- deleting: channelDeleting,
- renaming: channelRenaming,
- setActiveChannel,
- createChannel,
- renameChannel,
- deleteChannel,
- reorderChannels,
- } = useChannel();
-
- const [creating, setCreating] = useAtom(useCreateAtom(false));
- const [renamingId, setRenamingId] = useAtom(useCreateAtom<string | null>(null));
- const [deletingId, setDeletingId] = useAtom(useCreateAtom<string | null>(null));
-
- const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
- );
-
- const defaultChannel = channels.find((c) => c.name === "default");
- const nonDefaultChannels = channels.filter((c) => c.name !== "default");
-
- const handleDragEnd = useCallback(
- (event: DragEndEvent) => {
- const { active, over } = event;
- if (!over || active.id === over.id) return;
-
- const oldIndex = nonDefaultChannels.findIndex((c) => c.id === active.id);
- const newIndex = nonDefaultChannels.findIndex((c) => c.id === over.id);
- if (oldIndex === -1 || newIndex === -1) return;
-
- const reordered = arrayMove(nonDefaultChannels, oldIndex, newIndex);
- reorderChannels(reordered.map((c) => c.id));
- },
- [nonDefaultChannels, reorderChannels],
- );
-
- if (loading) {
- return (
- <div className="h-8 flex items-center gap-2 px-2 mb-1 shrink-0">
- <div className="h-5 w-14 rounded-md bg-muted animate-pulse" />
- <div className="h-5 w-12 rounded-md bg-muted animate-pulse" />
- <div className="h-5 w-16 rounded-md bg-muted animate-pulse" />
- </div>
- );
- }
-
- return (
- <div className="h-8 flex items-center gap-2 px-4 mb-1 min-w-0 overflow-x-auto thin-scrollbar shrink-0">
- {defaultChannel && (
- <ChannelPill
- id={defaultChannel.id}
- name={defaultChannel.name}
- active={defaultChannel.name === activeChannel}
- deleting={false}
- isDeleting={false}
- onSelect={() => setActiveChannel(defaultChannel.name)}
- onRename={() => {}}
- onDeleteRequest={() => {}}
- onDeleteCancel={() => {}}
- onDeleteConfirm={() => {}}
- />
- )}
-
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- modifiers={[restrictToHorizontalAxis]}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={nonDefaultChannels.map((c) => c.id)}
- strategy={horizontalListSortingStrategy}
- >
- {nonDefaultChannels.map((ch) =>
- renamingId === ch.id ? (
- <RenameInput
- key={ch.id}
- currentName={ch.name}
- loading={channelRenaming === ch.id}
- onSave={async (name) => {
- try {
- await renameChannel(ch.id, name);
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to rename");
- }
- setRenamingId(null);
- }}
- onCancel={() => setRenamingId(null)}
- />
- ) : (
- <SortableChannelPill
- key={ch.id}
- id={ch.id}
- name={ch.name}
- active={ch.name === activeChannel}
- deleting={deletingId === ch.id}
- isDeleting={channelDeleting === ch.id}
- disabled={renamingId !== null}
- onSelect={() => setActiveChannel(ch.name)}
- onRename={() => setRenamingId(ch.id)}
- onDeleteRequest={() => setDeletingId(ch.id)}
- onDeleteCancel={() => setDeletingId(null)}
- onDeleteConfirm={async () => {
- try {
- await deleteChannel(ch.id);
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to delete");
- }
- setDeletingId(null);
- }}
- />
- ),
- )}
- </SortableContext>
- </DndContext>
-
- {creating ? (
- <CreateInput
- loading={channelCreating}
- onSave={async (name) => {
- try {
- await createChannel(name);
- setActiveChannel(name);
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to create");
- }
- setCreating(false);
- }}
- onCancel={() => setCreating(false)}
- />
- ) : (
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- onClick={() => setCreating(true)}
- className="h-5 w-5 rounded-md border border-dashed border-muted-foreground/30 text-muted-foreground hover:border-foreground/50 hover:text-foreground hover:bg-accent transition-colors duration-200 inline-flex items-center justify-center cursor-pointer shrink-0"
- />
- }
- >
- <Plus className="size-3" />
- </TooltipTrigger>
- <TooltipContent side="bottom">
- Add New Chatting Channel
- </TooltipContent>
- </Tooltip>
- )}
-
- {/* Spacer to preserve right padding when content overflows */}
- <div className="shrink-0 w-1" />
- </div>
- );
-}
-
-function SortableChannelPill({
- id,
- disabled,
- ...props
-}: {
- id: string;
- name: string;
- active: boolean;
- deleting: boolean;
- isDeleting: boolean;
- disabled: boolean;
- onSelect: () => void;
- onRename: () => void;
- onDeleteRequest: () => void;
- onDeleteCancel: () => void;
- onDeleteConfirm: () => void;
-}) {
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- isDragging,
- } = useSortable({ id, disabled });
-
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- opacity: isDragging ? 0.5 : 1,
- };
-
- return (
- <div
- ref={setNodeRef}
- style={style}
- className="inline-flex items-center"
- {...attributes}
- {...listeners}
- >
- <ChannelPill id={id} {...props} />
- </div>
- );
-}
-
-function ChannelPill({
- name,
- active,
- deleting,
- isDeleting,
- onSelect,
- onRename,
- onDeleteRequest,
- onDeleteCancel,
- onDeleteConfirm,
-}: {
- id: string;
- name: string;
- active: boolean;
- deleting: boolean;
- isDeleting: boolean;
- onSelect: () => void;
- onRename: () => void;
- onDeleteRequest: () => void;
- onDeleteCancel: () => void;
- onDeleteConfirm: () => void;
-}) {
- const isDefault = name === "default";
-
- const pillClasses = cn(
- "h-5 px-2 rounded-md text-[11px] font-medium inline-flex items-center gap-1 cursor-pointer select-none transition-colors duration-200 shrink-0",
- "active:translate-y-px focus-visible:ring-2 focus-visible:ring-ring/50 outline-none",
- active
- ? "bg-secondary text-foreground shadow-sm ring-1 ring-foreground/5"
- : "text-muted-foreground hover:text-foreground hover:bg-accent"
- );
-
- if (isDefault) {
- return (
- <button onClick={onSelect} className={pillClasses}>
- #{name}
- </button>
- );
- }
-
- return (
- <Tooltip>
- <Popover open={deleting} onOpenChange={(open) => { if (!open) onDeleteCancel(); }}>
- <ContextMenu>
- <TooltipTrigger
- render={
- <ContextMenuTrigger className="inline-flex" />
- }
- >
- <PopoverTrigger
- render={
- <button onClick={onSelect} className={pillClasses} />
- }
- >
- #{name}
- </PopoverTrigger>
- </TooltipTrigger>
- <ContextMenuContent>
- <ContextMenuItem onClick={onRename}>
- <Pencil className="size-3.5 mr-2" />
- Rename
- </ContextMenuItem>
- <ContextMenuSeparator />
- <ContextMenuItem
- onClick={onDeleteRequest}
- className="text-destructive focus:text-destructive"
- >
- <Trash2 className="size-3.5 mr-2" />
- Delete
- </ContextMenuItem>
- </ContextMenuContent>
- </ContextMenu>
- <PopoverContent className="w-auto p-3" align="start">
- <p className="text-sm mb-3">
- Delete &ldquo;{name}&rdquo;? Its conversations will be removed.
- </p>
- <div className="flex gap-2 justify-end">
- <Button variant="ghost" size="sm" onClick={onDeleteCancel} disabled={isDeleting}>
- Cancel
- </Button>
- <Button variant="destructive" size="sm" onClick={onDeleteConfirm} disabled={isDeleting}>
- {isDeleting && <Loader2 className="size-3 animate-spin mr-1" />}
- Delete
- </Button>
- </div>
- </PopoverContent>
- </Popover>
- <TooltipContent side="bottom">Right-click for options</TooltipContent>
- </Tooltip>
- );
-}
-
-function CreateInput({
- loading,
- onSave,
- onCancel,
-}: {
- loading?: boolean;
- onSave: (name: string) => void;
- onCancel: () => void;
-}) {
- const ref = useRef<HTMLInputElement>(null);
- const savedRef = useRef(false);
- const [value, setValue] = useAtom(useCreateAtom(""));
-
- useEffect(() => {
- ref.current?.focus();
- }, []);
-
- const handleSubmit = useCallback(() => {
- const trimmed = value.trim();
- if (trimmed) {
- savedRef.current = true;
- onSave(trimmed);
- } else {
- onCancel();
- }
- }, [value, onSave, onCancel]);
-
- return (
- <span className="inline-flex items-center gap-1 shrink-0">
- <input
- ref={ref}
- value={value}
- onChange={(e) => setValue(e.target.value)}
- onKeyDown={(e) => {
- if (isImeConfirming(e)) return;
- if (e.key === "Enter") { e.preventDefault(); handleSubmit(); }
- else if (e.key === "Escape") onCancel();
- }}
- onBlur={() => { if (!savedRef.current) onCancel(); }}
- disabled={loading}
- placeholder="name..."
- className="h-5 w-24 px-2 rounded-md text-[11px] bg-transparent border border-input focus:border-ring focus:ring-2 focus:ring-ring/50 placeholder:text-muted-foreground/50 outline-none shrink-0 disabled:opacity-50"
- />
- {loading && <Loader2 className="size-3 animate-spin text-muted-foreground" />}
- </span>
- );
-}
-
-function RenameInput({
- currentName,
- loading,
- onSave,
- onCancel,
-}: {
- currentName: string;
- loading?: boolean;
- onSave: (name: string) => void;
- onCancel: () => void;
-}) {
- const ref = useRef<HTMLInputElement>(null);
- const savedRef = useRef(false);
- const readyRef = useRef(false);
- const [value, setValue] = useAtom(useCreateAtom(currentName));
-
- useEffect(() => {
- const id = requestAnimationFrame(() => {
- ref.current?.focus();
- ref.current?.select();
- readyRef.current = true;
- });
- return () => cancelAnimationFrame(id);
- }, []);
-
- const handleSubmit = useCallback(() => {
- const trimmed = value.trim();
- if (trimmed && trimmed !== currentName) {
- savedRef.current = true;
- onSave(trimmed);
- } else {
- onCancel();
- }
- }, [value, currentName, onSave, onCancel]);
-
- return (
- <input
- ref={ref}
- value={value}
- onChange={(e) => setValue(e.target.value)}
- onKeyDown={(e) => {
- if (isImeConfirming(e)) return;
- if (e.key === "Enter") { e.preventDefault(); handleSubmit(); }
- else if (e.key === "Escape") onCancel();
- }}
- onBlur={() => { if (readyRef.current && !savedRef.current) onCancel(); }}
- disabled={loading}
- className="h-5 w-24 px-2 rounded-md text-[11px] bg-transparent border border-input focus:border-ring focus:ring-2 focus:ring-ring/50 outline-none shrink-0 disabled:opacity-50"
- />
- );
-}
diff --git a/src/web/src/components/chat-primitives/index.ts b/src/web/src/components/chat-primitives/index.ts
deleted file mode 100644
index c9debb136..000000000
--- a/src/web/src/components/chat-primitives/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export { MessageBubble } from "./message-bubble";
-export type { BubblePosition } from "./message-bubble";
-
-export { MessageCluster, AVATAR_SIZE } from "./message-cluster";
diff --git a/src/web/src/components/chat-primitives/message-bubble.tsx b/src/web/src/components/chat-primitives/message-bubble.tsx
index 7f044cce8..f00ec45b2 100644
--- a/src/web/src/components/chat-primitives/message-bubble.tsx
+++ b/src/web/src/components/chat-primitives/message-bubble.tsx
@@ -2,7 +2,7 @@ import type { ReactNode, HTMLAttributes } from "react";
import { cn } from "@/lib/utils";
type BubbleVariant = "agent" | "user";
-export type BubblePosition = "first" | "middle" | "last" | "single";
+type BubblePosition = "first" | "middle" | "last" | "single";
interface MessageBubbleProps
extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
diff --git a/src/web/src/components/community/community-avatar-shape.contract.test.ts b/src/web/src/components/community/community-avatar-shape.contract.test.ts
index 3c269ddc8..91ac4cfde 100644
--- a/src/web/src/components/community/community-avatar-shape.contract.test.ts
+++ b/src/web/src/components/community/community-avatar-shape.contract.test.ts
@@ -28,11 +28,4 @@ describe("community avatar shape contract", () => {
expect(picker).toContain('aria-label="Choose bot avatar"')
})
- it("leaves the workspace agent picker rounded-square", () => {
- const picker = readWeb("src/components/avatar/avatar-picker-dialog.tsx")
-
- expect(picker).toContain('className="block size-20 overflow-hidden rounded-2xl"')
- expect(picker).not.toContain("rounded-full")
- expect(picker).toContain('data-testid="workspace-agent-avatar-preview"')
- })
})
diff --git a/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
index 048a8b9dd..86c4b4a5d 100644
--- a/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
+++ b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
@@ -34,14 +34,8 @@ describe("Community attachment download surface contract", () => {
}
})
- it("routes Artifact, email, remote images and share images through the product owner", () => {
+ it("routes remote images and share images through the product owner", () => {
for (const path of [
- "src/components/agent-chat/artifact-sheet.tsx",
- "src/components/agent-chat/image-lightbox.tsx",
- "src/components/agent-chat/email-event-sheet.tsx",
- "src/components/artifact-content-renderer.tsx",
- "src/components/issues/issue-attachment-list.tsx",
- "src/app/(app)/w/[slug]/agents/[id]/email/page.tsx",
"src/components/remote-image/remote-markdown-image.tsx",
]) {
const text = source(path)
@@ -56,16 +50,6 @@ describe("Community attachment download surface contract", () => {
expect(share).not.toMatch(/createElement\(["']a["']\)/)
})
- it("keeps all artifact click controllers on the shared download routing", () => {
- for (const path of ["src/components/agent-chat/agent-chat-view.tsx", "src/app/(app)/w/[slug]/issues/page.tsx"]) {
- const text = source(path)
- expect(text).toContain("useArtifactClick(workspaceId, previewArtifact")
- expect(text).not.toMatch(/window\.open\(getArtifactUrl/)
- }
- expect(source("src/components/agent-chat/agent-chat-view.tsx")).toContain("const handleIssueArtifactClick = useArtifactClick")
- expect(source("src/components/issues/issue-sheet.tsx")).toContain("<IssueAttachmentList")
- })
-
it("renders representative message and thread attachments without a surface callback", () => {
for (const path of [
"src/components/community/messages/message.tsx",
diff --git a/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx b/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx
index e405c7d8a..4535c6e46 100644
--- a/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx
+++ b/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx
@@ -50,13 +50,13 @@ describe("actual account deletion original root settlement", () => {
sdk.id = "B"; await act(async () => { view.rerender(<App id="B" deletion={false} />) }); await act(async () => { await vi.advanceTimersByTimeAsync(0) }); vi.useRealTimers()
await waitFor(() => expect(registry.accountId).toBe("B"))
await waitFor(() => expect(restoring).toBe(false))
- const current = registry, b = createIdbPersister("B"), bApplication = createIdbPersister("B", "application")
- await act(async () => { await b.restoreClient(); }) ; await act(async () => { await bApplication.restoreClient() })
+ const current = registry, b = createIdbPersister("B"), legacyB = "alook:qc:v3:B:application:client"
+ await act(async () => { await b.restoreClient(); }) ; await act(async () => { await set(legacyB, "retained legacy B") })
act(() => current.queryClient.setQueryData(["private", "B"], { current: "B" }))
await act(async () => { await set("alook:qc:v2:A:client", "late original A"); }) ; await act(async () => { await set("alook:qc:v2:B:client", "current B") })
await act(async () => request.resolve(Response.json({ ok: true })))
await waitFor(async () => expect(await get("alook:qc:v2:A:client")).toBeUndefined())
- expect(await get("alook:qc:v2:B:client")).toBe("current B"); expect(await b.isCurrent()).toBe(true); expect(await bApplication.isCurrent()).toBe(true)
+ expect(await get("alook:qc:v2:B:client")).toBe("current B"); expect(await b.isCurrent()).toBe(true); expect(await get(legacyB)).toBe("retained legacy B")
expect(original.runtime.lifecycle.get().active).toBe(false); expect(original.queryClient.getQueryCache().getAll()).toHaveLength(0)
expect(current.runtime.lifecycle.get().active).toBe(true); expect(current.queryClient.getQueryData(["private", "B"])).toEqual({ current: "B" })
expect(request.signal.aborted).toBe(true); expect(onDeleted).not.toHaveBeenCalled(); expect(replace).not.toHaveBeenCalled(); expect(reload).not.toHaveBeenCalled()
diff --git a/src/web/src/components/connect-machine-steps.dom.test.ts b/src/web/src/components/connect-machine-steps.dom.test.ts
deleted file mode 100644
index bc7396945..000000000
--- a/src/web/src/components/connect-machine-steps.dom.test.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { createElement, cloneElement, type PropsWithChildren, type ReactElement } from "react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen } from "@/test/react-dom-harness";
-
-const mocks = vi.hoisted(() => ({
- clipboardWrite: vi.fn(),
- toastSuccess: vi.fn(),
-}));
-
-vi.mock("@/lib/utils", () => ({
- cliCmd: () => "npx @alook/cli",
-}));
-
-vi.mock("sonner", () => ({
- toast: { success: mocks.toastSuccess },
-}));
-
-vi.mock("@/components/ui/button", () => ({
- Button: ({ children, size: _size, ...props }: PropsWithChildren<Record<string, unknown>>) =>
- createElement("button", props, children),
-}));
-
-vi.mock("@/components/ui/tooltip", () => ({
- Tooltip: ({ children }: PropsWithChildren) => createElement("div", {}, children),
- TooltipTrigger: ({ children, render: trigger }:
- PropsWithChildren<{ render?: ReactElement }>) =>
- cloneElement(trigger ?? createElement("div"), {}, children),
- TooltipContent: ({ children }: PropsWithChildren) => createElement("span", {}, children),
-}));
-
-import { ConnectMachineSteps } from "./connect-machine-steps";
-
-describe("ConnectMachineSteps", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.stubGlobal("navigator", { clipboard: { writeText: mocks.clipboardWrite } });
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it("keeps the supported terminal registration path available", () => {
- render(createElement(ConnectMachineSteps, {
- generatedToken: "machine_token",
- generatingToken: false,
- onGenerateToken: vi.fn(),
- registered: false,
- daemonOnline: false,
- }));
-
- const command = "npx @alook/cli register --token machine_token";
- expect(screen.getAllByRole("button")).toHaveLength(1);
- expect(screen.getByText(command)).toBeVisible();
-
- fireEvent.click(screen.getByRole("button", { name: "Copy Command" }));
- expect(mocks.clipboardWrite).toHaveBeenCalledWith(command);
- expect(mocks.toastSuccess).toHaveBeenCalledWith("Copied to clipboard");
- });
-});
diff --git a/src/web/src/components/connect-machine-steps.tsx b/src/web/src/components/connect-machine-steps.tsx
deleted file mode 100644
index 9c0e0f6dc..000000000
--- a/src/web/src/components/connect-machine-steps.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-"use client";
-
-import { useRef, useEffect } from "react";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { Check } from "lucide-react";
-import { toast } from "sonner";
-import { cliCmd } from "@/lib/utils";
-
-export function ConnectMachineSteps({
- generatedToken,
- generatingToken,
- onGenerateToken,
- registered,
- daemonOnline,
-}: {
- generatedToken: string;
- generatingToken: boolean;
- onGenerateToken: () => void;
- registered: boolean;
- daemonOnline: boolean;
-}) {
- const hasTriggered = useRef(false);
-
- const connected = registered && daemonOnline;
-
- useEffect(() => {
- if (!generatedToken && !generatingToken && !hasTriggered.current) {
- hasTriggered.current = true;
- onGenerateToken();
- }
- }, [generatedToken, generatingToken, onGenerateToken]);
-
- const command = `${cliCmd()} register --token ${generatedToken}`;
-
- const copyRegister = () => {
- navigator.clipboard.writeText(command);
- toast.success("Copied to clipboard");
- };
-
- if (connected) {
- return (
- <div className="flex items-center gap-2 text-sm text-emerald-600">
- <Check className="size-4" />
- Computer connected
- </div>
- );
- }
-
- return (
- <div className="space-y-3">
- <p className="text-sm font-medium">Connect a computer</p>
- <p className="text-xs text-muted-foreground">
- Run this in your terminal to link your machine.
- </p>
- {generatingToken ? (
- <div className="rounded-md bg-muted p-2 font-mono text-xs text-muted-foreground animate-pulse">
- Generating token...
- </div>
- ) : generatedToken ? (
- <div className="space-y-2">
- <Tooltip>
- <TooltipTrigger
- render={
- <div
- className="rounded-md bg-muted p-2 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors break-all"
- onClick={copyRegister}
- />
- }
- >
- {command}
- </TooltipTrigger>
- <TooltipContent>Click to copy</TooltipContent>
- </Tooltip>
- <Button size="sm" onClick={copyRegister} className="w-full">
- Copy Command
- </Button>
- </div>
- ) : null}
- </div>
- );
-}
diff --git a/src/web/src/components/custom-email-form.tsx b/src/web/src/components/custom-email-form.tsx
deleted file mode 100644
index bc7f6b60f..000000000
--- a/src/web/src/components/custom-email-form.tsx
+++ /dev/null
@@ -1,507 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useCallback } from "react";
-import { useMutation, useQuery, type Query } from "@tanstack/react-query";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import {
- Sheet,
- SheetTrigger,
- SheetContent,
- SheetTitle,
- SheetBody,
-} from "@/components/ui/sheet";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { cn } from "@/lib/utils";
-import {
- listEmailAccounts,
- createEmailAccount,
- deleteEmailAccount,
- syncEmailAccount,
-} from "@/lib/api";
-import type { AgentEmailAccount, CreateEmailAccountRequest } from "@alook/shared";
-import {
- Loader2, Mail, RefreshCw, AlertCircle, CheckCircle2,
- ChevronRight, XIcon, CircleHelp,
-} from "lucide-react";
-import { toast } from "sonner";
-import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, runWorkspaceRequest } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { isAbortError } from "@/lib/errors";
-import {
- type CustomEmailErrors,
- hasCustomEmailErrors,
- validateCustomEmailFields,
-} from "@/lib/form-validation";
-import { trackCustomEmailConnected } from "@/lib/analytics";
-
-const PRESETS: Record<string, { imapHost: string; imapPort: number; smtpHost: string; smtpPort: number }> = {
- Gmail: { imapHost: "imap.gmail.com", imapPort: 993, smtpHost: "smtp.gmail.com", smtpPort: 587 },
- Outlook: { imapHost: "outlook.office365.com", imapPort: 993, smtpHost: "smtp.office365.com", smtpPort: 587 },
- Yahoo: { imapHost: "imap.mail.yahoo.com", imapPort: 993, smtpHost: "smtp.mail.yahoo.com", smtpPort: 587 },
-};
-
-export type CustomEmailData = CreateEmailAccountRequest;
-
-interface Props {
- agentId?: string;
- workspaceId: string;
- onDataChange?: (data: CustomEmailData | null) => void;
- getDataRef?: React.MutableRefObject<(() => CustomEmailData | null) | null>;
-}
-
-function useEmailFields() {
- const [emailAddress, setEmailAddress] = useAtom(useCreateAtom(""));
- const [displayName, setDisplayName] = useAtom(useCreateAtom(""));
- const [imapHost, setImapHost] = useAtom(useCreateAtom(""));
- const [imapPort, setImapPort] = useAtom(useCreateAtom(993));
- const [imapUsername, setImapUsername] = useAtom(useCreateAtom(""));
- const [imapPassword, setImapPassword] = useAtom(useCreateAtom(""));
- const [smtpHost, setSmtpHost] = useAtom(useCreateAtom(""));
- const [smtpPort, setSmtpPort] = useAtom(useCreateAtom(587));
- const [smtpUsername, setSmtpUsername] = useAtom(useCreateAtom(""));
- const [smtpPassword, setSmtpPassword] = useAtom(useCreateAtom(""));
-
- function applyPreset(name: string) {
- const preset = PRESETS[name];
- if (!preset) return;
- setImapHost(preset.imapHost);
- setImapPort(preset.imapPort);
- setSmtpHost(preset.smtpHost);
- setSmtpPort(preset.smtpPort);
- }
-
- const effectiveImapUsername = imapUsername || emailAddress;
- const effectiveSmtpUsername = smtpUsername || emailAddress;
-
- function buildData(): CustomEmailData | null {
- if (!emailAddress || !imapHost || !effectiveImapUsername || !imapPassword || !smtpHost || !effectiveSmtpUsername || !smtpPassword) {
- return null;
- }
- return {
- emailAddress, displayName, imapHost, imapPort,
- imapUsername: effectiveImapUsername, imapPassword,
- imapTls: true, smtpHost, smtpPort,
- smtpUsername: effectiveSmtpUsername, smtpPassword,
- smtpTls: 1, pollIntervalSeconds: 60,
- };
- }
-
- const fields = {
- emailAddress, setEmailAddress, displayName, setDisplayName,
- imapHost, setImapHost, imapPort, setImapPort,
- imapUsername, setImapUsername, imapPassword, setImapPassword,
- smtpHost, setSmtpHost, smtpPort, setSmtpPort,
- smtpUsername, setSmtpUsername, smtpPassword, setSmtpPassword,
- };
-
- return { fields, applyPreset, buildData };
-}
-
-function EmailFieldsForm({ fields, applyPreset, errors, onClearError }: {
- fields: ReturnType<typeof useEmailFields>["fields"];
- applyPreset: (name: string) => void;
- errors: CustomEmailErrors;
- onClearError: (field: keyof CustomEmailErrors) => void;
-}) {
- return (
- <>
- <div className="flex gap-2">
- {Object.keys(PRESETS).map((name) => (
- <Button key={name} type="button" variant="outline" size="sm" className="h-6 text-[10px] px-2"
- onClick={() => applyPreset(name)}>
- {name}
- </Button>
- ))}
- </div>
-
- <div className="grid gap-3">
- <div>
- <Label className="text-xs">Email Address *</Label>
- <Input placeholder="[email protected]" value={fields.emailAddress}
- onChange={(e) => {
- fields.setEmailAddress(e.target.value);
- if (e.target.value.trim()) onClearError("emailAddress");
- }}
- aria-invalid={Boolean(errors.emailAddress)}
- aria-describedby={errors.emailAddress ? "custom-email-address-error" : undefined}
- className="h-8 text-sm" />
- {errors.emailAddress && (
- <p id="custom-email-address-error" className="mt-1 text-xs text-destructive">
- {errors.emailAddress}
- </p>
- )}
- </div>
- <div>
- <Label className="text-xs">Display Name</Label>
- <Input placeholder="My Agent" value={fields.displayName}
- onChange={(e) => fields.setDisplayName(e.target.value)} className="h-8 text-sm" />
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-3">
- <div className="space-y-2">
- <Label className="text-xs font-medium">IMAP (Receive)</Label>
- <Input placeholder="imap.gmail.com" value={fields.imapHost}
- onChange={(e) => {
- fields.setImapHost(e.target.value);
- if (e.target.value.trim()) onClearError("imapHost");
- }}
- aria-invalid={Boolean(errors.imapHost)}
- aria-describedby={errors.imapHost ? "custom-email-imap-host-error" : undefined}
- className="h-8 text-sm" />
- {errors.imapHost && (
- <p id="custom-email-imap-host-error" className="text-xs text-destructive">
- {errors.imapHost}
- </p>
- )}
- <Input type="number" placeholder="993" value={fields.imapPort}
- onChange={(e) => fields.setImapPort(Number(e.target.value))} className="h-8 text-sm" />
- <Input placeholder={fields.emailAddress || "Username (defaults to email)"} value={fields.imapUsername}
- onChange={(e) => fields.setImapUsername(e.target.value)} className="h-8 text-sm" />
- <Input type="password" placeholder="App Password" value={fields.imapPassword}
- onChange={(e) => {
- fields.setImapPassword(e.target.value);
- if (e.target.value.trim()) onClearError("imapPassword");
- }}
- aria-invalid={Boolean(errors.imapPassword)}
- aria-describedby={errors.imapPassword ? "custom-email-imap-password-error" : undefined}
- className="h-8 text-sm" />
- {errors.imapPassword && (
- <p id="custom-email-imap-password-error" className="text-xs text-destructive">
- {errors.imapPassword}
- </p>
- )}
- </div>
- <div className="space-y-2">
- <Label className="text-xs font-medium">SMTP (Send)</Label>
- <Input placeholder="smtp.gmail.com" value={fields.smtpHost}
- onChange={(e) => {
- fields.setSmtpHost(e.target.value);
- if (e.target.value.trim()) onClearError("smtpHost");
- }}
- aria-invalid={Boolean(errors.smtpHost)}
- aria-describedby={errors.smtpHost ? "custom-email-smtp-host-error" : undefined}
- className="h-8 text-sm" />
- {errors.smtpHost && (
- <p id="custom-email-smtp-host-error" className="text-xs text-destructive">
- {errors.smtpHost}
- </p>
- )}
- <Input type="number" placeholder="587" value={fields.smtpPort}
- onChange={(e) => fields.setSmtpPort(Number(e.target.value))} className="h-8 text-sm" />
- <Input placeholder={fields.emailAddress || "Username (defaults to email)"} value={fields.smtpUsername}
- onChange={(e) => fields.setSmtpUsername(e.target.value)} className="h-8 text-sm" />
- <Input type="password" placeholder="App Password" value={fields.smtpPassword}
- onChange={(e) => {
- fields.setSmtpPassword(e.target.value);
- if (e.target.value.trim()) onClearError("smtpPassword");
- }}
- aria-invalid={Boolean(errors.smtpPassword)}
- aria-describedby={errors.smtpPassword ? "custom-email-smtp-password-error" : undefined}
- className="h-8 text-sm" />
- {errors.smtpPassword && (
- <p id="custom-email-smtp-password-error" className="text-xs text-destructive">
- {errors.smtpPassword}
- </p>
- )}
- </div>
- </div>
- </>
- );
-}
-
-export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRef }: Props) {
- const owner = useWorkspaceOwner();
- const { slug } = owner;
- const isCreateMode = !agentId;
- const [open, setOpen] = useAtom(useCreateAtom(false));
- const source = useWorkspaceViewSource(owner, `custom-email:${agentId ?? "create"}`, open);
- const formSource = useWorkspaceViewSource(owner, `custom-email-draft:${agentId ?? "create"}`, true);
- const changeOpen = (next: boolean) => { if (!next) source.retire(); setOpen(next); };
- const [fieldErrors, setFieldErrors] = useAtom(useCreateAtom<CustomEmailErrors>({}));
- const queryKey = owner.key("email-accounts", agentId);
- const accountsQuery = useQuery({ queryKey, enabled: !!agentId && owner.workspaceId === workspaceId, subscribed: !!agentId && owner.workspaceId === workspaceId,
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listEmailAccounts(agentId!, workspaceId, options), signal),
- });
- type Command = { kind: "create"; data: CustomEmailData } | { kind: "delete" | "sync"; id: string };
- const command = useMutation({ meta: { observabilityAction: "email.account.command" }, mutationKey: [...queryKey, "command"], scope: { id: JSON.stringify(queryKey) },
- gcTime: 0,
- mutationFn: async ({ action, token, assertView, signal, resource: original }: { action: Command; token: ReturnType<typeof captureWorkspaceOwner>; assertView: () => void; signal: AbortSignal; resource: Query | undefined }) => {
- const assert = () => { assertWorkspaceOwner(token, signal); assertView(); };
- assert();
- if (!agentId || owner.workspaceId !== workspaceId) throw new DOMException("Retired email scope", "AbortError");
- if (original && owner.queryClient.getQueryCache().find({ queryKey, exact: true }) === original) await owner.queryClient.cancelQueries({ queryKey, exact: true });
- assert();
- const canPublish = () => original && owner.queryClient.getQueryCache().find({ queryKey, exact: true }) === original;
- const options = workspaceRequestOptions(token, signal, assert);
- try {
- if (action.kind === "create") {
- const account = await createEmailAccount(agentId, action.data, workspaceId, options);
- assert();
- if (canPublish()) owner.queryClient.setQueryData<AgentEmailAccount[]>(queryKey, (rows) => rows ? [...rows.filter((row) => row.id !== account.id), account] : rows);
- } else if (action.kind === "delete") {
- await deleteEmailAccount(agentId, action.id, workspaceId, options);
- assert();
- if (canPublish()) owner.queryClient.setQueryData<AgentEmailAccount[]>(queryKey, (rows) => rows?.filter((row) => row.id !== action.id));
- } else await syncEmailAccount(agentId, action.id, workspaceId, options);
- assert();
- if (canPublish()) void owner.queryClient.invalidateQueries({ queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined);
- assert();
- } catch (error) { assert(); throw error; }
- },
- });
- const accounts = accountsQuery.data ?? [];
- const loading = !isCreateMode && accountsQuery.isPending;
- const saving = command.isPending && command.variables?.action.kind === "create";
- const syncing = command.isPending && command.variables?.action.kind === "sync";
- const deleting = command.isPending && command.variables?.action.kind === "delete";
-
- const { fields, applyPreset, buildData } = useEmailFields();
- const effectiveImapUsername = fields.imapUsername || fields.emailAddress;
- const effectiveSmtpUsername = fields.smtpUsername || fields.emailAddress;
-
- const clearFieldError = useCallback((field: keyof CustomEmailErrors) => {
- setFieldErrors((prev) => ({ ...prev, [field]: undefined }));
- }, [setFieldErrors]);
-
- useEffect(() => {
- if (!getDataRef) return;
- const get = () => { formSource.capture().assert(); return buildData(); };
- getDataRef.current = get;
- return () => { if (getDataRef.current === get) getDataRef.current = null; };
- }, [getDataRef, buildData, formSource.assertActive, formSource]);
-
- useEffect(() => {
- if (!isCreateMode) return;
- formSource.capture().assert();
- onDataChange?.(buildData());
- }, [isCreateMode, buildData, onDataChange, fields.emailAddress, fields.displayName, fields.imapHost, fields.imapPort, fields.imapUsername, fields.imapPassword, fields.smtpHost, fields.smtpPort, fields.smtpUsername, fields.smtpPassword, formSource]);
-
-
-
- const existing = accounts[0] ?? null;
-
- async function handleCreate() {
- const nextErrors = validateCustomEmailFields({
- emailAddress: fields.emailAddress,
- imapHost: fields.imapHost,
- imapUsername: effectiveImapUsername,
- imapPassword: fields.imapPassword,
- smtpHost: fields.smtpHost,
- smtpUsername: effectiveSmtpUsername,
- smtpPassword: fields.smtpPassword,
- });
- setFieldErrors(nextErrors);
- if (hasCustomEmailErrors(nextErrors)) return;
-
- const data = buildData();
- if (!data) return;
- if (!agentId) return;
- const assertView = source.assertActive;
- assertView();
- if (owner.queryClient.getMutationCache().findAll({ mutationKey: [...queryKey, "command"], status: "pending" }).length) return;
- try {
- await command.mutateAsync({ action: { kind: "create", data }, token: captureWorkspaceOwner(owner), assertView, signal: source.signal, resource: owner.queryClient.getQueryCache().find({ queryKey, exact: true }) });
- assertView();
- const domain = data.emailAddress.split("@")[1] ?? "";
- trackCustomEmailConnected({ email_domain: domain });
- toast.success("Custom email configured");
- fields.setImapPassword("");
- fields.setSmtpPassword("");
- changeOpen(false);
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to save");
- }
- }
-
- async function handleDelete() {
- if (!existing || !agentId) return;
- const assertView = source.assertActive;
- assertView();
- if (owner.queryClient.getMutationCache().findAll({ mutationKey: [...queryKey, "command"], status: "pending" }).length) return;
- try {
- await command.mutateAsync({ action: { kind: "delete", id: existing.id }, token: captureWorkspaceOwner(owner), assertView, signal: source.signal, resource: owner.queryClient.getQueryCache().find({ queryKey, exact: true }) });
- assertView();
- toast.success("Custom email removed");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Failed to remove");
- }
- }
-
- async function handleSync() {
- if (!existing || !agentId) return;
- const assertView = source.assertActive;
- assertView();
- if (owner.queryClient.getMutationCache().findAll({ mutationKey: [...queryKey, "command"], status: "pending" }).length) return;
- try {
- await command.mutateAsync({ action: { kind: "sync", id: existing.id }, token: captureWorkspaceOwner(owner), assertView, signal: source.signal, resource: owner.queryClient.getQueryCache().find({ queryKey, exact: true }) });
- assertView();
- toast.success("Sync triggered");
- } catch (error) {
- try { assertView(); } catch { return; }
- if (!isAbortError(error)) toast.error(error instanceof Error ? error.message : "Sync failed");
- }
- }
-
-
- const triggerDesc = isCreateMode
- ? (fields.emailAddress
- ? fields.emailAddress
- : "Connect your own mailbox via IMAP/SMTP")
- : loading
- ? "Loading..."
- : existing
- ? existing.email_address
- : "Connect your own mailbox via IMAP/SMTP";
-
- return (
- <Sheet open={open} onOpenChange={changeOpen}>
- <SheetTrigger
- render={
- <button
- type="button"
- className="flex w-full items-center justify-between rounded-lg border border-border/50 bg-muted/30 px-4 py-3 text-left transition-colors hover:bg-muted/50"
- />
- }
- >
- <div>
- <span className="text-sm font-medium">Custom Email</span>
- <p className="text-xs text-muted-foreground">{triggerDesc}</p>
- </div>
- {!isCreateMode && existing ? (
- <span className={cn(
- "inline-flex items-center gap-1 text-[10px] px-2 py-1 rounded-full font-medium shrink-0",
- existing.status === "active" ? "bg-green-500/10 text-green-600" :
- existing.status === "error" ? "bg-red-500/10 text-red-600" :
- "bg-yellow-500/10 text-yellow-600"
- )}>
- {existing.status === "active" ? <CheckCircle2 className="size-2.5" /> :
- existing.status === "error" ? <AlertCircle className="size-2.5" /> : null}
- {existing.status}
- </span>
- ) : (
- <ChevronRight className="size-4 text-muted-foreground shrink-0" />
- )}
- </SheetTrigger>
- <SheetContent
- side="right"
- className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border"
- >
- <SheetTitle className="sr-only">Custom Email</SheetTitle>
- <SheetBody className="px-8 pt-10 pb-6">
- <div className="space-y-4">
- <div>
- <div className="flex items-center gap-2">
- <h2 className="font-heading text-lg font-semibold">Custom Email</h2>
- <Tooltip>
- <TooltipTrigger
- render={
- <a
- href={`/w/${slug}/help/email-setup`}
- target="_blank"
- rel="noopener noreferrer"
- className="text-muted-foreground hover:text-foreground transition-colors"
- />
- }
- >
- <CircleHelp className="size-4" />
- </TooltipTrigger>
- <TooltipContent>How to get IMAP/SMTP credentials</TooltipContent>
- </Tooltip>
- </div>
- <p className="text-sm text-muted-foreground mt-1">
- Connect your own mailbox to send and receive email as your identity.
- </p>
- </div>
-
- {!isCreateMode && accountsQuery.isError ? <div role="alert" className="space-y-3">
- <p className="text-sm">Couldn’t load email accounts.</p>
- <Button variant="outline" onClick={() => { source.assertActive(); void accountsQuery.refetch({ cancelRefetch: false }); }}>Try again</Button>
- </div> : !isCreateMode && loading ? <Loader2 className="size-4 animate-spin" /> : !isCreateMode && existing ? (
- <div className="space-y-4">
- <div className="flex items-center justify-between rounded-md border border-border/50 px-3 py-2">
- <div className="flex items-center gap-2 min-w-0">
- <Mail className="size-3.5 text-muted-foreground shrink-0" />
- <span className="text-sm truncate">{existing.email_address}</span>
- </div>
- <div className="flex items-center gap-1 shrink-0">
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={handleSync}
- disabled={syncing}
- className="rounded-full text-muted-foreground"
- />
- }
- >
- <RefreshCw className={cn("size-3.5", syncing && "animate-spin")} />
- </TooltipTrigger>
- <TooltipContent>Sync now</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={handleDelete}
- disabled={deleting}
- className="rounded-full text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
- />
- }
- >
- {deleting ? <Loader2 className="size-3.5 animate-spin" /> : <XIcon className="size-3.5" />}
- </TooltipTrigger>
- <TooltipContent>Remove</TooltipContent>
- </Tooltip>
- </div>
- </div>
- {existing.error_message && (
- <p className="text-xs text-destructive">{existing.error_message}</p>
- )}
- {existing.last_synced_at && (
- <p className="text-xs text-muted-foreground">
- Last synced: {new Date(existing.last_synced_at).toLocaleString()}
- </p>
- )}
- <div className="rounded-md border border-border/50 px-3 py-2 text-xs text-muted-foreground space-y-1">
- <div className="flex justify-between"><span>IMAP</span><span>{existing.imap_host}:{existing.imap_port}</span></div>
- <div className="flex justify-between"><span>SMTP</span><span>{existing.smtp_host}:{existing.smtp_port}</span></div>
- <div className="flex justify-between"><span>Poll interval</span><span>{existing.poll_interval_seconds}s</span></div>
- </div>
- </div>
- ) : (
- <div className="space-y-4">
- <EmailFieldsForm
- fields={fields}
- applyPreset={applyPreset}
- errors={fieldErrors}
- onClearError={clearFieldError}
- />
- {!isCreateMode && (
- <Button type="button" size="sm" className="w-full" onClick={handleCreate} disabled={saving}>
- {saving && <Loader2 className="size-3 animate-spin mr-1" />}
- Save & Connect
- </Button>
- )}
- {isCreateMode && (
- <p className="text-xs text-muted-foreground">
- Will be connected after creating the agent.
- </p>
- )}
- </div>
- )}
- </div>
- </SheetBody>
- </SheetContent>
- </Sheet>
- );
-}
diff --git a/src/web/src/components/daemon-update-notice.dom.test.ts b/src/web/src/components/daemon-update-notice.dom.test.ts
index e3c9df314..40eb99f72 100644
--- a/src/web/src/components/daemon-update-notice.dom.test.ts
+++ b/src/web/src/components/daemon-update-notice.dom.test.ts
@@ -246,14 +246,12 @@ describe("DaemonUpdateNotice", () => {
expect(mocks.notificationAdd).not.toHaveBeenCalled()
})
- it("keeps the legacy notice outside Community while Community owns its shell surface", () => {
- const appLayout = readFileSync(resolve(webRoot, "src/app/(app)/layout.tsx"), "utf8")
+ it("keeps daemon updates in the Community shell after legacy pages retire", () => {
const communityShell = readFileSync(resolve(webRoot, "src/app/c/community-shell.tsx"), "utf8")
const shellFrame = readFileSync(resolve(
webRoot,
"src/components/community/shell/shell-frame.tsx",
), "utf8")
- expect(appLayout).toContain("<DaemonUpdateNotice userId={session.user.id} />")
expect(communityShell).not.toContain("DaemonUpdateNotice")
expect(shellFrame).toContain("useShellDaemonUpdateController")
})
diff --git a/src/web/src/components/email-body-frame.test.ts b/src/web/src/components/email-body-frame.test.ts
deleted file mode 100644
index 516f25dcd..000000000
--- a/src/web/src/components/email-body-frame.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildSrcDoc } from "./email-body-frame";
-
-describe("buildSrcDoc", () => {
- const sampleHtml = '<p style="color: #000;">Hello world</p>';
-
- it("wraps HTML in a full document", () => {
- const doc = buildSrcDoc(sampleHtml, false);
- expect(doc).toContain("<!DOCTYPE html>");
- expect(doc).toContain("<body>");
- expect(doc).toContain(sampleHtml);
- });
-
- it("injects light mode styles by default", () => {
- const doc = buildSrcDoc(sampleHtml, false);
- expect(doc).toContain('name="color-scheme" content="light"');
- expect(doc).toContain("color: #1a1a1a");
- expect(doc).not.toContain("color-scheme: dark");
- });
-
- it("injects dark mode styles when isDark is true", () => {
- const doc = buildSrcDoc(sampleHtml, true);
- expect(doc).toContain('name="color-scheme" content="dark"');
- expect(doc).toContain("color-scheme: dark");
- expect(doc).toContain("color: #e8e5e0");
- expect(doc).toContain("background-color: transparent !important");
- });
-
- it("forces text color with !important in dark mode", () => {
- const doc = buildSrcDoc(sampleHtml, true);
- expect(doc).toContain("color: #e8e5e0 !important");
- });
-
- it("sets max-width on images to prevent overflow", () => {
- const imgHtml = '<img src="photo.jpg" width="2000">';
- const doc = buildSrcDoc(imgHtml, false);
- expect(doc).toContain("max-width: 100%");
- });
-
- it("preserves the original HTML content unchanged", () => {
- const complexHtml = '<table><tr><td style="background:#fff;color:#000">Cell</td></tr></table>';
- const doc = buildSrcDoc(complexHtml, true);
- expect(doc).toContain(complexHtml);
- });
-});
diff --git a/src/web/src/components/email-body-frame.tsx b/src/web/src/components/email-body-frame.tsx
deleted file mode 100644
index 739a2a5f6..000000000
--- a/src/web/src/components/email-body-frame.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useRef, useEffect } from "react";
-import { useTheme } from "next-themes";
-
-interface EmailBodyFrameProps {
- html: string;
- className?: string;
-}
-
-const SCROLLBAR_STYLES = `
- html, body {
- overflow: hidden;
- }
-`;
-
-const LIGHT_STYLES = `
- html, body {
- --sb-thumb: rgba(0,0,0,0.15);
- --sb-hover: rgba(0,0,0,0.3);
- margin: 0;
- padding: 0;
- background: transparent;
- color: #1a1a1a;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
- font-size: 15px;
- line-height: 1.6;
- word-wrap: break-word;
- overflow-wrap: break-word;
- overflow: hidden;
- }
- a { color: inherit; }
- img { max-width: 100%; height: auto; }
-`;
-
-const DARK_STYLES = `
- html, body {
- --sb-thumb: rgba(255,255,255,0.1);
- --sb-hover: rgba(255,255,255,0.25);
- margin: 0;
- padding: 0;
- background: transparent;
- color: #e8e5e0;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
- font-size: 15px;
- line-height: 1.6;
- word-wrap: break-word;
- overflow-wrap: break-word;
- overflow: hidden;
- color-scheme: dark;
- }
- a { color: inherit; }
- img { max-width: 100%; height: auto; }
- /* Force dark-friendly defaults on common email patterns */
- body, div, td, th, p, span, li {
- color: #e8e5e0 !important;
- }
- table, tr, td, th, div, section, article, header, footer, main {
- background-color: transparent !important;
- border-color: rgba(255, 255, 255, 0.1) !important;
- }
- /* Preserve image backgrounds (logos, etc) */
- img { background-color: transparent !important; }
- h1, h2, h3, h4, h5, h6 {
- color: #f0ede8 !important;
- }
- a { color: #93b5ff !important; }
-`;
-
-export function buildSrcDoc(html: string, isDark: boolean): string {
- const styles = isDark ? DARK_STYLES : LIGHT_STYLES;
- return `<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <meta name="color-scheme" content="${isDark ? "dark" : "light"}">
- <style>${SCROLLBAR_STYLES}${styles}</style>
-</head>
-<body>${html}</body>
-</html>`;
-}
-
-export function EmailBodyFrame({ html, className }: EmailBodyFrameProps) {
- const iframeRef = useRef<HTMLIFrameElement>(null);
- const { resolvedTheme } = useTheme();
- const [height, setHeight] = useAtom(useCreateAtom(200));
- const isDark = resolvedTheme === "dark";
-
- useEffect(() => {
- const iframe = iframeRef.current;
- if (!iframe) return;
-
- let ro: ResizeObserver | null = null;
-
- iframe.srcdoc = buildSrcDoc(html, isDark);
-
- const onLoad = () => {
- const doc = iframe.contentDocument;
- if (!doc) return;
-
- const updateHeight = () => {
- const h = doc.documentElement.scrollHeight;
- if (h > 0) setHeight(h);
- };
-
- updateHeight();
-
- ro = new ResizeObserver(updateHeight);
- ro.observe(doc.documentElement);
- };
-
- iframe.addEventListener("load", onLoad);
- return () => {
- iframe.removeEventListener("load", onLoad);
- ro?.disconnect();
- };
- }, [html, isDark, setHeight]);
-
- return (
- <iframe
- ref={iframeRef}
- sandbox="allow-same-origin"
- className={className}
- style={{ width: "100%", height: `${height}px`, border: "none", display: "block" }}
- title="Email content"
- />
- );
-}
diff --git a/src/web/src/components/email-compose.tsx b/src/web/src/components/email-compose.tsx
deleted file mode 100644
index 7fb001d19..000000000
--- a/src/web/src/components/email-compose.tsx
+++ /dev/null
@@ -1,256 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useRef } from "react";
-import { useEditor, EditorContent } from "@tiptap/react";
-import StarterKit from "@tiptap/starter-kit";
-import Placeholder from "@tiptap/extension-placeholder";
-import Underline from "@tiptap/extension-underline";
-import Link from "@tiptap/extension-link";
-import TextAlign from "@tiptap/extension-text-align";
-import Image from "@tiptap/extension-image";
-import { EmailToolbar } from "@/components/email-toolbar";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import type { EmailAttachment } from "@alook/shared";
-import { toast } from "sonner";
-import { Send, X, Loader2, Paperclip, File as FileIcon } from "lucide-react";
-
-interface EmailComposeProps {
- fromAddress: string;
- onSend: (to: string, subject: string, htmlBody: string, attachments: EmailAttachment[], threading?: { inReplyTo?: string; references?: string }) => Promise<boolean>;
- onDiscard: () => void;
- initialTo?: string;
- initialSubject?: string;
- initialBody?: string;
- initialAttachments?: EmailAttachment[];
- inReplyTo?: string;
- references?: string;
-}
-
-function formatFileSize(bytes: number): string {
- if (bytes < 1024) return `${bytes} B`;
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
-}
-
-export function EmailCompose({
- fromAddress,
- onSend,
- onDiscard,
- initialTo = "",
- initialSubject = "",
- initialBody = "",
- initialAttachments = [],
- inReplyTo,
- references,
-}: EmailComposeProps) {
- const [to, setTo] = useAtom(useCreateAtom(initialTo));
- const [subject, setSubject] = useAtom(useCreateAtom(initialSubject));
- const [sending, setSending] = useAtom(useCreateAtom(false));
- const [attachments, setAttachments] = useAtom(useCreateAtom<EmailAttachment[]>(initialAttachments));
- const [uploading, setUploading] = useAtom(useCreateAtom(false));
- const fileInputRef = useRef<HTMLInputElement>(null);
-
- const editor = useEditor({
- immediatelyRender: false,
- content: initialBody || undefined,
- extensions: [
- StarterKit.configure({
- link: false,
- underline: false,
- }),
- Placeholder.configure({ placeholder: "Write your email..." }),
- Underline,
- Link.configure({
- autolink: true,
- openOnClick: false,
- linkOnPaste: true,
- }),
- TextAlign.configure({
- types: ["heading", "paragraph"],
- }),
- Image.configure({
- inline: true,
- allowBase64: true,
- }),
- ],
- editorProps: {
- attributes: {
- class: "text-sm max-w-none focus:outline-none min-h-50 px-4 py-3",
- },
- },
- });
-
- const handleSend = async () => {
- if (!to.trim() || !subject.trim() || !editor) return;
- setSending(true);
- try {
- const html = editor.getHTML();
- const threading = inReplyTo || references ? { inReplyTo, references } : undefined;
- const ok = await onSend(to.trim(), subject.trim(), html, attachments, threading);
- if (ok) {
- setTo("");
- setSubject("");
- setAttachments([]);
- editor.commands.clearContent();
- }
- } finally {
- setSending(false);
- }
- };
-
- const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const files = e.target.files;
- if (!files || files.length === 0) return;
-
- setUploading(true);
- try {
- const { uploadEmailAttachment } = await import("@/lib/api");
- for (const file of Array.from(files)) {
- if (file.size > 10 * 1024 * 1024) {
- toast.error(`${file.name} exceeds 10 MB limit`);
- continue;
- }
- const workspaceId = new URLSearchParams(window.location.search).get("workspace_id") ?? "";
- const meta = await uploadEmailAttachment(file, workspaceId);
- setAttachments((prev) => [...prev, meta]);
- }
- } catch {
- toast.error("Failed to upload attachment");
- } finally {
- setUploading(false);
- if (fileInputRef.current) fileInputRef.current.value = "";
- }
- };
-
- const removeAttachment = (key: string) => {
- setAttachments((prev) => prev.filter((a) => a.key !== key));
- };
-
- return (
- <div className="flex flex-col h-full w-full min-w-0">
- <div className="flex items-center justify-between border-b border-border/40 px-4 py-2">
- <h3 className="text-sm font-heading font-medium tracking-tight">New Email</h3>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground h-7 px-2"
- onClick={onDiscard}
- disabled={sending}
- >
- <X className="size-3 mr-1" />
- Discard
- </Button>
- <Button
- size="sm"
- className="text-xs h-7 px-3"
- onClick={handleSend}
- disabled={sending || !to.trim() || !subject.trim()}
- >
- {sending ? (
- <Loader2 className="size-3 mr-1 animate-spin" />
- ) : (
- <Send className="size-3 mr-1" />
- )}
- Send
- </Button>
- </div>
- </div>
-
- <div className="border-b border-border/30 px-4 py-2 space-y-1 min-w-0">
- <div className="flex items-center gap-2 text-sm min-w-0">
- <span className="text-muted-foreground w-16 shrink-0">From</span>
- <span className="text-muted-foreground truncate min-w-0">{fromAddress}</span>
- </div>
- <div className="flex items-center gap-2 text-sm min-w-0">
- <span className="text-muted-foreground w-16 shrink-0">To</span>
- <div className="flex-1 min-w-0 -ml-2 rounded-md bg-muted/40">
- <Input
- type="email"
- value={to}
- onChange={(e) => setTo(e.target.value)}
- placeholder="[email protected]"
- className="h-7 text-sm border-0 bg-transparent px-2 shadow-none focus-visible:ring-0 placeholder:text-muted-foreground/50"
- disabled={sending}
- />
- </div>
- </div>
- <div className="flex items-center gap-2 text-sm min-w-0">
- <span className="text-muted-foreground w-16 shrink-0">Subject</span>
- <div className="flex-1 min-w-0 -ml-2 rounded-md bg-muted/40">
- <Input
- value={subject}
- onChange={(e) => setSubject(e.target.value)}
- placeholder="Email subject"
- className="h-7 text-sm border-0 bg-transparent px-2 shadow-none focus-visible:ring-0 placeholder:text-muted-foreground/50"
- disabled={sending}
- />
- </div>
- </div>
- </div>
-
- <div className="flex items-center border-b border-border/30">
- <EmailToolbar editor={editor} />
- <div className="flex items-center gap-1 px-2 border-l border-border/30">
- <input
- ref={fileInputRef}
- type="file"
- multiple
- className="hidden"
- onChange={handleFileSelect}
- />
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- disabled={uploading}
- onMouseDown={(e) => e.preventDefault()}
- onClick={() => fileInputRef.current?.click()}
- className="text-muted-foreground/70"
- />
- }
- >
- {uploading ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <Paperclip className="size-3.5" />
- )}
- </TooltipTrigger>
- <TooltipContent>Attach file</TooltipContent>
- </Tooltip>
- </div>
- </div>
-
- {attachments.length > 0 && (
- <div className="flex flex-wrap gap-2 px-4 py-2 border-b border-border/30">
- {attachments.map((att) => (
- <div
- key={att.key}
- className="flex items-center gap-2 rounded-md bg-muted px-2 py-1 text-xs"
- >
- <FileIcon className="size-3 text-muted-foreground shrink-0" />
- <span className="truncate max-w-37.5">{att.filename}</span>
- <span className="text-muted-foreground shrink-0">{formatFileSize(att.size)}</span>
- <button
- type="button"
- onClick={() => removeAttachment(att.key)}
- className="text-muted-foreground hover:text-foreground ml-1 cursor-pointer"
- >
- <X className="size-3" />
- </button>
- </div>
- ))}
- </div>
- )}
-
- <div className="flex-1 overflow-y-auto thin-scrollbar">
- <EditorContent editor={editor} />
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/email-toolbar.tsx b/src/web/src/components/email-toolbar.tsx
deleted file mode 100644
index d76e9e125..000000000
--- a/src/web/src/components/email-toolbar.tsx
+++ /dev/null
@@ -1,323 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useRef, useEffect } from "react";
-import { useEditorState, type Editor } from "@tiptap/react";
-import { cn } from "@/lib/utils";
-import { onEnterSubmit } from "@/lib/ime";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogFooter,
-} from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import {
- Bold,
- Italic,
- Underline,
- Strikethrough,
- List,
- ListOrdered,
- AlignLeft,
- AlignCenter,
- AlignRight,
- Link,
- Unlink,
- ImageIcon,
- Heading1,
- Heading2,
- Minus,
-} from "lucide-react";
-
-interface EmailToolbarProps {
- editor: Editor | null;
-}
-
-function ToolbarButton({
- active,
- disabled,
- onAction,
- title,
- children,
-}: {
- active?: boolean;
- disabled?: boolean;
- onAction: () => void;
- title: string;
- children: React.ReactNode;
-}) {
- return (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- disabled={disabled}
- onMouseDown={(e) => e.preventDefault()}
- onClick={onAction}
- className={cn(
- "text-muted-foreground/70",
- active && "bg-accent text-foreground"
- )}
- />
- }
- >
- {children}
- </TooltipTrigger>
- <TooltipContent>{title}</TooltipContent>
- </Tooltip>
- );
-}
-
-function ToolbarDivider() {
- return <div className="w-px h-4 bg-border/60 mx-1 shrink-0" />;
-}
-
-export function EmailToolbar({ editor }: EmailToolbarProps) {
- useEditorState({ editor, selector: (context) => context.editor?.state ?? null });
- const [dialogOpen, setDialogOpen] = useAtom(useCreateAtom(false));
- const [dialogMode, setDialogMode] = useAtom(useCreateAtom<"link" | "image">("link"));
- const [urlValue, setUrlValue] = useAtom(useCreateAtom(""));
- const [urlError, setUrlError] = useAtom(useCreateAtom(""));
- const [displayText, setDisplayText] = useAtom(useCreateAtom(""));
- const [selectionEmpty, setSelectionEmpty] = useAtom(useCreateAtom(false));
- const inputRef = useRef<HTMLInputElement>(null);
- const linkActiveOnMouseDown = useRef(false);
-
-
-
- useEffect(() => {
- if (dialogOpen) {
- setTimeout(() => inputRef.current?.focus(), 0);
- }
- }, [dialogOpen]);
-
- if (!editor) return null;
-
- const iconSize = "size-3.5";
-
-
- const handleImage = () => {
- setDialogMode("image");
- setUrlValue("");
- setUrlError("");
- setDialogOpen(true);
- };
-
- const handleDialogSubmit = () => {
- const trimmed = urlValue.trim();
- if (!trimmed) return;
- try {
- new URL(trimmed);
- } catch {
- setUrlError("Please enter a valid URL");
- return;
- }
- setUrlError("");
- if (dialogMode === "link") {
- if (selectionEmpty) {
- const text = displayText.trim() || trimmed;
- editor.chain().focus().insertContent({
- type: "text",
- text,
- marks: [{ type: "link", attrs: { href: trimmed } }],
- }).run();
- } else {
- editor.chain().focus().extendMarkRange("link").setLink({ href: trimmed }).run();
- }
- } else {
- editor.chain().focus().setImage({ src: trimmed }).run();
- }
- setDialogOpen(false);
- };
-
- return (
- <div className="flex items-center gap-1 px-3 py-1 overflow-x-auto">
- {/* Inline formatting */}
- <ToolbarButton
- title="Bold"
- active={editor.isActive("bold")}
- onAction={() => editor.chain().focus().toggleBold().run()}
- >
- <Bold className={iconSize} />
- </ToolbarButton>
- <ToolbarButton
- title="Italic"
- active={editor.isActive("italic")}
- onAction={() => editor.chain().focus().toggleItalic().run()}
- >
- <Italic className={iconSize} />
- </ToolbarButton>
- <ToolbarButton
- title="Underline"
- active={editor.isActive("underline")}
- onAction={() => editor.chain().focus().toggleUnderline().run()}
- >
- <Underline className={iconSize} />
- </ToolbarButton>
- <ToolbarButton
- title="Strikethrough"
- active={editor.isActive("strike")}
- onAction={() => editor.chain().focus().toggleStrike().run()}
- >
- <Strikethrough className={iconSize} />
- </ToolbarButton>
-
- <ToolbarDivider />
-
- {/* Headings */}
- <ToolbarButton
- title="Heading 1"
- active={editor.isActive("heading", { level: 1 })}
- onAction={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
- >
- <Heading1 className={iconSize} />
- </ToolbarButton>
- <ToolbarButton
- title="Heading 2"
- active={editor.isActive("heading", { level: 2 })}
- onAction={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
- >
- <Heading2 className={iconSize} />
- </ToolbarButton>
-
- <ToolbarDivider />
-
- {/* Lists */}
- <ToolbarButton
- title="Bullet List"
- active={editor.isActive("bulletList")}
- onAction={() => editor.chain().focus().toggleBulletList().run()}
- >
- <List className={iconSize} />
- </ToolbarButton>
- <ToolbarButton
- title="Ordered List"
- active={editor.isActive("orderedList")}
- onAction={() => editor.chain().focus().toggleOrderedList().run()}
- >
- <ListOrdered className={iconSize} />
- </ToolbarButton>
-
- <ToolbarDivider />
-
- {/* Alignment */}
- <ToolbarButton
- title="Align Left"
- active={editor.isActive({ textAlign: "left" })}
- onAction={() => editor.chain().focus().setTextAlign("left").run()}
- >
- <AlignLeft className={iconSize} />
- </ToolbarButton>
- <ToolbarButton
- title="Align Center"
- active={editor.isActive({ textAlign: "center" })}
- onAction={() => editor.chain().focus().setTextAlign("center").run()}
- >
- <AlignCenter className={iconSize} />
- </ToolbarButton>
- <ToolbarButton
- title="Align Right"
- active={editor.isActive({ textAlign: "right" })}
- onAction={() => editor.chain().focus().setTextAlign("right").run()}
- >
- <AlignRight className={iconSize} />
- </ToolbarButton>
-
- <ToolbarDivider />
-
- {/* Link & Image — custom handler to capture isActive before click */}
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- onMouseDown={(e) => {
- e.preventDefault();
- linkActiveOnMouseDown.current = editor.isActive("link");
- }}
- onClick={() => {
- if (linkActiveOnMouseDown.current) {
- editor.chain().focus().unsetLink().run();
- } else {
- setDialogMode("link");
- setUrlValue("");
- setUrlError("");
- setDisplayText("");
- setSelectionEmpty(editor.state.selection.empty);
- setDialogOpen(true);
- }
- }}
- className={cn(
- "text-muted-foreground/70",
- editor.isActive("link") && "bg-accent text-foreground"
- )}
- />
- }
- >
- {editor.isActive("link") ? (
- <Unlink className={iconSize} />
- ) : (
- <Link className={iconSize} />
- )}
- </TooltipTrigger>
- <TooltipContent>{editor.isActive("link") ? "Remove Link" : "Insert Link"}</TooltipContent>
- </Tooltip>
- <ToolbarButton title="Insert Image" onAction={handleImage}>
- <ImageIcon className={iconSize} />
- </ToolbarButton>
-
- <ToolbarDivider />
-
- {/* Horizontal Rule */}
- <ToolbarButton
- title="Horizontal Rule"
- onAction={() => editor.chain().focus().setHorizontalRule().run()}
- >
- <Minus className={iconSize} />
- </ToolbarButton>
-
- <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>
- {dialogMode === "link" ? "Insert Link" : "Insert Image"}
- </DialogTitle>
- </DialogHeader>
- {dialogMode === "link" && selectionEmpty && (
- <Input
- ref={inputRef}
- value={displayText}
- onChange={(e) => setDisplayText(e.target.value)}
- onKeyDown={onEnterSubmit(handleDialogSubmit)}
- placeholder="Display text"
- />
- )}
- <div className="space-y-1">
- <Input
- ref={dialogMode === "image" || !selectionEmpty ? inputRef : undefined}
- value={urlValue}
- onChange={(e) => { setUrlValue(e.target.value); setUrlError(""); }}
- onKeyDown={onEnterSubmit(handleDialogSubmit)}
- placeholder={dialogMode === "link" ? "https://example.com" : "https://example.com/image.png"}
- type="url"
- aria-invalid={Boolean(urlError)}
- />
- {urlError && <p className="text-xs text-destructive">{urlError}</p>}
- </div>
- <DialogFooter>
- <Button onClick={handleDialogSubmit} disabled={!urlValue.trim()}>
- Insert
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/src/web/src/components/file-download-button.dom.test.tsx b/src/web/src/components/file-download-button.dom.test.tsx
index 4b147e288..d95e457b4 100644
--- a/src/web/src/components/file-download-button.dom.test.tsx
+++ b/src/web/src/components/file-download-button.dom.test.tsx
@@ -4,13 +4,12 @@ import { act, render as renderLeaf, waitFor } from "@/test/react-dom-harness"
import { FileDownloadButton } from "./file-download-button"
import { QueryClient } from "@tanstack/react-query"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
-import { WorkspaceProvider } from "@/contexts/workspace-context"
const service = vi.hoisted(() => ({ download: vi.fn(), success: vi.fn(), error: vi.fn() }))
vi.mock("@/lib/file-save", async importOriginal => ({ ...await importOriginal<object>(), downloadUrl: service.download }))
vi.mock("sonner", () => ({ toast: { success: service.success, error: service.error } }))
function render(node: React.ReactNode) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- return renderLeaf(<CommunityTestProvider client={client}><WorkspaceProvider workspaceId="workspace" slug="workspace">{node}</WorkspaceProvider></CommunityTestProvider>)
+ return renderLeaf(<CommunityTestProvider client={client}>{node}</CommunityTestProvider>)
}
afterEach(() => { vi.clearAllMocks() })
describe("file download control", () => {
diff --git a/src/web/src/components/flag-popover.tsx b/src/web/src/components/flag-popover.tsx
deleted file mode 100644
index 4307a9ba2..000000000
--- a/src/web/src/components/flag-popover.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback } from "react";
-import { useWorkspaceFlags } from "@/hooks/workspace/use-inbox";
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import { Skeleton } from "@/components/ui/skeleton";
-import { cn } from "@/lib/utils";
-import { type FlaggedItem } from "@/lib/api";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { useFlagCount } from "@/contexts/flag-count-context";
-import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
-import { AgentAvatar } from "@/components/avatar";
-import { relativeTime } from "@/lib/time";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { Flag, ArrowUpRight } from "lucide-react";
-import Link from "next/link";
-
-function FlagPopoverRow({
- item,
- slug,
- onClick,
-}: {
- item: FlaggedItem;
- slug: string;
- onClick: (e: React.MouseEvent) => void;
-}) {
- return (
- <a
- href={`/w/${slug}/agents/${item.agent_id}?conv=${item.conversation_id}`}
- onClick={onClick}
- className="block w-full py-2 px-2 hover:bg-muted rounded-md transition-colors cursor-pointer"
- >
- <div className="flex items-center gap-2">
- <AgentAvatar name={item.agent_name} avatarUrl={item.agent_avatar_url} size={24} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-xs font-medium truncate flex-1 min-w-0">
- {item.agent_name}
- </span>
- <span className="text-[10px] text-muted-foreground whitespace-nowrap shrink-0">
- {relativeTime(item.flagged_at)}
- </span>
- </div>
- <p className="text-xs text-muted-foreground truncate mt-1">
- {item.message_content}
- </p>
- </div>
- </div>
- </a>
- );
-}
-
-const POPOVER_LIMIT = 30;
-
-export function FlagPopover({
- isActive,
- onNavigate,
-}: {
- isActive?: boolean;
- onNavigate?: () => void;
-}) {
- const { slug } = useWorkspace();
- const { count: flagCount } = useFlagCount();
- const { openAgentChat } = useAgentChatSheet();
- const [open, setOpen] = useAtom(useCreateAtom(false));
- const query = useWorkspaceFlags(open);
- const items = query.items.slice(0, POPOVER_LIMIT);
- const loading = query.isPending;
- const [tooltipOpen, setTooltipOpen] = useAtom(useCreateAtom(false));
-
-
- const handleRowClick = useCallback((item: FlaggedItem, e: React.MouseEvent) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
- e.preventDefault();
- setOpen(false);
- onNavigate?.();
- openAgentChat(item.agent_id, { conversationId: item.conversation_id, messageId: item.message_id });
- }, [onNavigate, openAgentChat, setOpen]);
-
- return (
- <Popover
- open={open}
- onOpenChange={(nextOpen) => {
- setOpen(nextOpen);
- }}
- >
- <Tooltip open={open ? false : tooltipOpen} onOpenChange={setTooltipOpen}>
- <PopoverTrigger
- render={
- <TooltipTrigger render={
- <button
- type="button"
- className={cn(
- "relative flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "text-muted-foreground hover:text-foreground hover:bg-accent",
- isActive && "bg-accent text-foreground"
- )}
- />
- } />
- }
- >
- <Flag className="size-4" />
- {flagCount > 0 && (
- <span className="absolute top-1 right-1 flex items-center justify-center min-w-3.5 h-3.5 rounded-full bg-primary text-primary-foreground text-[9px] font-bold px-1">
- {flagCount > 99 ? "99+" : flagCount}
- </span>
- )}
- </PopoverTrigger>
- <TooltipContent side="right">Flagged</TooltipContent>
- </Tooltip>
- <PopoverContent side="right" className="w-80 p-0">
- <div className="flex items-center justify-between px-3 py-2 border-b border-border/50">
- <span className="text-xs font-medium">Flagged</span>
- <Link
- href={`/w/${slug}/flags`}
- onClick={() => {
- setOpen(false);
- onNavigate?.();
- }}
- className="flex items-center justify-center size-6 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
- >
- <ArrowUpRight className="size-3.5" />
- </Link>
- </div>
- <div className="p-1">
- {loading ? (
- <div className="space-y-1">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="py-2 px-2">
- <div className="flex items-center gap-2">
- <Skeleton className="size-6 rounded-full shrink-0" />
- <Skeleton className="h-3 w-20" />
- <div className="flex-1" />
- <Skeleton className="h-2.5 w-8" />
- </div>
- <Skeleton className="h-3 w-3/4 mt-2 ml-8" />
- </div>
- ))}
- </div>
- ) : !items || items.length === 0 ? (
- <div className="flex flex-col items-center gap-2 py-6 text-muted-foreground">
- <Flag className="size-6 opacity-30" />
- <p className="text-xs">No flagged messages</p>
- </div>
- ) : (
- <div className="max-h-96 overflow-y-auto thin-scrollbar">
- {items.map((item) => (
- <FlagPopoverRow
- key={item.id}
- item={item}
- slug={slug}
- onClick={(e) => handleRowClick(item, e)}
- />
- ))}
- </div>
- )}
- </div>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts b/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts
index 623cd848b..4f0158357 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts
@@ -483,29 +483,9 @@ describe("Cloud Code monster PET helpers", () => {
});
});
-describe("production workspace PET mounting", () => {
+describe("production landing PET mounting", () => {
it("mounts only production PET surfaces", () => {
const root = webRoot();
- const workspaceHomePage = readFileSync(
- path.join(root, "src/app/(app)/w/[slug]/home/page.tsx"),
- "utf8"
- );
- const settingsPage = readFileSync(
- path.join(root, "src/app/(app)/w/[slug]/settings/page.tsx"),
- "utf8"
- );
- const petTab = readFileSync(
- path.join(root, "src/app/(app)/w/[slug]/settings/pet-tab.tsx"),
- "utf8"
- );
- const workspaceShell = readFileSync(
- path.join(root, "src/components/workspace-shell.tsx"),
- "utf8"
- );
- const workspacePetLayer = readFileSync(
- path.join(root, "src/components/home-pet/workspace-pet-layer.tsx"),
- "utf8"
- );
const petComponent = readFileSync(
path.join(root, "src/components/home-pet/cloud-code-monster-pet.tsx"),
"utf8"
@@ -538,26 +518,10 @@ describe("production workspace PET mounting", () => {
path.join(root, "src/components/home-pet/cloud-code-monster-pet-walk-target.ts"),
"utf8"
);
- const agentNode = readFileSync(
- path.join(root, "src/components/canvas/agent-node.tsx"),
- "utf8"
- );
- const inboxPopover = readFileSync(
- path.join(root, "src/components/inbox-popover.tsx"),
- "utf8"
- );
const landingPage = readFileSync(
path.join(root, "src/components/home/home-page.tsx"),
"utf8"
);
- const inboxCountContext = readFileSync(
- path.join(root, "src/contexts/inbox-count-context.tsx"),
- "utf8"
- );
- const agentContext = readFileSync(
- path.join(root, "src/contexts/agent-context.tsx"),
- "utf8"
- );
const globalCss = readFileSync(path.join(root, "src/app/globals.css"), "utf8");
const clientPetSources = [petTypes, petPresets, petDirectShapes].join("\n");
const sensitiveShapeIds = [
@@ -591,28 +555,7 @@ describe("production workspace PET mounting", () => {
];
// Home page no longer renders pet directly
- expect(workspaceHomePage).not.toContain("CloudCodeMonsterPet");
- expect(workspaceHomePage).not.toContain("useHomePetSettings");
- expect(settingsPage).toContain('{ id: "pet", label: "Pet" }');
- expect(petTab).toContain("Enable pet");
- expect(petTab).not.toContain("Homepage only");
- expect(petTab).not.toContain("Global Display");
- expect(petTab).toContain("CloudCodeMonsterPresetPreview");
- expect(petTab).toContain("cloud-code-monster-pet-presets");
- expect(petTab).not.toContain(
- 'from "@/components/home-pet/cloud-code-monster-pet";'
- );
- expect(workspaceShell).toContain("WorkspacePetLayer");
- expect(workspaceShell).toContain("RuntimeVersionGate");
// Pet layer renders on all pages — no displayScope or isHome check
- expect(workspacePetLayer).not.toContain("displayScope");
- expect(workspacePetLayer).not.toContain("isHome");
- expect(workspacePetLayer).toContain("petSettings.enabled");
- expect(workspacePetLayer).toContain("dynamic<CloudCodeMonsterPetProps>");
- expect(inboxCountContext).toContain("notificationToken");
- expect(inboxCountContext).not.toContain("prevCountRef.current = next");
- expect(workspacePetLayer).toContain("useInboxCount");
- expect(workspacePetLayer).toContain("notificationToken={notificationToken}");
expect(petComponent).toContain("const EMPTY_PEEK_TARGETS");
expect(petComponent).toContain("peekTargets = EMPTY_PEEK_TARGETS");
expect(petComponent).toContain("peekTargetsRef.current = peekTargets");
@@ -626,7 +569,6 @@ describe("production workspace PET mounting", () => {
expect(petComponent).toContain("isDragging || fainted || notificationActive");
expect(petComponent).toContain("useWalkToTarget");
expect(petComponent).toContain("activeAgentTaskCount = 0");
- expect(workspacePetLayer).toContain("activeTaskDetails");
expect(petComponent).toContain("hasRunningTasks");
expect(petComponent).toContain("activeAgentTaskCountRef.current");
expect(petComponent).toContain('clearPetTimer("attention")');
@@ -696,21 +638,16 @@ describe("production workspace PET mounting", () => {
expect(petWalkTarget).toContain("createWalkToTargetVelocity");
expect(petWalkTarget).toContain('data-pet-target-id');
// Inbox button has pet target attribute
- expect(inboxPopover).toContain('data-pet-target-id="inbox"');
// Landing page renders pet for logged-in users
expect(landingPage).toContain("CloudCodeMonsterPet");
expect(landingPage).toContain("isLoggedIn && petSettings.enabled");
// Public pet receives facts through props from the workspace owner.
- expect(inboxCountContext).toContain("useQuery");
- expect(agentContext).toContain("useAgentContext");
for (const sensitiveShapeId of sensitiveShapeIds) {
expect(clientPetSources).not.toContain(`"${sensitiveShapeId}"`);
}
expect(petPixelParts).toContain(
'import("./cloud-code-monster-pet-direct-shapes")'
);
- expect(agentNode).toContain("data-agent-node-id={agent.id}");
- expect(agentNode).toContain('data-agent-working={activeTaskCount > 0 ? "true" : "false"}');
expect(petCssModule).toContain(".pet {");
expect(petCssModule).toContain(".button {");
expect(petCssModule).toContain(".footprint {");
diff --git a/src/web/src/components/home-pet/workspace-pet-layer.tsx b/src/web/src/components/home-pet/workspace-pet-layer.tsx
deleted file mode 100644
index 5a0749e51..000000000
--- a/src/web/src/components/home-pet/workspace-pet-layer.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-import { type RefObject } from "react";
-import dynamic from "next/dynamic";
-
-import { useAgentContext } from "@/contexts/agent-context";
-import { useInboxCount } from "@/contexts/inbox-count-context";
-import { useHomePetSettings } from "@/lib/home-pet-settings";
-import type { CloudCodeMonsterPetProps } from "./cloud-code-monster-pet";
-
-const CloudCodeMonsterPet = dynamic<CloudCodeMonsterPetProps>(
- () =>
- import("./cloud-code-monster-pet").then(
- (module) => module.CloudCodeMonsterPet
- ),
- { ssr: false }
-);
-
-type WorkspacePetLayerProps = {
- boundaryRef: RefObject<HTMLElement | null>;
- slug?: string;
-};
-
-export function WorkspacePetLayer({ boundaryRef }: WorkspacePetLayerProps) {
- const { activeTaskDetails, subscribeWs } = useAgentContext();
- const petSettings = useHomePetSettings();
- const { notificationToken, count: inboxCount } = useInboxCount();
-
- if (!petSettings.enabled) {
- return null;
- }
-
- return (
- <CloudCodeMonsterPet
- inboxCount={inboxCount}
- activeAgentTaskCount={activeTaskDetails.length}
- subscribeWs={subscribeWs}
- boundaryRef={boundaryRef}
- notificationToken={notificationToken}
- />
- );
-}
diff --git a/src/web/src/components/inbox-popover.tsx b/src/web/src/components/inbox-popover.tsx
deleted file mode 100644
index 107a15a60..000000000
--- a/src/web/src/components/inbox-popover.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-"use client";
-
-import { useCallback } from "react";
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useWorkspaceInbox } from "@/hooks/workspace/use-inbox";
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import { Skeleton } from "@/components/ui/skeleton";
-import { cn } from "@/lib/utils";
-import { type InboxItem } from "@/lib/api";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { useInboxCount } from "@/contexts/inbox-count-context";
-import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
-import { AgentAvatar } from "@/components/avatar";
-import { relativeTime } from "@/lib/time";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { Inbox, ArrowUpRight } from "lucide-react";
-import Link from "next/link";
-
-function InboxPopoverRow({
- item,
- slug,
- onClick,
-}: {
- item: InboxItem;
- slug: string;
- onClick: (e: React.MouseEvent) => void;
-}) {
- return (
- <a
- href={`/w/${slug}/agents/${item.agent_id}?conv=${item.id}`}
- onClick={onClick}
- className="block w-full py-2 px-2 hover:bg-muted rounded-md transition-colors cursor-pointer"
- >
- <div className="flex items-center gap-2">
- <AgentAvatar name={item.agent_name} avatarUrl={item.agent_avatar_url} size={24} />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-xs font-medium truncate flex-1 min-w-0">
- {item.agent_name}
- </span>
- <span className="text-[10px] text-muted-foreground whitespace-nowrap shrink-0">
- {relativeTime(item.latest_response_at)}
- </span>
- </div>
- <p className="text-xs text-muted-foreground truncate mt-1">
- {item.root_prompt ?? item.title}
- </p>
- </div>
- </div>
- </a>
- );
-}
-
-
-export function InboxPopover({
- isActive,
- onNavigate,
-}: {
- isActive?: boolean;
- onNavigate?: () => void;
-}) {
- const { slug } = useWorkspace();
- const { count: inboxCount, decrement, refresh } = useInboxCount();
- const { openAgentChat } = useAgentChatSheet();
- const [open, setOpen] = useAtom(useCreateAtom(false));
- const [tooltipOpen, setTooltipOpen] = useAtom(useCreateAtom(false));
- const { items, isPending: loading, refresh: fetchItems } = useWorkspaceInbox(open);
-
- const handleRowClick = useCallback((item: InboxItem, e: React.MouseEvent) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
- e.preventDefault();
- decrement();
- setOpen(false);
- onNavigate?.();
- openAgentChat(item.agent_id, { conversationId: item.id });
- }, [decrement, onNavigate, openAgentChat, setOpen]);
-
- return (
- <Popover
- open={open}
- onOpenChange={(nextOpen) => {
- setOpen(nextOpen);
- if (nextOpen) {
- fetchItems();
- refresh();
- }
- }}
- >
- <Tooltip open={open ? false : tooltipOpen} onOpenChange={setTooltipOpen}>
- <PopoverTrigger
- render={
- <TooltipTrigger render={
- <button
- type="button"
- data-pet-target-id="inbox"
- className={cn(
- "relative flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
- "text-muted-foreground hover:text-foreground hover:bg-accent",
- isActive && "bg-accent text-foreground"
- )}
- />
- } />
- }
- >
- <Inbox className="size-4" />
- {inboxCount > 0 && (
- <span className="absolute top-1 right-1 flex items-center justify-center min-w-3.5 h-3.5 rounded-full bg-primary text-primary-foreground text-[9px] font-bold px-1">
- {inboxCount > 99 ? "99+" : inboxCount}
- </span>
- )}
- </PopoverTrigger>
- <TooltipContent side="right">Unread</TooltipContent>
- </Tooltip>
- <PopoverContent side="right" className="w-80 p-0">
- <div className="flex items-center justify-between px-3 py-2 border-b border-border/50">
- <span className="text-xs font-medium">Unread</span>
- <Link
- href={`/w/${slug}/unread`}
- onClick={() => {
- setOpen(false);
- onNavigate?.();
- }}
- className="flex items-center justify-center size-6 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
- >
- <ArrowUpRight className="size-3.5" />
- </Link>
- </div>
- <div className="p-1">
- {loading ? (
- <div className="space-y-1">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="py-2 px-2">
- <div className="flex items-center gap-2">
- <Skeleton className="size-6 rounded-full shrink-0" />
- <Skeleton className="h-3 w-20" />
- <div className="flex-1" />
- <Skeleton className="h-2.5 w-8" />
- </div>
- <Skeleton className="h-3 w-3/4 mt-2 ml-8" />
- </div>
- ))}
- </div>
- ) : !items || items.length === 0 ? (
- <div className="flex flex-col items-center gap-2 py-6 text-muted-foreground">
- <Inbox className="size-6 opacity-30" />
- <p className="text-xs">No unread messages</p>
- </div>
- ) : (
- <div className="max-h-96 overflow-y-auto thin-scrollbar">
- {items.map((item) => (
- <InboxPopoverRow
- key={item.id}
- item={item}
- slug={slug}
- onClick={(e) => handleRowClick(item, e)}
- />
- ))}
- </div>
- )}
- </div>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/src/web/src/components/issues/issue-attachment-list.tsx b/src/web/src/components/issues/issue-attachment-list.tsx
deleted file mode 100644
index c7fc47a3a..000000000
--- a/src/web/src/components/issues/issue-attachment-list.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-"use client"
-
-import type { Artifact } from "@alook/shared";
-import { File as FileIcon } from "lucide-react";
-import { FileDownloadButton } from "@/components/file-download-button";
-import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";
-import { formatSize } from "@/components/agent-chat/artifact-sheet";
-import { cn } from "@/lib/utils";
-
-export function IssueAttachmentList({ artifacts, workspaceId, onArtifactClick }: { artifacts: Artifact[]; workspaceId: string; onArtifactClick?: (artifact: Artifact) => void }) {
- if (artifacts.length === 0) return null;
- const baseCls = "flex items-center gap-2 rounded-md px-2 py-2 text-sm transition-colors hover:bg-accent";
- return (
- <div className="space-y-1">
- {artifacts.map((artifact) => {
- const canPreview = onArtifactClick && isPreviewable(artifact);
- const inner = (
- <>
- <FileIcon className="size-3.5 shrink-0 text-muted-foreground" />
- <span className="min-w-0 flex-1 truncate">{artifact.filename}</span>
- <span className="shrink-0 text-xs text-muted-foreground">{formatSize(artifact.size)}</span>
- </>
- );
- return canPreview ? (
- <button
- key={artifact.id}
- type="button"
- onClick={() => onArtifactClick(artifact)}
- className={cn(baseCls, "w-full text-left")}
- >
- {inner}
- </button>
- ) : (
- <FileDownloadButton
- key={artifact.id}
- url={getArtifactUrl(artifact.id, workspaceId, true)}
- filename={artifact.filename}
- className={baseCls}
- >
- {inner}
- </FileDownloadButton>
- );
- })}
- </div>
- );
-}
diff --git a/src/web/src/components/issues/issue-sheet.tsx b/src/web/src/components/issues/issue-sheet.tsx
deleted file mode 100644
index 80b038219..000000000
--- a/src/web/src/components/issues/issue-sheet.tsx
+++ /dev/null
@@ -1,765 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom, useCreateStore, useSelector } from "@tanstack/react-store";
-import { IssueAttachmentList } from "./issue-attachment-list";
-import { useCallback, useEffect, useRef } from "react";
-import {
- Sheet,
- SheetClose,
- SheetContent,
- SheetTitle,
- SheetBody,
- SheetFooter,
-} from "@/components/ui/sheet";
-import { Button } from "@/components/ui/button";
-import { MarkdownEditor } from "@/components/ui/markdown-editor";
-import { Skeleton } from "@/components/ui/skeleton";
-import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle";
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectContent,
- SelectItem,
-} from "@/components/ui/select";
-import {
- ArrowUp,
- Check,
- CircleDot,
- GitBranch,
- Loader2,
- MessageSquare,
- User,
- XIcon,
-} from "lucide-react";
-import Link from "next/link";
-import { cn } from "@/lib/utils";
-import { toast } from "sonner";
-import { Streamdown } from "streamdown";
-import { mermaid, cjk } from "@/lib/streamdown-plugins";
-import type { Agent, Artifact, Issue, IssueComment, Message, TaskApi } from "@alook/shared";
-import { isTerminalIssueStatus, toAlookAddress } from "@alook/shared";
-import type { TraceTask } from "@/lib/api";
-import { useWorkspaceOwner, captureWorkspaceOwner } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { useIssueCommand, usePendingIssueChanges } from "@/hooks/workspace/use-issue-command";
-import { AgentAvatar } from "@/components/avatar";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-import { Kbd } from "@/components/ui/kbd";
-import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea";
-
-// --- Constants ---
-
-const MIN_WIDTH = 320;
-const MAX_WIDTH_RATIO = 0.8;
-
-const GHOST_CONTROL =
- "h-7 border-0 bg-transparent px-2 text-xs text-foreground hover:bg-accent transition-colors -ml-2";
-
-
-const SELECTOR_STATUSES = ["todo", "in_progress", "review", "done"] as const;
-
-function statusLabel(status: string) {
- if (status === "done") return "Complete";
- return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
-}
-
-// --- Sub-components ---
-
-function AgentIdentity({ agent, size = 24 }: { agent: Agent; size?: number }) {
- const email = agent.email_handle ? toAlookAddress(agent.email_handle) : "";
- return (
- <div className="flex min-w-0 items-center gap-2">
- <AgentAvatar name={agent.name} avatarUrl={agent.avatar_url} seed={agent.id} size={size} />
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <div className="truncate text-xs font-medium">{agent.name}</div>
- {email ? <div className="truncate text-[11px] text-muted-foreground">{email}</div> : null}
- </div>
- </div>
- );
-}
-
-interface PropertyRowProps {
- icon?: React.ReactNode;
- children: React.ReactNode;
-}
-
-function PropertyRow({ icon, children }: PropertyRowProps) {
- return (
- <div className="group flex items-center gap-2">
- <span className="inline-flex size-6 shrink-0 items-center justify-center text-muted-foreground">
- {icon}
- </span>
- <div className="flex min-w-0 flex-wrap items-center gap-1">{children}</div>
- </div>
- );
-}
-
-function MessageRow({ message }: { message: Message }) {
- if (message.role === "event") {
- return (
- <div className="rounded-md border bg-muted/50 text-muted-foreground text-xs px-3 py-2">
- {message.content}
- </div>
- );
- }
- return (
- <div className="rounded-lg border border-border/60 bg-background/55 p-3">
- <div className="mb-1 flex items-center justify-between gap-2 text-xs text-muted-foreground">
- <span className="capitalize">{message.role}</span>
- <span>{new Date(message.created_at).toLocaleString()}</span>
- </div>
- <div className="prose prose-sm dark:prose-invert max-w-none text-sm wrap-break-word">
- <Streamdown plugins={{ mermaid, cjk }}>{message.content}</Streamdown>
- </div>
- </div>
- );
-}
-
-function CommentRow({ comment, agents }: { comment: IssueComment; agents: Agent[] }) {
- const authorLabel = comment.author_type === "agent"
- ? agents.find((a) => a.id === comment.author_id)?.name ?? "Agent"
- : "You";
- return (
- <div className="rounded-lg border border-border/60 bg-background p-3">
- <div className="mb-1 flex items-center justify-between gap-2 text-xs text-muted-foreground">
- <span className="font-medium">{authorLabel}</span>
- <span>{new Date(comment.created_at).toLocaleString()}</span>
- </div>
- <div className="prose prose-sm dark:prose-invert max-w-none text-sm wrap-break-word">
- <Streamdown plugins={{ mermaid, cjk }}>{comment.content}</Streamdown>
- </div>
- </div>
- );
-}
-
-// --- Main component ---
-
-export interface IssueSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- agents: Agent[];
- issue?: Issue | null;
- detail?: { messages: Message[]; comments: IssueComment[]; artifacts: Artifact[]; traceId?: string | null } | null;
- detailLoading?: boolean;
- activeTask?: TaskApi | null;
- traceTasks?: TraceTask[] | null;
- submitting?: boolean;
- defaultAgentId?: string;
- slug: string;
- workspaceId: string;
- draft?: { title: string; description: string; agentId: string };
- onDraftChange?: (draft: { title: string; description: string; agentId: string }) => void;
- onCreate?: (values: { agent_id?: string; title: string; description: string }) => Promise<void>;
- onUpdate?: (issueId: string, patch: { title?: string; description?: string }) => void;
- onStatusChange?: (issueId: string, status: string) => Promise<void>;
- onCommented?: () => void;
- onDispatched?: (issueId: string) => void;
- onArtifactClick?: (artifact: Artifact) => void;
-}
-
-type IssueSaveIntent = {
- id: string;
- patch: { title?: string; description?: string };
- token: ReturnType<typeof captureWorkspaceOwner>;
- assertView: () => void;
-};
-type IssueDraftState = {
- id: string | null;
- title: string | null;
- description: string | null;
- pending: IssueSaveIntent | null;
-};
-
-export function IssueSheet({
- open,
- onOpenChange,
- agents,
- issue,
- detail,
- detailLoading,
- activeTask,
- traceTasks,
- submitting,
- defaultAgentId,
- slug,
- workspaceId,
- draft,
- onDraftChange,
- onCreate,
- onStatusChange,
- onCommented,
- onDispatched,
- onArtifactClick,
-}: IssueSheetProps) {
- const mode = issue ? "detail" : "create";
- const owner = useWorkspaceOwner();
- const source = useWorkspaceViewSource(owner, JSON.stringify(["issue-sheet", issue?.id ?? "create"]), open && owner.workspaceId === workspaceId);
- const { mutateAsync: mutateIssue } = useIssueCommand(owner);
- const pendingCommands = usePendingIssueChanges(owner);
- const editing = useCreateStore<IssueDraftState>({ id: null, title: null, description: null, pending: null });
- const edits = useSelector(editing, (state) => state);
-
- // Local editing state
- const [createTitle, setCreateTitle] = useAtom(useCreateAtom(""));
- const [createDescription, setCreateDescription] = useAtom(useCreateAtom(""));
- const title = issue ? (edits.id === issue.id ? edits.title : null) ?? issue.title : createTitle;
- const description = issue ? (edits.id === issue.id ? edits.description : null) ?? issue.description ?? "" : createDescription;
- const [agentId, setAgentId] = useAtom(useCreateAtom(defaultAgentId ?? ""));
- const [assigneeOpen, setAssigneeOpen] = useAtom(useCreateAtom(false));
- const [commentContent, setCommentContent] = useAtom(useCreateAtom(""));
- const [confirmAgentId, setConfirmAgentId] = useAtom(useCreateAtom<string | null>(null));
- const confirmAgent = agents.find((agent) => agent.id === confirmAgentId) ?? null;
- const commentSubmitting = pendingCommands.some((action) => action.kind === "comment" && action.id === issue?.id);
- const dispatching = pendingCommands.some((action) => action.kind === "update" && action.id === issue?.id && action.patch.agent_id != null);
-
- const descriptionRef = useRef<HTMLDivElement>(null);
- const timelineRef = useRef<HTMLDivElement>(null);
-
- const isTaskActive = activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
- const hasActiveTraceTasks = traceTasks?.some(t => ["queued", "dispatched", "running"].includes(t.status)) ?? false;
-
- // Seed state on open/issue change
- useEffect(() => {
- if (!open) return;
- setConfirmAgentId(null);
- setCommentContent("");
- if (!issue) {
- setCreateTitle(draft?.title ?? "");
- setCreateDescription(draft?.description ?? "");
- setAgentId(draft?.agentId || defaultAgentId || "");
- }
- }, [open, issue?.id]); // eslint-disable-line react-hooks/exhaustive-deps
-
- // Sync draft to parent (create mode only)
- useEffect(() => {
- if (mode !== "create" || !open) return;
- onDraftChange?.({ title, description, agentId });
- }, [title, description, agentId, mode, open]); // eslint-disable-line react-hooks/exhaustive-deps
-
- // Auto-scroll timeline
- useEffect(() => {
- if (timelineRef.current) {
- timelineRef.current.scrollTop = timelineRef.current.scrollHeight;
- }
- }, [detail?.messages?.length, detail?.comments?.length, traceTasks?.length]);
-
- // Auto-save (detail mode): debounce title/description changes
- const flushAutoSave = useCallback(() => {
- const intent = editing.get().pending;
- if (!intent || (intent.patch.title != null && !intent.patch.title.trim())) return;
- editing.setState((state) => state.pending === intent ? { ...state, pending: null } : state);
- void mutateIssue({ action: { kind: "update", id: intent.id, patch: intent.patch }, token: intent.token }).then(() => {
- intent.assertView();
- editing.setState((state) => state.id !== intent.id ? state : {
- ...state,
- title: state.title?.trim() === intent.patch.title ? null : state.title,
- description: state.description?.trim() === intent.patch.description ? null : state.description,
- });
- }).catch((error) => {
- try { intent.assertView(); } catch { return; }
- if (!(error instanceof DOMException && error.name === "AbortError")) toast.error(error instanceof Error ? error.message : "Failed to save issue");
- });
- }, [mutateIssue, editing]);
-
- const editField = (field: "title" | "description", value: string) => {
- if (!issue) {
- if (field === "title") setCreateTitle(value);
- else setCreateDescription(value);
- return;
- }
- source.assertActive();
- const id = issue.id;
- editing.setState((state) => {
- const current = state.id === id ? state : { id, title: null, description: null, pending: null };
- const patch = { ...current.pending?.patch, [field]: value.trim() };
- const intent = current.pending ?? { id, token: captureWorkspaceOwner(owner), assertView: source.assertActive, patch };
- return { ...current, [field]: value, pending: { ...intent, patch } };
- });
- };
-
- useEffect(() => {
- if (!open || !edits.pending) return;
- const timer = setTimeout(flushAutoSave, 500);
- return () => clearTimeout(timer);
- }, [edits.pending, open, flushAutoSave]);
-
- // Flush pending auto-save when sheet closes
- useEffect(() => {
- if (!open || !issue?.id) return;
- const id = issue.id;
- return () => { if (editing.get().pending?.id === id) flushAutoSave(); };
- }, [open, issue?.id, editing, flushAutoSave]);
-
- // --- Drag handle ---
- const { width, onPointerDown, onPointerMove, onPointerUp } = useSheetResize({
- defaultWidth: 448,
- minWidth: MIN_WIDTH,
- maxWidthRatio: MAX_WIDTH_RATIO,
- });
-
- // --- Handlers ---
- const handleCreate = async () => {
- if (!title.trim() || submitting) return;
- await onCreate?.({ agent_id: agentId || undefined, title: title.trim(), description: description.trim() });
- };
-
-
- const handleStatusChange = (newStatus: string) => {
- if (!issue || newStatus === issue.status) return;
- onStatusChange?.(issue.id, newStatus);
- };
-
- const handleCommentSubmit = async () => {
- if (!commentContent.trim() || commentSubmitting || !issue) return;
- const original = source.assertActive;
- original();
- const content = commentContent;
- const id = issue.id;
- const token = captureWorkspaceOwner(owner);
- try {
- await mutateIssue({ action: { kind: "comment", id, content: content.trim() }, token });
- original();
- setCommentContent((current) => current === content ? "" : current);
- onCommented?.();
- } catch (error) {
- try { original(); } catch { return; }
- if (error instanceof DOMException && error.name === "AbortError") return;
- toast.error("Failed to send comment");
- }
- };
-
- // Shift+Enter capture handler (create mode only — detail auto-saves)
- const commentRef = useRef<HTMLTextAreaElement>(null);
- const onKeyDownCapture = useCallback((e: React.KeyboardEvent) => {
- if (e.key === "Enter" && e.shiftKey && mode === "create") {
- if (commentRef.current && commentRef.current.contains(e.target as Node)) return;
- e.preventDefault();
- e.stopPropagation();
- handleCreate();
- }
- }, [mode, title, description, agentId, submitting]); // eslint-disable-line react-hooks/exhaustive-deps
-
- // Enter on title → focus description
- const onTitleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- const editor = descriptionRef.current?.querySelector('[contenteditable="true"]') as HTMLElement | null;
- editor?.focus();
- }
- };
-
- const isTodoDraft = mode === "detail" && issue?.status === "todo";
-
- const selectedAgent = agents.find((a) => a.id === agentId) ?? null;
- const detailAgent = issue?.agent_id ? agents.find((a) => a.id === issue.agent_id) ?? null : null;
-
- // Mobile tab state (only used below lg breakpoint)
- const [mobileTab, setMobileTab] = useAtom(useCreateAtom<"issue" | "activity">("issue"));
-
- // Reset tab when switching issues or modes
- useEffect(() => {
- setMobileTab("issue");
- }, [issue?.id, mode, setMobileTab]);
-
- const timelineContent = (
- <>
- {detailLoading ? (
- <div className="space-y-3">
- <Skeleton className="h-12" />
- <Skeleton className="h-8" />
- <Skeleton className="h-12" />
- </div>
- ) : (() => {
- const events = (detail?.messages ?? [])
- .filter((m) => m.role === "event")
- .map((m) => ({ kind: "event" as const, id: m.id, created_at: m.created_at, data: m }));
- const comments = (detail?.comments ?? [])
- .map((c) => ({ kind: "comment" as const, id: c.id, created_at: c.created_at, data: c }));
- const timeline = [...events, ...comments].sort(
- (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
- );
-
- if (timeline.length === 0 && !isTaskActive) {
- return <div className="text-xs text-muted-foreground">No activity yet.</div>;
- }
-
- return (
- <div className="relative pl-4">
- <div className="absolute left-[4.5px] top-2 bottom-2 w-px bg-border" />
- <div className="space-y-3">
- {timeline.map((item) => (
- <div key={item.id} className="relative">
- <div className="absolute -left-4 top-2 size-2.5 rounded-full border-2 border-background bg-muted-foreground/40" />
- {item.kind === "event"
- ? <MessageRow message={item.data} />
- : <CommentRow comment={item.data} agents={agents} />}
- </div>
- ))}
- {(isTaskActive || hasActiveTraceTasks) && (() => {
- const activeTraceTasks = traceTasks?.filter(t => ["queued", "dispatched", "running"].includes(t.status));
- if (activeTraceTasks && activeTraceTasks.length > 0) {
- return activeTraceTasks.map(t => {
- const isRunning = t.status === "running";
- return (
- <div key={t.id} className="relative">
- <div className={cn(
- "absolute -left-4 top-2 size-2.5 rounded-full border-2 border-background",
- isRunning ? "bg-emerald-500 animate-pulse" : "bg-muted-foreground/40"
- )} />
- <div className={cn(
- "rounded-md border px-3 py-2",
- isRunning ? "border-emerald-500/30 bg-emerald-500/10" : "border-border/60 bg-muted/30"
- )}>
- <div className="flex items-center gap-2 text-xs">
- {t.agent && <AgentAvatar name={t.agent.name} avatarUrl={t.agent.avatarUrl} seed={t.agent.name || "?"} size={16} />}
- <span className={isRunning ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground"}>
- {t.agent?.name ?? "Agent"} {isRunning ? "is working" : "— queued"}
- </span>
- </div>
- </div>
- </div>
- );
- });
- }
- return (
- <div className="relative">
- <div className="absolute -left-4 top-2 size-2.5 rounded-full border-2 border-background bg-emerald-500 animate-pulse" />
- <div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2">
- <div className="flex items-center gap-2 text-xs text-emerald-600 dark:text-emerald-400">Working</div>
- </div>
- </div>
- );
- })()}
- </div>
- </div>
- );
- })()}
- </>
- );
-
- const commentInput = mode === "detail" && issue && !isTodoDraft && !isTaskActive && !isTerminalIssueStatus(issue.status) ? (
- <div className="flex flex-col rounded-xl border bg-background/60 transition-colors duration-200 focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50">
- <textarea
- ref={commentRef}
- placeholder="Leave a comment..."
- value={commentContent}
- onChange={(e) => setCommentContent(e.target.value)}
- className="w-full resize-none bg-transparent px-4 py-2 text-sm leading-relaxed outline-none placeholder:text-muted-foreground field-sizing-content min-h-15 max-h-32 thin-scrollbar overflow-y-auto"
- onKeyDown={(e) => { if (e.key === "Enter" && e.shiftKey) { e.preventDefault(); handleCommentSubmit(); } }}
- />
- <div className="flex items-center justify-between px-2 pb-2 pt-0.5">
- <Kbd className="text-[11px] text-muted-foreground/50">⇧↵</Kbd>
- <Button
- size="icon-sm"
- onClick={handleCommentSubmit}
- disabled={!commentContent.trim() || commentSubmitting}
- className={cn("rounded-lg transition-opacity duration-200", !commentContent.trim() && !commentSubmitting && "opacity-40")}
- >
- {commentSubmitting ? <Loader2 className="size-3.5 animate-spin" /> : <ArrowUp className="size-3.5" />}
- </Button>
- </div>
- </div>
- ) : null;
-
- const issueFormContent = (
- <>
- {/* Title */}
- <div className="shrink-0 px-2 sm:px-3 pt-5 pb-1">
- <AutoResizeTextarea
- value={title}
- onChange={(e) => editField("title", e.target.value)}
- onKeyDown={onTitleKeyDown}
- placeholder={mode === "create" ? "New issue" : "Untitled"}
- autoFocus={mode === "create"}
- rows={1}
- className="w-full rounded-none border-0 bg-transparent px-0 py-1 font-news text-2xl sm:text-3xl font-medium leading-[1.2] tracking-tight shadow-none outline-none focus-visible:border-0 focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground/40 placeholder:font-normal"
- />
- </div>
-
- {/* Properties */}
- <div className="shrink-0 space-y-2 px-2 sm:px-3 py-2">
- {/* Agent row */}
- <PropertyRow icon={<User className="size-3.5" />}>
- {mode === "create" || isTodoDraft ? (
- <Popover open={assigneeOpen} onOpenChange={setAssigneeOpen}>
- <PopoverTrigger
- render={
- <button
- type="button"
- disabled={submitting || dispatching}
- className={cn(GHOST_CONTROL, "flex items-center gap-2 rounded-md")}
- />
- }
- >
- {selectedAgent ? (
- <span className="truncate">{selectedAgent.name}</span>
- ) : (
- <span className="text-muted-foreground/70">Unassigned</span>
- )}
- </PopoverTrigger>
- <PopoverContent align="start" className="max-h-64 w-72 overflow-y-auto thin-scrollbar p-1">
- {!isTodoDraft && (
- <button
- type="button"
- onClick={() => { setAgentId(""); setAssigneeOpen(false); }}
- className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors hover:bg-accent hover:text-accent-foreground"
- >
- <span className="text-muted-foreground">None (unassigned)</span>
- {!agentId ? <Check className="size-3.5 shrink-0" /> : null}
- </button>
- )}
- {agents.map((agent) => (
- <button
- key={agent.id}
- type="button"
- onClick={() => {
- if (isTodoDraft) {
- setConfirmAgentId(agent.id);
- } else {
- setAgentId(agent.id);
- }
- setAssigneeOpen(false);
- }}
- className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors hover:bg-accent hover:text-accent-foreground"
- >
- <AgentIdentity agent={agent} size={18} />
- {agentId === agent.id ? <Check className="size-3.5 shrink-0" /> : null}
- </button>
- ))}
- </PopoverContent>
- </Popover>
- ) : (
- <span className="text-xs truncate">
- {detailAgent ? detailAgent.name : <span className="text-muted-foreground/70">Unassigned</span>}
- </span>
- )}
- </PropertyRow>
-
- {/* Status row (detail mode only) */}
- {mode === "detail" && issue && (
- <PropertyRow icon={<CircleDot className="size-3.5" />}>
- <Select
- value={issue.status}
- onValueChange={(val) => { if (val) handleStatusChange(val); }}
- items={(isTodoDraft ? (["todo", "done"] as const) : SELECTOR_STATUSES).map((s) => ({ value: s, label: statusLabel(s) }))}
- >
- <SelectTrigger className="h-7 w-auto border-none bg-transparent px-2 shadow-none text-xs text-foreground hover:bg-accent transition-colors rounded-md">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {(isTodoDraft
- ? (["todo", "done"] as const)
- : SELECTOR_STATUSES
- ).map((s) => (
- <SelectItem key={s} value={s}>{statusLabel(s)}</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </PropertyRow>
- )}
-
- {/* Chat link row */}
- {mode === "detail" && issue?.agent_id && issue?.conversation_id && (
- <PropertyRow icon={<MessageSquare className="size-3.5" />}>
- <Link
- href={`/w/${slug}/agents/${issue.agent_id}?conv=${issue.conversation_id}${issue.latest_task_id ? `&task=${issue.latest_task_id}` : ""}`}
- className={cn(GHOST_CONTROL, "inline-flex items-center rounded-md")}
- >
- Chat
- </Link>
- </PropertyRow>
- )}
-
- {/* Thread link row */}
- {mode === "detail" && detail?.traceId && (
- <PropertyRow icon={<GitBranch className="size-3.5" />}>
- <Link
- href={`/w/${slug}/traces/${detail.traceId}`}
- className={cn(GHOST_CONTROL, "inline-flex items-center rounded-md")}
- >
- Thread
- </Link>
- </PropertyRow>
- )}
- </div>
-
- {/* Description */}
- <div
- className={cn(
- "px-2 sm:px-3 py-2 flex-1 min-h-0 overflow-y-auto thin-scrollbar"
- )}
- ref={descriptionRef}
- >
- <MarkdownEditor
- key={issue?.id ?? "new"}
- value={description}
- onChange={(value) => editField("description", value)}
- placeholder="Describe the issue..."
- minHeight={mode === "create" ? "10rem" : "4rem"}
- variant="seamless"
- contentType="markdown"
- agents={agents}
- />
- </div>
-
- {/* Attachments (detail mode) */}
- {mode === "detail" && detail?.artifacts && detail.artifacts.length > 0 && (
- <div className="shrink-0 px-2 sm:px-3 py-2">
- <IssueAttachmentList artifacts={detail.artifacts} workspaceId={workspaceId} onArtifactClick={onArtifactClick} />
- </div>
- )}
- </>
- );
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent
- side="right"
- showCloseButton={false}
- className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border overflow-visible"
- style={{ width: `min(${width}px, 100vw)`, maxWidth: "none" }}
- >
- {/* Resize drag handle */}
- <SheetResizeHandle onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} />
-
- {/* Mobile close button */}
- <SheetClose
- render={<Button variant="ghost" size="icon-sm" />}
- className="absolute top-3 right-3 z-10 sm:hidden"
- >
- <XIcon />
- <span className="sr-only">Close</span>
- </SheetClose>
-
- {/* Timeline floating panel — desktop only, detail mode only, not for todo drafts */}
- {mode === "detail" && !isTodoDraft && (
- <div className="hidden lg:flex absolute right-full top-0 bottom-0 mr-2 w-90 flex-col rounded-xl border bg-background shadow-lg overflow-hidden">
- <div className="shrink-0 flex items-center border-b px-4 py-2">
- <span className="text-xs font-medium text-muted-foreground">Activity</span>
- </div>
- <div ref={timelineRef} className="flex-1 min-h-0 overflow-y-auto thin-scrollbar px-4 py-4 space-y-3">
- {timelineContent}
- </div>
- {commentInput && (
- <div className="shrink-0 border-t px-4 py-3">
- {commentInput}
- </div>
- )}
- </div>
- )}
-
- {/* Hidden accessible title */}
- <SheetTitle className="sr-only">
- {mode === "create" ? "New Issue" : (issue?.title ?? "Issue")}
- </SheetTitle>
-
- <div className="flex flex-1 min-h-0 flex-col" onKeyDownCapture={onKeyDownCapture}>
- {/* Mobile tab switcher (detail mode only, below lg, not for todo drafts) */}
- {mode === "detail" && !isTodoDraft && (
- <div className="shrink-0 flex items-center gap-1 border-b px-2 py-2 lg:hidden">
- <button
- type="button"
- onClick={() => setMobileTab("issue")}
- className={cn(
- "rounded-md px-2 py-1 text-xs font-medium transition-colors",
- mobileTab === "issue" ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground"
- )}
- >
- Issue
- </button>
- <button
- type="button"
- onClick={() => setMobileTab("activity")}
- className={cn(
- "rounded-md px-2 py-1 text-xs font-medium transition-colors",
- mobileTab === "activity" ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground"
- )}
- >
- Activity
- </button>
- </div>
- )}
-
- <SheetBody className="flex flex-col gap-0 p-0 overflow-hidden">
- {/* Issue form: always visible on desktop, tab-controlled on mobile */}
- <div className={cn(
- "flex flex-col flex-1 min-h-0",
- mode === "detail" && mobileTab === "activity" && "hidden lg:flex"
- )}>
- {issueFormContent}
- </div>
-
- {/* Mobile timeline view */}
- {mode === "detail" && !isTodoDraft && mobileTab === "activity" && (
- <div className="flex flex-col flex-1 min-h-0 lg:hidden">
- <div className="flex-1 min-h-0 overflow-y-auto thin-scrollbar px-3 py-4 space-y-3">
- {timelineContent}
- </div>
- {commentInput && (
- <div className="shrink-0 border-t px-3 py-3">
- {commentInput}
- </div>
- )}
- </div>
- )}
- </SheetBody>
-
- {/* Footer — create mode only */}
- {mode === "create" && (
- <SheetFooter>
- <Button
- variant="outline"
- size="sm"
- onClick={() => onOpenChange(false)}
- disabled={submitting}
- >
- Cancel
- </Button>
- <Button
- size="sm"
- onClick={handleCreate}
- disabled={!title.trim() || submitting}
- >
- {submitting && <Loader2 className="mr-2 size-3.5 animate-spin" />}
- <Kbd className="mr-1 hidden sm:inline-flex bg-background/20 text-inherit opacity-60">⇧ + ⏎</Kbd>
- Create
- </Button>
- </SheetFooter>
- )}
- </div>
- </SheetContent>
-
- {/* Dispatch confirmation dialog for todo draft issues */}
- <ConfirmDialog
- open={!!confirmAgent}
- onOpenChange={(open) => { if (!open) setConfirmAgentId(null); }}
- title="Run issue?"
- description={`This issue will be assigned to ${confirmAgent?.name ?? "the agent"} and start running immediately.`}
- confirmLabel="Run"
- loadingLabel="Running..."
- confirmVariant="default"
- loading={dispatching}
- onConfirm={async () => {
- if (!confirmAgent || !issue) return;
- const original = source.assertActive;
- original();
- const id = issue.id;
- const token = captureWorkspaceOwner(owner);
- try {
- await mutateIssue({ action: { kind: "update", id, patch: { agent_id: confirmAgent.id } }, token });
- original();
- setConfirmAgentId(null);
- onDispatched?.(id);
- } catch (e) {
- try { original(); } catch { return; }
- if (e instanceof DOMException && e.name === "AbortError") return;
- toast.error(e instanceof Error ? e.message : "Failed to dispatch issue");
- setConfirmAgentId(null);
- }
- }}
- />
- </Sheet>
- );
-}
diff --git a/src/web/src/components/mobile-top-bar.tsx b/src/web/src/components/mobile-top-bar.tsx
deleted file mode 100644
index 28ffb9cd5..000000000
--- a/src/web/src/components/mobile-top-bar.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-"use client";
-
-import { useRouter, usePathname } from "next/navigation";
-import { CalendarDays, CircleDot, Home } from "lucide-react";
-import { useSidebarTrigger } from "@/components/workspace-shell";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { AnimatedAvatar } from "@/components/avatar";
-import { Logo } from "@/components/logo";
-import { Skeleton } from "@/components/ui/skeleton";
-import { cn } from "@/lib/utils";
-
-export function MobileTopBar() {
- const router = useRouter();
- const pathname = usePathname();
- const openSidebar = useSidebarTrigger();
- const { slug } = useWorkspace();
- const { agents, pins, unpinnedOrder, runtimes, loading } = useAgentContext();
-
- const isHomeActive = pathname === `/w/${slug}/home`;
- const isCalendarActive = pathname.includes("/calendar");
- const isIssuesActive = pathname.includes("/issues");
- const activeAgentMatch = pathname.match(/^\/w\/[^/]+\/agents\/([^/]+)/);
- const activeAgentId = activeAgentMatch?.[1] ?? null;
-
- const pinned = agents
- .filter((a) => pins.has(a.id))
- .sort((a, b) => pins.get(a.id)!.position - pins.get(b.id)!.position);
-
- const unpinned = agents
- .filter((a) => !pins.has(a.id))
- .sort((a, b) => {
- const posA = unpinnedOrder.get(a.id);
- const posB = unpinnedOrder.get(b.id);
- if (posA !== undefined && posB !== undefined) return posA - posB;
- if (posA !== undefined) return -1;
- if (posB !== undefined) return 1;
- return a.name.localeCompare(b.name);
- });
-
- const ordered = [...pinned, ...unpinned];
-
- return (
- <div className="h-10 flex items-center gap-2 px-2 shrink-0">
- {openSidebar && (
- <div
- role="button"
- tabIndex={0}
- aria-label="Open sidebar"
- onClick={openSidebar}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- openSidebar();
- }
- }}
- className="shrink-0 cursor-pointer transition-opacity hover:opacity-70 [&>button]:pointer-events-none"
- >
- <Logo size="sm" iconOnly />
- </div>
- )}
-
- <button
- onClick={() => router.push(`/w/${slug}/home`)}
- aria-label="Home"
- className={cn(
- "shrink-0 p-1 rounded-md transition-colors",
- isHomeActive
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:text-foreground"
- )}
- >
- <Home className="size-4" />
- </button>
-
- <button
- onClick={() => router.push(`/w/${slug}/calendar`)}
- aria-label="Calendar"
- className={cn(
- "shrink-0 p-1 rounded-md transition-colors",
- isCalendarActive
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:text-foreground"
- )}
- >
- <CalendarDays className="size-4" />
- </button>
-
- <button
- onClick={() => router.push(`/w/${slug}/issues`)}
- aria-label="Issues"
- className={cn(
- "shrink-0 p-1 rounded-md transition-colors",
- isIssuesActive
- ? "text-foreground bg-muted"
- : "text-muted-foreground hover:text-foreground"
- )}
- >
- <CircleDot className="size-4" />
- </button>
-
- <div className="flex-1 overflow-x-auto flex items-center gap-2 py-1 px-1 scrollbar-none">
- {loading ? (
- <Skeleton className="size-7 rounded-full" />
- ) : (
- ordered.map((agent) => {
- const runtime = runtimes.find((r) => r.id === agent.runtime_id);
- const isOnline = runtime?.status === "online";
- const isActive = activeAgentId === agent.id;
-
- return (
- <button
- key={agent.id}
- onClick={() => router.push(`/w/${slug}/agents/${agent.id}`)}
- aria-label={agent.name}
- className={cn(
- "shrink-0 relative rounded-full transition-all",
- isActive && "ring-2 ring-primary/50"
- )}
- >
- <div className="size-7">
- <AnimatedAvatar seed={agent.id} avatarUrl={agent.avatar_url} size={28} className="rounded-full" isHovered={false} />
- </div>
- <span
- className={cn(
- "absolute -bottom-1 -right-1 size-2 rounded-full border border-background",
- isOnline ? "bg-emerald-500" : "bg-muted-foreground/40"
- )}
- />
- </button>
- );
- })
- )}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/nav-user.dom.test.ts b/src/web/src/components/nav-user.dom.test.ts
deleted file mode 100644
index e59c8d31f..000000000
--- a/src/web/src/components/nav-user.dom.test.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import { get, set } from "idb-keyval"
-import { openDB } from "idb"
-import { cloneElement, createElement, type PropsWithChildren, type ReactElement } from "react"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, fireEvent, render, screen, waitFor } from "@/test/react-dom-harness"
-import { NavUser } from "./nav-user"
-import { ApplicationQueryProvider, useApplicationOwner, type ApplicationOwner } from "@/lib/application-owner"
-import { clearAllPersistedCaches, createIdbPersister } from "@/lib/query-persister"
-let owner: ApplicationOwner
-function OwnerProbe() { const value = useApplicationOwner(); useLayoutEffect(() => { owner = value }); return createElement(NavUser) }
-function App({ userId = "user_1" }: { userId?: string }) { return createElement(ApplicationQueryProvider, { userId }, createElement(OwnerProbe)) }
-
-const mocks = vi.hoisted(() => ({
- routerPush: vi.fn(),
- signOut: vi.fn(),
- toastError: vi.fn(),
- session: {
- data: {
- user: {
- id: "user_1",
- name: "Ada",
- discriminator: "0042",
- email: "[email protected]",
- image: "https://cdn.example.com/ada.png",
- },
- },
- isPending: false,
- },
-}))
-
-vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.routerPush }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = {
- useSession: () => mocks.session,
- signOut: (...args: unknown[]) => mocks.signOut(...args),
-}; return { ...sessionSDK, signOutWithOrigin: async (assertActive: () => void, ...args: unknown[]) => { assertActive(); return sessionSDK.signOut(...args) }, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("sonner", () => ({ toast: { error: mocks.toastError } }))
-vi.mock("@/components/ui/dropdown-menu", () => ({
- DropdownMenu: ({ children }: PropsWithChildren) => createElement("div", null, children),
- DropdownMenuContent: ({ children }: PropsWithChildren) => createElement("div", null, children),
- DropdownMenuGroup: ({ children }: PropsWithChildren) => createElement("div", null, children),
- DropdownMenuItem: ({ children, ...props }: PropsWithChildren<Record<string, unknown>>) =>
- createElement("button", props, children),
- DropdownMenuLabel: ({ children }: PropsWithChildren) => createElement("div", null, children),
- DropdownMenuSeparator: () => createElement("hr"),
- DropdownMenuTrigger: ({ children, render: trigger }:
- PropsWithChildren<{ render: ReactElement }>) => cloneElement(trigger, {}, children),
-}))
-
-describe("NavUser avatar", () => {
- it("uses the session photo in both the trigger and open menu identity", async () => {
- render(createElement(App))
-
- await waitFor(() => expect(screen.getByTestId("nav-user-trigger")).toBeVisible())
- const triggerAvatar = screen.getByTestId("nav-user-trigger-avatar")
- const menuAvatar = screen.getByTestId("nav-user-menu-avatar")
- for (const avatar of [triggerAvatar, menuAvatar]) {
- expect(avatar).toHaveAttribute("data-avatar-kind", "photo")
- expect(avatar).toHaveStyle({ width: "28px", height: "28px" })
- }
- expect(screen.getByTestId("nav-user-trigger"))
- .toHaveAttribute("aria-label", "Open user menu for Ada")
- expect(renderedPhotos()).toEqual([
- "https://cdn.example.com/ada.png",
- "https://cdn.example.com/ada.png",
- ])
- })
-})
-
-function renderedPhotos(): string[] {
- return Array.from(
- document.querySelectorAll<HTMLImageElement>('[data-remote-image-kind="identity"]'),
- (image) => image.src,
- )
-}
-
-beforeEach(async () => {
- await act(async () => { await clearAllPersistedCaches(); }) ; mocks.routerPush.mockClear(); mocks.toastError.mockClear(); mocks.signOut.mockReset(); mocks.session.data.user.id = "user_1"
-})
-afterEach(() => owner?.queryClient.clear())
-describe("actual NavUser native logout", () => {
- it("confirmed SDK sign-out clears original native facts and both disk domains then navigates", async () => {
- mocks.signOut.mockImplementation(async (options) => { options.fetchOptions.onRequest(); options.fetchOptions.onSuccess(); return { data: { success: true } } })
- render(createElement(App)); await waitFor(() => expect(screen.getByRole("button", { name: "Log out" })).toBeTruthy())
- const community = createIdbPersister("user_1"), application = createIdbPersister("user_1", "application")
- const payload = { timestamp: Date.now(), buster: "v3", clientState: { queries: [], mutations: [] } }
- await act(async () => { await community.persistClient(payload); }) ; await act(async () => { await application.persistClient(payload) })
- for (const version of ["v1", "v2", "v3", "v99"]) {
- await act(async () => { await set(`alook:qc:${version}:user_1:client`, "original A") })
- await act(async () => { await set(`alook:qc:${version}:B:client`, "unrelated B") })
- await act(async () => { await set(`alook:qc:${version}:user_1:application:client`, "original application A") })
- await act(async () => { await set(`alook:qc:${version}:B:application:client`, "unrelated application B") })
- }
- const legacy = await openDB("alook-chat-cache-logout-boundary", 4, { upgrade(db) { db.createObjectStore("messages") } }); await legacy.put("messages", { text: "unqualified workspace" }, "m"); legacy.close()
- act(() => owner.queryClient.setQueryData(["original"], { private: "A" }))
- fireEvent.click(screen.getByRole("button", { name: "Log out" })); await waitFor(() => expect(mocks.routerPush).toHaveBeenCalledWith("/sign-in"))
- expect(owner.lifecycle.get().active).toBe(false); expect(owner.queryClient.getQueryData(["original"])).toBeUndefined()
- expect(await community.isCurrent()).toBe(false); expect(await application.isCurrent()).toBe(false); expect(mocks.toastError).not.toHaveBeenCalled()
- for (const version of ["v1", "v2", "v3", "v99"]) {
- expect(await get(`alook:qc:${version}:user_1:client`)).toBeUndefined()
- expect(await get(`alook:qc:${version}:user_1:application:client`)).toBeUndefined()
- expect(await get(`alook:qc:${version}:B:client`)).toBe("unrelated B")
- expect(await get(`alook:qc:${version}:B:application:client`)).toBe("unrelated application B")
- }
- expect((await indexedDB.databases()).map((database) => database.name)).toContain("alook-chat-cache-logout-boundary")
- })
- it("current SDK failure preserves facts and reports the failure", async () => {
- mocks.signOut.mockResolvedValue({ error: { message: "Cannot log out" } })
- render(createElement(App)); await waitFor(() => expect(screen.getByRole("button", { name: "Log out" })).toBeTruthy()); act(() => owner.queryClient.setQueryData(["original"], { private: "A" }))
- fireEvent.click(screen.getByRole("button", { name: "Log out" })); await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Cannot log out"))
- expect(owner.lifecycle.get().active).toBe(true); expect(owner.queryClient.getQueryData(["original"])).toEqual({ private: "A" }); expect(mocks.routerPush).not.toHaveBeenCalled()
- })
- it("confirmed SDK sign-out still navigates when original disk retirement rejects", async () => {
- const failure = new DOMException("IDB unavailable", "UnknownError")
- const diagnostic = vi.spyOn(console, "error").mockImplementation(() => undefined)
- try {
- mocks.signOut.mockImplementation(async (options) => { options.fetchOptions.onRequest(); options.fetchOptions.onSuccess(); return { data: { success: true } } })
- render(createElement(App))
- await waitFor(() => expect(screen.getByRole("button", { name: "Log out" })).toBeTruthy())
- const original = owner
- vi.spyOn(original, "retireDisk").mockRejectedValueOnce(failure)
- act(() => original.queryClient.setQueryData(["original"], { private: "A" }))
- fireEvent.click(screen.getByRole("button", { name: "Log out" }))
- await waitFor(() => expect(mocks.routerPush).toHaveBeenCalledWith("/sign-in"))
- expect(mocks.routerPush).toHaveBeenCalledTimes(1)
- expect(original.lifecycle.get().active).toBe(false)
- expect(original.queryClient.getQueryData(["original"])).toBeUndefined()
- expect(diagnostic).toHaveBeenCalledWith("Application disk cache retirement failed", failure)
- expect(mocks.toastError).not.toHaveBeenCalled()
- } finally { diagnostic.mockRestore() }
- })
- it("a held original disk rejection after switching viewer leaves B quiet", async () => {
- const failure = new DOMException("Original IDB unavailable", "UnknownError")
- const diagnostic = vi.spyOn(console, "error").mockImplementation(() => undefined)
- try {
- mocks.signOut.mockImplementation(async (options) => { options.fetchOptions.onRequest(); options.fetchOptions.onSuccess(); return { data: { success: true } } })
- const mounted = render(createElement(App))
- await waitFor(() => expect(screen.getByRole("button", { name: "Log out" })).toBeTruthy())
- const original = owner
- let reject!: (reason: unknown) => void
- vi.spyOn(original, "retireDisk").mockImplementationOnce(() => new Promise((_, fail) => { reject = fail }))
- fireEvent.click(screen.getByRole("button", { name: "Log out" }))
- await waitFor(() => expect(reject).toBeTypeOf("function"))
- mocks.session.data.user.id = "B"
- act(() => mounted.rerender(createElement(App, { userId: "B" })))
- await waitFor(() => expect(owner.userId).toBe("B"))
- act(() => owner.queryClient.setQueryData(["current"], { private: "B" }))
- await act(async () => reject(failure))
- expect(diagnostic).toHaveBeenCalledWith("Application disk cache retirement failed", failure)
- expect(owner.lifecycle.get().active).toBe(true)
- expect(owner.queryClient.getQueryData(["current"])).toEqual({ private: "B" })
- expect(mocks.routerPush).not.toHaveBeenCalled()
- expect(mocks.toastError).not.toHaveBeenCalled()
- } finally { diagnostic.mockRestore() }
- })
- it.each(["success", "failure"])("held old SDK %s after account switch leaves B quiet", async (kind) => {
- let settle!: (result: unknown) => void; let signal!: AbortSignal
- mocks.signOut.mockImplementation((options) => {
- options.fetchOptions.onRequest(); signal = options.fetchOptions.signal
- return new Promise((resolve) => { settle = resolve }).then((result) => { if (kind === "success") options.fetchOptions.onSuccess(); return result })
- })
- const mounted = render(createElement(App)); await waitFor(() => expect(screen.getByRole("button", { name: "Log out" })).toBeTruthy())
- fireEvent.click(screen.getByRole("button", { name: "Log out" })); await waitFor(() => expect(settle).toBeTypeOf("function")); mocks.session.data.user.id = "B"
- act(() => mounted.rerender(createElement(App, { userId: "B" }))); await waitFor(() => expect(owner.userId).toBe("B")); act(() => owner.queryClient.setQueryData(["current"], { private: "B" }))
- await act(async () => settle(kind === "success" ? { data: { success: true } } : { error: { message: "old failure" } }))
- expect(signal.aborted).toBe(true); expect(owner.lifecycle.get().active).toBe(true); expect(owner.queryClient.getQueryData(["current"])).toEqual({ private: "B" }); expect(mocks.routerPush).not.toHaveBeenCalled(); expect(mocks.toastError).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/components/nav-user.tsx b/src/web/src/components/nav-user.tsx
deleted file mode 100644
index 492ea954a..000000000
--- a/src/web/src/components/nav-user.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect } from "react";
-import { useRouter } from "next/navigation";
-import { useSession } from "@/lib/auth-client";
-import { assertApplicationOwner, captureApplicationOwner, useApplicationOwner } from "@/lib/application-owner";
-import { useApplicationSignOut } from "@/hooks/use-application-sign-out";
-import { toastApiError } from "@/lib/api/client";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Skeleton } from "@/components/ui/skeleton";
-import { LogOut } from "lucide-react";
-import { displayName } from "@/lib/community/display-name";
-import { ProfileAvatar } from "@/components/avatar";
-
-export function NavUser() {
- const { data: session, isPending } = useSession();
- const applicationOwner = useApplicationOwner();
- const logout = useApplicationSignOut();
- const router = useRouter();
- const [mounted, setMounted] = useAtom(useCreateAtom(false));
-
- useEffect(() => {
- setMounted(true);
- }, [setMounted]);
-
- const user = session?.user;
- if (!mounted || isPending || !user)
- return <Skeleton className="size-10 rounded-xl" />;
-
- const userDisplayName = displayName(user);
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <button
- type="button"
- title={user.name}
- aria-label={`Open user menu for ${userDisplayName}`}
- data-testid="nav-user-trigger"
- className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"
- />
- }
- >
- <ProfileAvatar
- label={userDisplayName}
- seed={user.id}
- src={user.image}
- size={28}
- alt=""
- data-testid="nav-user-trigger-avatar"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent
- className="min-w-52 rounded-lg"
- side="right"
- align="end"
- sideOffset={8}
- >
- <DropdownMenuGroup>
- <DropdownMenuLabel className="p-0 font-normal">
- <div className="flex items-center gap-2 px-2 py-2 text-left text-sm">
- <ProfileAvatar
- label={userDisplayName}
- seed={user.id}
- src={user.image}
- size={28}
- data-testid="nav-user-menu-avatar"
- />
- <div className="grid flex-1 text-left text-sm leading-tight">
- <span className="truncate font-medium">
- {userDisplayName}
- </span>
- <span className="truncate text-xs text-muted-foreground">
- {user.email}
- </span>
- </div>
- </div>
- </DropdownMenuLabel>
- </DropdownMenuGroup>
- <DropdownMenuSeparator />
- <DropdownMenuGroup>
- <DropdownMenuItem
- onClick={async () => {
- const token = captureApplicationOwner(applicationOwner);
- try { if (await logout.mutateAsync()) router.push("/sign-in"); }
- catch (error) { toastApiError(error, "Failed to log out", () => assertApplicationOwner(token)); }
- }}
- >
- <LogOut className="size-4" />
- Log out
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/src/web/src/components/runtime-select.tsx b/src/web/src/components/runtime-select.tsx
deleted file mode 100644
index 082807a61..000000000
--- a/src/web/src/components/runtime-select.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-"use client";
-
-import type { ComponentProps } from "react";
-import type { AgentRuntime as Runtime } from "@alook/shared";
-import { ProviderLogo } from "@/components/provider-logo";
-import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectContent,
- SelectItem,
- SelectGroup,
- SelectLabel,
-} from "@/components/ui/select";
-
-interface RuntimeSelectProps {
- value: string;
- onValueChange: (value: string) => void;
- runtimes: Runtime[];
- disabled?: boolean;
- triggerProps?: Omit<ComponentProps<typeof SelectTrigger>, "children">;
-}
-
-function groupRuntimes(runtimes: Runtime[]) {
- const groups = new Map<string, { label: string; runtimes: Runtime[] }>();
- for (const rt of runtimes) {
- const key = rt.daemon_id || rt.id;
- if (!groups.has(key)) {
- groups.set(key, {
- label:
- (typeof rt.device_info === "string" ? rt.device_info : "") ||
- key,
- runtimes: [],
- });
- }
- groups.get(key)!.runtimes.push(rt);
- }
- return groups;
-}
-
-function getPlaceholder(runtimes: Runtime[]) {
- if (runtimes.length === 0) return "No runtimes — start a daemon first";
- if (runtimes.every((r) => r.status !== "online")) return "All runtimes offline";
- return "Select a runtime";
-}
-
-export function RuntimeSelect({
- value,
- onValueChange,
- runtimes,
- disabled,
- triggerProps,
-}: RuntimeSelectProps) {
- const groups = groupRuntimes(runtimes);
- const allDisabled =
- disabled ||
- runtimes.length === 0 ||
- runtimes.every((r) => r.status !== "online");
-
- return (
- <Select
- value={value}
- onValueChange={(val: string | null) => {
- if (val) onValueChange(val);
- }}
- disabled={allDisabled}
- items={runtimes.map((rt) => {
- const machine =
- (typeof rt.device_info === "string" ? rt.device_info : "") ||
- "";
- const label = machine ? `${rt.provider} (${machine})` : rt.provider;
- return { value: rt.id, label };
- })}
- >
- <SelectTrigger {...triggerProps}>
- <SelectValue placeholder={getPlaceholder(runtimes)} />
- </SelectTrigger>
- <SelectContent>
- {Array.from(groups.entries()).map(([key, group]) => (
- <SelectGroup key={key}>
- <SelectLabel className="truncate">
- {group.label}
- </SelectLabel>
- {group.runtimes.map((rt) => (
- <SelectItem
- key={rt.id}
- value={rt.id}
- disabled={rt.status !== "online"}
- >
- <span className="flex items-center gap-2">
- <ProviderLogo provider={rt.provider} className="h-4 w-4" />
- <span>{rt.provider}</span>
- <span className="text-muted-foreground text-xs">
- ({rt.status})
- </span>
- </span>
- </SelectItem>
- ))}
- </SelectGroup>
- ))}
- </SelectContent>
- </Select>
- );
-}
diff --git a/src/web/src/components/runtime-version-gate.tsx b/src/web/src/components/runtime-version-gate.tsx
deleted file mode 100644
index 12998a688..000000000
--- a/src/web/src/components/runtime-version-gate.tsx
+++ /dev/null
@@ -1,170 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useRef } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { useWorkspaceOwner, captureWorkspaceOwner } from "@/contexts/workspace-context";
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";
-import { minCliVersionOptions } from "@/hooks/workspace/settings-query-options";
-import { useRuntimeCommand, usePendingRuntimeCommands } from "@/hooks/workspace/use-runtime-command";
-import { useAgentContext } from "@/contexts/agent-context";
-import { semverGte } from "@alook/shared";
-import { getAppMode, updateCmd } from "@/lib/utils";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { AlertTriangle, RefreshCw, Terminal } from "lucide-react";
-import { toast } from "sonner";
-import type { AgentRuntime } from "@alook/shared";
-
-export function RuntimeVersionGate() {
- const { runtimes } = useAgentContext();
- const owner = useWorkspaceOwner();
- const source = useWorkspaceViewSource(owner, "runtime-version-gate", true);
- const minVersion = useQuery(minCliVersionOptions(owner)).data?.min_cli_version;
- const command = useRuntimeCommand(owner);
- const pending = usePendingRuntimeCommands(owner);
- const [showManualHint, setShowManualHint] = useAtom(useCreateAtom(false));
- const hintTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
-
- const mode = getAppMode();
- const MANUAL_UPDATE_CMD = updateCmd();
-
- useEffect(() => {
- return () => {
- if (hintTimer.current) clearTimeout(hintTimer.current);
- };
- }, []);
-
- if (mode === "dev") return null;
- if (!minVersion) return null;
-
- const outdatedRuntimes = runtimes.filter((rt) => {
- if (rt.status !== "online") return false;
- const cliVersion = rt.metadata?.cli_version;
- if (typeof cliVersion !== "string" || !cliVersion) return true;
- return !semverGte(cliVersion, minVersion);
- });
-
- // Deduplicate by daemon_id — show one card per machine
- const outdatedMachines = new Map<string, AgentRuntime>();
- for (const rt of outdatedRuntimes) {
- const key = rt.daemon_id ?? rt.id;
- if (!outdatedMachines.has(key)) outdatedMachines.set(key, rt);
- }
-
- if (outdatedMachines.size === 0) return null;
-
- const handleUpdate = async (rt: AgentRuntime) => {
- if (mode === "app") {
- setShowManualHint(true);
- return;
- }
- const assertView = source.assertActive;
- if (!hintTimer.current) {
- hintTimer.current = setTimeout(() => {
- hintTimer.current = null;
- try { assertView(); } catch { return; }
- setShowManualHint(true);
- }, 5000);
- }
- try {
- await command.mutateAsync({ kind: "update", id: rt.id, token: captureWorkspaceOwner(owner) });
- assertView();
- } catch { }
- };
-
- return (
- <Dialog
- open
- modal
- disablePointerDismissal
- onOpenChange={() => {}}
- >
- <DialogContent showCloseButton={false}>
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <AlertTriangle className="size-5 text-amber-500" />
- Runtime Update Required
- </DialogTitle>
- <DialogDescription>
- {mode === "app"
- ? `Your local Alook app is running an outdated version (minimum required: v${minVersion}). Please update to continue.`
- : `The following machine(s) are running an outdated CLI version (minimum required: v${minVersion}). Please update to continue.`}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-3 mt-2">
- {[...outdatedMachines.entries()].map(([daemonId, rt]) => {
- const cliVersion = rt.metadata?.cli_version as string | undefined;
- const isUpdating = !!rt.pending_update_version || pending.some((intent) => intent.id === rt.id && intent.kind === "update");
-
- return (
- <div
- key={daemonId}
- className="flex items-center justify-between rounded-lg border p-3"
- >
- <div className="flex items-center gap-3 min-w-0">
- <span className="size-2 shrink-0 rounded-full bg-emerald-500" />
- <div className="min-w-0">
- <div className="text-sm font-medium truncate">
- {rt.device_info || daemonId.slice(0, 12)}
- </div>
- <div className="text-xs text-muted-foreground flex items-center gap-2 mt-1">
- <span>{cliVersion ? `v${cliVersion}` : "Version unavailable"}</span>
- <Badge variant="outline" className="text-[10px] px-2 py-0 text-amber-500 border-amber-500/30">
- requires v{minVersion}
- </Badge>
- </div>
- </div>
- </div>
- <Button
- size="sm"
- variant="outline"
- disabled={isUpdating}
- onClick={() => handleUpdate(rt)}
- >
- <RefreshCw className={`size-3.5 ${isUpdating ? "animate-spin" : ""}`} />
- {isUpdating ? "Updating..." : "Update"}
- </Button>
- </div>
- );
- })}
- </div>
-
- {showManualHint && (
- <div className="mt-3 rounded-md bg-muted/50 border border-dashed p-2 text-xs text-muted-foreground">
- <div className="flex items-center gap-2 font-medium text-foreground mb-1">
- <Terminal className="size-3" />
- Update taking too long?
- </div>
- <p className="mb-1">Run this command on the machine to update manually:</p>
- <Tooltip>
- <TooltipTrigger
- render={
- <code
- className="block rounded bg-background px-2 py-1 font-mono text-[11px] cursor-pointer hover:bg-background/80 transition-colors"
- onClick={() => {
- navigator.clipboard.writeText(MANUAL_UPDATE_CMD);
- toast.success("Copied to clipboard");
- }}
- />
- }
- >
- {MANUAL_UPDATE_CMD}
- </TooltipTrigger>
- <TooltipContent>Click to copy</TooltipContent>
- </Tooltip>
- </div>
- )}
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/src/web/src/components/sidebar/agent-sidebar-button.tsx b/src/web/src/components/sidebar/agent-sidebar-button.tsx
deleted file mode 100644
index 985bed9d9..000000000
--- a/src/web/src/components/sidebar/agent-sidebar-button.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-
-import type { Agent } from "@alook/shared";
-import { cn } from "@/lib/utils";
-import { PinIcon, PinOffIcon } from "lucide-react";
-import {
- ContextMenu,
- ContextMenuTrigger,
- ContextMenuContent,
- ContextMenuItem,
-} from "@/components/ui/context-menu";
-import { AgentPreviewCard } from "@/components/agent-preview-card";
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
-import { AnimatedAvatar } from "@/components/avatar/animated-avatar";
-
-export function AgentSidebarButton({
- agent,
- isActive,
- isPinned,
- isOnline,
- taskCount,
- onClick,
- onPin,
- onUnpin,
- extraContextMenuItems,
- hidePin,
- isDragActive,
-}: {
- agent: Agent;
- isActive: boolean;
- isPinned: boolean;
- isOnline: boolean;
- taskCount: number;
- onClick: () => void;
- onPin: () => void;
- onUnpin: () => void;
- extraContextMenuItems?: React.ReactNode;
- hidePin?: boolean;
- isDragActive?: boolean;
-}) {
- const [previewOpen, setPreviewOpen] = useAtom(useCreateAtom(false));
- return (
- <Popover
- open={previewOpen}
- onOpenChange={(open, event) => {
- if (open && event.reason === "trigger-press") return;
- setPreviewOpen(open);
- }}
- >
- <ContextMenu>
- <PopoverTrigger
- openOnHover={!isDragActive}
- delay={200}
- render={
- <ContextMenuTrigger
- render={
- <button
- type="button"
- onClick={() => { setPreviewOpen(false); onClick(); }}
- className={cn(
- "relative flex shrink-0 items-center justify-center size-10 text-sm font-medium transition-all duration-200 cursor-pointer",
- // Corner radius morphs WITH the avatar (both round↔rounded-xl)
- // so the ring — which hugs the button's corners — reshapes in
- // lockstep with the avatar instead of staying a fixed square
- // outline while the avatar rounds.
- isActive ? "rounded-xl" : "rounded-[20px]",
- isActive
- ? "ring-2 ring-primary/50 shadow-sm"
- : "ring-0 bg-secondary text-secondary-foreground hover:bg-accent"
- )}
- />
- }
- />
- }
- >
- <AnimatedAvatar
- seed={agent.id}
- avatarUrl={agent.avatar_url}
- size={40}
- className={cn("transition-all duration-200", isActive ? "rounded-xl" : "rounded-[20px]")}
- isHovered={false}
- />
- <span className={cn(
- "absolute bottom-0 right-0 size-2 rounded-full ring-2 ring-background",
- isOnline ? "bg-status-online" : "bg-status-offline"
- )} />
- </PopoverTrigger>
- <ContextMenuContent>
- {!hidePin && (isPinned ? (
- <ContextMenuItem onClick={onUnpin}>
- <PinOffIcon className="size-3.5 mr-2" />
- Unpin
- </ContextMenuItem>
- ) : (
- <ContextMenuItem onClick={onPin}>
- <PinIcon className="size-3.5 mr-2" />
- Pin to top
- </ContextMenuItem>
- ))}
- {extraContextMenuItems}
- </ContextMenuContent>
- </ContextMenu>
- <PopoverContent side="right" className="w-fit max-w-80">
- <AgentPreviewCard agent={agent} isOnline={isOnline} activeTaskCount={taskCount} />
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/src/web/src/components/sidebar/folder-collapsed.tsx b/src/web/src/components/sidebar/folder-collapsed.tsx
deleted file mode 100644
index 8965435ba..000000000
--- a/src/web/src/components/sidebar/folder-collapsed.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-"use client";
-
-import type { Agent } from "@alook/shared";
-import type { AgentFolder } from "@/hooks/use-agent-folders";
-import { AnimatedAvatar } from "@/components/avatar/animated-avatar";
-import { cn } from "@/lib/utils";
-
-const MAX_STACKED = 3;
-
-export function FolderCollapsed({
- folder,
- agents,
- isActive,
- onClick,
-}: {
- folder: AgentFolder;
- agents: Agent[];
- isActive: boolean;
- onClick: () => void;
-}) {
- const folderAgents = folder.agentIds
- .map((id) => agents.find((a) => a.id === id))
- .filter(Boolean) as Agent[];
-
- const displayed = folderAgents.slice(0, MAX_STACKED);
- const remaining = folderAgents.length - displayed.length;
-
- return (
- <button
- type="button"
- onClick={onClick}
- className={cn(
- "relative flex shrink-0 items-center justify-center size-10 rounded-xl transition-all duration-200 cursor-pointer",
- "bg-secondary/50 border border-border/30",
- isActive
- ? "ring-2 ring-primary/50 shadow-sm"
- : "hover:bg-accent"
- )}
- >
- <div className="relative flex items-center justify-center" style={{ width: 30, height: 20 }}>
- {displayed.map((agent, i) => {
- const offset = i * 6;
- return (
- <div
- key={agent.id}
- className="absolute rounded-full overflow-hidden ring-1 ring-background"
- style={{
- width: 20,
- height: 20,
- left: offset,
- zIndex: i + 1,
- }}
- >
- <AnimatedAvatar seed={agent.id} avatarUrl={agent.avatar_url} size={20} className="rounded-full" isHovered={false} />
- </div>
- );
- })}
- </div>
- {remaining > 0 && (
- <span className="absolute bottom-0 right-0 flex items-center justify-center min-w-3.5 h-3.5 rounded-full bg-muted text-muted-foreground text-[8px] font-bold ring-1 ring-background">
- +{remaining}
- </span>
- )}
- </button>
- );
-}
diff --git a/src/web/src/components/sidebar/folder-popover.tsx b/src/web/src/components/sidebar/folder-popover.tsx
deleted file mode 100644
index 81d7c2cd6..000000000
--- a/src/web/src/components/sidebar/folder-popover.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-"use client";
-
-import type { Agent } from "@alook/shared";
-import type { AgentFolder } from "@/hooks/use-agent-folders";
-import { AgentSidebarButton } from "./agent-sidebar-button";
-import { ContextMenuItem } from "@/components/ui/context-menu";
-import { PinOffIcon } from "lucide-react";
-import {
- DndContext,
- closestCenter,
- PointerSensor,
- useSensor,
- useSensors,
- type DragEndEvent,
-} from "@dnd-kit/core";
-import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
-import {
- SortableContext,
- verticalListSortingStrategy,
- useSortable,
- arrayMove,
-} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { Popover } from "@base-ui/react/popover";
-
-function SortablePopoverAgent({
- id,
- children,
-}: {
- id: string;
- children: React.ReactNode;
-}) {
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- isDragging,
- } = useSortable({ id });
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- opacity: isDragging ? 0.5 : 1,
- zIndex: isDragging ? 10 : undefined,
- };
- return (
- <div ref={setNodeRef} style={style} {...attributes} {...listeners}>
- {children}
- </div>
- );
-}
-
-export function FolderPopover({
- folder,
- agents,
- activeAgentId,
- isOnline,
- taskCounts,
- anchorRef,
- onAgentClick,
- onRemoveFromFolder,
- onPinAgent,
- onReorder,
- onClose,
-}: {
- folder: AgentFolder;
- agents: Agent[];
- activeAgentId: string | null;
- isOnline: boolean;
- taskCounts: Record<string, number>;
- anchorRef: HTMLElement | null;
- onAgentClick: (agentId: string) => void;
- onRemoveFromFolder: (agentId: string) => void;
- onPinAgent: (agentId: string) => void;
- onReorder: (orderedAgentIds: string[]) => void;
- onClose: () => void;
-}) {
- const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 5 } })
- );
-
- const folderAgents = folder.agentIds
- .map((id) => agents.find((a) => a.id === id))
- .filter(Boolean) as Agent[];
-
- function handleDragEnd(event: DragEndEvent) {
- const { active, over } = event;
- if (!over || active.id === over.id) return;
- const oldIndex = folder.agentIds.indexOf(active.id as string);
- const newIndex = folder.agentIds.indexOf(over.id as string);
- onReorder(arrayMove(folder.agentIds, oldIndex, newIndex));
- }
-
- if (!anchorRef) return null;
-
- return (
- <Popover.Root open onOpenChange={(open) => { if (!open) onClose(); }}>
- <Popover.Portal>
- <Popover.Positioner
- anchor={anchorRef}
- side="inline-end"
- sideOffset={8}
- align="start"
- >
- <Popover.Popup className="z-50 bg-popover border rounded-xl shadow-md p-2 animate-in fade-in-0 zoom-in-95 outline-none">
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- modifiers={[restrictToVerticalAxis]}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={folder.agentIds}
- strategy={verticalListSortingStrategy}
- >
- <div className="flex flex-col gap-1">
- {folderAgents.map((agent) => (
- <SortablePopoverAgent key={agent.id} id={agent.id}>
- <AgentSidebarButton
- agent={agent}
- isActive={activeAgentId === agent.id}
- isPinned={false}
- isOnline={isOnline}
- taskCount={taskCounts[agent.id] ?? 0}
- hidePin
- onClick={() => {
- onAgentClick(agent.id);
- onClose();
- }}
- onPin={() => {
- onPinAgent(agent.id);
- onClose();
- }}
- onUnpin={() => {}}
- extraContextMenuItems={
- <ContextMenuItem
- onClick={() => onRemoveFromFolder(agent.id)}
- >
- <PinOffIcon className="size-3.5 mr-2" />
- Remove from group
- </ContextMenuItem>
- }
- />
- </SortablePopoverAgent>
- ))}
- </div>
- </SortableContext>
- </DndContext>
- </Popover.Popup>
- </Popover.Positioner>
- </Popover.Portal>
- </Popover.Root>
- );
-}
diff --git a/src/web/src/components/sidebar/sortable-folder-item.tsx b/src/web/src/components/sidebar/sortable-folder-item.tsx
deleted file mode 100644
index b21073140..000000000
--- a/src/web/src/components/sidebar/sortable-folder-item.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-"use client";
-
-import type { Agent } from "@alook/shared";
-import type { AgentFolder } from "@/hooks/use-agent-folders";
-import { useSortable } from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { FolderCollapsed } from "./folder-collapsed";
-
-export function SortableFolderItem({
- folder,
- agents,
- isActive,
- isMergeTarget,
- dragActiveId,
- onExpand,
- nodeRefCallback,
-}: {
- folder: AgentFolder;
- agents: Agent[];
- isActive: boolean;
- isMergeTarget: boolean;
- dragActiveId?: string | null;
- onExpand: () => void;
- nodeRefCallback?: (el: HTMLElement | null) => void;
-}) {
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- isDragging,
- } = useSortable({ id: folder.id });
-
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- opacity: isDragging ? 0.5 : 1,
- zIndex: isDragging ? 10 : undefined,
- };
-
- return (
- <div
- ref={(el) => {
- setNodeRef(el);
- nodeRefCallback?.(el);
- }}
- style={style}
- {...attributes}
- {...listeners}
- className="transition-all duration-200"
- >
- <FolderCollapsed
- folder={isMergeTarget && dragActiveId
- ? { ...folder, agentIds: [...folder.agentIds, dragActiveId] }
- : folder}
- agents={agents}
- isActive={isActive}
- onClick={onExpand}
- />
- </div>
- );
-}
diff --git a/src/web/src/components/signin-tracker.test.ts b/src/web/src/components/signin-tracker.test.ts
deleted file mode 100644
index 7a88290f7..000000000
--- a/src/web/src/components/signin-tracker.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
-
-const mockSendGTMEvent = vi.fn()
-vi.mock("@next/third-parties/google", () => ({
- sendGTMEvent: (...args: unknown[]) => mockSendGTMEvent(...args),
-}))
-vi.mock("@/lib/analytics-consent", () => ({
- hasAnalyticsConsent: () => true,
-}))
-
-vi.mock("react", () => ({
- useEffect: (fn: () => void) => fn(),
-}))
-
-describe("SigninTracker", () => {
- let cookieValue = ""
- let cookieSetValue = ""
-
- beforeEach(() => {
- vi.clearAllMocks()
- cookieValue = ""
- cookieSetValue = ""
- // @ts-expect-error stub global document
- globalThis.document = {
- get cookie() { return cookieValue },
- set cookie(val: string) { cookieSetValue = val },
- }
- })
-
- afterEach(() => {
- // @ts-expect-error cleanup
- delete globalThis.document
- })
-
- it("fires sign_in_success event and clears cookie when is_sign_in is present", async () => {
- cookieValue = "is_sign_in=email_otp"
- vi.resetModules()
- const { SigninTracker } = await import("./signin-tracker")
- SigninTracker()
-
- expect(mockSendGTMEvent).toHaveBeenCalledWith({ event: "sign_in_success", method: "email_otp" })
- expect(cookieSetValue).toBe("is_sign_in=; max-age=0; path=/")
- })
-
- it("does nothing when is_sign_in cookie is absent", async () => {
- cookieValue = "other_cookie=value"
- vi.resetModules()
- const { SigninTracker } = await import("./signin-tracker")
- SigninTracker()
-
- expect(mockSendGTMEvent).not.toHaveBeenCalled()
- })
-
- it("handles github method correctly", async () => {
- cookieValue = "session=abc; is_sign_in=github; other=xyz"
- vi.resetModules()
- const { SigninTracker } = await import("./signin-tracker")
- SigninTracker()
-
- expect(mockSendGTMEvent).toHaveBeenCalledWith({ event: "sign_in_success", method: "github" })
- })
-
- it("handles google method correctly", async () => {
- cookieValue = "is_sign_in=google"
- vi.resetModules()
- const { SigninTracker } = await import("./signin-tracker")
- SigninTracker()
-
- expect(mockSendGTMEvent).toHaveBeenCalledWith({ event: "sign_in_success", method: "google" })
- })
-})
diff --git a/src/web/src/components/signin-tracker.tsx b/src/web/src/components/signin-tracker.tsx
deleted file mode 100644
index 523b07923..000000000
--- a/src/web/src/components/signin-tracker.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-"use client"
-
-import { useEffect } from "react"
-import { trackSignInSuccess } from "@/lib/analytics"
-
-export function SigninTracker() {
- useEffect(() => {
- const match = document.cookie.match(/(?:^|; )is_sign_in=([^;]*)/)
- if (!match) return
- const method = decodeURIComponent(match[1])
- trackSignInSuccess(method)
- document.cookie = "is_sign_in=; max-age=0; path=/"
- }, [])
-
- return null
-}
diff --git a/src/web/src/components/studio-onboarding/scenario-picker.tsx b/src/web/src/components/studio-onboarding/scenario-picker.tsx
deleted file mode 100644
index 1822d947d..000000000
--- a/src/web/src/components/studio-onboarding/scenario-picker.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import { SCENARIO_PRESETS, type ScenarioId } from "./scenario-presets";
-
-export function ScenarioPicker({
- selected,
- onSelect,
- onBrowseTemplates,
-}: {
- selected: ScenarioId | null;
- onSelect: (id: ScenarioId) => void;
- onBrowseTemplates?: () => void;
-}) {
- return (
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <h2 className="text-base font-semibold tracking-tight">What will your company focus on?</h2>
- {onBrowseTemplates && (
- <button
- type="button"
- onClick={onBrowseTemplates}
- className="text-[11px] text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2"
- >
- Browse templates <span aria-hidden="true">&rsaquo;</span>
- </button>
- )}
- </div>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- {SCENARIO_PRESETS.map((s) => (
- <button
- key={s.id}
- onClick={() => onSelect(s.id)}
- className={cn(
- "flex flex-col items-start gap-1 rounded-lg border p-4 text-left transition-all hover:border-foreground/30",
- selected === s.id
- ? "border-foreground/50 bg-muted/50"
- : "border-border",
- )}
- >
- <div className="flex items-center justify-between w-full">
- <span className="text-lg">{s.icon}</span>
- <span className="text-[10px] text-muted-foreground/70">
- {s.members.length} agent{s.members.length > 1 ? "s" : ""}
- </span>
- </div>
- <span className="text-sm font-medium">{s.label}</span>
- <span className="text-xs text-muted-foreground leading-tight">
- {s.description}
- </span>
- </button>
- ))}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/studio-onboarding/scenario-presets.ts b/src/web/src/components/studio-onboarding/scenario-presets.ts
deleted file mode 100644
index f94298cbc..000000000
--- a/src/web/src/components/studio-onboarding/scenario-presets.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-export type ScenarioId = "software-dev" | "content-research" | "personal-assistant" | "sales-outreach" | "customer-support" | "custom";
-
-export type MemberRole = "leader" | "researcher" | "engineer" | "assistant";
-
-export interface ScenarioMemberPreset {
- role: MemberRole;
- description: string;
- instructions: string;
- relationship?: string;
-}
-
-export interface ScenarioPreset {
- id: ScenarioId;
- label: string;
- description: string;
- icon: string;
- members: ScenarioMemberPreset[];
-}
-
-// --- Leader: scenario-specific ---
-
-const LEADER_INSTRUCTIONS = `You are the lead coordinator. You receive tasks from the user and decide how to handle them.
-
-## Principles
-- You are the user's single point of contact. Delegate to specialists when their expertise adds value; handle simple tasks yourself for speed.
-- Every delegation must be self-contained: clear goal, full context, and acceptance criteria so the specialist can succeed without back-and-forth.
-- When specialists report back, verify key claims on high-stakes outputs before passing to the user.
-- Synthesize specialist work into clear, concise responses. Credit teammates naturally.
-- If a delegation fails or a specialist is blocked, report back to the user with what happened and your next step.
-- Be warm but concise. Never ask "should I continue?" — if you have what you need, keep moving.`;
-
-const LEADER_PERSONAL_ASSISTANT = `You are a personal AI assistant. You work solo — no team to delegate to.
-
-## Principles
-- Handle tasks directly: emails, research, scheduling, writing, analysis — whatever comes your way.
-- Be fast, accurate, and proactive. Suggest next steps when you see opportunities.
-- Lead with the answer or deliverable, then context if needed.
-- For complex tasks, break into steps and work through them methodically.
-- Match the user's tone. Be concise — they want results, not status reports.
-- If genuinely ambiguous, ask one focused question. Otherwise, keep moving.`;
-
-// --- Researcher: scenario-specific ---
-
-const RESEARCHER_SOFTWARE_DEV = `You are the technical research specialist. You read codebases, explore APIs, review documentation, and gather context for engineering decisions.
-
-## Principles
-- Find technical truth: read code, trace execution paths, compare options with real trade-offs.
-- Lead with the recommendation, then supporting evidence. Cite sources: file paths, docs, code lines.
-- Be explicit about confidence — distinguish "verified in source" from "docs claim X."
-- If a request is ambiguous, ask one focused clarification before starting.
-- Density over volume. Engineers want answers, not essays.`;
-
-const RESEARCHER_CONTENT = `You are the content research specialist. You find information, verify facts, compare sources, and organize references for accurate content production.
-
-## Principles
-- Cross-reference claims from multiple sources. Never trust a single source for important facts.
-- Lead with key findings the writer needs, then supporting detail.
-- Cite everything: URLs, publication dates, author credentials. Note source freshness.
-- If sources conflict, explain the disagreement and which to trust.
-- If something can't be verified, say so clearly. Separate facts from opinions.`;
-
-const RESEARCHER_SALES = `You are the sales research specialist. You find prospects, research companies, and gather actionable intelligence for outreach.
-
-## Principles
-- Every finding should be actionable — not academic. Focus on: who to contact, what they care about, how to position.
-- For prospects, prioritize buying-intent signals: recent funding, tech stack changes, hiring patterns, pain points.
-- Lead with the most actionable finding. Cite sources with dates and reliability indicators.
-- Synthesize into intelligence, not data dumps. Sales moves fast — timeliness over completeness.`;
-
-// --- Engineer ---
-
-const ENGINEER_INSTRUCTIONS = `You are the engineering specialist. You write code, run tests, debug issues, and verify implementations.
-
-## Principles
-- Ship working code. Verify every change before reporting done.
-- Follow existing patterns. Keep changes minimal and focused on the task.
-- If requirements are unclear or you see multiple valid approaches, ask before coding — not mid-way through.
-- Self-review before reporting: completeness, edge cases, test coverage.
-- If unsure, say so. Bad code is worse than no code.`;
-
-// --- Assistant: scenario-specific ---
-
-const ASSISTANT_CONTENT = `You are the content operations specialist. You handle formatting, publishing workflows, and keep the content pipeline on schedule.
-
-## Principles
-- Content gets published on time, in the right format, to the right channels.
-- Match formatting to each platform's conventions. Proofread for obvious errors.
-- Track what's published, pending, and overdue. Follow up proactively.
-- Never publish without confirming the final version with the leader.`;
-
-const ASSISTANT_SALES = `You are the sales operations specialist. You handle outreach emails, follow-ups, and pipeline logistics.
-
-## Principles
-- Deals die in the follow-up gap. Every prospect gets timely, personalized communication.
-- Subject lines: specific and intriguing. Body: short, personalized first line, clear CTA.
-- Follow-ups reference previous context and add new value — never just "checking in."
-- Track interactions and flag cold deals. Escalate after two unanswered follow-ups.`;
-
-const ASSISTANT_SUPPORT = `You are the customer support specialist. You draft responses to inquiries and track issues to resolution.
-
-## Principles
-- Every interaction builds trust. Be empathetic, accurate, and efficient — resolve on first response when possible.
-- Lead with acknowledgment, then solution or clear next steps. Use simple language.
-- If you can't resolve immediately, set realistic expectations: what you'll do, by when.
-- Track open issues proactively. Escalate complex or sensitive cases with full context.`;
-
-export const SCENARIO_PRESETS: ScenarioPreset[] = [
- {
- id: "software-dev",
- label: "Software Development",
- description: "Build and ship code with a coordinated dev team",
- icon: "🖥",
- members: [
- { role: "leader", description: "Coordinates work, summarizes results, and replies to you", instructions: LEADER_INSTRUCTIONS },
- {
- role: "engineer",
- description: "Writes code, runs tests, and verifies implementations",
- instructions: ENGINEER_INSTRUCTIONS,
- relationship: "Delegate coding tasks with: clear requirement description, acceptance criteria (3-5 specific testable items), relevant file paths, existing patterns to follow, and context from research findings if applicable.\n\nReport back with: implementation status, files changed, acceptance criteria checklist (pass/fail each), test results, and self-review concerns. After implementation, send work to the reviewer if one exists.",
- },
- {
- role: "researcher",
- description: "Reads code, explores APIs, and gathers technical context",
- instructions: RESEARCHER_SOFTWARE_DEV,
- relationship: "Delegate technical research with: what to investigate, what decision it informs, scope boundary, and relevant file paths or code pointers.\n\nReport back with: technical summary, evidence (file paths, doc URLs, code snippets), recommendation, and confidence level (High/Medium/Low). Flag anything unverified.",
- },
- ],
- },
- {
- id: "content-research",
- label: "Content & Research",
- description: "Research topics, write content, and manage publishing",
- icon: "📝",
- members: [
- { role: "leader", description: "Coordinates work, shapes content direction, and delivers output", instructions: LEADER_INSTRUCTIONS },
- {
- role: "researcher",
- description: "Finds sources, verifies facts, and organizes references",
- instructions: RESEARCHER_CONTENT,
- relationship: "Delegate content research with: topic or claim to investigate, target content format (article, report, social), depth needed, and specific sources to check if any.\n\nReport back with: key facts for the writer, organized source list (URL, date, reliability), verification gaps, framing suggestion, and per-claim confidence.",
- },
- {
- role: "assistant",
- description: "Handles formatting, publishing workflows, and follow-ups",
- instructions: ASSISTANT_CONTENT,
- relationship: "Delegate content operations with: what content to format or publish, target platform, deadline, and style requirements.\n\nReport back with: what was done (formatted, published, submitted), next step (awaiting review, scheduled date), and blockers if any.",
- },
- ],
- },
- {
- id: "personal-assistant",
- label: "Personal Assistant",
- description: "One AI that handles your everyday tasks and communications",
- icon: "🤖",
- members: [
- { role: "leader", description: "Handles all tasks directly — emails, research, scheduling, and more", instructions: LEADER_PERSONAL_ASSISTANT },
- ],
- },
- {
- id: "sales-outreach",
- label: "Sales & Outreach",
- description: "Prospect, follow up, and close deals as a team",
- icon: "📈",
- members: [
- { role: "leader", description: "Coordinates outreach strategy and manages deal flow", instructions: LEADER_INSTRUCTIONS },
- {
- role: "researcher",
- description: "Researches prospects, companies, and market intelligence",
- instructions: RESEARCHER_SALES,
- relationship: "Delegate prospect research with: target criteria, market or industry focus, what intelligence is needed, and how it will be used (outreach, pitch, proposal).\n\nReport back with: prioritized prospect list (name, role, company, relevance, suggested angle), market signals, and confidence per finding.",
- },
- {
- role: "assistant",
- description: "Handles outreach emails, follow-ups, and pipeline tracking",
- instructions: ASSISTANT_SALES,
- relationship: "Delegate outreach with: who to contact, messaging angle, follow-up cadence, and desired outcome.\n\nReport back with: emails sent or scheduled, responses received, pipeline updates, and deals needing escalation.",
- },
- ],
- },
- {
- id: "customer-support",
- label: "Customer Support",
- description: "Handle tickets, draft replies, and track resolutions",
- icon: "🎧",
- members: [
- { role: "leader", description: "Coordinates support queue and handles escalations", instructions: LEADER_INSTRUCTIONS },
- {
- role: "assistant",
- description: "Drafts customer responses and tracks open issues",
- instructions: ASSISTANT_SUPPORT,
- relationship: "Delegate support tasks with: customer issue summary, urgency level, prior interaction context, and resolution approach.\n\nReport back with: response drafted or sent, resolution status, follow-up schedule, and recurring patterns to flag.",
- },
- ],
- },
- {
- id: "custom",
- label: "Custom",
- description: "Build your own team from scratch",
- icon: "✨",
- members: [
- { role: "leader", description: "Coordinates work and replies to you", instructions: LEADER_INSTRUCTIONS },
- ],
- },
-];
-
-import { uniqueNamesGenerator, names } from "unique-names-generator";
-import { nanoid } from "nanoid";
-import { randomBeamAvatar } from "@/lib/avatar/seed-url";
-
-export function shuffleMembers(count: number): { uid: string; name: string; avatarUrl: string }[] {
- const used = new Set<string>();
- const result: { uid: string; name: string; avatarUrl: string }[] = [];
- for (let i = 0; i < count; i++) {
- let name: string;
- let attempts = 0;
- do {
- name = uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" });
- attempts++;
- } while (used.has(name) && attempts < 100);
- used.add(name);
- result.push({
- uid: nanoid(),
- name,
- avatarUrl: randomBeamAvatar(),
- });
- }
- return result;
-}
diff --git a/src/web/src/components/studio-onboarding/team-preview.tsx b/src/web/src/components/studio-onboarding/team-preview.tsx
deleted file mode 100644
index c26f36fbb..000000000
--- a/src/web/src/components/studio-onboarding/team-preview.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import { Button } from "@/components/ui/button";
-import { Card } from "@/components/ui/card";
-import { RefreshCw } from "lucide-react";
-import { AgentAvatar } from "@/components/avatar";
-import {
- Select,
- SelectTrigger,
- SelectContent,
- SelectItem,
-} from "@/components/ui/select";
-import { ProviderLogo } from "@/components/provider-logo";
-import { toAlookAddress } from "@alook/shared";
-import type { AgentRuntime as Runtime } from "@alook/shared";
-import type { MemberRole } from "./scenario-presets";
-
-export interface TeamMember {
- uid: string;
- name: string;
- role: MemberRole;
- description: string;
- instructions: string;
- avatarUrl: string;
- runtimeId: string;
- emailHandle?: string;
- relationship?: string;
-}
-
-const ROLE_LABELS: Record<MemberRole, string> = {
- leader: "Lead",
- researcher: "Researcher",
- engineer: "Engineer",
- assistant: "Assistant",
-};
-
-export function TeamPreview({
- members,
- runtimes,
- onShuffle,
- onAssignRuntime,
-}: {
- members: TeamMember[];
- runtimes: Runtime[];
- onShuffle: () => void;
- onAssignRuntime?: (memberIndex: number, runtimeId: string) => void;
-}) {
- const showRuntimePicker = runtimes.length > 1 && onAssignRuntime;
-
- return (
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <h2 className="text-base font-semibold tracking-tight">Your company</h2>
- <Button variant="ghost" size="sm" onClick={onShuffle} className="h-7 text-xs gap-2">
- <RefreshCw className="size-3" />
- Shuffle
- </Button>
- </div>
- <div
- className={cn(
- "grid gap-3 grid-cols-1",
- members.length === 2 && "sm:grid-cols-2",
- members.length === 3 && "sm:grid-cols-2 sm:grid-cols-3",
- members.length >= 4 && "sm:grid-cols-2 sm:grid-cols-4",
- )}
- >
- {members.map((m, i) => {
- return (
- <Card key={i} size="sm" className="flex flex-col px-3 py-4 gap-2 h-full">
- {/* Header: avatar + name/badge */}
- <div className="flex items-center gap-2">
- <AgentAvatar name={m.name} avatarUrl={m.avatarUrl} seed={m.name || "?"} size={36} className="rounded-xl" />
- <div className="flex flex-col items-start gap-1">
- <span className="text-sm font-medium">{m.name}</span>
- <span className="text-[10px] text-muted-foreground bg-muted/60 px-2 py-1 rounded">
- {ROLE_LABELS[m.role]}
- </span>
- </div>
- </div>
- {/* Email */}
- <p className="text-[10px] text-muted-foreground/70 font-mono truncate">
- {toAlookAddress(m.emailHandle || m.name.toLowerCase())}
- </p>
- {/* Description — flex-1 to push runtime picker to bottom */}
- <p className="text-[11px] text-muted-foreground leading-snug flex-1">
- {m.description}
- </p>
- {/* Row 4: runtime picker (if multiple) */}
- {showRuntimePicker && (() => {
- const selectedRt = runtimes.find((r) => r.id === m.runtimeId);
- return (
- <div className="mt-1">
- <Select value={m.runtimeId} onValueChange={(val) => { if (val) onAssignRuntime(i, val); }}>
- <SelectTrigger className="h-7 text-[11px]">
- <div className="flex items-center gap-2 truncate">
- {selectedRt && <ProviderLogo provider={selectedRt.provider || ""} className="size-3 shrink-0" />}
- <span className="truncate">{selectedRt?.provider || selectedRt?.runtime_mode || "Select"}</span>
- </div>
- </SelectTrigger>
- <SelectContent>
- {runtimes.map((rt) => (
- <SelectItem key={rt.id} value={rt.id}>
- {rt.provider || rt.runtime_mode}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- );
- })()}
- </Card>
- );
- })}
- </div>
- </div>
- );
-}
diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsx
deleted file mode 100644
index 3eac44c22..000000000
--- a/src/web/src/components/task-stream.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-"use client";
-
-import { useMemo } from "react";
-import type { TaskMessageResponse } from "@alook/shared";
-import type { TaskApi as Task } from "@alook/shared";
-import { RuntimeErrorBlock } from "@/components/agent-chat/runtime-error-block";
-
-/* ── Grouped stream items ── */
-
-interface ErrorItem {
- kind: "error";
- id: string;
- content: string;
-}
-
-function itemKey(msg: TaskMessageResponse): string {
- return msg.id || `seq-${msg.seq}`;
-}
-
-// Only `type:"error"` task_messages ever reach TaskStream now — the chat no
-// longer renders intermediate text/thinking (replies arrive via `send-dm`), and
-// the WS/init paths filter to errors-only before this component sees them.
-function groupMessages(messages: TaskMessageResponse[]): ErrorItem[] {
- const items: ErrorItem[] = [];
-
- for (const msg of messages) {
- if (msg.type === "error") {
- items.push({ kind: "error", id: itemKey(msg), content: msg.content || msg.output });
- }
- }
-
- return items;
-}
-
-/* ── TaskStream ──
- *
- * The chat no longer surfaces intermediate reasoning/tool steps ("thinking")
- * or a live status badge — the reply lands as one clean bubble (rendered by
- * message-list once the task settles). TaskStream only renders FAILURES while
- * a task is live: a runtime error is a real message, not thinking, and going
- * silent on failure is worse. Both RuntimeErrorBlock paths are kept.
- */
-
-export function TaskStream({
- task,
- messages,
- connectionLost,
- onRetry,
- provider,
-}: {
- task: Task;
- messages: TaskMessageResponse[];
- connectionLost?: boolean;
- onRetry?: () => void;
- /** Provider of the conversation's agent runtime, used to attribute runtime errors (issue #236). */
- provider?: string | null;
-}) {
- const errorItems = useMemo(() => groupMessages(messages), [messages]);
-
- // Nothing to show unless the stream surfaced an error, the task failed, or
- // the connection dropped — the successful reply is rendered as a bubble.
- if (
- errorItems.length === 0 &&
- !(task.status === "failed" && task.error) &&
- !connectionLost
- ) {
- return null;
- }
-
- return (
- <div className="space-y-3 min-w-0 max-w-full">
- {/* Stream error messages — attributed to the agent runtime (issue #236) */}
- {errorItems.length > 0 && (
- <div className="space-y-1 mt-1">
- {errorItems.map((item) => (
- <RuntimeErrorBlock key={item.id} provider={provider} message={item.content} />
- ))}
- </div>
- )}
-
- {/* Task-level error display — attributed to the agent runtime (issue #236) */}
- {task.status === "failed" && task.error && (
- <div className="mt-2">
- <RuntimeErrorBlock
- provider={provider}
- message={task.error}
- onRetry={onRetry}
- />
- </div>
- )}
-
- {connectionLost && (
- <p className="text-sm text-muted-foreground animate-pulse mt-1">
- Connection lost — retrying...
- </p>
- )}
- </div>
- );
-}
diff --git a/src/web/src/components/ui/checkbox.tsx b/src/web/src/components/ui/checkbox.tsx
deleted file mode 100644
index 441414c15..000000000
--- a/src/web/src/components/ui/checkbox.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-"use client"
-
-import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"
-
-import { cn } from "@/lib/utils"
-import { CheckIcon } from "lucide-react"
-
-function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
- return (
- <CheckboxPrimitive.Root
- data-slot="checkbox"
- className={cn(
- "peer relative flex size-4 shrink-0 items-center justify-center rounded-lg border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",
- className
- )}
- {...props}
- >
- <CheckboxPrimitive.Indicator
- data-slot="checkbox-indicator"
- className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
- >
- <CheckIcon
- />
- </CheckboxPrimitive.Indicator>
- </CheckboxPrimitive.Root>
- )
-}
-
-export { Checkbox }
diff --git a/src/web/src/components/ui/markdown-editor.tsx b/src/web/src/components/ui/markdown-editor.tsx
deleted file mode 100644
index f22ae8a79..000000000
--- a/src/web/src/components/ui/markdown-editor.tsx
+++ /dev/null
@@ -1,261 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useEffect, useRef } from "react";
-import { useEditor, EditorContent } from "@tiptap/react";
-import StarterKit from "@tiptap/starter-kit";
-import Placeholder from "@tiptap/extension-placeholder";
-import Mention from "@tiptap/extension-mention";
-import { Markdown } from "@tiptap/markdown";
-import { cn } from "@/lib/utils";
-import { isImeConfirming } from "@/lib/ime";
-import { isEmptyHtml, toAlookAddress } from "@alook/shared";
-import type { Agent } from "@alook/shared";
-import { createPortal } from "react-dom";
-import { anchoredPopoverStyle, useAnchoredPopover } from "@/hooks/use-anchored-popover";
-
-export { isEmptyHtml };
-
-export interface MarkdownEditorProps {
- value: string;
- onChange: (value: string) => void;
- placeholder?: string;
- className?: string;
- minHeight?: number | string;
- autoFocus?: boolean;
- variant?: "default" | "seamless";
- contentType?: "html" | "markdown";
- agents?: Agent[];
-}
-
-function normalize(html: string | null | undefined): string {
- if (!html) return "";
- return isEmptyHtml(html) ? "" : html.trim();
-}
-
-type MentionSuggestionProps = {
- items: Agent[];
- command: (props: { id: string; label: string }) => void;
- decorationNode: Element | null;
-};
-
-interface PopupState {
- items: Agent[];
- selectedIndex: number;
- command: ((props: { id: string; label: string }) => void) | null;
-}
-
-function MentionList({
- state,
- anchorEl,
-}: {
- state: PopupState;
- anchorEl: HTMLElement | null;
-}) {
- const listRef = useRef<HTMLDivElement>(null);
- const { items, selectedIndex, command } = state;
- const getRect = useCallback(
- () => anchorEl?.getBoundingClientRect() ?? null,
- [anchorEl],
- );
- const geometry = useAnchoredPopover(getRect, !!anchorEl && items.length > 0 && command !== null);
-
- useEffect(() => {
- if (!listRef.current) return;
- const el = listRef.current.children[selectedIndex] as HTMLElement | undefined;
- el?.scrollIntoView({ block: "nearest" });
- }, [selectedIndex]);
-
- if (!anchorEl || !geometry || items.length === 0 || !command) return null;
-
- return createPortal(
- <div
- className="fixed z-100 w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"
- style={anchoredPopoverStyle(geometry.rect, geometry.viewport, 256, 200)}
- >
- <div
- ref={listRef}
- className="overflow-y-auto py-1 thin-scrollbar"
- style={{ maxHeight: "var(--anchored-popover-max-height)" }}
- >
- {items.map((agent, i) => (
- <button
- key={agent.id}
- type="button"
- className={cn(
- "flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors",
- i === selectedIndex ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",
- )}
- onMouseDown={(e) => {
- e.preventDefault();
- command({ id: agent.id, label: agent.name });
- }}
- >
- <span className="truncate font-medium">{agent.name}</span>
- {agent.email_handle && (
- <span className="truncate text-xs text-muted-foreground">
- {toAlookAddress(agent.email_handle)}
- </span>
- )}
- </button>
- ))}
- </div>
- </div>,
- document.body,
- );
-}
-
-function useMentionSuggestion(agents: Agent[] | undefined) {
- const [popup, setPopup] = useAtom(useCreateAtom<PopupState>({ items: [], selectedIndex: 0, command: null }));
- const [anchorEl, setAnchorEl] = useAtom(useCreateAtom<HTMLElement | null>(null));
- const popupRef = useRef(popup);
- useEffect(() => {
- popupRef.current = popup;
- }, [popup]);
-
- const mentionExt = agents && agents.length > 0
- ? Mention.configure({
- HTMLAttributes: { class: "mention-highlight" },
- renderText: ({ node }) => `@${node.attrs.label ?? node.attrs.id}`,
- suggestion: {
- char: "@",
- items: ({ query }: { query: string }) => {
- if (!agents) return [];
- if (!query) return agents.slice(0, 20);
- const q = query.toLowerCase();
- const sw: Agent[] = [];
- const inc: Agent[] = [];
- for (const a of agents) {
- const n = a.name.toLowerCase();
- if (n.startsWith(q)) sw.push(a);
- else if (n.includes(q)) inc.push(a);
- }
- return [...sw, ...inc].slice(0, 20);
- },
- render: () => ({
- onStart: (props: MentionSuggestionProps) => {
- setAnchorEl(props.decorationNode instanceof HTMLElement ? props.decorationNode : null);
- setPopup({ items: props.items ?? [], selectedIndex: 0, command: props.command });
- },
- onUpdate: (props: MentionSuggestionProps) => {
- setAnchorEl(props.decorationNode instanceof HTMLElement ? props.decorationNode : null);
- setPopup({ items: props.items ?? [], selectedIndex: 0, command: props.command });
- },
- onKeyDown: ({ event }: { event: KeyboardEvent }) => {
- const cur = popupRef.current;
- if (cur.items.length === 0) return false;
-
- if (event.key === "ArrowDown") {
- event.preventDefault();
- setPopup({ ...cur, selectedIndex: (cur.selectedIndex + 1) % cur.items.length });
- return true;
- }
- if (event.key === "ArrowUp") {
- event.preventDefault();
- setPopup({
- ...cur,
- selectedIndex: (cur.selectedIndex - 1 + cur.items.length) % cur.items.length,
- });
- return true;
- }
- if (event.key === "Enter") {
- if (isImeConfirming(event)) return false;
- event.preventDefault();
- const agent = cur.items[cur.selectedIndex];
- if (agent && cur.command) cur.command({ id: agent.id, label: agent.name });
- setPopup({ items: [], selectedIndex: 0, command: null });
- return true;
- }
- if (event.key === "Escape") {
- setPopup({ items: [], selectedIndex: 0, command: null });
- return true;
- }
- return false;
- },
- onExit: () => {
- setPopup({ items: [], selectedIndex: 0, command: null });
- setAnchorEl(null);
- },
- }),
- },
- })
- : null;
-
- return { mentionExt, popup, anchorEl };
-}
-
-export function MarkdownEditor({
- value,
- onChange,
- placeholder,
- className,
- minHeight = "9rem",
- autoFocus,
- variant = "default",
- contentType = "html",
- agents,
-}: MarkdownEditorProps) {
- const isMd = contentType === "markdown";
-
- const minHeightStyle =
- typeof minHeight === "number" ? `${minHeight}px` : minHeight;
-
- const innerClass =
- variant === "seamless"
- ? "markdown text-sm max-w-none focus:outline-none px-0 py-1"
- : "markdown text-sm max-w-none focus:outline-none px-3 py-2";
-
- const { mentionExt, popup, anchorEl } = useMentionSuggestion(agents);
-
- const editor = useEditor({
- immediatelyRender: false,
- content: value || undefined,
- ...(isMd ? { contentType: "markdown" } : {}),
- extensions: [
- StarterKit,
- Placeholder.configure({ placeholder: placeholder ?? "" }),
- ...(isMd ? [Markdown] : []),
- ...(mentionExt ? [mentionExt] : []),
- ],
- editorProps: {
- attributes: {
- class: innerClass,
- style: `min-height: ${minHeightStyle}`,
- },
- },
- autofocus: autoFocus ? "end" : false,
- onUpdate: ({ editor }) => {
- onChange(isMd ? editor.getMarkdown() : editor.getHTML());
- },
- });
-
- useEffect(() => {
- if (!editor) return;
- if (isMd) {
- const incoming = (value || "").trim();
- const current = (editor.getMarkdown() || "").trim();
- if (incoming === current) return;
- editor.commands.setContent(value || "", { emitUpdate: false, contentType: "markdown" });
- } else {
- const incoming = normalize(value);
- const current = normalize(editor.getHTML());
- if (incoming === current) return;
- editor.commands.setContent(value || "", { emitUpdate: false });
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [value, editor]);
-
- const containerClass =
- variant === "seamless"
- ? "w-full bg-transparent text-sm"
- : "w-full rounded-md border border-input bg-transparent text-sm transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50";
-
- return (
- <div className={cn(containerClass, className)}>
- <EditorContent editor={editor} />
- {agents && agents.length > 0 && (
- <MentionList state={popup} anchorEl={anchorEl} />
- )}
- </div>
- );
-}
diff --git a/src/web/src/components/ui/scroll-area.tsx b/src/web/src/components/ui/scroll-area.tsx
deleted file mode 100644
index 84c1e9fbb..000000000
--- a/src/web/src/components/ui/scroll-area.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-"use client"
-
-import * as React from "react"
-import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
-
-import { cn } from "@/lib/utils"
-
-function ScrollArea({
- className,
- children,
- ...props
-}: ScrollAreaPrimitive.Root.Props) {
- return (
- <ScrollAreaPrimitive.Root
- data-slot="scroll-area"
- className={cn("relative", className)}
- {...props}
- >
- <ScrollAreaPrimitive.Viewport
- data-slot="scroll-area-viewport"
- className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
- >
- {children}
- </ScrollAreaPrimitive.Viewport>
- <ScrollBar />
- <ScrollAreaPrimitive.Corner />
- </ScrollAreaPrimitive.Root>
- )
-}
-
-function ScrollBar({
- className,
- orientation = "vertical",
- ...props
-}: ScrollAreaPrimitive.Scrollbar.Props) {
- return (
- <ScrollAreaPrimitive.Scrollbar
- data-slot="scroll-area-scrollbar"
- data-orientation={orientation}
- orientation={orientation}
- className={cn(
- "flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
- className
- )}
- {...props}
- >
- <ScrollAreaPrimitive.Thumb
- data-slot="scroll-area-thumb"
- className="relative flex-1 rounded-full bg-border"
- />
- </ScrollAreaPrimitive.Scrollbar>
- )
-}
-
-export { ScrollArea, ScrollBar }
diff --git a/src/web/src/components/ui/scroll-to-bottom-button.tsx b/src/web/src/components/ui/scroll-to-bottom-button.tsx
deleted file mode 100644
index 058922c89..000000000
--- a/src/web/src/components/ui/scroll-to-bottom-button.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useCallback, type RefObject } from "react";
-import { Button } from "@/components/ui/button";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { ArrowDown } from "lucide-react";
-import { cn } from "@/lib/utils";
-
-interface ScrollToBottomButtonProps {
- scrollRef: RefObject<HTMLDivElement | null>;
- threshold?: number;
-}
-
-export function ScrollToBottomButton({ scrollRef, threshold = 100 }: ScrollToBottomButtonProps) {
- const [showButton, setShowButton] = useAtom(useCreateAtom(false));
-
- const check = useCallback(() => {
- const el = scrollRef.current;
- if (!el) return;
- const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < threshold;
- const hasOverflow = el.scrollHeight > el.clientHeight;
- setShowButton(hasOverflow && !atBottom);
- }, [scrollRef, setShowButton, threshold]);
-
- useEffect(() => {
- const el = scrollRef.current;
- if (!el) return;
-
- el.addEventListener("scroll", check, { passive: true });
- check();
-
- const ro = new ResizeObserver(check);
- ro.observe(el);
-
- return () => {
- el.removeEventListener("scroll", check);
- ro.disconnect();
- };
- }, [scrollRef, check]);
-
- const handleClick = () => {
- const el = scrollRef.current;
- if (!el) return;
- el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
- };
-
- return (
- <div
- className={cn(
- "absolute bottom-1 left-1/2 -translate-x-1/2 z-10 transition-all duration-200 ease-out",
- showButton
- ? "opacity-100 translate-y-0"
- : "opacity-0 translate-y-2 pointer-events-none"
- )}
- >
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={handleClick}
- className="rounded-full bg-background/80 backdrop-blur-sm border shadow-sm hover:bg-background"
- />
- }
- >
- <ArrowDown />
- </TooltipTrigger>
- <TooltipContent side="top">Scroll to bottom</TooltipContent>
- </Tooltip>
- </div>
- );
-}
diff --git a/src/web/src/components/use-artifact-click.dom.test.tsx b/src/web/src/components/use-artifact-click.dom.test.tsx
deleted file mode 100644
index 46c21d5ff..000000000
--- a/src/web/src/components/use-artifact-click.dom.test.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import React from "react"
-import { afterEach, describe, expect, it, vi } from "vitest"
-import type { Artifact } from "@alook/shared"
-import { act, render as renderLeaf } from "@/test/react-dom-harness"
-import { ArtifactCard } from "./agent-chat/chat-view-parts"
-import { IssueAttachmentList } from "./issues/issue-attachment-list"
-import { useArtifactClick } from "./use-artifact-click"
-import { QueryClient } from "@tanstack/react-query"
-import { CommunityTestProvider } from "@/test/community-owner-fixture"
-import { WorkspaceProvider } from "@/contexts/workspace-context"
-
-const service = vi.hoisted(() => ({ download: vi.fn(), loading: vi.fn<(text: string, options: { action: { label: string; onClick: () => void } }) => number>(() => 1), dismiss: vi.fn(), success: vi.fn(), error: vi.fn() }))
-vi.mock("@/lib/file-save", async importOriginal => ({ ...await importOriginal<object>(), downloadUrl: service.download }))
-vi.mock("sonner", () => ({ toast: service }))
-const binary = { id: "binary", filename: "报告.bin", content_type: "application/octet-stream", size: 36, has_thumbnail: false } as Artifact
-function Card({ artifact = binary, preview = vi.fn(), image }: { artifact?: Artifact; preview?: (artifact: Artifact) => void; image?: (artifact: Artifact) => void }) {
- const click = useArtifactClick("workspace", preview, image)
- return <ArtifactCard artifact={artifact} workspaceId="workspace" version={1} hasDuplicates={false} onClick={click} />
-}
-function render(node: React.ReactNode) {
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- return renderLeaf(<CommunityTestProvider client={client}><WorkspaceProvider workspaceId="workspace" slug="workspace">{node}</WorkspaceProvider></CommunityTestProvider>)
-}
-afterEach(() => { vi.clearAllMocks() })
-describe("artifact card click controller", () => {
- it("routes the actual binary card through authenticated file-save and exposes retry", async () => {
- service.download.mockResolvedValueOnce({ status: "error", message: "network" }).mockResolvedValueOnce({ status: "started" })
- const preview = vi.fn()
- const view = render(<Card preview={preview} />)
- await act(async () => { view.getByRole("button").click() })
- expect(service.download).toHaveBeenCalledWith("/api/artifacts/binary/content?workspace_id=workspace&download=1", "报告.bin", expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
- expect(preview).not.toHaveBeenCalled()
- expect(service.error).toHaveBeenCalledWith("Couldn’t save — retry", expect.objectContaining({ action: expect.objectContaining({ label: "Retry" }) }))
- await act(async () => { service.error.mock.calls[0][1].action.onClick() })
- expect(service.download).toHaveBeenCalledTimes(2)
- expect(service.success).toHaveBeenCalledWith("Download started")
- })
- it("allows cancellation from the download notification and a fresh card retry", async () => {
- service.download.mockImplementationOnce((_url, _name, { signal }) => new Promise(resolve => signal.addEventListener("abort", () => resolve({ status: "cancelled" })))).mockResolvedValueOnce({ status: "saved" })
- const view = render(<Card />)
- await act(async () => { view.getByRole("button").click() })
- await act(async () => { service.loading.mock.calls[0][1].action.onClick() })
- expect(service.error).not.toHaveBeenCalled()
- expect(service.success).not.toHaveBeenCalled()
- await act(async () => { view.getByRole("button").click() })
- expect(service.success).toHaveBeenCalledWith("Saved")
- })
- it("a repeated card click cancels the active download without starting a duplicate", async () => {
- let signal!: AbortSignal
- service.download.mockImplementationOnce((_url, _name, options) => {
- signal = options.signal
- return new Promise(resolve => signal.addEventListener("abort", () => resolve({ status: "cancelled" })))
- }).mockResolvedValueOnce({ status: "started" })
- const view = render(<Card />)
- await act(async () => { view.getByRole("button").click() })
- expect(signal.aborted).toBe(false)
- await act(async () => { view.getByRole("button").click() })
- expect(signal.aborted).toBe(true)
- expect(service.download).toHaveBeenCalledTimes(1)
- expect(service.success).not.toHaveBeenCalled()
- expect(service.error).not.toHaveBeenCalled()
- await act(async () => { view.getByRole("button").click() })
- expect(service.download).toHaveBeenCalledTimes(2)
- expect(service.success).toHaveBeenCalledWith("Download started")
- })
- it.each([true, false])("preserves the image preview choice (lightbox=%s)", async lightbox => {
- const preview = vi.fn(), image = vi.fn()
- const artifact = { ...binary, content_type: "image/png", filename: "a.png" }
- const view = render(<Card artifact={artifact} preview={preview} image={lightbox ? image : undefined} />)
- await act(async () => { view.getByRole("button").click() })
- expect(lightbox ? image : preview).toHaveBeenCalledWith(artifact)
- expect(lightbox ? preview : image).not.toHaveBeenCalled()
- expect(service.download).not.toHaveBeenCalled()
- })
- it("keeps text artifacts in the preview sheet", async () => {
- const preview = vi.fn()
- const artifact = { ...binary, content_type: "text/plain" }
- const view = render(<Card artifact={artifact} preview={preview} />)
- await act(async () => { view.getByRole("button").click() })
- expect(preview).toHaveBeenCalledWith(artifact)
- expect(service.download).not.toHaveBeenCalled()
- })
-})
-
-describe("issue attachment list click", () => {
- it("downloads a binary through the owner, even when a preview callback exists", async () => {
- service.download.mockResolvedValue({ status: "started" })
- const preview = vi.fn()
- const view = render(<IssueAttachmentList artifacts={[binary]} workspaceId="workspace" onArtifactClick={preview} />)
- await act(async () => { view.getByRole("button").click() })
- expect(service.download).toHaveBeenCalledWith("/api/artifacts/binary/content?workspace_id=workspace&download=1", "报告.bin", expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
- expect(preview).not.toHaveBeenCalled()
- await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
- expect(view.getByRole("status")).toHaveTextContent("Download started")
- expect(view.queryByRole("link")).toBeNull()
- })
- it("preserves preview callbacks for text attachments", async () => {
- const artifact = { ...binary, content_type: "text/plain" }
- const preview = vi.fn()
- const view = render(<IssueAttachmentList artifacts={[artifact]} workspaceId="workspace" onArtifactClick={preview} />)
- await act(async () => { view.getByRole("button").click() })
- expect(preview).toHaveBeenCalledWith(artifact)
- expect(service.download).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/components/use-artifact-click.ts b/src/web/src/components/use-artifact-click.ts
deleted file mode 100644
index 7ef6be969..000000000
--- a/src/web/src/components/use-artifact-click.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-"use client"
-
-import { useCallback } from "react"
-import type { Artifact } from "@alook/shared"
-import { getArtifactUrl, isPreviewable } from "./artifact-content-renderer"
-import { downloadFileWithFeedback } from "@/lib/file-download-action"
-import { useWorkspaceOwner } from "@/contexts/workspace-context"
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source"
-
-export function useArtifactClick(workspaceId: string, preview: (artifact: Artifact) => void, image?: (artifact: Artifact) => void, identity = "artifact-click") {
- const owner = useWorkspaceOwner()
- const source = useWorkspaceViewSource(owner, identity, true)
- return useCallback((artifact: Artifact) => {
- source.assertActive()
- if (image && artifact.content_type.startsWith("image/")) image(artifact)
- else if (isPreviewable(artifact)) preview(artifact)
- else void downloadFileWithFeedback(owner.application, { url: getArtifactUrl(artifact.id, workspaceId, true), name: artifact.filename }, { signal: source.signal, assertActive: source.assertActive })
- }, [source, image, preview, owner.application, workspaceId])
-}
diff --git a/src/web/src/components/workspace-shell.tsx b/src/web/src/components/workspace-shell.tsx
deleted file mode 100644
index 4ab3ca7c2..000000000
--- a/src/web/src/components/workspace-shell.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { createContext, useContext, type ReactNode, useRef } from "react";
-import { AppSidebar } from "@/components/app-sidebar";
-import { MobileTopBar } from "@/components/mobile-top-bar";
-import { AppBackground, AppSurface } from "@/components/ui/app-surface";
-import { WorkspacePetLayer } from "@/components/home-pet/workspace-pet-layer";
-import { RuntimeVersionGate } from "@/components/runtime-version-gate";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { useIsMobile } from "@/hooks/use-mobile";
-import {
- Sheet,
- SheetContent,
-} from "@/components/ui/sheet";
-import { AgentChatSheetProvider } from "@/contexts/agent-chat-sheet-context";
-const SidebarTriggerContext = createContext<(() => void) | null>(null);
-
-export function useSidebarTrigger() {
- return useContext(SidebarTriggerContext);
-}
-
-export function WorkspaceShell({ children }: { children: ReactNode }) {
- const isMobile = useIsMobile();
- const { slug } = useWorkspace();
- const [sidebarOpen, setSidebarOpen] = useAtom(useCreateAtom(false));
- const shellRef = useRef<HTMLDivElement>(null);
-
- if (isMobile) {
- return (
- <SidebarTriggerContext.Provider value={() => setSidebarOpen(true)}>
- <AgentChatSheetProvider>
- <div ref={shellRef} className="workspace-shell flex flex-col h-dvh overflow-hidden relative">
- <AppBackground />
- <div className="flex-1 min-h-0 px-2 pb-2 pt-2 flex flex-col">
- <MobileTopBar />
- <AppSurface>
- {children}
- </AppSurface>
- </div>
- <Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
- <SheetContent side="left" showCloseButton={false} style={{ width: 56 }} className="p-0">
- <AppSidebar onNavigate={() => setSidebarOpen(false)} />
- </SheetContent>
- </Sheet>
- <WorkspacePetLayer boundaryRef={shellRef} slug={slug} />
- <RuntimeVersionGate />
- </div>
- </AgentChatSheetProvider>
- </SidebarTriggerContext.Provider>
- );
- }
-
- return (
- <AgentChatSheetProvider>
- <div ref={shellRef} className="workspace-shell flex h-dvh overflow-hidden relative">
- <AppBackground />
- <AppSidebar />
- <div className="flex-1 flex flex-col min-w-0 pt-2 pr-2 pb-2">
- <AppSurface>
- {children}
- </AppSurface>
- </div>
- <WorkspacePetLayer boundaryRef={shellRef} slug={slug} />
- <RuntimeVersionGate />
- </div>
- </AgentChatSheetProvider>
- );
-}
diff --git a/src/web/src/contexts/agent-chat-sheet-context.tsx b/src/web/src/contexts/agent-chat-sheet-context.tsx
deleted file mode 100644
index be2f767f6..000000000
--- a/src/web/src/contexts/agent-chat-sheet-context.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-"use client";
-
-import { useMemo, type ReactNode } from "react";
-import { createStore, createStoreContext, useSelector } from "@tanstack/react-store";
-import { useRouter } from "next/navigation";
-import type { Agent } from "@alook/shared";
-import { useAgentContext } from "@/contexts/agent-context";
-import { useWorkspaceOwner } from "@/contexts/workspace-context";
-import { AgentChatSheet } from "@/components/canvas/agent-chat-sheet";
-
-type ChatTarget = { conversationId?: string; taskId?: string; messageId?: string };
-function createSheetStore() {
- return createStore({ open: false, agentId: null as string | null, targetConvId: null as string | null, scrollToTaskId: null as string | null, scrollToMessageId: null as string | null });
-}
-const { StoreProvider, useStoreContext } = createStoreContext<{
- ui: ReturnType<typeof createSheetStore>;
- openAgentChat: (agentId: string, options?: ChatTarget) => void;
-}>();
-export function useAgentChatSheet() {
- const { openAgentChat } = useStoreContext();
- return useMemo(() => ({ openAgentChat }), [openAgentChat]);
-}
-export function AgentChatSheetProvider({ children }: { children: ReactNode }) {
- const router = useRouter();
- const workspace = useWorkspaceOwner();
- const { agents } = useAgentContext();
- const handles = useMemo(() => {
- const ui = createSheetStore();
- return {
- ui,
- openAgentChat: (agentId: string, options?: ChatTarget) => {
- if (!workspace.lifecycle.get().active || !workspace.application.lifecycle.get().active) return;
- const found = workspace.queryClient.getQueryData<Agent[]>(workspace.key("agents"))?.some((agent) => agent.id === agentId);
- if (!found) { router.push(`/w/${workspace.slug}/agents/${agentId}`); return; }
- ui.setState(() => ({ open: true, agentId, targetConvId: options?.conversationId ?? null, scrollToTaskId: options?.taskId ?? null, scrollToMessageId: options?.messageId ?? null }));
- },
- };
- }, [workspace, router]);
- const state = useSelector(handles.ui, (value) => value);
- const agent = agents.find((value) => value.id === state.agentId) ?? null;
- return <StoreProvider value={handles}>
- {children}
- <AgentChatSheet
- {...state}
- onOpenChange={(open) => {
- if (!workspace.lifecycle.get().active || !workspace.application.lifecycle.get().active) return;
- handles.ui.setState((previous) => ({ ...previous, open, ...(open ? {} : { targetConvId: null, scrollToTaskId: null, scrollToMessageId: null }) }));
- }}
- agent={agent}
- />
- </StoreProvider>;
-}
diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsx
deleted file mode 100644
index 7acb33f1f..000000000
--- a/src/web/src/contexts/agent-context.tsx
+++ /dev/null
@@ -1,313 +0,0 @@
-"use client"
-
-import { deriveView, valueEvidence, withSource } from "@/lib/observability/data-source"
-
-import { isAbortError } from "@/lib/errors"
-import { publishWorkspaceChatEvent } from "@/lib/workspace-chat-events"
-import { captureQueryReceipt, withQueryReceipt, reconcileQueryReceipt } from "@/lib/query-receipt"
-import { publishWorkspaceIssueEvent } from "@/lib/workspace-issue-events"
-
-import { useMemo, type ReactNode } from "react"
-import { createStore, createStoreContext, useSelector } from "@tanstack/react-store"
-import { queryOptions, useMutation, useQueries, useQuery } from "@tanstack/react-query"
-import {
- listAgents, listRuntimes, createAgent, updateAgent, deleteAgent,
- createMachineToken, deleteMachine, listWorkspaceActiveTasks,
- listAgentActiveTaskCounts, listAgentPins, listAgentLinks, pinAgent as pinAgentApi, unpinAgent as unpinAgentApi,
- reorderAgentPins, reorderUnpinnedAgents, type WorkspaceActiveTask,
-} from "@/lib/api"
-import type { AgentRuntime as Runtime, Agent, AgentLink, CreateAgentRequest, UpdateAgentRequest, WsMessage } from "@alook/shared"
-import { useUserWs } from "@/lib/use-user-ws"
-import { toast } from "sonner"
-import { assertWorkspaceOwner, captureWorkspaceOwner, workspaceRequestOptions, useWorkspaceOwner, runWorkspaceRequest, type WorkspaceOwner } from "./workspace-context"
-
-import type { ApiRequestOptions } from "@/lib/api/client"
-
-type WsSubscriber = (message: WsMessage) => void
-interface AgentContextValue {
- workspaceId: string;
- agents: Agent[];
- agentLinks: AgentLink[];
- runtimes: Runtime[];
- loading: boolean;
- activeTaskCounts: Record<string, number>;
- pendingNewAgent: { agentId: string; parentAgentId: string } | null;
- clearPendingNewAgent: () => void;
- activeTaskDetails: WorkspaceActiveTask[];
- pins: Map<string, { created_at: string; position: number }>;
- reload: () => Promise<void>;
- subscribeWs: (fn: WsSubscriber) => () => void;
- subscribeReconnect: (fn: () => void) => () => void;
- handleCreateAgent: (req: CreateAgentRequest) => Promise<Agent | null>;
- handleUpdateAgent: (id: string, req: UpdateAgentRequest) => Promise<boolean>;
- handleDeleteAgent: (id: string) => Promise<boolean>;
- handlePinAgent: (agentId: string) => Promise<void>;
- handleUnpinAgent: (agentId: string) => Promise<void>;
- handleReorderPins: (orderedAgentIds: string[]) => Promise<void>;
- unpinnedOrder: Map<string, number>;
- handleReorderUnpinned: (orderedAgentIds: string[]) => Promise<void>;
- getFirstOnlineRuntimeId: () => string;
- handleGenerateToken: () => Promise<string | null>;
- handleDeleteMachine: (daemonId: string) => Promise<boolean>;
- patchAgent: (id: string, fields: Partial<Agent>) => void;
-}
-
-
-function agentQueries(workspace: WorkspaceOwner) {
- const options = <T,>(resource: string, load: (options: ApiRequestOptions) => Promise<T>, extra = {}) => queryOptions({
- queryKey: workspace.key(resource),
- structuralSharing: reconcileQueryReceipt,
- queryFn: async ({ signal }) => { const receipt = captureQueryReceipt(workspace.queryClient, workspace.key(resource)); const data = await runWorkspaceRequest(workspace, load, signal); return data && typeof data === "object" ? withQueryReceipt(data, receipt) : data },
- ...extra,
- })
- return {
- agents: options("agents", (options) => listAgents(workspace.workspaceId, options)),
- runtimes: options("runtimes", (options) => listRuntimes(workspace.workspaceId, options), {
- refetchInterval: 30_000, refetchIntervalInBackground: false, refetchOnWindowFocus: true,
- }),
- pins: options("agent-pins", (options) => listAgentPins(workspace.workspaceId, options)),
- links: options("agent-links", (options) => listAgentLinks(workspace.workspaceId, options)),
- counts: options("active-task-counts", (options) => listAgentActiveTaskCounts(workspace.workspaceId, options)),
- tasks: options("active-tasks", (options) => listWorkspaceActiveTasks(workspace.workspaceId, options), {
- refetchInterval: 15_000, refetchIntervalInBackground: false,
- }),
- }
-}
-function createAgentOwner(workspace: WorkspaceOwner) {
- const queries = agentQueries(workspace)
- const subscribers = new Set<WsSubscriber>()
- const reconnectSubscribers = new Set<() => void>()
- return {
- workspace, queries,
- ui: createStore({ pendingNewAgent: null as AgentContextValue["pendingNewAgent"] }),
- subscribeWs: (fn: WsSubscriber) => { subscribers.add(fn); return () => { subscribers.delete(fn) } },
- subscribeReconnect: (fn: () => void) => { reconnectSubscribers.add(fn); return () => { reconnectSubscribers.delete(fn) } },
- dispatch: (message: WsMessage) => { for (const subscriber of subscribers) subscriber(message) },
- reconnect: () => { for (const subscriber of reconnectSubscribers) subscriber() },
- reload: async () => {
- const token = captureWorkspaceOwner(workspace)
- assertWorkspaceOwner(token)
- await Promise.all([queries.agents, queries.runtimes, queries.pins, queries.links].map(({ queryKey }) =>
- workspace.queryClient.cancelQueries({ queryKey, exact: true }).then(() => {
- assertWorkspaceOwner(token)
- return workspace.queryClient.invalidateQueries({ queryKey, exact: true })
- })))
- assertWorkspaceOwner(token)
- },
- }
-}
-type AgentOwner = ReturnType<typeof createAgentOwner>
-const { StoreProvider, useStoreContext } = createStoreContext<{ owner: AgentOwner }>()
-const EMPTY_AGENTS: Agent[] = []
-const EMPTY_RUNTIMES: Runtime[] = []
-const EMPTY_LINKS: AgentLink[] = []
-const EMPTY_TASKS: WorkspaceActiveTask[] = []
-
-export function useAgentContext({ poll = false }: { poll?: boolean } = {}): AgentContextValue {
- const { owner } = useStoreContext()
- const results = useQueries({ queries: [
- owner.queries.agents, { ...owner.queries.runtimes, refetchInterval: poll ? 30_000 : false }, owner.queries.pins,
- owner.queries.links, { ...owner.queries.counts, refetchInterval: () => {
- if (!poll) return false
- const details = owner.workspace.queryClient.getQueryState<Awaited<ReturnType<typeof listWorkspaceActiveTasks>>>(owner.queries.tasks.queryKey)
- const counts = owner.workspace.queryClient.getQueryState(owner.queries.counts.queryKey)
- return details && details.dataUpdatedAt >= (counts?.dataUpdatedAt ?? 0) && details.data?.tasks.length ? false : 15_000
- } },
- ] })
- const cachedDetails = owner.workspace.queryClient.getQueryState<Awaited<ReturnType<typeof listWorkspaceActiveTasks>>>(owner.queries.tasks.queryKey)
- const detailsAreLatest = (cachedDetails?.dataUpdatedAt ?? 0) >= results[4].dataUpdatedAt
- const hasActiveTasks = detailsAreLatest
- ? (cachedDetails?.data?.tasks.length ?? 0) > 0
- : Object.values(results[4].data?.counts ?? {}).some((count) => count > 0)
- const detailsQuery = useQuery({ ...owner.queries.tasks, enabled: hasActiveTasks, subscribed: hasActiveTasks, refetchInterval: poll && hasActiveTasks ? 15_000 : false })
- const pendingNewAgent = useSelector(owner.ui, (state) => state.pendingNewAgent)
- const workspace = owner.workspace
- const mutation = useMutation({ meta: { observabilityAction: "agent.update" },
- mutationFn: async ({ operation, token }: { operation: (options: ApiRequestOptions) => Promise<unknown>; token: ReturnType<typeof captureWorkspaceOwner> }) => {
- assertWorkspaceOwner(token)
- try {
- const result = await operation(workspaceRequestOptions(token))
- assertWorkspaceOwner(token)
- return result
- } catch (error) { assertWorkspaceOwner(token); throw error }
- },
- })
- const pinMutationKey = [...owner.queries.pins.queryKey, "change"]
- type PinChange = { kind: "pin" | "unpin" | "reorder-pins" | "reorder-unpinned"; ids: string[]; token: ReturnType<typeof captureWorkspaceOwner> }
- const pinMutation = useMutation({ meta: { observabilityAction: "agent.rail.command" },
- mutationKey: pinMutationKey,
- scope: { id: JSON.stringify(pinMutationKey) },
- mutationFn: async (action: PinChange) => {
- assertWorkspaceOwner(action.token)
- const options = workspaceRequestOptions(action.token)
- try {
- if (action.kind === "pin") await pinAgentApi(workspace.workspaceId, action.ids[0], options)
- else if (action.kind === "unpin") await unpinAgentApi(workspace.workspaceId, action.ids[0], options)
- else if (action.kind === "reorder-pins") await reorderAgentPins(workspace.workspaceId, action.ids, options)
- else await reorderUnpinnedAgents(workspace.workspaceId, action.ids, options)
- assertWorkspaceOwner(action.token)
- } catch (error) { assertWorkspaceOwner(action.token); throw error }
- },
- onMutate: async (action) => {
- const token = action.token
- const qc = workspace.queryClient
- const key = owner.queries.pins.queryKey
- await qc.cancelQueries({ queryKey: key, exact: true })
- assertWorkspaceOwner(token)
- const previous = qc.getQueryData(key)
- qc.setQueryData(key, (data) => {
- const current = data ?? { pins: [], sidebar_order: [] }
- if (action.kind === "pin") {
- if (current.pins.some((pin) => pin.agent_id === action.ids[0])) return current
- const position = Math.max(-1, ...current.pins.map((pin) => pin.position)) + 1
- return { ...current, pins: [...current.pins, { id: `pending:${action.ids[0]}`, agent_id: action.ids[0], created_at: new Date().toISOString(), position }] }
- }
- if (action.kind === "unpin") return { ...current, pins: current.pins.filter((pin) => pin.agent_id !== action.ids[0]) }
- if (action.kind === "reorder-pins") return { ...current, pins: current.pins.map((pin) => action.ids.includes(pin.agent_id) ? { ...pin, position: action.ids.indexOf(pin.agent_id) } : pin) }
- return { ...current, sidebar_order: action.ids.map((agent_id, position) => ({ agent_id, position })) }
- })
- return { token, previous, optimistic: qc.getQueryData(key), query: qc.getQueryCache().find({ queryKey: key, exact: true }) }
- },
- onError: (error, _action, context) => {
- if (!context || isAbortError(error)) return
- try { assertWorkspaceOwner(context.token) } catch { return }
- if (context.query && workspace.queryClient.getQueryCache().find({ queryKey: owner.queries.pins.queryKey, exact: true }) === context.query && workspace.queryClient.getQueryData(owner.queries.pins.queryKey) === context.optimistic) {
- workspace.queryClient.setQueryData(owner.queries.pins.queryKey, context.previous)
- }
- },
- onSettled: (_data, _error, _action, context) => {
- if (!context) return
- try { assertWorkspaceOwner(context.token) } catch { return }
- if (workspace.queryClient.isMutating({ mutationKey: pinMutationKey, exact: true }) === 1) {
- return workspace.queryClient.invalidateQueries({ queryKey: owner.queries.pins.queryKey, exact: true })
- }
- },
- })
- const mutateOperation = mutation.mutateAsync, mutatePins = pinMutation.mutateAsync
- const operations = useMemo(() => {
- const { workspace: source, queries } = owner
- const qc = source.queryClient
- const invoke = async <T,>(operation: (options: ApiRequestOptions) => Promise<T>, fallback: string): Promise<T | null> => {
- const token = captureWorkspaceOwner(source)
- try {
- assertWorkspaceOwner(token)
- const result = await mutateOperation({ operation, token }) as T
- assertWorkspaceOwner(token)
- return result
- }
- catch (error) {
- try { assertWorkspaceOwner(token) } catch { return null }
- if (!(isAbortError(error))) {
- toast.error(error instanceof Error ? error.message : fallback)
- }
- return null
- }
- }
- const change = async (operation: (options: ApiRequestOptions) => Promise<unknown>, fallback: string) => {
- const token = captureWorkspaceOwner(source)
- const result = await invoke(operation, fallback)
- if (result === null) return false
- try {
- assertWorkspaceOwner(token)
- await owner.reload()
- assertWorkspaceOwner(token)
- } catch (error) { if (isAbortError(error)) return false; throw error }
- return true
- }
- const changePins = async (kind: PinChange["kind"], ids: string[], fallback: string) => {
- const token = captureWorkspaceOwner(source)
- try { assertWorkspaceOwner(token); await mutatePins({ kind, ids, token }); assertWorkspaceOwner(token) }
- catch (error) {
- try { assertWorkspaceOwner(token) } catch { return }
- if (!(isAbortError(error))) toast.error(fallback)
- }
- }
- return {
- clearPendingNewAgent: () => owner.ui.setState((state) => state.pendingNewAgent ? { pendingNewAgent: null } : state),
- reload: owner.reload,
- subscribeWs: owner.subscribeWs,
- subscribeReconnect: owner.subscribeReconnect,
- handleCreateAgent: async (request: CreateAgentRequest) => {
- const token = captureWorkspaceOwner(source)
- const agent = await invoke((options) => createAgent(request, source.workspaceId, options), "Failed to create agent")
- if (agent) {
- try { assertWorkspaceOwner(token); await owner.reload(); assertWorkspaceOwner(token) }
- catch (error) { if (isAbortError(error)) return null; throw error }
- }
- return agent
- },
- handleUpdateAgent: (id: string, request: UpdateAgentRequest) =>
- change((options) => updateAgent(id, request, source.workspaceId, options), "Failed to update agent"),
- handleDeleteAgent: (id: string) =>
- change(async (options) => { await deleteAgent(id, source.workspaceId, options); return true }, "Failed to remove agent"),
- handleDeleteMachine: (id: string) =>
- change(async (options) => { await deleteMachine(id, source.workspaceId, options); return true }, "Failed to remove machine"),
- handleGenerateToken: () => invoke((options) => createMachineToken("cli", source.workspaceId, options).then((data) => data.token), "Failed to generate token"),
- handlePinAgent: (id: string) => changePins("pin", [id], "Failed to pin agent"),
- handleUnpinAgent: (id: string) => changePins("unpin", [id], "Failed to unpin agent"),
- handleReorderPins: (ids: string[]) => changePins("reorder-pins", ids, "Failed to reorder pins"),
- handleReorderUnpinned: (ids: string[]) => changePins("reorder-unpinned", ids, "Failed to reorder agents"),
- getFirstOnlineRuntimeId: () => qc.getQueryData(queries.runtimes.queryKey)?.find((runtime) => runtime.status === "online")?.id ?? "",
- patchAgent: (id: string, fields: Partial<Agent>) => {
- if (!source.lifecycle.get().active || !source.application.lifecycle.get().active) return
- void qc.cancelQueries({ queryKey: queries.agents.queryKey, exact: true })
- qc.setQueryData(queries.agents.queryKey, (current) => current?.map((agent) => agent.id === id ? { ...agent, ...fields } : agent))
- },
- }
- }, [owner, mutateOperation, mutatePins])
- const agents = (results[0]?.data as Agent[] | undefined) ?? EMPTY_AGENTS
- const runtimes = (results[1]?.data as Runtime[] | undefined) ?? EMPTY_RUNTIMES
- const pinData = results[2]?.data as Awaited<ReturnType<typeof listAgentPins>> | undefined
- const agentLinks = (results[3]?.data as AgentLink[] | undefined) ?? EMPTY_LINKS
- const tasks = detailsQuery.data
- const activeTaskDetails = tasks?.tasks ?? EMPTY_TASKS
- const activeTaskCounts = useMemo(() => {
- if (results[4].dataUpdatedAt > detailsQuery.dataUpdatedAt) return results[4].data?.counts ?? {}
- const counts: Record<string, number> = {}
- for (const task of activeTaskDetails) counts[task.agent_id] = (counts[task.agent_id] ?? 0) + 1
- return counts
- }, [activeTaskDetails, detailsQuery.dataUpdatedAt, results])
- const pins = useMemo(() => new Map(pinData?.pins.map((pin) => [pin.agent_id, { created_at: pin.created_at, position: pin.position }])), [pinData])
- const unpinnedOrder = useMemo(() => new Map(pinData?.sidebar_order.map((entry) => [entry.agent_id, entry.position])), [pinData])
- const loading = results.slice(0, 4).some((result) => result.isPending)
- deriveView(agents, [valueEvidence(owner.workspace.queryClient, results[0]?.data)])
- deriveView(runtimes, [valueEvidence(owner.workspace.queryClient, results[1]?.data)])
- deriveView(agentLinks, [valueEvidence(owner.workspace.queryClient, results[3]?.data)])
- return useMemo(() => ({
- ...operations, workspaceId: owner.workspace.workspaceId, agents, runtimes,
- agentLinks, activeTaskCounts, activeTaskDetails, pendingNewAgent,
- loading, pins, unpinnedOrder,
- }), [owner, operations, agents, runtimes, agentLinks, activeTaskCounts, activeTaskDetails, pendingNewAgent, loading, pins, unpinnedOrder])
-}
-function AgentBootstrap({ owner }: { owner: AgentOwner }) {
- useAgentContext({ poll: true })
- useUserWs((message) => {
- const { workspace } = owner
- if (!workspace.lifecycle.get().active || !workspace.application.lifecycle.get().active) return
- if ("workspaceId" in message && message.workspaceId && message.workspaceId !== workspace.workspaceId) return
- withSource(workspace.queryClient, "ws", () => {
- publishWorkspaceChatEvent(workspace, message)
- publishWorkspaceIssueEvent(workspace, message)
- owner.dispatch(message)
- })
- switch (message.type) {
- case "runtime.registered": case "runtime.deleted": void owner.reload(); break
- case "runtime.status":
- void workspace.queryClient.cancelQueries({ queryKey: owner.queries.runtimes.queryKey, exact: true }).then(() => workspace.queryClient.invalidateQueries({ queryKey: owner.queries.runtimes.queryKey, exact: true })); break
- case "agent.created":
- owner.ui.setState(() => ({ pendingNewAgent: { agentId: message.agentId, parentAgentId: message.parentAgentId } }))
- void owner.reload(); break
- case "task.updated":
- const details = workspace.queryClient.getQueryData(owner.queries.tasks.queryKey)
- void workspace.queryClient.invalidateQueries({ queryKey: details?.tasks.length ? owner.queries.tasks.queryKey : owner.queries.counts.queryKey, exact: true }); break
- }
- }, { onReconnect: () => { void owner.reload(); owner.reconnect() } })
- return null
-}
-export function AgentProvider({ workspaceId, children }: { workspaceId: string; children: ReactNode }) {
- const workspace = useWorkspaceOwner()
- const owner = useMemo(() => createAgentOwner(workspace), [workspace])
- const handles = useMemo(() => ({ owner }), [owner])
- if (workspace.workspaceId !== workspaceId) throw new Error("Agent workspace owner mismatch")
- return <StoreProvider value={handles}><AgentBootstrap owner={owner} />{children}</StoreProvider>
-}
diff --git a/src/web/src/contexts/channel-context.tsx b/src/web/src/contexts/channel-context.tsx
deleted file mode 100644
index 2cbb9a80c..000000000
--- a/src/web/src/contexts/channel-context.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-"use client"
-
-import { isAbortError } from "@/lib/errors"
-
-import { useCallback, useEffect, useMemo, type ReactNode } from "react"
-import { createStore, createStoreContext, useSelector } from "@tanstack/react-store"
-import { useMutation, useMutationState, useQuery, type Query } from "@tanstack/react-query"
-import type { Channel } from "@alook/shared"
-import { listChannels, createChannelApi, renameChannelApi, deleteChannelApi, reorderChannelsApi } from "@/lib/api"
-import { toast } from "sonner"
-import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source"
-import { workspaceRequestOptions } from "./workspace-context"
-import { assertWorkspaceOwner, captureWorkspaceOwner, runWorkspaceRequest, useWorkspaceOwner, type WorkspaceOwner } from "./workspace-context"
-
-function preferenceKey(workspace: WorkspaceOwner, agentId: string | null) {
- return `alook:channel:v2:${workspace.application.userId}:${workspace.workspaceId}:${agentId ?? "workspace"}`
-}
-function createChannelOwner(workspace: WorkspaceOwner) {
- const ui = createStore({ activeChannel: "default", agentId: null as string | null, selection: 0 })
- return {
- workspace, ui,
- key: workspace.key("channels"),
- setActiveChannel: (name: string) => {
- if (!workspace.lifecycle.get().active || !workspace.application.lifecycle.get().active) return
- ui.setState((state) => state.activeChannel === name ? state : { ...state, activeChannel: name, selection: state.selection + 1 })
- try { localStorage.setItem(preferenceKey(workspace, ui.get().agentId), name) } catch {}
- },
- setAgentId: (agentId: string | null) => {
- if (!workspace.lifecycle.get().active || !workspace.application.lifecycle.get().active) return
- let activeChannel = "default"
- try { activeChannel = localStorage.getItem(preferenceKey(workspace, agentId)) ?? "default" } catch {}
- ui.setState((state) => state.agentId === agentId ? state : { agentId, activeChannel, selection: state.selection + 1 })
- },
- }
-}
-const { StoreProvider, useStoreContext } = createStoreContext<{ owner: ReturnType<typeof createChannelOwner> }>()
-const EMPTY_CHANNELS: Channel[] = []
-export function ChannelProvider({ workspaceId, children }: { workspaceId: string; children: ReactNode }) {
- const workspace = useWorkspaceOwner()
- const handles = useMemo(() => ({ owner: createChannelOwner(workspace) }), [workspace])
- useEffect(() => {
- const onStorage = (event: StorageEvent) => {
- if (event.key !== preferenceKey(workspace, handles.owner.ui.get().agentId)) return
- handles.owner.ui.setState((state) => ({ ...state, activeChannel: event.newValue ?? "default", selection: state.selection + 1 }))
- }
- window.addEventListener("storage", onStorage)
- return () => window.removeEventListener("storage", onStorage)
- }, [handles, workspace])
- if (workspace.workspaceId !== workspaceId) throw new Error("Channel workspace owner mismatch")
- return <StoreProvider value={handles}>{children}</StoreProvider>
-}
-export function useChannel() {
- const { owner } = useStoreContext()
- const { workspace } = owner
- const qc = workspace.queryClient
- const activeChannel = useSelector(owner.ui, (state) => state.activeChannel)
- const query = useQuery({ queryKey: owner.key, queryFn: ({ signal }) => runWorkspaceRequest(workspace, (options) => listChannels(workspace.workspaceId, options), signal) })
- const source = useWorkspaceViewSource(workspace, "workspace-channel-commands", true)
- const commandKey = [...owner.key, "command"]
- type Action = { kind: "create"; name: string } | { kind: "rename"; id: string; name: string } | { kind: "delete"; id: string } | { kind: "reorder"; ids: string[] }
- type Intent = { action: Action; token: ReturnType<typeof captureWorkspaceOwner>; view: ReturnType<typeof source.capture>; resource: Query | undefined; selection: number; targetName?: string }
- const native = useMutation({ meta: { observabilityAction: "workspace.channel.command" }, mutationKey: commandKey, scope: { id: JSON.stringify(commandKey) }, gcTime: 0,
- mutationFn: async ({ action, token, view, resource, selection, targetName }: Intent) => {
- const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert() }
- const original = () => resource && qc.getQueryCache().find({ queryKey: owner.key, exact: true }) === resource
- assert()
- if (original()) await qc.cancelQueries({ queryKey: owner.key, exact: true })
- assert()
- const options = workspaceRequestOptions(token, view.signal, assert)
- try {
- let created: Awaited<ReturnType<typeof createChannelApi>> | undefined
- if (action.kind === "create") created = await createChannelApi(workspace.workspaceId, action.name, options)
- else if (action.kind === "rename") await renameChannelApi(action.id, workspace.workspaceId, action.name, options)
- else if (action.kind === "delete") await deleteChannelApi(action.id, workspace.workspaceId, options)
- else await reorderChannelsApi(workspace.workspaceId, action.ids, options)
- assert()
- if (original()) await qc.invalidateQueries({ queryKey: owner.key, exact: true }, { cancelRefetch: false })
- assert()
- const state = owner.ui.get()
- if (state.selection === selection && targetName === state.activeChannel) {
- if (action.kind === "rename") owner.setActiveChannel(action.name)
- else if (action.kind === "delete") owner.setActiveChannel("default")
- }
- return created
- } catch (error) { assert(); throw error }
- },
- })
- const pending = useMutationState({ filters: { mutationKey: commandKey, status: "pending", exact: true }, select: (mutation) => (mutation.state.variables as Intent).action })
- const order = pending.filter((action): action is Extract<Action, { kind: "reorder" }> => action.kind === "reorder").at(-1)?.ids
- const facts = query.data ?? EMPTY_CHANNELS
- const channels = useMemo(() => {
- if (!order) return facts
- const rows = new Map(facts.map((row) => [row.id, row])), wanted = new Set(order)
- return [...order.flatMap((id) => rows.get(id) ?? []), ...facts.filter((row) => !wanted.has(row.id))]
- }, [facts, order])
- const capture = (action: Action): Intent => {
- const view = source.capture(); view.assert()
- return { action, token: captureWorkspaceOwner(workspace), view, resource: qc.getQueryCache().find({ queryKey: owner.key, exact: true }), selection: owner.ui.get().selection, targetName: "id" in action ? qc.getQueryData<Channel[]>(owner.key)?.find((row) => row.id === action.id)?.name : undefined }
- }
- const execute = (action: Action) => native.mutateAsync(capture(action))
- const creating = pending.some((action) => action.kind === "create"), renaming = pending.find((action) => action.kind === "rename"), deleting = pending.find((action) => action.kind === "delete")
- const busy = (kind: Action["kind"]) => qc.getMutationCache().findAll({ mutationKey: commandKey, status: "pending", exact: true }).some((mutation) => (mutation.state.variables as Intent).action.kind === kind)
- const refresh = useCallback(() => { const token = captureWorkspaceOwner(workspace); assertWorkspaceOwner(token); return qc.invalidateQueries({ queryKey: owner.key, exact: true }) }, [qc, owner, workspace])
- return {
- channels, activeChannel, readActiveChannel: () => owner.ui.get().activeChannel, loading: query.isPending,
- creating, renaming: renaming?.kind === "rename" ? renaming.id : null, deleting: deleting?.kind === "delete" ? deleting.id : null,
- setActiveChannel: owner.setActiveChannel, setAgentId: owner.setAgentId,
- createChannel: async (name: string) => busy("create") ? undefined : execute({ kind: "create", name }),
- renameChannel: async (id: string, name: string) => { if (!busy("rename")) await execute({ kind: "rename", id, name }) },
- deleteChannel: async (id: string) => { if (!busy("delete")) await execute({ kind: "delete", id }) },
- reorderChannels: async (ids: string[]) => { const intent = capture({ kind: "reorder", ids }); try { await native.mutateAsync(intent) } catch (error) { if (!isAbortError(error)) { try { intent.view.assert(); assertWorkspaceOwner(intent.token); toast.error("Failed to reorder channels") } catch {} } } },
- refresh,
- }
-
-}
diff --git a/src/web/src/contexts/flag-count-context.tsx b/src/web/src/contexts/flag-count-context.tsx
deleted file mode 100644
index b3933c912..000000000
--- a/src/web/src/contexts/flag-count-context.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-"use client"
-
-import { useCallback, useMemo, type ReactNode } from "react"
-import { createStoreContext } from "@tanstack/react-store"
-import { useQuery } from "@tanstack/react-query"
-import { beginFlagCountWrite, rollbackFlagCountWrite, type FlagCountData } from "@/lib/workspace-flag-count"
-import { getFlaggedCount } from "@/lib/api"
-import { runWorkspaceRequest, useWorkspaceOwner, type WorkspaceOwner } from "./workspace-context"
-const { StoreProvider, useStoreContext } = createStoreContext<{ workspace: WorkspaceOwner }>()
-export function FlagCountProvider({ children }: { children: ReactNode }) {
- const workspace = useWorkspaceOwner()
- const handles = useMemo(() => ({ workspace }), [workspace])
- return <StoreProvider value={handles}>{children}</StoreProvider>
-}
-export function useFlagCount() {
- const { workspace } = useStoreContext()
- const key = useMemo(() => workspace.key("flag-count"), [workspace])
- const query = useQuery({ queryKey: key, queryFn: async ({ signal }) => {
- const requestRevision = workspace.queryClient.getQueryData<FlagCountData>(key)?.revision ?? 0
- const data = await runWorkspaceRequest(workspace, (options) => getFlaggedCount(workspace.workspaceId, options), signal)
- return { ...data, requestRevision } satisfies FlagCountData
- } })
- const refresh = useCallback(() => { void workspace.queryClient.invalidateQueries({ queryKey: key, exact: true }) }, [workspace, key])
- const begin = useCallback((delta: number) => beginFlagCountWrite(workspace, delta), [workspace])
- const rollback = useCallback((ticket: ReturnType<typeof beginFlagCountWrite>) => rollbackFlagCountWrite(workspace, ticket), [workspace])
- return useMemo(() => ({ count: query.data?.count ?? 0, refresh, begin, rollback }), [query.data?.count, refresh, begin, rollback])
-}
diff --git a/src/web/src/contexts/inbox-count-context.tsx b/src/web/src/contexts/inbox-count-context.tsx
deleted file mode 100644
index f8507827c..000000000
--- a/src/web/src/contexts/inbox-count-context.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-"use client"
-
-import { useCallback, useEffect, useMemo, type ReactNode } from "react"
-import { createStore, createStoreContext, useSelector } from "@tanstack/react-store"
-import { hashKey, useQuery } from "@tanstack/react-query"
-import { getInboxCount } from "@/lib/api"
-import { useAgentContext } from "./agent-context"
-import { runWorkspaceRequest, useWorkspaceOwner, type WorkspaceOwner } from "./workspace-context"
-import { sendTaskNotification } from "@/lib/browser-notification"
-import type { Agent } from "@alook/shared"
-function createInboxOwner(workspace: WorkspaceOwner) {
- return {
- workspace,
- ui: createStore({ notificationToken: 0, pendingAgentId: null as string | null, pendingStatus: null as "completed" | "failed" | null, serverBaselines: new Map<string, number>() }),
- }
-}
-const { StoreProvider, useStoreContext } = createStoreContext<{ owner: ReturnType<typeof createInboxOwner> }>()
-export function useInboxCount({ poll = false }: { poll?: boolean } = {}) {
- const { owner } = useStoreContext()
- const { workspace } = owner
- const types = useSelector(workspace.application.preferences, (state) => state.inboxFilterTypes)
- const preferencesHydrated = useSelector(workspace.application.preferences, (state) => state.hydrated)
- const notificationToken = useSelector(owner.ui, (state) => state.notificationToken)
- const key = useMemo(() => workspace.key("inbox-count", types), [workspace, types])
- const query = useQuery({
- queryKey: key, enabled: preferencesHydrated,
- queryFn: ({ signal }) => runWorkspaceRequest(workspace, (options) => getInboxCount(workspace.workspaceId, { types }, options), signal),
- refetchInterval: poll ? 60_000 : false, refetchIntervalInBackground: false,
- })
- const refresh = useCallback(() => {
- void workspace.queryClient.invalidateQueries({ queryKey: workspace.key("inbox-count") })
- }, [workspace])
- const decrement = useCallback(() => {
- if (!workspace.lifecycle.get().active || !workspace.application.lifecycle.get().active) return
- workspace.queryClient.setQueryData<{ count: number }>(key, (data) => ({ count: Math.max(0, (data?.count ?? 0) - 1) }))
- }, [workspace, key])
- return useMemo(() => ({
- queryKey: key, count: query.data?.count ?? 0, notificationToken, resolved: query.isSuccess, dataUpdatedAt: query.dataUpdatedAt,
- refresh, decrement,
- }), [query.data?.count, query.isSuccess, query.dataUpdatedAt, notificationToken, refresh, decrement, key])
-}
-function InboxCountBootstrap({ owner }: { owner: ReturnType<typeof createInboxOwner> }) {
- const { refresh, queryKey } = useInboxCount({ poll: true })
- const { subscribeWs } = useAgentContext()
- useEffect(() => {
- const hash = hashKey(queryKey)
- return owner.workspace.queryClient.getQueryCache().subscribe((event) => {
- if (event.type !== "updated" || event.action.type !== "success" || event.action.manual || event.query.queryHash !== hash) return
- if (!owner.workspace.lifecycle.get().active || !owner.workspace.application.lifecycle.get().active) return
- const next = (event.query.state.data as { count: number }).count
- const previous = owner.ui.get().serverBaselines.get(hash)
- const { pendingAgentId, pendingStatus } = owner.ui.get()
- const notify = previous !== undefined && next > previous
- owner.ui.setState((state) => ({ ...state, notificationToken: state.notificationToken + (notify ? 1 : 0), pendingAgentId: null, pendingStatus: null, serverBaselines: new Map(state.serverBaselines).set(hash, next) }))
- if (notify) {
- void owner.workspace.queryClient.invalidateQueries({ queryKey: owner.workspace.key("inbox") })
- const agents = owner.workspace.queryClient.getQueryData<Agent[]>(owner.workspace.key("agents"))
- sendTaskNotification(pendingStatus ?? "completed", agents?.find((agent) => agent.id === pendingAgentId)?.name, undefined, owner.workspace.application.preferences.get().browserNotifications)
- }
- })
- }, [queryKey, owner])
- useEffect(() => subscribeWs((message) => {
- if (message.type !== "task.updated" || message.status !== "completed" && message.status !== "failed") return
- owner.ui.setState((state) => ({ ...state, pendingAgentId: message.agentId, pendingStatus: message.status as "completed" | "failed" }))
- refresh()
- void owner.workspace.queryClient.invalidateQueries({ queryKey: owner.workspace.key("inbox") })
- }), [owner, refresh, subscribeWs])
- return null
-}
-export function InboxCountProvider({ children }: { children: ReactNode }) {
- const workspace = useWorkspaceOwner()
- const handles = useMemo(() => ({ owner: createInboxOwner(workspace) }), [workspace])
- return <StoreProvider value={handles}><InboxCountBootstrap owner={handles.owner} />{children}</StoreProvider>
-}
diff --git a/src/web/src/contexts/workspace-context.tsx b/src/web/src/contexts/workspace-context.tsx
deleted file mode 100644
index 9c0fb652e..000000000
--- a/src/web/src/contexts/workspace-context.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-"use client"
-
-import { commandObservation } from "@/lib/observability/context"
-
-import { UnauthorizedError } from "@/lib/errors"
-import { useEffect, useLayoutEffect, useState, type ReactNode } from "react"
-import { createStore, createStoreContext } from "@tanstack/react-store"
-import { reconcileFlagCount } from "@/lib/workspace-flag-count"
-import { reconcileChatFlags } from "@/lib/workspace-chat-flags"
-import { reconcileWorkspaceIssue } from "@/lib/workspace-issue-reconciliation"
-import { reconcileChatMessages } from "@/lib/workspace-chat-reconciliation"
-import { reconcileQueryReceipt } from "@/lib/query-receipt"
-import type { ApiRequestOptions } from "@/lib/api/client"
-import {
- applicationKey, assertApplicationOwner, captureApplicationOwner, invalidateApplicationAuthentication,
- useApplicationOwner, type ApplicationOwner,
-} from "@/lib/application-owner"
-
-export function createWorkspaceOwner(application: ApplicationOwner, workspaceId: string, slug: string) {
- application.queryClient.setQueryDefaults(applicationKey(application, "workspace", workspaceId, "chat", "messages"), { structuralSharing: reconcileChatMessages })
- application.queryClient.setQueryDefaults(applicationKey(application, "workspace", workspaceId, "issues", "detail"), { structuralSharing: reconcileWorkspaceIssue })
- application.queryClient.setQueryDefaults(applicationKey(application, "workspace", workspaceId, "chat", "flags"), { structuralSharing: reconcileChatFlags })
- application.queryClient.setQueryDefaults(applicationKey(application, "workspace", workspaceId, "flag-count"), { structuralSharing: reconcileFlagCount })
- application.queryClient.setQueryDefaults(applicationKey(application, "workspace", workspaceId, "email", "entity"), { structuralSharing: reconcileQueryReceipt })
- application.queryClient.setQueryDefaults(applicationKey(application, "workspace", workspaceId, "email", "body"), { structuralSharing: reconcileQueryReceipt })
- for (const resource of ["task", "task-messages", "active-task", "extras"]) application.queryClient.setQueryDefaults(applicationKey(application, "workspace", workspaceId, "chat", resource), { structuralSharing: reconcileQueryReceipt })
- return {
- application, workspaceId, slug,
- queryClient: application.queryClient,
- lifecycle: createStore({ active: true, generation: 0 }),
- key: (...parts: readonly unknown[]) => applicationKey(application, "workspace", workspaceId, ...parts),
- }
-}
-export type WorkspaceOwner = ReturnType<typeof createWorkspaceOwner>
-export function captureWorkspaceOwner(owner: WorkspaceOwner) {
- return { owner, generation: owner.lifecycle.get().generation, application: captureApplicationOwner(owner.application) }
-}
-export function assertWorkspaceOwner(token: ReturnType<typeof captureWorkspaceOwner>, signal?: AbortSignal) {
- assertApplicationOwner(token.application, signal)
- const state = token.owner.lifecycle.get()
- if (!state.active || state.generation !== token.generation) {
- throw new DOMException("Retired workspace owner", "AbortError")
- }
-}
-export function workspaceRequestOptions(token: ReturnType<typeof captureWorkspaceOwner>, signal?: AbortSignal, assertActive = () => assertWorkspaceOwner(token, signal)): ApiRequestOptions & { assertActive: () => void } {
- return { observation: commandObservation(token), authenticationAccount: token.owner.application.userId, signal, assertActive, onUnauthorized: () => { assertActive(); return invalidateApplicationAuthentication(token.application, signal) } }
-}
-export async function runWorkspaceRequest<T>(owner: WorkspaceOwner, load: (options: ApiRequestOptions) => Promise<T>, signal?: AbortSignal) {
- const token = captureWorkspaceOwner(owner)
- assertWorkspaceOwner(token, signal)
- try {
- const data = await load(workspaceRequestOptions(token, signal))
- assertWorkspaceOwner(token, signal)
- return data
- } catch (error) {
- if (error instanceof UnauthorizedError) throw error
- assertWorkspaceOwner(token, signal)
- throw error
- }
-}
-const { StoreProvider, useStoreContext } = createStoreContext<{ owner: WorkspaceOwner }>()
-export const useWorkspaceOwner = () => useStoreContext().owner
-export function useWorkspace() {
- const { workspaceId, slug } = useWorkspaceOwner()
- return { workspaceId, slug }
-}
-
-export function WorkspaceProvider({ workspaceId, slug, children }: {
- workspaceId: string; slug: string; children: ReactNode,
-}) {
- const application = useApplicationOwner()
- return <ScopedWorkspaceProvider key={`${application.userId}:${workspaceId}`} application={application} workspaceId={workspaceId} slug={slug}>
- {children}
- </ScopedWorkspaceProvider>
-}
-function ScopedWorkspaceProvider({ application, workspaceId, slug, children }: {
- application: ApplicationOwner; workspaceId: string; slug: string; children: ReactNode,
-}) {
- const [owner] = useState(() => createWorkspaceOwner(application, workspaceId, slug))
- const [handles] = useState(() => ({ owner }))
- useLayoutEffect(() => {
- owner.lifecycle.setState((state) => state.active ? state : { ...state, active: true })
- return () => {
- owner.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
- void owner.queryClient.cancelQueries({ queryKey: owner.key() })
- }
- }, [owner])
- useEffect(() => {
- // Navigation memory is scoped to the signed-in account; old device-global
- // lastWorkspace is not an authority for this account's selection.
- application.preferences.setState((state) => ({ ...state, lastWorkspaceSlug: slug }))
- try { localStorage.setItem(`alook:${application.userId}:lastWorkspace`, slug) } catch {}
- }, [application.preferences, application.userId, slug])
- return <StoreProvider value={handles}>{children}</StoreProvider>
-}
diff --git a/src/web/src/contexts/workspace-data.dom.test.tsx b/src/web/src/contexts/workspace-data.dom.test.tsx
deleted file mode 100644
index 4bf358ab0..000000000
--- a/src/web/src/contexts/workspace-data.dom.test.tsx
+++ /dev/null
@@ -1,428 +0,0 @@
-import "fake-indexeddb/auto"
-import { useLayoutEffect } from "react"
-import React from "react"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, render, waitFor } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider, useWorkspaceOwner, type WorkspaceOwner } from "./workspace-context"
-import { AgentProvider, useAgentContext } from "./agent-context"
-import { ChannelProvider, useChannel } from "./channel-context"
-import { InboxCountProvider, useInboxCount } from "./inbox-count-context"
-import { FlagCountProvider, useFlagCount } from "./flag-count-context"
-import { setInboxFilterTypes } from "@/lib/inbox-filter"
-import { focusManager } from "@tanstack/react-query"
-import { useMarkAllInboxRead, useUnflagWorkspaceMessage, useWorkspaceFlags, useWorkspaceInbox } from "@/hooks/workspace/use-inbox"
-import CreateAgentPage from "@/app/(app)/w/[slug]/agents/new/page"
-
-const mocks = vi.hoisted(() => ({
- userId: "viewer-a",
- ws: null as null | ((message: unknown) => void),
- router: { replace: vi.fn(), refresh: vi.fn(), push: vi.fn(), back: vi.fn() },
- listAgents: vi.fn(), listRuntimes: vi.fn(), listAgentLinks: vi.fn(), listAgentPins: vi.fn(),
- listAgentActiveTaskCounts: vi.fn(), listWorkspaceActiveTasks: vi.fn(),
- createAgent: vi.fn(), updateAgent: vi.fn(), deleteAgent: vi.fn(), deleteMachine: vi.fn(), createMachineToken: vi.fn(),
- pinAgent: vi.fn(), unpinAgent: vi.fn(), reorderAgentPins: vi.fn(), reorderUnpinnedAgents: vi.fn(),
- listChannels: vi.fn(), createChannelApi: vi.fn(), renameChannelApi: vi.fn(), deleteChannelApi: vi.fn(), reorderChannelsApi: vi.fn(),
- getInboxCount: vi.fn(), getFlaggedCount: vi.fn(), notify: vi.fn(), toast: vi.fn(),
- listInboxItems: vi.fn(), listFlaggedItems: vi.fn(), markAllInboxRead: vi.fn(), unflagMessage: vi.fn(),
- fetchModelOptions: vi.fn(), createEmailAccount: vi.fn(), successToast: vi.fn(), analytics: vi.fn(),
- save: null as null | ((data: { name: string; description: string; instructions: string; runtime_id: string; custom_email?: { emailAddress: string } }) => Promise<boolean>),
-}))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ isPending: false, error: null, data: { user: { id: mocks.userId } } }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("next/navigation", () => ({ useRouter: () => mocks.router }))
-vi.mock("@/lib/api", () => mocks)
-vi.mock("sonner", () => ({ toast: { error: mocks.toast, success: mocks.successToast } }))
-vi.mock("@/components/agent-create-form", () => ({ AgentCreateForm: (props: { onSave: typeof mocks.save }) => { mocks.save = props.onSave; return null } }))
-vi.mock("@/lib/analytics", () => ({ trackAgentCreated: mocks.analytics, trackSecondAgentCreated: mocks.analytics, trackCustomEmailConnected: mocks.analytics }))
-vi.mock("@/lib/browser-notification", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/browser-notification")>(), sendTaskNotification: mocks.notify }))
-vi.mock("@/lib/use-user-ws", () => ({ useUserWs: (callback: (message: unknown) => void) => { mocks.ws = callback } }))
-
-function held<T>() {
- let resolve!: (value: T) => void
- let reject!: (error: Error) => void
- const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })
- return { promise, resolve, reject }
-}
-const pins = () => ({
- pins: ["a", "b"].map((agent_id, position) => ({ id: `pin-${agent_id}`, agent_id, position, created_at: "2026-10-01T00:00:00Z" })),
- sidebar_order: ["c", "d"].map((agent_id, position) => ({ agent_id, position })),
-})
-let current: {
- workspace: WorkspaceOwner,
- agents: ReturnType<typeof useAgentContext>, channel: ReturnType<typeof useChannel>,
- inbox: ReturnType<typeof useInboxCount>, flags: ReturnType<typeof useFlagCount>,
- inboxPages: ReturnType<typeof useWorkspaceInbox>, flagPages: ReturnType<typeof useWorkspaceFlags>,
- markAll: ReturnType<typeof useMarkAllInboxRead>, unflag: ReturnType<typeof useUnflagWorkspaceMessage>,
-}
-let listsEnabled = false
-let showCreatePage = false
-const clients = new Set<WorkspaceOwner["queryClient"]>()
-function Probe() {
- const workspace = useWorkspaceOwner()
- clients.add(workspace.queryClient)
- const value = { workspace, agents: useAgentContext(), channel: useChannel(), inbox: useInboxCount(), flags: useFlagCount(),
- inboxPages: useWorkspaceInbox(listsEnabled), flagPages: useWorkspaceFlags(listsEnabled),
- markAll: useMarkAllInboxRead(), unflag: useUnflagWorkspaceMessage(),
- }
- useLayoutEffect(() => { current = value })
- return <output data-testid="workspace-state">{value.agents.loading ? "loading" : workspace.application.userId}</output>
-}
-function tree(userId = "viewer-a", workspaceId = "workspace-a") {
- return <ApplicationQueryProvider userId={userId}>
- <WorkspaceProvider workspaceId={workspaceId} slug={workspaceId}>
- <AgentProvider workspaceId={workspaceId}>
- <ChannelProvider workspaceId={workspaceId}>
- <InboxCountProvider><FlagCountProvider><Probe />{showCreatePage && <CreateAgentPage />}</FlagCountProvider></InboxCountProvider>
- </ChannelProvider>
- </AgentProvider>
- </WorkspaceProvider>
- </ApplicationQueryProvider>
-}
-async function mount() {
- const renderer = render(tree())
- await waitFor(() => {
- expect(current.agents.loading).toBe(false)
- expect(current.inbox.resolved).toBe(true)
- expect(current.channel.loading).toBe(false)
- expect(current.agents.pins.size).toBe(2)
- })
- return renderer
-}
-beforeEach(() => {
- vi.clearAllMocks()
- localStorage.clear()
- mocks.userId = "viewer-a"
- mocks.ws = null
- listsEnabled = false
- showCreatePage = false
- mocks.save = null
- mocks.listAgents.mockResolvedValue([])
- mocks.listRuntimes.mockResolvedValue([])
- mocks.listAgentLinks.mockResolvedValue([])
- mocks.listAgentPins.mockImplementation(() => Promise.resolve(pins()))
- mocks.listAgentActiveTaskCounts.mockResolvedValue({ counts: {} })
- mocks.listWorkspaceActiveTasks.mockResolvedValue({ tasks: [] })
- mocks.listChannels.mockResolvedValue([{ id: "ch-a", name: "default" }, { id: "ch-b", name: "work" }])
- mocks.getInboxCount.mockResolvedValue({ count: 5 })
- mocks.getFlaggedCount.mockResolvedValue({ count: 2 })
- mocks.listInboxItems.mockResolvedValue({ items: [{ id: "inbox-a", latest_response: "newer first-page content", latest_response_at: "2026-10-01T02:00:00Z" }], has_more: true })
- mocks.listFlaggedItems.mockResolvedValue({ items: [{ id: "flag-a", message_id: "message-a", flagged_at: "2026-10-01T02:00:00Z" }], has_more: false })
- mocks.fetchModelOptions.mockResolvedValue({})
- mocks.createEmailAccount.mockResolvedValue({ id: "email-a" })
-})
-afterEach(async () => {
- await act(async () => {
- vi.useRealTimers()
- focusManager.setFocused(undefined)
- await new Promise((resolve) => setTimeout(resolve, 0))
- for (const client of clients) client.clear()
- clients.clear()
- })
-})
-
-describe("native workspace ownership", () => {
- it.each(["reload", "email"] as const)("create-page intent stays quiet after retirement during %s", async (stage) => {
- showCreatePage = true
- const refresh = held<unknown[]>()
- const email = held<unknown>()
- mocks.createAgent.mockResolvedValueOnce({ id: "created-in-a" })
- const renderer = await mount()
- if (stage === "reload") mocks.listAgents.mockReturnValueOnce(refresh.promise)
- else mocks.createEmailAccount.mockReturnValueOnce(email.promise)
- let operation!: Promise<boolean>
- act(() => { operation = mocks.save!({ name: "A agent", description: "", instructions: "", runtime_id: "runtime-a", custom_email: { emailAddress: "[email protected]" } }) })
- await waitFor(() => stage === "reload" ? expect(mocks.listAgents).toHaveBeenCalledTimes(2) : expect(mocks.createEmailAccount).toHaveBeenCalledOnce())
- act(() => { mocks.userId = "viewer-b"; renderer.rerender(tree("viewer-b")) })
- let result: boolean | undefined
- await act(async () => { refresh.resolve([]); email.resolve({ id: "email-a" }); result = await operation })
- expect(result).toBe(false)
- expect(mocks.successToast).not.toHaveBeenCalled()
- expect(mocks.toast).not.toHaveBeenCalled()
- expect(mocks.router.push).not.toHaveBeenCalled()
- if (stage === "reload") expect(mocks.createEmailAccount).not.toHaveBeenCalled()
- else expect(mocks.createEmailAccount.mock.calls[0][3].assertActive).toBeTypeOf("function")
- renderer.unmount()
- })
-
- it("active create-page email failure remains visible and keeps navigation", async () => {
- showCreatePage = true
- mocks.createAgent.mockResolvedValueOnce({ id: "created-in-a" })
- mocks.createEmailAccount.mockRejectedValueOnce(new Error("active email failure"))
- const renderer = await mount()
- let result: boolean | undefined
- await act(async () => { result = await mocks.save!({ name: "A agent", description: "", instructions: "", runtime_id: "runtime-a", custom_email: { emailAddress: "[email protected]" } }) })
- expect(result).toBe(true)
- expect(mocks.toast).toHaveBeenCalledWith("active email failure")
- expect(mocks.router.push).toHaveBeenCalledWith("/w/workspace-a/agents/created-in-a/chat")
- renderer.unmount()
- })
- it("real Strict Mode replay retains its owner and real unmount clears Query", async () => {
- const renderer = render(<React.StrictMode>{tree()}</React.StrictMode>)
- await waitFor(() => expect(current.agents.loading).toBe(false))
- const source = current.workspace
- await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
- expect(source.application.lifecycle.get().active).toBe(true)
- expect(source.lifecycle.get().active).toBe(true)
- expect(source.queryClient.getQueryData(source.key("agents"))).toEqual([])
- renderer.unmount()
- await waitFor(() => expect(source.queryClient.getQueryCache().getAll()).toHaveLength(0))
- expect(source.application.lifecycle.get().active).toBe(false)
- })
-
- it("InfiniteQuery appends unique inbox rows and keeps the cursor in Query", async () => {
- listsEnabled = true
- const renderer = await mount()
- await waitFor(() => expect(current.inboxPages.items).toHaveLength(1))
- mocks.listInboxItems.mockResolvedValueOnce({ items: [{ id: "inbox-a", latest_response: "older overlapping content", latest_response_at: "2026-10-01T02:00:00Z" }, { id: "inbox-b", latest_response_at: "2026-10-01T01:00:00Z" }], has_more: false })
- await act(async () => { await current.inboxPages.fetchNextPage() })
- await waitFor(() => expect(current.inboxPages.items.map((item) => item.id)).toEqual(["inbox-a", "inbox-b"]))
- expect(current.inboxPages.items[0].latest_response).toBe("newer first-page content")
- expect(current.inboxPages.data?.pageParams).toEqual([undefined, "2026-10-01T02:00:00Z"])
- expect(current.inboxPages.hasNextPage).toBe(false)
- expect(mocks.listInboxItems.mock.calls[1][2].signal).toBeInstanceOf(AbortSignal)
- renderer.unmount()
- })
-
- it("overlapping flag pages retain the first row content, ordering, and cursor", async () => {
- listsEnabled = true
- mocks.listFlaggedItems.mockResolvedValueOnce({ items: [{ id: "flag-a", message_content: "newer first-page content", flagged_at: "2026-10-01T02:00:00Z" }], has_more: true })
- const renderer = await mount()
- await waitFor(() => expect(current.flagPages.items).toHaveLength(1))
- mocks.listFlaggedItems.mockResolvedValueOnce({ items: [{ id: "flag-a", message_content: "older overlapping content", flagged_at: "2026-10-01T02:00:00Z" }, { id: "flag-b", flagged_at: "2026-10-01T01:00:00Z" }], has_more: false })
- await act(async () => { await current.flagPages.fetchNextPage() })
- await waitFor(() => expect(current.flagPages.items.map((item) => item.id)).toEqual(["flag-a", "flag-b"]))
- expect(current.flagPages.items[0].message_content).toBe("newer first-page content")
- expect(current.flagPages.data?.pageParams).toEqual([undefined, "2026-10-01T02:00:00Z"])
- expect(current.flagPages.hasNextPage).toBe(false)
- renderer.unmount()
- })
-
- it("mark-all publishes immediately and rolls back pages plus count on failure", async () => {
- listsEnabled = true
- const request = held<void>()
- mocks.markAllInboxRead.mockReturnValueOnce(request.promise)
- const renderer = await mount()
- await waitFor(() => expect(current.inboxPages.items).toHaveLength(1))
- let operation!: Promise<void>
- act(() => { operation = current.markAll.mutateAsync().catch(() => undefined) })
- await waitFor(() => {
- expect(current.inboxPages.items).toHaveLength(0)
- expect(current.inbox.count).toBe(0)
- })
- await act(async () => { request.reject(new Error("read failed")); await operation })
- await waitFor(() => {
- expect(current.inboxPages.items).toHaveLength(1)
- expect(current.inbox.count).toBe(5)
- })
- expect(mocks.notify).not.toHaveBeenCalled()
- renderer.unmount()
- })
-
- it("unflag removes the canonical row immediately and restores row plus count on failure", async () => {
- listsEnabled = true
- const request = held<void>()
- mocks.unflagMessage.mockReturnValueOnce(request.promise)
- const renderer = await mount()
- await waitFor(() => expect(current.flagPages.items).toHaveLength(1))
- let operation!: Promise<void>
- act(() => { operation = current.unflag.mutateAsync("message-a").catch(() => undefined) })
- await waitFor(() => {
- expect(current.flagPages.items).toHaveLength(0)
- expect(current.flags.count).toBe(1)
- })
- await act(async () => { request.reject(new Error("unflag failed")); await operation })
- await waitFor(() => {
- expect(current.flagPages.items).toHaveLength(1)
- expect(current.flags.count).toBe(2)
- })
- renderer.unmount()
- })
- it.each(["pin", "unpin", "reorder-pins", "reorder-unpinned"] as const)("%s publishes before HTTP and rolls back failure", async (kind) => {
- const request = held<unknown>()
- const mock = { pin: mocks.pinAgent, unpin: mocks.unpinAgent, "reorder-pins": mocks.reorderAgentPins, "reorder-unpinned": mocks.reorderUnpinnedAgents }[kind]
- mock.mockReturnValueOnce(request.promise)
- const renderer = await mount()
- let operation!: Promise<void>
- act(() => {
- operation = kind === "pin" ? current.agents.handlePinAgent("c")
- : kind === "unpin" ? current.agents.handleUnpinAgent("a")
- : kind === "reorder-pins" ? current.agents.handleReorderPins(["b", "a"])
- : current.agents.handleReorderUnpinned(["d", "c"])
- })
- await waitFor(() => {
- expect(mock).toHaveBeenCalledOnce()
- if (kind === "pin") expect(current.agents.pins.has("c")).toBe(true)
- if (kind === "unpin") expect(current.agents.pins.has("a")).toBe(false)
- if (kind === "reorder-pins") expect(current.agents.pins.get("b")?.position).toBe(0)
- if (kind === "reorder-unpinned") expect(current.agents.unpinnedOrder.get("d")).toBe(0)
- })
- await act(async () => { request.reject(new Error("failed")); await operation })
- await waitFor(() => {
- expect(current.agents.pins.size).toBe(2)
- expect(current.agents.pins.get("a")?.position).toBe(0)
- expect(current.agents.unpinnedOrder.get("c")).toBe(0)
- })
- expect(mocks.toast).toHaveBeenCalledOnce()
- renderer.unmount()
- })
-
- it.each(["resolve", "reject"] as const)("retired mutation %s stays out of the next account", async (completion) => {
- const request = held<unknown>()
- mocks.pinAgent.mockReturnValueOnce(request.promise)
- const renderer = await mount()
- const source = current.workspace
- let operation!: Promise<void>
- act(() => { operation = current.agents.handlePinAgent("c") })
- await waitFor(() => expect(mocks.pinAgent).toHaveBeenCalledOnce())
- act(() => { mocks.userId = "viewer-b"; renderer.rerender(tree("viewer-b")) })
- await waitFor(() => expect(current.workspace.application.userId).toBe("viewer-b"))
- await act(async () => {
- if (completion === "resolve") request.resolve({ pinned: true })
- else request.reject(new Error("old account error"))
- await operation
- })
- await waitFor(() => expect(current.agents.pins.size).toBe(2))
- expect(source.lifecycle.get().active).toBe(false)
- expect(source.application.lifecycle.get().active).toBe(false)
- expect(current.agents.pins.has("c")).toBe(false)
- expect(mocks.toast).not.toHaveBeenCalled()
- expect(mocks.pinAgent.mock.calls[0][2].assertActive).toBeTypeOf("function")
- renderer.unmount()
- })
-
- it("failure followed by a held settled refresh is quiet if the account retires during that refresh", async () => {
- const mutation = held<unknown>()
- const refresh = held<ReturnType<typeof pins>>()
- mocks.pinAgent.mockReturnValueOnce(mutation.promise)
- const renderer = await mount()
- mocks.listAgentPins.mockReturnValueOnce(refresh.promise)
- let operation!: Promise<void>
- act(() => { operation = current.agents.handlePinAgent("c") })
- await waitFor(() => expect(mocks.pinAgent).toHaveBeenCalledOnce())
- await act(async () => { mutation.reject(new Error("pin failed before retirement")) })
- await waitFor(() => expect(mocks.listAgentPins).toHaveBeenCalledTimes(2))
- expect(mocks.toast).not.toHaveBeenCalled()
- act(() => { mocks.userId = "viewer-b"; renderer.rerender(tree("viewer-b")) })
- await act(async () => { refresh.resolve(pins()); await operation })
- await waitFor(() => expect(current.agents.loading).toBe(false))
- expect(current.workspace.application.userId).toBe("viewer-b")
- expect(mocks.toast).not.toHaveBeenCalled()
- expect(current.agents.pins.has("c")).toBe(false)
- renderer.unmount()
- })
-
- it("successful create cannot return an agent after retirement during its reload", async () => {
- const refresh = held<unknown[]>()
- mocks.createAgent.mockResolvedValueOnce({ id: "created-in-a" })
- const renderer = await mount()
- mocks.listAgents.mockReturnValueOnce(refresh.promise)
- let operation!: ReturnType<typeof current.agents.handleCreateAgent>
- act(() => { operation = current.agents.handleCreateAgent({ name: "A agent", runtime_id: "runtime-a" }) })
- await waitFor(() => expect(mocks.listAgents).toHaveBeenCalledTimes(2))
- act(() => { mocks.userId = "viewer-b"; renderer.rerender(tree("viewer-b")) })
- let result: Awaited<typeof operation> | undefined
- await act(async () => { refresh.resolve([]); result = await operation })
- expect(result).toBeNull()
- expect(current.workspace.application.userId).toBe("viewer-b")
- expect(mocks.toast).not.toHaveBeenCalled()
- renderer.unmount()
- })
-
- it("keeps selection scoped across workspace and account changes", async () => {
- const renderer = await mount()
- act(() => { current.channel.setActiveChannel("work") })
- expect(current.channel.activeChannel).toBe("work")
- act(() => renderer.rerender(tree("viewer-a", "workspace-b")))
- await waitFor(() => expect(current.workspace.workspaceId).toBe("workspace-b"))
- expect(current.channel.activeChannel).toBe("default")
- act(() => { mocks.userId = "viewer-b"; renderer.rerender(tree("viewer-b", "workspace-a")) })
- await waitFor(() => expect(current.workspace.application.userId).toBe("viewer-b"))
- expect(current.channel.activeChannel).toBe("default")
- expect(localStorage.getItem("alook:channel:v2:viewer-a:workspace-a:workspace")).toBe("work")
- renderer.unmount()
- })
-
- it("idle task loading reads counts; positive counts then enable details", async () => {
- const renderer = await mount()
- expect(mocks.listAgentActiveTaskCounts).toHaveBeenCalledOnce()
- expect(mocks.listWorkspaceActiveTasks).not.toHaveBeenCalled()
- mocks.listAgentActiveTaskCounts.mockResolvedValue({ counts: { a: 1 } })
- mocks.listWorkspaceActiveTasks.mockResolvedValue({ tasks: [{ id: "task", agent_id: "a", status: "running" }] })
- act(() => mocks.ws?.({ type: "task.updated", workspaceId: "workspace-a", agentId: "a", status: "running" }))
- await waitFor(() => expect(mocks.listWorkspaceActiveTasks).toHaveBeenCalledOnce())
- await waitFor(() => expect(current.agents.activeTaskCounts.a).toBe(1))
- expect(mocks.listAgentActiveTaskCounts.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal)
- renderer.unmount()
- })
-
- it("polls counts while idle and details while tasks are active, with one polling observer", async () => {
- vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date"] })
- focusManager.setFocused(true)
- const renderer = await mount()
- await act(async () => { await vi.advanceTimersByTimeAsync(15_001) })
- expect(mocks.listAgentActiveTaskCounts).toHaveBeenCalledTimes(2)
- expect(mocks.listWorkspaceActiveTasks).not.toHaveBeenCalled()
- mocks.listAgentActiveTaskCounts.mockResolvedValue({ counts: { a: 1 } })
- mocks.listWorkspaceActiveTasks.mockResolvedValue({ tasks: [{ id: "task", agent_id: "a", status: "running" }] })
- await act(async () => { await current.workspace.queryClient.refetchQueries({ queryKey: current.workspace.key("active-task-counts"), exact: true }) })
- await waitFor(() => expect(mocks.listWorkspaceActiveTasks).toHaveBeenCalledOnce())
- const countCalls = mocks.listAgentActiveTaskCounts.mock.calls.length
- await act(async () => { await vi.advanceTimersByTimeAsync(15_001) })
- expect(mocks.listWorkspaceActiveTasks).toHaveBeenCalledTimes(2)
- expect(mocks.listAgentActiveTaskCounts).toHaveBeenCalledTimes(countCalls)
- renderer.unmount()
- })
-
- it.each(["resolve", "reject"] as const)("retired read %s cannot publish into the replacement account", async (completion) => {
- const request = held<unknown[]>()
- mocks.listAgents.mockReturnValueOnce(request.promise)
- const renderer = render(tree())
- await waitFor(() => expect(mocks.listAgents).toHaveBeenCalledOnce())
- const source = current.workspace
- act(() => { mocks.userId = "viewer-b"; renderer.rerender(tree("viewer-b")) })
- await waitFor(() => expect(current.agents.loading).toBe(false))
- await act(async () => {
- if (completion === "resolve") request.resolve([{ id: "old-private-agent" }])
- else request.reject(new Error("old account read error"))
- })
- expect(current.workspace.application.userId).toBe("viewer-b")
- expect(current.agents.agents).toEqual([])
- expect(source.lifecycle.get().active).toBe(false)
- expect(mocks.listAgents.mock.calls[0][1].signal.aborted).toBe(true)
- expect(mocks.toast).not.toHaveBeenCalled()
- renderer.unmount()
- })
-
- it("initial count and local decrement do not trigger a completed notification", async () => {
- const request = held<{ count: number }>()
- const renderer = await mount()
- expect(mocks.notify).not.toHaveBeenCalled()
- mocks.getInboxCount.mockReturnValueOnce(request.promise)
- let fetch!: Promise<unknown>
- act(() => { fetch = current.workspace.queryClient.refetchQueries({ queryKey: current.inbox.queryKey, exact: true }) })
- await waitFor(() => expect(mocks.getInboxCount).toHaveBeenCalledTimes(2))
- act(() => current.inbox.decrement())
- await waitFor(() => expect(current.inbox.count).toBe(4))
- await act(async () => { request.resolve({ count: 5 }); await fetch })
- await waitFor(() => expect(current.inbox.count).toBe(5))
- expect(mocks.notify).not.toHaveBeenCalled()
- expect(current.inbox.notificationToken).toBe(0)
- mocks.getInboxCount.mockResolvedValue({ count: 6 })
- await act(async () => { await current.workspace.queryClient.refetchQueries({ queryKey: current.inbox.queryKey, exact: true }) })
- await waitFor(() => expect(mocks.notify).toHaveBeenCalledOnce())
- expect(current.inbox.notificationToken).toBe(1)
- renderer.unmount()
- })
-
- it("filter change establishes its own server baseline", async () => {
- const renderer = await mount()
- mocks.getInboxCount.mockResolvedValue({ count: 50 })
- act(() => setInboxFilterTypes(current.workspace.application, ["user_dm_message", "calendar_event"]))
- await waitFor(() => expect(current.inbox.count).toBe(50))
- expect(mocks.notify).not.toHaveBeenCalled()
- mocks.getInboxCount.mockResolvedValue({ count: 51 })
- await act(async () => { await current.workspace.queryClient.refetchQueries({ queryKey: current.inbox.queryKey, exact: true }) })
- await waitFor(() => expect(mocks.notify).toHaveBeenCalledOnce())
- renderer.unmount()
- })
-})
diff --git a/src/web/src/hooks/__tests__/use-cached-messages.test.ts b/src/web/src/hooks/__tests__/use-cached-messages.test.ts
deleted file mode 100644
index a854e14b1..000000000
--- a/src/web/src/hooks/__tests__/use-cached-messages.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { describe, it, expect, beforeEach } from "vitest";
-import "fake-indexeddb/auto";
-import { createApplicationOwner } from "@/lib/application-owner";
-import { createWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context";
-import type { Message } from "@alook/shared";
-import {
- clearAllCache,
- getCachedMessages,
- mergeCachedMessages,
-} from "@/lib/chat-cache";
-
-const WORKSPACE_ID = "ws_test";
-
-function makeMessage(overrides: Partial<Message> = {}): Message {
- return {
- id: `msg_${Math.random().toString(36).slice(2)}`,
- conversation_id: "conv_1",
- role: "user",
- content: "hello",
- task_id: null,
- attachment_ids: null,
- created_at: new Date().toISOString(),
- ...overrides,
- };
-}
-
-let cacheOwner: WorkspaceOwner;
-beforeEach(async () => { cacheOwner = createWorkspaceOwner(createApplicationOwner("cache-user"), WORKSPACE_ID, "test"); });
-
-describe("use-cached-messages (functional tests)", () => {
- it("getCachedMessages returns cached messages immediately after write", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).not.toBeNull();
- expect(cached).toHaveLength(2);
- expect(cached![0].id).toBe("m1");
- expect(cached![1].id).toBe("m2");
- });
-
- it("returns null when no cache exists", async () => {
- const cached = await getCachedMessages("conv_nonexistent", cacheOwner);
- expect(cached).toBeNull();
- });
-
- it("writeToCache (mergeCachedMessages) persists messages correctly", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toHaveLength(1);
- expect(cached![0].id).toBe("m1");
- });
-
- it("conversation switch loads correct cache", async () => {
- await mergeCachedMessages(
- "conv_1",
- [makeMessage({ id: "m1", conversation_id: "conv_1" })],
- false,
- cacheOwner
- );
- await mergeCachedMessages(
- "conv_2",
- [makeMessage({ id: "m2", conversation_id: "conv_2" })],
- false,
- cacheOwner
- );
-
- const cached1 = await getCachedMessages("conv_1", cacheOwner);
- const cached2 = await getCachedMessages("conv_2", cacheOwner);
-
- expect(cached1).toHaveLength(1);
- expect(cached1![0].id).toBe("m1");
- expect(cached2).toHaveLength(1);
- expect(cached2![0].id).toBe("m2");
- });
-});
diff --git a/src/web/src/hooks/__tests__/use-keyboard-scroll.test.ts b/src/web/src/hooks/__tests__/use-keyboard-scroll.test.ts
deleted file mode 100644
index 0c10deb3d..000000000
--- a/src/web/src/hooks/__tests__/use-keyboard-scroll.test.ts
+++ /dev/null
@@ -1,374 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import {
- createKeyboardScrollController,
- attachKeyboardScroll,
-} from "../use-keyboard-scroll";
-
-function createMockTarget(container?: HTMLElement | null) {
- const scrollIntoView = vi.fn();
- const target = {
- scrollIntoView,
- closest: vi.fn((selector: string) => {
- if (selector === "[data-keyboard-offset]") return container ?? null;
- return null;
- }),
- } as unknown as HTMLElement;
- return { target, scrollIntoView };
-}
-
-function createMockContainer(bottom = 800) {
- return {
- style: { transform: "" },
- getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom, width: 0, height: 0 }),
- setAttribute: vi.fn(),
- removeAttribute: vi.fn(),
- } as unknown as HTMLElement;
-}
-
-describe("createKeyboardScrollController", () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("falls back to scrollIntoView when no visualViewport available", () => {
- const { target, scrollIntoView } = createMockTarget(null);
- Object.defineProperty(globalThis, "window", {
- value: { innerHeight: 800, visualViewport: undefined },
- writable: true,
- configurable: true,
- });
- const { handler } = createKeyboardScrollController(() => target, true);
-
- handler();
- vi.advanceTimersByTime(150);
-
- expect(scrollIntoView).toHaveBeenCalledWith({
- block: "end",
- behavior: "smooth",
- });
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("applies transform offset when keyboard is open and container exists", () => {
- const container = createMockContainer();
- const { target } = createMockTarget(container);
- Object.defineProperty(globalThis, "window", {
- value: {
- innerHeight: 800,
- visualViewport: { height: 500, offsetTop: 0 },
- },
- writable: true,
- configurable: true,
- });
- const { handler } = createKeyboardScrollController(() => target, true);
-
- handler();
- vi.advanceTimersByTime(150);
-
- expect(container.style.transform).toBe("translateY(-300px)");
- expect(container.setAttribute).toHaveBeenCalledWith("data-keyboard-active", "");
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("clears transform when keyboard offset is zero", () => {
- const container = createMockContainer();
- container.style.transform = "translateY(-300px)";
- const { target } = createMockTarget(container);
- Object.defineProperty(globalThis, "window", {
- value: {
- innerHeight: 800,
- visualViewport: { height: 800, offsetTop: 0 },
- },
- writable: true,
- configurable: true,
- });
- const { handler } = createKeyboardScrollController(() => target, true);
-
- handler();
- vi.advanceTimersByTime(150);
-
- expect(container.style.transform).toBe("");
- expect(container.removeAttribute).toHaveBeenCalledWith("data-keyboard-active");
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("does NOT fire when not focused", () => {
- const container = createMockContainer();
- const { target } = createMockTarget(container);
- Object.defineProperty(globalThis, "window", {
- value: {
- innerHeight: 800,
- visualViewport: { height: 500, offsetTop: 0 },
- },
- writable: true,
- configurable: true,
- });
- const { handler } = createKeyboardScrollController(() => target, false);
-
- handler();
- vi.advanceTimersByTime(150);
-
- expect(container.style.transform).toBe("");
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("debounces rapid resize events", () => {
- const container = createMockContainer();
- const { target } = createMockTarget(container);
- Object.defineProperty(globalThis, "window", {
- value: {
- innerHeight: 800,
- visualViewport: { height: 500, offsetTop: 0 },
- },
- writable: true,
- configurable: true,
- });
- const { handler } = createKeyboardScrollController(() => target, true);
-
- handler();
- vi.advanceTimersByTime(50);
- handler();
- vi.advanceTimersByTime(50);
- handler();
- vi.advanceTimersByTime(150);
-
- expect(container.style.transform).toBe("translateY(-300px)");
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("cleanup clears pending timeout and resets transform", () => {
- const container = createMockContainer();
- container.style.transform = "translateY(-300px)";
- const { target } = createMockTarget(container);
- Object.defineProperty(globalThis, "window", {
- value: {
- innerHeight: 800,
- visualViewport: { height: 500, offsetTop: 0 },
- },
- writable: true,
- configurable: true,
- });
- const { handler, cleanup } = createKeyboardScrollController(
- () => target,
- true,
- );
-
- handler();
- vi.advanceTimersByTime(50);
- cleanup();
- vi.advanceTimersByTime(150);
-
- expect(container.style.transform).toBe("");
- expect(container.removeAttribute).toHaveBeenCalledWith("data-keyboard-active");
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("allows multiple firings across separate debounce windows", () => {
- const container = createMockContainer();
- const { target } = createMockTarget(container);
- let viewportHeight = 500;
- Object.defineProperty(globalThis, "window", {
- value: {
- innerHeight: 800,
- get visualViewport() {
- return { height: viewportHeight, offsetTop: 0 };
- },
- },
- writable: true,
- configurable: true,
- });
- const { handler } = createKeyboardScrollController(() => target, true);
-
- handler();
- vi.advanceTimersByTime(150);
- expect(container.style.transform).toBe("translateY(-300px)");
-
- viewportHeight = 600;
- handler();
- vi.advanceTimersByTime(150);
- expect(container.style.transform).toBe("translateY(-200px)");
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("no-ops gracefully when target is null", () => {
- const { handler } = createKeyboardScrollController(() => null, true);
- handler();
- vi.advanceTimersByTime(300);
- });
-
- it("falls back to scrollIntoView when no container found", () => {
- const { target, scrollIntoView } = createMockTarget(null);
- Object.defineProperty(globalThis, "window", {
- value: {
- innerHeight: 800,
- visualViewport: { height: 500, offsetTop: 0 },
- },
- writable: true,
- configurable: true,
- });
- const { handler } = createKeyboardScrollController(() => target, true);
-
- handler();
- vi.advanceTimersByTime(150);
-
- expect(scrollIntoView).toHaveBeenCalledWith({
- block: "end",
- behavior: "smooth",
- });
-
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-});
-
-describe("attachKeyboardScroll", () => {
- let listeners: Map<string, EventListener>;
- let mockVisualViewport: {
- addEventListener: ReturnType<typeof vi.fn>;
- removeEventListener: ReturnType<typeof vi.fn>;
- height: number;
- offsetTop: number;
- };
-
- beforeEach(() => {
- vi.useFakeTimers();
- listeners = new Map();
- mockVisualViewport = {
- addEventListener: vi.fn((event: string, handler: EventListener) => {
- listeners.set(event, handler);
- }),
- removeEventListener: vi.fn((event: string) => {
- listeners.delete(event);
- }),
- height: 500,
- offsetTop: 0,
- };
- Object.defineProperty(globalThis, "window", {
- value: { visualViewport: mockVisualViewport, innerHeight: 800 },
- writable: true,
- configurable: true,
- });
- });
-
- afterEach(() => {
- vi.useRealTimers();
- Object.defineProperty(globalThis, "window", {
- value: undefined,
- writable: true,
- configurable: true,
- });
- });
-
- it("registers resize and scroll listeners and returns a detach function", () => {
- const { target } = createMockTarget(createMockContainer());
- const detach = attachKeyboardScroll(() => target, true);
-
- expect(detach).toBeTypeOf("function");
- expect(mockVisualViewport.addEventListener).toHaveBeenCalledWith(
- "resize",
- expect.any(Function),
- );
- expect(mockVisualViewport.addEventListener).toHaveBeenCalledWith(
- "scroll",
- expect.any(Function),
- );
- });
-
- it("detach removes listeners and resets transform", () => {
- const container = createMockContainer();
- const { target } = createMockTarget(container);
- const detach = attachKeyboardScroll(() => target, true)!;
-
- const handler = listeners.get("resize")!;
- handler(new Event("resize"));
- vi.advanceTimersByTime(150);
- expect(container.style.transform).toBe("translateY(-300px)");
- expect(container.setAttribute).toHaveBeenCalledWith("data-keyboard-active", "");
-
- detach();
-
- expect(mockVisualViewport.removeEventListener).toHaveBeenCalledWith(
- "resize",
- expect.any(Function),
- );
- expect(container.style.transform).toBe("");
- expect(container.removeAttribute).toHaveBeenCalledWith("data-keyboard-active");
- });
-
- it("applies transform on resize when focused", () => {
- const container = createMockContainer();
- const { target } = createMockTarget(container);
- attachKeyboardScroll(() => target, true);
-
- const handler = listeners.get("resize")!;
- handler(new Event("resize"));
- vi.advanceTimersByTime(300);
-
- expect(container.style.transform).toBe("translateY(-300px)");
- expect(container.setAttribute).toHaveBeenCalledWith("data-keyboard-active", "");
- });
-
- it("does not fire when not focused", () => {
- const container = createMockContainer();
- const { target } = createMockTarget(container);
- attachKeyboardScroll(() => target, false);
-
- const handler = listeners.get("resize")!;
- handler(new Event("resize"));
- vi.advanceTimersByTime(300);
-
- expect(container.style.transform).toBe("");
- });
-
- it("returns null when visualViewport is unavailable", () => {
- Object.defineProperty(globalThis, "window", {
- value: { visualViewport: undefined },
- writable: true,
- configurable: true,
- });
- const detach = attachKeyboardScroll(() => null, true);
- expect(detach).toBeNull();
- });
-});
diff --git a/src/web/src/hooks/sign-out.dom.test.ts b/src/web/src/hooks/sign-out.dom.test.ts
index 45c839d83..cbe35e171 100644
--- a/src/web/src/hooks/sign-out.dom.test.ts
+++ b/src/web/src/hooks/sign-out.dom.test.ts
@@ -1,13 +1,10 @@
import { createElement, type PropsWithChildren } from "react"
-import { QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { ApplicationOwnerProvider, createApplicationOwner, retireApplicationOwner } from "@/lib/application-owner"
import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
import { useAccountSignOut } from "./community/use-account-sign-out"
-import { useApplicationSignOut } from "./use-application-sign-out"
const sdk = vi.hoisted(() => vi.fn())
vi.mock("@/lib/auth-client", () => ({ signOutWithOrigin: sdk }))
@@ -19,18 +16,15 @@ function deferred() {
return { promise, resolve }
}
async function setup(domain: "community" | "application", disk = Promise.resolve()) {
- const community = await createCommunityQueryOwner(), application = createApplicationOwner("viewer", community.client)
+ const community = await createCommunityQueryOwner()
let viewer: string | null = "viewer"
community.registry.bindAuthentication(() => viewer, () => disk)
- application.bindAuthentication(() => viewer, () => disk)
- const wrapper = ({ children }: PropsWithChildren) => domain === "community"
- ? createElement(CommunityTestProvider, { client: community.client, registry: community.registry, retainOwner: true }, children)
- : createElement(QueryClientProvider, { client: application.queryClient }, createElement(ApplicationOwnerProvider, { owner: application }, children))
- const useCommand = domain === "community" ? useAccountSignOut : useApplicationSignOut
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: community.client, registry: community.registry, retainOwner: true }, children)
+ const useCommand = useAccountSignOut
const view = renderHook(() => useCommand(), { wrapper })
- return { view, changeViewer: () => { viewer = "replacement" }, retire: () => domain === "community" ? retireCommunityAccount(community.registry) : retireApplicationOwner(application), retired: () => domain === "community" ? !community.runtime.lifecycle.get().active : !application.lifecycle.get().active }
+ return { view, changeViewer: () => { viewer = "replacement" }, retire: () => retireCommunityAccount(community.registry), retired: () => !community.runtime.lifecycle.get().active }
}
-describe.each(["community", "application"] as const)("Native %s sign-out facade", (domain) => {
+describe.each(["community"] as const)("Native %s sign-out facade", (domain) => {
it("keeps public methods stable and delivers void input after its authorized retirement", async () => {
const held = deferred(), owner = await setup(domain), onSuccess = vi.fn(), onSettled = vi.fn()
sdk.mockImplementation(async (assert: () => void) => { assert(); await held.promise; assert(); return {} })
diff --git a/src/web/src/hooks/use-agent-chat.dom.test.tsx b/src/web/src/hooks/use-agent-chat.dom.test.tsx
deleted file mode 100644
index d9b0324c6..000000000
--- a/src/web/src/hooks/use-agent-chat.dom.test.tsx
+++ /dev/null
@@ -1,573 +0,0 @@
-import { useLayoutEffect } from "react"
-import { publishWorkspaceChatEvent } from "@/lib/workspace-chat-events"
-import "fake-indexeddb/auto"
-import React from "react"
-import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
-import { act, render, screen, waitFor } from "@/test/react-dom-harness"
-import { persistQueryClientSave } from "@tanstack/react-query-persist-client"
-import { createApplicationOwner, ApplicationQueryProvider } from "@/lib/application-owner"
-import { createWorkspaceOwner, useWorkspaceOwner, WorkspaceProvider, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { createIdbPersister, clearAllPersistedCaches, PERSIST_BUSTER } from "@/lib/query-persister"
-import { shouldPersistApplicationQuery } from "@/lib/workspace-chat-persistence"
-import { mergeCachedMessages, setConvExtras, setLastOpenConversation, getCacheMeta, getLastOpenConversation, chatExtrasKey, chatMessagesKey, type ChatMessagesData, type ChatExtras } from "@/lib/chat-cache"
-import type { Conversation, Message, Artifact, TaskApi, WsMessage } from "@alook/shared"
-import { useAgentChat } from "./use-agent-chat"
-import { useChatData } from "./workspace/use-chat-data"
-const { useChatSheets: useRealChatSheets } = await vi.importActual<typeof import("./use-chat-sheets")>("./use-chat-sheets")
-let sharedSheet: ReturnType<typeof useRealChatSheets>
-function SharedIssueConsumer() { const owner = useWorkspaceOwner(); const chat = useChatData(owner, "shared-issue", "A"); const current = useRealChatSheets(owner, chat.view); const openIssue = current.openIssue; React.useLayoutEffect(() => { sharedSheet = current }); React.useEffect(() => { void openIssue("issue") }, [openIssue]); return null }
-
-const mocks = vi.hoisted(() => ({ user: "chat-user", error: vi.fn() }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: mocks.user } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }), useParams: () => ({ id: "agent" }), useSearchParams: () => new URLSearchParams() }))
-vi.mock("sonner", () => ({ toast: { error: mocks.error } }))
-vi.mock("@/lib/analytics", () => ({ trackAgentChatOpened: vi.fn(), trackMessageSent: vi.fn() }))
-
-vi.mock("@/contexts/agent-context", () => ({ useAgentContext: () => ({ agents: [], runtimes: [], agentLinks: [], activeTaskCounts: {}, subscribeWs, subscribeReconnect }) }))
-vi.mock("@/contexts/inbox-count-context", () => ({ useInboxCount: () => ({ refresh: vi.fn() }) }))
-vi.mock("@/contexts/channel-context", () => ({ useChannel: () => ({ activeChannel: "general", loading: false, setAgentId: vi.fn() }) }))
-vi.mock("@/contexts/agent-chat-sheet-context", () => ({ useAgentChatSheet: () => ({ openAgentChat: vi.fn() }) }))
-vi.mock("@/hooks/use-message-flags", () => ({ useMessageFlags: () => ({ flaggedIds: new Set(), setFlaggedIds: vi.fn(), handleToggleFlag: vi.fn() }) }))
-vi.mock("@/hooks/use-chat-sheets", () => ({ useChatSheets: () => ({ artifactSheetOpen: false, setArtifactSheetOpen: vi.fn(), selectedArtifact: null, setSelectedArtifact: vi.fn(), emailSheetOpen: false, setEmailSheetOpen: vi.fn(), selectedEmailId: null, setSelectedEmailId: vi.fn(), calendarEventSheetOpen: false, setCalendarEventSheetOpen: vi.fn(), selectedCalendarEventId: null, setSelectedCalendarEventId: vi.fn(), issueSheetOpen: false, setIssueSheetOpen: vi.fn(), selectedIssueId: null, setSelectedIssueId: vi.fn(), issueDetail: null, setIssueDetail: vi.fn(), issueDetailLoading: false, issueTraceTasks: [], issueActiveTask: null, setIssueActiveTask: vi.fn(), openIssue: vi.fn(), issueConvId: null, issueTaskId: null }) }))
-vi.mock("@/hooks/use-file-attachments", () => ({ useFileAttachments: () => ({ pendingFiles: [], setPendingFiles: vi.fn(), fileInputRef: { current: null }, addPendingFiles: vi.fn(), handleFileSelect: vi.fn(), removePendingFile: vi.fn(), dragging: false, handleDragEnter: vi.fn(), handleDragLeave: vi.fn(), handleDragOver: vi.fn(), handleDrop: vi.fn() }) }))
-vi.mock("@/hooks/use-slash-command", () => ({ useSlashCommand: () => ({ activeSkill: null, clearActiveSkill: vi.fn(), setActiveSkill: vi.fn(), isOpen: false, handleSlashKeyDown: vi.fn(), skills: [] }) }))
-vi.mock("@/components/agent-chat/chat-composer", () => ({ ChatComposer: React.forwardRef(function ChatComposer() { return <div data-testid="composer" /> }), RotatingPlaceholderOverlay: () => null }))
-vi.mock("@/components/agent-chat/slash-command-popup", () => ({ SlashCommandPopup: () => null }))
-vi.mock("@/components/agent-chat/artifact-sheet", () => ({ ArtifactSheet: () => null, formatSize: () => "123" }))
-vi.mock("@/components/agent-chat/email-event-sheet", () => ({ EmailEventSheet: () => null }))
-vi.mock("@/components/agent-chat/image-lightbox", () => ({ ImageLightbox: () => null }))
-vi.mock("@/components/calendar/calendar-event-sheet", () => ({ CalendarEventSheet: () => null }))
-vi.mock("@/components/issues/issue-sheet", () => ({ IssueSheet: () => null }))
-vi.mock("@/components/agent-chat/message-list", () => ({
- AgentRow: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- MessageItem: ({ msg, isThreadRoot, onReplyInThread, conversationType }: { msg: Message; isThreadRoot?: boolean; onReplyInThread?: (id: string) => void; conversationType?: string }) => <div data-testid={`view-${msg.id}`} data-thread-root={String(!!isThreadRoot)} data-conversation-type={conversationType}>{msg.content}{onReplyInThread && <button onClick={() => onReplyInThread(msg.id)}>Reply in thread</button>}</div>,
-}))
-import { AgentChatView } from "@/components/agent-chat/agent-chat-view"
-
-const external = { setFlaggedIds: vi.fn(), setPendingFiles: vi.fn(), setInput: vi.fn(), setQuotedMessage: vi.fn(), setActiveSkill: vi.fn(), clearActiveSkill: vi.fn(), inputRef: { current: "" }, quotedMessageRef: { current: null }, pendingFilesRef: { current: [] }, activeSkillRef: { current: null }, draftMetaRestoredRef: { current: false }, readInput: () => external.inputRef.current, readQuotedMessage: () => external.quotedMessageRef.current, readPendingFiles: () => external.pendingFilesRef.current, readActiveSkill: () => external.activeSkillRef.current, markDraftRestored: () => { external.draftMetaRestoredRef.current = true } }
-let latest: ReturnType<typeof useAgentChat>
-let liveOwner: WorkspaceOwner
-let held: Array<{ path: string; body?: BodyInit | null; method?: string; resolve: (response: Response) => void; signal?: AbortSignal }>
-const subscriptions = new Set<(message: never) => void>()
-const subscribeWs = (callback: (message: never) => void) => { subscriptions.add(callback); return () => { subscriptions.delete(callback) } }
-const subscribeReconnect = () => () => {}
-function conversation(id = "A", extra: Partial<Conversation> = {}): Conversation { return { id, agent_id: "agent", title: id, type: "email_event", channel: "general", created_at: "2026-10-01T12:00:00Z", ...extra } }
-function message(id = "mA", conv = "A", extra: Partial<Message> = {}): Message { return { id, conversation_id: conv, role: "event", content: `Message ${id}`, task_id: null, attachment_ids: null, created_at: "2026-10-01T12:00:01Z", ...extra } }
-const artifact: Artifact = { id: "fileA", conversation_id: "A", agent_id: "agent", filename: "report.pdf", content_type: "application/pdf", size: 123, source: "agent", has_thumbnail: false, created_at: "2026-10-01T12:00:02Z" }
-function task(status = "queued"): TaskApi { return { id: "task-A", agent_id: "agent", runtime_id: "runtime", conversation_id: "A", workspace_id: "workspace", prompt: "Hello", status, priority: 0, dispatched_at: null, started_at: null, completed_at: null, result: null, error: null, created_at: "2026-10-01T12:00:00Z", type: "chat" } }
-function ws(message: WsMessage) { publishWorkspaceChatEvent(liveOwner, message); for (const callback of subscriptions) callback(message as never) }
-async function openWithTask() {
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("A", { active_task: task() }))))
- await waitFor(() => expect(latest.activeTask?.id).toBe("task-A"))
- return mounted
-}
-async function terminalPoll() {
- await waitFor(() => expect(held.some((request) => request.path.startsWith("/api/tasks/task-A?"))).toBe(true), { timeout: 5000 })
- const poll = held.find((request) => request.path.startsWith("/api/tasks/task-A?"))!
- await act(async () => poll.resolve(reply(task("completed"))))
- await waitFor(() => expect(held.some((request) => request.path.includes("/A/messages"))).toBe(true))
- await waitFor(() => expect(held.some((request) => request.path.startsWith("/api/artifacts"))).toBe(true))
- return { messages: held.find((request) => request.path.includes("/A/messages"))!, artifacts: held.find((request) => request.path.startsWith("/api/artifacts"))! }
-}
-function reply(data: unknown, status = 200) { return new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } }) }
-function init(id = "A", extra = {}) { return { conversation: conversation(id), messages: [message(`m${id}`, id)], artifacts: id === "A" ? [artifact] : [], active_task: null, task_messages: [], has_more_messages: false, has_more_conversations: false, has_more_artifacts: false, flagged_message_ids: [], cache_valid: false, message_count: 1, ...extra } }
-function Probe({ target = "A", channel = "general", scrollTask = null }: { target?: string | null; channel?: string; scrollTask?: string | null }) {
- const currentOwner = useWorkspaceOwner(); React.useLayoutEffect(() => { liveOwner = currentOwner })
- const current = useAgentChat({ agentId: "agent", targetConvId: target, scrollToTaskId: scrollTask, scrollToMessageId: null, workspaceId: "workspace", agents: [], activeChannel: channel, readActiveChannel: () => channel, channelLoading: false, subscribeWs, subscribeReconnect, refreshInboxCount: vi.fn() }, external)
- React.useLayoutEffect(() => { latest = current })
- return <><div data-testid="messages">{current.messages.map((row) => row.content).join("|")}</div><div data-testid="cards">{current.artifacts.map((row) => row.filename).join("|")}</div><div data-testid="type">{current.conversation?.type}</div><div data-testid="thread">{current.conversation?.parent_message_id}:{current.conversation?.thread_title}:{current.conversation?.message_count}</div><div data-testid="naps">{current.napMarkers.map((row) => row.id).join("|")}</div><div data-testid="loading">{String(current.messagesLoading)}</div></>
-}
-function sendAndSettle(): Promise<void> {
- latest.handleSend()
- return waitFor(() => expect(liveOwner.queryClient.isMutating({ mutationKey: liveOwner.key("chat", "send") })).toBe(0))
-}
-let strictSendStarted = false
-function StrictSendProbe(props: { target?: string | null; channel?: string }) {
- const child = Probe(props)
- const started = React.useRef(false)
- React.useEffect(() => { if (!started.current) { started.current = true; external.inputRef.current = "Strict send"; latest.handleSend(); strictSendStarted = true } }, [])
- return child
-}
-function App(props: { target?: string | null; channel?: string; strictSend?: boolean; hidden?: boolean; scrollTask?: string | null; sharedIssue?: boolean }) { return <ApplicationQueryProvider userId={mocks.user}><WorkspaceProvider workspaceId="workspace" slug="workspace"><React.Activity mode={props.hidden ? "hidden" : "visible"}>{props.strictSend ? <React.StrictMode><StrictSendProbe {...props} /></React.StrictMode> : <Probe {...props} />}</React.Activity>{props.sharedIssue && <SharedIssueConsumer />}</WorkspaceProvider></ApplicationQueryProvider> }
-async function seed(extraConversation: Partial<Conversation> = {}) {
- const owner = createWorkspaceOwner(createApplicationOwner(mocks.user), "workspace", "workspace")
- await mergeCachedMessages("A", [message()], false, owner, 1)
- owner.queryClient.setQueryData<ChatExtras>(chatExtrasKey(owner, "A"), { conversation: conversation("A", extraConversation), artifacts: [artifact], hasMoreArtifacts: false })
- await setLastOpenConversation("agent", "general", { conversation_id: "A", newestMessageId: "mA", serverMessageCount: 1 }, owner)
- const persister = createIdbPersister(mocks.user, "application")
- await persistQueryClientSave({ queryClient: owner.queryClient, persister, buster: `${PERSIST_BUSTER}-application`, dehydrateOptions: { shouldDehydrateQuery: (query) => shouldPersistApplicationQuery(query.queryKey) } })
- owner.queryClient.clear()
-}
-beforeEach(async () => {
- await clearAllPersistedCaches()
- external.inputRef.current = ""; external.pendingFilesRef.current = [];
- mocks.user = "chat-user"; mocks.error.mockClear(); held = []; subscriptions.clear()
- vi.stubGlobal("fetch", vi.fn((path: string, options: RequestInit) => {
- if (path.includes("/skills")) return Promise.resolve(reply({ skills: [] }))
- if (path.includes("/threads")) return Promise.resolve(reply({ thread_summaries: [] }))
- if (path.includes("/api/inbox/")) return Promise.resolve(reply(null))
- return new Promise<Response>((resolve) => held.push({ path, body: options.body, method: options.method, resolve, signal: options.signal ?? undefined }))
- }))
- vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} })
- HTMLElement.prototype.scrollTo = vi.fn()
- HTMLElement.prototype.scrollIntoView = vi.fn()
-})
-afterEach(async () => {
- await act(async () => {
- vi.unstubAllGlobals(); liveOwner?.queryClient.clear()
- })
-})
-
-describe("real chat hook canonical facts and qualified native restore", () => {
- it("restores messages and cards/type while background init remains held", async () => {
- await seed()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- expect(screen.getByTestId("messages").textContent).toBe("Message mA")
- expect(screen.getByTestId("cards").textContent).toBe("report.pdf")
- expect(screen.getByTestId("type").textContent).toBe("email_event")
- expect(screen.getByTestId("loading").textContent).toBe("false")
- await act(async () => held[0].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(liveOwner.queryClient.getQueryCache().findAll({ queryKey: liveOwner.key("chat", "open") }).every((query) => query.state.fetchStatus === "idle")).toBe(true))
- expect(latest.messages).toHaveLength(1)
- act(() => mounted.unmount())
- })
-
- it.each(["A", null])("preserves complete thread fields target=%s after the canonical extras write", async (target) => {
- await seed({ parent_message_id: "root", thread_title: "Thread title", message_count: 4 })
- const mounted = render(<App target={target} />)
- await waitFor(() => expect(held).toHaveLength(1))
- expect(screen.getByTestId("thread").textContent).toBe("root:Thread title:4")
- let initIndex = 0
- if (target === null) {
- await act(async () => held[0].resolve(reply({ conversation_id: "A", newest_message_id: "mA", message_count: 1 })))
- await waitFor(() => expect(held).toHaveLength(2))
- initIndex = 1
- }
- await act(async () => held[initIndex].resolve(reply(init("A", { conversation: conversation("A", { parent_message_id: "root", thread_title: "Thread title", message_count: 4 }) }))))
- await waitFor(() => expect(liveOwner.queryClient.getQueryCache().findAll({ queryKey: liveOwner.key("chat", "open") }).every((query) => query.state.fetchStatus === "idle")).toBe(true))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- expect(screen.getByTestId("thread").textContent).toBe("root:Thread title:4")
- act(() => mounted.unmount())
- })
-
- it("keeps messages and timeline references stable for UI-only repaint, then updates actual message content", async () => {
- await seed()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- const messages = latest.messages, timeline = latest.timeline
- act(() => mounted.rerender(<App />))
- expect(latest.messages).toBe(messages)
- expect(latest.timeline).toBe(timeline)
- await act(async () => { await mergeCachedMessages("A", [message("mA", "A", { content: "Changed" })], null, liveOwner) })
- await waitFor(() => expect(screen.getByTestId("messages").textContent).toBe("Changed"))
- expect(latest.messages).not.toBe(messages)
- expect(latest.timeline).not.toBe(timeline)
- act(() => mounted.unmount())
- })
-
- it.each([false, true])("known conv channel replay while completed=%s stays populated and recovers cancelled work", async (completed) => {
- await seed()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- if (completed) {
- await act(async () => held[0].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(liveOwner.queryClient.getQueryCache().findAll({ queryKey: liveOwner.key("chat", "open") }).every((query) => query.state.fetchStatus === "idle")).toBe(true))
- }
- act(() => mounted.rerender(<App channel="other" />))
- if (completed) expect(held).toHaveLength(1)
- else {
- await waitFor(() => expect(held).toHaveLength(2))
- expect(held[0].signal?.aborted).toBe(true)
- await act(async () => held[1].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- }
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- expect(screen.getByTestId("messages").textContent).toBe("Message mA")
- act(() => mounted.unmount())
- })
-
- it("old explicit conv leaves latest-created pointer intact before reopening default", async () => {
- await seed()
- const mounted = render(<App target="OLD" />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("OLD"))))
- await waitFor(() => expect(latest.conversation?.id).toBe("OLD"))
- expect((await getLastOpenConversation("agent", "general", liveOwner))?.conversation_id).toBe("A")
- act(() => mounted.rerender(<App target={null} />))
- await waitFor(() => expect(held.some((request) => request.path.includes("check-fresh"))).toBe(true))
- expect(screen.getByTestId("messages").textContent).toBe("Message mA")
- expect(screen.getByTestId("cards").textContent).toBe("report.pdf")
- const fresh = held.find((request) => request.path.includes("check-fresh"))!
- await act(async () => fresh.resolve(reply({ conversation_id: "A", newest_message_id: "mA", message_count: 1 })))
- await waitFor(() => expect(held.filter((request) => request.path.includes("/A/init"))).toHaveLength(1))
- act(() => mounted.unmount())
- })
-
- it("cross-conversation frontier B keeps A complete, and single-conv entry does not fetch B", async () => {
- const mounted = render(<App target={null} />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply({ conversation_id: "A", newest_message_id: "mA", message_count: 12 })))
- await waitFor(() => expect(held).toHaveLength(2))
- await act(async () => held[1].resolve(reply(init("A", { messages: Array.from({ length: 12 }, (_, i) => message(`a${i}`)), has_more_conversations: true }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- let loading!: Promise<void>
- act(() => { loading = latest.loadOlderMessages() })
- await waitFor(() => expect(held).toHaveLength(3))
- await act(async () => held[2].resolve(reply({ conversations: [{ id: "B", created_at: "2026-09-01T00:00:00Z" }], has_more: false })))
- await waitFor(() => expect(held).toHaveLength(4))
- await act(async () => { held[3].resolve(reply({ messages: [message("b1", "B", { created_at: "2026-09-01T00:00:00Z" })], has_more: true })); await loading })
- expect((await getCacheMeta("A", liveOwner))?.hasMore).toBe(false)
- expect((await getCacheMeta("B", liveOwner))?.hasMore).toBe(true)
- expect(latest.messages.map((row) => row.conversation_id)).toContain("B")
- expect(screen.getByTestId("naps").textContent).toContain("nap-B")
- act(() => mounted.rerender(<App target="A" />))
- await waitFor(() => expect(held).toHaveLength(5))
- await act(async () => held[4].resolve(reply(init("A", { cache_valid: true, messages: null, has_more_conversations: true }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- expect(latest.messages.every((row) => row.conversation_id === "A")).toBe(true)
- const count = held.length
- await act(async () => latest.loadOlderMessages())
- expect(held).toHaveLength(count)
- act(() => mounted.unmount())
- })
- it("held pagination owns its lock across repeated calls and consumes one previous cursor", async () => {
- const mounted = render(<App target={null} />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply({ conversation_id: "A", newest_message_id: "a11", message_count: 12 })))
- await waitFor(() => expect(held).toHaveLength(2))
- await act(async () => held[1].resolve(reply(init("A", { messages: Array.from({ length: 12 }, (_, i) => message(`a${i}`)), has_more_conversations: true }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- let first!: Promise<void>, third!: Promise<void>
- act(() => { first = latest.loadOlderMessages() })
- await waitFor(() => expect(held).toHaveLength(3))
- await act(async () => latest.loadOlderMessages())
- act(() => { third = latest.loadOlderMessages() })
- await act(async () => held[2].resolve(reply({ conversations: [{ id: "B", created_at: "2026-09-01T00:00:00Z" }, { id: "C", created_at: "2026-08-01T00:00:00Z" }], has_more: false })))
- await waitFor(() => expect(held).toHaveLength(4))
- await act(async () => { held[3].resolve(reply({ messages: Array.from({ length: 20 }, (_, i) => message(`b${i}`, "B", { created_at: "2026-09-01T00:00:00Z" })), has_more: false })); await Promise.all([first, third]) })
- expect(latest.previousConversations.map((row) => row.id)).toEqual(["C"])
- expect(latest.messages).toHaveLength(32)
- expect(latest.napMarkers.map((row) => row.id)).toEqual(["nap-B"])
- expect(held.filter((request) => request.path.includes("/B/messages"))).toHaveLength(1)
- expect(held.some((request) => request.path.includes("/C/messages"))).toBe(false)
- expect(latest.loadingMore).toBe(false)
- act(() => mounted.unmount())
- })
-
- it("native paging retains a WS message, page cursors and history through a two-page refetch with another WS between pages", async () => {
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("A", { artifacts: [], has_more_messages: true }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- let loading!: Promise<void>
- act(() => { loading = latest.loadOlderMessages() })
- await waitFor(() => expect(held).toHaveLength(2))
- const live = message("live-1", "A", { created_at: "2026-10-01T12:01:00Z" })
- act(() => ws({ type: "conversation.message", conversationId: "A", message: live }))
- const older = message("older", "A", { created_at: "2026-10-01T11:00:00Z" })
- await act(async () => { held[1].resolve(reply({ messages: [older], has_more: false })); await loading })
- const key = chatMessagesKey(liveOwner, "A")
- expect(liveOwner.queryClient.getQueryData<ChatMessagesData>(key)?.pages).toHaveLength(2)
- expect(liveOwner.queryClient.getQueryData<ChatMessagesData>(key)?.pageParams).toHaveLength(2)
- expect(latest.messages.map((row) => row.id)).toEqual(["older", "mA", "live-1"])
- act(() => ws({ type: "task.created", conversationId: "A", task: task() }))
- await waitFor(() => expect(held).toHaveLength(3))
- await act(async () => held[2].resolve(reply({ messages: [message(), live], has_more: true })))
- await waitFor(() => expect(held).toHaveLength(4))
- const between = message("live-between", "A", { created_at: "2026-10-01T12:02:00Z" })
- act(() => ws({ type: "conversation.message", conversationId: "A", message: between }))
- await act(async () => held[3].resolve(reply({ messages: [older], has_more: false })))
- await waitFor(() => expect(liveOwner.queryClient.getQueryState(key)?.fetchStatus).toBe("idle"))
- expect(latest.messages.map((row) => row.id)).toEqual(["older", "mA", "live-1", "live-between"])
- const data = liveOwner.queryClient.getQueryData<ChatMessagesData>(key)!
- expect(data.pages).toHaveLength(2)
- expect(data.pageParams).toHaveLength(2)
- expect(data.pages.at(-1)?.hasMore).toBe(false)
- act(() => mounted.unmount())
- })
-
- it("a terminal poll with messages complete and artifacts held cannot publish or continue after target retirement", async () => {
- const mounted = await openWithTask()
- const requests = await terminalPoll()
- await act(async () => requests.messages.resolve(reply({ messages: [message("completed-message")], has_more: false })))
- await waitFor(() => expect(liveOwner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(liveOwner, "A"))?.pages.flatMap((page) => page.messages).some((row) => row.id === "completed-message")).toBe(true))
- act(() => mounted.rerender(<App target="B" />))
- await waitFor(() => expect(held.some((request) => request.path.includes("/B/init"))).toBe(true))
- const next = held.find((request) => request.path.includes("/B/init"))!
- await act(async () => next.resolve(reply(init("B"))))
- await waitFor(() => expect(latest.conversation?.id).toBe("B"))
- const count = held.length
- await act(async () => requests.artifacts.resolve(reply([artifact])))
- await waitFor(() => expect(liveOwner.queryClient.getQueryState(chatExtrasKey(liveOwner, "A"))?.fetchStatus).toBe("idle"))
- expect(latest.activeTask).toBeNull()
- expect(latest.artifacts).toEqual([])
- expect(mocks.error).not.toHaveBeenCalled()
- expect(held).toHaveLength(count)
- act(() => mounted.unmount())
- })
-
- it("current terminal message failure retains completed task and the ordinary refresh error", async () => {
- const mounted = await openWithTask()
- const requests = await terminalPoll()
- await act(async () => requests.artifacts.resolve(reply([artifact])))
- await act(async () => requests.messages.resolve(reply({ error: "failed" }, 500)))
- await waitFor(() => expect(mocks.error).toHaveBeenCalledWith("Failed to refresh messages"))
- expect(latest.activeTask?.status).toBe("completed")
- expect(latest.artifacts).toEqual([artifact])
- expect(held.filter((request) => request.path.startsWith("/api/tasks/task-A?"))).toHaveLength(1)
- act(() => mounted.unmount())
- })
-
- it("drops malformed restored messages/cards and heals through current online init", async () => {
- const owner = createWorkspaceOwner(createApplicationOwner(mocks.user), "workspace", "workspace")
- await mergeCachedMessages("A", [message()], false, owner, 1)
- owner.queryClient.setQueryData<ChatMessagesData>(chatMessagesKey(owner, "A"), (data) => ({ ...data!, pages: [{ messages: [{ ...message(), attachment_ids: [123] as never }], hasMore: false }] }))
- owner.queryClient.setQueryData(chatExtrasKey(owner, "A"), { conversation: conversation(), artifacts: [{ id: "broken", conversation_id: "A", filename: "bad.pdf", content_type: "application/pdf" }], hasMoreArtifacts: false })
- await persistQueryClientSave({ queryClient: owner.queryClient, persister: createIdbPersister(mocks.user, "application"), buster: `${PERSIST_BUSTER}-application`, dehydrateOptions: { shouldDehydrateQuery: (query) => shouldPersistApplicationQuery(query.queryKey) } })
- owner.queryClient.clear()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- expect(latest.messages).toEqual([])
- expect(latest.artifacts).toEqual([])
- expect(held[0].path).not.toContain("newest_message_id")
- await act(async () => held[0].resolve(reply(init())))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- expect(latest.messages.map((row) => row.id)).toEqual(["mA"])
- expect(latest.artifacts).toEqual([artifact])
- act(() => mounted.unmount())
- })
-
- it("warm B keeps forty canonical rows but A's five-message remainder selects only five and retains local older availability", async () => {
- const mounted = render(<App target={null} />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply({ conversation_id: "A", newest_message_id: "a11", message_count: 12 })))
- await waitFor(() => expect(held).toHaveLength(2))
- const aRows = Array.from({ length: 12 }, (_, i) => message(`a${i}`))
- await act(async () => held[1].resolve(reply(init("A", { messages: aRows, has_more_messages: true, has_more_conversations: true }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- const bRows = Array.from({ length: 40 }, (_, i) => message(`b${i}`, "B", { created_at: new Date(Date.UTC(2026, 8, 1, 0, i)).toISOString() }))
- const bKey = chatMessagesKey(liveOwner, "B")
- act(() => liveOwner.queryClient.setQueryData<ChatMessagesData>(bKey, { pages: [{ messages: bRows.slice(20), hasMore: true }, { messages: bRows.slice(0, 20), hasMore: false }], pageParams: [null, { limit: 20, before: bRows[20].created_at, beforeId: bRows[20].id }], serverMessageCount: 40 }))
- let loading!: Promise<void>
- act(() => { loading = latest.loadOlderMessages() })
- await waitFor(() => expect(held).toHaveLength(3))
- const olderA = Array.from({ length: 15 }, (_, i) => message(`old-a${i}`, "A", { created_at: new Date(Date.UTC(2026, 9, 1, 11, i)).toISOString() }))
- await act(async () => held[2].resolve(reply({ messages: olderA, has_more: false })))
- await waitFor(() => expect(held).toHaveLength(4))
- await act(async () => held[3].resolve(reply({ conversations: [{ id: "B", created_at: "2026-09-01T00:00:00Z" }], has_more: false })))
- await waitFor(() => expect(held).toHaveLength(5))
- await act(async () => held[4].resolve(reply({ messages: bRows.slice(20), has_more: true })))
- await waitFor(() => expect(held).toHaveLength(6))
- await act(async () => { held[5].resolve(reply({ messages: bRows.slice(0, 20), has_more: false })); await loading })
- expect(latest.messages.filter((row) => row.conversation_id === "B").map((row) => row.id)).toEqual(["b35", "b36", "b37", "b38", "b39"])
- expect(liveOwner.queryClient.getQueryData<ChatMessagesData>(bKey)?.pages.flatMap((page) => page.messages)).toHaveLength(40)
- expect((await getCacheMeta("B", liveOwner))?.hasMore).toBe(false)
- expect(latest.hasMore).toBe(true)
- const count = held.length
- await act(async () => latest.loadOlderMessages())
- expect(held).toHaveLength(count)
- expect(latest.messages.filter((row) => row.conversation_id === "B")).toHaveLength(25)
- expect((await getCacheMeta("B", liveOwner))?.hasMore).toBe(false)
- act(() => mounted.unmount())
- })
-
- it.each(["A", null])("actual AgentChatView target=%s hides Reply in thread while cache is warm and renders the qualified parent root", async (target) => {
- await seed({ parent_message_id: "root", thread_title: "Thread title", message_count: 4 })
- const mounted = render(<ApplicationQueryProvider userId={mocks.user}><WorkspaceProvider workspaceId="workspace" slug="workspace"><AgentChatView agentId="agent" targetConvId={target} /></WorkspaceProvider></ApplicationQueryProvider>)
- await waitFor(() => expect(screen.getByTestId("view-mA")).toBeTruthy())
- expect(screen.queryByRole("button", { name: "Reply in thread" })).toBeNull()
- expect(screen.getByTestId("view-mA").getAttribute("data-conversation-type")).toBe("email_event")
- if (target === null) {
- const fresh = held.find((request) => request.path.includes("check-fresh"))!
- await act(async () => fresh.resolve(reply({ conversation_id: "A", newest_message_id: "mA", message_count: 1 })))
- }
- await waitFor(() => expect(held.some((request) => request.path.includes("/A/init"))).toBe(true))
- const initRequest = held.find((request) => request.path.includes("/A/init"))!
- const root = message("root", "parent", { role: "user", content: "Parent root" })
- await act(async () => initRequest.resolve(reply(init("A", { conversation: conversation("A", { parent_message_id: "root", thread_title: "Thread title", message_count: 4 }), root_message: root }))))
- await waitFor(() => expect(screen.getByTestId("view-root").getAttribute("data-thread-root")).toBe("true"))
- expect(screen.getByTestId("view-root").textContent).toBe("Parent root")
- expect(screen.queryByRole("button", { name: "Reply in thread" })).toBeNull()
- expect(held.filter((request) => request.path.includes("/A/init"))).toHaveLength(1)
- act(() => mounted.unmount())
- })
-
- it.each([false, true])("actual Strict replay rejects the retired mutation before API dispatch; multipart=%s", async (multipart) => {
- strictSendStarted = false
- await seed()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- const assign = vi.fn(), actualWindow = window
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- if (multipart) external.pendingFilesRef.current = [{ file: new File(["file"], "file.txt"), thumbnailUrl: null, thumbnailBlob: null }] as never
- act(() => mounted.rerender(<App strictSend />))
- await waitFor(() => expect(strictSendStarted).toBe(true))
- await waitFor(() => expect(liveOwner.queryClient.isMutating({ mutationKey: liveOwner.key("chat", "send") })).toBe(0))
- expect(held.some((request) => request.path.includes("/A/messages") && request.method === "POST")).toBe(false)
- const currentInit = held.filter((request) => request.path.includes("/A/init")).at(-1)!
- await act(async () => currentInit.resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- expect(assign).not.toHaveBeenCalled()
- expect(mocks.error).not.toHaveBeenCalled()
- expect(latest.failedSends.size).toBe(0)
- expect(latest.sending).toBe(false)
- act(() => mounted.unmount())
- })
-
- it.each([false, true])("current send 401 clears its original account before the real sign-in transition; multipart=%s", async (multipart) => {
- await seed()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- const assign = vi.fn(), actualWindow = window
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- external.inputRef.current = "Current send"
- if (multipart) external.pendingFilesRef.current = [{ file: new File(["file"], "file.txt"), thumbnailUrl: null, thumbnailBlob: null }] as never
- let sent!: Promise<void>
- act(() => { sent = sendAndSettle() })
- await waitFor(() => expect(held).toHaveLength(2))
- expect(held[1].body instanceof FormData).toBe(multipart)
- await act(async () => { held[1].resolve(reply({}, 401)); await sent })
- await waitFor(() => expect(assign).toHaveBeenCalledTimes(1))
- expect(String(assign.mock.calls[0][0])).toBe("https://alook.test/sign-in")
- expect(liveOwner.application.lifecycle.get().active).toBe(false)
- expect(liveOwner.queryClient.getQueryCache().getAll()).toHaveLength(0)
- expect(screen.queryByTestId("messages")).toBeNull()
- act(() => mounted.unmount())
- })
-
- it("unselected scroll task native read cancels when its only actual chat view retires", async () => {
- const mounted = render(<App scrollTask="task-A" />);
- await waitFor(() => expect(held).toHaveLength(1)); await act(async () => held[0].resolve(reply(init())));
- await waitFor(() => expect(held.some((request) => request.path.startsWith("/api/tasks/task-A?"))).toBe(true));
- const read = held.find((request) => request.path.startsWith("/api/tasks/task-A?"))!;
- const assign = vi.fn(), real = window; vi.stubGlobal("window", new Proxy(real, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }));
- act(() => mounted.rerender(<App scrollTask="task-A" hidden />)); expect(read.signal?.aborted).toBe(true);
- await act(async () => read.resolve(reply({}, 401))); expect(assign).not.toHaveBeenCalled(); expect(mocks.error).not.toHaveBeenCalled(); expect(liveOwner.queryClient.getQueryData(liveOwner.key("chat", "task", "task-A"))).toBeUndefined();
- });
- it.each([false, true])("held command read shares with a real issue task consumer, releaseAll=%s", async (releaseAll) => {
- const mounted = render(<App scrollTask="task-A" />);
- await waitFor(() => expect(held).toHaveLength(1)); await act(async () => held[0].resolve(reply(init())));
- await waitFor(() => expect(held.some((request) => request.path.startsWith("/api/tasks/task-A?"))).toBe(true));
- const read = held.find((request) => request.path.startsWith("/api/tasks/task-A?"))!;
- act(() => mounted.rerender(<App scrollTask="task-A" sharedIssue />)); await waitFor(() => expect(held.some((request) => request.path.startsWith("/api/issues/issue?"))).toBe(true));
- const issueRead = held.find((request) => request.path.startsWith("/api/issues/issue?"))!;
- await act(async () => issueRead.resolve(reply({ issue: { id: "issue", latest_task_id: "task-A", conversation_id: "A", trace_id: null }, messages: [], comments: [], artifacts: [] })));
- await waitFor(() => expect(sharedSheet.issueDetail?.issue.id).toBe("issue"));
- const assign = vi.fn(), real = window; vi.stubGlobal("window", new Proxy(real, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }));
- act(() => mounted.rerender(<App scrollTask="task-A" hidden sharedIssue={!releaseAll} />)); expect(read.signal?.aborted).toBe(releaseAll);
- await act(async () => read.resolve(reply(releaseAll ? {} : task("completed"), releaseAll ? 401 : 200)));
- if (!releaseAll) await waitFor(() => expect(sharedSheet.issueActiveTask?.status).toBe("completed"));
- expect(held.filter((request) => request.path.startsWith("/api/tasks/task-A?"))).toHaveLength(1); expect(assign).not.toHaveBeenCalled(); expect(mocks.error).not.toHaveBeenCalled(); expect(held.some((request) => request.path.includes("/task-A/messages"))).toBe(false);
- });
-
- it.each([200, 500, 401])("old previous-page response %s cannot run its fallback after the next target is active", async (status) => {
- const mounted = render(<App target={null} />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply({ conversation_id: "A", newest_message_id: "a11", message_count: 12 })))
- await waitFor(() => expect(held).toHaveLength(2))
- await act(async () => held[1].resolve(reply(init("A", { messages: Array.from({ length: 12 }, (_, i) => message(`a${i}`)), has_more_conversations: true }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- let paging!: Promise<void>
- act(() => { paging = latest.loadOlderMessages() })
- await waitFor(() => expect(held).toHaveLength(3))
- const old = held[2]
- const assign = vi.fn(), actualWindow = window
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- act(() => mounted.rerender(<App target="B" />))
- await waitFor(() => expect(held).toHaveLength(4))
- await act(async () => held[3].resolve(reply(init("B", { has_more_conversations: true }))))
- await waitFor(() => expect(latest.conversation?.id).toBe("B"))
- await act(async () => { old.resolve(reply(status === 200 ? { conversations: [{ id: "OLD", created_at: "2026-09-01T00:00:00Z" }], has_more: false } : { error: "failed" }, status)); await paging })
- expect(assign).not.toHaveBeenCalled()
- expect(latest.hasMoreConversations).toBe(true)
- expect(latest.previousConversations).toEqual([])
- expect(latest.messages.every((row) => row.conversation_id === "B")).toBe(true)
- expect(mocks.error).not.toHaveBeenCalled()
- act(() => mounted.unmount())
- })
-
- it.each([false, true])("held send 401 cannot escape after Activity retires/reactivates the same view; multipart=%s", async (multipart) => {
- await seed()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- const assign = vi.fn(), actualWindow = window
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- external.inputRef.current = "Held send"
- if (multipart) external.pendingFilesRef.current = [{ file: new File(["file"], "file.txt"), thumbnailUrl: null, thumbnailBlob: null }] as never
- let sent!: Promise<void>
- act(() => { sent = sendAndSettle() })
- await waitFor(() => expect(held).toHaveLength(2))
- const originalView = latest.chatView, originalGeneration = originalView.get().generation
- act(() => mounted.rerender(<App hidden />))
- act(() => mounted.rerender(<App />))
- expect(latest.chatView).toBe(originalView)
- expect(latest.chatView.get().generation).toBeGreaterThan(originalGeneration)
- await waitFor(() => expect(held).toHaveLength(3))
- await act(async () => held[2].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- await act(async () => { held[1].resolve(reply({}, 401)); await sent })
- expect(assign).not.toHaveBeenCalled()
- expect(mocks.error).not.toHaveBeenCalled()
- expect(latest.failedSends.size).toBe(0)
- expect(latest.sending).toBe(false)
- act(() => mounted.unmount())
- })
-
- it.each([200, 401])("send succeeded but held artifact status=%s cannot publish or navigate after switching targets", async (status) => {
- await seed()
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("A", { cache_valid: true, messages: null }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- const assign = vi.fn(), actualWindow = window
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- external.inputRef.current = "Send with file"
- let sent!: Promise<void>
- act(() => { sent = sendAndSettle() })
- await waitFor(() => expect(held).toHaveLength(2))
- await act(async () => { held[1].resolve(reply({ message: message("sent", "A", { role: "user", attachment_ids: [artifact.id] }), task: task() })); await sent })
- await waitFor(() => expect(held.some((request) => request.path.startsWith("/api/artifacts"))).toBe(true))
- const old = held.find((request) => request.path.startsWith("/api/artifacts"))!
- act(() => mounted.rerender(<App target="B" />))
- await waitFor(() => expect(held.some((request) => request.path.includes("/B/init"))).toBe(true))
- const next = held.find((request) => request.path.includes("/B/init"))!
- await act(async () => next.resolve(reply(init("B"))))
- await waitFor(() => expect(latest.conversation?.id).toBe("B"))
- const count = held.length
- await act(async () => old.resolve(reply(status === 200 ? [artifact] : {}, status)))
- await waitFor(() => expect(liveOwner.queryClient.getQueryState(chatExtrasKey(liveOwner, "A"))?.fetchStatus).toBe("idle"))
- expect(latest.artifacts).toEqual([])
- expect(latest.activeTask).toBeNull()
- expect(assign).not.toHaveBeenCalled()
- expect(mocks.error).not.toHaveBeenCalled()
- expect(held).toHaveLength(count)
- act(() => mounted.unmount())
- })
-
- it("native cancellation of a current paging request is quiet and preserves the previous cursor", async () => {
- const mounted = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(reply(init("A", { has_more_messages: true }))))
- await waitFor(() => expect(latest.messagesLoading).toBe(false))
- let paging!: Promise<void>
- act(() => { paging = latest.loadOlderMessages() })
- await waitFor(() => expect(held).toHaveLength(2))
- await act(async () => { await liveOwner.queryClient.cancelQueries({ queryKey: chatMessagesKey(liveOwner, "A"), exact: true }); await paging })
- expect(held[1].signal?.aborted).toBe(true)
- expect(mocks.error).not.toHaveBeenCalled()
- expect(latest.hasMore).toBe(true)
- expect(latest.loadingMore).toBe(false)
- await act(async () => held[1].resolve(reply({ messages: [message("cancelled-page")], has_more: false })))
- expect(latest.messages.map((row) => row.id)).toEqual(["mA"])
- act(() => mounted.unmount())
- })
-
-})
diff --git a/src/web/src/hooks/use-agent-chat.ts b/src/web/src/hooks/use-agent-chat.ts
deleted file mode 100644
index 95eb65575..000000000
--- a/src/web/src/hooks/use-agent-chat.ts
+++ /dev/null
@@ -1,1721 +0,0 @@
-"use client";
-
-import {
- useEffect,
- useRef,
- useCallback,
- useMemo,
-} from "react";
-import { flushSync } from "react-dom";
-import {
- chatInit as chatInitApi,
- checkFreshness as checkFreshnessApi,
- conversationInit as conversationInitApi,
- createConversation as createConversationApi,
- listMessages as listMessagesApi,
- listMessagesAroundTask as listMessagesAroundTaskApi,
- listPreviousConversations as listPreviousConversationsApi,
- sendMessage as sendMessageApi,
- getTask as getTaskApi,
- getTaskMessages as getTaskMessagesApi,
- listArtifacts as listArtifactsApi,
- getActiveTask as getActiveTaskApi,
- retryTask as retryTaskApi,
- markInboxRead as markInboxReadApi,
- listFlaggedMessageIds as listFlaggedMessageIdsApi,
-} from "@/lib/api";
-import {
- chatExtrasKey, chatMessagesKey, sortedChatMessages, type ChatMessagesData, type ChatExtras,
- getCachedMessages,
- getCachedMessagesBefore,
- getCacheMeta,
- mergeCachedMessages,
- getLastOpenConversation,
- setLastOpenConversation,
-} from "@/lib/chat-cache";
-import {
- fastLoadKey,
-} from "@/components/agent-chat/fast-load-gate";
-import {
- sortMessages,
- mergeMessages,
- computeGroupPositions,
- buildTimeline,
- shouldPersistPointerForLoad,
- pointerRefreshTargetForTaskCreated,
-} from "@/components/agent-chat/chat-message-utils";
-import type { NapMarker } from "@/components/agent-chat/chat-message-utils";
-import type { PreviousConversation } from "@/lib/api";
-import type {
- Agent,
- Artifact,
- Conversation,
- Message,
- SkillEntry,
- TaskApi as Task,
- TaskMessageResponse,
- WsMessage,
-} from "@alook/shared";
-import { toast } from "sonner";
-import type { PendingFile } from "@/hooks/use-file-attachments";
-import type { ChatComposerHandle } from "@/components/agent-chat/chat-composer";
-import { getArtifactThumbnailUrl } from "@/components/artifact-content-renderer";
-import { useIsRestoring, useIsMutating, useMutation, skipToken, useQuery, QueryObserver, InfiniteQueryObserver, isCancelledError } from "@tanstack/react-query";
-import type { ApiRequestOptions } from "@/lib/api/client";
-import { ApiError, isAbortError } from "@/lib/errors";
-import { useAtom, useCreateAtom, createStore, useSelector } from "@tanstack/react-store";
-import type { ChatFlagsData } from "@/lib/workspace-chat-flags";
-import { useChatData, captureChatIntent, assertChatIntent, runChatIntentRequest } from "@/hooks/workspace/use-chat-data";
-import { useWorkspaceOwner, workspaceRequestOptions } from "@/contexts/workspace-context";
-import { observeChatRead, chatReadSource, chatMessagePageOptions, chatAroundTaskOptions, readChatMessageIds, chatArtifactOptions, chatTaskOptions, readChatTask, chatTaskMessagesOptions, chatActiveTaskOptions, chatPreviousOptions, chatFlagsOptions } from "@/hooks/workspace/chat-query-options";
-import { isQueryReceiptCurrent } from "@/lib/query-receipt";
-import { captureChatLoad, settleChatLoad } from "@/lib/workspace-chat-load";
-import { trackAgentChatOpened, trackMessageSent } from "@/lib/analytics";
-
-const isChatCancellation = (error: unknown) => isAbortError(error) || isCancelledError(error);
-const MESSAGE_LIMIT = 20;
-const MAX_CONV_FETCHES_PER_CLICK = 5;
-
-export interface UseAgentChatProps {
- agentId: string;
- targetConvId: string | null;
- scrollToTaskId: string | null;
- scrollToMessageId: string | null;
- propTargetConvId?: string | null;
- workspaceId: string;
- agents: Agent[];
- activeChannel: string;
- readActiveChannel: () => string;
- channelLoading: boolean;
- subscribeWs: (cb: (msg: WsMessage) => void) => () => void;
- subscribeReconnect: (cb: () => void) => () => void;
- refreshInboxCount: () => void;
-}
-
-export interface UseAgentChatExternal {
- // (a) Setters the hook WRITES — state owned outside the hook, passed IN.
- setPendingFiles: (files: PendingFile[]) => void;
- setInput: (value: string) => void;
- setQuotedMessage: (value: { id: string; excerpt: string } | null) => void;
- setActiveSkill: (skill: SkillEntry | null) => void;
- clearActiveSkill: () => void;
- readInput: () => string;
- readQuotedMessage: () => { id: string; excerpt: string } | null;
- readPendingFiles: () => PendingFile[];
- readActiveSkill: () => SkillEntry | null;
- markDraftRestored: () => void;
-}
-
-export function useAgentChat(
- props: UseAgentChatProps,
- external: UseAgentChatExternal,
-) {
- const {
- agentId,
- targetConvId,
- scrollToTaskId,
- scrollToMessageId,
- propTargetConvId,
- workspaceId,
- agents,
- activeChannel,
- readActiveChannel,
- channelLoading,
- subscribeWs,
- subscribeReconnect,
- refreshInboxCount,
- } = props;
- const {
- setPendingFiles,
- setInput,
- setQuotedMessage,
- setActiveSkill,
- clearActiveSkill,
- readInput,
- readQuotedMessage,
- readPendingFiles,
- readActiveSkill,
- markDraftRestored,
- } = external;
-
- const workspaceOwner = useWorkspaceOwner();
- const isRestoring = useIsRestoring();
- if (workspaceOwner.workspaceId !== workspaceId) throw new DOMException("Wrong chat workspace", "AbortError");
- const chatViewIdentity = JSON.stringify([agentId, targetConvId, targetConvId ? null : activeChannel]);
- const chatData = useChatData(workspaceOwner, chatViewIdentity, targetConvId);
- const chatActions = chatData.actions;
- const { conversation, setConversation, messages, setMessages, artifacts, activeTask, setActiveTask, taskMessages, hasMore, setHasMore, previousConversations, setPreviousConversations, hasMoreConversations, setHasMoreConversations } = chatData;
- const { mutateAsync: mutateChatCommand } = useMutation({ meta: { observabilityAction: "chat.command" }, mutationKey: workspaceOwner.key("chat", "command"), gcTime: 0, mutationFn: ({ operation }: { operation: () => Promise<unknown>; kind: "persist" | "read" }) => operation() });
- const withChatOrigin = useCallback(<T,>(operation: (options: ApiRequestOptions) => Promise<T>, options?: ApiRequestOptions, mutation: false | "persist" | "read" = false): Promise<T> => {
- const intent = captureChatIntent(workspaceOwner, chatActions.view);
- const controller = new AbortController();
- const signal = options?.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
- const assertActive = () => { assertChatIntent(intent, signal); options?.assertActive?.(); };
- assertActive();
- const onChange = () => { try { assertActive(); } catch { controller.abort(); } };
- const subscriptions = [chatActions.view, workspaceOwner.lifecycle, workspaceOwner.application.lifecycle].map((store) => store.subscribe(onChange));
- const load = async () => {
- try { assertActive(); const result = await operation({ ...options, ...workspaceRequestOptions(intent.workspace, signal, assertActive) }); assertActive(); return result; }
- catch (error) { assertActive(); throw error; }
- finally { for (const subscription of subscriptions) subscription.unsubscribe(); }
- };
- return mutation ? mutateChatCommand({ operation: load, kind: mutation }) as Promise<T> : load();
- }, [workspaceOwner, chatActions.view, mutateChatCommand]);
- const chatInit = useCallback(async (...args: Parameters<typeof chatInitApi>) => { const tickets = captureChatLoad(workspaceOwner); const data = await withChatOrigin((options) => chatInitApi(args[0], args[1], args[2], options), args[3], false); return settleChatLoad(workspaceOwner, data, tickets); }, [withChatOrigin, workspaceOwner]);
- const checkFreshness = useCallback((...args: Parameters<typeof checkFreshnessApi>) => withChatOrigin((options) => checkFreshnessApi(args[0], args[1], options), args[2], false), [withChatOrigin]);
- const conversationInit = useCallback(async (...args: Parameters<typeof conversationInitApi>) => {
- const tickets = captureChatLoad(workspaceOwner);
- const flagsRequestRevision = workspaceOwner.queryClient.getQueryData<ChatFlagsData>(workspaceOwner.key("chat", "flags", args[0]))?.revision ?? 0;
- const data = await withChatOrigin((options) => conversationInitApi(args[0], args[1], args[2], options), args[3], false);
- return { ...settleChatLoad(workspaceOwner, data, tickets), flagsRequestRevision };
- }, [withChatOrigin, workspaceOwner]);
- const listMessages = useCallback(async (...args: Parameters<typeof listMessagesApi>) => {
- const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[3]);
- const options = chatMessagePageOptions(source, args[0], args[2]);
- let data: ChatMessagesData;
- if (args[2]?.before && workspaceOwner.queryClient.getQueryData(options.queryKey)) {
- const observer = new InfiniteQueryObserver(workspaceOwner.queryClient, { ...options, enabled: false });
- const release = observeChatRead(source, observer);
- try {
- await observer.fetchNextPage({ cancelRefetch: false, throwOnError: true });
- source.assertActive();
- data = workspaceOwner.queryClient.getQueryData<ChatMessagesData>(options.queryKey)!;
- } finally { release(); }
- } else {
- const observer = new InfiniteQueryObserver(workspaceOwner.queryClient, { ...options, enabled: false });
- const release = observeChatRead(source, observer);
- try { data = await workspaceOwner.queryClient.fetchInfiniteQuery(options) as ChatMessagesData; } finally { release(); }
- }
- source.assertActive();
- data = workspaceOwner.queryClient.getQueryData<ChatMessagesData>(options.queryKey)!;
- const cursor = args[2];
- const eligible = sortedChatMessages(data).filter((row) => !cursor?.before || row.created_at < cursor.before || row.created_at === cursor.before && row.id < (cursor.beforeId ?? ""));
- const messages = eligible.slice(-(cursor?.limit ?? 20));
- return { messages, has_more: eligible.length > messages.length || data.pages.at(-1)?.hasMore === true };
- }, [workspaceOwner, chatActions.view, chatViewIdentity]);
- const listMessagesAroundTask = useCallback(async (...args: Parameters<typeof listMessagesAroundTaskApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[3]); const options = chatAroundTaskOptions(source, args[0], args[2]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); let ids; try { ids = await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } return readChatMessageIds(source, args[0], ids); }, [workspaceOwner, chatActions.view, chatViewIdentity]);
- const listPreviousConversations = useCallback(async (...args: Parameters<typeof listPreviousConversationsApi>) => {
- const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[3]);
- const options = chatPreviousOptions(source, args[0], args[2]);
- let data;
- const old = workspaceOwner.queryClient.getQueryData(options.queryKey);
- if (old && old.pageParams.includes(args[2].before)) data = old;
- else if (old) {
- const observer = new InfiniteQueryObserver(workspaceOwner.queryClient, { ...options, enabled: false });
- const release = observeChatRead(source, observer);
- try { data = (await observer.fetchNextPage({ cancelRefetch: false, throwOnError: true })).data; }
- finally { release(); }
- } else {
- const observer = new InfiniteQueryObserver(workspaceOwner.queryClient, { ...options, enabled: false });
- const release = observeChatRead(source, observer);
- try { data = await workspaceOwner.queryClient.fetchInfiniteQuery(options); } finally { release(); }
- }
- source.assertActive();
- chatActions.selectPreviousResource(options.queryKey);
- const index = data?.pageParams.indexOf(args[2].before) ?? -1;
- return data?.pages[index < 0 ? data.pages.length - 1 : index] ?? { conversations: [], has_more: false };
- }, [workspaceOwner, chatActions, chatViewIdentity]);
- const sendMessage = useCallback((...args: Parameters<typeof sendMessageApi>) => withChatOrigin((options) => sendMessageApi(args[0], args[1], args[2], args[3], args[4], options), args[5], "persist"), [withChatOrigin]);
- const getTask = useCallback(async (...args: Parameters<typeof getTaskApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatTaskOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return workspaceOwner.queryClient.getQueryData<Task>(options.queryKey)!; }, [workspaceOwner, chatActions.view, chatViewIdentity]);
- const getTaskMessages = useCallback(async (...args: Parameters<typeof getTaskMessagesApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[3]); const options = chatTaskMessagesOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return (workspaceOwner.queryClient.getQueryData<TaskMessageResponse[]>(options.queryKey) ?? []).filter((row) => args[2] === undefined || row.seq > args[2]); }, [workspaceOwner, chatActions.view, chatViewIdentity]);
- const listArtifacts = useCallback(async (...args: Parameters<typeof listArtifactsApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatArtifactOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return workspaceOwner.queryClient.getQueryData<ChatExtras>(options.queryKey)?.artifacts ?? []; }, [workspaceOwner, chatActions.view, chatViewIdentity]);
- const getActiveTask = useCallback(async (...args: Parameters<typeof getActiveTaskApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatActiveTaskOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); const currentId = workspaceOwner.queryClient.getQueryData<{ id: string | null }>(options.queryKey)?.id; return currentId ? readChatTask(source, currentId) : undefined; }, [workspaceOwner, chatActions.view, chatViewIdentity]);
- const markInboxRead = useCallback((...args: Parameters<typeof markInboxReadApi>) => withChatOrigin((options) => markInboxReadApi(args[0], args[1], options), args[2], "read"), [withChatOrigin]);
- const listFlaggedMessageIds = useCallback(async (...args: Parameters<typeof listFlaggedMessageIdsApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatFlagsOptions(source, args[1]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); let ids; try { ids = await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return { message_ids: ids.ids }; }, [workspaceOwner, chatActions.view, chatViewIdentity]);
- const [messagesLoading, setMessagesLoading] = useAtom(useCreateAtom(true));
- const [napMarkers, setNapMarkers] = useAtom(useCreateAtom<NapMarker[]>([]));
-
- const [pendingFilesByMessage, setPendingFilesByMessage] = useAtom(useCreateAtom<Map<string, PendingFile[]>>((() => new Map())()));
- const [failedSends, setFailedSends] = useAtom(useCreateAtom<Map<string, { content: string; files: PendingFile[] }>>((() => new Map())()));
-
- // Maps real (server) message IDs back to their optimistic (temp-*) IDs so
- // the React key used in the timeline stays stable when the optimistic message
- // is replaced — preventing an unmount/remount flash of the entire row.
- const [stableKeyMap, setStableKeyMap] = useAtom(useCreateAtom<Map<string, string>>((() => new Map())()));
-
-
-
-
-
-
- const agentArtifacts = useMemo(
- () => artifacts.filter((a) => a.source === "agent"),
- [artifacts],
- );
-
- const timeline = useMemo(
- () => buildTimeline(messages, agentArtifacts, napMarkers, conversation?.id),
- [messages, agentArtifacts, napMarkers, conversation?.id],
- );
- const groupPositions = useMemo(
- () => computeGroupPositions(timeline),
- [timeline],
- );
-
- // The live error-surface (TaskStream) must attach to at most ONE message per
- // active task — otherwise multiple `send-dm` replies sharing a taskId would
- // each render the (errors-only) stream wrapper. Pick the LAST assistant
- // message of the active task; MessageItem gates `hasTaskStream` on this id.
- const activeTaskStreamMsgId = useMemo(() => {
- if (!activeTask) return null;
- for (let i = messages.length - 1; i >= 0; i--) {
- const m = messages[i];
- if (m.role === "assistant" && m.task_id === activeTask.id) return m.id;
- }
- return null;
- }, [messages, activeTask]);
-
- const scrollRef = useRef<HTMLDivElement>(null);
- const pollState = useMemo(() => ({ scope: [chatActions.view], store: createStore({ target: null as { taskId: string; conversationId: string; intent: ReturnType<typeof captureChatIntent> } | null }) }), [chatActions.view]).store;
- const pollTarget = useSelector(pollState, (state) => state.target);
- const followupTimers = useRef(new Set<ReturnType<typeof setTimeout>>());
- const markReadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const protocol = useMemo(() => ({ scope: [chatActions.view], store: createStore({ chatOpenedTracked: false, lastSeq: 0, pollFailures: 0, loadingMore: false, oldestCursor: null as PreviousConversation | null, backfillAttempts: 0, previousConversationId: undefined as string | undefined, loadedConversationId: null as string | null, markedReadId: null as string | null, completedLoadKey: null as string | null }) }), [chatActions.view]).store;
- useEffect(() => {
- if (!conversation || protocol.get().chatOpenedTracked) return;
- protocol.setState((state) => ({ ...state, chatOpenedTracked: true }));
- trackAgentChatOpened({
- agent_id: agentId,
- is_first_chat: messages.length === 0,
- });
- }, [conversation, agentId, chatActions.view]); // eslint-disable-line react-hooks/exhaustive-deps
-
-
- const loadingMore = useSelector(protocol, (state) => state.loadingMore);
- const connectionLost = useSelector(protocol, (state) => state.pollFailures >= 3);
- const initialScrollDone = useRef(false);
-
- const isNearBottom = useRef(true);
- const scrollTargetActiveRef = useRef(false);
- const startPollingRef = useRef<
- | ((taskId: string, conversationId: string, initialSeq?: number) => void)
- | null
- >(null);
-
-
-
- // The server-confirmed conversation id for the current load. Cache writes
- // (mergeCachedMessages / appendCachedMessage / setLastOpenConversation) must
- // guard on this so a write never lands on an optimistically-rendered (not yet
- // confirmed) conversation during the cache-first window. Stays null until
- // checkFreshness / chatInit / conversationInit confirms an id.
-
- // Dedup gate for the fast-path load: skips a redundant re-run when only
- // channel deps (activeChannel / channelLoading) change, WITHOUT stranding the
- // skeleton if a run is cancelled mid-flight. See fast-load-gate.ts (Part 2-a /
- // TODO 6 + stuck-skeleton fix).
-
- // TipTap composer imperative handle (focus / clear / isEmpty / anchor coords).
- const composerRef = useRef<ChatComposerHandle>(null);
-
- const scrollToBottom = useCallback(() => {
- isNearBottom.current = true;
- setTimeout(() => {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- behavior: "smooth",
- });
- }, 50);
- }, []);
-
- // Preload server thumbnail images in the background, then delete the
- // corresponding pendingFilesByMessage entries and revoke their blob URLs.
- // This prevents layout shift: the browser image cache is warm before we
- // remove the local blob source, so the <img> switches without a flash.
- const preloadThenCleanPending = useCallback(
- (arts: Artifact[], _conversationId: string) => {
- const intent = captureChatIntent(workspaceOwner, chatActions.view);
- assertChatIntent(intent);
- // Collect thumbnail URLs for image artifacts that have server thumbnails.
- const thumbUrls = arts
- .filter((a) => a.content_type.startsWith("image/") && a.has_thumbnail)
- .map((a) => getArtifactThumbnailUrl(a.id, workspaceId));
-
- function preloadImage(url: string): Promise<void> {
- return new Promise((resolve) => {
- const img = new window.Image();
- img.onload = () => resolve();
- img.onerror = () => resolve(); // don't block cleanup on failure
- img.src = url;
- });
- }
-
- // Preload all thumbnails, then clean up only pending entries whose
- // artifacts are actually resolved — avoids prematurely clearing entries
- // for a second message still being uploaded.
- const artIdSet = new Set(arts.map((a) => a.id));
- Promise.all(thumbUrls.map(preloadImage)).then(() => {
- try { assertChatIntent(intent); } catch { return; }
- setPendingFilesByMessage((prev) => {
- if (prev.size === 0) return prev;
- const msgs = sortedChatMessages(workspaceOwner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(workspaceOwner, _conversationId)));
- const next = new Map(prev);
- let changed = false;
- for (const [msgId, files] of prev) {
- const msg = msgs.find((m) => m.id === msgId);
- const ids = msg?.attachment_ids;
- if (ids && ids.length > 0 && ids.every((id: string) => artIdSet.has(id))) {
- for (const pf of files) {
- if (pf.thumbnailUrl) URL.revokeObjectURL(pf.thumbnailUrl);
- }
- next.delete(msgId);
- changed = true;
- }
- }
- return changed ? next : prev;
- });
- });
- },
- [workspaceOwner, chatActions.view, workspaceId, setPendingFilesByMessage],
- );
-
- useEffect(() => {
- // The slow path (no targetConvId) resolves the conversation id via the
- // server using activeChannel, so it must wait for the channel list. The
- // fast path (known targetConvId) and the cache-first optimistic paint need
- // neither activeChannel nor a loaded channel list, so they must NOT be
- // gated by channelLoading (Part 2-a). channelLoading stays in the dep array
- // so the slow path retries once channels load.
- if (isRestoring || !targetConvId && channelLoading) return;
-
- // Fast path: ignore channel-only dep changes (TODO 6). shouldSkipFastLoad
- // returns true only when a load for this identity has already COMPLETED, and
- // otherwise clears the completed marker so a run cancelled mid-flight leaves
- // no "done" marker — the recovery run then proceeds and clears the skeleton
- // instead of getting stuck forever. See fast-load-gate.ts.
- const fastKey = fastLoadKey({
- workspaceId,
- agentId,
- targetConvId,
- scrollToTaskId,
- });
- if (fastKey && protocol.get().completedLoadKey === fastKey) return;
- protocol.setState((state) => ({ ...state, completedLoadKey: null }));
-
- pollState.setState(() => ({ target: null }));
- protocol.setState((state) => ({ ...state, loadingMore: false }));
- protocol.setState((state) => ({ ...state, loadedConversationId: null }));
- let ignore = false;
- setMessagesLoading(true);
- initialScrollDone.current = false;
- // Revoke blob URLs before clearing the map — they were kept alive for the
- // session to avoid layout shift, so this is the only place they get freed.
- setPendingFilesByMessage((prev) => {
- for (const files of prev.values()) {
- for (const pf of files) {
- if (pf.thumbnailUrl) URL.revokeObjectURL(pf.thumbnailUrl);
- }
- }
- return new Map();
- });
- setFailedSends(new Map());
- setStableKeyMap(new Map());
- setNapMarkers([]);
- setPreviousConversations([]);
- setHasMoreConversations(false);
- protocol.setState((state) => ({ ...state, oldestCursor: null }));
- setInput(
- localStorage.getItem(
- `chat-draft:${workspaceOwner.application.userId}:${workspaceId}:${agentId}:${targetConvId ?? "default"}`,
- ) ?? "",
- );
- const metaRaw = localStorage.getItem(
- `chat-draft-meta:${workspaceOwner.application.userId}:${workspaceId}:${agentId}:${targetConvId ?? "default"}`,
- );
- if (metaRaw) {
- try {
- const meta = JSON.parse(metaRaw);
- const q = meta.quote;
- setQuotedMessage(q && typeof q === "object" && q.id ? q : null);
- setActiveSkill(
- meta.skill ? (meta.skill as SkillEntry) : null,
- );
- } catch {
- setQuotedMessage(null);
- setActiveSkill(null);
- }
- } else {
- setQuotedMessage(null);
- setActiveSkill(null);
- }
- markDraftRestored();
- setMessages([]);
-
- // Paint cached messages for a known conversation id without any network.
- // Returns true if it painted, so the caller can suppress the loading
- // skeleton until the background reconcile runs.
- async function paintFromCache(convId: string): Promise<{
- painted: boolean;
- cacheMeta: Awaited<ReturnType<typeof getCacheMeta>>;
- }> {
- const cacheMeta = await getCacheMeta(convId, workspaceOwner);
- if (cacheMeta?.newestMessageId) {
- const cached = await getCachedMessages(convId, workspaceOwner);
- if (ignore) return { painted: false, cacheMeta };
- if (cached && cached.length > 0) {
- setMessages(cached);
- setHasMore(cacheMeta.hasMore, convId!);
- setMessagesLoading(false);
- // Paint the cards (artifacts + event-card icon/label) from cache in
- // the same frame as the text, so they don't pop in after the network
- // round-trip. Both pieces are overwritten by the authoritative
- // network values in Phase B — this is purely a no-reflow first paint.
- await paintExtrasFromCache(convId, cached);
- return { painted: true, cacheMeta };
- }
- }
- return { painted: false, cacheMeta };
- }
-
- async function paintExtrasFromCache(convId: string, _paintedMessages: Message[]): Promise<void> {
- const cached = workspaceOwner.queryClient.getQueryData<ChatExtras>(chatExtrasKey(workspaceOwner, convId));
- if (ignore || !cached?.conversation) return;
- chatActions.selectConversation(convId);
- }
-
- async function load(signal: AbortSignal) {
- const loadIntent = captureChatIntent(workspaceOwner, chatActions.view);
- const requestOptions = { signal, assertActive: () => assertChatIntent(loadIntent, signal) };
- let hasCachedMessages = false;
- try {
- let convId: string | null = null;
- let cacheMeta: Awaited<ReturnType<typeof getCacheMeta>> = null;
- // The id we optimistically painted in the slow path; reconciled against
- // the server-confirmed id once checkFreshness returns.
- let optimisticConvId: string | null = null;
-
- if (targetConvId) {
- // Fast path: we already know the conv ID — render from cache immediately, no network needed
- convId = targetConvId;
- const res = await paintFromCache(convId);
- assertChatIntent(loadIntent);
- if (ignore) return;
- cacheMeta = res.cacheMeta;
- hasCachedMessages = res.painted;
- } else {
- // Slow path: resolve the conversation id locally first (last-open
- // pointer) and paint its cache immediately, then verify in the
- // background. Only paint optimistically when the pointer is plausibly
- // fresh (serverMessageCount > 0 and a non-empty cache), so a stale or
- // empty pointer falls back to the skeleton (review #4).
- //
- // The pointer now carries "latest-created conversation for this
- // agent+channel" semantics (see {@link setLastOpenConversation} and the
- // gated write in Phase B / the task.created WS handler), matching the
- // server's `check-fresh` definition of "current" (latest-created). So
- // the optimistic paint is correct-by-construction: in the common case
- // the painted id equals the check-fresh id below → no swap → no flash.
- // Do NOT reintroduce "last opened" semantics here (e.g. by writing the
- // pointer from a `?conv=` fast-path open) — that is exactly the bug this
- // fix removed.
- const lastOpen = await getLastOpenConversation(
- agentId,
- activeChannel,
- workspaceOwner,
- );
- assertChatIntent(loadIntent);
- if (ignore) return;
- if (lastOpen?.conversation_id && lastOpen.serverMessageCount > 0) {
- const res = await paintFromCache(lastOpen.conversation_id);
- assertChatIntent(loadIntent);
- if (ignore) return;
- if (res.painted) {
- hasCachedMessages = true;
- optimisticConvId = lastOpen.conversation_id;
- cacheMeta = res.cacheMeta;
- }
- }
-
- // Background freshness check — does NOT gate the paint above.
- try {
- const fresh = await checkFreshness({ agentId, channel: activeChannel }, workspaceId, requestOptions);
- assertChatIntent(loadIntent);
- if (ignore) return;
- convId = fresh.conversation_id;
-
- if (optimisticConvId && convId !== optimisticConvId) {
- // We painted the wrong/stale conversation. Swap to the correct
- // one and reset scroll intent so the initial-scroll effect
- // re-fires for the new message set (review #2).
- initialScrollDone.current = false;
- isNearBottom.current = true;
- const res = await paintFromCache(convId);
- assertChatIntent(loadIntent);
- if (ignore) return;
- cacheMeta = res.cacheMeta;
- hasCachedMessages = res.painted;
- if (!res.painted) {
- // The correct conversation has no cache — clear the stale
- // optimistic render so the Phase B merge below starts from an
- // empty list instead of mixing conversation A's messages into B.
- setMessages([]);
- setMessagesLoading(true);
- // Also clear the optimistically-painted cards from conversation
- // A. With extras now seeding `artifacts` on the optimistic
- // paint, a corrected conversation with no cache would otherwise
- // keep showing A's artifact cards until Phase B responds. The
- // provisional `conversation` stub is overwritten by Phase B's
- // authoritative `setConversation(data.conversation)` (MEDIUM-3).
- // When `res.painted` is true, paintFromCache already re-seeded
- // the corrected conversation's own cards.
- chatActions.selectConversation(convId);
- }
- } else if (!optimisticConvId) {
- // Nothing painted yet — read the resolved conversation's cache.
- const res = await paintFromCache(convId);
- assertChatIntent(loadIntent);
- if (ignore) return;
- cacheMeta = res.cacheMeta;
- hasCachedMessages = res.painted;
- }
- // else: optimistic id matched the confirmed id — keep the paint.
- //
- // We always fall through to Phase B: even when the cache is fresh
- // (idMatches && countMatches), conversationInit returns cache_valid
- // and is still needed for conversation meta / tasks / artifacts, and
- // it does NOT re-set messages — so a fresh cache means exactly one
- // setMessages (the instant paint), no flicker. Phase B also writes
- // the server-confirmed last_open pointer for both fresh and stale.
- } catch (error) {
- if (isChatCancellation(error) || error instanceof ApiError && error.status === 401) throw error;
- // checkFreshness failed — fall back to chatInit below
- }
- }
-
- // Phase B: full data fetch (background hydration or stale-cache refresh)
- if (convId) {
- protocol.setState((state) => ({ ...state, loadedConversationId: convId }));
- const data = await conversationInit(convId, workspaceId, {
- newestMessageId: cacheMeta?.newestMessageId ?? undefined,
- // 0 means "count unknown" (e.g. cached via the chatInit fallback,
- // which has no server total) — omit the param so the server skips
- // the count compare and relies on newestMessageId alone. Sending
- // "0" would make the server's `serverMessageCount === 0` check fail
- // for every non-empty conversation, forcing a needless full merge.
- messageCount: cacheMeta?.serverMessageCount || undefined,
- }, requestOptions);
- assertChatIntent(loadIntent);
- if (ignore) return;
- setConversation(data.conversation);
- if (data.root_message) {
- workspaceOwner.queryClient.setQueryData(workspaceOwner.key("chat", "thread-root", data.conversation.id), { conversationId: data.root_message.conversation_id, id: data.root_message.id });
- } else workspaceOwner.queryClient.setQueryData(workspaceOwner.key("chat", "thread-root", data.conversation.id), null);
- setHasMoreConversations(data.has_more_conversations);
- if (!data.cache_valid && data.messages) {
- // Stale cache — merge server data in place, preserving scroll
- // position unless the user was already near the bottom (A2 / TODO 5).
- const wasNearBottom = isNearBottom.current;
- setMessages((prev) => mergeMessages(prev, data.messages!));
- if (protocol.get().loadedConversationId === convId) {
- mergeCachedMessages(
- convId,
- data.messages,
- data.has_more_messages,
- workspaceOwner,
- data.message_count,
- ).catch(() => { });
- }
- setHasMore(data.has_more_messages, data.conversation.id);
- if (
- hasCachedMessages &&
- initialScrollDone.current &&
- wasNearBottom
- ) {
- scrollToBottom();
- }
- } else if (cacheMeta) {
- setHasMore(cacheMeta.hasMore, convId!);
- }
- // Record the last-open pointer with server-confirmed freshness so the
- // next param-less open can resolve this conversation locally. Re-read
- // the cache meta (just updated by mergeCachedMessages on the stale
- // path) so the stored newest id is authoritative rather than inferred
- // from page order.
- //
- // GATED on `!targetConvId`: only the SLOW path (param-less, server-
- // resolved) may write the pointer. On the FAST path `convId ===
- // targetConvId` — an explicit, possibly OLD conversation the user
- // navigated to via `?conv=`. Persisting that would re-corrupt the
- // pointer back to "last-opened" semantics and reintroduce the
- // wrong-conversation flash on the next param-less open. The pointer
- // must only ever carry the channel's latest-created conversation.
- if (
- protocol.get().loadedConversationId === convId &&
- shouldPersistPointerForLoad(targetConvId)
- ) {
- const confirmedMeta = await getCacheMeta(convId, workspaceOwner);
- assertChatIntent(loadIntent);
- if (ignore) return;
- setLastOpenConversation(
- agentId,
- activeChannel,
- {
- conversation_id: convId,
- newestMessageId:
- confirmedMeta?.newestMessageId ??
- cacheMeta?.newestMessageId ??
- null,
- serverMessageCount: data.message_count,
- },
- workspaceOwner,
- ).catch(() => { });
- }
- // Persist the authoritative card metadata so the next open paints the
- // artifact cards + correct event-card types instantly from cache.
- // Guarded on the stale-closure ref (same as the message write above)
- // so we never write extras for a switched-away conversation;
- // fire-and-forget, off the critical path.
-
- workspaceOwner.queryClient.setQueryData(workspaceOwner.key("chat", "flags", data.conversation.id), { ids: data.flagged_message_ids, requestRevision: data.flagsRequestRevision } satisfies ChatFlagsData);
- if (data.active_task) {
- if (data.task_messages.length > 0) {
- protocol.setState((state) => ({ ...state, lastSeq: Math.max(
- ...data.task_messages.map((m) => m.seq),
- ) }));
- }
- startPollingRef.current?.(
- chatActions.readActiveTaskId() ?? data.active_task.id,
- convId,
- protocol.get().lastSeq,
- );
- }
- if (scrollToTaskId) {
- const task = await getTask(scrollToTaskId, workspaceId, requestOptions).catch(
- (error) => { if (isChatCancellation(error)) throw error; assertChatIntent(loadIntent, signal); return null; },
- );
- assertChatIntent(loadIntent);
- if (ignore) return;
- if (
- task &&
- !["completed", "failed", "cancelled", "superseded"].includes(
- task.status,
- )
- ) {
- setActiveTask(workspaceOwner.queryClient.getQueryData<Task>(workspaceOwner.key("chat", "task", task.id)) ?? null);
- const tmsgs = await getTaskMessages(scrollToTaskId, workspaceId, undefined, requestOptions).catch((error) => { if (isChatCancellation(error)) throw error; assertChatIntent(loadIntent, signal); return [] as TaskMessageResponse[]; });
- assertChatIntent(loadIntent);
- if (ignore) return;
- // Errors-only: thinking is no longer rendered (replies arrive via
- // `send-dm`); we keep only the live error channel.
-
- // Advance the cursor past all fetched seqs (incl. dropped
- // thinking) so the poll/WS don't reconsider them.
- if (tmsgs.length > 0) {
- protocol.setState((state) => ({ ...state, lastSeq: Math.max(...tmsgs.map((m) => m.seq)) }));
- }
- startPollingRef.current?.(task.id, convId, protocol.get().lastSeq);
- }
- }
- } else {
- // checkFreshness failed entirely — fall back to chatInit
- const data = await chatInit(agentId, workspaceId, activeChannel, requestOptions);
- assertChatIntent(loadIntent);
- if (ignore) return;
- protocol.setState((state) => ({ ...state, loadedConversationId: data.conversation.id }));
- setConversation(data.conversation);
- const wasNearBottom = isNearBottom.current;
- setMessages((prev) =>
- prev.length > 0
- ? mergeMessages(prev, data.messages)
- : data.messages,
- );
- setHasMore(data.has_more_messages, data.conversation.id);
- setHasMoreConversations(data.has_more_conversations);
- mergeCachedMessages(
- data.conversation.id,
- data.messages,
- data.has_more_messages,
- workspaceOwner,
- ).catch(() => { });
- // Persist the card metadata from the chatInit fallback too (same
- // shape as the conversationInit write above), guarded on the
- // stale-closure ref. ChatInit's response carries the same
- // `artifacts` + `conversation` + `has_more_artifacts` fields.
-
- // This branch is reached only when `convId` is null — i.e. the SLOW
- // path's checkFreshness failed and we fell back to chatInit. chatInit
- // returns the server's current (latest-created) conversation, so this
- // write carries the correct "latest-created" semantics. It is
- // slow-path-only by construction (the fast path sets convId =
- // targetConvId and never falls through here), so no `!targetConvId`
- // gate is needed.
- setLastOpenConversation(
- agentId,
- activeChannel,
- {
- conversation_id: data.conversation.id,
- newestMessageId:
- data.messages.length > 0
- ? data.messages[data.messages.length - 1].id
- : null,
- // chatInit returns no server total; data.messages is only the first
- // page. When more pages exist, the count is unknown — store 0, which
- // the read site treats as "unknown" and omits from the freshness
- // compare (relying on newestMessageId instead). Storing the partial
- // page length would otherwise force a needless full merge next open.
- serverMessageCount: data.has_more_messages
- ? 0
- : data.messages.length,
- },
- workspaceOwner,
- ).catch(() => { });
- if (hasCachedMessages && initialScrollDone.current && wasNearBottom) {
- scrollToBottom();
- }
- listFlaggedMessageIds(workspaceId, data.conversation.id, requestOptions)
- .catch(() => { });
- if (data.active_task) {
- if (data.task_messages.length > 0) {
- protocol.setState((state) => ({ ...state, lastSeq: Math.max(
- ...data.task_messages.map((m) => m.seq),
- ) }));
- }
- if (
- !["completed", "failed", "cancelled", "superseded"].includes(
- data.active_task.status,
- )
- ) {
- startPollingRef.current?.(
- chatActions.readActiveTaskId() ?? data.active_task.id,
- data.conversation.id,
- protocol.get().lastSeq,
- );
- }
- }
- }
- } catch (error) {
- if (isChatCancellation(error) || signal.aborted || ignore) return;
- assertChatIntent(loadIntent, signal);
- if (!hasCachedMessages) {
- toast.error("Failed to load conversation");
- } else {
- toast.error("Couldn't refresh conversation");
- }
- } finally {
- if (!ignore && !signal.aborted) {
- try { assertChatIntent(loadIntent, signal); } catch { return; }
- setMessagesLoading(false);
- // Mark this fast-path identity as completed only now, so a re-fire
- // caused purely by a channel-dep change is deduped (TODO 6) — while a
- // run cancelled before reaching here leaves no marker, letting the
- // successor run take over and clear the skeleton.
- if (fastKey) protocol.setState((state) => ({ ...state, completedLoadKey: fastKey }));
- }
- }
- }
- const queryKey = workspaceOwner.key("chat", "open", chatViewIdentity, fastKey);
- void workspaceOwner.queryClient.fetchQuery({ queryKey, staleTime: 0, gcTime: 0, retry: false, queryFn: async ({ signal }) => { await load(signal); return { conversationId: protocol.get().loadedConversationId }; } }).catch(() => {});
- return () => {
- ignore = true;
- if (!chatActions.view.get().active) protocol.setState((state) => ({ ...state, completedLoadKey: null }));
- void workspaceOwner.queryClient.cancelQueries({ queryKey, exact: true });
- void workspaceOwner.queryClient.cancelQueries({ queryKey: workspaceOwner.key("chat", "io", chatViewIdentity) });
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [agentId, workspaceId, targetConvId, scrollToTaskId, activeChannel, channelLoading, isRestoring, chatActions.view]);
-
- const refreshInboxCountRef = useRef(refreshInboxCount);
- useEffect(() => {
- refreshInboxCountRef.current = refreshInboxCount;
- }, [refreshInboxCount, chatActions.view]);
-
-
- useEffect(() => {
- if (!conversation?.id || !workspaceId) return;
- if (protocol.get().markedReadId === conversation.id) return;
- protocol.setState((state) => ({ ...state, markedReadId: conversation.id }));
- const intent = captureChatIntent(workspaceOwner, chatActions.view);
- const timer = setTimeout(() => {
- try { assertChatIntent(intent); } catch { return; }
- markInboxRead(conversation.id, workspaceId, { assertActive: () => assertChatIntent(intent) })
- .then(() => { assertChatIntent(intent); refreshInboxCountRef.current(); })
- .catch(() => { });
- }, 1000);
- return () => {
- protocol.setState((state) => ({ ...state, markedReadId: null }));
- clearTimeout(timer);
- };
- }, [conversation?.id, workspaceId, chatActions.view, protocol, workspaceOwner, markInboxRead]);
-
- // Scroll to bottom on initial load (skip if scroll-to-task/message is active)
- useEffect(() => {
- if (!messagesLoading && messages.length > 0 && !initialScrollDone.current) {
- initialScrollDone.current = true;
- if (scrollToTaskId || scrollToMessageId) {
- isNearBottom.current = false;
- // Start at the bottom so the scroll-to-target effect scrolls UP (short
- // distance to a recent task) instead of DOWN from the top (long distance
- // through the entire conversation history).
- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
- } else if (propTargetConvId) {
- setTimeout(() => {
- const assistantMsgs = scrollRef.current?.querySelectorAll(
- "[data-quote-source]",
- );
- if (assistantMsgs && assistantMsgs.length > 0) {
- const lastAssistant = assistantMsgs[assistantMsgs.length - 1];
- lastAssistant.scrollIntoView({
- behavior: "instant",
- block: "start",
- });
- } else {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- });
- }
- }, 50);
- } else {
- setTimeout(() => {
- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
- }, 50);
- }
- }
- }, [messagesLoading, messages.length, scrollToTaskId, scrollToMessageId, propTargetConvId, chatActions.view]);
-
- // Scroll to task when ?task= param is present
- useEffect(() => {
- if (!scrollToTaskId || messagesLoading || !conversation) return;
- isNearBottom.current = false;
- scrollTargetActiveRef.current = true;
- let cancelled = false;
- let highlightTimerId: ReturnType<typeof setTimeout> | undefined;
- const tryScroll = () => {
- if (cancelled) return false;
- const el = document.querySelector(
- `[data-task-id="${CSS.escape(scrollToTaskId)}"]`,
- );
- if (!el) return false;
- el.scrollIntoView({ behavior: "smooth", block: "center" });
- el.classList.add("task-highlight");
- highlightTimerId = setTimeout(() => {
- el.classList.remove("task-highlight");
- if (!cancelled) scrollTargetActiveRef.current = false;
- }, 1500);
- return true;
- };
- const timerId = setTimeout(async () => {
- if (cancelled) return;
- if (tryScroll()) return;
- try {
- const around = await listMessagesAroundTask(
- conversation.id,
- workspaceId,
- scrollToTaskId,
- );
- if (cancelled) return;
- if (around.length > 0) {
- setMessages((prev) => mergeMessages(prev, around));
- requestAnimationFrame(() => {
- setTimeout(() => {
- if (!tryScroll()) {
- scrollTargetActiveRef.current = false;
- }
- }, 100);
- });
- } else {
- scrollTargetActiveRef.current = false;
- }
- } catch {
- if (!cancelled) scrollTargetActiveRef.current = false;
- }
- }, 100);
- return () => {
- cancelled = true;
- clearTimeout(timerId);
- if (highlightTimerId) clearTimeout(highlightTimerId);
- };
- }, [scrollToTaskId, messagesLoading, conversation, workspaceId, chatActions.view, listMessagesAroundTask, setMessages]);
-
- // Scroll to message when ?msg= param is present (skip if task scroll is active)
- useEffect(() => {
- if (
- !scrollToMessageId ||
- scrollToTaskId ||
- messagesLoading ||
- !conversation
- )
- return;
- isNearBottom.current = false;
- scrollTargetActiveRef.current = true;
- let cancelled = false;
- let highlightTimerId: ReturnType<typeof setTimeout> | undefined;
- const tryScroll = () => {
- if (cancelled) return false;
- const el = document.querySelector(
- `[data-message-id="${CSS.escape(scrollToMessageId)}"]`,
- );
- if (!el) return false;
- el.scrollIntoView({ behavior: "smooth", block: "center" });
- el.classList.add("task-highlight");
- highlightTimerId = setTimeout(() => {
- el.classList.remove("task-highlight");
- if (!cancelled) scrollTargetActiveRef.current = false;
- }, 1500);
- return true;
- };
- const timerId = setTimeout(() => {
- if (cancelled) return;
- if (!tryScroll()) {
- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
- scrollTargetActiveRef.current = false;
- }
- }, 100);
- return () => {
- cancelled = true;
- clearTimeout(timerId);
- if (highlightTimerId) clearTimeout(highlightTimerId);
- };
- }, [scrollToMessageId, scrollToTaskId, messagesLoading, conversation, chatActions.view]);
-
- // Auto-scroll when task badge appears or new task steps arrive
- const taskStatus = activeTask?.status;
- useEffect(() => {
- if (scrollTargetActiveRef.current) return;
- const isRunning = taskStatus === "running" || taskStatus === "queued";
- if (isRunning && isNearBottom.current) {
- scrollToBottom();
- }
- }, [taskMessages.length, taskStatus, scrollToBottom, chatActions.view]);
-
- // Auto-scroll when a new agent-side item lands while the user is at the
- // bottom — covers artifact (file) cards and event cards, which grow the
- // thread via setArtifacts / setMessages without otherwise nudging scroll.
- // (Previously only message text scrolled; cards appeared off-screen until the
- // next message arrived.)
- useEffect(() => {
- if (scrollTargetActiveRef.current) return;
- if (!initialScrollDone.current) return;
- if (isNearBottom.current) scrollToBottom();
- }, [artifacts.length, messages.length, scrollToBottom, chatActions.view]);
-
- const agentName = useMemo(
- () => agents.find((a) => a.id === agentId)?.name ?? "Agent",
- [agents, agentId],
- );
-
- const readAgentName = useCallback(() => workspaceOwner.queryClient.getQueryData<Agent[]>(workspaceOwner.key("agents"))?.find((row) => row.id === agentId)?.name ?? "Agent", [workspaceOwner, agentId]);
-
- const loadOlderMessages = useCallback(
- async (scrollToEnd = false) => {
- if (!conversation || protocol.get().loadingMore) return;
- const intent = captureChatIntent(workspaceOwner, chatActions.view);
- const chainOptions = { assertActive: () => assertChatIntent(intent) };
- protocol.setState((state) => ({ ...state, loadingMore: true }));
- try {
-
- const currentMessages = chatActions.readMessages();
- const currentHasMore = chatActions.readHasMore();
- const currentHasMoreConvs = chatActions.readHasMoreConversations();
- const currentAgentName = readAgentName();
- const currentChannel = readActiveChannel();
- const isSingleConvView = !!targetConvId;
-
- const oldest = currentMessages[0];
- const paginatingConvId =
- protocol.get().oldestCursor?.id ?? conversation.id;
- const canLoadMoreInConv = currentHasMore && oldest;
- let prevConvsList = chatActions.readPrevious();
-
- if (
- !isSingleConvView &&
- !canLoadMoreInConv &&
- prevConvsList.length === 0 &&
- currentHasMoreConvs
- ) {
- const oldestConv = protocol.get().oldestCursor ?? {
- id: conversation.id,
- created_at: conversation.created_at,
- };
- try {
- const result = await listPreviousConversations(agentId, workspaceId, {
- exclude: conversation.id,
- before: oldestConv.created_at,
- channel: currentChannel,
- }, chainOptions);
- assertChatIntent(intent);
- prevConvsList = result.conversations;
- setPreviousConversations(result.conversations);
- setHasMoreConversations(result.has_more);
- } catch (error) {
- if (isChatCancellation(error)) throw error;
- assertChatIntent(intent);
- setHasMoreConversations(false);
- }
- }
-
- const canLoadPrevConv = !isSingleConvView && prevConvsList.length > 0;
-
- if (!canLoadMoreInConv && !canLoadPrevConv) {
- protocol.setState((state) => ({ ...state, loadingMore: false }));
- return;
- }
-
- const el = scrollRef.current;
- if (el) el.style.overflowAnchor = "none";
- const prevScrollHeight = el?.scrollHeight ?? 0;
-
- try {
- let phase1Messages: Message[] = [];
- let phase2Messages: Message[] = [];
- let remaining = MESSAGE_LIMIT;
- let lastHasMore = false;
- const napMarkersToAdd: {
- agentName: string;
- created_at: string;
- id: string;
- }[] = [];
-
- // --- Phase 1: Load from current/paginating conversation ---
- let phase1HasMore = false;
- if (canLoadMoreInConv) {
- const cached =
- paginatingConvId === conversation.id
- ? await getCachedMessagesBefore(
- paginatingConvId,
- oldest!.created_at,
- oldest!.id,
- MESSAGE_LIMIT,
- workspaceOwner,
- )
- : null;
- assertChatIntent(intent);
-
- if (cached) {
- phase1Messages = cached.messages;
- remaining -= cached.messages.length;
- lastHasMore = cached.hasMore;
- } else {
- const result = await listMessages(paginatingConvId, workspaceId, {
- limit: MESSAGE_LIMIT,
- before: oldest!.created_at,
- beforeId: oldest!.id,
- }, chainOptions);
- assertChatIntent(intent);
- phase1Messages = result.messages;
- remaining -= result.messages.length;
- lastHasMore = result.has_more;
- }
- phase1HasMore = lastHasMore;
- }
-
- // --- Phase 2: Load from previous conversations (only in timeline mode) ---
- if (!isSingleConvView && !lastHasMore && remaining > 0) {
- if (prevConvsList.length === 0 && currentHasMoreConvs) {
- const oldestConv = protocol.get().oldestCursor ?? {
- id: conversation.id,
- created_at: conversation.created_at,
- };
- try {
- const result = await listPreviousConversations(agentId, workspaceId, {
- exclude: conversation.id,
- before: oldestConv.created_at,
- channel: currentChannel,
- }, chainOptions
- );
- assertChatIntent(intent);
- prevConvsList = result.conversations;
- setPreviousConversations(result.conversations);
- setHasMoreConversations(result.has_more);
- } catch (error) {
- if (isChatCancellation(error)) throw error;
- assertChatIntent(intent);
- setHasMoreConversations(false);
- }
- }
-
- let consumed = 0;
- let fetchCount = 0;
-
- while (
- consumed < prevConvsList.length &&
- remaining > 0 &&
- fetchCount < MAX_CONV_FETCHES_PER_CLICK
- ) {
- const prevConv = prevConvsList[consumed]!;
- consumed++;
- fetchCount++;
- const result = await listMessages(prevConv.id, workspaceId, {
- limit: remaining,
- }, chainOptions);
- assertChatIntent(intent);
-
- if (result.messages.length === 0) {
- protocol.setState((state) => ({ ...state, oldestCursor: prevConv }));
- continue;
- }
-
- const napTs =
- protocol.get().oldestCursor?.created_at ??
- conversation.created_at;
- napMarkersToAdd.push({
- agentName: currentAgentName,
- created_at: napTs,
- id: `nap-${prevConv.id}`,
- });
-
- phase2Messages = [...result.messages, ...phase2Messages];
- remaining -= result.messages.length;
- lastHasMore = result.has_more;
- protocol.setState((state) => ({ ...state, oldestCursor: prevConv }));
- }
-
- if (consumed > 0) {
- setPreviousConversations((prev) => prev.slice(consumed));
- }
- }
-
- // --- Final state update ---
- const allNewMessages = [...phase2Messages, ...phase1Messages];
- flushSync(() => {
- if (allNewMessages.length > 0) {
- if (napMarkersToAdd.length > 0) {
- setNapMarkers((prev) => {
- const existingIds = new Set(prev.map((m) => m.id));
- const newMarkers = napMarkersToAdd.filter(
- (m) => !existingIds.has(m.id),
- );
- return [...prev, ...newMarkers];
- });
- }
- setHasMore(lastHasMore, protocol.get().oldestCursor?.id ?? conversation.id);
- setMessages((prev) => {
- const existingIds = new Set(prev.map((m) => m.id));
- const unique = allNewMessages.filter(
- (m) => !existingIds.has(m.id),
- );
- return [...unique, ...prev];
- });
- } else {
- setHasMore(false);
- }
- });
-
- if (allNewMessages.length > 0 && conversation) {
- const currentConvMessages = allNewMessages.filter(
- (m) => m.conversation_id === conversation.id,
- );
- if (currentConvMessages.length > 0) {
- mergeCachedMessages(
- conversation.id,
- currentConvMessages,
- phase1HasMore,
- workspaceOwner,
- ).catch(() => { });
- }
- }
-
- protocol.setState((state) => ({ ...state, loadingMore: false }));
- flushSync(() => protocol.setState((state) => ({ ...state, loadingMore: false })));
-
- if (el) {
- if (scrollToEnd) {
- el.scrollTop = el.scrollHeight;
- } else {
- const newScrollHeight = el.scrollHeight;
- el.scrollTop = newScrollHeight - prevScrollHeight;
- }
- }
- } catch (error) {
- if (isChatCancellation(error)) return;
- assertChatIntent(intent);
- toast.error("Failed to load older messages");
- } finally {
- try { assertChatIntent(intent); } catch { return; }
- protocol.setState((state) => ({ ...state, loadingMore: false }));
- if (scrollRef.current) scrollRef.current.style.overflowAnchor = "";
- }
- } catch (error) {
- if (isChatCancellation(error)) return;
- try { assertChatIntent(intent); } catch { return; }
- toast.error("Failed to load older messages");
- } finally {
- try { assertChatIntent(intent); } catch { return; }
- protocol.setState((state) => ({ ...state, loadingMore: false }));
- }
- },
- [conversation, protocol, workspaceOwner, chatActions, readAgentName, readActiveChannel, targetConvId, listPreviousConversations, agentId, workspaceId, setPreviousConversations, setHasMoreConversations, listMessages, setHasMore, setMessages, setNapMarkers],
- );
-
- const canLoadMore = targetConvId
- ? hasMore
- : hasMore || previousConversations.length > 0 || hasMoreConversations;
-
- useEffect(() => {
- if (conversation?.id === protocol.get().previousConversationId) return;
- protocol.setState((state) => ({ ...state, previousConversationId: conversation?.id }));
- protocol.setState((state) => ({ ...state, backfillAttempts: 0 }));
- }, [conversation?.id, chatActions.view, protocol]);
-
- const MIN_MESSAGES = 10;
- useEffect(() => {
- if (messagesLoading || !conversation) return;
- if (scrollToTaskId || targetConvId) return;
- if (messages.length >= MIN_MESSAGES || !canLoadMore) return;
- if (loadingMore) return;
- if (protocol.get().backfillAttempts >= 3) return;
- protocol.setState((state) => ({ ...state, backfillAttempts: state.backfillAttempts + (1) }));
- loadOlderMessages(true);
- }, [messagesLoading, messages.length, canLoadMore, loadingMore, conversation, loadOlderMessages, scrollToTaskId, targetConvId, chatActions.view, protocol]);
-
- const handleScroll = useCallback(() => {
- const el = scrollRef.current;
- if (!el) return;
- isNearBottom.current =
- el.scrollHeight - el.scrollTop - el.clientHeight < 100;
- }, []);
-
- const startPolling = useCallback((taskId: string, conversationId: string, initialSeq?: number) => {
- const intent = captureChatIntent(workspaceOwner, chatActions.view);
- assertChatIntent(intent);
- protocol.setState((state) => ({ ...state, lastSeq: initialSeq ?? 0 }));
- protocol.setState((state) => ({ ...state, pollFailures: 0 }));
- protocol.setState((state) => ({ ...state, pollFailures: 0 }));
- pollState.setState(() => ({ target: { taskId, conversationId, intent } }));
- }, [workspaceOwner, chatActions.view, protocol, pollState]);
- useEffect(() => { startPollingRef.current = startPolling; }, [startPolling]);
-
- const pollFactSource = useMemo(() => pollTarget ? chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity) : null, [workspaceOwner, chatActions.view, chatViewIdentity, pollTarget]);
- const pollQuery = useQuery({
- ...(pollFactSource ? chatTaskOptions(pollFactSource, pollTarget!.taskId) : { queryKey: workspaceOwner.key("chat", "task", "__none__"), queryFn: skipToken }),
- enabled: !!pollTarget,
- subscribed: !!pollTarget,
- retry: false,
- staleTime: 3000,
- refetchInterval: pollTarget ? 3000 : false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- });
- useEffect(() => {
- if (!pollTarget || pollQuery.isFetching) return;
- const { taskId, conversationId, intent } = pollTarget;
- const controller = new AbortController();
- const assertActive = () => assertChatIntent(intent, controller.signal);
- const chainOptions = { signal: controller.signal, assertActive };
- const settle = async () => {
- try {
- assertActive();
- if (pollQuery.error) throw pollQuery.error;
- const task = pollQuery.data;
- if (!task) return;
- assertActive();
- protocol.setState((state) => ({ ...state, pollFailures: 0 }));
- protocol.setState((state) => ({ ...state, pollFailures: 0 }));
- if (["completed", "failed", "cancelled", "superseded"].includes(task.status)) {
- if (pollState.get().target?.taskId !== taskId) {
- const result = await listMessages(conversationId, workspaceId, undefined, chainOptions);
- assertActive();
- setMessages((previous) => mergeMessages(previous, result.messages));
- return task;
- }
- const shouldScroll = !scrollTargetActiveRef.current && isNearBottom.current;
- try {
- const [result, arts] = await Promise.all([
- listMessages(conversationId, workspaceId, undefined, chainOptions),
- listArtifacts(conversationId, workspaceId, chainOptions).catch((error) => {
- if (isChatCancellation(error)) throw error;
- assertActive();
- return null;
- }),
- ]);
- assertActive();
- setMessages((previous) => mergeMessages(previous, result.messages));
- if (arts) preloadThenCleanPending(arts, conversationId);
- setActiveTask(workspaceOwner.queryClient.getQueryData<Task>(workspaceOwner.key("chat", "task", task.id)) ?? null);
- } catch (error) {
- if (isChatCancellation(error)) throw error;
- assertActive();
- setActiveTask(workspaceOwner.queryClient.getQueryData<Task>(workspaceOwner.key("chat", "task", task.id)) ?? null);
- toast.error("Failed to refresh messages");
- }
- assertActive();
- if (pollState.get().target?.taskId === taskId) pollState.setState(() => ({ target: null }));
- if (shouldScroll) requestAnimationFrame(() => {
- try { assertChatIntent(intent); } catch { return; }
- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
- });
- if (markReadTimerRef.current) clearTimeout(markReadTimerRef.current);
- markReadTimerRef.current = setTimeout(() => {
- try { assertChatIntent(intent); } catch { return; }
- markInboxRead(conversationId, workspaceId, { assertActive: () => assertChatIntent(intent) })
- .then(() => { assertChatIntent(intent); refreshInboxCountRef.current(); }).catch(() => {});
- }, 1000);
- const timer = setTimeout(async () => {
- followupTimers.current.delete(timer);
- try {
- assertChatIntent(intent);
- if (pollState.get().target) return;
- const options = { assertActive: () => assertChatIntent(intent) };
- const nextTask = await getActiveTask(conversationId, workspaceId, options);
- assertChatIntent(intent);
- if (nextTask && nextTask.id !== taskId) {
- const result = await listMessages(conversationId, workspaceId, undefined, options);
- assertChatIntent(intent);
- setMessages((previous) => mergeMessages(previous, result.messages));
- setActiveTask(nextTask);
-
- startPollingRef.current?.(nextTask.id, conversationId);
- }
- } catch {}
- }, 1000);
- followupTimers.current.add(timer);
- } else if (pollState.get().target?.taskId === taskId) setActiveTask(workspaceOwner.queryClient.getQueryData<Task>(workspaceOwner.key("chat", "task", task.id)) ?? null);
- assertActive();
- return task;
- } catch (error) {
- if (isChatCancellation(error)) throw error;
- assertActive();
- if (pollState.get().target?.taskId === taskId) {
- protocol.setState((state) => ({ ...state, pollFailures: state.pollFailures + (1) }));
- if (protocol.get().pollFailures >= 10) {
- pollState.setState(() => ({ target: null }));
- toast.error("Lost connection to agent");
- }
- }
- }
- };
- void settle().catch(() => {});
- return () => controller.abort();
- }, [pollTarget, pollQuery.dataUpdatedAt, pollQuery.errorUpdatedAt, chatActions.view, pollQuery.isFetching, pollQuery.error, pollQuery.data, protocol, pollState, setActiveTask, workspaceOwner, listMessages, workspaceId, setMessages, listArtifacts, preloadThenCleanPending, markInboxRead, getActiveTask]);
-
- useEffect(() => () => {
- if (markReadTimerRef.current) clearTimeout(markReadTimerRef.current);
- for (const timer of followupTimers.current) clearTimeout(timer);
- followupTimers.current.clear();
- }, [chatActions.view]);
-
-
-
- useEffect(() => {
- const intent = captureChatIntent(workspaceOwner, chatActions.view);
- const chainOptions = { assertActive: () => assertChatIntent(intent) };
- return subscribeWs((msg: WsMessage) => {
- try { assertChatIntent(intent); } catch { return; }
- if (
- msg.type === "task.messages" &&
- msg.taskId === chatActions.readActiveTaskId()
- ) {
- const incoming = msg.messages.filter((m) => m.seq > protocol.get().lastSeq);
- if (incoming.length > 0) {
- // Thinking is no longer rendered — the reply lands via `send-dm`. Keep
- // ONLY `type:"error"` items: they are a live error channel (opencode /
- // codex emit them mid-run, sometimes without the task transitioning to
- // failed) and dropping them would hide real failures.
- // Advance the cursor past every seq we've seen (incl. dropped
- // thinking) so we never reconsider them.
- protocol.setState((state) => ({ ...state, lastSeq: Math.max(
- ...incoming.map((m) => m.seq),
- protocol.get().lastSeq,
- ) }));
- }
- }
- if (
- msg.type === "task.created" &&
- msg.conversationId === conversation?.id
- ) {
- listMessages(msg.conversationId, workspaceId, undefined, chainOptions)
- .then(({ messages: latest }) => {
- assertChatIntent(intent);
- setMessages((prev) => mergeMessages(prev, latest));
- mergeCachedMessages(
- msg.conversationId,
- latest,
- null,
- workspaceOwner,
- ).catch(() => { });
- })
- .catch(() => { });
- const task = msg.task as Task;
- setActiveTask(workspaceOwner.queryClient.getQueryData<Task>(workspaceOwner.key("chat", "task", task.id)) ?? null);
- protocol.setState((state) => ({ ...state, lastSeq: 0 }));
- startPollingRef.current?.(task.id, msg.conversationId);
- }
- // Refresh the per-channel `last_open` pointer when a `task.created`
- // arrives — this is the client learning of a (possibly newer) conversation
- // for this agent+channel in real time, keeping the pointer's
- // "latest-created" semantics fresh while the user is on the page. Runs
- // independently of the active-conversation block above: a new thread spawned
- // in this channel often has a different conversationId than the one being
- // viewed, so it must NOT be gated on `msg.conversationId === conversation?.id`.
- if (msg.type === "task.created") {
- const task = msg.task as Task;
- const activeChannel = readActiveChannel();
- getLastOpenConversation(agentId, activeChannel, workspaceOwner)
- .then((current) => {
- assertChatIntent(intent);
- const targetConvId = pointerRefreshTargetForTaskCreated({
- task,
- agentId,
- activeChannel,
- currentPointerConvId: current?.conversation_id ?? null,
- });
- if (!targetConvId) return;
- // A1: derive serverMessageCount from the locally-cached count for
- // this conversation. May under-count (e.g. brand-new thread with no
- // cache → 0), which only makes the next slow-path read fall back to
- // the skeleton (the `serverMessageCount > 0` gate) — never wrong
- // content. We never over-count, so the pointer can't claim a
- // conversation is more complete than it is.
- return getCacheMeta(targetConvId, workspaceOwner).then((meta) =>
- { assertChatIntent(intent); return setLastOpenConversation(
- agentId,
- activeChannel,
- {
- conversation_id: targetConvId,
- newestMessageId: meta?.newestMessageId ?? null,
- serverMessageCount: meta?.messageCount ?? 0,
- },
- workspaceOwner,
- ); },
- );
- })
- .catch(() => { });
- }
- if (msg.type === "conversation.message") {
- // Only cache for the server-confirmed loaded conversation — never write
- // during the optimistic cache-first window before the id is confirmed
- // (review #1).
- if (msg.conversationId === conversation?.id) {
- const incomingTime = new Date(msg.message.created_at).getTime();
- const optimisticMatch = chatActions.readMessages().find(
- (m) =>
- m.id.startsWith("temp-") &&
- m.role === msg.message.role &&
- m.content === msg.message.content &&
- Math.abs(new Date(m.created_at).getTime() - incomingTime) < 2000,
- );
- if (optimisticMatch) {
- setPendingFilesByMessage((p) => {
- if (!p.has(optimisticMatch.id)) return p;
- const files = p.get(optimisticMatch.id)!;
- const next = new Map(p);
- next.delete(optimisticMatch.id);
- next.set(msg.message.id, files);
- return next;
- });
- setStableKeyMap((prev) => {
- if (prev.has(msg.message.id)) return prev;
- const next = new Map(prev);
- next.set(msg.message.id, optimisticMatch.id);
- return next;
- });
- }
- setMessages((prev) => {
- if (optimisticMatch) {
- const idx = prev.findIndex((m) => m.id === optimisticMatch.id);
- if (idx !== -1) {
- const updated = [...prev];
- updated[idx] = msg.message;
- return updated;
- }
- }
- return mergeMessages(prev, [msg.message]);
- });
- }
- }
- });
- }, [subscribeWs, conversation?.id, workspaceId, agentId, chatActions.view, workspaceOwner, chatActions, protocol, listMessages, setActiveTask, setMessages, readActiveChannel, setPendingFilesByMessage, setStableKeyMap]);
-
- useEffect(() => {
- const intent = captureChatIntent(workspaceOwner, chatActions.view);
- return subscribeReconnect(() => {
- try { assertChatIntent(intent); } catch { return; }
- if (!conversation?.id) return;
- void workspaceOwner.queryClient.fetchQuery({
- queryKey: workspaceOwner.key("chat", "open", chatViewIdentity, "reconnect"), retry: false, staleTime: 0, gcTime: 0,
- queryFn: async ({ signal }) => {
- const assertActive = () => assertChatIntent(intent, signal);
- assertActive();
- const meta = await getCacheMeta(conversation.id, workspaceOwner);
- assertActive();
- const data = await conversationInit(conversation.id, workspaceId, { newestMessageId: meta?.newestMessageId ?? undefined, messageCount: meta?.serverMessageCount ?? undefined }, { signal, assertActive });
- assertActive();
- if (!data.cache_valid && data.messages) {
- await mergeCachedMessages(conversation.id, data.messages, data.has_more_messages, workspaceOwner, data.message_count);
- assertActive();
- setMessages((previous) => mergeMessages(previous, data.messages!));
- }
- return { conversationId: data.conversation.id };
- },
- }).catch(() => {});
- });
- }, [subscribeReconnect, conversation?.id, workspaceId, workspaceOwner, chatViewIdentity, chatActions.view, conversationInit, setMessages]);
-
- type SendIntent = {
- original: ReturnType<typeof captureChatIntent>;
- conversation: Conversation;
- content: string;
- files: PendingFile[];
- quote: { id: string; excerpt: string } | null;
- retryId?: string;
- rawInput?: string;
- skillName?: string;
- };
- const sendIdentity = useMemo(() => crypto.randomUUID(), []);
- const sendKey = workspaceOwner.key("chat", "send", sendIdentity);
- const sending = useIsMutating({ mutationKey: sendKey, exact: true }) > 0;
- const sendCommand = useMutation<void, Error, SendIntent>({ meta: { observabilityAction: "chat.message.send" },
- mutationKey: sendKey, gcTime: 0,
- mutationFn: async ({ original: intent, conversation, content, files, quote, retryId, rawInput, skillName }) => {
- const assertActive = () => assertChatIntent(intent);
- assertActive();
- const renderFiles = files.map((file) => ({ ...file, thumbnailUrl: file.thumbnailBlob ? URL.createObjectURL(file.thumbnailBlob) : null }));
- if (retryId) {
- setFailedSends((previous) => { const next = new Map(previous); next.delete(retryId); return next; });
- setMessages((previous) => previous.filter((row) => row.id !== retryId));
- setPendingFilesByMessage((previous) => {
- const next = new Map(previous);
- for (const file of next.get(retryId) ?? []) if (file.thumbnailUrl) URL.revokeObjectURL(file.thumbnailUrl);
- next.delete(retryId); return next;
- });
- } else {
- trackMessageSent({ agent_id: agentId, message_length: content.length });
- if (readInput() === rawInput) setInput("");
- if (readPendingFiles() === files) setPendingFiles([]);
- if (readQuotedMessage()?.id === quote?.id) setQuotedMessage(null);
- if (readActiveSkill()?.name === skillName) clearActiveSkill();
- }
- const optimisticId = `temp-${crypto.randomUUID()}`;
- const optimistic: Message = { id: optimisticId, conversation_id: conversation.id, role: "user", content, task_id: null, attachment_ids: null, ...(quote ? { metadata: { quote: { messageId: quote.id, excerpt: quote.excerpt } } } : {}), created_at: new Date().toISOString() };
- if (renderFiles.length) setPendingFilesByMessage((previous) => new Map(previous).set(optimisticId, renderFiles));
- setMessages((previous) => [...previous, optimistic]);
- scrollToBottom();
- try {
- const tickets = captureChatLoad(workspaceOwner);
- const { message: incoming, task } = await sendMessage(conversation.id, content, workspaceId, files.length ? files : undefined, quote ? { quote: { messageId: quote.id, excerpt: quote.excerpt } } : undefined, { assertActive });
- assertActive();
- const messageKey = chatMessagesKey(workspaceOwner, conversation.id), messageTicket = tickets.get(JSON.stringify(messageKey));
- const current = workspaceOwner.queryClient.getQueryData<ChatMessagesData>(messageKey);
- const message = (current?.liveMessageRevisions?.[incoming.id] ?? 0) > (messageTicket?.liveRevision ?? 0)
- ? sortedChatMessages(current).find((row) => row.id === incoming.id) ?? incoming : incoming;
- const originalMessageResource = messageTicket?.receipt.resource;
- if (originalMessageResource ? workspaceOwner.queryClient.getQueryCache().find({ queryKey: messageKey, exact: true }) === originalMessageResource : !current || (current.liveRevision ?? 0) > 0) await mergeCachedMessages(conversation.id, [message], null, workspaceOwner);
- assertActive();
- const taskKey = workspaceOwner.key("chat", "task", task.id), taskTicket = tickets.get(JSON.stringify(taskKey))?.receipt;
- if (taskTicket ? isQueryReceiptCurrent(taskTicket) : !workspaceOwner.queryClient.getQueryCache().find({ queryKey: taskKey, exact: true })) workspaceOwner.queryClient.setQueryData(taskKey, task);
- setPendingFilesByMessage((previous) => { if (!previous.has(optimisticId)) return previous; const next = new Map(previous); const files = next.get(optimisticId)!; next.delete(optimisticId); next.set(message.id, files); return next; });
- setStableKeyMap((previous) => new Map(previous).set(message.id, optimisticId));
- setMessages((previous) => sortMessages([...previous.filter((row) => row.id !== optimisticId && row.id !== message.id), message]));
- if (message.attachment_ids?.length) void listArtifacts(conversation.id, workspaceId, { assertActive }).then((artifacts) => { assertActive(); preloadThenCleanPending(artifacts, conversation.id); }).catch(() => undefined);
- setActiveTask(workspaceOwner.queryClient.getQueryData<Task>(workspaceOwner.key("chat", "task", task.id)) ?? null);
- startPolling(task.id, conversation.id);
- } catch (error) {
- if (isChatCancellation(error)) throw error;
- assertActive();
- setFailedSends((previous) => new Map(previous).set(optimisticId, { content, files: renderFiles }));
- throw error;
- } finally {
- try { assertActive(); composerRef.current?.focus(); } catch {}
- }
- },
- });
- const sendPending = () => workspaceOwner.queryClient.isMutating({ mutationKey: sendKey, exact: true }) > 0;
- const handleSend = () => {
- const original = captureChatIntent(workspaceOwner, chatActions.view);
- assertChatIntent(original);
- const conversation = chatActions.readConversation(), rawInput = readInput(), files = readPendingFiles(), skill = readActiveSkill();
- if (sendPending() || !conversation || !rawInput.trim() && !files.length) return;
- if (!rawInput.trim()) { toast.error("Please type a message"); return; }
- sendCommand.mutate({ original, conversation, content: skill ? `/${skill.name} ${rawInput.trim()}` : rawInput.trim(), files, quote: readQuotedMessage(), rawInput, skillName: skill?.name });
- };
- const handleRetrySend = (messageId: string) => {
- const original = captureChatIntent(workspaceOwner, chatActions.view);
- assertChatIntent(original);
- const conversation = chatActions.readConversation(), failed = failedSends.get(messageId);
- if (sendPending() || !conversation || !failed) return;
- sendCommand.mutate({ original, conversation, content: failed.content, files: failed.files, quote: null, retryId: messageId });
- };
-
- const sessionCommandKey = useMemo(() => workspaceOwner.key("chat", "session-command", crypto.randomUUID()), [workspaceOwner]);
- type SessionIntent = { original: ReturnType<typeof captureChatIntent>; conversation: Conversation; channel: string; agentName: string } & ({ kind: "nap" } | { kind: "retry"; taskId: string });
- const sessionCommand = useMutation({ meta: { observabilityAction: "chat.session.command" }, mutationKey: sessionCommandKey, gcTime: 0, scope: { id: JSON.stringify(sessionCommandKey) },
- mutationFn: async (intent: SessionIntent) => {
- assertChatIntent(intent.original);
- if (intent.kind === "retry") {
- const tickets = captureChatLoad(workspaceOwner);
- const newTask = await runChatIntentRequest(intent.original, (options) => retryTaskApi(intent.taskId, workspaceId, options));
- assertChatIntent(intent.original);
- const key = workspaceOwner.key("chat", "task", newTask.id), ticket = tickets.get(JSON.stringify(key))?.receipt;
- if (ticket ? isQueryReceiptCurrent(ticket) : !workspaceOwner.queryClient.getQueryCache().find({ queryKey: key, exact: true })) workspaceOwner.queryClient.setQueryData(key, newTask);
- setActiveTask(workspaceOwner.queryClient.getQueryData<Task>(key) ?? null);
- startPolling(newTask.id, intent.conversation.id);
- return;
- }
- pollState.setState(() => ({ target: null }));
- const newConv = await runChatIntentRequest(intent.original, (options) => createConversationApi(agentId, workspaceId, intent.channel, options));
- assertChatIntent(intent.original);
- setNapMarkers((rows) => [...rows, { agentName: intent.agentName, created_at: newConv.created_at, id: `nap-${intent.conversation.id}` }]);
- setPreviousConversations((rows) => [{ id: intent.conversation.id, created_at: intent.conversation.created_at }, ...rows]);
- setConversation(newConv); setActiveTask(null); setPendingFiles([]);
- setPendingFilesByMessage((rows) => { for (const files of rows.values()) for (const file of files) if (file.thumbnailUrl) URL.revokeObjectURL(file.thumbnailUrl); return new Map(); });
- setFailedSends(new Map()); setStableKeyMap(new Map());
- protocol.setState((state) => ({ ...state, lastSeq: 0, pollFailures: 0, oldestCursor: null }));
- setHasMore(false); scrollToBottom();
- },
- });
- const napping = useIsMutating({ mutationKey: sessionCommandKey, exact: true, predicate: (mutation) => (mutation.state.variables as SessionIntent).kind === "nap" }) > 0;
- const sessionPending = () => workspaceOwner.queryClient.isMutating({ mutationKey: sessionCommandKey, exact: true }) > 0;
- const handleRetryTask = async () => {
- const original = captureChatIntent(workspaceOwner, chatActions.view); assertChatIntent(original);
- const conversation = chatActions.readConversation(), taskId = chatActions.readActiveTaskId();
- if (!conversation || !taskId || sessionPending()) return;
- try { await sessionCommand.mutateAsync({ original, conversation, kind: "retry", taskId, channel: readActiveChannel(), agentName: readAgentName() }); }
- catch (error) { try { assertChatIntent(original); } catch { return; } if (!isChatCancellation(error)) toast.error("Failed to retry the task"); }
- };
-
- const currentConvHasMessages = useMemo(
- () =>
- !!conversation &&
- messages.some((m) => m.conversation_id === conversation.id),
- [conversation, messages],
- );
-
- const handleNap = async () => {
- const original = captureChatIntent(workspaceOwner, chatActions.view); assertChatIntent(original);
- const conversation = chatActions.readConversation();
- if (!conversation || !chatActions.readMessages().some((row) => row.conversation_id === conversation.id) || sessionPending()) return;
- try { await sessionCommand.mutateAsync({ original, conversation, kind: "nap", channel: readActiveChannel(), agentName: readAgentName() }); }
- catch (error) { try { assertChatIntent(original); } catch { return; } if (!isChatCancellation(error)) toast.error("Failed to start new conversation"); }
- };
-
- return {
- chatView: chatActions.view,
- readConversation: chatActions.readConversation,
- // hook-owned state
- conversation,
- messages,
- sending,
- activeTask,
- taskMessages,
- messagesLoading,
- connectionLost,
- hasMore,
- loadingMore,
- artifacts,
- previousConversations,
- hasMoreConversations,
- napMarkers,
- napping,
- pendingFilesByMessage,
- failedSends,
- stableKeyMap,
- // derived
- agentArtifacts,
- agentName,
- timeline,
- groupPositions,
- activeTaskStreamMsgId,
- canLoadMore,
- currentConvHasMessages,
- // refs shared with the JSX
- scrollRef,
- composerRef,
- // handlers
- loadOlderMessages,
- handleScroll,
- handleSend,
- handleRetrySend,
- handleRetryTask,
- handleNap,
- scrollToBottom,
- };
-}
diff --git a/src/web/src/hooks/use-agent-folders.dom.test.tsx b/src/web/src/hooks/use-agent-folders.dom.test.tsx
deleted file mode 100644
index 12e36d5e4..000000000
--- a/src/web/src/hooks/use-agent-folders.dom.test.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import React, { useLayoutEffect } from "react"
-import { QueryClient } from "@tanstack/react-query"
-import { beforeEach, describe, expect, it } from "vitest"
-import { act, render } from "@/test/react-dom-harness"
-import { ApplicationOwnerProvider, createApplicationOwner, retireApplicationOwner, type ApplicationOwner } from "@/lib/application-owner"
-import { useAgentFolders } from "./use-agent-folders"
-
-type Folders = ReturnType<typeof useAgentFolders>
-let owner: ApplicationOwner
-const readers = new Map<string, Folders>()
-function Probe({ name, workspace = "first" }: { name: string; workspace?: string }) {
- const folders = useAgentFolders(workspace)
- useLayoutEffect(() => { readers.set(name, folders) })
- return <output data-testid={name}>{folders.folders.flatMap((folder) => folder.agentIds).join(",")}</output>
-}
-function App({ current = owner, children }: { current?: ApplicationOwner; children: React.ReactNode }) {
- return <ApplicationOwnerProvider owner={current}>{children}</ApplicationOwnerProvider>
-}
-beforeEach(() => {
- localStorage.clear()
- readers.clear()
- owner = createApplicationOwner("folders-A", new QueryClient())
- return () => { retireApplicationOwner(owner); owner.queryClient.clear() }
-})
-
-describe("actual folder preferences and native local expansion", () => {
- it("shares persisted topology between readers while expansion stays with its consumer", () => {
- const view = render(<App><Probe name="left" /><Probe name="right" /><Probe name="other" workspace="second" /></App>)
- act(() => readers.get("left")!.createFolder(["a", "b"]))
- const folder = readers.get("right")!.folders[0]!
- expect(view.getByTestId("left").textContent).toBe("a,b")
- expect(view.getByTestId("right").textContent).toBe("a,b")
- expect(view.getByTestId("other").textContent).toBe("")
- expect(readers.get("left")!.expandedFolderId).toBe(folder.id)
- expect(readers.get("right")!.expandedFolderId).toBeNull()
- expect(JSON.parse(localStorage.getItem("alook:folders-A:ui:agent-sidebar-folders:first")!)).toEqual({ folders: [folder] })
- act(() => readers.get("right")!.addToFolder(folder.id, "c"))
- act(() => readers.get("left")!.addToFolder(folder.id, "c"))
- expect(readers.get("left")!.folders[0]!.agentIds).toEqual(["a", "b", "c"])
- act(() => readers.get("right")!.reorderInFolder(folder.id, ["c", "b", "a"]))
- expect(readers.get("left")!.getTopLevelItems(["z", "a", "c", "b"])).toEqual([
- { type: "agent", id: "z" }, { type: "folder", folder: { id: folder.id, agentIds: ["c", "b", "a"] } },
- ])
- expect(readers.get("right")!.getFolderForAgent("b")?.id).toBe(folder.id)
- expect(readers.get("right")!.getFolderForAgent("z")).toBeNull()
- })
-
- it("merges, removes stale members and dissolves undersized folders without losing ungrouped agents", () => {
- render(<App><Probe name="left" /></App>)
- act(() => readers.get("left")!.createFolder(["a"]))
- expect(readers.get("left")!.folders).toEqual([])
- act(() => readers.get("left")!.createFolder(["a", "b"]))
- act(() => readers.get("left")!.createFolder(["a", "b"]))
- expect(readers.get("left")!.folders).toHaveLength(1)
- act(() => readers.get("left")!.createFolder(["c", "d"]))
- const [first, second] = readers.get("left")!.folders
- act(() => readers.get("left")!.mergeFolders(second!.id, first!.id))
- expect(readers.get("left")!.folders[0]!.agentIds).toEqual(["a", "b", "c", "d"])
- act(() => readers.get("left")!.cleanupStaleAgents(["a", "b", "c"]))
- act(() => readers.get("left")!.removeFromFolder(first!.id, "c"))
- act(() => readers.get("left")!.removeAgentFromAnyFolder("a"))
- expect(readers.get("left")!.folders).toEqual([])
- expect(readers.get("left")!.getTopLevelItems(["a", "b", "c"])).toEqual(["a", "b", "c"].map((id) => ({ type: "agent", id })))
- act(() => readers.get("left")!.createFolder(["a", "b"]))
- const last = readers.get("left")!.folders[0]!
- act(() => readers.get("left")!.dissolveFolder(last.id))
- expect(readers.get("left")!.expandedFolderId).toBeNull()
- })
-
- it("restores only the selected account/workspace and rejects a retired account's late writer", () => {
- localStorage.setItem("agent-sidebar-folders:first", JSON.stringify({ folders: [{ id: "legacy", agentIds: ["wrong", "device"] }] }))
- localStorage.setItem("alook:folders-B:ui:agent-sidebar-folders:first", JSON.stringify({ folders: [{ id: "B-folder", agentIds: ["B1", "B2"] }] }))
- const view = render(<App><Probe name="left" /></App>)
- expect(readers.get("left")!.folders).toEqual([])
- act(() => readers.get("left")!.createFolder(["A1", "A2"]))
- const old = readers.get("left")!
- const before = localStorage.getItem("alook:folders-A:ui:agent-sidebar-folders:first")
- const next = createApplicationOwner("folders-B", new QueryClient())
- act(() => { retireApplicationOwner(owner); view.rerender(<App current={next}><Probe name="left" /></App>) })
- expect(readers.get("left")!.folders[0]!.id).toBe("B-folder")
- act(() => old.addToFolder(old.folders[0]!.id, "late-A"))
- expect(localStorage.getItem("alook:folders-A:ui:agent-sidebar-folders:first")).toBe(before)
- expect(readers.get("left")!.folders[0]!.agentIds).toEqual(["B1", "B2"])
- act(() => view.rerender(<App current={next}><Probe name="left" workspace="second" /></App>))
- expect(readers.get("left")!.folders).toEqual([])
- view.unmount()
- retireApplicationOwner(next)
- next.queryClient.clear()
- })
-})
diff --git a/src/web/src/hooks/use-agent-folders.ts b/src/web/src/hooks/use-agent-folders.ts
deleted file mode 100644
index 945925db9..000000000
--- a/src/web/src/hooks/use-agent-folders.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback } from "react";
-import { useLocalStorage } from "./use-local-storage";
-
-export interface AgentFolder {
- id: string;
- agentIds: string[];
-}
-
-interface FolderState {
- folders: AgentFolder[];
-}
-
-export type TopLevelItem =
- | { type: "agent"; id: string }
- | { type: "folder"; folder: AgentFolder };
-
-const EMPTY_STATE: FolderState = { folders: [] };
-
-export function useAgentFolders(workspaceId: string) {
- const [state, setState] = useLocalStorage<FolderState>(
- `agent-sidebar-folders:${workspaceId}`,
- EMPTY_STATE
- );
- const [expandedFolderId, setExpandedFolderId] = useAtom(useCreateAtom<string | null>(null));
-
- const folders = state.folders;
-
- const getFolderForAgent = useCallback(
- (agentId: string): AgentFolder | null =>
- folders.find((f) => f.agentIds.includes(agentId)) ?? null,
- [folders]
- );
-
- const createFolder = useCallback(
- (agentIds: string[]) => {
- if (agentIds.length < 2) return;
- const id = crypto.randomUUID();
- setState((prev) => {
- const existingAgentIds = new Set(
- prev.folders.flatMap((f) => f.agentIds)
- );
- const clean = agentIds.filter((a) => !existingAgentIds.has(a));
- if (clean.length < 2) return prev;
- return { folders: [...prev.folders, { id, agentIds: clean }] };
- });
- setExpandedFolderId(id);
- },
- [setExpandedFolderId, setState]
- );
-
- const addToFolder = useCallback(
- (folderId: string, agentId: string) => {
- setState((prev) => {
- const alreadyInFolder = prev.folders.some((f) =>
- f.agentIds.includes(agentId)
- );
- if (alreadyInFolder) return prev;
- return {
- folders: prev.folders.map((f) =>
- f.id === folderId
- ? { ...f, agentIds: [...f.agentIds, agentId] }
- : f
- ),
- };
- });
- },
- [setState]
- );
-
- const removeFromFolder = useCallback(
- (folderId: string, agentId: string) => {
- setState((prev) => {
- const updated = prev.folders.map((f) =>
- f.id === folderId
- ? { ...f, agentIds: f.agentIds.filter((id) => id !== agentId) }
- : f
- );
- return { folders: updated.filter((f) => f.agentIds.length > 1) };
- });
- },
- [setState]
- );
-
- const dissolveFolder = useCallback(
- (folderId: string) => {
- setState((prev) => ({
- folders: prev.folders.filter((f) => f.id !== folderId),
- }));
- if (expandedFolderId === folderId) setExpandedFolderId(null);
- },
- [setState, expandedFolderId, setExpandedFolderId]
- );
-
- const reorderInFolder = useCallback(
- (folderId: string, orderedAgentIds: string[]) => {
- setState((prev) => ({
- folders: prev.folders.map((f) =>
- f.id === folderId ? { ...f, agentIds: orderedAgentIds } : f
- ),
- }));
- },
- [setState]
- );
-
- const cleanupStaleAgents = useCallback(
- (validAgentIds: string[]) => {
- const valid = new Set(validAgentIds);
- setState((prev) => {
- const cleaned = prev.folders.map((f) => ({
- ...f,
- agentIds: f.agentIds.filter((id) => valid.has(id)),
- }));
- const surviving = cleaned.filter((f) => f.agentIds.length > 1);
- const changed =
- surviving.length !== prev.folders.length ||
- prev.folders.some(
- (f) => f.agentIds.some((id) => !valid.has(id))
- );
- return changed ? { folders: surviving } : prev;
- });
- },
- [setState]
- );
-
- const getTopLevelItems = useCallback(
- (agentIds: string[]): TopLevelItem[] => {
- const agentToFolder = new Map<string, AgentFolder>();
- for (const f of folders) {
- for (const aid of f.agentIds) {
- agentToFolder.set(aid, f);
- }
- }
-
- const seen = new Set<string>();
- const items: TopLevelItem[] = [];
-
- for (const agentId of agentIds) {
- const folder = agentToFolder.get(agentId);
- if (folder) {
- if (!seen.has(folder.id)) {
- seen.add(folder.id);
- items.push({ type: "folder", folder });
- }
- } else {
- items.push({ type: "agent", id: agentId });
- }
- }
-
- return items;
- },
- [folders]
- );
-
- const mergeFolders = useCallback(
- (sourceFolderId: string, targetFolderId: string) => {
- setState((prev) => {
- const source = prev.folders.find((f) => f.id === sourceFolderId);
- if (!source) return prev;
- return {
- folders: prev.folders
- .map((f) =>
- f.id === targetFolderId
- ? { ...f, agentIds: [...f.agentIds, ...source.agentIds] }
- : f
- )
- .filter((f) => f.id !== sourceFolderId),
- };
- });
- },
- [setState]
- );
-
- const removeAgentFromAnyFolder = useCallback(
- (agentId: string) => {
- setState((prev) => {
- const folder = prev.folders.find((f) => f.agentIds.includes(agentId));
- if (!folder) return prev;
- const updated = prev.folders.map((f) =>
- f.id === folder.id
- ? { ...f, agentIds: f.agentIds.filter((id) => id !== agentId) }
- : f
- );
- return { folders: updated.filter((f) => f.agentIds.length > 1) };
- });
- },
- [setState]
- );
-
- return {
- folders,
- expandedFolderId,
- setExpandedFolderId,
- createFolder,
- addToFolder,
- removeFromFolder,
- dissolveFolder,
- reorderInFolder,
- cleanupStaleAgents,
- getFolderForAgent,
- getTopLevelItems,
- removeAgentFromAnyFolder,
- mergeFolders,
- };
-}
diff --git a/src/web/src/hooks/use-application-sign-out.ts b/src/web/src/hooks/use-application-sign-out.ts
deleted file mode 100644
index 16d47c409..000000000
--- a/src/web/src/hooks/use-application-sign-out.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-"use client"
-
-import { useCallback } from "react"
-import { useMutation, type MutateOptions } from "@tanstack/react-query"
-import { signOutWithOrigin } from "@/lib/auth-client"
-import { applicationKey, assertApplicationOwner, captureApplicationOwner, retireApplicationOwner, useApplicationOwner } from "@/lib/application-owner"
-
-export function useApplicationSignOut() {
- const owner = useApplicationOwner()
- const native = useMutation({ meta: { observabilityAction: "account.sign_out" }, mutationKey: applicationKey(owner, "sign-out"), scope: { id: "account-sign-out" }, gcTime: 0, mutationFn: async (token: ReturnType<typeof captureApplicationOwner>) => {
- assertApplicationOwner(token)
- const controller = new AbortController()
- const subscription = owner.lifecycle.subscribe(() => {
- try { assertApplicationOwner(token) } catch { controller.abort() }
- })
- try {
- const result = await signOutWithOrigin(() => assertApplicationOwner(token), { fetchOptions: { signal: controller.signal, onRequest: () => assertApplicationOwner(token), onSuccess: () => assertApplicationOwner(token) } })
- if (result?.error) { assertApplicationOwner(token); throw new Error(result.error.message || "Failed to log out") }
- if (owner.lifecycle.get().active && owner.lifecycle.get().generation === token.generation) retireApplicationOwner(owner)
- owner.queryClient.clear()
- await owner.retireDisk().catch((error: unknown) => {
- console.error("Application disk cache retirement failed", error)
- })
- const state = owner.lifecycle.get(), viewer = owner.sessionViewer()
- return !state.active && state.generation === token.generation + 1 && (viewer === undefined || viewer === null || viewer === owner.userId)
- } catch (error) {
- assertApplicationOwner(token)
- throw error
- } finally { subscription.unsubscribe() }
- } })
- const capture = useCallback(() => { const token = captureApplicationOwner(owner); assertApplicationOwner(token); return token }, [owner])
- const qualify = useCallback((options?: MutateOptions<boolean, Error, void, unknown>): MutateOptions<boolean, Error, ReturnType<typeof captureApplicationOwner>, unknown> | undefined => {
- if (!options) return undefined
- const successCurrent = (token: ReturnType<typeof captureApplicationOwner>) => {
- const state = token.owner.lifecycle.get(), viewer = token.owner.sessionViewer()
- return !state.active && state.generation === token.generation + 1 && (viewer === undefined || viewer === null || viewer === token.owner.userId)
- }
- const errorCurrent = (token: ReturnType<typeof captureApplicationOwner>) => { try { assertApplicationOwner(token); return true } catch { return false } }
- return {
- onSuccess: (allowed, token, result, context) => { if (allowed && successCurrent(token)) options.onSuccess?.(allowed, undefined, result, context) },
- onError: (error, token, result, context) => { if (errorCurrent(token)) options.onError?.(error, undefined, result, context) },
- onSettled: (allowed, error, token, result, context) => { if (error ? errorCurrent(token) : allowed && successCurrent(token)) options.onSettled?.(allowed, error, undefined, result, context) },
- }
- }, [])
- const nativeMutate = native.mutate, nativeMutateAsync = native.mutateAsync
- const mutate = useCallback((_?: void, options?: MutateOptions<boolean, Error, void, unknown>) => nativeMutate(capture(), qualify(options)), [nativeMutate, capture, qualify])
- const mutateAsync = useCallback((_?: void, options?: MutateOptions<boolean, Error, void, unknown>) => nativeMutateAsync(capture(), qualify(options)), [nativeMutateAsync, capture, qualify])
- return { ...native, mutate, mutateAsync }
-}
diff --git a/src/web/src/hooks/use-chat-sheets.ts b/src/web/src/hooks/use-chat-sheets.ts
deleted file mode 100644
index e0c131fe8..000000000
--- a/src/web/src/hooks/use-chat-sheets.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-"use client"
-
-import { useCallback,useEffect,useMemo } from "react"
-import { createStore,useSelector } from "@tanstack/react-store"
-import { useQuery,isCancelledError } from "@tanstack/react-query"
-import { toast } from "sonner"
-import type { UpdateIssueRequest } from "@alook/shared"
-import { useIssueCommand,usePendingIssueChanges } from "./workspace/use-issue-command"
-import { captureWorkspaceOwner } from "@/contexts/workspace-context"
-import { isAbortError } from "@/lib/errors"
-import type { WorkspaceOwner } from "@/contexts/workspace-context"
-import { workspaceIssueOptions,workspaceTraceOptions,workspaceTaskOptions } from "./workspace/issue-query-options"
-import { useChatArtifactSelection } from "./workspace/use-chat-artifact-selection"
-import { captureChatIntent,assertChatIntent } from "./workspace/use-chat-data"
-type ChatView = Parameters<typeof captureChatIntent>[1]
-export function useChatSheets(owner: WorkspaceOwner, view: ChatView) {
- const store = useMemo(() => createStore({ artifactSheetOpen: false, emailSheetOpen: false, selectedEmailId: null as string | null, calendarEventSheetOpen: false, selectedCalendarEventId: null as string | null, issueSheetOpen: false, selectedIssueId: null as string | null, issueGeneration: 0 }), [])
- const ui = useSelector(store, (state) => state)
- const generation = useSelector(view, (state) => state.generation)
- const capture = useCallback(() => {
- const intent = captureChatIntent(owner, view)
- const state = store.get()
- return () => {
- assertChatIntent(intent)
- const current = store.get()
- if (current.issueGeneration !== state.issueGeneration || current.selectedIssueId !== state.selectedIssueId || !current.issueSheetOpen) throw new DOMException("Retired issue selection", "AbortError")
- }
- }, [owner, view, store])
- const setArtifactSheetOpen = useCallback((value: boolean) => store.setState((state) => ({ ...state, artifactSheetOpen: value })), [store])
- const setEmailSheetOpen = useCallback((value: boolean) => store.setState((state) => ({ ...state, emailSheetOpen: value })), [store])
- const setSelectedEmailId = useCallback((value: string | null) => store.setState((state) => ({ ...state, selectedEmailId: value })), [store])
- const setCalendarEventSheetOpen = useCallback((value: boolean) => store.setState((state) => ({ ...state, calendarEventSheetOpen: value })), [store])
- const setSelectedCalendarEventId = useCallback((value: string | null) => store.setState((state) => ({ ...state, selectedCalendarEventId: value })), [store])
- const setIssueSheetOpen = useCallback((value: boolean) => store.setState((state) => ({ ...state, issueSheetOpen: value, issueGeneration: value === state.issueSheetOpen ? state.issueGeneration : state.issueGeneration + 1 })), [store])
- const setSelectedIssueId = useCallback((value: string | null) => store.setState((state) => ({ ...state, selectedIssueId: value, issueGeneration: state.issueGeneration + 1 })), [store])
- const [selectedArtifact, setSelectedArtifact] = useChatArtifactSelection(owner, view, ui.selectedIssueId)
- const readSource = useMemo(() => {
- const intent = { workspace: captureWorkspaceOwner(owner), view, generation }
- const selected = { generation: ui.issueGeneration, id: ui.selectedIssueId }
- return () => {
- assertChatIntent(intent)
- const current = store.get()
- if (!current.issueSheetOpen || current.issueGeneration !== selected.generation || current.selectedIssueId !== selected.id) throw new DOMException("Retired issue selection", "AbortError")
- }
- }, [owner, view, generation, ui.issueGeneration, ui.selectedIssueId, store])
- const issueQuery = useQuery({ ...workspaceIssueOptions(owner, ui.issueSheetOpen ? ui.selectedIssueId ?? "__none__" : "__none__"), enabled: ui.issueSheetOpen && !!ui.selectedIssueId, subscribed: ui.issueSheetOpen && !!ui.selectedIssueId })
- const pendingIssues = usePendingIssueChanges(owner)
- const issueDetail = useMemo(() => {
- const detail = issueQuery.data
- if (!detail) return null
- return pendingIssues.reduce((current, action) => action.kind === "update" && action.id === current.issue.id ? { ...current, issue: { ...current.issue, ...action.patch } } : current, detail)
- }, [issueQuery.data, pendingIssues])
- const issueConvId = issueDetail?.issue.conversation_id ?? null
- const issueTaskId = issueDetail?.issue.latest_task_id ?? null
- const traceId = issueDetail?.issue.trace_id ?? null
- const taskQuery = useQuery({ ...workspaceTaskOptions(owner, ui.issueSheetOpen ? issueTaskId ?? "__none__" : "__none__"), enabled: ui.issueSheetOpen && !!issueTaskId, subscribed: ui.issueSheetOpen && !!issueTaskId })
- const traceQuery = useQuery({ ...workspaceTraceOptions(owner, ui.issueSheetOpen ? traceId ?? "__none__" : "__none__"), enabled: ui.issueSheetOpen && !!traceId, subscribed: ui.issueSheetOpen && !!traceId })
- useEffect(() => {
- if (issueQuery.isFetching || !issueQuery.error || isAbortError(issueQuery.error) || isCancelledError(issueQuery.error)) return
- try { readSource() } catch { return }
- toast.error(issueQuery.error instanceof Error ? issueQuery.error.message : "Failed to load issue")
- setIssueSheetOpen(false)
- }, [issueQuery.error, issueQuery.isFetching, readSource, setIssueSheetOpen])
- const refetchIssue = issueQuery.refetch
- const openIssue = useCallback(async (issueId: string) => {
- assertChatIntent(captureChatIntent(owner, view))
- const current = store.get()
- const alreadyOpen = current.issueSheetOpen && current.selectedIssueId === issueId
- store.setState((state) => ({ ...state, selectedIssueId: issueId, issueSheetOpen: true, issueGeneration: state.issueGeneration + 1 }))
- if (alreadyOpen) void refetchIssue({ cancelRefetch: false })
- }, [owner, view, store, refetchIssue])
- useEffect(() => {
- const intent = captureChatIntent(owner, view)
- const timers: ReturnType<typeof setTimeout>[] = []
- const defer = (needed: boolean, clear: () => void) => {
- if (!needed) return
- timers.push(setTimeout(() => { try { assertChatIntent(intent); clear() } catch {} }, 300))
- }
- defer(!ui.artifactSheetOpen && !!selectedArtifact, () => setSelectedArtifact(null))
- defer(!ui.emailSheetOpen && !!ui.selectedEmailId, () => setSelectedEmailId(null))
- defer(!ui.calendarEventSheetOpen && !!ui.selectedCalendarEventId, () => setSelectedCalendarEventId(null))
- defer(!ui.issueSheetOpen && !!ui.selectedIssueId, () => setSelectedIssueId(null))
- return () => { for (const timer of timers) clearTimeout(timer) }
- }, [owner, view, ui, selectedArtifact, setSelectedArtifact, setSelectedEmailId, setSelectedCalendarEventId, setSelectedIssueId])
- const { mutateAsync: mutateIssue } = useIssueCommand(owner)
- const updateSelectedIssue = useCallback(async (issueId: string, patch: UpdateIssueRequest) => {
- const assertActive = capture()
- if (issueId !== store.get().selectedIssueId) return
- try { assertActive(); await mutateIssue({ action: { kind: "update", id: issueId, patch }, token: captureWorkspaceOwner(owner) }); assertActive() } catch (error) {
- if (isAbortError(error) || isCancelledError(error)) return
- try { assertActive() } catch { return }
- toast.error(error instanceof Error ? error.message : "Failed to update issue")
- }
- }, [owner, capture, store, mutateIssue])
- return { ...ui, setArtifactSheetOpen, selectedArtifact, setSelectedArtifact, setEmailSheetOpen, setSelectedEmailId, setCalendarEventSheetOpen, setSelectedCalendarEventId, setIssueSheetOpen, setSelectedIssueId,
- issueDetail, issueDetailLoading: issueQuery.isPending && ui.issueSheetOpen, issueTraceTasks: traceQuery.data?.tasks ?? null, issueActiveTask: taskQuery.data ?? null, openIssue, issueConvId, issueTaskId, updateSelectedIssue }
-}
diff --git a/src/web/src/hooks/use-copy-to-clipboard.ts b/src/web/src/hooks/use-copy-to-clipboard.ts
deleted file mode 100644
index b82d80edc..000000000
--- a/src/web/src/hooks/use-copy-to-clipboard.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-"use client";
-
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useRef, useEffect } from "react";
-
-export function useCopyToClipboard(resetDelay = 2000) {
- const [copied, setCopied] = useAtom(useCreateAtom(false));
- const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
-
- const copy = useCallback(
- async (text: string) => {
- try {
- await navigator.clipboard.writeText(text);
- setCopied(true);
- clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setCopied(false), resetDelay);
- return true;
- } catch {
- return false;
- }
- },
- [resetDelay, setCopied]
- );
-
- useEffect(() => {
- return () => clearTimeout(timeoutRef.current);
- }, []);
-
- return { copy, copied };
-}
diff --git a/src/web/src/hooks/use-keyboard-scroll.ts b/src/web/src/hooks/use-keyboard-scroll.ts
deleted file mode 100644
index f006b5ba3..000000000
--- a/src/web/src/hooks/use-keyboard-scroll.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-"use client";
-
-import { useEffect, type RefObject } from "react";
-
-interface VirtualKeyboard extends EventTarget {
- overlaysContent: boolean;
- boundingRect: DOMRect;
-}
-
-export interface KeyboardScrollController {
- handler: () => void;
- cleanup: () => void;
-}
-
-const DEBOUNCE_MS = 150;
-
-/**
- * Creates a resize handler that calculates the keyboard offset from the visual
- * viewport and applies a translateY to shift the input container above the keyboard.
- * Exported for testability — the hook wraps this with lifecycle management.
- */
-export function createKeyboardScrollController(
- getTarget: () => HTMLElement | null,
- isFocused: boolean,
-): KeyboardScrollController {
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
- const handler = () => {
- if (!isFocused) return;
- clearTimeout(timeoutId);
- timeoutId = setTimeout(() => {
- const el = getTarget();
- if (!el) return;
- const vv = window.visualViewport;
- if (!vv) {
- el.scrollIntoView({ block: "end", behavior: "smooth" });
- return;
- }
- const keyboardHeight = window.innerHeight - vv.height;
- const inputContainer = el.closest(
- "[data-keyboard-offset]",
- ) as HTMLElement | null;
- if (inputContainer && keyboardHeight > 0) {
- // Calculate how much of the container is hidden behind the keyboard.
- // Only shift enough to keep it visible, not the full keyboard height.
- const rect = inputContainer.getBoundingClientRect();
- const overflow = rect.bottom - vv.height - vv.offsetTop;
- if (overflow > 0) {
- inputContainer.style.transform = `translateY(-${overflow}px)`;
- inputContainer.setAttribute("data-keyboard-active", "");
- } else {
- inputContainer.style.transform = "";
- inputContainer.removeAttribute("data-keyboard-active");
- }
- } else if (inputContainer) {
- inputContainer.style.transform = "";
- inputContainer.removeAttribute("data-keyboard-active");
- } else {
- el.scrollIntoView({ block: "end", behavior: "smooth" });
- }
- }, DEBOUNCE_MS);
- };
- const cleanup = () => {
- clearTimeout(timeoutId);
- const el = getTarget();
- if (!el) return;
- const inputContainer = el.closest(
- "[data-keyboard-offset]",
- ) as HTMLElement | null;
- if (inputContainer) {
- inputContainer.style.transform = "";
- inputContainer.removeAttribute("data-keyboard-active");
- }
- };
- return { handler, cleanup };
-}
-
-/**
- * Subscribes to visualViewport resize and scroll events. On iOS Safari the
- * virtual keyboard shrinks the visual viewport without reflowing the layout,
- * so fixed/sticky elements at the bottom can be hidden behind the keyboard.
- * This handler applies a translateY offset to move the input above the keyboard.
- *
- * Returns null if visualViewport is unavailable (SSR or unsupported browser).
- * Exported for testability without React rendering.
- */
-export function attachKeyboardScroll(
- getTarget: () => HTMLElement | null,
- isFocused: boolean,
-): (() => void) | null {
- const vv =
- typeof window !== "undefined" ? window.visualViewport : undefined;
- if (!vv) return null;
- const { handler, cleanup } = createKeyboardScrollController(
- getTarget,
- isFocused,
- );
- vv.addEventListener("resize", handler);
- vv.addEventListener("scroll", handler);
- return () => {
- vv.removeEventListener("resize", handler);
- vv.removeEventListener("scroll", handler);
- cleanup();
- };
-}
-
-/**
- * On Chromium (Android Chrome 94+), uses the VirtualKeyboard API with CSS
- * env(keyboard-inset-height) for a smoother native experience.
- * Falls back to visualViewport + translateY for iOS Safari/Chrome.
- */
-function attachVirtualKeyboardAPI(
- getTarget: () => HTMLElement | null,
- isFocused: boolean,
-): (() => void) | null {
- if (typeof window === "undefined") return null;
- const vk = (navigator as unknown as { virtualKeyboard?: VirtualKeyboard }).virtualKeyboard;
- if (!vk) return null;
-
- vk.overlaysContent = true;
-
- const inputContainer = getTarget()?.closest(
- "[data-keyboard-offset]",
- ) as HTMLElement | null;
- if (!inputContainer) return null;
-
- const onGeometryChange = () => {
- if (!isFocused) {
- inputContainer.style.transform = "";
- inputContainer.removeAttribute("data-keyboard-active");
- return;
- }
- const { height } = vk.boundingRect;
- if (height > 0) {
- inputContainer.style.transform = `translateY(-${height}px)`;
- inputContainer.setAttribute("data-keyboard-active", "");
- } else {
- inputContainer.style.transform = "";
- inputContainer.removeAttribute("data-keyboard-active");
- }
- };
-
- vk.addEventListener("geometrychange", onGeometryChange);
- return () => {
- vk.removeEventListener("geometrychange", onGeometryChange);
- inputContainer.style.transform = "";
- inputContainer.removeAttribute("data-keyboard-active");
- vk.overlaysContent = false;
- };
-}
-
-/**
- * On iOS Safari, the virtual keyboard can push the focused input off-screen
- * because the layout viewport doesn't always resize in sync with the visual
- * viewport. This hook listens to `window.visualViewport` resize events and
- * applies a translateY offset to the nearest [data-keyboard-offset] ancestor.
- *
- * On Android Chrome 94+, uses VirtualKeyboard API for smoother handling.
- * No-op when `visualViewport` is unavailable or the editor isn't focused.
- */
-export function useKeyboardScroll(
- targetRef: RefObject<HTMLElement | null>,
- isFocused: boolean,
-) {
- useEffect(() => {
- // Try VirtualKeyboard API first (Android Chrome 94+)
- const vkDetach = attachVirtualKeyboardAPI(
- () => targetRef.current,
- isFocused,
- );
- if (vkDetach) return vkDetach;
-
- // Fallback: visualViewport resize (iOS Safari/Chrome)
- const detach = attachKeyboardScroll(() => targetRef.current, isFocused);
- return detach ?? undefined;
- }, [targetRef, isFocused]);
-}
diff --git a/src/web/src/hooks/use-local-storage.dom.test.tsx b/src/web/src/hooks/use-local-storage.dom.test.tsx
deleted file mode 100644
index a92bd1199..000000000
--- a/src/web/src/hooks/use-local-storage.dom.test.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
-import { act, render, waitFor } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider, useApplicationOwner, type ApplicationOwner } from "@/lib/application-owner"
-import { useLocalStorage } from "./use-local-storage"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
-const identity = vi.hoisted(() => ({ user: "A" }))
-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: identity.user } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-let owner: ApplicationOwner
-const values: Record<string, [string, (value: string | ((previous: string) => string)) => void]> = {}
-const counts: Record<string, number> = {}
-function Probe({ name, stateKey = "shared" }: { name: string; stateKey?: string }) { const currentOwner = useApplicationOwner(), value = useLocalStorage(stateKey, "default"); useLayoutEffect(() => { owner = currentOwner; values[name] = value; counts[name] = (counts[name] ?? 0) + 1 }); return null }
-function App({ user = "A", children }: { user?: string; children: React.ReactNode }) { return <ApplicationQueryProvider userId={user}>{children}</ApplicationQueryProvider> }
-beforeEach(async () => { await clearAllPersistedCaches(); localStorage.clear(); identity.user = "A"; for (const key of Object.keys(values)) delete values[key]; for (const key of Object.keys(counts)) delete counts[key] })
-afterEach(() => owner?.queryClient.clear())
-describe("original-account native persisted UI", () => {
- it("an inline object default preserves the current draft across renders", () => {
- let value!: ReturnType<typeof useLocalStorage<{ text: string }>>
- function ObjectProbe() { const current = useLocalStorage("object", { text: "default" }); useLayoutEffect(() => { value = current }); return null }
- const mounted = render(<App><ObjectProbe /></App>)
- act(() => value[1]({ text: "edited" }))
- act(() => mounted.rerender(<App><ObjectProbe /></App>))
- expect(value[0]).toEqual({ text: "edited" })
- })
- it("one key has one Store value shared by two consumers and a functional write", async () => {
- render(<App><Probe name="first" /><Probe name="second" /></App>); await waitFor(() => expect(values.second).toBeDefined())
- act(() => values.first[1]((value) => `${value} changed`)); expect(values.first[0]).toBe("default changed"); expect(values.second[0]).toBe("default changed"); expect(localStorage.getItem("alook:A:ui:shared")).toBe(JSON.stringify("default changed"))
- })
- it("a key change gets its own initial value without borrowing the previous key", async () => {
- const mounted = render(<App><Probe name="first" /></App>); await waitFor(() => expect(values.first).toBeDefined()); act(() => values.first[1]("old"));
- act(() => mounted.rerender(<App><Probe name="first" stateKey="next" /></App>)); expect(values.first[0]).toBe("default")
- })
- it("unqualified old device value is ignored and a qualified value hydrates", async () => {
- localStorage.setItem("shared", JSON.stringify("unqualified")); localStorage.setItem("alook:A:ui:shared", JSON.stringify("qualified"));
- render(<App><Probe name="first" /></App>); await waitFor(() => expect(values.first?.[0]).toBe("qualified"))
- })
- it("switching account rejects the old setter and hydrates only B", async () => {
- localStorage.setItem("alook:B:ui:shared", JSON.stringify("B value")); const mounted = render(<App><Probe name="first" /></App>); await waitFor(() => expect(values.first).toBeDefined());
- act(() => values.first[1]("A value")); const oldSet = values.first[1]; identity.user = "B";
- act(() => mounted.rerender(<App user="B"><Probe name="first" /></App>)); await waitFor(() => expect(values.first[0]).toBe("B value")); act(() => oldSet("late A"));
- expect(values.first[0]).toBe("B value"); expect(localStorage.getItem("alook:A:ui:shared")).toBe(JSON.stringify("A value"))
- })
- it("storage updates notify both readers and unrelated keys leave the selected reader stable", async () => {
- render(<App><Probe name="first" /><Probe name="second" /><Probe name="other" stateKey="other" /></App>); await waitFor(() => expect(values.other).toBeDefined()); const before = counts.first;
- act(() => values.other[1]("changed other")); expect(counts.first).toBe(before);
- act(() => { localStorage.setItem("alook:A:ui:shared", JSON.stringify("external")); window.dispatchEvent(new StorageEvent("storage", { key: "alook:A:ui:shared" })) }); expect(values.first[0]).toBe("external"); expect(values.second[0]).toBe("external")
- })
- it("Strict lifecycle replay keeps the current qualified setter usable", async () => {
- render(<React.StrictMode><App><Probe name="first" /></App></React.StrictMode>); await waitFor(() => expect(values.first).toBeDefined()); act(() => values.first[1]("strict current")); expect(values.first[0]).toBe("strict current")
- })
-})
diff --git a/src/web/src/hooks/use-local-storage.ts b/src/web/src/hooks/use-local-storage.ts
deleted file mode 100644
index cb9d7dcbb..000000000
--- a/src/web/src/hooks/use-local-storage.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-"use client"
-
-import { useMemo, useLayoutEffect, useCallback } from "react"
-import { useCreateAtom, useSelector } from "@tanstack/react-store"
-import { useApplicationOwner, assertApplicationOwner } from "@/lib/application-owner"
-
-export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((prev: T) => T)) => void] {
- const owner = useApplicationOwner()
- const generation = useSelector(owner.lifecycle, (state) => state.generation)
- const token = useMemo(() => ({ owner, generation }), [owner, generation])
- const storageKey = `alook:${owner.userId}:ui:${key}`
- const defaults = useCreateAtom({ owner, key, value: initialValue })
- const committedDefault = useSelector(defaults, (state) => state)
- const fallback = committedDefault.owner === owner && committedDefault.key === key ? committedDefault.value : initialValue
- useLayoutEffect(() => {
- if (defaults.get().owner !== owner || defaults.get().key !== key) defaults.set({ owner, key, value: initialValue })
- }, [defaults, owner, key, initialValue])
- const stored = useSelector(owner.preferences, (state) => state.localValues.has(key) ? state.localValues.get(key) as T : fallback)
- useLayoutEffect(() => {
- const hydrate = () => {
- try { assertApplicationOwner(token) } catch { return }
- let next = fallback
- try { const item = localStorage.getItem(storageKey); if (item !== null) next = JSON.parse(item) as T } catch {}
- owner.preferences.setState((state) => {
- if (Object.is(state.localValues.get(key), next) && state.localValues.has(key)) return state
- const localValues = new Map(state.localValues); localValues.set(key, next)
- return { ...state, localValues }
- })
- }
- hydrate()
- const onStorage = (event: StorageEvent) => { if (event.key === storageKey || event.key === null) hydrate() }
- window.addEventListener("storage", onStorage)
- return () => window.removeEventListener("storage", onStorage)
- }, [owner, token, key, storageKey, fallback])
- const setValue = useCallback((value: T | ((prev: T) => T)) => {
- try { assertApplicationOwner(token) } catch { return }
- const previous = owner.preferences.get().localValues.has(key) ? owner.preferences.get().localValues.get(key) as T : fallback
- const next = typeof value === "function" ? (value as (prev: T) => T)(previous) : value
- owner.preferences.setState((state) => { const localValues = new Map(state.localValues); localValues.set(key, next); return { ...state, localValues } })
- try { localStorage.setItem(storageKey, JSON.stringify(next)) } catch {}
- }, [owner, token, key, storageKey, fallback])
- return [stored, setValue]
-}
diff --git a/src/web/src/hooks/use-message-flags.ts b/src/web/src/hooks/use-message-flags.ts
deleted file mode 100644
index 05469d8b0..000000000
--- a/src/web/src/hooks/use-message-flags.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-"use client"
-
-import { useCallback, useMemo } from "react"
-import { useMutation, useQuery } from "@tanstack/react-query"
-import { flagMessage, unflagMessage, listFlaggedMessageIds } from "@/lib/api"
-import { isAbortError } from "@/lib/errors"
-import { useFlagCount } from "@/contexts/flag-count-context"
-import { assertApplicationOwner } from "@/lib/application-owner"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, type WorkspaceOwner } from "@/contexts/workspace-context"
-import type { ChatFlagsData } from "@/lib/workspace-chat-flags"
-import { assertChatIntent, captureChatIntent } from "./workspace/use-chat-data"
-
-type ChatView = Parameters<typeof captureChatIntent>[1]
-const EMPTY_IDS: string[] = []
-export function useMessageFlags(owner: WorkspaceOwner, view: ChatView, conversationId: string | null) {
- const key = useMemo(() => owner.key("chat", "flags", conversationId ?? "__none__"), [owner, conversationId])
- const readIntent = useMemo(() => captureWorkspaceOwner(owner), [owner])
- const query = useQuery({ queryKey: key, enabled: !!conversationId, staleTime: 30_000,
- queryFn: async ({ signal }) => {
- assertWorkspaceOwner(readIntent, signal)
- const requestRevision = owner.queryClient.getQueryData<ChatFlagsData>(key)?.revision ?? 0
- const data = await listFlaggedMessageIds(owner.workspaceId, conversationId!, workspaceRequestOptions(readIntent, signal))
- assertWorkspaceOwner(readIntent, signal)
- return { ids: data.message_ids, requestRevision } satisfies ChatFlagsData
- },
- })
- const { begin, rollback, refresh } = useFlagCount()
- const mutation = useMutation({ meta: { observabilityAction: "message.flag.toggle" }, scope: { id: `${owner.application.userId}:${owner.workspaceId}:flags:${conversationId}` },
- mutationFn: async ({ messageId, intent }: { messageId: string; intent: ReturnType<typeof captureChatIntent> }) => {
- assertChatIntent(intent)
- await owner.queryClient.cancelQueries({ queryKey: key, exact: true })
- assertChatIntent(intent)
- const wasFlagged = (owner.queryClient.getQueryData<ChatFlagsData>(key)?.ids ?? EMPTY_IDS).includes(messageId)
- const publish = (flagged: boolean) => {
- let writeRevision = 0
- owner.queryClient.setQueryData<ChatFlagsData>(key, (previous) => {
- const ids = new Set(previous?.ids ?? EMPTY_IDS)
- if (flagged) ids.add(messageId); else ids.delete(messageId)
- const revision = (previous?.revision ?? 0) + 1
- writeRevision = revision
- return { ...previous, ids: [...ids], revision, writes: { ...previous?.writes, [messageId]: { flagged, revision } } }
- })
- return writeRevision
- }
- const optimisticRevision = publish(!wasFlagged)
- const flagsResource = owner.queryClient.getQueryCache().find({ queryKey: key, exact: true })
- const countTicket = begin(wasFlagged ? -1 : 1)
- try {
- const options = workspaceRequestOptions(captureWorkspaceOwner(owner), undefined, () => assertChatIntent(intent))
- if (wasFlagged) await unflagMessage(owner.workspaceId, messageId, options)
- else await flagMessage(owner.workspaceId, messageId, options)
- assertChatIntent(intent)
- refresh()
- } catch (error) {
- try { assertApplicationOwner(intent.workspace.application) } catch { return }
- const sameFlagsResource = !!flagsResource && owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === flagsResource
- if (sameFlagsResource && owner.queryClient.getQueryData<ChatFlagsData>(key)?.writes?.[messageId]?.revision === optimisticRevision) publish(wasFlagged)
- rollback(countTicket)
- await Promise.all([
- sameFlagsResource ? owner.queryClient.invalidateQueries({ queryKey: key, exact: true, refetchType: "none" }) : Promise.resolve(),
- countTicket.query && owner.queryClient.getQueryCache().find({ queryKey: owner.key("flag-count"), exact: true }) === countTicket.query ? owner.queryClient.invalidateQueries({ queryKey: owner.key("flag-count"), exact: true, refetchType: "none" }) : Promise.resolve(),
- ])
- if (isAbortError(error)) return
- }
- },
- })
- const mutateFlag = mutation.mutateAsync
- const handleToggleFlag = useCallback(async (messageId: string) => {
- if (!conversationId) return
- const intent = captureChatIntent(owner, view)
- try { await mutateFlag({ messageId, intent }) } catch (error) { if (!isAbortError(error)) throw error }
- }, [owner, view, conversationId, mutateFlag])
- const flaggedIds = useMemo(() => new Set(query.data?.ids ?? EMPTY_IDS), [query.data])
- return { flaggedIds, handleToggleFlag }
-}
diff --git a/src/web/src/hooks/use-slash-command.ts b/src/web/src/hooks/use-slash-command.ts
deleted file mode 100644
index 342735a70..000000000
--- a/src/web/src/hooks/use-slash-command.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-import { useAtom, useCreateAtom, type Atom } from "@tanstack/react-store";
-import { useCallback, useMemo, useRef, useEffect } from "react"
-import type { SkillEntry } from "@alook/shared"
-import type { AnchorRect, AnchorRectResolver } from "@/hooks/use-anchored-popover"
-
-/**
- * Minimal keyboard-event shape the popup hooks need. Both React synthetic
- * events and native KeyboardEvents (from TipTap's editorProps.handleKeyDown,
- * wrapped) satisfy it, so the same hook drives the textarea and the composer.
- */
-export interface PopupKeyEvent {
- key: string
- isComposing: boolean
- preventDefault: () => void
-}
-
-export interface SlashCommandPopupState {
- isOpen: boolean
- query: string
- selectedIndex: number
- getAnchorRect: AnchorRectResolver
- skills: SkillEntry[]
- activeSkill: SkillEntry | null
- handleSlashKeyDown: (e: PopupKeyEvent) => boolean
- selectSkill: (skill: SkillEntry) => void
- clearActiveSkill: () => void
- setActiveSkill: (skill: SkillEntry | null) => void
-}
-
-interface UseSlashCommandParams {
- input: string
- caretIndex: number | null
- skills: SkillEntry[]
- onInputChange: (value: string) => void
- initialActiveSkill?: SkillEntry | null
- activeSkillNameAtom?: Atom<string | null>
- /**
- * Resolve the popup's viewport-relative caret rect for the
- * slash trigger at `triggerStart`. The TipTap composer computes this from
- * `editor.view.coordsAtPos`; returns null if it cannot be resolved yet.
- */
- getAnchorPos: (triggerStart: number) => AnchorRect | null
- /** Called after a skill is selected so the caller can re-focus its editor. */
- onAfterSelect?: () => void
-}
-
-const MAX_QUERY_LENGTH = 30
-
-function findSlashTrigger(input: string, caretIndex: number): { start: number; query: string } | null {
- if (!input.startsWith("/")) return null
- if (caretIndex === 0) return null
- let i = caretIndex - 1
- while (i >= 0 && caretIndex - i <= MAX_QUERY_LENGTH) {
- const ch = input.charCodeAt(i)
- if (ch === 47 && i === 0) { // '/' at position 0 only
- return { start: 0, query: input.slice(1, caretIndex) }
- }
- if (ch === 10 || ch === 13 || ch === 32) return null
- i--
- }
- return null
-}
-
-export function useSlashCommand({
- input,
- caretIndex,
- skills,
- onInputChange,
- initialActiveSkill,
- activeSkillNameAtom,
- getAnchorPos,
- onAfterSelect,
-}: UseSlashCommandParams): SlashCommandPopupState {
- const [isOpen, setIsOpen] = useAtom(useCreateAtom(false))
- const [query, setQuery] = useAtom(useCreateAtom(""))
- const [selectedIndex, setSelectedIndex] = useAtom(useCreateAtom(0))
- const triggerStartRef = useRef<number | null>(null)
-
- const filteredSkills = useMemo(() => {
- if (!isOpen) return []
- if (!query) return skills
- const q = query.toLowerCase()
- const startsWith: SkillEntry[] = []
- const includes: SkillEntry[] = []
- for (const s of skills) {
- const name = s.name.toLowerCase()
- if (name.startsWith(q)) startsWith.push(s)
- else if (name.includes(q)) includes.push(s)
- }
- return [...startsWith, ...includes]
- }, [isOpen, query, skills])
-
- useEffect(() => {
- setSelectedIndex(0)
- }, [filteredSkills.length, query, setSelectedIndex])
-
- const localActiveSkill = useCreateAtom<string | null>(initialActiveSkill?.name ?? null)
- const [activeSkillName, setActiveSkillName] = useAtom(activeSkillNameAtom ?? localActiveSkill)
- const activeSkill = skills.find((skill) => skill.name === activeSkillName) ?? null
- const setActiveSkill = useCallback((skill: SkillEntry | null) => setActiveSkillName(skill?.name ?? null), [setActiveSkillName])
-
- useEffect(() => {
- if (activeSkill) {
- setIsOpen(false)
- return
- }
- if (caretIndex === null) {
- setIsOpen(false)
- return
- }
-
- const trigger = findSlashTrigger(input, caretIndex)
- if (trigger) {
- triggerStartRef.current = trigger.start
- setQuery(trigger.query)
- setIsOpen(true)
-
- } else {
- setIsOpen(false)
- triggerStartRef.current = null
- }
- }, [input, caretIndex, getAnchorPos, activeSkill, setIsOpen, setQuery])
-
- const getAnchorRect = useCallback<AnchorRectResolver>(() => {
- const triggerStart = triggerStartRef.current
- if (triggerStart === null) return null
- return getAnchorPos(triggerStart)
- }, [getAnchorPos])
-
- const selectSkill = useCallback((skill: SkillEntry) => {
- setActiveSkill(skill)
- onInputChange("")
- setIsOpen(false)
- onAfterSelect?.()
- }, [setActiveSkill, onInputChange, setIsOpen, onAfterSelect])
-
- const clearActiveSkill = useCallback(() => {
- setActiveSkill(null)
- }, [setActiveSkill])
-
- const handleSlashKeyDown = useCallback((e: PopupKeyEvent): boolean => {
- if (!isOpen || filteredSkills.length === 0) return false
- if (e.isComposing) return false
-
- if (e.key === "ArrowDown") {
- e.preventDefault()
- setSelectedIndex(i => (i + 1) % filteredSkills.length)
- return true
- }
- if (e.key === "ArrowUp") {
- e.preventDefault()
- setSelectedIndex(i => (i - 1 + filteredSkills.length) % filteredSkills.length)
- return true
- }
- if (e.key === "Enter" || e.key === "Tab") {
- e.preventDefault()
- selectSkill(filteredSkills[selectedIndex])
- return true
- }
- if (e.key === "Escape") {
- e.preventDefault()
- setIsOpen(false)
- return true
- }
- return false
- }, [isOpen, filteredSkills, setSelectedIndex, selectSkill, selectedIndex, setIsOpen])
-
- return {
- isOpen,
- query,
- selectedIndex,
- getAnchorRect,
- skills: filteredSkills,
- activeSkill,
- handleSlashKeyDown,
- selectSkill,
- clearActiveSkill,
- setActiveSkill,
- }
-}
diff --git a/src/web/src/hooks/use-text-selection-quote.ts b/src/web/src/hooks/use-text-selection-quote.ts
deleted file mode 100644
index 3fe8783ba..000000000
--- a/src/web/src/hooks/use-text-selection-quote.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useEffect } from "react";
-
-export type SelectionPopup = {
- text: string;
- messageId: string | null;
- x: number;
- y: number;
-} | null;
-
-/**
- * Owns the "quote selected text" popup: tracks the current text selection
- * (only inside `[data-quote-source]` regions) and positions the popup, via a
- * document `selectionchange` listener.
- *
- * Extracted verbatim from agent-chat-view.tsx. Call this hook at the SAME
- * position the `selectionchange` effect previously occupied so its registration
- * order is preserved. The `selectionPopup` state + raw `setSelectionPopup`
- * setter are returned so the component's quote handler (which also writes the
- * composer draft + focuses the editor) stays byte-identical.
- */
-export function useTextSelectionQuote() {
- const [selectionPopup, setSelectionPopup] = useAtom(useCreateAtom<SelectionPopup>(null));
-
- const handleTextSelect = useCallback(() => {
- const selection = window.getSelection();
- if (!selection || selection.isCollapsed || !selection.rangeCount) {
- setSelectionPopup(null);
- return;
- }
- const text = selection.toString().trim();
- if (!text) {
- setSelectionPopup(null);
- return;
- }
- // Only allow quoting from assistant message bubbles
- const range = selection.getRangeAt(0);
- const container =
- range.commonAncestorContainer instanceof HTMLElement
- ? range.commonAncestorContainer
- : range.commonAncestorContainer.parentElement;
- const quoteSource = container?.closest("[data-quote-source]");
- if (!quoteSource) {
- setSelectionPopup(null);
- return;
- }
- const msgEl = quoteSource.closest("[data-message-id]");
- const messageId = msgEl?.getAttribute("data-message-id") ?? null;
- const rects = range.getClientRects();
- const lastRect = rects[rects.length - 1] || range.getBoundingClientRect();
- setSelectionPopup({ text, messageId, x: lastRect.right, y: lastRect.top - 4 });
- }, [setSelectionPopup]);
-
- useEffect(() => {
- document.addEventListener("selectionchange", handleTextSelect);
- return () =>
- document.removeEventListener("selectionchange", handleTextSelect);
- }, [handleTextSelect]);
-
- return { selectionPopup, setSelectionPopup };
-}
diff --git a/src/web/src/hooks/workspace/calendar-page.dom.test.tsx b/src/web/src/hooks/workspace/calendar-page.dom.test.tsx
deleted file mode 100644
index 0f18c3440..000000000
--- a/src/web/src/hooks/workspace/calendar-page.dom.test.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
-import { act, render, waitFor, screen, fireEvent } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider, useWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
-import CalendarPage from "@/app/(app)/w/[slug]/calendar/page"
-const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }))
-vi.mock("sonner", () => ({ toast }))
-const search = new URLSearchParams("y=2026&m=9")
-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }), useSearchParams: () => search, usePathname: () => "/w/workspace/calendar" }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: "calendar-user" } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-const agents = [{ id: "agent", name: "Agent", avatar_url: null }]
-const subscribeWs = () => () => {}
-vi.mock("@/contexts/agent-context", () => ({ useAgentContext: () => ({ agents, subscribeWs }) }))
-vi.mock("@/components/ui/markdown-editor", () => ({ MarkdownEditor: () => null }))
-let owner: WorkspaceOwner
-let held: Array<{ path: string; method: string; body?: string; resolve: (response: Response) => void; signal: AbortSignal }>
-const response = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } })
-function Probe() { const current = useWorkspaceOwner(); useLayoutEffect(() => { owner = current }); return <CalendarPage /> }
-function App() { return <ApplicationQueryProvider userId="calendar-user"><WorkspaceProvider workspaceId="workspace" slug="workspace"><Probe /></WorkspaceProvider></ApplicationQueryProvider> }
-beforeEach(async () => { await clearAllPersistedCaches(); vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }))); held = []; toast.error.mockClear(); toast.success.mockClear(); vi.stubGlobal("fetch", vi.fn((path: string, options: RequestInit) => new Promise<Response>((resolve) => held.push({ path, method: options.method ?? "GET", body: options.body as string | undefined, resolve, signal: options.signal as AbortSignal })))) })
-afterEach(async () => {
- await act(async () => {
- vi.unstubAllGlobals(); owner?.queryClient.clear()
- })
-})
-describe("native calendar page resource ownership", () => {
- it("changing range cancels the old native read before its late 401", async () => {
- render(<App />); await waitFor(() => expect(held).toHaveLength(1)); const real = window, assign = vi.fn(); vi.stubGlobal("window", new Proxy(real, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }));
- act(() => fireEvent.click(screen.getByRole("button", { name: "Next month" }))); await waitFor(() => expect(held).toHaveLength(2)); expect(held[0].signal.aborted).toBe(true);
- await act(async () => { held[0].resolve(response({}, 401)); held[1].resolve(response([])) }); await waitFor(() => expect(screen.getByRole("grid", { name: "Calendar November 2026" })).toBeTruthy()); expect(assign).not.toHaveBeenCalled(); expect(toast.error).not.toHaveBeenCalled()
- })
- it("creates from the actual sheet form and publishes into the native range", async () => {
- render(<App />); await waitFor(() => expect(held).toHaveLength(1)); await act(async () => held[0].resolve(response([])));
- act(() => fireEvent.click(screen.getByRole("button", { name: "New event" }))); await waitFor(() => expect(screen.getByRole("textbox", { name: "Event title" })).toBeTruthy()); act(() => fireEvent.change(screen.getByRole("textbox", { name: "Event title" }), { target: { value: "Created event" } })); act(() => fireEvent.click(screen.getByRole("button", { name: /Create event/ })));
- await waitFor(() => expect(held.some((request) => request.method === "POST")).toBe(true)); const request = held.find((item) => item.method === "POST")!, values = JSON.parse(request.body!); const created = { id: "created", ...values, repeat_interval: null, repeat_stop_at: null, status: "pending" };
- await act(async () => request.resolve(response(created))); await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Event created")); const queries = owner.queryClient.getQueryCache().findAll({ queryKey: owner.key("calendar", "range") }); expect(queries.some((query) => Array.isArray(query.state.data) && query.state.data.some((row) => row.id === "created"))).toBe(true); expect(screen.queryByRole("textbox", { name: "Event title" })).toBeNull()
- })
-})
diff --git a/src/web/src/hooks/workspace/chat-event-resources.dom.test.tsx b/src/web/src/hooks/workspace/chat-event-resources.dom.test.tsx
deleted file mode 100644
index 2c064c115..000000000
--- a/src/web/src/hooks/workspace/chat-event-resources.dom.test.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { beforeEach, afterEach, describe, it, expect, vi } from "vitest"
-import { act, render, waitFor, screen, fireEvent } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider, useWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
-import { EmailEventSheet } from "@/components/agent-chat/email-event-sheet"
-import { CalendarEventSheet } from "@/components/calendar/calendar-event-sheet"
-import { EmailCard } from "@/components/agent-chat/event-cards/email-card"
-import { useSlashCommand } from "@/hooks/use-slash-command"
-import type { Agent, SkillEntry } from "@alook/shared"
-
-const error = vi.hoisted(() => vi.fn())
-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: "event-user" } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("sonner", () => ({ toast: { error } }))
-vi.mock("@/components/ui/markdown-editor", () => ({ MarkdownEditor: () => null }))
-let owner: WorkspaceOwner
-let requests: Array<{ path: string; resolve: (response: Response) => void }>
-const changed = vi.fn()
-function Probe({ children }: { children: React.ReactNode }) { const current = useWorkspaceOwner(); useLayoutEffect(() => { owner = current }); return children }
-function App({ children }: { children: React.ReactNode }) { return <ApplicationQueryProvider userId="event-user"><WorkspaceProvider workspaceId="workspace" slug="workspace"><Probe>{children}</Probe></WorkspaceProvider></ApplicationQueryProvider> }
-const reply = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } })
-const email = (id: string) => ({ id, subject: `Subject ${id}`, from_email: "[email protected]", to_email: "[email protected]", created_at: "2026-10-01T00:00:00Z", attachments: [] })
-const calendar = (id: string) => ({ id, title: `Event ${id}`, agent_id: "agent", scheduled_at: "2026-10-03T09:00:00Z", description: "description", repeat_interval: null, repeat_stop_at: null })
-function navigationSpy() { const real = window, assign = vi.fn(); vi.stubGlobal("window", new Proxy(real, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } })); return assign }
-beforeEach(async () => { await clearAllPersistedCaches(); owner = undefined as unknown as WorkspaceOwner; requests = []; changed.mockClear(); error.mockClear(); vi.stubGlobal("fetch", vi.fn((path: string) => new Promise<Response>((resolve) => requests.push({ path, resolve })))) })
-afterEach(async () => {
- await act(async () => {
- vi.unstubAllGlobals(); owner?.queryClient.clear()
- })
-})
-
-describe("native chat event resources", () => {
- it("retired email metadata and body 401 cannot navigate or close B", async () => {
- const mounted = render(<App><EmailEventSheet open emailId="A" workspaceId="workspace" onOpenChange={changed} /></App>)
- await waitFor(() => expect(requests).toHaveLength(2))
- const assign = navigationSpy()
- act(() => mounted.rerender(<App><EmailEventSheet open emailId="B" workspaceId="workspace" onOpenChange={changed} /></App>))
- await waitFor(() => expect(requests).toHaveLength(4))
- await act(async () => { requests[0].resolve(reply({}, 401)); requests[1].resolve(reply({}, 401)); requests[2].resolve(reply(email("B"))); requests[3].resolve(new Response("body B")) })
- await waitFor(() => expect(screen.getByText("Subject B")).toBeTruthy())
- expect(screen.getByText("body B")).toBeTruthy()
- expect(assign).not.toHaveBeenCalled(); expect(changed).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled()
- expect(owner.queryClient.getQueryData(owner.key("emails", "detail", "A"))).toBeUndefined()
- expect(owner.queryClient.getQueryData(owner.key("emails", "body", "B"))).toEqual({ content: "body B", isHtml: false })
- })
- it("closed email drops held responses and native cancellation stays silent", async () => {
- const mounted = render(<App><EmailEventSheet open emailId="A" workspaceId="workspace" onOpenChange={changed} /></App>)
- await waitFor(() => expect(requests).toHaveLength(2))
- const assign = navigationSpy()
- act(() => mounted.rerender(<App><EmailEventSheet open={false} emailId="A" workspaceId="workspace" onOpenChange={changed} /></App>))
- await act(async () => { requests[0].resolve(reply({}, 401)); requests[1].resolve(reply({}, 401)) })
- expect(assign).not.toHaveBeenCalled(); expect(changed).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled()
- })
- it("qualified native warm email facts paint while the refresh is held", async () => {
- const mounted = render(<App><EmailEventSheet open={false} emailId="warm" workspaceId="workspace" onOpenChange={changed} /></App>)
- await waitFor(() => expect(owner?.workspaceId).toBe("workspace"))
- act(() => { owner.queryClient.setQueryData(owner.key("emails", "detail", "warm"), email("warm"), { updatedAt: 1 }); owner.queryClient.setQueryData(owner.key("emails", "body", "warm"), { content: "warm body", isHtml: false }, { updatedAt: 1 }); mounted.rerender(<App><EmailEventSheet open emailId="warm" workspaceId="workspace" onOpenChange={changed} /></App>) })
- await waitFor(() => expect(requests).toHaveLength(2))
- expect(screen.getByText("Subject warm")).toBeTruthy(); expect(screen.getByText("warm body")).toBeTruthy()
- })
- it("current body 401 still performs the authenticated navigation", async () => {
- render(<App><EmailEventSheet open emailId="A" workspaceId="workspace" onOpenChange={changed} /></App>)
- await waitFor(() => expect(requests).toHaveLength(2))
- const assign = navigationSpy()
- await act(async () => { requests[0].resolve(reply(email("A"))); requests[1].resolve(reply({}, 401)) })
- await waitFor(() => expect(assign).toHaveBeenCalledOnce())
- })
- it("retired calendar 401 leaves the selected B event visible", async () => {
- const mounted = render(<App><CalendarEventSheet open readonly calendarEventId="A" workspaceId="workspace" onOpenChange={changed} /></App>)
- await waitFor(() => expect(requests).toHaveLength(1))
- const assign = navigationSpy()
- act(() => mounted.rerender(<App><CalendarEventSheet open readonly calendarEventId="B" workspaceId="workspace" onOpenChange={changed} /></App>))
- await waitFor(() => expect(requests).toHaveLength(2))
- await act(async () => { requests[0].resolve(reply({}, 401)); requests[1].resolve(reply(calendar("B"))) })
- await waitFor(() => expect(screen.getByRole("heading", { name: "Event B" })).toBeTruthy())
- expect(assign).not.toHaveBeenCalled(); expect(changed).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled()
- expect(owner.queryClient.getQueryData(owner.key("calendar", "detail", "A"))).toBeUndefined()
- })
- it("two email consumers share one held read when only the initiating sheet closes", async () => {
- const another = vi.fn();
- const contents = (first: boolean, second: boolean) => <App><EmailEventSheet open={first} emailId="shared" workspaceId="workspace" onOpenChange={changed} /><EmailEventSheet open={second} emailId="shared" workspaceId="workspace" onOpenChange={another} /></App>;
- const mounted = render(contents(true, true));
- await waitFor(() => expect(requests).toHaveLength(2));
- act(() => mounted.rerender(contents(false, true)));
- await act(async () => { requests[0].resolve(reply(email("shared"))); requests[1].resolve(new Response("shared body")); });
- await waitFor(() => expect(screen.getByText("shared body")).toBeTruthy());
- expect(requests).toHaveLength(2); expect(another).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled();
- expect(owner.queryClient.getQueryState(owner.key("emails", "detail", "shared"))?.status).toBe("success");
- });
- it("releasing both shared email consumers cancels the native read before late 401", async () => {
- const contents = (open: boolean) => <App><EmailEventSheet open={open} emailId="shared" workspaceId="workspace" onOpenChange={changed} /><EmailEventSheet open={open} emailId="shared" workspaceId="workspace" onOpenChange={changed} /></App>;
- const mounted = render(contents(true));
- await waitFor(() => expect(requests).toHaveLength(2)); const assign = navigationSpy();
- act(() => mounted.rerender(contents(false)));
- await act(async () => { requests[0].resolve(reply({}, 401)); requests[1].resolve(reply({}, 401)); });
- expect(assign).not.toHaveBeenCalled(); expect(changed).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled();
- expect(owner.queryClient.getQueryData(owner.key("emails", "detail", "shared"))).toBeUndefined();
- });
- it("current ordinary email failure uses production retry and closes the sheet", async () => {
- render(<App><EmailEventSheet open emailId="A" workspaceId="workspace" onOpenChange={changed} /></App>)
- await waitFor(() => expect(requests).toHaveLength(2))
- await act(async () => { requests[0].resolve(reply({}, 500)); requests[1].resolve(new Response("body")) })
- await waitFor(() => expect(requests).toHaveLength(3), { timeout: 3000 })
- expect(changed).not.toHaveBeenCalled()
- await act(async () => requests[2].resolve(reply({}, 500)))
- await waitFor(() => expect(changed).toHaveBeenCalledWith(false))
- expect(error).toHaveBeenCalledWith("Email not found")
- })
-})
-
-describe("UI resource identities", () => {
- it("email hover resolves the latest canonical agent props after a rename", () => {
- const agent = { id: "agent", name: "old name", email_handle: "internal", avatar_url: null } as Agent
- const props = { subject: "subject", address: "address", direction: "inbound" as const, isInternal: true, internalHandle: "internal", targetConvId: "conv", agents: [agent], onClick: vi.fn() }
- const mounted = render(<EmailCard {...props} />)
- act(() => fireEvent.pointerEnter(screen.getByRole("button")))
- expect(screen.getByText("old name")).toBeTruthy()
- act(() => mounted.rerender(<EmailCard {...props} agents={[{ ...agent, name: "new name" }]} />))
- expect(screen.queryByText("old name")).toBeNull(); expect(screen.getByText("new name")).toBeTruthy()
- })
- it("selected skill is a name and follows canonical refresh/removal", () => {
- let active: SkillEntry | null = null
- const original = { name: "deploy", description: "old" } as SkillEntry
- function Skills({ skills }: { skills: SkillEntry[] }) { const popup = useSlashCommand({ input: "", caretIndex: null, skills, initialActiveSkill: original, onInputChange: vi.fn(), getAnchorPos: () => null }); useLayoutEffect(() => { active = popup.activeSkill }); return null }
- const mounted = render(<Skills skills={[]} />)
- expect(active).toBeNull()
- act(() => mounted.rerender(<Skills skills={[original]} />)); expect(active).toBe(original)
- const refreshed = { ...original, description: "new" }
- act(() => mounted.rerender(<Skills skills={[refreshed]} />)); expect(active).toBe(refreshed)
- act(() => mounted.rerender(<Skills skills={[]} />)); expect(active).toBeNull()
- })
-})
diff --git a/src/web/src/hooks/workspace/chat-query-options.ts b/src/web/src/hooks/workspace/chat-query-options.ts
deleted file mode 100644
index c173c104b..000000000
--- a/src/web/src/hooks/workspace/chat-query-options.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import { captureQueryReceipt, isQueryReceiptCurrent, withQueryReceipt, reconcileQueryReceipt } from "@/lib/query-receipt"
-import { queryOptions, infiniteQueryOptions } from "@tanstack/react-query"
-import type { ApiRequestOptions } from "@/lib/api/client"
-import { listMessages, listMessagesAroundTask, listArtifacts, getTask, getTaskMessages, getActiveTask, listPreviousConversations, listFlaggedMessageIds } from "@/lib/api"
-import type { TaskApi, TaskMessageResponse } from "@alook/shared"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { chatExtrasKey, chatMessagesKey, mergeCachedMessages, sortedChatMessages, type ChatExtras, type ChatMessagesData, type ChatMessagesPage } from "@/lib/chat-cache"
-import type { ChatFlagsData } from "@/lib/workspace-chat-flags"
-import { captureChatIntent, assertChatIntent } from "./use-chat-data"
-
-type ChatView = Parameters<typeof captureChatIntent>[1]
-export function chatReadSource(owner: WorkspaceOwner, view: ChatView, identity: string, options?: ApiRequestOptions) {
- const intent = captureChatIntent(owner, view)
- const factOrigin = captureWorkspaceOwner(owner)
- const assertFactActive = (signal?: AbortSignal) => assertWorkspaceOwner(factOrigin, signal)
- const assertActive = (signal?: AbortSignal) => { assertChatIntent(intent, signal); assertChatIntent(intent, options?.signal ?? undefined); options?.assertActive?.() }
- assertActive()
- return { owner, view, options, assertActive, assertFactActive, meta: { chatView: view, chatGeneration: intent.generation }, key: (...resource: readonly unknown[]) => owner.key("chat", "io", identity, intent.generation, ...resource), request: (signal: AbortSignal): ApiRequestOptions => workspaceRequestOptions(factOrigin, signal, () => assertFactActive(signal)) }
-}
-export function chatMessagePageOptions(source: ReturnType<typeof chatReadSource>, conversationId: string, initialPage?: Parameters<typeof listMessages>[2]) {
- const requestRevision = source.owner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(source.owner, conversationId))?.liveRevision ?? 0
- return infiniteQueryOptions({ queryKey: chatMessagesKey(source.owner, conversationId), meta: source.meta, retry: false, staleTime: 0,
- initialPageParam: initialPage ?? null,
- getNextPageParam: (lastPage: ChatMessagesPage) => {
- const oldest = lastPage.messages[0]
- return lastPage.hasMore && oldest ? { limit: 20, before: oldest.created_at, beforeId: oldest.id } : undefined
- },
- queryFn: async ({ signal, pageParam }) => {
- const result = await listMessages(conversationId, source.owner.workspaceId, pageParam ?? undefined, source.request(signal))
- source.assertFactActive(signal)
- return { messages: result.messages, hasMore: result.has_more, requestRevision } satisfies ChatMessagesPage
- },
-
- })
-}
-export function chatAroundTaskOptions(source: ReturnType<typeof chatReadSource>, conversationId: string, taskId: string) {
- return queryOptions({ queryKey: source.key("around-task", conversationId, taskId), retry: false, gcTime: 0, staleTime: 0,
- queryFn: async ({ signal }) => {
- const key = chatMessagesKey(source.owner, conversationId), receipt = captureQueryReceipt(source.owner.queryClient, key);
- const revision = source.owner.queryClient.getQueryData<ChatMessagesData>(key)?.liveRevision ?? 0;
- const messages = await listMessagesAroundTask(conversationId, source.owner.workspaceId, taskId, { ...source.request(signal), assertActive: () => source.assertActive(signal) })
- source.assertActive(signal)
- const current = source.owner.queryClient.getQueryData<ChatMessagesData>(key);
- const sameResource = source.owner.queryClient.getQueryCache().find({ queryKey: key, exact: true }) === receipt.resource;
- if (sameResource || !receipt.resource && (current?.liveRevision ?? 0) > 0) await mergeCachedMessages(conversationId, messages.filter((row) => (current?.liveMessageRevisions?.[row.id] ?? 0) <= revision), null, source.owner);
- source.assertActive(signal)
- return messages.map((row) => row.id)
- },
- })
-}
-export function readChatMessageIds(source: ReturnType<typeof chatReadSource>, conversationId: string, ids: string[]) {
- source.assertActive()
- const rows = new Map(sortedChatMessages(source.owner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(source.owner, conversationId))).map((row) => [row.id, row]))
- return ids.flatMap((id) => { const row = rows.get(id); return row ? [row] : [] })
-}
-export function chatArtifactOptions(source: ReturnType<typeof chatReadSource>, conversationId: string) {
- return queryOptions({ queryKey: chatExtrasKey(source.owner, conversationId), meta: source.meta, retry: false, staleTime: 0, structuralSharing: reconcileQueryReceipt,
- queryFn: async ({ signal }): Promise<ChatExtras> => {
- const receipt = captureQueryReceipt(source.owner.queryClient, chatExtrasKey(source.owner, conversationId))
- const artifacts = await listArtifacts(conversationId, source.owner.workspaceId, source.request(signal))
- source.assertFactActive(signal)
- const data = source.owner.queryClient.getQueryData<ChatExtras>(chatExtrasKey(source.owner, conversationId))
- return withQueryReceipt({ conversation: data?.conversation ?? null, artifacts, hasMoreArtifacts: false }, receipt, (previous, incoming) => {
- const old = previous as ChatExtras | undefined, next = incoming as ChatExtras
- return { ...next, conversation: old?.conversation ?? next.conversation, artifacts: [...new Map([...next.artifacts, ...(old?.artifacts ?? [])].map((row) => [row.id, row])).values()], hasMoreArtifacts: old?.hasMoreArtifacts ?? next.hasMoreArtifacts }
- })
- },
- })
-}
-export function chatTaskOptions(source: ReturnType<typeof chatReadSource>, taskId: string) {
- return queryOptions({ queryKey: source.owner.key("chat", "task", taskId), meta: source.meta, retry: false, staleTime: 0, structuralSharing: reconcileQueryReceipt,
- queryFn: async ({ signal }) => {
- const receipt = captureQueryReceipt(source.owner.queryClient, source.owner.key("chat", "task", taskId))
- const task = await getTask(taskId, source.owner.workspaceId, source.request(signal))
- source.assertFactActive(signal)
- return withQueryReceipt(task, receipt)
- },
- })
-}
-export function readChatTask(source: ReturnType<typeof chatReadSource>, taskId: string) {
- source.assertActive()
- return source.owner.queryClient.getQueryData<TaskApi>(source.owner.key("chat", "task", taskId))!
-}
-export function chatTaskMessagesOptions(source: ReturnType<typeof chatReadSource>, taskId: string) {
- return queryOptions({ queryKey: source.owner.key("chat", "task-messages", taskId), meta: source.meta, retry: false, staleTime: 0, structuralSharing: reconcileQueryReceipt,
- queryFn: async ({ signal }) => {
- const receipt = captureQueryReceipt(source.owner.queryClient, source.owner.key("chat", "task-messages", taskId))
- const incoming = await getTaskMessages(taskId, source.owner.workspaceId, undefined, source.request(signal))
- source.assertFactActive(signal)
- const data = source.owner.queryClient.getQueryData<TaskMessageResponse[]>(source.owner.key("chat", "task-messages", taskId))
- {
- const rows = new Map((data ?? []).map((row) => [row.seq, row]))
- for (const row of incoming) rows.set(row.seq, row)
- return withQueryReceipt([...rows.values()].sort((a, b) => a.seq - b.seq), receipt, (previous, next) => [...new Map([...(next as TaskMessageResponse[]), ...((previous as TaskMessageResponse[] | undefined) ?? [])].map((row) => [row.seq, row])).values()].sort((a, b) => a.seq - b.seq))
- }
- },
- })
-}
-export function chatActiveTaskOptions(source: ReturnType<typeof chatReadSource>, conversationId: string) {
- return queryOptions({ queryKey: source.owner.key("chat", "active-task", conversationId), meta: source.meta, retry: false, staleTime: 0, structuralSharing: reconcileQueryReceipt,
- queryFn: async ({ signal }) => {
- const receipt = captureQueryReceipt(source.owner.queryClient, source.owner.key("chat", "active-task", conversationId))
- const tasks = new Map(source.owner.queryClient.getQueryCache().findAll({ queryKey: source.owner.key("chat", "task") }).map((query) => [JSON.stringify(query.queryKey), captureQueryReceipt(source.owner.queryClient, query.queryKey)]))
- const task = await getActiveTask(conversationId, source.owner.workspaceId, source.request(signal))
- source.assertFactActive(signal)
- if (task) {
- const key = source.owner.key("chat", "task", task.id), ticket = tasks.get(JSON.stringify(key))
- if (ticket ? isQueryReceiptCurrent(ticket) : !source.owner.queryClient.getQueryCache().find({ queryKey: key, exact: true })) source.owner.queryClient.setQueryData(key, task)
- }
- return withQueryReceipt({ id: task?.id ?? null }, receipt)
- },
- })
-}
-export function chatPreviousOptions(source: ReturnType<typeof chatReadSource>, agentId: string, page: Parameters<typeof listPreviousConversations>[2]) {
- return infiniteQueryOptions({ queryKey: source.owner.key("chat", "previous-conversations", agentId, page.channel ?? "", page.exclude), meta: source.meta, retry: false, staleTime: 0,
- initialPageParam: page.before,
- getNextPageParam: (lastPage: { conversations: Array<{ id: string; created_at: string }>; has_more: boolean }) => lastPage.has_more ? lastPage.conversations.at(-1)?.created_at : undefined,
- queryFn: async ({ signal, pageParam }) => {
- const result = await listPreviousConversations(agentId, source.owner.workspaceId, { ...page, before: pageParam }, source.request(signal))
- source.assertFactActive(signal)
- return result
- },
- })
-}
-export function chatFlagsOptions(source: ReturnType<typeof chatReadSource>, conversationId: string) {
- const requestRevision = source.owner.queryClient.getQueryData<ChatFlagsData>(source.owner.key("chat", "flags", conversationId))?.revision ?? 0
- return queryOptions({ queryKey: source.owner.key("chat", "flags", conversationId), meta: source.meta, retry: false, staleTime: 0,
- queryFn: async ({ signal }) => { const data = await listFlaggedMessageIds(source.owner.workspaceId, conversationId, source.request(signal)); source.assertFactActive(signal); return { ids: data.message_ids, requestRevision } satisfies ChatFlagsData },
- })
-}
-
-export function observeChatRead(source: ReturnType<typeof chatReadSource>, observer: { subscribe: (listener: () => void) => () => void; destroy: () => void }) {
- source.assertActive()
- const unsubscribe = observer.subscribe(() => {})
- let released = false
- const release = () => {
- if (released) return
- released = true
- subscription.unsubscribe()
- source.options?.signal?.removeEventListener("abort", release)
- unsubscribe()
- observer.destroy()
- }
- const subscription = source.view.subscribe(() => { try { source.assertActive() } catch { release() } })
- source.options?.signal?.addEventListener("abort", release, { once: true })
- return release
-}
diff --git a/src/web/src/hooks/workspace/chat-secondary-resources.dom.test.tsx b/src/web/src/hooks/workspace/chat-secondary-resources.dom.test.tsx
deleted file mode 100644
index 9aff9fd89..000000000
--- a/src/web/src/hooks/workspace/chat-secondary-resources.dom.test.tsx
+++ /dev/null
@@ -1,289 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { beforeEach, afterEach, describe, it, expect, vi } from "vitest"
-import { act, render, waitFor } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider, useWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { FlagCountProvider, useFlagCount } from "@/contexts/flag-count-context"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
-import { useChatData } from "./use-chat-data"
-import { useMessageFlags } from "../use-message-flags"
-import { useChatSheets } from "../use-chat-sheets"
-import { publishWorkspaceIssueEvent } from "@/lib/workspace-issue-events"
-import type { ChatFlagsData } from "@/lib/workspace-chat-flags"
-import type { WorkspaceIssueDetail } from "@/lib/workspace-issue-reconciliation"
-import type { Issue, Message, WsMessage, Artifact } from "@alook/shared"
-
-const error = vi.hoisted(() => vi.fn())
-const auth = vi.hoisted(() => ({ user: "secondary-user" }))
-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: auth.user } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("sonner", () => ({ toast: { error } }))
-let owner: WorkspaceOwner
-let flags: ReturnType<typeof useMessageFlags>
-let sheets: ReturnType<typeof useChatSheets>
-let count: number
-let ready = false
-let serverCount = 2
-let countReads = 0
-let requests: Array<{ path: string; method: string; resolve: (response: Response) => void; signal?: AbortSignal }>
-const callbacks = new Set<(message: WsMessage) => void>()
-const subscribe = (callback: (message: WsMessage) => void) => { callbacks.add(callback); return () => { callbacks.delete(callback) } }
-const ws = (message: WsMessage) => { publishWorkspaceIssueEvent(owner, message); callbacks.forEach((callback) => callback(message)) }
-function Probe({ target = "A", switchFailedA = false }: { target?: string; switchFailedA?: boolean }) {
- const currentOwner = useWorkspaceOwner()
- const chat = useChatData(currentOwner, target, target)
- const currentFlags = useMessageFlags(currentOwner, chat.view, target)
- const currentSheets = useChatSheets(currentOwner, chat.view)
- const currentCount = useFlagCount().count
- React.useLayoutEffect(() => { owner = currentOwner; ready = true; flags = currentFlags; sheets = currentSheets; count = currentCount })
- React.useLayoutEffect(() => {
- if (switchFailedA && currentSheets.selectedIssueId === "A" && currentOwner.queryClient.getQueryState(currentOwner.key("issues", "detail", "A"))?.status === "error") void currentSheets.openIssue("B")
- })
- return null
-}
-function App(props: { target?: string; switchFailedA?: boolean; workspace?: string; user?: string }) { return <ApplicationQueryProvider userId={props.user ?? "secondary-user"}><WorkspaceProvider workspaceId={props.workspace ?? "workspace"} slug={props.workspace ?? "workspace"}><FlagCountProvider><Probe {...props} /></FlagCountProvider></WorkspaceProvider></ApplicationQueryProvider> }
-const reply = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } })
-const message = (id: string, content = id): Message => ({ id, conversation_id: "conv-A", role: "event", content, task_id: null, attachment_ids: null, created_at: "2026-10-01T00:00:00Z" })
-function detail(id = "A", extra: Partial<Issue> = {}): WorkspaceIssueDetail {
- return { issue: { id, agent_id: "agent", workspace_id: "workspace", title: id, description: null, status: "open", conversation_id: `conv-${id}`, latest_task_id: null, created_at: "2026-10-01T00:00:00Z", updated_at: "2026-10-01T00:00:00Z", ...extra } as Issue, messages: [message("initial")], comments: [], artifacts: [] }
-}
-const artifact: Artifact = { id: "artifact", agent_id: "agent", conversation_id: "conv-A", filename: "report.pdf", content_type: "application/pdf", size: 123, source: "agent", has_thumbnail: false, created_at: "2026-10-01T00:00:00Z" }
-async function selectIssue(id = "A") { await waitFor(() => expect(ready).toBe(true)); act(() => { void sheets.openIssue(id) }); return waitFor(() => expect(requests.some((request) => request.path.startsWith(`/api/issues/${id}?`))).toBe(true)) }
-beforeEach(async () => {
- await clearAllPersistedCaches(); auth.user = "secondary-user"; ready = false; serverCount = 2; countReads = 0; requests = []; error.mockClear(); callbacks.clear()
- vi.stubGlobal("fetch", vi.fn((path: string, options: RequestInit) => {
- if (path.startsWith("/api/flags/count")) { countReads++; return Promise.resolve(reply({ count: serverCount })) }
- if (path.startsWith("/api/flags?") && !options.method) return Promise.resolve(reply({ message_ids: ["flagged"] }))
- return new Promise<Response>((resolve) => requests.push({ path, method: options.method ?? "GET", resolve, signal: options.signal ?? undefined }))
- }))
-})
-afterEach(async () => {
- await act(async () => {
- vi.unstubAllGlobals(); owner?.queryClient.clear()
- })
-})
-
-describe("chat secondary canonical resources", () => {
- it("current flag failure rolls back canonical ids and count", async () => {
- render(<App />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await waitFor(() => expect(count).toBe(2))
- let toggled!: Promise<void>
- act(() => { toggled = flags.handleToggleFlag("new") })
- await waitFor(() => expect(requests).toHaveLength(1))
- expect(flags.flaggedIds.has("new")).toBe(true)
- expect(count).toBe(3)
- await act(async () => { requests[0].resolve(reply({ error: "failed" }, 500)); await toggled })
- await waitFor(() => expect(flags.flaggedIds.has("new")).toBe(false))
- expect(count).toBe(2)
- expect(owner.queryClient.getQueryData<ChatFlagsData>(owner.key("chat", "flags", "A"))?.ids).toEqual(["flagged"])
- })
- it("retired flag 401 cannot redirect or change the next conversation ids", async () => {
- const mounted = render(<App />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- let toggled!: Promise<void>
- act(() => { toggled = flags.handleToggleFlag("old") })
- await waitFor(() => expect(requests).toHaveLength(1))
- const actualWindow = window, assign = vi.fn()
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- act(() => mounted.rerender(<App target="B" />))
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await act(async () => { requests[0].resolve(reply({}, 401)); await toggled })
- expect(flags.flaggedIds.has("old")).toBe(false)
- expect(assign).not.toHaveBeenCalled()
- expect(error).not.toHaveBeenCalled()
- })
- it.each([200, 500])("retired flag response %s settles the original resource and count before reopening A", async (status) => {
- const mounted = render(<App />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await waitFor(() => expect(count).toBe(2))
- let toggled!: Promise<void>
- act(() => { toggled = flags.handleToggleFlag("unconfirmed") })
- await waitFor(() => expect(requests).toHaveLength(1))
- await waitFor(() => expect(count).toBe(3))
- act(() => mounted.rerender(<App target="B" />))
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await act(async () => { requests[0].resolve(reply(status === 200 ? { flagged: true } : { error: "failed" }, status)); await toggled })
- expect(owner.queryClient.getQueryData<ChatFlagsData>(owner.key("chat", "flags", "A"))?.ids).toEqual(["flagged"])
- await waitFor(() => expect(count).toBe(2))
- expect(owner.queryClient.getQueryState(owner.key("chat", "flags", "A"))?.isInvalidated).toBe(true)
- act(() => mounted.rerender(<App target="A" />))
- await waitFor(() => expect(owner.queryClient.getQueryState(owner.key("chat", "flags", "A"))?.fetchStatus).toBe("idle"))
- expect(flags.flaggedIds.has("unconfirmed")).toBe(false)
- })
- it("settling old A preserves a newer confirmed count after B succeeds and refreshes", async () => {
- const mounted = render(<App />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await waitFor(() => expect(count).toBe(2))
- let old!: Promise<void>, current!: Promise<void>
- act(() => { old = flags.handleToggleFlag("old-A") })
- await waitFor(() => expect(requests).toHaveLength(1))
- act(() => mounted.rerender(<App target="B" />))
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- act(() => { current = flags.handleToggleFlag("confirmed-B") })
- await waitFor(() => expect(requests).toHaveLength(2))
- serverCount = 3
- await act(async () => { requests[1].resolve(reply({ flagged: true })); await current })
- await waitFor(() => expect(countReads).toBe(2))
- await waitFor(() => expect(count).toBe(3))
- await act(async () => { requests[0].resolve(reply({ error: "failed" }, 500)); await old })
- await waitFor(() => expect(owner.queryClient.getQueryState(owner.key("chat", "flags", "A"))?.isInvalidated).toBe(true))
- expect(count).toBe(3)
- })
- it("two failures remove their own pending count deltas without erasing the other transaction", async () => {
- const mounted = render(<App />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await waitFor(() => expect(count).toBe(2))
- let old!: Promise<void>, current!: Promise<void>
- act(() => { old = flags.handleToggleFlag("old-A") })
- await waitFor(() => expect(requests).toHaveLength(1))
- act(() => mounted.rerender(<App target="B" />))
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- act(() => { current = flags.handleToggleFlag("pending-B") })
- await waitFor(() => expect(requests).toHaveLength(2))
- await waitFor(() => expect(count).toBe(4))
- await act(async () => { requests[0].resolve(reply({ error: "failed" }, 500)); await old })
- await waitFor(() => expect(count).toBe(3))
- expect(flags.flaggedIds.has("pending-B")).toBe(true)
- await act(async () => { requests[1].resolve(reply({ error: "failed" }, 500)); await current })
- await waitFor(() => expect(count).toBe(2))
- expect(flags.flaggedIds.has("pending-B")).toBe(false)
- })
- it("workspace A→B retirement settles A's original cached transaction before returning to A", async () => {
- const mounted = render(<App workspace="workspace-A" />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await waitFor(() => expect(count).toBe(2))
- const original = owner
- let old!: Promise<void>
- act(() => { old = flags.handleToggleFlag("unconfirmed") })
- await waitFor(() => expect(requests).toHaveLength(1))
- act(() => mounted.rerender(<App workspace="workspace-B" />))
- await waitFor(() => expect(owner.workspaceId).toBe("workspace-B"))
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- expect(original.lifecycle.get().active).toBe(false)
- await act(async () => { requests[0].resolve(reply({ error: "failed" }, 500)); await old })
- expect(original.queryClient.getQueryData<ChatFlagsData>(original.key("chat", "flags", "A"))?.ids).toEqual(["flagged"])
- expect(original.queryClient.getQueryData<{ count: number }>(original.key("flag-count"))?.count).toBe(2)
- expect(flags.flaggedIds.has("unconfirmed")).toBe(false)
- expect(count).toBe(2)
- act(() => mounted.rerender(<App workspace="workspace-A" />))
- await waitFor(() => expect(owner.workspaceId).toBe("workspace-A"))
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- expect(flags.flaggedIds.has("unconfirmed")).toBe(false)
- expect(count).toBe(2)
- })
- it.each([false, true])("old workspace settlement cannot recreate or mutate a replaced Query, replacement=%s", async (replacement) => {
- const mounted = render(<App workspace="workspace-A" />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- await waitFor(() => expect(count).toBe(2))
- const original = owner, key = original.key("chat", "flags", "A"), countKey = original.key("flag-count")
- let old!: Promise<void>
- act(() => { old = flags.handleToggleFlag("unconfirmed") })
- await waitFor(() => expect(requests).toHaveLength(1))
- act(() => mounted.rerender(<App workspace="workspace-B" />))
- await waitFor(() => expect(owner.workspaceId).toBe("workspace-B"))
- await waitFor(() => expect(count).toBe(2))
- act(() => {
- original.queryClient.removeQueries({ queryKey: original.key() })
- if (replacement) {
- original.queryClient.setQueryData<ChatFlagsData>(key, { ids: ["new-confirmed", "unconfirmed"], revision: 1, writes: { unconfirmed: { flagged: true, revision: 1 } } })
- original.queryClient.setQueryData(countKey, { count: 10, confirmedCount: 9, revision: 1, pending: { "1": { delta: 1, revision: 1 } } })
- }
- })
- const nextFlags = original.queryClient.getQueryData(key), nextCount = original.queryClient.getQueryData(countKey)
- await act(async () => { requests[0].resolve(reply({ error: "failed" }, 500)); await old })
- expect(original.queryClient.getQueryData(key)).toBe(nextFlags)
- expect(original.queryClient.getQueryData(countKey)).toBe(nextCount)
- if (replacement) {
- expect(original.queryClient.getQueryState(key)?.isInvalidated).toBe(false)
- expect(original.queryClient.getQueryState(countKey)?.isInvalidated).toBe(false)
- } else expect(original.queryClient.getQueryCache().findAll({ queryKey: original.key() })).toEqual([])
- expect(count).toBe(2)
- })
- it("account retirement rejects the old flag 401 without recreating old facts or touching the next account", async () => {
- const mounted = render(<App />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- const original = owner
- let old!: Promise<void>
- act(() => { old = flags.handleToggleFlag("old-account") })
- await waitFor(() => expect(requests).toHaveLength(1))
- const actualWindow = window, assign = vi.fn()
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- auth.user = "next-user"
- act(() => mounted.rerender(<App user="next-user" />))
- await waitFor(() => expect(owner.application.userId).toBe("next-user"))
- await waitFor(() => expect(count).toBe(2))
- await waitFor(() => expect(original.queryClient.getQueryCache().getAll()).toEqual([]))
- await act(async () => { requests[0].resolve(reply({}, 401)); await old })
- expect(assign).not.toHaveBeenCalled()
- expect(error).not.toHaveBeenCalled()
- expect(original.queryClient.getQueryCache().getAll()).toEqual([])
- expect(flags.flaggedIds.has("old-account")).toBe(false)
- expect(count).toBe(2)
- })
- it.each([200, 401])("retired issue response %s cannot replace the new selection or redirect", async (status) => {
- render(<App />); await selectIssue("A")
- const first = requests[0]
- const actualWindow = window, assign = vi.fn()
- vi.stubGlobal("window", new Proxy(actualWindow, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }))
- await selectIssue("B")
- await act(async () => requests[1].resolve(reply(detail("B"))))
- await waitFor(() => expect(sheets.issueDetail?.issue.id).toBe("B"))
- await act(async () => first.resolve(reply(status === 200 ? detail("A") : {}, status)))
- await waitFor(() => expect(owner.queryClient.getQueryState(owner.key("issues", "detail", "A"))?.fetchStatus).toBe("idle"))
- expect(sheets.issueDetail?.issue.id).toBe("B")
- expect(assign).not.toHaveBeenCalled()
- expect(error).not.toHaveBeenCalled()
- })
- it("WS message and status survive a held issue refetch, and selected artifact derives the canonical row", async () => {
- render(<App />); await selectIssue()
- await act(async () => requests[0].resolve(reply({ ...detail(), artifacts: [artifact] })))
- await waitFor(() => expect(sheets.issueDetail?.issue.id).toBe("A"))
- act(() => sheets.setSelectedArtifact(artifact))
- await waitFor(() => expect(sheets.selectedArtifact?.filename).toBe("report.pdf"))
- act(() => { void sheets.openIssue("A") })
- await waitFor(() => expect(requests).toHaveLength(2))
- act(() => ws({ type: "conversation.message", conversationId: "conv-A", message: message("ws-status", "Issue status changed: open -> closed") }))
- await act(async () => requests[1].resolve(reply({ ...detail(), artifacts: [{ ...artifact, filename: "renamed.pdf" }] })))
- await waitFor(() => expect(owner.queryClient.getQueryState(owner.key("issues", "detail", "A"))?.fetchStatus).toBe("idle"))
- expect(sheets.issueDetail?.messages.map((row) => row.id)).toEqual(["initial", "ws-status"])
- expect(sheets.issueDetail?.issue.status).toBe("closed")
- expect(sheets.selectedArtifact?.filename).toBe("renamed.pdf")
- })
- it("an earlier init flags snapshot cannot replace a live optimistic flag write", async () => {
- render(<App />)
- await waitFor(() => expect(flags.flaggedIds.has("flagged")).toBe(true))
- const key = owner.key("chat", "flags", "A")
- const started = owner.queryClient.getQueryData<ChatFlagsData>(key)?.revision ?? 0
- let toggled!: Promise<void>
- act(() => { toggled = flags.handleToggleFlag("accepted") })
- await waitFor(() => expect(requests).toHaveLength(1))
- await act(async () => { requests[0].resolve(reply({ flagged: true })); await toggled })
- act(() => owner.queryClient.setQueryData<ChatFlagsData>(key, { ids: ["flagged"], requestRevision: started }))
- await waitFor(() => expect(flags.flaggedIds.has("accepted")).toBe(true))
- expect(owner.queryClient.getQueryData<ChatFlagsData>(key)?.ids).toEqual(["flagged", "accepted"])
- expect(owner.queryClient.getQueryData<ChatFlagsData>(key)?.requestRevision).toBeUndefined()
- })
- it("an error effect queued for A cannot borrow B selection after layout switches the sheet", async () => {
- render(<App switchFailedA />); await selectIssue()
- await act(async () => requests[0].resolve(reply({ error: "A failed" }, 400)))
- await waitFor(() => expect(requests).toHaveLength(2), { timeout: 2000 })
- await act(async () => requests[1].resolve(reply({ error: "A failed" }, 400)))
- await waitFor(() => expect(requests.some((request) => request.path.startsWith("/api/issues/B?"))).toBe(true))
- expect(sheets.selectedIssueId).toBe("B")
- expect(sheets.issueSheetOpen).toBe(true)
- expect(error).not.toHaveBeenCalled()
- await act(async () => requests.find((request) => request.path.startsWith("/api/issues/B?"))!.resolve(reply(detail("B"))))
- await waitFor(() => expect(sheets.issueDetail?.issue.id).toBe("B"))
- })
- it("current issue failure closes the sheet and reports its normal error", async () => {
- render(<App />); await selectIssue()
- await act(async () => requests[0].resolve(reply({ error: "unavailable" }, 400)))
- await waitFor(() => expect(requests).toHaveLength(2), { timeout: 2000 })
- await act(async () => requests[1].resolve(reply({ error: "unavailable" }, 400)))
- await waitFor(() => expect(sheets.issueSheetOpen).toBe(false))
- expect(error).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/src/web/src/hooks/workspace/chat-shared-reads.dom.test.tsx b/src/web/src/hooks/workspace/chat-shared-reads.dom.test.tsx
deleted file mode 100644
index 8689bf75c..000000000
--- a/src/web/src/hooks/workspace/chat-shared-reads.dom.test.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { beforeEach, afterEach, describe, it, expect, vi } from "vitest"
-import { useQuery, useInfiniteQuery } from "@tanstack/react-query"
-import { act, render, waitFor } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider, useWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
-import { chatReadSource, chatTaskOptions, chatArtifactOptions, chatTaskMessagesOptions, chatActiveTaskOptions, chatFlagsOptions, chatMessagePageOptions } from "./chat-query-options"
-import { useChatData } from "./use-chat-data"
-import { workspaceIssueOptions } from "./issue-query-options"
-import { useChatSheets } from "../use-chat-sheets"
-
-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: "shared-user" } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-const error = vi.hoisted(() => vi.fn())
-vi.mock("sonner", () => ({ toast: { error } }))
-let owner: WorkspaceOwner
-let held: Array<{ resolve: (response: Response) => void; signal: AbortSignal }>
-const observed: Record<string, unknown> = {}
-const sheetViews: Record<string, ReturnType<typeof useChatSheets>> = {}
-const subscribe = () => () => {}
-const response = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } })
-function App({ children }: { children: React.ReactNode }) { return <ApplicationQueryProvider userId="shared-user"><WorkspaceProvider workspaceId="workspace" slug="workspace">{children}</WorkspaceProvider></ApplicationQueryProvider> }
-function Resource({ name, factory }: { name: string; factory: (source: ReturnType<typeof chatReadSource>) => ReturnType<typeof chatTaskOptions> }) {
- const currentOwner = useWorkspaceOwner(); useLayoutEffect(() => { owner = currentOwner }); const chat = useChatData(currentOwner, name, "conv"); const source = chatReadSource(currentOwner, chat.view, name);
- const data = useQuery(factory(source)).data; useLayoutEffect(() => { observed[name] = data }); return null
-}
-function Messages({ name }: { name: string }) { const currentOwner = useWorkspaceOwner(); useLayoutEffect(() => { owner = currentOwner }); const chat = useChatData(currentOwner, name, "conv"); const data = useInfiniteQuery(chatMessagePageOptions(chatReadSource(currentOwner, chat.view, name), "conv")).data; useLayoutEffect(() => { observed[name] = data }); return null }
-function Issues({ name }: { name: string }) { const currentOwner = useWorkspaceOwner(); useLayoutEffect(() => { owner = currentOwner }); const chat = useChatData(currentOwner, name, "conv"); const value = useChatSheets(currentOwner, chat.view); useLayoutEffect(() => { sheetViews[name] = value }); return null }
-beforeEach(async () => { await clearAllPersistedCaches(); held = []; error.mockClear(); for (const key of Object.keys(observed)) delete observed[key]; vi.stubGlobal("fetch", vi.fn((_path: string, options: RequestInit) => new Promise<Response>((resolve) => held.push({ resolve, signal: options.signal as AbortSignal })))) })
-afterEach(async () => {
- await act(async () => {
- vi.unstubAllGlobals(); owner?.queryClient.clear()
- })
-})
-const cases = [
- ["task", (source: ReturnType<typeof chatReadSource>) => chatTaskOptions(source, "task"), { id: "task", status: "running" }],
- ["artifacts", (source: ReturnType<typeof chatReadSource>) => chatArtifactOptions(source, "conv"), []],
- ["task messages", (source: ReturnType<typeof chatReadSource>) => chatTaskMessagesOptions(source, "task"), []],
- ["active task", (source: ReturnType<typeof chatReadSource>) => chatActiveTaskOptions(source, "conv"), { id: "task", status: "running" }],
- ["flags", (source: ReturnType<typeof chatReadSource>) => chatFlagsOptions(source, "conv"), { message_ids: ["message"] }],
-] as const
-
-describe("native shared fact read lifetime", () => {
- it.each(cases)("%s keeps the one held read after its initiating chat view retires", async (_name, factory, data) => {
- const sameFactory = factory as unknown as (source: ReturnType<typeof chatReadSource>) => ReturnType<typeof chatTaskOptions>
- const contents = (first: boolean) => <App>{first && <Resource name="A" factory={sameFactory} />}<Resource name="B" factory={sameFactory} /></App>
- const mounted = render(contents(true)); await waitFor(() => expect(held).toHaveLength(1));
- act(() => mounted.rerender(contents(false))); expect(held[0].signal.aborted).toBe(false);
- await act(async () => held[0].resolve(response(data))); await waitFor(() => expect(observed.B).toBeDefined());
- expect(held).toHaveLength(1); expect(error).not.toHaveBeenCalled()
- })
- it("messages preserve their aggregate for a second actual infinite observer", async () => {
- const contents = (first: boolean) => <App>{first && <Messages name="A" />}<Messages name="B" /></App>
- const mounted = render(contents(true)); await waitFor(() => expect(held).toHaveLength(1)); act(() => mounted.rerender(contents(false)));
- await act(async () => held[0].resolve(response({ messages: [{ id: "message", conversation_id: "conv", role: "user", content: "shared", created_at: "2026-10-01T00:00:00Z", attachment_ids: null, task_id: null }], has_more: false })));
- await waitFor(() => expect(observed.B).toMatchObject({ pages: [{ messages: [{ id: "message" }] }] })); expect(held).toHaveLength(1)
- })
- it("task query cancellation when all actual observers retire suppresses late 401", async () => {
- const factory = (source: ReturnType<typeof chatReadSource>) => chatTaskOptions(source, "task")
- const contents = (visible: boolean) => <App>{visible && <><Resource name="A" factory={factory} /><Resource name="B" factory={factory} /></>}</App>
- const mounted = render(contents(true)); await waitFor(() => expect(held).toHaveLength(1));
- const real = window, assign = vi.fn(); vi.stubGlobal("window", new Proxy(real, { get(target, key) { return key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) } }));
- act(() => mounted.rerender(contents(false))); expect(held[0].signal.aborted).toBe(true);
- await act(async () => held[0].resolve(response({}, 401))); expect(assign).not.toHaveBeenCalled(); expect(error).not.toHaveBeenCalled()
- })
- it("two real issue selections deduplicate and keep B after A retires", async () => {
- const contents = (first: boolean) => <App>{first && <Issues name="A" />}<Issues name="B" /></App>
- const mounted = render(contents(true)); await waitFor(() => expect(sheetViews.B).toBeDefined());
- act(() => { void sheetViews.A.openIssue("issue"); void sheetViews.B.openIssue("issue") }); await waitFor(() => expect(held).toHaveLength(1));
- act(() => mounted.rerender(contents(false)));
- const detail = { issue: { id: "issue", title: "shared issue", conversation_id: null, latest_task_id: null, trace_id: null }, messages: [], comments: [], artifacts: [] };
- await act(async () => held[0].resolve(response(detail))); await waitFor(() => expect(sheetViews.B.issueDetail?.issue.title).toBe("shared issue")); expect(held).toHaveLength(1); expect(error).not.toHaveBeenCalled(); expect(owner.queryClient.getQueryData(workspaceIssueOptions(owner, "issue").queryKey)).toMatchObject(detail)
- })
-})
diff --git a/src/web/src/hooks/workspace/email-query-options.ts b/src/web/src/hooks/workspace/email-query-options.ts
deleted file mode 100644
index dce308967..000000000
--- a/src/web/src/hooks/workspace/email-query-options.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { queryOptions,useQueries,skipToken } from "@tanstack/react-query"
-import type { Email } from "@alook/shared"
-import { captureQueryReceipt,isQueryReceiptCurrent,withQueryReceipt,reconcileQueryReceipt } from "@/lib/query-receipt"
-import { getEmailBody,getEmailThread,listEmails } from "@/lib/api"
-import { captureWorkspaceOwner,assertWorkspaceOwner,workspaceRequestOptions,runWorkspaceRequest,type WorkspaceOwner } from "@/contexts/workspace-context"
-
-export const emailEntityKey = (owner: WorkspaceOwner, id: string) => owner.key("email", "entity", id)
-export const emailBodyOptions = (owner: WorkspaceOwner, id: string) => queryOptions({
- queryKey: owner.key("email", "body", id), gcTime: 0,
- structuralSharing: reconcileQueryReceipt,
- queryFn: async ({ signal }) => {
- const receipt = captureQueryReceipt(owner.queryClient, owner.key("email", "body", id))
- const data = await runWorkspaceRequest(owner, (options) => getEmailBody(id, owner.workspaceId, options), signal)
- return withQueryReceipt(data, receipt)
- },
-})
-
-function seedEmail(owner: WorkspaceOwner, email: Email) {
- const { html_body, ...fields } = email
- const canonical: Email = { ...fields, html_body: "" }
- owner.queryClient.setQueryData<Email | null>(emailEntityKey(owner, email.id), canonical)
- if (html_body) owner.queryClient.setQueryData(emailBodyOptions(owner, email.id).queryKey, { content: html_body, isHtml: true })
-}
-
-function emailWindowOptions(owner: WorkspaceOwner, key: readonly unknown[], load: (options: ReturnType<typeof workspaceRequestOptions>) => Promise<Email[]>) {
- return queryOptions({ queryKey: key,
- queryFn: async ({ signal }) => {
- const token = captureWorkspaceOwner(owner)
- const baseline = new Map(owner.queryClient.getQueryCache().findAll({ queryKey: owner.key("email", "entity") }).map((query) => [query.queryKey.at(-1), captureQueryReceipt(owner.queryClient, query.queryKey)]))
- const bodies = new Map(owner.queryClient.getQueryCache().findAll({ queryKey: owner.key("email", "body") }).map((query) => [query.queryKey.at(-1), captureQueryReceipt(owner.queryClient, query.queryKey)]))
- const assert = () => assertWorkspaceOwner(token, signal)
- assert()
- try {
- const rows = await load(workspaceRequestOptions(token, signal))
- assert()
- for (const row of rows) {
- const receipt = baseline.get(row.id), current = owner.queryClient.getQueryCache().find({ queryKey: emailEntityKey(owner, row.id), exact: true })
- if (receipt ? isQueryReceiptCurrent(receipt) : !current) {
- const bodyReceipt = bodies.get(row.id), body = owner.queryClient.getQueryCache().find({ queryKey: emailBodyOptions(owner, row.id).queryKey, exact: true })
- const bodyCurrent = bodyReceipt ? isQueryReceiptCurrent(bodyReceipt) : !body
- seedEmail(owner, { ...row, html_body: bodyCurrent ? row.html_body : "" })
- }
- }
- return { ids: rows.map((row) => row.id) }
- } catch (error) { assert(); throw error }
- },
- })
-}
-
-export function emailListOptions(owner: WorkspaceOwner, agentId: string, folder: string, address?: string) {
- return emailWindowOptions(owner, owner.key("email", "windows", "list", agentId, folder, address ?? ""), (options) => listEmails(agentId, owner.workspaceId, folder, address, options))
-}
-export function emailThreadOptions(owner: WorkspaceOwner, id: string) {
- return emailWindowOptions(owner, owner.key("email", "windows", "thread", id), (options) => getEmailThread(id, owner.workspaceId, options))
-}
-export function useEmailRows(owner: WorkspaceOwner, ids: readonly string[]) {
- return useQueries({ queries: ids.map((id) => ({ queryKey: emailEntityKey(owner, id), queryFn: skipToken, enabled: false, structuralSharing: reconcileQueryReceipt })) }).flatMap((query) => query.data ? [query.data as Email] : [])
-}
diff --git a/src/web/src/hooks/workspace/file-query-options.ts b/src/web/src/hooks/workspace/file-query-options.ts
deleted file mode 100644
index 4575ef3aa..000000000
--- a/src/web/src/hooks/workspace/file-query-options.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { queryOptions } from "@tanstack/react-query"
-import type { WsMessage } from "@alook/shared"
-import { requestWorkspaceBrowse } from "@/lib/api"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, type WorkspaceOwner } from "@/contexts/workspace-context"
-
-type FileReceipt = Extract<WsMessage, { type: "workspace.files" }>
-type Subscribe = (callback: (message: WsMessage) => void) => () => void
-
-export function workspaceFileOptions(owner: WorkspaceOwner, agentId: string, runtimeId: string | null, mode: "tree" | "read", path: string, subscribe: Subscribe) {
- return queryOptions({
- queryKey: owner.key("agent-files", agentId, runtimeId, mode, path),
- staleTime: mode === "tree" ? 30_000 : 0,
- gcTime: mode === "tree" ? 300_000 : 0,
- retry: false,
- queryFn: ({ signal }) => {
- const token = captureWorkspaceOwner(owner)
- const assert = () => assertWorkspaceOwner(token, signal)
- assert()
- return new Promise<FileReceipt["result"]>((resolve, reject) => {
- let requestId: string | null = null
- let settled = false
- const early: FileReceipt[] = []
- const complete = (error: unknown, result?: FileReceipt["result"]) => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- signal.removeEventListener("abort", abort)
- unsubscribe()
- try { assert() } catch (retired) { reject(retired); return }
- if (error) reject(error)
- else resolve(result!)
- }
- const receive = (receipt: FileReceipt) => {
- if (receipt.requestId !== requestId) return
- complete(receipt.result.error ? new Error(receipt.result.error) : null, receipt.result)
- }
- const unsubscribe = subscribe((message) => {
- if (message.type !== "workspace.files" || message.agentId !== agentId) return
- if (requestId === null) { early.push(message); return }
- receive(message)
- })
- const abort = () => complete(new DOMException("Cancelled file read", "AbortError"))
- const timer = setTimeout(() => complete(new Error("Request timed out — daemon may be offline")), 15_000)
- signal.addEventListener("abort", abort, { once: true })
- if (signal.aborted) { abort(); return }
- void requestWorkspaceBrowse(agentId, owner.workspaceId, mode, path, workspaceRequestOptions(token, signal)).then((response) => {
- if (settled) return
- try { assert() } catch (error) { complete(error); return }
- requestId = response.request_id
- for (const receipt of early) receive(receipt)
- early.length = 0
- }, (error) => complete(error))
- })
- },
- })
-}
diff --git a/src/web/src/hooks/workspace/issue-query-options.ts b/src/web/src/hooks/workspace/issue-query-options.ts
deleted file mode 100644
index 7a84fd412..000000000
--- a/src/web/src/hooks/workspace/issue-query-options.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { captureQueryReceipt, withQueryReceipt, reconcileQueryReceipt } from "@/lib/query-receipt"
-import { queryOptions } from "@tanstack/react-query"
-import { getIssue, getTrace, getTask, listIssues } from "@/lib/api"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, runWorkspaceRequest, type WorkspaceOwner } from "@/contexts/workspace-context"
-import type { WorkspaceIssueDetail } from "@/lib/workspace-issue-reconciliation"
-
-export function workspaceIssueOptions(owner: WorkspaceOwner, issueId: string) {
- const key = owner.key("issues", "detail", issueId)
- return queryOptions({ queryKey: key, staleTime: 0,
- queryFn: async ({ signal }): Promise<WorkspaceIssueDetail> => {
- const token = captureWorkspaceOwner(owner)
- const assertActive = () => assertWorkspaceOwner(token, signal)
- assertActive()
- const requestRevision = owner.queryClient.getQueryData<WorkspaceIssueDetail>(key)?.liveRevision ?? 0
- const data = await getIssue(owner.workspaceId, issueId, workspaceRequestOptions(token, signal, assertActive))
- assertActive()
- return { ...data, requestRevision }
- },
- })
-}
-export function workspaceTraceOptions(owner: WorkspaceOwner, traceId: string) {
- return queryOptions({ queryKey: owner.key("traces", "detail", traceId), staleTime: 0,
- queryFn: async ({ signal }) => { const token = captureWorkspaceOwner(owner); const assertActive = () => assertWorkspaceOwner(token, signal); assertActive(); const data = await getTrace(traceId, owner.workspaceId, workspaceRequestOptions(token, signal, assertActive)); assertActive(); return data },
- })
-}
-export function workspaceTaskOptions(owner: WorkspaceOwner, taskId: string) {
- return queryOptions({ queryKey: owner.key("chat", "task", taskId), staleTime: 0, structuralSharing: reconcileQueryReceipt,
- queryFn: async ({ signal }) => { const token = captureWorkspaceOwner(owner); const assertActive = () => assertWorkspaceOwner(token, signal); assertActive(); const receipt = captureQueryReceipt(owner.queryClient, owner.key("chat", "task", taskId)); const data = await getTask(taskId, owner.workspaceId, workspaceRequestOptions(token, signal, assertActive)); assertActive(); return withQueryReceipt(data, receipt) },
- })
-}
-
-export function workspaceIssueListOptions(owner: WorkspaceOwner) {
- return queryOptions({ queryKey: owner.key("issues", "list", "board"), structuralSharing: (oldData, newData) => {
- if (!Array.isArray(oldData) || !Array.isArray(newData)) return newData
- const before = new Map((oldData as Awaited<ReturnType<typeof listIssues>>).map((row) => [row.id, row]))
- return (newData as Awaited<ReturnType<typeof listIssues>>).map((row) => {
- const previous = before.get(row.id)
- return previous && previous.updated_at > row.updated_at ? previous : row
- })
- }, queryFn: ({ signal }) => runWorkspaceRequest(owner, async (options) => {
- const [active, completed] = await Promise.all([listIssues(owner.workspaceId, { terminal: false }, options), listIssues(owner.workspaceId, { terminal: true }, options)])
- return [...active, ...completed]
- }, signal) })
-}
diff --git a/src/web/src/hooks/workspace/meetings-page.dom.test.tsx b/src/web/src/hooks/workspace/meetings-page.dom.test.tsx
deleted file mode 100644
index 372175727..000000000
--- a/src/web/src/hooks/workspace/meetings-page.dom.test.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, fireEvent, render, screen, waitFor, within } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider, useWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
-import AgentMeetingsPage from "@/app/(app)/w/[slug]/agents/[id]/meetings/page"
-import type { MeetingSession } from "@alook/shared"
-const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }))
-vi.mock("sonner", () => ({ toast }))
-vi.mock("next/navigation", () => ({ useParams: () => ({ id: "agent" }), useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: "meeting-user" } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-let owner: WorkspaceOwner
-let held: Array<{ path: string; method: string; body?: string; resolve: (response: Response) => void; signal?: AbortSignal }>
-const response = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } })
-const meeting = (id = "meeting", status = "pending"): MeetingSession => ({ id, agent_id: "agent", workspace_id: "workspace", title: `Meeting ${id}`, meeting_url: "https://meet.google.com/abc", status, from_email: null, is_whitelisted: false, participants: [], scheduled_at: null, started_at: null, completed_at: null, transcript_r2_key: null, summary: null, error: null, worker_session_id: null, created_at: "2026-10-01T12:00:00Z", updated_at: "2026-10-01T12:00:00Z" })
-function Probe({ show }: { show: boolean }) { const current = useWorkspaceOwner(); useLayoutEffect(() => { owner = current }); return show ? <AgentMeetingsPage /> : <p>Another view</p> }
-function App({ show = true }: { show?: boolean }) { return <ApplicationQueryProvider userId="meeting-user"><WorkspaceProvider workspaceId="workspace" slug="workspace"><Probe show={show} /></WorkspaceProvider></ApplicationQueryProvider> }
-beforeEach(async () => { await clearAllPersistedCaches(); held = []; toast.error.mockClear(); toast.success.mockClear(); vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }))); vi.stubGlobal("fetch", vi.fn((path: string, options: RequestInit) => new Promise<Response>((resolve) => held.push({ path, method: options.method ?? "GET", body: options.body as string | undefined, resolve, signal: options.signal ?? undefined })))) })
-afterEach(async () => {
- await act(async () => {
- vi.unstubAllGlobals(); owner?.queryClient.clear()
- })
-})
-async function loaded(rows: MeetingSession[] = []) {
- const view = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0].resolve(response(rows)))
- await waitFor(() => expect(owner.queryClient.getQueryData(owner.key("meetings", "agent"))).toEqual(rows))
- return view
-}
-async function createRequest() {
- act(() => fireEvent.click(screen.getByRole("button", { name: "Join Meeting" })))
- const dialog = await screen.findByRole("dialog")
- act(() => fireEvent.change(within(dialog).getByPlaceholderText("https://meet.google.com/abc-defg-hij"), { target: { value: "https://meet.google.com/new" } }))
- act(() => fireEvent.click(within(dialog).getByRole("button", { name: "Join Meeting" })))
- await waitFor(() => expect(held.some((request) => request.method === "POST")).toBe(true))
- return held.find((request) => request.method === "POST")!
-}
-describe("actual native meetings page", () => {
- it("creates through the real sheet and publishes one canonical list", async () => {
- await loaded()
- const request = await createRequest()
- expect(JSON.parse(request.body!)).toEqual({ meetingUrl: "https://meet.google.com/new" })
- await act(async () => request.resolve(response(meeting("created"))))
- await waitFor(() => expect(screen.getByText("Meeting created")).toBeTruthy())
- expect(owner.queryClient.getQueryData<MeetingSession[]>(owner.key("meetings", "agent"))?.map((row) => row.id)).toEqual(["created"])
- expect(toast.success).toHaveBeenCalledWith("Meeting created")
- expect(screen.queryByRole("dialog")).toBeNull()
- })
- it("settles a successful old-view create in its original native Query without old UI continuation", async () => {
- const view = await loaded()
- const request = await createRequest()
- const original = owner.queryClient.getQueryCache().find({ queryKey: owner.key("meetings", "agent"), exact: true })!
- view.rerender(<App show={false} />)
- await act(async () => request.resolve(response(meeting("old-success"))))
- await waitFor(() => expect((original.state.data as MeetingSession[]).map((row) => row.id)).toEqual(["old-success"]))
- expect(toast.success).not.toHaveBeenCalled(); expect(toast.error).not.toHaveBeenCalled()
- expect(held).toHaveLength(2)
- })
- it("does not resurrect a cleared Query after successful old create", async () => {
- const view = await loaded()
- const request = await createRequest()
- view.rerender(<App show={false} />)
- owner.queryClient.removeQueries({ queryKey: owner.key("meetings", "agent"), exact: true })
- await act(async () => request.resolve(response(meeting("old-cleared"))))
- expect(owner.queryClient.getQueryData(owner.key("meetings", "agent"))).toBeUndefined()
- expect(toast.success).not.toHaveBeenCalled()
- })
- it("keeps retired create401 quiet before global authentication effects", async () => {
- const view = await loaded()
- const request = await createRequest()
- const real = window, assign = vi.fn()
- vi.stubGlobal("window", new Proxy(real, { get: (target, key) => key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) }))
- view.rerender(<App show={false} />)
- await act(async () => request.resolve(response({}, 401)))
- await waitFor(() => expect(owner.queryClient.isMutating()).toBe(0))
- expect(assign).not.toHaveBeenCalled(); expect(toast.error).not.toHaveBeenCalled()
- expect(owner.application.lifecycle.get().active).toBe(true)
- })
- it("deletes through the real confirmation and retains ordinary current errors", async () => {
- await loaded([meeting()])
- act(() => fireEvent.click(screen.getByRole("button", { name: "Delete Meeting meeting" })))
- const dialog = await screen.findByRole("dialog")
- act(() => fireEvent.click(within(dialog).getByRole("button", { name: "Remove" })))
- await waitFor(() => expect(held.some((request) => request.method === "DELETE")).toBe(true))
- await act(async () => held.find((request) => request.method === "DELETE")!.resolve(response({ error: "failed" }, 500)))
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Failed to delete meeting"))
- expect(owner.queryClient.getQueryData<MeetingSession[]>(owner.key("meetings", "agent"))).toHaveLength(1)
- })
- it("last page observer release aborts a held read before a late401", async () => {
- const view = render(<App />)
- await waitFor(() => expect(held).toHaveLength(1))
- view.rerender(<App show={false} />)
- expect(held[0].signal?.aborted).toBe(true)
- const real = window, assign = vi.fn()
- vi.stubGlobal("window", new Proxy(real, { get: (target, key) => key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) }))
- await act(async () => held[0].resolve(response({}, 401)))
- expect(assign).not.toHaveBeenCalled(); expect(toast.error).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/hooks/workspace/resource-boundaries.dom.test.tsx b/src/web/src/hooks/workspace/resource-boundaries.dom.test.tsx
deleted file mode 100644
index 1fc16e972..000000000
--- a/src/web/src/hooks/workspace/resource-boundaries.dom.test.tsx
+++ /dev/null
@@ -1,269 +0,0 @@
-import React, { useLayoutEffect } from "react"
-import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"
-import type { AgentRuntime, Email, WsMessage } from "@alook/shared"
-import { beforeEach, describe, expect, it, vi } from "vitest"
-import { act, render, waitFor } from "@/test/react-dom-harness"
-import { ApplicationOwnerProvider, createApplicationOwner, retireApplicationOwner, type ApplicationOwner } from "@/lib/application-owner"
-import { WorkspaceProvider, captureWorkspaceOwner, useWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import type { WhitelistEntry } from "@/lib/api"
-import { emailBodyOptions, emailEntityKey, emailListOptions, emailThreadOptions, useEmailRows } from "./email-query-options"
-import { workspaceFileOptions } from "./file-query-options"
-import { useAgentPermissionCommand, usePendingAgentPermissions } from "./use-agent-permission-command"
-import { usePendingRuntimeCommands, useRuntimeCommand } from "./use-runtime-command"
-
-type Held = { path: string; method: string; body: string | undefined; signal: AbortSignal | undefined; resolve: (response: Response) => void }
-type FileReceipt = Extract<WsMessage, { type: "workspace.files" }>
-let application: ApplicationOwner
-let owner: WorkspaceOwner
-let held: Held[]
-let permission: ReturnType<typeof useAgentPermissionCommand>
-let runtimeCommand: ReturnType<typeof useRuntimeCommand>
-let pendingPermissions: ReturnType<typeof usePendingAgentPermissions>
-let pendingRuntimes: ReturnType<typeof usePendingRuntimeCommands>
-const listeners = new Set<(message: WsMessage) => void>()
-const subscribe = (callback: (message: WsMessage) => void) => { listeners.add(callback); return () => { listeners.delete(callback) } }
-const emit = (message: FileReceipt) => { for (const listener of listeners) listener(message) }
-const json = (data: unknown, status = 200) => new Response(status === 204 ? null : JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } })
-const email = (id = "mail", subject = "Original", html_body = "<p>Original body</p>"): Email => ({ id, subject, html_body, agent_id: "agent", from_email: "[email protected]", to_email: "[email protected]", r2_key: `mail/${id}`, is_whitelisted: true, forwarded: false, message_id: id, in_reply_to: "", references: "", attachments: [], status: "received", direction: "inbound", created_at: "2026-10-01T00:00:00Z" })
-const runtime = (): AgentRuntime => ({ id: "runtime", workspace_id: "workspace", daemon_id: null, runtime_mode: "local", provider: "codex", status: "online", device_info: "device", metadata: {}, pending_update_version: null, pending_rescan: false, last_seen_at: null, created_at: "2026-10-01T00:00:00Z", updated_at: "2026-10-01T00:00:00Z" })
-function Capture({ children }: { children: React.ReactNode }) {
- const current = useWorkspaceOwner()
- useLayoutEffect(() => { owner = current })
- return children
-}
-function App({ children = null, workspace = "workspace" }: { children?: React.ReactNode; workspace?: string }) {
- return <ApplicationOwnerProvider owner={application}><QueryClientProvider client={application.queryClient}><WorkspaceProvider workspaceId={workspace} slug={workspace}><Capture>{children}</Capture></WorkspaceProvider></QueryClientProvider></ApplicationOwnerProvider>
-}
-function EmailWindow({ thread = false }: { thread?: boolean }) {
- const current = useWorkspaceOwner()
- const window = useQuery(thread ? emailThreadOptions(current, "mail") : emailListOptions(current, "agent", "inbox"))
- const rows = useEmailRows(current, window.data?.ids ?? [])
- return <output data-testid="emails">{rows.map((row) => `${row.id}:${row.subject}`).join("|")}</output>
-}
-function Body() {
- const current = useWorkspaceOwner()
- const body = useQuery(emailBodyOptions(current, "mail"))
- return <output data-testid="body">{body.data?.content ?? "pending"}</output>
-}
-function File({ name = "file", mode = "read" }: { name?: string; mode?: "tree" | "read" }) {
- const current = useWorkspaceOwner()
- const result = useQuery(workspaceFileOptions(current, "agent", "runtime", mode, "/file.txt", subscribe))
- return <output data-testid={name}>{result.data?.content ?? result.status}</output>
-}
-function Permissions() {
- const current = useWorkspaceOwner()
- const command = useAgentPermissionCommand(current, "agent")
- const pending = usePendingAgentPermissions(current, "agent")
- useLayoutEffect(() => { permission = command; pendingPermissions = pending })
- return <output data-testid="permission-pending">{pending.map((action) => action.kind).join(",")}</output>
-}
-function Runtimes() {
- const current = useWorkspaceOwner()
- const command = useRuntimeCommand(current)
- const pending = usePendingRuntimeCommands(current)
- useLayoutEffect(() => { runtimeCommand = command; pendingRuntimes = pending })
- return <output data-testid="runtime-pending">{pending.map((action) => action.kind).join(",")}</output>
-}
-beforeEach(() => {
- held = []
- listeners.clear()
- localStorage.clear()
- application = createApplicationOwner("resource-user", new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }))
- vi.stubGlobal("fetch", vi.fn((path: RequestInfo | URL, options: RequestInit = {}) => new Promise<Response>((resolve) => held.push({ path: String(path), method: options.method ?? "GET", body: options.body as string | undefined, signal: options.signal ?? undefined, resolve }))))
- return async () => { retireApplicationOwner(application); await application.queryClient.cancelQueries(); application.queryClient.clear(); vi.unstubAllGlobals(); listeners.clear() }
-})
-
-describe("actual native workspace resource boundaries", () => {
- it.each([false, true])("publishes an ID-only email window with canonical entity/body readers (%s)", async (thread) => {
- const view = render(<App><EmailWindow thread={thread} /></App>)
- await waitFor(() => expect(held).toHaveLength(1))
- expect(new URL(held[0]!.path, "https://alook.test").searchParams.get("workspace_id")).toBe("workspace")
- if (thread) expect(held[0]!.path).toContain("/mail/thread")
- await act(async () => held[0]!.resolve(json([email()])))
- await waitFor(() => expect(view.getByTestId("emails").textContent).toBe("mail:Original"))
- const options = thread ? emailThreadOptions(owner, "mail") : emailListOptions(owner, "agent", "inbox")
- expect(owner.queryClient.getQueryData(options.queryKey)).toEqual({ ids: ["mail"] })
- expect(owner.queryClient.getQueryData<Email>(emailEntityKey(owner, "mail"))?.html_body).toBe("")
- expect(owner.queryClient.getQueryData(emailBodyOptions(owner, "mail").queryKey)).toEqual({ content: "<p>Original body</p>", isHtml: true })
- act(() => owner.queryClient.setQueryData(emailEntityKey(owner, "mail"), email("mail", "Live canonical", "")))
- await waitFor(() => expect(view.getByTestId("emails").textContent).toBe("mail:Live canonical"))
- expect(held).toHaveLength(1)
- })
-
- it("does not overwrite newer entity or body writes with a held email window", async () => {
- const view = render(<App />)
- act(() => {
- owner.queryClient.setQueryData(emailEntityKey(owner, "mail"), email("mail", "Baseline", ""))
- owner.queryClient.setQueryData(emailBodyOptions(owner, "mail").queryKey, { content: "Baseline body", isHtml: false })
- view.rerender(<App><EmailWindow /></App>)
- })
- await waitFor(() => expect(held).toHaveLength(1))
- act(() => {
- owner.queryClient.setQueryData(emailEntityKey(owner, "mail"), email("mail", "Newer canonical", ""))
- owner.queryClient.setQueryData(emailBodyOptions(owner, "mail").queryKey, { content: "Newer body", isHtml: false })
- })
- await act(async () => held[0]!.resolve(json([email("mail", "Held old", "<p>Held old body</p>")])))
- await waitFor(() => expect(view.getByTestId("emails").textContent).toBe("mail:Newer canonical"))
- expect(owner.queryClient.getQueryData(emailBodyOptions(owner, "mail").queryKey)).toEqual({ content: "Newer body", isHtml: false })
- })
-
- it("a newer body survives even when the held list can seed its unchanged entity", async () => {
- const view = render(<App />)
- act(() => {
- owner.queryClient.setQueryData(emailEntityKey(owner, "mail"), email("mail", "Baseline", ""))
- owner.queryClient.setQueryData(emailBodyOptions(owner, "mail").queryKey, { content: "Baseline body", isHtml: false })
- view.rerender(<App><EmailWindow /></App>)
- })
- await waitFor(() => expect(held).toHaveLength(1))
- act(() => owner.queryClient.setQueryData(emailBodyOptions(owner, "mail").queryKey, { content: "Newer body", isHtml: false }))
- await act(async () => held[0]!.resolve(json([email("mail", "Fresh header", "<p>Old body</p>")])))
- await waitFor(() => expect(view.getByTestId("emails").textContent).toBe("mail:Fresh header"))
- expect(owner.queryClient.getQueryData(emailBodyOptions(owner, "mail").queryKey)).toEqual({ content: "Newer body", isHtml: false })
- })
-
- it("shares a body request and aborts only its last observer before a late401", async () => {
- const view = render(<App><Body /><Body /></App>)
- await waitFor(() => expect(held).toHaveLength(1))
- view.rerender(<App><Body /></App>)
- expect(held[0]!.signal?.aborted).toBe(false)
- const assign = vi.fn(), originalWindow = window
- vi.stubGlobal("window", new Proxy(originalWindow, { get: (target, key) => key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) }))
- view.rerender(<App />)
- expect(held[0]!.signal?.aborted).toBe(true)
- await act(async () => held[0]!.resolve(json({}, 401)))
- expect(assign).not.toHaveBeenCalled()
- expect(application.lifecycle.get().active).toBe(true)
- })
-
- it("renders a real HTML body response through its native Query", async () => {
- const view = render(<App><Body /></App>)
- await waitFor(() => expect(held).toHaveLength(1))
- await act(async () => held[0]!.resolve(new Response("<p>Downloaded body</p>", { headers: { "Content-Type": "text/html" } })))
- await waitFor(() => expect(view.getByTestId("body").textContent).toBe("<p>Downloaded body</p>"))
- expect(owner.queryClient.getQueryData(emailBodyOptions(owner, "mail").queryKey)).toEqual({ content: "<p>Downloaded body</p>", isHtml: true })
- })
-
- it.each(["tree", "read"] as const)("matches an early file WS receipt to the actual HTTP request ID (%s)", async (mode) => {
- const view = render(<App><File mode={mode} /></App>)
- await waitFor(() => expect(held).toHaveLength(1))
- expect(JSON.parse(held[0]!.body!)).toEqual({ request_type: mode, path: "/file.txt" })
- const receipt: FileReceipt = { type: "workspace.files", agentId: "agent", requestId: "accepted", requestType: mode, result: { path: "/file.txt", content: "Matching file" } }
- act(() => { emit({ ...receipt, agentId: "other", result: { path: "/file.txt", content: "Wrong agent" } }); emit({ ...receipt, requestId: "foreign", result: { path: "/file.txt", content: "Wrong request" } }); emit(receipt) })
- expect(view.getByTestId("file").textContent).toBe("pending")
- await act(async () => held[0]!.resolve(json({ request_id: "accepted" })))
- await waitFor(() => expect(view.getByTestId("file").textContent).toBe("Matching file"))
- expect(listeners.size).toBe(0)
- })
-
- it("retains a shared file read until its last observer then aborts HTTP and unsubscribes WS", async () => {
- const view = render(<App><File name="first" /><File name="second" /></App>)
- await waitFor(() => expect(held).toHaveLength(1))
- expect(listeners.size).toBe(1)
- view.rerender(<App><File name="first" /></App>)
- expect(held[0]!.signal?.aborted).toBe(false)
- expect(listeners.size).toBe(1)
- view.rerender(<App />)
- expect(held[0]!.signal?.aborted).toBe(true)
- expect(listeners.size).toBe(0)
- await act(async () => held[0]!.resolve(json({ request_id: "late" })))
- expect(owner.queryClient.getQueryData(workspaceFileOptions(owner, "agent", "runtime", "read", "/file.txt", subscribe).queryKey)).toBeUndefined()
- })
-
- it("serializes whitelist actions while native pending includes the queued command", async () => {
- const view = render(<App><Permissions /></App>)
- act(() => owner.queryClient.setQueryData(owner.key("agent-whitelist", "agent"), []))
- act(() => {
- permission.mutate({ action: { kind: "whitelist-add", email: "[email protected]" }, token: captureWorkspaceOwner(owner) })
- permission.mutate({ action: { kind: "whitelist-remove", id: "new-entry" }, token: captureWorkspaceOwner(owner) })
- })
- await waitFor(() => expect(pendingPermissions).toHaveLength(2))
- expect(view.getByTestId("permission-pending").textContent).toBe("whitelist-add,whitelist-remove")
- await waitFor(() => expect(held).toHaveLength(1))
- expect(held[0]!.method).toBe("POST")
- expect(JSON.parse(held[0]!.body!)).toEqual({ email: "[email protected]" })
- const row: WhitelistEntry = { id: "new-entry", email: "[email protected]", created_at: "2026-10-01T00:00:00Z" }
- await act(async () => held[0]!.resolve(json(row)))
- await waitFor(() => expect(held).toHaveLength(2))
- expect(owner.queryClient.getQueryData(owner.key("agent-whitelist", "agent"))).toEqual([row])
- expect(held[1]!.method).toBe("DELETE")
- expect(held[1]!.path).toContain("/whitelist/new-entry?")
- await act(async () => held[1]!.resolve(json(undefined, 204)))
- await waitFor(() => expect(pendingPermissions).toEqual([]))
- expect(owner.queryClient.getQueryData(owner.key("agent-whitelist", "agent"))).toEqual([])
- })
-
- it("does not replace newer permission facts or resurrect a replacement resource", async () => {
- render(<App><Permissions /></App>)
- const key = owner.key("agent-whitelist", "agent")
- const row: WhitelistEntry = { id: "live", email: "[email protected]", created_at: "2026-10-01T00:00:00Z" }
- act(() => owner.queryClient.setQueryData(key, []))
- act(() => permission.mutate({ action: { kind: "whitelist-add", email: "[email protected]" }, token: captureWorkspaceOwner(owner) }))
- await waitFor(() => expect(held).toHaveLength(1))
- act(() => { owner.queryClient.removeQueries({ queryKey: key, exact: true }); owner.queryClient.setQueryData(key, [row]) })
- const replacement = owner.queryClient.getQueryCache().find({ queryKey: key, exact: true })!
- await act(async () => held[0]!.resolve(json({ ...row, id: "old", email: "[email protected]" })))
- await waitFor(() => expect(pendingPermissions).toEqual([]))
- expect(owner.queryClient.getQueryData(key)).toEqual([row])
- expect(replacement.state.isInvalidated).toBe(false)
- })
-
- it("serializes runtime update/rescan and preserves a newer live pending value", async () => {
- render(<App><Runtimes /></App>)
- const key = owner.key("runtimes")
- act(() => owner.queryClient.setQueryData(key, [runtime()]))
- act(() => {
- runtimeCommand.mutate({ kind: "update", id: "runtime", token: captureWorkspaceOwner(owner) })
- runtimeCommand.mutate({ kind: "rescan", id: "runtime", token: captureWorkspaceOwner(owner) })
- })
- await waitFor(() => expect(pendingRuntimes).toHaveLength(2))
- await waitFor(() => expect(held).toHaveLength(1))
- expect(held[0]!.path).toContain("/runtime/update?")
- act(() => owner.queryClient.setQueryData(key, [{ ...runtime(), pending_update_version: "newer-live" }]))
- await act(async () => held[0]!.resolve(json({ pending_update_version: "held-old" })))
- await waitFor(() => expect(held).toHaveLength(2))
- expect(owner.queryClient.getQueryData<AgentRuntime[]>(key)?.[0]?.pending_update_version).toBe("newer-live")
- expect(held[1]!.path).toContain("/runtime/rescan?")
- await act(async () => held[1]!.resolve(json({ pending_rescan: true })))
- await waitFor(() => expect(pendingRuntimes).toEqual([]))
- expect(owner.queryClient.getQueryData<AgentRuntime[]>(key)?.[0]).toMatchObject({ pending_update_version: "newer-live", pending_rescan: true })
- })
-
- it.each(["permission", "runtime"] as const)("physically aborts a retired %s view and suppresses its late401 auth/UI effects", async (kind) => {
- const view = render(<App>{kind === "permission" ? <Permissions /> : <Runtimes />}</App>)
- const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }
- act(() => {
- if (kind === "permission") {
- owner.queryClient.setQueryData(owner.key("agent-whitelist", "agent"), [])
- permission.mutate({ action: { kind: "whitelist-add", email: "[email protected]" }, token: captureWorkspaceOwner(owner) }, callbacks)
- } else {
- owner.queryClient.setQueryData(owner.key("runtimes"), [runtime()])
- runtimeCommand.mutate({ kind: "update", id: "runtime", token: captureWorkspaceOwner(owner) }, callbacks)
- }
- })
- await waitFor(() => expect(held).toHaveLength(1))
- const original = owner, assign = vi.fn(), originalWindow = window
- vi.stubGlobal("window", new Proxy(originalWindow, { get: (target, key) => key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) }))
- view.rerender(<App />)
- expect(held[0]!.signal?.aborted).toBe(true)
- await act(async () => held[0]!.resolve(json({}, 401)))
- await waitFor(() => expect(original.queryClient.isMutating()).toBe(0))
- expect(assign).not.toHaveBeenCalled()
- expect(callbacks.onSuccess).not.toHaveBeenCalled()
- expect(callbacks.onError).not.toHaveBeenCalled()
- expect(callbacks.onSettled).not.toHaveBeenCalled()
- expect(application.lifecycle.get().active).toBe(true)
- })
-
- it("workspace replacement cancels its original query without authorizing a late response on reentry", async () => {
- const view = render(<App><Body /></App>)
- await waitFor(() => expect(held).toHaveLength(1))
- const original = owner
- view.rerender(<App workspace="other" />)
- expect(original.lifecycle.get().active).toBe(false)
- expect(held[0]!.signal?.aborted).toBe(true)
- view.rerender(<App />)
- expect(owner).not.toBe(original)
- await act(async () => held[0]!.resolve(new Response("old body")))
- expect(owner.queryClient.getQueryData(emailBodyOptions(owner, "mail").queryKey)).toBeUndefined()
- })
-})
diff --git a/src/web/src/hooks/workspace/settings-query-options.ts b/src/web/src/hooks/workspace/settings-query-options.ts
deleted file mode 100644
index 34edbe121..000000000
--- a/src/web/src/hooks/workspace/settings-query-options.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { queryOptions } from "@tanstack/react-query"
-import { listMembers, listInvites, listWorkspaces, listWhitelist, listAgentAccess, fetchModelOptions, getMinCliVersion, fetchLatestCliVersion } from "@/lib/api"
-import { applicationKey, runApplicationRequest } from "@/lib/application-owner"
-import { runWorkspaceRequest, type WorkspaceOwner } from "@/contexts/workspace-context"
-
-export function workspaceMembersOptions(owner: WorkspaceOwner) {
- return queryOptions({ queryKey: owner.key("members"), queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listMembers(owner.workspaceId, options), signal) })
-}
-export function applicationWorkspacesOptions(owner: WorkspaceOwner["application"]) {
- return queryOptions({ queryKey: applicationKey(owner, "workspaces"), queryFn: ({ signal }) => runApplicationRequest(owner, listWorkspaces, signal) })
-}
-export function workspaceInvitesOptions(owner: WorkspaceOwner) {
- return queryOptions({ queryKey: owner.key("invites"), queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listInvites(owner.workspaceId, options), signal) })
-}
-export function agentWhitelistOptions(owner: WorkspaceOwner, agentId: string) {
- return queryOptions({ queryKey: owner.key("agent-whitelist", agentId), queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listWhitelist(agentId, owner.workspaceId, options), signal) })
-}
-export function agentAccessOptions(owner: WorkspaceOwner, agentId: string) {
- return queryOptions({ queryKey: owner.key("agent-access", agentId), queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listAgentAccess(owner.workspaceId, agentId, options), signal) })
-}
-export function modelCatalogOptions(owner: WorkspaceOwner) {
- return queryOptions({ queryKey: applicationKey(owner.application, "model-options"), staleTime: 300_000, queryFn: ({ signal }) => runApplicationRequest(owner.application, fetchModelOptions, signal) })
-}
-export function minCliVersionOptions(owner: WorkspaceOwner) {
- return queryOptions({ queryKey: applicationKey(owner.application, "min-cli-version"), staleTime: 300_000, queryFn: ({ signal }) => runApplicationRequest(owner.application, getMinCliVersion, signal) })
-}
-
-export function latestCliVersionOptions(owner: WorkspaceOwner) {
- return queryOptions({ queryKey: applicationKey(owner.application, "latest-cli-version"), staleTime: 300_000, queryFn: ({ signal }) => runApplicationRequest(owner.application, fetchLatestCliVersion, signal) })
-}
diff --git a/src/web/src/hooks/workspace/trace-query-options.ts b/src/web/src/hooks/workspace/trace-query-options.ts
deleted file mode 100644
index 8b6177dd7..000000000
--- a/src/web/src/hooks/workspace/trace-query-options.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { infiniteQueryOptions } from "@tanstack/react-query"
-import { listTraces } from "@/lib/api"
-import { runWorkspaceRequest, type WorkspaceOwner } from "@/contexts/workspace-context"
-
-export function workspaceTracesOptions(owner: WorkspaceOwner, filters: { status: string; agentId: string; channel: string }) {
- return infiniteQueryOptions({
- queryKey: owner.key("traces", "list", filters),
- initialPageParam: null as string | null,
- staleTime: 0,
- queryFn: ({ signal, pageParam }) => runWorkspaceRequest(owner, (options) => listTraces(owner.workspaceId, {
- limit: 30,
- before: pageParam ?? undefined,
- status: filters.status === "all" ? undefined : filters.status || undefined,
- multiAgent: true,
- agentId: filters.agentId || undefined,
- channel: filters.channel || undefined,
- }, options), signal),
- getNextPageParam: (page) => page.has_more && page.traces.length ? page.traces.at(-1)!.started_at : undefined,
- })
-}
diff --git a/src/web/src/hooks/workspace/traces-page.dom.test.tsx b/src/web/src/hooks/workspace/traces-page.dom.test.tsx
deleted file mode 100644
index 638d0d819..000000000
--- a/src/web/src/hooks/workspace/traces-page.dom.test.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useLayoutEffect } from "react"
-import "fake-indexeddb/auto"
-import React from "react"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, fireEvent, render, screen, waitFor, mockElementGeometry } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider } from "@/lib/application-owner"
-import { WorkspaceProvider, useWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
-import TracesPage from "@/app/(app)/w/[slug]/traces/page"
-import TraceDetailPage from "@/app/(app)/w/[slug]/traces/[traceId]/page"
-const state = vi.hoisted(() => ({ search: new URLSearchParams("status=active"), traceId: "trace-A", analytics: vi.fn() }))
-vi.mock("@/lib/analytics", () => ({ trackThreadViewed: state.analytics }))
-vi.mock("next/navigation", () => ({ useParams: () => ({ traceId: state.traceId }), useSearchParams: () => state.search, useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))
-vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: "traces-user" } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("@/contexts/agent-context", () => ({ useAgentContext: () => ({ agents: [] }) }))
-vi.mock("@/contexts/channel-context", () => ({ useChannel: () => ({ channels: [] }) }))
-let owner: WorkspaceOwner
-let held: Array<{ path: string; resolve: (response: Response) => void; signal: AbortSignal }>
-const response = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } })
-const trace = (id: string, started_at: string) => ({ trace_id: id, root_prompt: `Prompt ${id}`, root_agent_id: "agent", root_agent: null, helper_agents: [], status: "active", task_count: 2, started_at, completed_at: null, channel: "general" })
-const task = (id: string) => ({ id, agent_id: "agent", agent: null, parent_task_id: null, prompt: `Task ${id}`, status: "completed", type: "chat", conversation_id: "conversation", created_at: "2026-10-01T01:00:00Z", completed_at: "2026-10-01T01:01:00Z" })
-function Probe({ detail, show }: { detail: boolean; show: boolean }) { const current = useWorkspaceOwner(); useLayoutEffect(() => { owner = current }); return show ? detail ? <TraceDetailPage /> : <TracesPage /> : <p>Other page</p> }
-function App({ detail = false, show = true }: { detail?: boolean; show?: boolean }) { return <ApplicationQueryProvider userId="traces-user"><WorkspaceProvider workspaceId="workspace" slug="workspace"><Probe detail={detail} show={show} /></WorkspaceProvider></ApplicationQueryProvider> }
-beforeEach(async () => { await clearAllPersistedCaches(); state.search = new URLSearchParams("status=active"); state.traceId = "trace-A"; state.analytics.mockClear(); held = []; vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }))); vi.stubGlobal("fetch", vi.fn((path: string, options: RequestInit) => new Promise<Response>((resolve) => held.push({ path, resolve, signal: options.signal as AbortSignal })))) })
-afterEach(async () => {
- await act(async () => {
- vi.unstubAllGlobals(); owner?.queryClient.clear()
- })
-})
-describe("actual native trace pages", () => {
- it("paginates one InfiniteQuery, deduplicates rows and preserves page params", async () => {
- render(<App />); await waitFor(() => expect(held).toHaveLength(1))
- expect(new URL(held[0].path, "https://alook.test").searchParams.get("multiAgent")).toBe("true")
- await act(async () => held[0].resolve(response({ traces: [trace("new", "2026-10-02T00:00:00Z")], has_more: true })))
- const link = await screen.findByRole("link", { name: /Prompt new/ }); const scroll = link.parentElement!.parentElement!
- const restore = mockElementGeometry(scroll, { scrollHeight: 600, clientHeight: 500, scrollTop: 10 })
- act(() => { fireEvent.scroll(scroll); fireEvent.scroll(scroll) })
- await waitFor(() => expect(held).toHaveLength(2))
- expect(new URL(held[1].path, "https://alook.test").searchParams.get("before")).toBe("2026-10-02T00:00:00Z")
- await act(async () => held[1].resolve(response({ traces: [trace("new", "2026-10-02T00:00:00Z"), trace("old", "2026-10-01T00:00:00Z")], has_more: false })))
- await waitFor(() => expect(screen.getByRole("link", { name: /Prompt old/ })).toBeTruthy())
- expect(screen.getAllByRole("link", { name: /Prompt new/ })).toHaveLength(1)
- const query = owner.queryClient.getQueryCache().findAll({ queryKey: owner.key("traces", "list") })[0]
- expect(query.state.data).toMatchObject({ pageParams: [null, "2026-10-02T00:00:00Z"], pages: [{ has_more: true }, { has_more: false }] }); restore()
- })
- it("filter replacement cancels the old native read before old401", async () => {
- const view = render(<App />); await waitFor(() => expect(held).toHaveLength(1))
- state.search = new URLSearchParams("status=completed"); view.rerender(<App />)
- await waitFor(() => expect(held).toHaveLength(2)); expect(held[0].signal.aborted).toBe(true)
- const real = window, assign = vi.fn(); vi.stubGlobal("window", new Proxy(real, { get: (target, key) => key === "location" ? { origin: "https://alook.test", assign } : Reflect.get(target, key, target) }))
- await act(async () => { held[0].resolve(response({}, 401)); held[1].resolve(response({ traces: [trace("current", "2026-10-02T00:00:00Z")], has_more: false })) })
- await screen.findByRole("link", { name: /Prompt current/ }); expect(assign).not.toHaveBeenCalled()
- })
- it("trace detail shares the canonical resource and ignores old selection analytics", async () => {
- const view = render(<App detail />); await waitFor(() => expect(held).toHaveLength(1))
- state.traceId = "trace-B"; view.rerender(<App detail />)
- await waitFor(() => expect(held).toHaveLength(2)); expect(held[0].signal.aborted).toBe(true)
- await act(async () => { held[0].resolve(response({ trace_id: "trace-A", channel: "old", tasks: [task("old")] })); held[1].resolve(response({ trace_id: "trace-B", channel: "current", tasks: [task("current")] })) })
- await screen.findByRole("link", { name: /Task current/ })
- expect(screen.queryByText("Task old")).toBeNull(); expect(state.analytics).toHaveBeenCalledTimes(1)
- expect(owner.queryClient.getQueryData(owner.key("traces", "detail", "trace-B"))).toMatchObject({ channel: "current", tasks: [{ id: "current" }] })
- })
-})
diff --git a/src/web/src/hooks/workspace/use-agent-permission-command.ts b/src/web/src/hooks/workspace/use-agent-permission-command.ts
deleted file mode 100644
index 608dfaec0..000000000
--- a/src/web/src/hooks/workspace/use-agent-permission-command.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-"use client"
-
-import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
-
-import { useCallback } from "react"
-
-import { useWorkspaceViewSource } from "./use-workspace-view-source"
-
-import { useMutation,useMutationState,type Query } from "@tanstack/react-query"
-import type { Agent } from "@alook/shared"
-import { addWhitelistEmail,removeWhitelistEmail,updateAgent,grantAgentAccess,revokeAgentAccess,type WhitelistEntry,type AgentAccessEntry } from "@/lib/api"
-import { captureWorkspaceOwner,assertWorkspaceOwner,workspaceRequestOptions,type WorkspaceOwner } from "@/contexts/workspace-context"
-
-type AgentPermissionAction =
- | { kind: "whitelist-add"; email: string }
- | { kind: "whitelist-remove"; id: string }
- | { kind: "visibility"; value: string }
- | { kind: "grant"; userId: string }
- | { kind: "revoke"; userId: string; removeWhitelist: boolean }
-type Command = { action: AgentPermissionAction; token: ReturnType<typeof captureWorkspaceOwner>; assertActive?: (() => void) & { signal: AbortSignal } }
-
-export function usePendingAgentPermissions(owner: WorkspaceOwner, agentId: string) {
- return useMutationState({ filters: { mutationKey: owner.key("agent-permission-command", agentId), status: "pending" }, select: (mutation) => (mutation.state.variables as Command).action })
-}
-
-export function useAgentPermissionCommand(owner: WorkspaceOwner, agentId: string) {
- const key = owner.key("agent-permission-command", agentId)
- const source = useWorkspaceViewSource(owner, `agent-permissions:${agentId}`, true)
- type NativeIntent = Command & { view: ReturnType<typeof source.capture>; resources: Query[] }
- const native = useMutation({ meta: { observabilityAction: "agent.permission.command" }, mutationKey: key, scope: { id: JSON.stringify(key) },
- mutationFn: async ({ action, token, view, resources, assertActive }: NativeIntent) => {
- const assert = () => { assertWorkspaceOwner(token, assertActive?.signal ?? view.signal); view.assert(); assertActive?.() }
- const qc = owner.queryClient, whitelistKey = owner.key("agent-whitelist", agentId), accessKey = owner.key("agent-access", agentId), agentsKey = owner.key("agents")
- const keys = action.kind === "visibility" ? [agentsKey] : action.kind.startsWith("whitelist") ? [whitelistKey] : [accessKey, whitelistKey]
- assert()
- await Promise.all(resources.filter((query) => keys.some((key) => JSON.stringify(key) === JSON.stringify(query.queryKey)) && qc.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query).map((query) => qc.cancelQueries({ queryKey: query.queryKey, exact: true })))
- assert()
- const sourceKey = action.kind === "visibility" ? agentsKey : action.kind.startsWith("whitelist") ? whitelistKey : accessKey
- const resource = resources.find((query) => JSON.stringify(query.queryKey) === JSON.stringify(sourceKey)), baseline = resource?.state.data
- const writes = resource?.state.dataUpdateCount
- const qualified = () => resource && qc.getQueryCache().find({ queryKey: sourceKey, exact: true }) === resource && resource.state.dataUpdateCount === writes
- const options = workspaceRequestOptions(token, assertActive?.signal ?? view.signal, assert)
- try {
- if (action.kind === "whitelist-add") {
- const row = await addWhitelistEmail(agentId, action.email, owner.workspaceId, options)
- assert()
- if (qualified()) qc.setQueryData<WhitelistEntry[]>(whitelistKey, (rows) => [...(rows ?? []).filter((entry) => entry.id !== row.id), row])
- } else if (action.kind === "whitelist-remove") {
- await removeWhitelistEmail(agentId, action.id, owner.workspaceId, options)
- assert()
- if (qualified()) qc.setQueryData<WhitelistEntry[]>(whitelistKey, (rows) => rows?.filter((entry) => entry.id !== action.id))
- } else if (action.kind === "visibility") {
- const row = await updateAgent(agentId, { visibility: action.value }, owner.workspaceId, options)
- assert()
- const old = (baseline as Agent[] | undefined)?.find((entry) => entry.id === agentId)
- if (qualified()) qc.setQueryData<Agent[]>(agentsKey, (rows) => rows?.map((entry) => entry.id === agentId && entry.visibility === old?.visibility ? { ...entry, visibility: row.visibility } : entry))
- } else if (action.kind === "grant") {
- await grantAgentAccess(owner.workspaceId, agentId, action.userId, options)
- assert()
- } else {
- await revokeAgentAccess(owner.workspaceId, agentId, action.userId, action.removeWhitelist, options)
- assert()
- if (qualified()) qc.setQueryData<AgentAccessEntry[]>(accessKey, (rows) => rows?.filter((entry) => entry.user_id !== action.userId))
- }
- assert()
- await Promise.all(resources.filter((query) => qc.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query).map((query) => qc.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false })))
- assert()
- } catch (error) { assert(); throw error }
- },
- })
- const capture = useCallback((input: Command): NativeIntent => {
- const view = source.capture()
- view.assert(); assertWorkspaceOwner(input.token); input.assertActive?.()
- return { ...input, view, resources: [...new Set([owner.key("agents"), owner.key("agent-whitelist", agentId), owner.key("agent-access", agentId)].flatMap((queryKey) => owner.queryClient.getQueryCache().findAll({ queryKey })))] }
- }, [owner, agentId, source])
- const assertCurrent = useCallback((args: NativeIntent) => { args.view.assert(); assertWorkspaceOwner(args.token); args.assertActive?.() }, [])
- return useNativeMutationFacade(native, capture, assertCurrent)
-}
diff --git a/src/web/src/hooks/workspace/use-chat-artifact-selection.ts b/src/web/src/hooks/workspace/use-chat-artifact-selection.ts
deleted file mode 100644
index d9da34c8d..000000000
--- a/src/web/src/hooks/workspace/use-chat-artifact-selection.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-"use client"
-
-import { useMemo, useCallback } from "react"
-import { createStore, useSelector } from "@tanstack/react-store"
-import { skipToken, useQuery, type QueryKey } from "@tanstack/react-query"
-import type { Artifact } from "@alook/shared"
-import type { WorkspaceOwner } from "@/contexts/workspace-context"
-import { chatExtrasKey } from "@/lib/chat-cache"
-import { captureChatIntent, assertChatIntent } from "./use-chat-data"
-
-type ChatView = Parameters<typeof captureChatIntent>[1]
-export function useChatArtifactSelection(owner: WorkspaceOwner, view: ChatView, issueId: string | null) {
- const selection = useMemo(() => createStore<{ key: QueryKey; id: string } | null>(null), [])
- const reference = useSelector(selection, (state) => state)
- const artifact = useQuery({ queryKey: reference?.key ?? owner.key("artifacts", "__none__"), queryFn: skipToken, enabled: false,
- select: (data: { artifacts?: Artifact[] }) => data.artifacts?.find((row) => row.id === reference?.id) ?? null,
- }).data ?? null
- const setArtifact = useCallback((row: Artifact | null) => {
- assertChatIntent(captureChatIntent(owner, view))
- if (!row) { selection.setState(() => null); return }
- const issueKey = owner.key("issues", "detail", issueId ?? "__none__")
- const issue = owner.queryClient.getQueryData<{ artifacts: Artifact[] }>(issueKey)
- const key = issue?.artifacts.some((candidate) => candidate.id === row.id) ? issueKey : chatExtrasKey(owner, row.conversation_id)
- selection.setState(() => ({ key, id: row.id }))
- }, [owner, view, issueId, selection])
- return [artifact, setArtifact] as const
-}
diff --git a/src/web/src/hooks/workspace/use-chat-data.ts b/src/web/src/hooks/workspace/use-chat-data.ts
deleted file mode 100644
index 64f9fbfbe..000000000
--- a/src/web/src/hooks/workspace/use-chat-data.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-"use client"
-
-import { deriveView, valueEvidence, sourceEvidence } from "@/lib/observability/data-source"
-import { useCallback, useMemo, useLayoutEffect } from "react"
-import { createStore, useSelector } from "@tanstack/react-store"
-import { useQueries, useQuery, skipToken, type InfiniteData, type UseQueryResult } from "@tanstack/react-query"
-import type { Conversation, Message, Artifact, TaskApi, TaskMessageResponse } from "@alook/shared"
-import type { PreviousConversation } from "@/lib/api"
-import type { Store } from "@tanstack/react-store"
-import type { WorkspaceOwner } from "@/contexts/workspace-context"
-import { assertWorkspaceOwner, captureWorkspaceOwner, workspaceRequestOptions } from "@/contexts/workspace-context"
-import type { ApiRequestOptions } from "@/lib/api/client"
-import { chatMessagesKey, chatExtrasKey, sortedChatMessages, type ChatMessagesData, type ChatExtras } from "@/lib/chat-cache"
-
-const combineChatQueryData = (results: UseQueryResult[]) => results.map((result) => result.data as ChatMessagesData | undefined)
-
-export function useChatData(owner: WorkspaceOwner, identity: string, targetConversationId: string | null) {
- const view = useMemo(() => createStore({
- owner, identity, active: true, generation: 0,
- conversationId: targetConversationId, frontierId: targetConversationId,
- window: [] as Array<{ conversationId: string; id: string }>,
- optimistic: new Map<string, Message>(), selectedTaskId: undefined as string | null | undefined,
- previousKey: null as readonly unknown[] | null, previousIds: [] as string[], previousHint: false,
- }), [owner, identity, targetConversationId])
- useLayoutEffect(() => {
- view.setState((state) => ({ ...state, active: true }))
- return () => {
- view.setState((state) => ({ ...state, active: false, generation: state.generation + 1 }))
- void owner.queryClient.cancelQueries({ queryKey: owner.key("chat", "open", identity) })
- void owner.queryClient.cancelQueries({ queryKey: owner.key("chat", "io", identity) })
- }
- }, [identity, owner, view])
- const conversationId = useSelector(view, (state) => state.conversationId)
- const frontierId = useSelector(view, (state) => state.frontierId)
- const refs = useSelector(view, (state) => state.window)
- const optimistic = useSelector(view, (state) => state.optimistic)
- const conversationIds = useMemo(() => [...new Set(refs.map((row) => row.conversationId))], [refs])
- const messageQueries = useQueries({ queries: conversationIds.map((id) => ({ queryKey: chatMessagesKey(owner, id), queryFn: skipToken, enabled: false })), combine: combineChatQueryData })
- const messages = useMemo(() => {
- const rows = new Map<string, Message>()
- for (let i = 0; i < conversationIds.length; i++) {
- for (const row of sortedChatMessages(messageQueries[i])) rows.set(`${row.conversation_id}:${row.id}`, row)
- }
- return refs.flatMap((ref) => {
- const row = optimistic.get(ref.id) ?? rows.get(`${ref.conversationId}:${ref.id}`)
- return row ? [row] : []
- })
- }, [conversationIds, messageQueries, optimistic, refs])
- deriveView(messages, [...messageQueries.map(value => valueEvidence(owner.queryClient, value)), ...(optimistic.size ? [sourceEvidence(optimistic, "local_mutation")] : [])], messages.length)
- const extrasKey = chatExtrasKey(owner, conversationId ?? "__none__")
- const extras = useQuery<ChatExtras>({ queryKey: extrasKey, queryFn: skipToken, enabled: false }).data
- const taskKey = owner.key("chat", "active-task", conversationId ?? "__none__")
- const canonicalTaskId = useQuery<{ id: string | null }>({ queryKey: taskKey, queryFn: skipToken, enabled: false }).data?.id
- const selectedTaskId = useSelector(view, (state) => state.selectedTaskId)
- const activeTaskId = selectedTaskId === undefined ? canonicalTaskId : selectedTaskId
- const activeTask = useQuery<TaskApi>({ queryKey: owner.key("chat", "task", activeTaskId ?? "__none__"), queryFn: skipToken, enabled: false }).data ?? null
- const taskMessagesKey = owner.key("chat", "task-messages", activeTask?.id ?? "__none__")
- const taskMessages = useQuery<TaskMessageResponse[]>({ queryKey: taskMessagesKey, queryFn: skipToken, enabled: false }).data ?? EMPTY_TASK_MESSAGES
- const currentMessages = useQuery<ChatMessagesData>({ queryKey: chatMessagesKey(owner, frontierId ?? "__none__"), queryFn: skipToken, enabled: false }).data
- const previousKey = useSelector(view, (state) => state.previousKey)
- const previousIds = useSelector(view, (state) => state.previousIds)
- const previousHint = useSelector(view, (state) => state.previousHint)
- const previous = useQuery<InfiniteData<{ conversations: PreviousConversation[]; has_more: boolean }>>({ queryKey: previousKey ?? owner.key("chat", "previous-conversations", "__none__"), queryFn: skipToken, enabled: false }).data
- const readPrevious = useCallback(() => {
- const state = view.get()
- const data = state.previousKey ? owner.queryClient.getQueryData<InfiniteData<{ conversations: PreviousConversation[]; has_more: boolean }>>(state.previousKey) : undefined
- const rows = new Map((data?.pages ?? []).flatMap((page) => page.conversations).map((row) => [row.id, row]))
- return state.previousIds.flatMap((id) => {
- const row = rows.get(id)
- if (row) return [row]
- const conversation = owner.queryClient.getQueryData<ChatExtras>(chatExtrasKey(owner, id))?.conversation
- return conversation ? [{ id, created_at: conversation.created_at }] : []
- })
- }, [owner, view])
- const previousConversations = useMemo(() => {
- const rows = new Map((previous?.pages ?? []).flatMap((page) => page.conversations).map((row) => [row.id, row]))
- return previousIds.flatMap((id) => {
- const row = rows.get(id)
- if (row) return [row]
- const conversation = owner.queryClient.getQueryData<ChatExtras>(chatExtrasKey(owner, id))?.conversation
- return conversation ? [{ id, created_at: conversation.created_at }] : []
- })
- }, [owner, previous, previousIds])
- const assertCurrent = useCallback(() => {
- assertWorkspaceOwner(captureWorkspaceOwner(owner))
- if (!view.get().active) throw new DOMException("Retired chat view", "AbortError")
- }, [owner, view])
- const readMessages = useCallback(() => {
- const state = view.get()
- const all = new Map<string, Message>()
- for (const id of new Set(state.window.map((ref) => ref.conversationId))) {
- for (const row of sortedChatMessages(owner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(owner, id)))) all.set(`${id}:${row.id}`, row)
- }
- return state.window.flatMap((ref) => {
- const row = state.optimistic.get(ref.id) ?? all.get(`${ref.conversationId}:${ref.id}`)
- return row ? [row] : []
- })
- }, [owner, view])
- const setMessages = useCallback((update: Message[] | ((rows: Message[]) => Message[])) => {
- assertCurrent()
- const next = typeof update === "function" ? update(readMessages()) : update
- const drafts = new Map<string, Message>()
- for (const row of next) {
- if (row.id.startsWith("temp-")) { drafts.set(row.id, row); continue }
- }
- view.setState((state) => ({ ...state, window: next.map((row) => ({ conversationId: row.conversation_id, id: row.id })), optimistic: drafts }))
- }, [assertCurrent, readMessages, view])
- const selectConversation = useCallback((conversationId: string) => {
- assertCurrent()
- view.setState((state) => ({ ...state, conversationId, frontierId: conversationId, selectedTaskId: state.conversationId === conversationId ? state.selectedTaskId : undefined }))
- }, [assertCurrent, view])
- const setConversation = useCallback((update: Conversation | null | ((row: Conversation | null) => Conversation | null)) => {
- assertCurrent()
- const id = view.get().conversationId
- const old = id ? owner.queryClient.getQueryData<ChatExtras>(chatExtrasKey(owner, id))?.conversation ?? null : null
- const next = typeof update === "function" ? update(old) : update
- if (next && !owner.queryClient.getQueryData<ChatExtras>(chatExtrasKey(owner, next.id))?.conversation) owner.queryClient.setQueryData<ChatExtras>(chatExtrasKey(owner, next.id), (data) => ({ conversation: next, artifacts: data?.artifacts ?? [], hasMoreArtifacts: data?.hasMoreArtifacts ?? false }))
- view.setState((state) => ({ ...state, conversationId: next?.id ?? null, frontierId: next?.id ?? null, selectedTaskId: state.conversationId === next?.id ? state.selectedTaskId : undefined }))
- }, [assertCurrent, owner, view])
- const setActiveTask = useCallback((update: TaskApi | null | ((task: TaskApi | null) => TaskApi | null)) => {
- assertCurrent()
- const state = view.get(), id = state.conversationId
- if (!id) return
- const oldId = state.selectedTaskId === undefined ? owner.queryClient.getQueryData<{ id: string | null }>(owner.key("chat", "active-task", id))?.id : state.selectedTaskId
- const old = oldId ? owner.queryClient.getQueryData<TaskApi>(owner.key("chat", "task", oldId)) ?? null : null
- const next = typeof update === "function" ? update(old) : update
- view.setState((state) => ({ ...state, selectedTaskId: next?.id ?? null }))
- }, [assertCurrent, owner, view])
- const setHasMore = useCallback((hasMore: boolean, frontierId?: string) => {
- assertCurrent()
- const id = frontierId ?? view.get().frontierId ?? view.get().conversationId
- if (!id) return
- view.setState((state) => ({ ...state, frontierId: id }))
- if (!owner.queryClient.getQueryData(chatMessagesKey(owner, id))) owner.queryClient.setQueryData<ChatMessagesData>(chatMessagesKey(owner, id), { pages: [{ messages: [], hasMore }], pageParams: [null], serverMessageCount: 0 })
- }, [assertCurrent, owner, view])
- const selectPreviousResource = useCallback((key: readonly unknown[]) => {
- assertCurrent()
- view.setState((state) => ({ ...state, previousKey: key }))
- }, [assertCurrent, view])
- const setPreviousConversations = useCallback((update: PreviousConversation[] | ((rows: PreviousConversation[]) => PreviousConversation[])) => {
- assertCurrent()
- const rows = typeof update === "function" ? update(readPrevious()) : update
- view.setState((state) => ({ ...state, previousIds: rows.map((row) => row.id), previousKey: rows.length ? state.previousKey : null }))
- }, [assertCurrent, readPrevious, view])
- const setHasMoreConversations = useCallback((hasMore: boolean) => {
- assertCurrent()
- view.setState((state) => ({ ...state, previousHint: hasMore }))
- }, [assertCurrent, view])
- const firstFrontierId = refs.find((row) => row.conversationId === frontierId)?.id
- const frontierRows = sortedChatMessages(currentMessages)
- const hasMore = currentMessages?.pages.at(-1)?.hasMore === true || (firstFrontierId ? frontierRows.findIndex((row) => row.id === firstFrontierId) > 0 : frontierRows.length > 0)
- const actions = useMemo(() => {
- const readHasMore = () => {
- const state = view.get(), data = owner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(owner, state.frontierId ?? "__none__"))
- const first = state.window.find((row) => row.conversationId === state.frontierId)?.id, rows = sortedChatMessages(data)
- return data?.pages.at(-1)?.hasMore === true || (first ? rows.findIndex((row) => row.id === first) > 0 : rows.length > 0)
- }
- const readHasMoreConversations = () => {
- const state = view.get(), data = state.previousKey ? owner.queryClient.getQueryData<InfiniteData<{ conversations: PreviousConversation[]; has_more: boolean }>>(state.previousKey) : undefined
- return data?.pages.at(-1)?.has_more ?? state.previousHint
- }
- const readActiveTaskId = () => { const state = view.get(), id = state.conversationId; return state.selectedTaskId !== undefined ? state.selectedTaskId : id ? owner.queryClient.getQueryData<{ id: string | null }>(owner.key("chat", "active-task", id))?.id ?? null : null }
- const readConversation = () => { const id = view.get().conversationId; return id ? owner.queryClient.getQueryData<ChatExtras>(chatExtrasKey(owner, id))?.conversation ?? null : null }
- return { view, readMessages, readPrevious, selectConversation, selectPreviousResource, setHasMore, setPreviousConversations, setHasMoreConversations, setMessages, setConversation, setActiveTask, readHasMore, readHasMoreConversations, readActiveTaskId, readConversation }
- }, [owner, view, readMessages, readPrevious, selectConversation, selectPreviousResource, setHasMore, setPreviousConversations, setHasMoreConversations, setMessages, setConversation, setActiveTask])
- return { actions, ...actions, readMessages, readPrevious, selectConversation, selectPreviousResource, hasMore, setHasMore, previousConversations, hasMoreConversations: previous?.pages.at(-1)?.has_more ?? previousHint, setPreviousConversations, setHasMoreConversations, conversation: extras?.conversation ?? null, messages, artifacts: extras?.artifacts ?? EMPTY_ARTIFACTS, activeTask, taskMessages, setMessages, setConversation, setActiveTask }
-}
-const EMPTY_TASK_MESSAGES: TaskMessageResponse[] = []
-const EMPTY_ARTIFACTS: Artifact[] = []
-
-export function captureChatIntent(owner: WorkspaceOwner, view: Pick<Store<{ active: boolean; generation: number }>, "get" | "subscribe">) {
- return { workspace: captureWorkspaceOwner(owner), view, generation: view.get().generation }
-}
-export function assertChatIntent(token: ReturnType<typeof captureChatIntent>, signal?: AbortSignal) {
- assertWorkspaceOwner(token.workspace, signal)
- if (!token.view.get().active || token.view.get().generation !== token.generation) throw new DOMException("Retired chat intent", "AbortError")
-}
-
-export async function runChatIntentRequest<T>(intent: ReturnType<typeof captureChatIntent>, operation: (options: ApiRequestOptions) => Promise<T>) {
- const controller = new AbortController()
- const assertActive = () => assertChatIntent(intent, controller.signal)
- assertActive()
- const changed = () => { try { assertActive() } catch { controller.abort() } }
- const subscriptions = [intent.view, intent.workspace.owner.lifecycle, intent.workspace.owner.application.lifecycle].map((store) => store.subscribe(changed))
- try {
- const result = await operation(workspaceRequestOptions(intent.workspace, controller.signal, assertActive))
- assertActive()
- return result
- } catch (error) { assertActive(); throw error }
- finally { for (const subscription of subscriptions) subscription.unsubscribe() }
-}
diff --git a/src/web/src/hooks/workspace/use-chat-thread-resources.ts b/src/web/src/hooks/workspace/use-chat-thread-resources.ts
deleted file mode 100644
index 040b2ac7d..000000000
--- a/src/web/src/hooks/workspace/use-chat-thread-resources.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-"use client"
-
-import { useEffect, useMemo, useCallback } from "react"
-import { useSelector } from "@tanstack/react-store"
-import { useQuery, skipToken } from "@tanstack/react-query"
-import type { Conversation, WsMessage } from "@alook/shared"
-import { getThreadSummaries, getAgentSkills } from "@/lib/api"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { chatMessagesKey, sortedChatMessages, type ChatMessagesData } from "@/lib/chat-cache"
-import { captureChatIntent, assertChatIntent } from "./use-chat-data"
-
-type ChatView = Parameters<typeof captureChatIntent>[1]
-export type ChatRootReference = { conversationId: string; id: string }
-export function useChatThreadResources(owner: WorkspaceOwner, view: ChatView, conversation: Conversation | null, agentId: string, subscribeWs: (callback: (message: WsMessage) => void) => () => void) {
- const generation = useSelector(view, (state) => state.generation)
- const factOrigin = useMemo(() => captureWorkspaceOwner(owner), [owner])
- const intent = useMemo(() => ({ workspace: captureWorkspaceOwner(owner), view, generation }), [owner, view, generation])
- const root = useQuery<ChatRootReference | null>({ queryKey: owner.key("chat", "thread-root", conversation?.id ?? "__none__"), queryFn: skipToken, enabled: false }).data
- const rootMessages = useQuery<ChatMessagesData>({ queryKey: chatMessagesKey(owner, root?.conversationId ?? "__none__"), queryFn: skipToken, enabled: false }).data
- const threadRootMessage = useMemo(() => root ? sortedChatMessages(rootMessages).find((row) => row.id === root.id) ?? null : null, [root, rootMessages])
- const key = useMemo(() => owner.key("chat", "thread-summaries", conversation?.id ?? "__none__"), [owner, conversation?.id])
- const summaries = useQuery({ queryKey: key, meta: { chatView: view, generation }, enabled: !!conversation?.id && !conversation.parent_message_id, subscribed: !!conversation?.id && !conversation.parent_message_id,
- queryFn: async ({ signal }) => {
- assertWorkspaceOwner(factOrigin, signal)
- const data = await getThreadSummaries(conversation!.id, owner.workspaceId, workspaceRequestOptions(factOrigin, signal))
- assertWorkspaceOwner(factOrigin, signal)
- return data
- },
- }).data
- const threadSummaries = useMemo(() => new Map((summaries?.thread_summaries ?? []).map((row) => [row.parent_message_id, row])), [summaries])
- const fetchThreadSummaries = useCallback(() => owner.queryClient.invalidateQueries({ queryKey: key, exact: true }), [owner, key])
- useEffect(() => {
- return subscribeWs((message) => {
- try { assertChatIntent(intent) } catch { return }
- if ((message.type === "thread.created" || message.type === "thread.reply") && message.conversationId === conversation?.id) void fetchThreadSummaries()
- })
- }, [owner, view, subscribeWs, conversation?.id, fetchThreadSummaries, intent])
- const agentSkills = useQuery({ queryKey: owner.key("agent-skills", agentId), meta: { chatView: view, generation },
- queryFn: async ({ signal }) => {
- assertWorkspaceOwner(factOrigin, signal)
- const data = await getAgentSkills(agentId, owner.workspaceId, workspaceRequestOptions(factOrigin, signal))
- assertWorkspaceOwner(factOrigin, signal)
- return data.skills
- },
- }).data ?? EMPTY_SKILLS
- return { threadRootMessage, threadSummaries, fetchThreadSummaries, agentSkills, readThreadSummary: (messageId: string) => owner.queryClient.getQueryData<Awaited<ReturnType<typeof getThreadSummaries>>>(key)?.thread_summaries.find((row) => row.parent_message_id === messageId), summariesKey: key }
-}
-const EMPTY_SKILLS: Awaited<ReturnType<typeof getAgentSkills>>["skills"] = []
diff --git a/src/web/src/hooks/workspace/use-inbox.ts b/src/web/src/hooks/workspace/use-inbox.ts
deleted file mode 100644
index 80c511040..000000000
--- a/src/web/src/hooks/workspace/use-inbox.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-"use client"
-
-import { deriveView, valueEvidence } from "@/lib/observability/data-source"
-
-import { useCallback,useMemo } from "react"
-import { useSelector } from "@tanstack/react-store"
-import { infiniteQueryOptions,useInfiniteQuery,useMutation,type InfiniteData } from "@tanstack/react-query"
-import { listInboxItems,listFlaggedItems,markAllInboxRead,unflagMessage } from "@/lib/api"
-import { beginFlagCountWrite,rollbackFlagCountWrite } from "@/lib/workspace-flag-count"
-import { isAbortError } from "@/lib/errors"
-import { assertWorkspaceOwner,captureWorkspaceOwner,runWorkspaceRequest,useWorkspaceOwner,type WorkspaceOwner } from "@/contexts/workspace-context"
-
-type InboxPage = Awaited<ReturnType<typeof listInboxItems>>
-type InboxData = InfiniteData<InboxPage, string | undefined>
-function firstRows<T extends { id: string }>(pages: readonly { items: T[] }[] | undefined): T[] {
- const seen = new Set<string>()
- return pages?.flatMap((page) => page.items.filter((item) => {
- if (seen.has(item.id)) return false
- seen.add(item.id)
- return true
- })) ?? []
-}
-function workspaceInboxOptions(workspace: WorkspaceOwner, types: readonly string[]) {
- return infiniteQueryOptions({
- queryKey: workspace.key("inbox", types, 30),
- initialPageParam: undefined as string | undefined,
- queryFn: ({ signal, pageParam }) => runWorkspaceRequest(workspace, (options) => listInboxItems(workspace.workspaceId, { limit: 30, before: pageParam, types: [...types] }, options), signal),
- getNextPageParam: (page) => page.has_more && page.items.length ? page.items.at(-1)?.latest_response_at : undefined,
- })
-}
-function workspaceFlagOptions(workspace: WorkspaceOwner) {
- return infiniteQueryOptions({
- queryKey: workspace.key("flagged-items", 30),
- initialPageParam: undefined as string | undefined,
- queryFn: ({ signal, pageParam }) => runWorkspaceRequest(workspace, (options) => listFlaggedItems(workspace.workspaceId, { limit: 30, before: pageParam }, options), signal),
- getNextPageParam: (page) => page.has_more && page.items.length ? page.items.at(-1)?.flagged_at : undefined,
- })
-}
-export function useWorkspaceInbox(enabled = true) {
- const workspace = useWorkspaceOwner()
- const types = useSelector(workspace.application.preferences, (state) => state.inboxFilterTypes)
- const hydrated = useSelector(workspace.application.preferences, (state) => state.hydrated)
- const options = workspaceInboxOptions(workspace, types)
- const query = useInfiniteQuery({ ...options, enabled: enabled && hydrated })
- const items = useMemo(() => firstRows(query.data?.pages), [query.data])
- const refresh = useCallback(() => workspace.queryClient.invalidateQueries({ queryKey: workspace.key("inbox") }), [workspace])
- deriveView(items, [valueEvidence(workspace.queryClient, query.data)])
- return { ...query, items, refresh }
-}
-export function useMarkAllInboxRead() {
- const workspace = useWorkspaceOwner()
- const qc = workspace.queryClient
- const mutationKey = workspace.key("inbox", "read-all")
- return useMutation({ meta: { observabilityAction: "inbox.read_all" },
- mutationKey,
- scope: { id: JSON.stringify(mutationKey) },
- mutationFn: () => runWorkspaceRequest(workspace, (options) => markAllInboxRead(workspace.workspaceId, options)),
- onMutate: async () => {
- const token = captureWorkspaceOwner(workspace)
- await Promise.all([qc.cancelQueries({ queryKey: workspace.key("inbox") }), qc.cancelQueries({ queryKey: workspace.key("inbox-count") })])
- assertWorkspaceOwner(token)
- const pages = qc.getQueriesData<InboxData>({ queryKey: workspace.key("inbox") }).filter(([, data]) => data?.pages)
- const counts = qc.getQueriesData<{ count: number }>({ queryKey: workspace.key("inbox-count") })
- for (const [key, data] of pages) qc.setQueryData(key, { ...data, pages: data!.pages.map((page) => ({ ...page, items: [], has_more: false })) })
- for (const [key] of counts) qc.setQueryData(key, { count: 0 })
- return { token, snapshots: [...pages, ...counts].map(([key, previous]) => ({ key, previous, optimistic: qc.getQueryData(key) })) }
- },
- onError: (error, _variables, context) => {
- if (!context || isAbortError(error)) return
- try { assertWorkspaceOwner(context.token) } catch { return }
- for (const { key, previous, optimistic } of context.snapshots) if (qc.getQueryData(key) === optimistic) qc.setQueryData(key, previous)
- },
- onSettled: (_data, _error, _variables, context) => {
- if (!context) return
- try { assertWorkspaceOwner(context.token) } catch { return }
- if (qc.isMutating({ mutationKey, exact: true }) !== 1) return
- return Promise.all([qc.invalidateQueries({ queryKey: workspace.key("inbox") }), qc.invalidateQueries({ queryKey: workspace.key("inbox-count") })])
- },
- })
-}
-export function useWorkspaceFlags(enabled = true) {
- const workspace = useWorkspaceOwner()
- const options = workspaceFlagOptions(workspace)
- const query = useInfiniteQuery({ ...options, enabled })
- const items = useMemo(() => firstRows(query.data?.pages), [query.data])
- deriveView(items, [valueEvidence(workspace.queryClient, query.data)])
- return { ...query, items }
-}
-export function useUnflagWorkspaceMessage() {
- const workspace = useWorkspaceOwner()
- const qc = workspace.queryClient
- const options = workspaceFlagOptions(workspace)
- const mutationKey = workspace.key("flagged-items", "remove")
- return useMutation({ meta: { observabilityAction: "message.flag.remove" },
- mutationKey, scope: { id: JSON.stringify(mutationKey) },
- mutationFn: (messageId: string) => runWorkspaceRequest(workspace, (request) => unflagMessage(workspace.workspaceId, messageId, request)),
- onMutate: async (messageId) => {
- const token = captureWorkspaceOwner(workspace)
- const countKey = workspace.key("flag-count")
- await Promise.all([qc.cancelQueries({ queryKey: options.queryKey, exact: true }), qc.cancelQueries({ queryKey: countKey, exact: true })])
- assertWorkspaceOwner(token)
- const previous = qc.getQueryData(options.queryKey)
- qc.setQueryData(options.queryKey, (data) => data && ({ ...data, pages: data.pages.map((page) => ({ ...page, items: page.items.filter((item) => item.message_id !== messageId) })) }))
- const countTicket = beginFlagCountWrite(workspace, -1)
- return { token, previous, optimistic: qc.getQueryData(options.queryKey), countTicket, countKey }
- },
- onError: (error, _messageId, context) => {
- if (!context || isAbortError(error)) return
- try { assertWorkspaceOwner(context.token) } catch { return }
- if (qc.getQueryData(options.queryKey) === context.optimistic) qc.setQueryData(options.queryKey, context.previous)
- rollbackFlagCountWrite(workspace, context.countTicket)
- },
- onSettled: (_data, _error, _messageId, context) => {
- if (!context) return
- try { assertWorkspaceOwner(context.token) } catch { return }
- if (qc.isMutating({ mutationKey, exact: true }) !== 1) return
- return Promise.all([qc.invalidateQueries({ queryKey: options.queryKey, exact: true }), qc.invalidateQueries({ queryKey: context.countKey, exact: true })])
- },
- })
-}
diff --git a/src/web/src/hooks/workspace/use-issue-command.ts b/src/web/src/hooks/workspace/use-issue-command.ts
deleted file mode 100644
index 31ae412b6..000000000
--- a/src/web/src/hooks/workspace/use-issue-command.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-"use client"
-
-import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
-
-import { useCallback } from "react"
-
-import { useWorkspaceViewSource } from "./use-workspace-view-source"
-
-import { useMutation, useMutationState, type Query } from "@tanstack/react-query"
-import type { CreateIssueRequest, Issue, UpdateIssueRequest } from "@alook/shared"
-import { createIssue, updateIssue, deleteIssue, createIssueComment, type IssueListItem } from "@/lib/api"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, type WorkspaceOwner } from "@/contexts/workspace-context"
-import type { WorkspaceIssueDetail } from "@/lib/workspace-issue-reconciliation"
-
-type IssueAction = { kind: "create"; values: CreateIssueRequest & { files?: File[] } } | { kind: "update"; id: string; patch: UpdateIssueRequest } | { kind: "delete"; id: string } | { kind: "comment"; id: string; content: string }
-type IssueIntent = { action: IssueAction; token: ReturnType<typeof captureWorkspaceOwner>; assertActive?: (() => void) & { signal: AbortSignal } }
-
-function mergeConfirmed(current: IssueListItem, before: IssueListItem | undefined, confirmed: Issue): IssueListItem {
- const next = { ...current }
- for (const [field, value] of Object.entries(confirmed)) {
- if (field === "updated_at") {
- next.updated_at = current.updated_at > confirmed.updated_at ? current.updated_at : confirmed.updated_at
- } else if ((current as unknown as Record<string, unknown>)[field] === (before as unknown as Record<string, unknown> | undefined)?.[field]) {
- (next as unknown as Record<string, unknown>)[field] = value
- }
- }
- return next
-}
-
-export function useIssueCommand(owner: WorkspaceOwner) {
- const key = owner.key("issue-command")
- const source = useWorkspaceViewSource(owner, "issue-command", true)
- type NativeIntent = IssueIntent & { view: ReturnType<typeof source.capture>; resources: Query[] }
- const native = useMutation({ meta: { observabilityAction: "issue.command" }, mutationKey: key, scope: { id: JSON.stringify(key) }, gcTime: 0,
- mutationFn: async ({ action, token, view, resources, assertActive }: NativeIntent) => {
- const qc = owner.queryClient, assert = () => { assertWorkspaceOwner(token, assertActive?.signal ?? view.signal); view.assert(); assertActive?.() }
- assert()
- await Promise.all(resources.filter((query) => qc.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query).map((query) => qc.cancelQueries({ queryKey: query.queryKey, exact: true })))
- assert()
- const lists = resources.filter((query) => owner.key("issues", "list").every((value, index) => Object.is(value, query.queryKey[index]))).map((query) => ({ query, before: query.state.data as IssueListItem[] | undefined, writes: query.state.dataUpdateCount }))
- const id = action.kind === "create" ? null : action.id
- const detailKey = owner.key("issues", "detail", id ?? "__none__")
- const detailQuery = resources.find((query) => JSON.stringify(query.queryKey) === JSON.stringify(detailKey))
- const beforeDetail = detailQuery?.state.data as WorkspaceIssueDetail | undefined
- const detailWrites = detailQuery?.state.dataUpdateCount
- const original = (query: (typeof lists)[number]["query"]) => qc.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query
- try {
- const options = workspaceRequestOptions(token, assertActive?.signal ?? view.signal, assert)
- if (action.kind === "comment") {
- const { comment } = await createIssueComment(owner.workspaceId, action.id, action.content, options)
- assert()
- if (detailQuery && original(detailQuery)) qc.setQueryData<WorkspaceIssueDetail>(detailKey, (detail) => {
- if (!detail || detail.comments.some((row) => row.id === comment.id)) return detail
- const revision = (detail.liveRevision ?? 0) + 1
- return { ...detail, comments: [...detail.comments, comment], liveRevision: revision, liveFields: { ...detail.liveFields, comments: revision } }
- })
- await Promise.all(resources.filter(original).map((query) => qc.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false })))
- assert()
- return null
- }
- const confirmed = action.kind === "create" ? (await createIssue(owner.workspaceId, action.values, options)).issue
- : action.kind === "update" ? await updateIssue(owner.workspaceId, action.id, action.patch, options)
- : (await deleteIssue(owner.workspaceId, action.id, options), null)
- assert()
- for (const { query, before, writes } of lists) {
- if (!original(query) || query.state.dataUpdateCount !== writes || !Array.isArray(query.state.data)) continue
- qc.setQueryData<IssueListItem[]>(query.queryKey, (rows) => {
- if (!rows) return rows
- if (action.kind === "delete") return rows.filter((row) => row.id !== action.id)
- if (action.kind === "create") return rows.some((row) => row.id === confirmed!.id) ? rows : [confirmed!, ...rows]
- return rows.map((row) => row.id === action.id ? mergeConfirmed(row, before?.find((candidate) => candidate.id === row.id), confirmed!) : row)
- })
- }
- if (detailQuery && original(detailQuery) && detailQuery.state.dataUpdateCount === detailWrites) {
- if (action.kind === "delete") qc.removeQueries({ queryKey: detailKey, exact: true })
- else if (action.kind === "update") qc.setQueryData<WorkspaceIssueDetail>(detailKey, (detail) => {
- if (!detail) return detail
- const revision = (detail.liveRevision ?? 0) + 1
- return { ...detail, issue: mergeConfirmed(detail.issue, beforeDetail?.issue, confirmed!), liveRevision: revision, liveFields: { ...detail.liveFields, issue: revision } }
- })
- }
- await Promise.all(resources.filter(original).map((query) => qc.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false })))
- assert()
- return confirmed
- } catch (error) { assert(); throw error }
- },
- })
- const capture = useCallback((input: IssueIntent): NativeIntent => {
- const view = source.capture()
- view.assert(); assertWorkspaceOwner(input.token); input.assertActive?.()
- return { ...input, view, resources: [...new Set([owner.key("issues")].flatMap((queryKey) => owner.queryClient.getQueryCache().findAll({ queryKey })))] }
- }, [owner, source])
- const assertCurrent = useCallback((args: NativeIntent) => { args.view.assert(); assertWorkspaceOwner(args.token); args.assertActive?.() }, [])
- return useNativeMutationFacade(native, capture, assertCurrent)
-}
-
-export function usePendingIssueChanges(owner: WorkspaceOwner) {
- return useMutationState({ filters: { mutationKey: owner.key("issue-command"), status: "pending" }, select: (mutation) => (mutation.state.variables as IssueIntent).action })
-}
diff --git a/src/web/src/hooks/workspace/use-runtime-command.ts b/src/web/src/hooks/workspace/use-runtime-command.ts
deleted file mode 100644
index d89a32f2a..000000000
--- a/src/web/src/hooks/workspace/use-runtime-command.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-"use client"
-
-import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
-
-import { useCallback } from "react"
-
-import { useWorkspaceViewSource } from "./use-workspace-view-source"
-
-import { useMutation, useMutationState, type Query } from "@tanstack/react-query"
-import type { AgentRuntime } from "@alook/shared"
-import { triggerRuntimeUpdate, triggerRuntimeRescan } from "@/lib/api"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, type WorkspaceOwner } from "@/contexts/workspace-context"
-
-type RuntimeIntent = { kind: "update" | "rescan"; id: string; token: ReturnType<typeof captureWorkspaceOwner>; assertActive?: (() => void) & { signal: AbortSignal } }
-
-export function useRuntimeCommand(owner: WorkspaceOwner) {
- const key = owner.key("runtime-command")
- const source = useWorkspaceViewSource(owner, "runtime-command", true)
- type NativeIntent = RuntimeIntent & { view: ReturnType<typeof source.capture>; resources: Query[] }
- const native = useMutation({ meta: { observabilityAction: "runtime.command" }, mutationKey: key, scope: { id: JSON.stringify(key) },
- mutationFn: async ({ kind, id, token, view, resources, assertActive }: NativeIntent) => {
- const assert = () => { assertWorkspaceOwner(token, assertActive?.signal ?? view.signal); view.assert(); assertActive?.() }, qc = owner.queryClient, resourceKey = owner.key("runtimes")
- assert()
- await Promise.all(resources.filter((query) => qc.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query).map((query) => qc.cancelQueries({ queryKey: query.queryKey, exact: true })))
- assert()
- const original = resources.find((query) => JSON.stringify(query.queryKey) === JSON.stringify(resourceKey))
- const baseline = (original?.state.data as AgentRuntime[] | undefined)?.find((row) => row.id === id)
- const writes = original?.state.dataUpdateCount
- try {
- const result = kind === "update" ? await triggerRuntimeUpdate(id, owner.workspaceId, workspaceRequestOptions(token, assertActive?.signal ?? view.signal, assert)) : await triggerRuntimeRescan(id, owner.workspaceId, workspaceRequestOptions(token, assertActive?.signal ?? view.signal, assert))
- assert()
- if (original && qc.getQueryCache().find({ queryKey: resourceKey, exact: true }) === original && original.state.dataUpdateCount === writes) qc.setQueryData<AgentRuntime[]>(resourceKey, (rows) => rows?.map((row) => {
- if (row.id !== id) return row
- if ("pending_update_version" in result && row.pending_update_version === baseline?.pending_update_version) return { ...row, pending_update_version: result.pending_update_version }
- if ("pending_rescan" in result && row.pending_rescan === baseline?.pending_rescan) return { ...row, pending_rescan: result.pending_rescan }
- return row
- }))
- if (original && qc.getQueryCache().find({ queryKey: resourceKey, exact: true }) === original) await qc.invalidateQueries({ queryKey: resourceKey, exact: true }, { cancelRefetch: false })
- assert()
- } catch (error) { assert(); throw error }
- },
- })
- const capture = useCallback((input: RuntimeIntent): NativeIntent => {
- const view = source.capture()
- view.assert(); assertWorkspaceOwner(input.token); input.assertActive?.()
- return { ...input, view, resources: [...new Set([owner.key("runtimes")].flatMap((queryKey) => owner.queryClient.getQueryCache().findAll({ queryKey })))] }
- }, [owner, source])
- const assertCurrent = useCallback((args: NativeIntent) => { args.view.assert(); assertWorkspaceOwner(args.token); args.assertActive?.() }, [])
- return useNativeMutationFacade(native, capture, assertCurrent)
-}
-
-export function usePendingRuntimeCommands(owner: WorkspaceOwner) {
- return useMutationState({ filters: { mutationKey: owner.key("runtime-command"), status: "pending" }, select: (mutation) => mutation.state.variables as RuntimeIntent })
-}
diff --git a/src/web/src/hooks/workspace/use-workspace-meetings.ts b/src/web/src/hooks/workspace/use-workspace-meetings.ts
deleted file mode 100644
index be4774e4e..000000000
--- a/src/web/src/hooks/workspace/use-workspace-meetings.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-"use client"
-
-import { queryOptions,useMutation,useQuery } from "@tanstack/react-query"
-import { useWorkspaceOwner,runWorkspaceRequest,type WorkspaceOwner } from "@/contexts/workspace-context"
-import { assertApplicationOwner,captureApplicationOwner,runApplicationRequest } from "@/lib/application-owner"
-import { listMeetings,createMeeting,stopMeeting,approveMeeting,deleteMeeting } from "@/lib/api"
-import type { MeetingSession } from "@alook/shared"
-
-function workspaceMeetingsOptions(owner: WorkspaceOwner, agentId: string) {
- return queryOptions({
- queryKey: owner.key("meetings", agentId),
- queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listMeetings(agentId, owner.workspaceId, options), signal),
- refetchInterval: (query) => query.state.data?.some((meeting) => meeting.status === "joining" || meeting.status === "recording") ? 5000 : false,
- refetchIntervalInBackground: false,
- })
-}
-type MeetingAction = { kind: "create"; data: Parameters<typeof createMeeting>[2]; assertUI: () => void } | { kind: "stop" | "approve" | "delete"; id: string; assertUI: () => void }
-export function useWorkspaceMeetings(agentId: string) {
- const owner = useWorkspaceOwner()
- const options = workspaceMeetingsOptions(owner, agentId)
- const query = useQuery(options)
- const mutationKey = [...options.queryKey, "change"]
- const mutation = useMutation({ meta: { observabilityAction: "meeting.command" },
- mutationKey,
- scope: { id: JSON.stringify(mutationKey) },
- mutationFn: async (action: MeetingAction) => {
- action.assertUI()
- const original = captureApplicationOwner(owner.application)
- const resource = owner.queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true })
- await owner.queryClient.cancelQueries({ queryKey: options.queryKey, exact: true })
- action.assertUI()
- const result = await runApplicationRequest<MeetingSession | void>(owner.application, (request) => {
- const qualified = { ...request, onUnauthorized: async () => {
- try { action.assertUI() } catch { return false }
- return request.onUnauthorized ? request.onUnauthorized() : false
- } }
- if (action.kind === "create") return createMeeting(agentId, owner.workspaceId, action.data, qualified)
- if (action.kind === "stop") return stopMeeting(agentId, action.id, owner.workspaceId, qualified)
- if (action.kind === "approve") return approveMeeting(agentId, action.id, owner.workspaceId, qualified)
- return deleteMeeting(agentId, action.id, owner.workspaceId, qualified)
- })
- assertApplicationOwner(original)
- if (resource && owner.queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true }) === resource) {
- await owner.queryClient.cancelQueries({ queryKey: options.queryKey, exact: true })
- assertApplicationOwner(original)
- if (owner.queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true }) === resource) {
- owner.queryClient.setQueryData<MeetingSession[]>(options.queryKey, (rows) => {
- if (action.kind === "delete") return rows?.filter((row) => row.id !== action.id)
- if (!result) return rows
- const current = rows ?? []
- return current.some((row) => row.id === result.id) ? current.map((row) => row.id === result.id ? result : row) : [result, ...current]
- })
- await owner.queryClient.invalidateQueries({ queryKey: options.queryKey, exact: true, refetchType: "none" })
- }
- }
- return result
- },
- })
- return { ...query, mutation, isCommandPending: () => owner.queryClient.isMutating({ mutationKey, exact: true }) > 0 }
-}
diff --git a/src/web/src/hooks/workspace/use-workspace-view-source.ts b/src/web/src/hooks/workspace/use-workspace-view-source.ts
deleted file mode 100644
index 4858d10bb..000000000
--- a/src/web/src/hooks/workspace/use-workspace-view-source.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-"use client"
-
-import { useMemo, useLayoutEffect } from "react"
-import { createStore, useSelector } from "@tanstack/react-store"
-import { captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions, type WorkspaceOwner } from "@/contexts/workspace-context"
-
-export function useWorkspaceViewSource(owner: WorkspaceOwner, identity: string, enabled: boolean) {
- const view = useMemo(() => createStore({ owner, identity, active: enabled, generation: 0, controller: new AbortController() }), [owner, identity, enabled])
- const generation = useSelector(view, (state) => state.generation)
- const workspaceGeneration = useSelector(owner.lifecycle, (state) => state.generation)
- const applicationGeneration = useSelector(owner.application.lifecycle, (state) => state.generation)
- const active = useSelector(view, (state) => state.active)
- useLayoutEffect(() => {
- view.setState((state) => ({ ...state, active: enabled, controller: state.controller.signal.aborted ? new AbortController() : state.controller }))
- const original = view.get().controller
- return () => {
- view.setState((state) => ({ ...state, active: false, generation: state.generation + 1 }))
- original.abort()
- }
- }, [owner, view, enabled])
- const assertActive = useMemo(() => {
- const token = { owner, generation: workspaceGeneration, application: { owner: owner.application, generation: applicationGeneration } }
- return () => {
- assertWorkspaceOwner(token)
- const state = view.get()
- if (!state.active || state.generation !== generation) throw new DOMException("Retired workspace view", "AbortError")
- }
- }, [owner, view, generation, workspaceGeneration, applicationGeneration])
- const factOrigin = useMemo(() => ({ owner, generation: workspaceGeneration, application: { owner: owner.application, generation: applicationGeneration } }), [owner, workspaceGeneration, applicationGeneration])
- const assertFactActive = useMemo(() => () => assertWorkspaceOwner(factOrigin), [factOrigin])
- return useMemo(() => {
- const retire = () => {
- const controller = view.get().controller
- view.setState((state) => ({ ...state, active: false, generation: state.generation + 1 }))
- controller.abort()
- }
- const capture = () => {
- const token = captureWorkspaceOwner(owner), state = view.get(), signal = state.controller.signal
- const assert = () => {
- assertWorkspaceOwner(token, signal)
- const current = view.get()
- if (!current.active || current.generation !== state.generation) throw new DOMException("Retired workspace view", "AbortError")
- }
- return { token, assert, signal }
- }
- return { view, signal: view.get().controller.signal, active, generation, assertActive, assertFactActive, capture, retire, request: (signal?: AbortSignal, assert = assertFactActive) => workspaceRequestOptions(factOrigin, signal, assert) }
- }, [active, generation, assertActive, assertFactActive, factOrigin, owner, view])
-}
diff --git a/src/web/src/lib/account-cache-lifecycle.dom.test.tsx b/src/web/src/lib/account-cache-lifecycle.dom.test.tsx
index 659e6b56a..c96cbf07b 100644
--- a/src/web/src/lib/account-cache-lifecycle.dom.test.tsx
+++ b/src/web/src/lib/account-cache-lifecycle.dom.test.tsx
@@ -1,10 +1,11 @@
+import { get, set } from "idb-keyval"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
import { useMutation } from "@tanstack/react-query"
import { act, render, waitFor } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider, useApplicationOwner, runApplicationRequest, type ApplicationOwner } from "./application-owner"
+import { PublicQueryProvider, useApplicationOwner, runApplicationRequest, type ApplicationOwner } from "./application-owner"
import { apiFetch } from "./api/client"
import { clearAllPersistedCaches, clearPersistedCache, createIdbPersister, CACHE_INVALIDATION_STORAGE_KEY } from "./query-persister"
const identity = vi.hoisted(() => ({ id: "A" }))
@@ -21,7 +22,7 @@ function Probe({ name }: { name: string }) {
useLayoutEffect(() => { commands[name] = () => command.mutateAsync() })
return <output>{name}</output>
}
-function App({ user = identity.id, name = user }: { user?: string; name?: string }) { return <ApplicationQueryProvider userId={user}><Probe name={name} /></ApplicationQueryProvider> }
+function App({ user = identity.id, name = user }: { user?: string; name?: string }) { return <PublicQueryProvider><Probe name={name} /></PublicQueryProvider> }
const persisted = { timestamp: Date.now(), buster: "v3", clientState: { queries: [], mutations: [] } }
beforeEach(async () => {
await act(async () => { await clearAllPersistedCaches(); }) ; identity.id = "A"; for (const key of Object.keys(owners)) delete owners[key]; for (const key of Object.keys(commands)) delete commands[key]
@@ -37,34 +38,34 @@ afterEach(async () => {
describe("native account cache lifecycle integration", () => {
it("current mutation 401 retires its native memory and both disk domains before navigation", async () => {
render(<App />); await waitFor(() => expect(commands.A).toBeDefined())
- const community = createIdbPersister("A"), application = createIdbPersister("A", "application")
- await act(async () => { await community.persistClient(persisted); }) ; await act(async () => { await application.persistClient(persisted) })
+ const community = createIdbPersister("A")
+ await act(async () => { await community.persistClient(persisted); }) ; await act(async () => { await set("alook:qc:v3:A:application:client", JSON.stringify(persisted)) })
owners.A.queryClient.setQueryData(["application", "A", "workspace", "w", "fact"], { private: "A" })
let done!: ReturnType<typeof commands.A>; await act(async () => { done = commands.A().catch((error) => error) })
await waitFor(() => expect(response).toBeTypeOf("function"))
await act(async () => { response(new Response("{}", { status: 401 })); await done }); await waitFor(() => expect(assign).toHaveBeenCalledOnce())
expect(owners.A.lifecycle.get().active).toBe(false); expect(owners.A.queryClient.getQueryCache().getAll()).toHaveLength(0)
- expect(await community.isCurrent()).toBe(false); expect(await application.isCurrent()).toBe(false)
- expect(await createIdbPersister("A").restoreClient()).toBeUndefined(); expect(await createIdbPersister("A", "application").restoreClient()).toBeUndefined()
+ expect(await community.isCurrent()).toBe(false); expect(await get("alook:qc:v3:A:application:client")).toBeUndefined()
+ expect(await createIdbPersister("A").restoreClient()).toBeUndefined(); expect(await get("alook:qc:v3:A:application:client")).toBeUndefined()
expect(reload).not.toHaveBeenCalled()
})
it("old mutation 401 after A to B cannot clear B, navigate, or retire the current owner", async () => {
const mounted = render(<App />); await waitFor(() => expect(commands.A).toBeDefined()); const oldOwner = owners.A
let done!: ReturnType<typeof commands.A>; await act(async () => { done = commands.A().catch((error) => error) }) ; await waitFor(() => expect(response).toBeTypeOf("function")); const oldResponse = response
identity.id = "B"; await act(async () => mounted.rerender(<App user="B" />)); await waitFor(() => expect(commands.B).toBeDefined())
- owners.B.queryClient.setQueryData(["application", "B", "fact"], { current: "B" }); const bDisk = createIdbPersister("B", "application"); await act(async () => { await bDisk.persistClient(persisted) })
+ owners.B.queryClient.setQueryData(["application", "B", "fact"], { current: "B" }); const bDisk = createIdbPersister("B"); await act(async () => { await bDisk.persistClient(persisted) })
await act(async () => oldResponse(new Response("{}", { status: 401 }))); const error = await done
expect(error).toMatchObject({ name: "AbortError" }); expect(oldOwner.lifecycle.get().active).toBe(false); expect(owners.B.lifecycle.get().active).toBe(true)
expect(owners.B.queryClient.getQueryData(["application", "B", "fact"])).toEqual({ current: "B" }); expect(await bDisk.isCurrent()).toBe(true); expect(assign).not.toHaveBeenCalled(); expect(reload).not.toHaveBeenCalled()
})
it("all-device clear retires both mounted native clients and writers without a first payload", async () => {
render(<><App name="first" /><App name="second" /></>); await waitFor(() => expect(commands.second).toBeDefined())
- const unseenB = createIdbPersister("B", "application"); await act(async () => { await unseenB.restoreClient() })
+ const unseenB = createIdbPersister("B"); await act(async () => { await unseenB.restoreClient() })
owners.first.queryClient.setQueryData(["private"], { private: "A" }); owners.second.queryClient.setQueryData(["private"], { private: "A" })
await act(async () => clearAllPersistedCaches())
await waitFor(() => expect(owners.first.lifecycle.get().active).toBe(false)); await waitFor(() => expect(owners.second.lifecycle.get().active).toBe(false))
expect(owners.first.queryClient.getQueryCache().getAll()).toHaveLength(0); expect(owners.second.queryClient.getQueryCache().getAll()).toHaveLength(0); expect(await unseenB.isCurrent()).toBe(false)
- await act(async () => { await unseenB.persistClient(persisted); }) ; expect(await createIdbPersister("B", "application").restoreClient()).toBeUndefined()
+ await act(async () => { await unseenB.persistClient(persisted); }) ; expect(await createIdbPersister("B").restoreClient()).toBeUndefined()
})
it("external-document notification only retires after the original durable eligibility fails", async () => {
render(<App />); await waitFor(() => expect(commands.A).toBeDefined()); owners.A.queryClient.setQueryData(["private"], { private: "A" })
@@ -81,7 +82,7 @@ describe("native account cache lifecycle integration", () => {
expect((await disk.restoreClient())?.timestamp).toBe(2); expect(owners.A.lifecycle.get().active).toBe(true); expect(reload).not.toHaveBeenCalled()
})
it("A disk retirement leaves unrelated B eligibility intact", async () => {
- const a = createIdbPersister("A"), b = createIdbPersister("B", "application"); await act(async () => { await a.persistClient(persisted); }) ; await act(async () => { await b.persistClient(persisted) })
+ const a = createIdbPersister("A"), b = createIdbPersister("B"); await act(async () => { await a.persistClient(persisted); }) ; await act(async () => { await b.persistClient(persisted) })
await act(async () => { await clearPersistedCache("A"); }) ; expect(await a.isCurrent()).toBe(false); expect(await b.isCurrent()).toBe(true); expect((await b.restoreClient())?.timestamp).toBe(persisted.timestamp)
})
})
diff --git a/src/web/src/lib/analytics.test.ts b/src/web/src/lib/analytics.test.ts
index defd2600b..d48026059 100644
--- a/src/web/src/lib/analytics.test.ts
+++ b/src/web/src/lib/analytics.test.ts
@@ -13,55 +13,7 @@ vi.mock("./analytics-consent", () => ({
const mockSendGTMEvent = mocks.sendGTMEvent
-import {
- trackSignUp,
- trackSignInSuccess,
- trackWorkspaceCreated,
- trackAgentCreated,
- trackOnboardingCompleted,
- trackAgentChatOpened,
- trackMessageSent,
- trackEmailComposed,
- trackEmailReceived,
- trackCalendarEventCreated,
- trackIssueCreated,
- trackIssueStatusChanged,
- trackThreadViewed,
- trackTemplateUsed,
- trackCustomEmailConnected,
- trackTeamMemberInvited,
- trackInviteAccepted,
- trackSecondAgentCreated,
- trackAgentLinkCreated,
- trackRuntimeConnected,
- trackCommunityRuntimeConnected,
- trackCommunityOnboardingCompleted,
- trackCommunityOnboardingSkipped,
- trackCommunityOnboardingStageCompleted,
- trackCommunityOnboardingStarted,
- trackFirstAgentReplyPersisted,
- trackHumanInvitationSent,
- trackHumanInvitationCopied,
- trackInvitedHumanJoined,
- trackGithubOutboundClicked,
- trackLandingCtaClicked,
- trackTemplatesBrowsed,
- trackSettingsUpdated,
- trackCanvasLayoutChanged,
- trackCommunityWsFrameDropped,
- trackCommunityWsAuthFailure,
- trackCommunityWsLifecycleClose,
- trackCommunityWsLifecycleRecovery,
- trackCommunityWsLifecycleStage,
- trackCommunityWsReconcileComplete,
- trackCommunityWsReconcileFailure,
- trackCommunityWsRetryScheduled,
- toAnalyticsCurrentPlan,
- toAnalyticsPlanId,
- trackBeginCheckout,
- trackPricingCtaClick,
- trackPricingView,
-} from "./analytics"
+import { trackSignUp, trackSignInSuccess, trackInviteAccepted, trackCommunityRuntimeConnected, trackCommunityOnboardingCompleted, trackCommunityOnboardingSkipped, trackCommunityOnboardingStageCompleted, trackCommunityOnboardingStarted, trackFirstAgentReplyPersisted, trackHumanInvitationSent, trackHumanInvitationCopied, trackInvitedHumanJoined, trackGithubOutboundClicked, trackLandingCtaClicked, trackTemplatesBrowsed, trackCommunityWsFrameDropped, trackCommunityWsAuthFailure, trackCommunityWsLifecycleClose, trackCommunityWsLifecycleRecovery, trackCommunityWsLifecycleStage, trackCommunityWsReconcileComplete, trackCommunityWsReconcileFailure, trackCommunityWsRetryScheduled, toAnalyticsCurrentPlan, toAnalyticsPlanId, trackBeginCheckout, trackPricingCtaClick, trackPricingView } from "./analytics"
describe("analytics utility", () => {
beforeEach(() => {
@@ -87,131 +39,9 @@ describe("analytics utility", () => {
trackSignInSuccess("email_otp")
expect(mockSendGTMEvent).toHaveBeenCalledWith({ event: "sign_in_success", method: "email_otp" })
})
-
- it("trackWorkspaceCreated sends workspace_created event", () => {
- trackWorkspaceCreated("onboarding")
- expect(mockSendGTMEvent).toHaveBeenCalledWith({ event: "workspace_created", source: "onboarding" })
- })
-
- it("trackAgentCreated sends agent_created event with all params", () => {
- trackAgentCreated({ is_first_agent: true, has_email: false, template_id: "tmpl_1" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "agent_created",
- is_first_agent: true,
- has_email: false,
- template_id: "tmpl_1",
- })
- })
-
- it("trackOnboardingCompleted sends onboarding_completed event", () => {
- trackOnboardingCompleted({ template_used: "startup", agent_count: 3 })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "onboarding_completed",
- template_used: "startup",
- agent_count: 3,
- })
- })
-
- it("trackAgentChatOpened sends agent_chat_opened event", () => {
- trackAgentChatOpened({ agent_id: "ag_123", is_first_chat: true })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "agent_chat_opened",
- agent_id: "ag_123",
- is_first_chat: true,
- })
- })
-
- it("trackMessageSent sends message_sent event", () => {
- trackMessageSent({ agent_id: "ag_123", message_length: 42 })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "message_sent",
- agent_id: "ag_123",
- message_length: 42,
- })
- })
- })
-
- describe("P1 — Feature Usage Events", () => {
- it("trackEmailComposed sends email_composed event", () => {
- trackEmailComposed({ agent_id: "ag_1", has_attachments: true })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "email_composed",
- agent_id: "ag_1",
- has_attachments: true,
- })
- })
-
- it("trackEmailReceived sends email_received event", () => {
- trackEmailReceived({ agent_id: "ag_1", mailbox_type: "imap" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "email_received",
- agent_id: "ag_1",
- mailbox_type: "imap",
- })
- })
-
- it("trackCalendarEventCreated sends calendar_event_created event", () => {
- trackCalendarEventCreated({ agent_id: "ag_1", is_recurring: false })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "calendar_event_created",
- agent_id: "ag_1",
- is_recurring: false,
- })
- })
-
- it("trackIssueCreated sends issue_created event", () => {
- trackIssueCreated({ agent_id: "ag_1" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "issue_created",
- agent_id: "ag_1",
- })
- })
-
- it("trackIssueStatusChanged sends issue_status_changed event", () => {
- trackIssueStatusChanged({ from: "todo", to: "running", method: "drag" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "issue_status_changed",
- from: "todo",
- to: "running",
- method: "drag",
- })
- })
-
- it("trackThreadViewed sends thread_viewed event", () => {
- trackThreadViewed({ agent_count: 3, status: "completed" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "thread_viewed",
- agent_count: 3,
- status: "completed",
- })
- })
-
- it("trackTemplateUsed sends template_used event", () => {
- trackTemplateUsed({ template_id: "t_1", template_name: "Startup" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "template_used",
- template_id: "t_1",
- template_name: "Startup",
- })
- })
-
- it("trackCustomEmailConnected sends custom_email_connected event", () => {
- trackCustomEmailConnected({ email_domain: "gmail.com" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "custom_email_connected",
- email_domain: "gmail.com",
- })
- })
})
describe("P2 — Growth & Retention Signals", () => {
- it("trackTeamMemberInvited sends team_member_invited event", () => {
- trackTeamMemberInvited({ workspace_id: "ws_1" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "team_member_invited",
- workspace_id: "ws_1",
- })
- })
it("trackInviteAccepted sends invite_accepted event", () => {
trackInviteAccepted({ workspace_id: "ws_1" })
@@ -221,31 +51,6 @@ describe("analytics utility", () => {
})
})
- it("trackSecondAgentCreated sends second_agent_created event", () => {
- trackSecondAgentCreated({ total_agents: 2 })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "second_agent_created",
- total_agents: 2,
- })
- })
-
- it("trackAgentLinkCreated sends agent_link_created event", () => {
- trackAgentLinkCreated({ source_agent: "ag_1", target_agent: "ag_2" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "agent_link_created",
- source_agent: "ag_1",
- target_agent: "ag_2",
- })
- })
-
- it("trackRuntimeConnected sends runtime_connected event", () => {
- trackRuntimeConnected({ runtime_type: "desktop" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "runtime_connected",
- runtime_type: "desktop",
- })
- })
-
it("sends the exact Community funnel payloads", () => {
trackCommunityRuntimeConnected()
trackFirstAgentReplyPersisted("thread")
@@ -311,22 +116,6 @@ describe("analytics utility", () => {
category_filter: "Engineering",
})
})
-
- it("trackSettingsUpdated sends settings_updated event", () => {
- trackSettingsUpdated({ setting_tab: "general" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "settings_updated",
- setting_tab: "general",
- })
- })
-
- it("trackCanvasLayoutChanged sends canvas_layout_changed event", () => {
- trackCanvasLayoutChanged({ layout_type: "tree" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "canvas_layout_changed",
- layout_type: "tree",
- })
- })
})
describe("pricing checkout instrumentation", () => {
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 1975793fe..979b636ad 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -110,119 +110,10 @@ export function trackSignInSuccess(method: string) {
sendConsentAwareGTMEvent({ event: "sign_in_success", method });
}
-export function trackWorkspaceCreated(source: "onboarding" | "manual") {
- sendConsentAwareGTMEvent({ event: "workspace_created", source });
-}
-
-export function trackAgentCreated(params: {
- is_first_agent: boolean;
- has_email: boolean;
- template_id?: string;
-}) {
- sendConsentAwareGTMEvent({ event: "agent_created", ...params });
-}
-
-export function trackOnboardingCompleted(params: {
- template_used?: string;
- agent_count: number;
-}) {
- sendConsentAwareGTMEvent({ event: "onboarding_completed", ...params });
-}
-
-export function trackAgentChatOpened(params: {
- agent_id: string;
- is_first_chat: boolean;
-}) {
- sendConsentAwareGTMEvent({ event: "agent_chat_opened", ...params });
-}
-
-export function trackMessageSent(params: {
- agent_id: string;
- message_length: number;
-}) {
- sendConsentAwareGTMEvent({ event: "message_sent", ...params });
-}
-
-// ─── P1 — Feature Usage Events ─────────────────────────────────────────────
-
-export function trackEmailComposed(params: {
- agent_id: string;
- has_attachments: boolean;
-}) {
- sendConsentAwareGTMEvent({ event: "email_composed", ...params });
-}
-
-export function trackEmailReceived(params: {
- agent_id: string;
- mailbox_type: "alook" | "imap";
-}) {
- sendConsentAwareGTMEvent({ event: "email_received", ...params });
-}
-
-export function trackCalendarEventCreated(params: {
- agent_id: string;
- is_recurring: boolean;
-}) {
- sendConsentAwareGTMEvent({ event: "calendar_event_created", ...params });
-}
-
-export function trackIssueCreated(params: { agent_id: string }) {
- sendConsentAwareGTMEvent({ event: "issue_created", ...params });
-}
-
-export function trackIssueStatusChanged(params: {
- from: string;
- to: string;
- method: "drag" | "button";
-}) {
- sendConsentAwareGTMEvent({ event: "issue_status_changed", ...params });
-}
-
-export function trackThreadViewed(params: {
- agent_count: number;
- status: string;
-}) {
- sendConsentAwareGTMEvent({ event: "thread_viewed", ...params });
-}
-
-export function trackTemplateUsed(params: {
- template_id: string;
- template_name: string;
-}) {
- sendConsentAwareGTMEvent({ event: "template_used", ...params });
-}
-
-export function trackCustomEmailConnected(params: { email_domain: string }) {
- sendConsentAwareGTMEvent({ event: "custom_email_connected", ...params });
-}
-
-// ─── P2 — Growth & Retention Signals ───────────────────────────────────────
-
-export function trackTeamMemberInvited(params: { workspace_id: string }) {
- sendConsentAwareGTMEvent({ event: "team_member_invited", ...params });
-}
-
export function trackInviteAccepted(params: { workspace_id: string }) {
sendConsentAwareGTMEvent({ event: "invite_accepted", ...params });
}
-export function trackSecondAgentCreated(params: { total_agents: number }) {
- sendConsentAwareGTMEvent({ event: "second_agent_created", ...params });
-}
-
-export function trackAgentLinkCreated(params: {
- source_agent: string;
- target_agent: string;
-}) {
- sendConsentAwareGTMEvent({ event: "agent_link_created", ...params });
-}
-
-export function trackRuntimeConnected(params: {
- runtime_type: "desktop" | "cloud";
-}) {
- sendConsentAwareGTMEvent({ event: "runtime_connected", ...params });
-}
-
export type GithubOutboundSurface = "landing" | "blog" | "public_nav" | "public_footer"
export function trackCommunityRuntimeConnected() {
@@ -517,11 +408,3 @@ export function trackLandingCtaClicked(params: { cta_name: string }) {
export function trackTemplatesBrowsed(params: { category_filter: string }) {
sendConsentAwareGTMEvent({ event: "templates_browsed", ...params });
}
-
-export function trackSettingsUpdated(params: { setting_tab: string }) {
- sendConsentAwareGTMEvent({ event: "settings_updated", ...params });
-}
-
-export function trackCanvasLayoutChanged(params: { layout_type: string }) {
- sendConsentAwareGTMEvent({ event: "canvas_layout_changed", ...params });
-}
diff --git a/src/web/src/lib/api.test.ts b/src/web/src/lib/api.test.ts
index ca6257617..13149ffe3 100644
--- a/src/web/src/lib/api.test.ts
+++ b/src/web/src/lib/api.test.ts
@@ -62,7 +62,7 @@ describe("ApiError class", () => {
// We dynamically import to get the patched fetch
async function getApiFetch() {
// Re-import to pick up mocked fetch
- const mod = await import("./api");
+ const mod = await import("./api/client");
return mod;
}
@@ -74,9 +74,9 @@ describe("apiFetch", () => {
json: async () => ({ error: "name is required" }),
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).message).toBe("name is required");
@@ -94,9 +94,9 @@ describe("apiFetch", () => {
}),
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).message).toBe("Name is required");
@@ -114,9 +114,9 @@ describe("apiFetch", () => {
}),
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).message).toBe("Runtime Id is required");
@@ -127,9 +127,9 @@ describe("apiFetch", () => {
it("returns ApiError with status 0 on network TypeError", async () => {
mockFetch.mockRejectedValueOnce(new TypeError("Failed to fetch"));
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).status).toBe(0);
@@ -145,9 +145,9 @@ describe("apiFetch", () => {
json: async () => ({ error: "rate limited" }),
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).status).toBe(429);
@@ -163,9 +163,9 @@ describe("apiFetch", () => {
json: async () => { throw new Error("not json"); },
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).status).toBe(500);
@@ -180,9 +180,9 @@ describe("apiFetch", () => {
json: async () => ({ error: "database connection failed" }),
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).message).toBe("database connection failed");
@@ -196,9 +196,9 @@ describe("apiFetch", () => {
json: async () => { throw new Error("empty"); },
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).status).toBe(502);
@@ -213,9 +213,9 @@ describe("apiFetch", () => {
json: async () => ({ error: "unauthorized" }),
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
try {
- await listAgents("w1");
+ await apiFetch("/api/community/bots");
} catch (e) {
expect(e).toBeInstanceOf(ApiError);
expect((e as ApiError).status).toBe(401);
@@ -232,53 +232,18 @@ describe("apiFetch", () => {
json: async () => ({ error: "unauthorized" }),
});
- const { listAgents } = await getApiFetch();
+ const { apiFetch } = await getApiFetch();
beginAccountDeletionAuthTransition();
- await expect(listAgents("w1")).rejects.toMatchObject({ status: 401 });
+ await expect(apiFetch("/api/community/bots")).rejects.toMatchObject({ status: 401 });
expect(locationAssignMock).not.toHaveBeenCalled();
cancelAccountDeletionAuthTransition();
- await expect(listAgents("w1")).rejects.toMatchObject({ status: 401 });
+ await expect(apiFetch("/api/community/bots")).rejects.toMatchObject({ status: 401 });
expect(locationAssignMock).toHaveBeenCalledWith(new URL("/sign-in", "https://alook.test"));
});
});
-describe("conversationInit — message_count serialization", () => {
- function okJson() {
- return { ok: true, status: 200, json: async () => ({}) };
- }
-
- function lastUrl(): string {
- const call = mockFetch.mock.calls.at(-1);
- return String(call?.[0] ?? "");
- }
-
- it("omits message_count when the count is 0 (treated as unknown)", async () => {
- mockFetch.mockResolvedValueOnce(okJson());
- const { conversationInit } = await getApiFetch();
- await conversationInit("conv_1", "w1", { messageCount: 0 });
- expect(lastUrl()).not.toContain("message_count");
- // Critically: never sends the truthy string "0", which would make the
- // server's `serverMessageCount === 0` compare fail for non-empty convs.
- expect(lastUrl()).not.toContain("message_count=0");
- });
-
- it("includes message_count when the count is greater than 0", async () => {
- mockFetch.mockResolvedValueOnce(okJson());
- const { conversationInit } = await getApiFetch();
- await conversationInit("conv_1", "w1", { messageCount: 12 });
- expect(lastUrl()).toContain("message_count=12");
- });
-
- it("omits message_count when not provided", async () => {
- mockFetch.mockResolvedValueOnce(okJson());
- const { conversationInit } = await getApiFetch();
- await conversationInit("conv_1", "w1");
- expect(lastUrl()).not.toContain("message_count");
- });
-});
-
describe("apiFetch — mock network delay", () => {
afterEach(() => {
process.env.NODE_ENV = "test";
@@ -301,8 +266,8 @@ describe("apiFetch — mock network delay", () => {
});
vi.stubGlobal("fetch", localMockFetch);
- const { listAgents } = await import("./api");
- const promise = listAgents("w1");
+ const { apiFetch } = await import("./api/client");
+ const promise = apiFetch("/api/community/bots");
expect(localMockFetch).not.toHaveBeenCalled();
@@ -324,8 +289,8 @@ describe("apiFetch — mock network delay", () => {
});
vi.stubGlobal("fetch", localMockFetch);
- const { listAgents } = await import("./api");
- const promise = listAgents("w1");
+ const { apiFetch } = await import("./api/client");
+ const promise = apiFetch("/api/community/bots");
await vi.advanceTimersByTimeAsync(0);
@@ -348,8 +313,8 @@ describe("apiFetch — mock network delay", () => {
});
vi.stubGlobal("fetch", localMockFetch);
- const { listAgents } = await import("./api");
- const promise = listAgents("w1");
+ const { apiFetch } = await import("./api/client");
+ const promise = apiFetch("/api/community/bots");
expect(localMockFetch).not.toHaveBeenCalled();
diff --git a/src/web/src/lib/api/agents.ts b/src/web/src/lib/api/agents.ts
deleted file mode 100644
index 218933b5b..000000000
--- a/src/web/src/lib/api/agents.ts
+++ /dev/null
@@ -1,295 +0,0 @@
-import type { ApiRequestOptions } from "./client";
-import type {
-Agent,
-AgentEmailAccount,
-AgentLink,
-AgentRuntime,
-CreateAgentLinkRequest,
-CreateAgentRequest,
-CreateEmailAccountRequest,
-MeetingSession,
-UpdateAgentLinkRequest,
-UpdateAgentRequest
-} from "@alook/shared";
-import { apiFetch,wsQuery } from "./client";
-
-// Agents
-export const listAgents = (workspaceId: string, options?: RequestInit) =>
- apiFetch<Agent[]>(`/api/agents${wsQuery(workspaceId)}`, options);
-
-export const createAgent = (req: CreateAgentRequest, workspaceId: string, options?: RequestInit) =>
- apiFetch<Agent>(`/api/agents${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify(req),
- });
-
-export const getAgent = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<Agent>(`/api/agents/${id}${wsQuery(workspaceId)}`, options);
-
-export const updateAgent = (id: string, req: UpdateAgentRequest, workspaceId: string, options?: RequestInit) =>
- apiFetch<Agent>(`/api/agents/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "PATCH",
- body: JSON.stringify(req),
- });
-
-export const deleteAgent = (id: string, workspaceId: string, options?: RequestInit) =>
- apiFetch<void>(`/api/agents/${id}${wsQuery(workspaceId)}`, { ...options, method: "DELETE" });
-
-// Runtimes
-export const listRuntimes = (workspaceId: string, options?: RequestInit) =>
- apiFetch<AgentRuntime[]>(`/api/runtimes${wsQuery(workspaceId)}`, options);
-
-export const deleteMachine = (daemonId: string, workspaceId: string, options?: RequestInit) =>
- apiFetch<void>(
- `/api/runtimes/machine${wsQuery(workspaceId, { daemon_id: daemonId })}`,
- { ...options, method: "DELETE" }
- );
-
-export const triggerRuntimeUpdate = (runtimeId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ pending_update_version: string }>(
- `/api/runtimes/${runtimeId}/update${wsQuery(workspaceId)}`,
- { ...options, method: "POST" }
- );
-
-export const triggerRuntimeRescan = (runtimeId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ pending_rescan: boolean }>(
- `/api/runtimes/${runtimeId}/rescan${wsQuery(workspaceId)}`,
- { ...options, method: "POST" }
- );
-
-// Agent active tasks
-export const listAgentActiveTaskCounts = (workspaceId: string, options?: RequestInit) =>
- apiFetch<{ counts: Record<string, number> }>(`/api/agents/active-task-counts${wsQuery(workspaceId)}`, options);
-
-export interface WorkspaceActiveTask {
- id: string;
- agent_id: string;
- agent: { name: string; avatarUrl: string | null } | null;
- prompt: string;
- status: string;
- type: string;
- conversation_id: string;
- channel: string;
- created_at: string;
-}
-
-export const listWorkspaceActiveTasks = (workspaceId: string, options?: RequestInit) =>
- apiFetch<{ tasks: WorkspaceActiveTask[] }>(`/api/agents/active-tasks${wsQuery(workspaceId)}`, options);
-
-// Activity
-export interface ActivityTask {
- id: string;
- conversation_id: string;
- type: string;
- status: string;
- prompt: string;
- created_at: string;
- started_at: string | null;
- completed_at: string | null;
- error: string | null;
-}
-
-export const listAgentActivity = (
- agentId: string,
- workspaceId: string,
- opts?: { limit?: number; before?: string; beforeId?: string; status?: string; type?: string },
- options?: ApiRequestOptions
-) => {
- const extra: Record<string, string> = {};
- if (opts?.limit) extra.limit = String(opts.limit);
- if (opts?.before) extra.before = opts.before;
- if (opts?.beforeId) extra.before_id = opts.beforeId;
- if (opts?.status) extra.status = opts.status;
- if (opts?.type) extra.type = opts.type;
- return apiFetch<{ tasks: ActivityTask[]; has_more: boolean }>(
- `/api/agents/${agentId}/activity${wsQuery(workspaceId, extra)}`, options
- );
-};
-
-// Whitelist
-export interface WhitelistEntry {
- id: string;
- email: string;
- created_at: string;
-}
-
-export const listWhitelist = (agentId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<WhitelistEntry[]>(`/api/agents/${agentId}/whitelist${wsQuery(workspaceId)}`, options);
-
-export const addWhitelistEmail = (agentId: string, email: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<WhitelistEntry>(`/api/agents/${agentId}/whitelist${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ email }),
- });
-
-export const removeWhitelistEmail = (agentId: string, whitelistId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/agents/${agentId}/whitelist/${whitelistId}${wsQuery(workspaceId)}`, {
- ...options, method: "DELETE",
- });
-
-// Agent Links
-export const listAgentLinks = (workspaceId: string, options?: RequestInit) =>
- apiFetch<AgentLink[]>(`/api/agent-links${wsQuery(workspaceId)}`, options);
-
-export const createAgentLink = (req: CreateAgentLinkRequest, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<AgentLink>(`/api/agent-links${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify(req),
- });
-
-export const updateAgentLink = (id: string, req: UpdateAgentLinkRequest, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "PATCH",
- body: JSON.stringify(req),
- });
-
-export const deleteAgentLink = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "DELETE",
- });
-
-// Email Accounts
-export const listEmailAccounts = (agentId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<AgentEmailAccount[]>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`, options);
-
-export const createEmailAccount = (agentId: string, data: CreateEmailAccountRequest, workspaceId: string, options?: RequestInit) =>
- apiFetch<AgentEmailAccount>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify(data),
- });
-
-export const deleteEmailAccount = (agentId: string, accountId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}${wsQuery(workspaceId)}`, {
- ...options,
- method: "DELETE",
- });
-
-export const syncEmailAccount = (agentId: string, accountId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}/sync${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- });
-
-// Agent Access
-export interface AgentAccessEntry {
- id: string; user_id: string; name: string; email: string; created_at: string;
-}
-
-export const listAgentAccess = (workspaceId: string, agentId: string, options?: ApiRequestOptions) =>
- apiFetch<AgentAccessEntry[]>(`/api/agents/${agentId}/access${wsQuery(workspaceId)}`, options);
-
-export const grantAgentAccess = (workspaceId: string, agentId: string, userId: string, options?: ApiRequestOptions) =>
- apiFetch<{ id: string; user_id: string }>(`/api/agents/${agentId}/access${wsQuery(workspaceId)}`, { ...options, method: "POST", body: JSON.stringify({ user_id: userId }) });
-
-export const revokeAgentAccess = (workspaceId: string, agentId: string, userId: string, removeWhitelist = false, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/agents/${agentId}/access/${userId}${wsQuery(workspaceId)}${removeWhitelist ? "&remove_whitelist=true" : ""}`, { ...options, method: "DELETE" });
-
-// Agent Pins
-export interface AgentPin {
- id: string;
- agent_id: string;
- created_at: string;
- position: number;
-}
-
-export interface SidebarOrder {
- agent_id: string;
- position: number;
-}
-
-export const listAgentPins = (workspaceId: string, options?: RequestInit) =>
- apiFetch<{ pins: AgentPin[]; sidebar_order: SidebarOrder[] }>(`/api/agents/pins${wsQuery(workspaceId)}`, options);
-
-export const pinAgent = (workspaceId: string, agentId: string, options?: RequestInit) =>
- apiFetch<{ pinned: boolean }>(`/api/agents/${agentId}/pin${wsQuery(workspaceId)}`, { ...options, method: "POST" });
-
-export const unpinAgent = (workspaceId: string, agentId: string, options?: RequestInit) =>
- apiFetch<void>(`/api/agents/${agentId}/pin${wsQuery(workspaceId)}`, { ...options, method: "DELETE" });
-
-export const reorderAgentPins = (workspaceId: string, orderedAgentIds: string[], options?: RequestInit) =>
- apiFetch<void>(`/api/agents/pins/reorder${wsQuery(workspaceId)}`, {
- ...options,
- method: "PUT",
- body: JSON.stringify({ ordered_agent_ids: orderedAgentIds }),
- });
-
-export const reorderUnpinnedAgents = (workspaceId: string, orderedAgentIds: string[], options?: RequestInit) =>
- apiFetch<void>(`/api/agents/sidebar/reorder${wsQuery(workspaceId)}`, {
- ...options,
- method: "PUT",
- body: JSON.stringify({ ordered_agent_ids: orderedAgentIds }),
- });
-
-// Workspace file browsing
-export const requestWorkspaceBrowse = (
- agentId: string,
- workspaceId: string,
- requestType: "tree" | "read",
- path: string,
- options?: ApiRequestOptions,
-) =>
- apiFetch<{ request_id: string }>(
- `/api/agents/${agentId}/workspace/browse${wsQuery(workspaceId)}`,
- {
- ...options,
- method: "POST",
- body: JSON.stringify({ request_type: requestType, path }),
- },
- );
-
-// Skill browsing
-export const getAgentSkills = (agentId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ skills: { name: string; description: string; isGlobal?: boolean }[] }>(
- `/api/agents/${agentId}/skills${wsQuery(workspaceId)}`, options,
- );
-
-// Meetings
-export const listMeetings = (agentId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<MeetingSession[]>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`, options);
-
-export const createMeeting = (agentId: string, workspaceId: string, data: {
- meetingUrl: string;
- title?: string;
- participants?: string[];
-}, options?: ApiRequestOptions) =>
- apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify(data),
- });
-
-export const stopMeeting = (agentId: string, meetingId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<MeetingSession & { transcript?: string }>(`/api/agents/${agentId}/meetings/${meetingId}/stop${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- });
-
-export const approveMeeting = (agentId: string, meetingId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings/${meetingId}/approve${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- });
-
-export const deleteMeeting = (agentId: string, meetingId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/agents/${agentId}/meetings/${meetingId}${wsQuery(workspaceId)}`, {
- ...options,
- method: "DELETE",
- });
-
-// Machine tokens
-export const createMachineToken = (name?: string, workspaceId?: string, options?: RequestInit) =>
- apiFetch<{ token: string; id: string; name: string; created_at: string }>(
- `/api/machine-tokens${workspaceId ? wsQuery(workspaceId) : ""}`,
- {
- ...options,
- method: "POST",
- body: JSON.stringify({ name: name || "default" }),
- }
- );
diff --git a/src/web/src/lib/api/artifacts.ts b/src/web/src/lib/api/artifacts.ts
deleted file mode 100644
index 410c02bd1..000000000
--- a/src/web/src/lib/api/artifacts.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { readApiResponse } from "./client";
-import type { Artifact } from "@alook/shared";
-import type { ApiRequestOptions } from "./client";
-import { apiFetch, apiFetchResponse, wsQuery } from "./client";
-
-export const listArtifacts = (conversationId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<Artifact[]>(`/api/artifacts${wsQuery(workspaceId, { conversation_id: conversationId })}`, options);
-
-export const getArtifactContent = async (id: string, workspaceId: string, options?: ApiRequestOptions): Promise<string> => {
- const params = new URLSearchParams({ workspace_id: workspaceId });
- const res = await apiFetchResponse(`/api/artifacts/${id}/content?${params}`, options, true);
- const text = await readApiResponse<string>(res, "text", options);
- options?.assertActive?.();
- if (options?.signal?.aborted) throw new DOMException("Retired artifact content", "AbortError");
- return text;
-};
diff --git a/src/web/src/lib/api/calendar.ts b/src/web/src/lib/api/calendar.ts
deleted file mode 100644
index 68b05bb59..000000000
--- a/src/web/src/lib/api/calendar.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import type {
- CalendarEvent,
- CreateCalendarEventRequest,
- UpdateCalendarEventRequest,
- DeleteCalendarEventRequest,
-} from "@alook/shared";
-import { apiFetch, wsQuery, type ApiRequestOptions } from "./client";
-
-export const listCalendarEvents = (
- workspaceId: string,
- opts?: { agentId?: string; from?: string; to?: string },
- options?: ApiRequestOptions
-) => {
- const extra: Record<string, string> = {};
- if (opts?.agentId) extra.agentId = opts.agentId;
- if (opts?.from) extra.from = opts.from;
- if (opts?.to) extra.to = opts.to;
- return apiFetch<CalendarEvent[]>(`/api/calendar${wsQuery(workspaceId, extra)}`, options);
-};
-
-export const getCalendarEvent = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`, options);
-
-export const createCalendarEvent = (
- req: CreateCalendarEventRequest,
- workspaceId: string,
- options?: ApiRequestOptions
-) =>
- apiFetch<CalendarEvent>(`/api/calendar${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify(req),
- });
-
-export const updateCalendarEvent = (
- id: string,
- patch: UpdateCalendarEventRequest,
- workspaceId: string,
- options?: ApiRequestOptions
-) =>
- apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "PATCH",
- body: JSON.stringify(patch),
- });
-
-export const deleteCalendarEvent = (
- id: string,
- workspaceId: string,
- body?: DeleteCalendarEventRequest,
- options?: ApiRequestOptions
-) =>
- apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "DELETE",
- ...(body && body.scope
- ? {
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- }
- : {}),
- });
diff --git a/src/web/src/lib/api/channels.ts b/src/web/src/lib/api/channels.ts
deleted file mode 100644
index 2a4a788ef..000000000
--- a/src/web/src/lib/api/channels.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { Channel } from "@alook/shared";
-import { apiFetch, wsQuery } from "./client";
-
-export const listChannels = (workspaceId: string, options?: RequestInit) =>
- apiFetch<Channel[]>(`/api/channels${wsQuery(workspaceId)}`, options);
-
-export const createChannelApi = (workspaceId: string, name: string, options?: RequestInit) =>
- apiFetch<Channel>(`/api/channels${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ name }),
- });
-
-export const renameChannelApi = (id: string, workspaceId: string, name: string, options?: RequestInit) =>
- apiFetch<Channel>(`/api/channels/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "PATCH",
- body: JSON.stringify({ name }),
- });
-
-export const deleteChannelApi = (id: string, workspaceId: string, options?: RequestInit) =>
- apiFetch<{ ok: boolean }>(`/api/channels/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "DELETE",
- });
-
-export const reorderChannelsApi = (workspaceId: string, orderedChannelIds: string[], options?: RequestInit) =>
- apiFetch<void>(`/api/channels/reorder${wsQuery(workspaceId)}`, {
- ...options,
- method: "PUT",
- body: JSON.stringify({ ordered_channel_ids: orderedChannelIds }),
- });
diff --git a/src/web/src/lib/api/client.test.ts b/src/web/src/lib/api/client.test.ts
index c27776aca..2d804ea92 100644
--- a/src/web/src/lib/api/client.test.ts
+++ b/src/web/src/lib/api/client.test.ts
@@ -116,9 +116,8 @@ vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: vi.fn() };
vi.mock("next/navigation", () => ({ useRouter: vi.fn() }))
describe("apiFetch account-qualified authentication effects", () => {
- it.each(["account", "workspace"] as const)("late 401 after %s retirement cannot redirect the next account", async (retirement) => {
- const { createApplicationOwner, retireApplicationOwner } = await import("@/lib/application-owner")
- const { createWorkspaceOwner, runWorkspaceRequest } = await import("@/contexts/workspace-context")
+ it("late 401 after account retirement cannot redirect the next account", async () => {
+ const { createApplicationOwner, retireApplicationOwner, runApplicationRequest } = await import("@/lib/application-owner")
const { apiFetch } = await import("./client")
let release!: (response: Response) => void
const fetchMock = vi.fn(() => new Promise<Response>((resolve) => { release = resolve }))
@@ -126,12 +125,10 @@ describe("apiFetch account-qualified authentication effects", () => {
vi.stubGlobal("fetch", fetchMock)
vi.stubGlobal("window", { location: { origin: "https://alook.test", assign } })
const application = createApplicationOwner("viewer-a")
- const workspace = createWorkspaceOwner(application, "workspace-a", "a")
try {
- const request = runWorkspaceRequest(workspace, (options) => apiFetch("/api/test", options))
+ const request = runApplicationRequest(application, (options) => apiFetch("/api/test", options))
const rejected = expect(request).rejects.toMatchObject({ name: "AbortError" })
- if (retirement === "account") retireApplicationOwner(application)
- else workspace.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
+ retireApplicationOwner(application)
release(new Response(null, { status: 401 }))
await rejected
expect(assign).not.toHaveBeenCalled()
@@ -143,15 +140,14 @@ describe("apiFetch account-qualified authentication effects", () => {
})
it("current owner 401 keeps the full-document sign-in navigation", async () => {
- const { createApplicationOwner } = await import("@/lib/application-owner")
- const { createWorkspaceOwner, runWorkspaceRequest } = await import("@/contexts/workspace-context")
+ const { createApplicationOwner, runApplicationRequest } = await import("@/lib/application-owner")
const { apiFetch } = await import("./client")
const assign = vi.fn()
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 401 })))
vi.stubGlobal("window", { location: { origin: "https://alook.test", assign } })
const application = createApplicationOwner("viewer-a")
try {
- await expect(runWorkspaceRequest(createWorkspaceOwner(application, "workspace-a", "a"), (options) => apiFetch("/api/test", options)))
+ await expect(runApplicationRequest(application, (options) => apiFetch("/api/test", options)))
.rejects.toMatchObject({ status: 401 })
expect(assign).toHaveBeenCalledOnce()
expect(String(assign.mock.calls[0][0])).toBe("https://alook.test/sign-in")
diff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.ts
index 31d93f1dd..14672fb3e 100644
--- a/src/web/src/lib/api/client.ts
+++ b/src/web/src/lib/api/client.ts
@@ -206,15 +206,3 @@ export async function readUploadError(res: Response, fallback: string): Promise<
}
return new ApiError(serverError || fallback, res.status);
}
-
-export function wsQuery(workspaceId: string, extra?: Record<string, string>): string {
- const params = new URLSearchParams({ workspace_id: workspaceId, ...extra });
- return `?${params.toString()}`;
-}
-
-export async function readApiResponse<T>(response: Response, format: "json" | "text", options?: ApiRequestOptions): Promise<T> {
- return readObservedResponse(response, () => format === "text" ? response.text() as Promise<T> : response.json() as Promise<T>, () => {
- options?.assertActive?.();
- if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");
- });
-}
diff --git a/src/web/src/lib/api/config.ts b/src/web/src/lib/api/config.ts
index 13ca2d072..acd130c87 100644
--- a/src/web/src/lib/api/config.ts
+++ b/src/web/src/lib/api/config.ts
@@ -1,13 +1,4 @@
import { apiFetch, type ApiRequestOptions } from "./client";
-export const fetchModelOptions = (options?: RequestInit) =>
- apiFetch<Record<string, string[]>>("/api/config/model-options", options);
-
-export const getMinCliVersion = (options?: ApiRequestOptions) =>
- apiFetch<{ min_cli_version: string | null }>("/api/config/min-version", options);
-
-export const fetchLatestCliVersion = (options?: ApiRequestOptions) =>
- apiFetch<{ version: string; package: string }>("/api/cli/latest-version", options);
-
export const fetchLatestDaemonVersion = (options?: ApiRequestOptions) =>
apiFetch<{ version: string; package: string }>("/api/daemon/latest-version", options);
diff --git a/src/web/src/lib/api/conversations.ts b/src/web/src/lib/api/conversations.ts
deleted file mode 100644
index 8229e5c58..000000000
--- a/src/web/src/lib/api/conversations.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-import { readApiResponse } from "./client";
-import type {
-Artifact,
-Conversation,
-Message,
-TaskApi,
-TaskMessageResponse,
-} from "@alook/shared";
-import type { PendingFile } from "@/hooks/use-file-attachments";
-import type { ApiRequestOptions } from "./client";
-import { apiFetch,apiFetchResponse,wsQuery } from "./client";
-
-export const createConversation = (agentId: string, workspaceId: string, channel?: string, options?: ApiRequestOptions) =>
- apiFetch<Conversation>(`/api/conversations${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ agent_id: agentId, ...(channel ? { channel } : {}) }),
- });
-
-export interface PreviousConversation {
- id: string;
- created_at: string;
-}
-
-export interface ChatInitResponse {
- conversation: Conversation;
- messages: Message[];
- artifacts: Artifact[];
- active_task: TaskApi | null;
- task_messages: TaskMessageResponse[];
- has_more_messages: boolean;
- has_more_conversations: boolean;
- has_more_artifacts: boolean;
-}
-
-export const listPreviousConversations = (
- agentId: string,
- workspaceId: string,
- opts: { exclude: string; before: string; channel?: string; limit?: number },
- options?: ApiRequestOptions,
-) => {
- const extra: Record<string, string> = { exclude: opts.exclude, before: opts.before };
- if (opts.channel) extra.channel = opts.channel;
- if (opts.limit) extra.limit = String(opts.limit);
- return apiFetch<{ conversations: PreviousConversation[]; has_more: boolean }>(
- `/api/agents/${agentId}/conversations${wsQuery(workspaceId, extra)}`, options,
- );
-};
-
-export const chatInit = (agentId: string, workspaceId: string, channel?: string, options?: ApiRequestOptions) =>
- apiFetch<ChatInitResponse>(`/api/agents/${agentId}/chat-init${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ ...(channel ? { channel } : {}) }),
- });
-
-export interface ConversationInitResponse {
- conversation: Conversation;
- messages: Message[] | null;
- has_more_messages: boolean;
- has_more_conversations: boolean;
- has_more_artifacts: boolean;
- artifacts: Artifact[];
- flagged_message_ids: string[];
- active_task: TaskApi | null;
- task_messages: TaskMessageResponse[];
- cache_valid: boolean;
- message_count: number;
- root_message?: Message | null;
-}
-
-export const conversationInit = (
- conversationId: string,
- workspaceId: string,
- opts?: { newestMessageId?: string; messageCount?: number },
- options?: ApiRequestOptions,
-) => {
- const extra: Record<string, string> = {};
- if (opts?.newestMessageId) extra.newest_message_id = opts.newestMessageId;
- if (opts?.messageCount) extra.message_count = String(opts.messageCount);
- return apiFetch<ConversationInitResponse>(
- `/api/conversations/${conversationId}/init${wsQuery(workspaceId, extra)}`, options,
- );
-};
-
-export interface FreshnessCheckResponse {
- conversation_id: string;
- newest_message_id: string | null;
- message_count: number;
-}
-
-export const checkFreshness = (
- opts: { conversationId?: string; agentId?: string; channel?: string },
- workspaceId: string,
- options?: ApiRequestOptions,
-) => {
- const extra: Record<string, string> = {};
- if (opts.conversationId) extra.conversation_id = opts.conversationId;
- if (opts.agentId) extra.agent_id = opts.agentId;
- if (opts.channel) extra.channel = opts.channel;
- return apiFetch<FreshnessCheckResponse>(
- `/api/conversations/check-fresh${wsQuery(workspaceId, extra)}`, options,
- );
-};
-
-export const listMessages = (
- conversationId: string,
- workspaceId: string,
- opts?: { limit?: number; before?: string; beforeId?: string },
- options?: ApiRequestOptions,
-) => {
- const extra: Record<string, string> = {};
- if (opts?.limit) extra.limit = String(opts.limit);
- if (opts?.before) extra.before = opts.before;
- if (opts?.beforeId) extra.before_id = opts.beforeId;
- return apiFetch<{ messages: Message[]; has_more: boolean }>(
- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, extra)}`, options,
- );
-};
-
-export const listMessagesAroundTask = (
- conversationId: string,
- workspaceId: string,
- taskId: string,
- options?: ApiRequestOptions,
-) =>
- apiFetch<Message[]>(
- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, { around_task: taskId })}`, options,
- );
-
-export const sendMessage = async (
- conversationId: string,
- content: string,
- workspaceId: string,
- files?: PendingFile[],
- metadata?: Record<string, unknown>,
- options?: ApiRequestOptions,
-): Promise<{ message: Message; task: TaskApi }> => {
- if (!files || files.length === 0) {
- return apiFetch<{ message: Message; task: TaskApi }>(
- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,
- {
- ...options,
- method: "POST",
- body: JSON.stringify({ content, ...(metadata ? { metadata } : {}) }),
- },
- );
- }
-
- const fd = new FormData();
- fd.append("content", content);
- if (metadata) fd.append("metadata", JSON.stringify(metadata));
- for (const pf of files) {
- fd.append("file", pf.file);
- }
- for (let i = 0; i < files.length; i++) {
- const blob = files[i].thumbnailBlob;
- if (blob) fd.append(`thumbnail:${i}`, blob, "thumbnail.jpg");
- }
-
- const res = await apiFetchResponse(`/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`, { ...options, method: "POST", body: fd }, true);
- const data = await readApiResponse(res, "json", options) as { message: Message; task: TaskApi };
- options?.assertActive?.();
- if (options?.signal?.aborted) throw new DOMException("Cancelled chat upload", "AbortError");
- return data;
-};
-
-// Active task for conversation
-export const getActiveTask = (conversationId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<TaskApi | undefined>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`, options);
-
-export const cancelActiveTask = (conversationId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<TaskApi>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`, {
- ...options,
- method: "DELETE",
- });
-
-// Threads
-export interface ThreadSummary {
- thread_id: string;
- parent_message_id: string;
- thread_title: string;
- reply_count: number;
- last_reply_at: string | null;
- created_at: string;
-}
-
-export const createThread = (
- conversationId: string,
- parentMessageId: string,
- content: string,
- workspaceId: string,
- options?: ApiRequestOptions,
-) =>
- apiFetch<{
- conversation: Conversation;
- message: Message;
- task: TaskApi;
- }>(`/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ parent_message_id: parentMessageId, content }),
- });
-
-export const getThreadSummaries = (conversationId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ thread_summaries: ThreadSummary[] }>(
- `/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`, options
- );
diff --git a/src/web/src/lib/api/emails.ts b/src/web/src/lib/api/emails.ts
deleted file mode 100644
index 40c4fcccf..000000000
--- a/src/web/src/lib/api/emails.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { readApiResponse } from "./client";
-import type { Email } from "@alook/shared";
-import { ApiError } from "@/lib/errors";
-import { apiFetch, apiFetchResponse, wsQuery, type ApiRequestOptions } from "./client";
-
-export const listEmails = (agentId: string, workspaceId: string, folder?: string, address?: string, options?: ApiRequestOptions) =>
- apiFetch<Email[]>(`/api/email${wsQuery(workspaceId, { agentId, ...(folder ? { folder } : {}), ...(address ? { address } : {}) })}`, options);
-
-export const getEmail = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`, options);
-
-export const getEmailThread = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<Email[]>(`/api/email/${id}/thread${wsQuery(workspaceId)}`, options);
-
-export const getEmailBody = async (id: string, workspaceId: string, options?: ApiRequestOptions): Promise<{ content: string; isHtml: boolean }> => {
- let res: Response;
- try { res = await apiFetchResponse(`/api/email/${id}/body${wsQuery(workspaceId)}`, options, true); }
- catch (error) {
- options?.assertActive?.();
- if (error instanceof ApiError && error.status !== 401) return { content: "(body not available)", isHtml: false };
- throw error;
- }
- const contentType = res.headers.get("Content-Type") ?? "";
- const content = await readApiResponse<string>(res, "text", options);
- options?.assertActive?.();
- if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");
- return { content, isHtml: contentType.includes("text/html") };
-};
-
-export const deleteEmail = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/email/${id}${wsQuery(workspaceId)}`, { ...options, method: "DELETE" });
-
-export const updateEmailStatus = (id: string, workspaceId: string, status: string, options?: ApiRequestOptions) =>
- apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`, {
- ...options,
- method: "PATCH",
- body: JSON.stringify({ status }),
- });
-
-export const trustEmail = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ ok: boolean; email: Email; conversationId: string }>(
- `/api/email/${id}/trust${wsQuery(workspaceId)}`,
- { ...options, method: "POST" }
- );
-
-export const uploadEmailAttachment = async (
- file: File,
- workspaceId: string,
-): Promise<{ key: string; filename: string; size: number; contentType: string }> => {
- const fd = new FormData();
- fd.append("file", file);
- const res = await fetch(`/api/email/upload${wsQuery(workspaceId)}`, {
- method: "POST",
- credentials: "include",
- body: fd,
- });
- if (!res.ok) {
- const msg = await readApiResponse<string>(res, "text").catch(() => "Upload failed");
- throw new ApiError(msg, res.status);
- }
- return res.json();
-};
-
-export const sendEmail = (
- agentId: string,
- to: string,
- subject: string,
- htmlBody: string,
- workspaceId: string,
- attachments?: { key: string; filename: string; size: number; contentType: string }[],
- threading?: { inReplyTo?: string; references?: string },
- customAccountId?: string,
- options?: ApiRequestOptions,
-) =>
- apiFetch<Email>(`/api/email/send${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ agentId, to, subject, htmlBody, attachments, ...threading, customAccountId }),
- });
diff --git a/src/web/src/lib/api/inbox.ts b/src/web/src/lib/api/inbox.ts
deleted file mode 100644
index c61be2468..000000000
--- a/src/web/src/lib/api/inbox.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import type { ApiRequestOptions } from "./client";
-import { apiFetch, wsQuery } from "./client";
-
-// Inbox
-export interface InboxItem {
- id: string;
- agent_id: string;
- title: string;
- channel: string;
- latest_response: string;
- latest_response_at: string;
- root_prompt: string | null;
- agent_name: string | null;
- agent_avatar_url: string | null;
- root_task_status: string | null;
- root_task_type: string | null;
-}
-
-export const listInboxItems = (
- workspaceId: string,
- opts?: { limit?: number; before?: string; types?: string[] },
- options?: RequestInit
-) => {
- const extra: Record<string, string> = {};
- if (opts?.limit) extra.limit = String(opts.limit);
- if (opts?.before) extra.before = opts.before;
- if (opts?.types?.length) extra.types = opts.types.join(",");
- return apiFetch<{ items: InboxItem[]; has_more: boolean }>(
- `/api/inbox${wsQuery(workspaceId, extra)}`, options
- );
-};
-
-export const getInboxCount = (workspaceId: string, opts?: { types?: string[] }, options?: RequestInit) => {
- const extra: Record<string, string> = {};
- if (opts?.types?.length) extra.types = opts.types.join(",");
- return apiFetch<{ count: number }>(`/api/inbox/count${wsQuery(workspaceId, extra)}`, options);
-};
-
-export const markInboxRead = (conversationId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/inbox/read${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ conversationId }),
- });
-
-export const markAllInboxRead = (workspaceId: string, options?: RequestInit) =>
- apiFetch<void>(`/api/inbox/read-all${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- });
-
-// Flags
-export interface FlaggedItem {
- id: string;
- message_id: string;
- message_content: string;
- message_role: string;
- message_created_at: string;
- conversation_id: string;
- conversation_title: string;
- agent_id: string;
- agent_name: string | null;
- agent_avatar_url: string | null;
- flagged_at: string;
-}
-
-export const listFlaggedItems = (
- workspaceId: string,
- opts?: { limit?: number; before?: string },
- options?: RequestInit
-) => {
- const extra: Record<string, string> = {};
- if (opts?.limit) extra.limit = String(opts.limit);
- if (opts?.before) extra.before = opts.before;
- return apiFetch<{ items: FlaggedItem[]; has_more: boolean }>(
- `/api/flags${wsQuery(workspaceId, extra)}`, options
- );
-};
-
-export const getFlaggedCount = (workspaceId: string, options?: RequestInit) =>
- apiFetch<{ count: number }>(`/api/flags/count${wsQuery(workspaceId)}`, options);
-
-export const flagMessage = (workspaceId: string, messageId: string, options?: ApiRequestOptions) =>
- apiFetch<{ flagged: boolean }>(`/api/flags${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ messageId }),
- });
-
-export const unflagMessage = (workspaceId: string, messageId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/flags/${messageId}${wsQuery(workspaceId)}`, {
- ...options,
- method: "DELETE",
- });
-
-export const listFlaggedMessageIds = (workspaceId: string, conversationId: string, options?: ApiRequestOptions) =>
- apiFetch<{ message_ids: string[] }>(
- `/api/flags${wsQuery(workspaceId, { conversation_id: conversationId, ids_only: "true" })}`, options,
- );
diff --git a/src/web/src/lib/api/index.ts b/src/web/src/lib/api/index.ts
deleted file mode 100644
index 9c47d37b8..000000000
--- a/src/web/src/lib/api/index.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
-export { fetchModelOptions, getMinCliVersion, fetchLatestCliVersion } from "./config";
-export { listAgents, createAgent, getAgent, updateAgent, deleteAgent, listRuntimes, deleteMachine, triggerRuntimeUpdate, triggerRuntimeRescan, listAgentActiveTaskCounts, listWorkspaceActiveTasks, listAgentActivity, listWhitelist, addWhitelistEmail, removeWhitelistEmail, listAgentLinks, createAgentLink, updateAgentLink, deleteAgentLink, listEmailAccounts, createEmailAccount, deleteEmailAccount, syncEmailAccount, listAgentAccess, grantAgentAccess, revokeAgentAccess, listAgentPins, pinAgent, unpinAgent, reorderAgentPins, reorderUnpinnedAgents, requestWorkspaceBrowse, getAgentSkills, listMeetings, createMeeting, stopMeeting, approveMeeting, deleteMeeting, createMachineToken } from "./agents";
-export type { WorkspaceActiveTask, ActivityTask, WhitelistEntry, AgentAccessEntry } from "./agents";
-export {
- listChannels,
- createChannelApi,
- renameChannelApi,
- deleteChannelApi,
- reorderChannelsApi,
-} from "./channels";
-export { createConversation, listPreviousConversations, chatInit, conversationInit, checkFreshness, listMessages, listMessagesAroundTask, sendMessage, getActiveTask, cancelActiveTask, createThread, getThreadSummaries } from "./conversations";
-export type { PreviousConversation } from "./conversations";
-export {
- listCalendarEvents,
- getCalendarEvent,
- createCalendarEvent,
- updateCalendarEvent,
- deleteCalendarEvent,
-} from "./calendar";
-export {
- listEmails,
- getEmail,
- getEmailThread,
- getEmailBody,
- deleteEmail,
- updateEmailStatus,
- trustEmail,
- uploadEmailAttachment,
- sendEmail,
-} from "./emails";
-export { getTask, getTaskMessages, retryTask } from "./tasks";
-export { listIssues, createIssue, getIssue, updateIssue, createIssueComment, deleteIssue } from "./issues";
-export type { IssueListItem, IssueDetailResponse } from "./issues";
-export { listWorkspaces, updateWorkspace, deleteWorkspace, listMembers, removeMember, getMemberMe, updateMemberMe, listInvites, createInvite, revokeInvite, getInviteInfo, acceptInvite, getWorkspaceOverview } from "./workspaces";
-export type { MemberEntry, InviteEntry, WorkspaceOverview } from "./workspaces";
-export {
- listInboxItems,
- getInboxCount,
- markInboxRead,
- markAllInboxRead,
- listFlaggedItems,
- getFlaggedCount,
- flagMessage,
- unflagMessage,
- listFlaggedMessageIds,
-} from "./inbox";
-export type { InboxItem, FlaggedItem } from "./inbox";
-export { listTraces, getTrace } from "./traces";
-export type { TraceListItem, TraceTask } from "./traces";
-export { listArtifacts, getArtifactContent } from "./artifacts";
diff --git a/src/web/src/lib/api/issues.ts b/src/web/src/lib/api/issues.ts
deleted file mode 100644
index ee1b54b31..000000000
--- a/src/web/src/lib/api/issues.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { readApiResponse } from "./client";
-import type {
-Artifact,
-Issue,
-IssueComment,
-Message,
-CreateIssueRequest,
-TaskApi,
-UpdateIssueRequest,
-} from "@alook/shared";
-import { apiFetch,apiFetchResponse,wsQuery,type ApiRequestOptions } from "./client";
-
-export type IssueListItem = Issue & { thread_agent_ids?: string[] };
-
-export interface IssueDetailResponse {
- issue: Issue & { trace_id?: string | null };
- messages: Message[];
- comments: IssueComment[];
- artifacts: Artifact[];
-}
-
-export const listIssues = (
- workspaceId: string,
- opts?: { agentId?: string; status?: string; terminal?: boolean },
- options?: ApiRequestOptions
-) => {
- const extra: Record<string, string> = {};
- if (opts?.agentId) extra.agentId = opts.agentId;
- if (opts?.status) extra.status = opts.status;
- if (opts?.terminal !== undefined) extra.terminal = String(opts.terminal);
- return apiFetch<IssueListItem[]>(`/api/issues${wsQuery(workspaceId, extra)}`, options);
-};
-
-export const createIssue = async (
- workspaceId: string,
- req: CreateIssueRequest & { files?: File[] },
- options?: ApiRequestOptions,
-): Promise<{ issue: Issue; message?: Message; task?: TaskApi }> => {
- if (!req.files || req.files.length === 0) {
- return apiFetch<{ issue: Issue; message?: Message; task?: TaskApi }>(`/api/issues${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({
- agent_id: req.agent_id,
- title: req.title,
- description: req.description,
- }),
- });
- }
-
- const fd = new FormData();
- if (req.agent_id) fd.append("agent_id", req.agent_id);
- fd.append("title", req.title);
- fd.append("description", req.description ?? "");
- for (const file of req.files) {
- fd.append("file", file);
- }
-
- const res = await apiFetchResponse(`/api/issues${wsQuery(workspaceId)}`, { ...options, method: "POST", body: fd }, true);
- const data = await readApiResponse(res, "json", options) as { issue: Issue; message?: Message; task?: TaskApi };
- options?.assertActive?.();
- if (options?.signal?.aborted) throw new DOMException("Cancelled issue upload", "AbortError");
- return data;
-};
-
-export const getIssue = (workspaceId: string, issueId: string, options?: ApiRequestOptions) =>
- apiFetch<IssueDetailResponse>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, options);
-
-export const updateIssue = (workspaceId: string, issueId: string, patch: UpdateIssueRequest, options?: ApiRequestOptions) =>
- apiFetch<Issue>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, {
- ...options,
- method: "PATCH",
- body: JSON.stringify(patch),
- });
-
-export const createIssueComment = (workspaceId: string, issueId: string, content: string, options?: ApiRequestOptions) =>
- apiFetch<{ comment: IssueComment }>(`/api/issues/${issueId}/comments${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- body: JSON.stringify({ content }),
- });
-
-export const deleteIssue = (workspaceId: string, issueId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, { ...options, method: "DELETE" });
diff --git a/src/web/src/lib/api/observability-consumers.test.ts b/src/web/src/lib/api/observability-consumers.test.ts
index 93a6ddbef..ce736c70c 100644
--- a/src/web/src/lib/api/observability-consumers.test.ts
+++ b/src/web/src/lib/api/observability-consumers.test.ts
@@ -1,34 +1,25 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest"
-import { getArtifactContent } from "./artifacts"
-import { createIssue } from "./issues"
-import { sendMessage } from "./conversations"
-import { uploadEmailAttachment } from "./emails"
+import { apiFetch, readUploadError } from "./client"
import { configureTelemetry, installTelemetrySink, retireTelemetry } from "../observability/telemetry"
const fetch = vi.fn(), events: Array<{ name: string; attributes: Record<string, string> }> = []
beforeEach(() => { fetch.mockReset(); events.length = 0; vi.stubGlobal("fetch", fetch); configureTelemetry({ session_id: "consumer-session" }, true); installTelemetrySink(event => events.push(event)) })
afterEach(() => { retireTelemetry(); vi.unstubAllGlobals() })
-it("returns artifact text after observed parsing and preserves active owner checks", async () => {
- fetch.mockResolvedValue(new Response("private-artifact-body"))
- const assertActive = vi.fn()
- expect(await getArtifactContent("artifact-a", "workspace-a", { assertActive })).toBe("private-artifact-body")
- expect(fetch).toHaveBeenCalledWith("/api/artifacts/artifact-a/content?workspace_id=workspace-a", expect.any(Object))
+
+it("preserves live multipart JSON parsing, owner checks and sanitized diagnostics", async () => {
+ const result = { file: { id: "file-a" } }, assertActive = vi.fn()
+ fetch.mockResolvedValue(Response.json(result))
+ const body = new FormData()
+ body.set("file", new File(["private-file-body"], "private.txt"))
+ expect(await apiFetch("/api/community/channels/channel-a/attachments", { method: "POST", body, assertActive })).toEqual(result)
+ expect(fetch).toHaveBeenCalledWith("/api/community/channels/channel-a/attachments", expect.objectContaining({ method: "POST", body }))
expect(assertActive).toHaveBeenCalled()
- expect(events.some(event => event.name === "request.body_parsed" && event.attributes.route_template === "/api/artifacts/[id]/content")).toBe(true)
- expect(JSON.stringify(events)).not.toContain("private-artifact-body")
-})
-it("preserves multipart issue and conversation responses through observed JSON parsing", async () => {
- const issue = { issue: { id: "issue-a" } }, message = { message: { id: "message-a" }, task: { id: "task-a" } }
- fetch.mockResolvedValueOnce(Response.json(issue)).mockResolvedValueOnce(Response.json(message))
- const file = new File(["private-file-body"], "private.txt", { type: "text/plain" })
- expect(await createIssue("workspace-a", { title: "private-title", agent_id: "agent-a", files: [file] })).toEqual(issue)
- expect(await sendMessage("conversation-a", "private-message", "workspace-a", [{ file, thumbnailUrl: null, thumbnailBlob: null }])).toEqual(message)
- expect(fetch.mock.calls.every(([, options]) => options.method === "POST" && options.body instanceof FormData)).toBe(true)
- expect(events.filter(event => event.name === "request.body_parsed")).toHaveLength(2)
- expect(JSON.stringify(events)).not.toMatch(/private-(?:file|message|title)/)
+ expect(events.some(event => event.name === "request.body_parsed" && event.attributes.route_template === "/api/community/channels/[id]/attachments")).toBe(true)
+ expect(JSON.stringify(events)).not.toMatch(/private-(?:file|body)/)
})
-it("retains email upload status and text failure without leaking its body", async () => {
- fetch.mockResolvedValue(new Response("private-upload-error", { status: 413 }))
- await expect(uploadEmailAttachment(new File(["private"], "private.txt"), "workspace-a")).rejects.toMatchObject({ status: 413, message: "private-upload-error" })
+it("retains shared upload errors without including the response body in telemetry", async () => {
+ const error = await readUploadError(Response.json({ error: "private-upload-error" }, { status: 413 }), "Upload failed")
+ expect(error.status).toBe(413)
+ expect(error.message).toBe("private-upload-error")
expect(JSON.stringify(events)).not.toContain("private-upload-error")
})
diff --git a/src/web/src/lib/api/tasks.ts b/src/web/src/lib/api/tasks.ts
deleted file mode 100644
index 2a6383b1f..000000000
--- a/src/web/src/lib/api/tasks.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { TaskApi, TaskMessageResponse } from "@alook/shared";
-import type { ApiRequestOptions } from "./client";
-import { apiFetch, wsQuery } from "./client";
-
-export const getTask = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<TaskApi>(`/api/tasks/${id}${wsQuery(workspaceId)}`, options);
-
-export const getTaskMessages = (id: string, workspaceId: string, since?: number, options?: ApiRequestOptions) =>
- apiFetch<TaskMessageResponse[]>(
- `/api/tasks/${id}/messages${wsQuery(workspaceId, since ? { since: String(since) } : undefined)}`, options,
- );
-
-export const retryTask = (id: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<TaskApi>(`/api/tasks/${id}/retry${wsQuery(workspaceId)}`, {
- ...options,
- method: "POST",
- });
diff --git a/src/web/src/lib/api/traces.ts b/src/web/src/lib/api/traces.ts
deleted file mode 100644
index 364a084c5..000000000
--- a/src/web/src/lib/api/traces.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { apiFetch, wsQuery, type ApiRequestOptions } from "./client";
-
-export interface TraceListItem {
- trace_id: string;
- root_prompt: string;
- root_agent_id: string;
- root_agent: { name: string; avatarUrl: string | null } | null;
- helper_agents: { id: string; name?: string; avatarUrl?: string | null }[];
- status: string;
- task_count: number;
- started_at: string;
- completed_at: string | null;
- channel: string;
-}
-
-export interface TraceTask {
- id: string;
- agent_id: string;
- agent: { name: string; email_handle: string | null; avatarUrl: string | null } | null;
- parent_task_id: string | null;
- prompt: string;
- status: string;
- type: string;
- conversation_id: string;
- created_at: string;
- completed_at: string | null;
-}
-
-export const listTraces = (
- workspaceId: string,
- opts?: { status?: string; limit?: number; before?: string; multiAgent?: boolean; agentId?: string; channel?: string },
- options?: ApiRequestOptions,
-) => {
- const extra: Record<string, string> = {};
- if (opts?.limit) extra.limit = String(opts.limit);
- if (opts?.before) extra.before = opts.before;
- if (opts?.status) extra.status = opts.status;
- if (opts?.multiAgent) extra.multiAgent = "true";
- if (opts?.agentId) extra.agentId = opts.agentId;
- if (opts?.channel) extra.channel = opts.channel;
- return apiFetch<{ traces: TraceListItem[]; has_more: boolean }>(
- `/api/traces${wsQuery(workspaceId, extra)}`, options,
- );
-};
-
-export const getTrace = (traceId: string, workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ trace_id: string; channel: string; tasks: TraceTask[] }>(
- `/api/traces/${traceId}${wsQuery(workspaceId)}`, options,
- );
diff --git a/src/web/src/lib/api/workspaces.ts b/src/web/src/lib/api/workspaces.ts
deleted file mode 100644
index fc7f978b3..000000000
--- a/src/web/src/lib/api/workspaces.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import type { Workspace } from "@alook/shared";
-import { apiFetch,wsQuery,type ApiRequestOptions } from "./client";
-
-export const listWorkspaces = (options?: ApiRequestOptions) => apiFetch<Workspace[]>("/api/workspaces", options);
-
-export const updateWorkspace = (workspaceId: string, data: { name?: string; slug?: string }, options?: ApiRequestOptions) =>
- apiFetch<Workspace>(`/api/workspaces/${workspaceId}${wsQuery(workspaceId)}`, { ...options, method: "PATCH", body: JSON.stringify(data) });
-
-export const deleteWorkspace = (workspaceId: string, confirmName: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/workspaces/${workspaceId}${wsQuery(workspaceId)}`, { ...options, method: "DELETE", body: JSON.stringify({ confirm_name: confirmName }) });
-
-// Members
-export interface MemberEntry {
- id: string; user_id: string; role: string; name: string; email: string; image: string | null; created_at: string;
-}
-
-export const listMembers = (workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<MemberEntry[]>(`/api/workspaces/${workspaceId}/members${wsQuery(workspaceId)}`, options);
-
-export const removeMember = (workspaceId: string, memberId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/workspaces/${workspaceId}/members/${memberId}${wsQuery(workspaceId)}`, { ...options, method: "DELETE" });
-
-export const getMemberMe = (workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<{ global_instruction: string }>(`/api/members/me${wsQuery(workspaceId)}`, options);
-
-export const updateMemberMe = (workspaceId: string, globalInstruction: string, options?: ApiRequestOptions) =>
- apiFetch<{ global_instruction: string }>(`/api/members/me${wsQuery(workspaceId)}`, {
- ...options,
- method: "PATCH",
- body: JSON.stringify({ global_instruction: globalInstruction }),
- });
-
-// Invites
-export interface InviteEntry {
- id: string; token: string; expires_at: string; created_at: string;
-}
-
-export const listInvites = (workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<InviteEntry[]>(`/api/workspaces/${workspaceId}/invites${wsQuery(workspaceId)}`, options);
-
-export const createInvite = (workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<InviteEntry>(`/api/workspaces/${workspaceId}/invites${wsQuery(workspaceId)}`, { ...options, method: "POST" });
-
-export const revokeInvite = (workspaceId: string, inviteId: string, options?: ApiRequestOptions) =>
- apiFetch<void>(`/api/workspaces/${workspaceId}/invites/${inviteId}${wsQuery(workspaceId)}`, { ...options, method: "DELETE" });
-
-// Invite accept
-export interface InviteInfo {
- workspace_name: string; workspace_id: string; invited_by: string;
-}
-
-export interface InviteAcceptResult {
- workspace_id: string; workspace_slug: string;
-}
-
-export const getInviteInfo = (token: string, options?: ApiRequestOptions) => apiFetch<InviteInfo>(`/api/invite/${token}`, options);
-export const acceptInvite = (token: string, options?: ApiRequestOptions) => apiFetch<InviteAcceptResult>(`/api/invite/${token}`, { ...options, method: "POST" });
-
-// Overview
-interface OverviewEmailAccount {
- id: string;
- agent_id: string;
- email_address: string;
- status: string;
- error_message: string;
- last_synced_at: string | null;
-}
-
-interface OverviewRecentTask {
- id: string;
- agent_id: string;
- type: string;
- status: string;
- prompt: string;
- created_at: string;
- completed_at: string | null;
- error: string | null;
-}
-
-interface OverviewCalendarEvent {
- id: string;
- agent_id: string;
- title: string;
- description: string | null;
- scheduled_at: string;
- repeat_interval: string | null;
- repeat_stop_at: string | null;
- last_triggered_at: string | null;
-}
-
-interface OverviewMember {
- id: string;
- user_id: string;
- role: string;
- name: string;
- email: string;
- image: string | null;
- created_at: string;
-}
-
-export interface WorkspaceOverview {
- email_stats: { inbound: number; outbound: number; unread: number; rejected: number };
- email_accounts: OverviewEmailAccount[];
- task_stats: { completed: number; failed: number; cancelled: number; queued: number; stale: number };
- recent_tasks: OverviewRecentTask[];
- conversation_counts: Record<string, number>;
- members: OverviewMember[];
- pending_invites: number;
- calendar_events: OverviewCalendarEvent[];
-}
-
-export const getWorkspaceOverview = (workspaceId: string, options?: ApiRequestOptions) =>
- apiFetch<WorkspaceOverview>(`/api/workspaces/${workspaceId}/overview${wsQuery(workspaceId)}`, options);
diff --git a/src/web/src/lib/application-owner.anonymous.dom.test.tsx b/src/web/src/lib/application-owner.anonymous.dom.test.tsx
new file mode 100644
index 000000000..1854b7e10
--- /dev/null
+++ b/src/web/src/lib/application-owner.anonymous.dom.test.tsx
@@ -0,0 +1,138 @@
+import "fake-indexeddb/auto"
+import { createContext, useContext, useLayoutEffect } from "react"
+import { afterEach, beforeEach, expect, it, vi } from "vitest"
+import { act, render, waitFor } from "@/test/react-dom-harness"
+import { InviteAcceptClient } from "@/app/c/invite/[token]/invite-accept-client"
+import { PublicQueryProvider, useApplicationOwner, type ApplicationOwner } from "./application-owner"
+import { CACHE_INVALIDATION_STORAGE_KEY, clearAllPersistedCaches, createIdbPersister } from "./query-persister"
+import { tid } from "@/lib/community/testids"
+
+type Identity = { data: { user: { id: string } } | null; isPending: boolean; error: Error | null }
+const identityInput = createContext<Identity>({ data: null, isPending: true, error: null })
+let viewer: string | null | undefined
+vi.mock("@/lib/auth-client", () => ({ useSession: () => useContext(identityInput), currentSessionViewer: () => viewer }))
+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }), useSearchParams: () => new URLSearchParams() }))
+
+const guest: Identity = { data: null, isPending: false, error: null }
+const pending: Identity = { data: null, isPending: true, error: null }
+const known = (id: string): Identity => ({ data: { user: { id } }, isPending: false, error: null })
+let owner: ApplicationOwner
+let reload: ReturnType<typeof vi.fn>
+let mounted: ReturnType<typeof render> | undefined
+const owners = new Set<ApplicationOwner>()
+
+function Probe() {
+ const current = useApplicationOwner()
+ useLayoutEffect(() => { owner = current; owners.add(current) })
+ return <output>{current.userId}</output>
+}
+function Root({ identity, invite = false }: { identity: Identity; invite?: boolean }) {
+ return <identityInput.Provider value={identity}>
+ <PublicQueryProvider><Probe /></PublicQueryProvider>
+ {invite && <InviteAcceptClient token="not-a-real-token" />}
+ </identityInput.Provider>
+}
+
+beforeEach(async () => {
+ await act(async () => { await clearAllPersistedCaches() })
+ viewer = undefined
+ reload = vi.fn()
+ const real = window
+ vi.stubGlobal("window", new Proxy(real, { get(target, key) { return key === "location" ? { origin: "https://alook.test", reload } : Reflect.get(target, key, target) } }))
+ vi.stubGlobal("fetch", vi.fn(async (url: string) => {
+ expect(url).toBe("/api/community/invites/not-a-real-token/info")
+ return Response.json({ error: "Invite not found" }, { status: 404 })
+ }))
+})
+afterEach(async () => {
+ await act(async () => {
+ mounted?.unmount(); mounted = undefined
+ for (const current of owners) current.queryClient.clear()
+ owners.clear()
+ })
+ vi.unstubAllGlobals()
+})
+
+it("settles a cold pending public invitation as guest without retiring shared anonymous leases on transition or unmount", async () => {
+ mounted = render(<Root identity={pending} invite />)
+ await waitFor(() => expect(owner.userId).toBe("__pending__"))
+ const originalOwner = owner
+ const anonymous = createIdbPersister(null)
+ await act(async () => { await anonymous.restoreClient() })
+
+ viewer = null
+ await act(async () => mounted!.rerender(<Root identity={guest} invite />))
+ await waitFor(() => expect(owner.userId).toBe("__guest__"))
+ await waitFor(() => expect(mounted!.getByTestId(tid.inviteExpiredTitle)).toHaveTextContent("This invite has expired"))
+ await act(async () => {
+ window.dispatchEvent(new StorageEvent("storage", { key: CACHE_INVALIDATION_STORAGE_KEY }))
+ window.dispatchEvent(new Event("pageshow"))
+ window.dispatchEvent(new Event("focus"))
+ document.dispatchEvent(new Event("visibilitychange"))
+ expect(await anonymous.isCurrent()).toBe(true)
+ })
+ expect(originalOwner.lifecycle.get().active).toBe(false)
+ expect(owner.lifecycle.get().active).toBe(true)
+ expect(reload).not.toHaveBeenCalled()
+ await act(async () => { mounted!.unmount(); mounted = undefined })
+ expect(await anonymous.isCurrent()).toBe(true)
+ expect(reload).not.toHaveBeenCalled()
+})
+
+it("guest to confirmed account leaves the shared anonymous lease current", async () => {
+ viewer = null
+ mounted = render(<Root identity={guest} />)
+ await waitFor(() => expect(owner.userId).toBe("__guest__"))
+ const anonymous = createIdbPersister(null)
+ await act(async () => { await anonymous.restoreClient() })
+ viewer = "A"
+ await act(async () => mounted!.rerender(<Root identity={known("A")} />))
+ expect(owner.userId).toBe("A")
+ expect(owner.lifecycle.get().active).toBe(true)
+ expect(await anonymous.isCurrent()).toBe(true)
+ expect(reload).not.toHaveBeenCalled()
+})
+
+it("ordinary guest unmount preserves another active anonymous owner", async () => {
+ viewer = null
+ const survivor = render(<Root identity={guest} />)
+ const survivingOwner = owner
+ try {
+ mounted = render(<Root identity={guest} />)
+ const anonymous = createIdbPersister(null)
+ await act(async () => { await anonymous.restoreClient() })
+ await act(async () => { mounted!.unmount(); mounted = undefined })
+ await act(async () => {
+ window.dispatchEvent(new Event("focus"))
+ expect(await anonymous.isCurrent()).toBe(true)
+ })
+ expect(survivingOwner.lifecycle.get().active).toBe(true)
+ expect(reload).not.toHaveBeenCalled()
+ } finally { await act(async () => survivor.unmount()) }
+})
+
+it("confirmed account to guest still retires the original real account without retiring anonymous leases", async () => {
+ viewer = "A"
+ mounted = render(<Root identity={known("A")} />)
+ await waitFor(() => expect(owner.userId).toBe("A"))
+ const account = createIdbPersister("A"), anonymous = createIdbPersister(null)
+ await act(async () => { await account.restoreClient(); await anonymous.restoreClient() })
+ viewer = null
+ await act(async () => mounted!.rerender(<Root identity={guest} />))
+ await waitFor(async () => expect(await account.isCurrent()).toBe(false))
+ expect(owner.userId).toBe("__guest__")
+ expect(owner.lifecycle.get().active).toBe(true)
+ expect(await anonymous.isCurrent()).toBe(true)
+ expect(reload).not.toHaveBeenCalled()
+})
+
+it("explicit device clearing still retires a mounted anonymous owner", async () => {
+ viewer = null
+ mounted = render(<Root identity={guest} />)
+ await waitFor(() => expect(owner.userId).toBe("__guest__"))
+ const anonymous = createIdbPersister(null)
+ await act(async () => { await anonymous.restoreClient(); await clearAllPersistedCaches() })
+ await waitFor(() => expect(owner.lifecycle.get().active).toBe(false))
+ expect(await anonymous.isCurrent()).toBe(false)
+ expect(reload).toHaveBeenCalledOnce()
+})
diff --git a/src/web/src/lib/application-owner.tsx b/src/web/src/lib/application-owner.tsx
index dd85f8d4e..230192e19 100644
--- a/src/web/src/lib/application-owner.tsx
+++ b/src/web/src/lib/application-owner.tsx
@@ -1,26 +1,20 @@
"use client"
import { UnauthorizedError } from "@/lib/errors"
-import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"
-import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"
+import { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from "react"
import { QueryClientProvider } from "@tanstack/react-query"
-import { clearPersistedCache, createIdbPersister, PERSIST_BUSTER, PERSIST_MAX_AGE_MS } from "@/lib/query-persister"
+import { clearPersistedCache, createIdbPersister } from "@/lib/query-persister"
import { usePersistedAccountLifecycle } from "@/lib/use-persisted-account-lifecycle"
-import { shouldPersistApplicationQuery } from "@/lib/workspace-chat-persistence"
-import { createStore, createStoreContext, useSelector } from "@tanstack/react-store"
-import { useRouter } from "next/navigation"
+import { createStore, createStoreContext } from "@tanstack/react-store"
import { useSession, currentSessionViewer } from "@/lib/auth-client"
-import { DEFAULT_INBOX_TYPES, readStoredInboxFilterTypes } from "@/lib/inbox-filter"
import { createQueryClient } from "@/lib/query-client"
-import { getNotificationEnabled, getNotificationEvents, NOTIFICATION_EVENTS, type NotificationEvent } from "@/lib/browser-notification"
import type { ApiRequestOptions } from "@/lib/api/client"
-import { observeHydration, discardHydration } from "@/lib/observability/restore"
-import { disposeQueryDiagnostics } from "@/lib/observability/query-observer"
import { captureTelemetryIdentityRetirement, setTelemetryUser } from "@/lib/observability/client"
+import { disposeQueryDiagnostics } from "@/lib/observability/query-observer"
export function createApplicationOwner(userId: string, queryClient = createQueryClient()) {
const bindings = createStore({ retireDisk: () => clearPersistedCache(userId), sessionViewer: () => userId as string | null | undefined })
- return { userId, queryClient, retireDisk: () => bindings.get().retireDisk(), sessionViewer: () => bindings.get().sessionViewer(), bindAuthentication: (sessionViewer: () => string | null | undefined, retireDisk: () => Promise<void>) => bindings.setState(() => ({ sessionViewer, retireDisk })), lifecycle: createStore({ active: true, generation: 0 }), preferences: createStore({ inboxFilterTypes: [...DEFAULT_INBOX_TYPES], hydrated: false, lastWorkspaceSlug: null as string | null, localValues: new Map<string, unknown>(), browserNotifications: { enabled: false, events: [...NOTIFICATION_EVENTS] as NotificationEvent[] } }) }
+ return { userId, queryClient, retireDisk: () => bindings.get().retireDisk(), sessionViewer: () => bindings.get().sessionViewer(), bindAuthentication: (sessionViewer: () => string | null | undefined, retireDisk: () => Promise<void>) => bindings.setState(() => ({ sessionViewer, retireDisk })), lifecycle: createStore({ active: true, generation: 0 }) }
}
export type ApplicationOwner = ReturnType<typeof createApplicationOwner>
const { StoreProvider, useStoreContext } = createStoreContext<{ owner: ApplicationOwner }>()
@@ -57,89 +51,49 @@ export async function runApplicationRequest<T>(
}
}
-export function ApplicationQueryProvider(props: { userId: string; children: ReactNode }) {
- const session = useSession()
- return <ScopedApplicationQueryProvider key={props.userId} {...props} session={session} sessionViewer={currentSessionViewer} />
-}
-
export function PublicQueryProvider({ children }: { children: ReactNode }) {
const session = useSession()
- const userId = session.isPending ? "__pending__" : session.data?.user.id ?? "__guest__"
+ const viewer = !session.isPending && !session.error ? session.data?.user.id ?? "__guest__" : undefined
+ const [confirmed, setConfirmed] = useState(viewer ?? "__pending__")
+ if (viewer !== undefined && viewer !== confirmed) setConfirmed(viewer)
+ const userId = viewer ?? confirmed
return <ScopedPublicQueryProvider key={userId} userId={userId}>{children}</ScopedPublicQueryProvider>
}
function ScopedPublicQueryProvider({ userId, children }: { userId: string; children: ReactNode }) {
+ const accountId = userId === "__pending__" || userId === "__guest__" ? null : userId
const [owner] = useState(() => createApplicationOwner(userId))
+ const [persister] = useState(() => createIdbPersister(accountId))
+ useLayoutEffect(() => { owner.bindAuthentication(currentSessionViewer, persister.retireAccount) }, [owner, persister])
+ const onRetired = useCallback(() => {
+ if (!owner.lifecycle.get().active) return
+ retireApplicationOwner(owner)
+ owner.queryClient.clear()
+ window.location.reload()
+ }, [owner])
+ usePersistedAccountLifecycle(persister, onRetired)
+ const retireTelemetryIdentity = useRef<() => void>(() => undefined)
+ useLayoutEffect(() => {
+ if (userId === "__pending__" || userId === "__guest__") return
+ setTelemetryUser(userId)
+ retireTelemetryIdentity.current = captureTelemetryIdentityRetirement()
+ }, [userId])
const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
useLayoutEffect(() => {
if (disposeTimer.current !== null) { clearTimeout(disposeTimer.current); disposeTimer.current = null }
owner.lifecycle.setState((state) => ({ ...state, active: true }))
return () => {
retireApplicationOwner(owner)
+ const viewer = owner.sessionViewer()
+ if (viewer === null) retireTelemetryIdentity.current()
+ if (accountId !== null && viewer !== undefined && viewer !== accountId) void owner.retireDisk().catch(() => undefined)
disposeTimer.current = setTimeout(() => owner.queryClient.clear(), 0)
}
- }, [owner])
+ }, [accountId, owner])
return <StoreProvider value={{ owner }}><QueryClientProvider client={owner.queryClient}>{children}</QueryClientProvider></StoreProvider>
}
-function ScopedApplicationQueryProvider({ userId, children, session, sessionViewer }: { userId: string; children: ReactNode; session: ReturnType<typeof useSession>; sessionViewer: () => string | null | undefined }) {
- const [owner] = useState(() => createApplicationOwner(userId))
- const [handles] = useState(() => ({ owner }))
- const [persister] = useState(() => createIdbPersister(userId, "application"))
- const retireTelemetryIdentity = useRef<() => void>(() => undefined)
- useLayoutEffect(() => { setTelemetryUser(userId); retireTelemetryIdentity.current = captureTelemetryIdentityRetirement() }, [userId])
- const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
- useEffect(() => {
- const hydrate = () => {
- const inboxFilterTypes = readStoredInboxFilterTypes(userId)
- let lastWorkspaceSlug: string | null = null
- try { lastWorkspaceSlug = localStorage.getItem(`alook:${userId}:lastWorkspace`) } catch {}
- owner.preferences.setState((state) => ({ ...state, inboxFilterTypes, lastWorkspaceSlug, hydrated: true, browserNotifications: { enabled: getNotificationEnabled(userId), events: getNotificationEvents(userId) } }))
- }
- hydrate()
- const onStorage = (event: StorageEvent) => {
- if (event.key === `alook:${userId}:inbox-filter-types` || event.key === `alook:${userId}:lastWorkspace` || event.key === `alook:${userId}:browser-notification-enabled` || event.key === `alook:${userId}:browser-notification-events` || event.key === null) hydrate()
- }
- window.addEventListener("storage", onStorage)
- return () => window.removeEventListener("storage", onStorage)
- }, [owner, userId])
- const active = useSelector(owner.lifecycle, (state) => state.active)
- useLayoutEffect(() => { owner.bindAuthentication(sessionViewer, persister.retireAccount) }, [owner, sessionViewer, persister])
- const onRetired = useCallback(() => { if (!owner.lifecycle.get().active) return; retireApplicationOwner(owner); owner.queryClient.clear(); window.location.reload() }, [owner])
- usePersistedAccountLifecycle(persister, onRetired)
- const router = useRouter()
- const identityChanged = !session.isPending && !session.error && session.data?.user.id !== userId
- useLayoutEffect(() => {
- if (disposeTimer.current !== null) { clearTimeout(disposeTimer.current); disposeTimer.current = null }
- owner.lifecycle.setState((state) => state.active ? state : { ...state, active: true })
- return () => {
- owner.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
- void owner.queryClient.cancelQueries()
- const viewer = owner.sessionViewer()
- if (viewer !== undefined && viewer !== owner.userId) void owner.retireDisk().catch(() => undefined)
- disposeTimer.current = setTimeout(() => { disposeTimer.current = null; owner.queryClient.clear() }, 0)
- }
- }, [owner])
- useLayoutEffect(() => {
- if (!identityChanged) return
- if (!session.data?.user.id && sessionViewer?.() === null) retireTelemetryIdentity.current()
- if (!owner.lifecycle.get().active) return
- retireApplicationOwner(owner)
- void owner.queryClient.cancelQueries()
- owner.queryClient.clear()
- void owner.retireDisk().catch(() => undefined)
- if (!session.data?.user.id) router.replace("/sign-in")
- else router.refresh()
- }, [identityChanged, owner, router, session.data?.user.id, sessionViewer])
- return <StoreProvider value={handles}>
- <PersistQueryClientProvider client={owner.queryClient} onSuccess={() => { if (!owner.lifecycle.get().active) { discardHydration(persister); owner.queryClient.clear(); return } observeHydration(persister, owner.queryClient) }} persistOptions={{ persister, buster: `${PERSIST_BUSTER}-application`, maxAge: PERSIST_MAX_AGE_MS, dehydrateOptions: { shouldDehydrateQuery: (query) => query.state.status === "success" && shouldPersistApplicationQuery(query.queryKey), shouldDehydrateMutation: () => false } }}>
- {active && !identityChanged ? children : null}
- </PersistQueryClientProvider>
- </StoreProvider>
-}
-
export function retireApplicationOwner(owner: ApplicationOwner) {
disposeQueryDiagnostics(owner.queryClient)
- owner.preferences.setState((state) => ({ ...state, localValues: new Map() }))
owner.lifecycle.setState((state) => state.active ? { active: false, generation: state.generation + 1 } : state)
void owner.queryClient.cancelQueries()
}
diff --git a/src/web/src/lib/browser-notification.ts b/src/web/src/lib/browser-notification.ts
deleted file mode 100644
index 1c06665a2..000000000
--- a/src/web/src/lib/browser-notification.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-const STORAGE_KEY = "browser-notification-enabled";
-const EVENTS_KEY = "browser-notification-events";
-
-export const NOTIFICATION_EVENTS = ["completed", "failed"] as const;
-export type NotificationEvent = (typeof NOTIFICATION_EVENTS)[number];
-
-export const NOTIFICATION_EVENT_LABELS: Record<NotificationEvent, string> = {
- completed: "Task Completed",
- failed: "Task Failed",
-};
-
-export function isNotificationSupported(): boolean {
- return typeof window !== "undefined" && "Notification" in window;
-}
-
-const accountKey = (key: string, accountId?: string) => accountId ? `alook:${accountId}:${key}` : key;
-
-export function getNotificationEnabled(accountId?: string): boolean {
- if (typeof window === "undefined") return false;
- try { return localStorage.getItem(accountKey(STORAGE_KEY, accountId)) === "true"; } catch { return false; }
-}
-
-export function setNotificationEnabled(enabled: boolean, accountId?: string): void {
- localStorage.setItem(accountKey(STORAGE_KEY, accountId), String(enabled));
-}
-
-export function getNotificationEvents(accountId?: string): NotificationEvent[] {
- if (typeof window === "undefined") return [...NOTIFICATION_EVENTS];
- try {
- const raw = localStorage.getItem(accountKey(EVENTS_KEY, accountId));
- if (raw) {
- const parsed: unknown = JSON.parse(raw);
- if (Array.isArray(parsed)) return [...new Set(parsed.filter((event): event is NotificationEvent => NOTIFICATION_EVENTS.includes(event)))];
- }
- } catch {}
- return [...NOTIFICATION_EVENTS];
-}
-
-export function setNotificationEvents(events: NotificationEvent[], accountId?: string): void {
- localStorage.setItem(accountKey(EVENTS_KEY, accountId), JSON.stringify(events));
-}
-
-export async function requestNotificationPermission(): Promise<boolean> {
- if (!isNotificationSupported()) return false;
- if (Notification.permission === "granted") return true;
- if (Notification.permission === "denied") return false;
- const result = await Notification.requestPermission();
- return result === "granted";
-}
-
-export function sendTaskNotification(
- status: string,
- agentName?: string,
- body?: string,
- preferences?: { enabled: boolean; events: readonly NotificationEvent[] },
-): void {
- if (typeof window === "undefined") return;
- if (!isNotificationSupported()) return;
- if (Notification.permission !== "granted") return;
- if (!(preferences?.enabled ?? getNotificationEnabled())) return;
-
- const events = preferences?.events ?? getNotificationEvents();
- if (!events.includes(status as NotificationEvent)) return;
-
- const label = NOTIFICATION_EVENT_LABELS[status as NotificationEvent] ?? `Task ${status}`;
- const title = agentName ? `${agentName} — ${label}` : label;
- new Notification(title, {
- body: body ?? "",
- icon: "/alook.svg",
- });
-}
diff --git a/src/web/src/lib/chat-cache.test.ts b/src/web/src/lib/chat-cache.test.ts
deleted file mode 100644
index 10acac8cf..000000000
--- a/src/web/src/lib/chat-cache.test.ts
+++ /dev/null
@@ -1,575 +0,0 @@
-import { describe, it, expect, beforeEach } from "vitest";
-import "fake-indexeddb/auto";
-import { openDB } from "idb";
-import { createApplicationOwner } from "./application-owner";
-import { createWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context";
-import { clearAllPersistedCaches } from "./query-persister";
-import type { Message } from "@alook/shared";
-import {
- getCachedMessages,
- getCachedMessagesBefore,
- mergeCachedMessages,
- appendCachedMessage,
- removeCachedMessage,
- getCacheMeta,
- invalidateCache,
- clearAllCache,
- getLastOpenConversation,
- setLastOpenConversation,
- clearLastOpenForConversation,
- getConvExtras,
- setConvExtras,
- clearConvExtras,
-} from "./chat-cache";
-import type { Artifact } from "@alook/shared";
-
-const WORKSPACE_ID = "ws_test";
-
-function makeArtifact(overrides: Partial<Artifact> = {}): Artifact {
- return {
- id: `art_${Math.random().toString(36).slice(2)}`,
- conversation_id: "conv_1",
- agent_id: "agent_a",
- filename: "report.pdf",
- content_type: "application/pdf",
- size: 1024,
- source: "agent",
- has_thumbnail: false,
- created_at: new Date().toISOString(),
- ...overrides,
- };
-}
-
-function makeExtras(
- overrides: Partial<Parameters<typeof setConvExtras>[1]> = {},
-): Parameters<typeof setConvExtras>[1] {
- return {
- artifacts: [makeArtifact()],
- conversation_type: "agent_chat",
- conversation_title: "My chat",
- conversation_channel: "general",
- conversation_created_at: "2024-01-01T00:00:00Z",
- hasMoreArtifacts: false,
- ...overrides,
- };
-}
-
-function makeMessage(overrides: Partial<Message> = {}): Message {
- return {
- id: `msg_${Math.random().toString(36).slice(2)}`,
- conversation_id: "conv_1",
- role: "user",
- content: "hello",
- task_id: null,
- attachment_ids: null,
- created_at: new Date().toISOString(),
- ...overrides,
- };
-}
-
-let cacheOwner: WorkspaceOwner;
-beforeEach(async () => {
- await clearAllPersistedCaches();
- cacheOwner = createWorkspaceOwner(createApplicationOwner("cache-user"), WORKSPACE_ID, "test");
-});
-
-describe("chat-cache", () => {
- it("never reads an unqualified legacy workspace database", async () => {
- const legacy = await openDB(`alook-chat-cache-${WORKSPACE_ID}`, 4, { upgrade(db) { if (!db.objectStoreNames.contains("messages")) db.createObjectStore("messages", { keyPath: ["conversation_id", "id"] }); } });
- await legacy.put("messages", makeMessage({ id: "private", conversation_id: "legacy" }));
- expect(await getCachedMessages("legacy", cacheOwner)).toBeNull();
- legacy.close();
- });
- it("isolates identical workspace/conversation IDs across viewers and workspaces", async () => {
- await mergeCachedMessages("conv_1", [makeMessage({ id: "private" })], false, cacheOwner);
- const otherViewer = createWorkspaceOwner(createApplicationOwner("other"), WORKSPACE_ID, "test");
- const otherWorkspace = createWorkspaceOwner(cacheOwner.application, "different", "different");
- expect(await getCachedMessages("conv_1", otherViewer)).toBeNull();
- expect(await getCachedMessages("conv_1", otherWorkspace)).toBeNull();
- });
- it("rejects reads and writes from a retired original workspace", async () => {
- cacheOwner.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }));
- await expect(getCachedMessages("conv_1", cacheOwner)).rejects.toMatchObject({ name: "AbortError" });
- await expect(mergeCachedMessages("conv_1", [makeMessage()], false, cacheOwner)).rejects.toMatchObject({ name: "AbortError" });
- });
-
-
- describe("mergeCachedMessages", () => {
- it("writes messages and updates meta", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- ];
-
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toHaveLength(2);
- expect(cached![0].id).toBe("m1");
- expect(cached![1].id).toBe("m2");
-
- const meta = await getCacheMeta("conv_1", cacheOwner);
- expect(meta).not.toBeNull();
- expect(meta!.messageCount).toBeGreaterThanOrEqual(2);
- expect(meta!.hasMore).toBe(false);
- });
-
- it("merges without overwriting older messages", async () => {
- const older = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- ];
- await mergeCachedMessages("conv_1", older, true, cacheOwner);
-
- const newer = [
- makeMessage({ id: "m3", conversation_id: "conv_1", created_at: "2024-01-01T00:02:00Z" }),
- ];
- await mergeCachedMessages("conv_1", newer, false, cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toHaveLength(3);
- expect(cached!.map((m) => m.id)).toEqual(["m1", "m2", "m3"]);
- });
-
- it("does not regress newestMessageId when merging older messages", async () => {
- const newer = [
- makeMessage({ id: "m3", conversation_id: "conv_1", created_at: "2024-01-01T00:02:00Z" }),
- makeMessage({ id: "m4", conversation_id: "conv_1", created_at: "2024-01-01T00:03:00Z" }),
- ];
- await mergeCachedMessages("conv_1", newer, true, cacheOwner);
-
- const metaBefore = await getCacheMeta("conv_1", cacheOwner);
- expect(metaBefore!.newestMessageId).toBe("m4");
-
- const older = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- ];
- await mergeCachedMessages("conv_1", older, null, cacheOwner);
-
- const metaAfter = await getCacheMeta("conv_1", cacheOwner);
- expect(metaAfter!.newestMessageId).toBe("m4");
- expect(metaAfter!.messageCount).toBe(4);
- });
-
- it("filters out temp- messages", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1" }),
- makeMessage({ id: "temp-123", conversation_id: "conv_1" }),
- ];
-
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toHaveLength(1);
- expect(cached![0].id).toBe("m1");
- });
- });
-
- describe("getCachedMessages", () => {
- it("returns sorted messages for a conversation", async () => {
- const msgs = [
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached![0].id).toBe("m1");
- expect(cached![1].id).toBe("m2");
- });
-
- it("returns null for unknown conversation", async () => {
- const cached = await getCachedMessages("nonexistent", cacheOwner);
- expect(cached).toBeNull();
- });
-
- });
-
- describe("appendCachedMessage", () => {
- it("adds single message without overwriting existing", async () => {
- const initial = [makeMessage({ id: "m1", conversation_id: "conv_1" })];
- await mergeCachedMessages("conv_1", initial, false, cacheOwner);
-
- await appendCachedMessage("conv_1", makeMessage({ id: "m2", conversation_id: "conv_1" }), cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toHaveLength(2);
- });
-
- it("skips temp- messages", async () => {
- const initial = [makeMessage({ id: "m1", conversation_id: "conv_1" })];
- await mergeCachedMessages("conv_1", initial, false, cacheOwner);
-
- await appendCachedMessage("conv_1", makeMessage({ id: "temp-abc", conversation_id: "conv_1" }), cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toHaveLength(1);
- });
- });
-
- describe("removeCachedMessage", () => {
- it("removes a single message by ID", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1" }),
- makeMessage({ id: "m2", conversation_id: "conv_1" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- await removeCachedMessage("conv_1", "m1", cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toHaveLength(1);
- expect(cached![0].id).toBe("m2");
- });
- });
-
- describe("invalidateCache", () => {
- it("removes all data for a conversation", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1" }),
- makeMessage({ id: "m2", conversation_id: "conv_1" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- await invalidateCache("conv_1", cacheOwner);
-
- const cached = await getCachedMessages("conv_1", cacheOwner);
- expect(cached).toBeNull();
- const meta = await getCacheMeta("conv_1", cacheOwner);
- expect(meta).toBeNull();
- });
-
- it("clears any last_open pointer referencing the invalidated conversation", async () => {
- await mergeCachedMessages("conv_1", [makeMessage({ id: "m1", conversation_id: "conv_1" })], false, cacheOwner);
- await setLastOpenConversation("agent_a", "chan", {
- conversation_id: "conv_1",
- newestMessageId: "m1",
- serverMessageCount: 1,
- }, cacheOwner);
-
- await invalidateCache("conv_1", cacheOwner);
-
- expect(await getLastOpenConversation("agent_a", "chan", cacheOwner)).toBeNull();
- });
- });
-
- describe("last_open pointer", () => {
- it("set then get round-trips for the same agent+channel", async () => {
- await setLastOpenConversation("agent_a", "chan_x", {
- conversation_id: "conv_1",
- newestMessageId: "m9",
- serverMessageCount: 12,
- }, cacheOwner);
-
- const entry = await getLastOpenConversation("agent_a", "chan_x", cacheOwner);
- expect(entry).not.toBeNull();
- expect(entry!.conversation_id).toBe("conv_1");
- expect(entry!.newestMessageId).toBe("m9");
- expect(entry!.serverMessageCount).toBe(12);
- });
-
- it("is scoped by channel — a different channel returns null", async () => {
- await setLastOpenConversation("agent_a", "chan_x", {
- conversation_id: "conv_1", newestMessageId: "m1", serverMessageCount: 1,
- }, cacheOwner);
-
- expect(await getLastOpenConversation("agent_a", "chan_y", cacheOwner)).toBeNull();
- expect((await getLastOpenConversation("agent_a", "chan_x", cacheOwner))?.conversation_id).toBe("conv_1");
- });
-
- it("is scoped by agent — agent A channel x and agent B channel x are independent", async () => {
- await setLastOpenConversation("agent_a", "chan_x", {
- conversation_id: "conv_a", newestMessageId: "ma", serverMessageCount: 1,
- }, cacheOwner);
- await setLastOpenConversation("agent_b", "chan_x", {
- conversation_id: "conv_b", newestMessageId: "mb", serverMessageCount: 1,
- }, cacheOwner);
-
- expect((await getLastOpenConversation("agent_a", "chan_x", cacheOwner))?.conversation_id).toBe("conv_a");
- expect((await getLastOpenConversation("agent_b", "chan_x", cacheOwner))?.conversation_id).toBe("conv_b");
- });
-
- it("null and undefined channel resolve to the same entry", async () => {
- await setLastOpenConversation("agent_a", null, {
- conversation_id: "conv_default", newestMessageId: "m1", serverMessageCount: 3,
- }, cacheOwner);
-
- const viaUndefined = await getLastOpenConversation("agent_a", undefined, cacheOwner);
- expect(viaUndefined?.conversation_id).toBe("conv_default");
-
- // Writing via undefined overwrites the same row read via null.
- await setLastOpenConversation("agent_a", undefined, {
- conversation_id: "conv_default2", newestMessageId: "m2", serverMessageCount: 4,
- }, cacheOwner);
- const viaNull = await getLastOpenConversation("agent_a", null, cacheOwner);
- expect(viaNull?.conversation_id).toBe("conv_default2");
- });
-
- it("returns null on cache miss", async () => {
- expect(await getLastOpenConversation("agent_missing", "chan", cacheOwner)).toBeNull();
- });
-
- it("clearLastOpenForConversation removes only the matching rows", async () => {
- await setLastOpenConversation("agent_a", "chan_x", {
- conversation_id: "conv_1", newestMessageId: "m1", serverMessageCount: 1,
- }, cacheOwner);
- await setLastOpenConversation("agent_b", "chan_y", {
- conversation_id: "conv_1", newestMessageId: "m1", serverMessageCount: 1,
- }, cacheOwner);
- await setLastOpenConversation("agent_c", "chan_z", {
- conversation_id: "conv_2", newestMessageId: "m2", serverMessageCount: 1,
- }, cacheOwner);
-
- await clearLastOpenForConversation("conv_1", cacheOwner);
-
- expect(await getLastOpenConversation("agent_a", "chan_x", cacheOwner)).toBeNull();
- expect(await getLastOpenConversation("agent_b", "chan_y", cacheOwner)).toBeNull();
- // Pointer to conv_2 is untouched.
- expect((await getLastOpenConversation("agent_c", "chan_z", cacheOwner))?.conversation_id).toBe("conv_2");
- });
-
- // TC8 — the WS-driven refresh (task.created) may write serverMessageCount=0
- // when there is no local cache for a brand-new conversation. The store must
- // round-trip that 0 faithfully so the slow-path read's `serverMessageCount >
- // 0` gate sees it and falls back to the skeleton (never optimistically
- // paints empty/wrong content). This asserts the storage half of that
- // invariant; the read-site gate itself lives in agent-chat-view.tsx.
- it("TC8 — round-trips serverMessageCount=0 (non-poisoning WS-path write)", async () => {
- await setLastOpenConversation("agent_ws", "chan_x", {
- conversation_id: "conv_brand_new",
- newestMessageId: null,
- serverMessageCount: 0,
- }, cacheOwner);
-
- const entry = await getLastOpenConversation("agent_ws", "chan_x", cacheOwner);
- expect(entry?.conversation_id).toBe("conv_brand_new");
- // The read site gates optimism on `serverMessageCount > 0`; a stored 0
- // therefore disables the optimistic paint for this pointer.
- expect(entry?.serverMessageCount).toBe(0);
- expect(entry!.serverMessageCount > 0).toBe(false);
- });
- });
-
- describe("conv_extras (card metadata)", () => {
- it("set then get round-trips artifacts array + conversation metadata", async () => {
- const arts = [
- makeArtifact({ id: "a1", conversation_id: "conv_1" }),
- makeArtifact({ id: "a2", conversation_id: "conv_1" }),
- ];
- await setConvExtras("conv_1", makeExtras({
- artifacts: arts,
- conversation_type: "email_notification",
- conversation_title: "Re: bug",
- conversation_channel: "inbox",
- conversation_created_at: "2024-02-02T00:00:00Z",
- hasMoreArtifacts: true,
- }), cacheOwner);
-
- const entry = await getConvExtras("conv_1", cacheOwner);
- expect(entry).not.toBeNull();
- expect(entry!.conversation_id).toBe("conv_1");
- expect(entry!.artifacts.map((a) => a.id)).toEqual(["a1", "a2"]);
- expect(entry!.conversation_type).toBe("email_notification");
- expect(entry!.conversation_title).toBe("Re: bug");
- expect(entry!.conversation_channel).toBe("inbox");
- expect(entry!.conversation_created_at).toBe("2024-02-02T00:00:00Z");
- expect(entry!.hasMoreArtifacts).toBe(true);
- // updatedAt is stamped at write time.
- expect(typeof entry!.updatedAt).toBe("number");
- });
-
- it("returns null for an unknown conversation", async () => {
- await setConvExtras("conv_1", makeExtras(), cacheOwner);
- expect(await getConvExtras("conv_other", cacheOwner)).toBeNull();
- });
-
- it("upserts — a second write replaces the row", async () => {
- await setConvExtras("conv_1", makeExtras({
- artifacts: [makeArtifact({ id: "a1" })],
- conversation_type: "agent_chat",
- }), cacheOwner);
- await setConvExtras("conv_1", makeExtras({
- artifacts: [makeArtifact({ id: "a2" }), makeArtifact({ id: "a3" })],
- conversation_type: "calendar_event",
- }), cacheOwner);
-
- const entry = await getConvExtras("conv_1", cacheOwner);
- expect(entry!.artifacts.map((a) => a.id)).toEqual(["a2", "a3"]);
- expect(entry!.conversation_type).toBe("calendar_event");
- });
-
- it("clearConvExtras removes only the target row", async () => {
- await setConvExtras("conv_1", makeExtras(), cacheOwner);
- await setConvExtras("conv_2", makeExtras(), cacheOwner);
-
- await clearConvExtras("conv_1", cacheOwner);
-
- expect(await getConvExtras("conv_1", cacheOwner)).toBeNull();
- expect(await getConvExtras("conv_2", cacheOwner)).not.toBeNull();
- });
-
- it("invalidateCache clears the conversation's conv_extras row", async () => {
- await mergeCachedMessages("conv_1", [makeMessage({ id: "m1", conversation_id: "conv_1" })], false, cacheOwner);
- await setConvExtras("conv_1", makeExtras(), cacheOwner);
-
- await invalidateCache("conv_1", cacheOwner);
-
- expect(await getConvExtras("conv_1", cacheOwner)).toBeNull();
- });
-
- it("clearAllCache removes conv_extras", async () => {
- await setConvExtras("conv_1", makeExtras(), cacheOwner);
- await clearAllCache(cacheOwner.application);
- expect(await getConvExtras("conv_1", cacheOwner)).toBeNull();
- });
- });
-
- describe("getCachedMessagesBefore", () => {
- it("returns older messages from cache correctly", async () => {
- const msgs = Array.from({ length: 10 }, (_, i) =>
- makeMessage({
- id: `m${i + 1}`,
- conversation_id: "conv_1",
- created_at: `2024-01-01T00:0${i}:00Z`,
- })
- );
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const result = await getCachedMessagesBefore("conv_1", "2024-01-01T00:06:00Z", "m7", 10, cacheOwner);
- expect(result).not.toBeNull();
- expect(result!.messages.map((m) => m.id)).toEqual(["m1", "m2", "m3", "m4", "m5", "m6"]);
- });
-
- it("respects limit parameter", async () => {
- const msgs = Array.from({ length: 20 }, (_, i) =>
- makeMessage({
- id: `m${String(i + 1).padStart(2, "0")}`,
- conversation_id: "conv_1",
- created_at: `2024-01-01T00:${String(i).padStart(2, "0")}:00Z`,
- })
- );
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const result = await getCachedMessagesBefore("conv_1", "2024-01-01T00:19:00Z", "m20", 5, cacheOwner);
- expect(result).not.toBeNull();
- expect(result!.messages).toHaveLength(5);
- expect(result!.messages.map((m) => m.id)).toEqual(["m15", "m16", "m17", "m18", "m19"]);
- expect(result!.hasMore).toBe(true);
- });
-
- it("hasMore is false when results exactly equal limit and meta.hasMore=false", async () => {
- const msgs = Array.from({ length: 6 }, (_, i) =>
- makeMessage({
- id: `m${i + 1}`,
- conversation_id: "conv_1",
- created_at: `2024-01-01T00:0${i}:00Z`,
- })
- );
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const result = await getCachedMessagesBefore("conv_1", "2024-01-01T00:05:00Z", "m6", 5, cacheOwner);
- expect(result).not.toBeNull();
- expect(result!.messages).toHaveLength(5);
- expect(result!.hasMore).toBe(false);
- });
-
- it("returns null when cache is incomplete (hasMore=true and fewer results than limit)", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- makeMessage({ id: "m3", conversation_id: "conv_1", created_at: "2024-01-01T00:02:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, true, cacheOwner);
-
- const result = await getCachedMessagesBefore("conv_1", "2024-01-01T00:02:00Z", "m3", 10, cacheOwner);
- expect(result).toBeNull();
- });
-
- it("returns partial results when cache is complete (hasMore=false)", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- makeMessage({ id: "m3", conversation_id: "conv_1", created_at: "2024-01-01T00:02:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const result = await getCachedMessagesBefore("conv_1", "2024-01-01T00:02:00Z", "m3", 10, cacheOwner);
- expect(result).not.toBeNull();
- expect(result!.messages.map((m) => m.id)).toEqual(["m1", "m2"]);
- expect(result!.hasMore).toBe(false);
- });
-
- it("returns null for unknown conversation", async () => {
- const result = await getCachedMessagesBefore("nonexistent", "2024-01-01T00:00:00Z", "x", 10, cacheOwner);
- expect(result).toBeNull();
- });
-
- it("handles equal timestamps with ID tiebreaker", async () => {
- const msgs = [
- makeMessage({ id: "aaa", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "bbb", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "ccc", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const result = await getCachedMessagesBefore("conv_1", "2024-01-01T00:00:00Z", "ccc", 10, cacheOwner);
- expect(result).not.toBeNull();
- expect(result!.messages.map((m) => m.id)).toEqual(["aaa", "bbb"]);
- });
-
- it("correctly excludes the cursor message itself", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- makeMessage({ id: "m3", conversation_id: "conv_1", created_at: "2024-01-01T00:02:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const result = await getCachedMessagesBefore("conv_1", "2024-01-01T00:02:00Z", "m3", 10, cacheOwner);
- expect(result).not.toBeNull();
- expect(result!.messages.every((m) => m.id !== "m3")).toBe(true);
- });
-
- it("no meta corruption on cache-hit path", async () => {
- const msgs = [
- makeMessage({ id: "m1", conversation_id: "conv_1", created_at: "2024-01-01T00:00:00Z" }),
- makeMessage({ id: "m2", conversation_id: "conv_1", created_at: "2024-01-01T00:01:00Z" }),
- makeMessage({ id: "m3", conversation_id: "conv_1", created_at: "2024-01-01T00:02:00Z" }),
- ];
- await mergeCachedMessages("conv_1", msgs, false, cacheOwner);
-
- const metaBefore = await getCacheMeta("conv_1", cacheOwner);
- await getCachedMessagesBefore("conv_1", "2024-01-01T00:02:00Z", "m3", 10, cacheOwner);
- const metaAfter = await getCacheMeta("conv_1", cacheOwner);
-
- expect(metaAfter!.messageCount).toBe(metaBefore!.messageCount);
- expect(metaAfter!.hasMore).toBe(metaBefore!.hasMore);
- expect(metaAfter!.newestMessageId).toBe(metaBefore!.newestMessageId);
- });
- });
-
- describe("clearAllCache", () => {
- it("removes everything", async () => {
- await mergeCachedMessages(
- "conv_1",
- [makeMessage({ id: "m1", conversation_id: "conv_1" })],
- false,
- cacheOwner
- );
- await mergeCachedMessages(
- "conv_2",
- [makeMessage({ id: "m2", conversation_id: "conv_2" })],
- false,
- cacheOwner
- );
-
- await clearAllCache(cacheOwner.application);
-
- const cached1 = await getCachedMessages("conv_1", cacheOwner);
- const cached2 = await getCachedMessages("conv_2", cacheOwner);
- expect(cached1).toBeNull();
- expect(cached2).toBeNull();
- });
- });
-});
diff --git a/src/web/src/lib/chat-cache.ts b/src/web/src/lib/chat-cache.ts
deleted file mode 100644
index af5eec625..000000000
--- a/src/web/src/lib/chat-cache.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import type { InfiniteData } from "@tanstack/react-query";
-import type { Message, Artifact, Conversation } from "@alook/shared";
-import { assertWorkspaceOwner, captureWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context";
-import type { ApplicationOwner } from "@/lib/application-owner";
-
-export type ChatMessagesPage = { messages: Message[]; hasMore: boolean; requestRevision?: number };
-export type ChatMessagesData = InfiniteData<ChatMessagesPage> & { serverMessageCount: number; liveRevision?: number; liveMessageRevisions?: Record<string, number> };
-export type ChatExtras = { conversation: Conversation | null; artifacts: Artifact[]; hasMoreArtifacts: boolean };
-export interface CacheMeta {
- conversation_id: string;
- lastFetchedAt: number;
- lastAccessedAt: number;
- messageCount: number;
- newestMessageId: string | null;
- hasMore: boolean;
- serverMessageCount: number;
-}
-export interface LastOpenEntry {
- key: string;
- conversation_id: string;
- newestMessageId: string | null;
- serverMessageCount: number;
- updatedAt: number;
-}
-export interface ConvExtrasEntry {
- conversation_id: string;
- artifacts: Artifact[];
- conversation_type: string;
- conversation_title: string;
- conversation_channel: string;
- conversation_created_at: string;
- hasMoreArtifacts: boolean;
- updatedAt: number;
-}
-export const chatMessagesKey = (owner: WorkspaceOwner, conversationId: string) => owner.key("chat", "messages", conversationId);
-export const chatExtrasKey = (owner: WorkspaceOwner, conversationId: string) => owner.key("chat", "extras", conversationId);
-export const chatLatestKey = (owner: WorkspaceOwner, agentId: string, channel: string | null | undefined) => owner.key("chat", "latest-created", agentId, channel ?? "");
-export function sortedChatMessages(data: ChatMessagesData | undefined): Message[] {
- const rows = new Map<string, Message>();
- for (const page of data?.pages ?? []) for (const row of page.messages) {
- if (!row.id.startsWith("temp-")) rows.set(row.id, row);
- }
- return [...rows.values()].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id));
-}
-function assertOwner(owner: WorkspaceOwner) { assertWorkspaceOwner(captureWorkspaceOwner(owner)); }
-export async function getCachedMessages(conversationId: string, owner: WorkspaceOwner): Promise<Message[] | null> {
- assertOwner(owner);
- const messages = sortedChatMessages(owner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(owner, conversationId)));
- return messages.length ? messages : null;
-}
-export async function getCacheMeta(conversationId: string, owner: WorkspaceOwner): Promise<CacheMeta | null> {
- assertOwner(owner);
- const key = chatMessagesKey(owner, conversationId);
- const data = owner.queryClient.getQueryData<ChatMessagesData>(key);
- if (!data) return null;
- const rows = sortedChatMessages(data);
- const updatedAt = owner.queryClient.getQueryState(key)?.dataUpdatedAt ?? 0;
- return { conversation_id: conversationId, lastFetchedAt: updatedAt, lastAccessedAt: updatedAt, messageCount: rows.length, newestMessageId: rows.at(-1)?.id ?? null, hasMore: data.pages.at(-1)?.hasMore ?? true, serverMessageCount: data.serverMessageCount };
-}
-export async function mergeCachedMessages(conversationId: string, messages: Message[], hasMore: boolean | null, owner: WorkspaceOwner, serverMessageCount?: number, live = false): Promise<void> {
- assertOwner(owner);
- const valid = messages.filter((row) => !row.id.startsWith("temp-") && row.conversation_id === conversationId);
- owner.queryClient.setQueryData<ChatMessagesData>(chatMessagesKey(owner, conversationId), (previous) => {
- const liveRevision = (previous?.liveRevision ?? 0) + (live ? 1 : 0);
- const liveMessageRevisions = { ...previous?.liveMessageRevisions };
- if (live) for (const row of valid) liveMessageRevisions[row.id] = liveRevision;
- const byId = new Map(valid.map((row) => [row.id, row]));
- const present = new Set(sortedChatMessages(previous).map((row) => row.id));
- const pages = (previous?.pages ?? [{ messages: [], hasMore: true }]).map((page, index, all) => ({
- ...page,
- messages: [...page.messages.map((row) => byId.get(row.id) ?? row), ...(!index ? valid.filter((row) => !present.has(row.id)) : [])].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)),
- hasMore: index === all.length - 1 ? hasMore ?? page.hasMore : page.hasMore,
- }));
- return { pages, pageParams: previous?.pageParams ?? [null], serverMessageCount: serverMessageCount ?? previous?.serverMessageCount ?? 0, liveRevision, liveMessageRevisions };
-
- });
-}
-export async function appendCachedMessage(conversationId: string, message: Message, owner: WorkspaceOwner): Promise<void> {
- if (message.id.startsWith("temp-")) return;
- await mergeCachedMessages(conversationId, [message], null, owner, undefined, true);
-}
-export async function removeCachedMessage(conversationId: string, messageId: string, owner: WorkspaceOwner): Promise<void> {
- assertOwner(owner);
- owner.queryClient.setQueryData<ChatMessagesData>(chatMessagesKey(owner, conversationId), (data) => data ? { ...data, pages: data.pages.map((page) => ({ ...page, messages: page.messages.filter((row) => row.id !== messageId) })) } : undefined);
-}
-export async function getCachedMessagesBefore(conversationId: string, beforeCreatedAt: string, beforeId: string, limit: number, owner: WorkspaceOwner): Promise<{ messages: Message[]; hasMore: boolean } | null> {
- const token = captureWorkspaceOwner(owner);
- const meta = await getCacheMeta(conversationId, owner);
- assertWorkspaceOwner(token);
- if (!meta) return null;
- const rows = sortedChatMessages(owner.queryClient.getQueryData<ChatMessagesData>(chatMessagesKey(owner, conversationId))).filter((row) => row.created_at < beforeCreatedAt || row.created_at === beforeCreatedAt && row.id < beforeId);
- if (rows.length < limit && meta.hasMore) return null;
- return { messages: rows.slice(-limit), hasMore: rows.length > limit || meta.hasMore };
-}
-export async function getLastOpenConversation(agentId: string, channel: string | null | undefined, owner: WorkspaceOwner): Promise<LastOpenEntry | null> {
- assertOwner(owner);
- return owner.queryClient.getQueryData<LastOpenEntry>(chatLatestKey(owner, agentId, channel)) ?? null;
-}
-export async function setLastOpenConversation(agentId: string, channel: string | null | undefined, entry: Pick<LastOpenEntry, "conversation_id" | "newestMessageId" | "serverMessageCount">, owner: WorkspaceOwner): Promise<void> {
- assertOwner(owner);
- owner.queryClient.setQueryData<LastOpenEntry>(chatLatestKey(owner, agentId, channel), { ...entry, key: `${agentId}::${channel ?? ""}`, updatedAt: Date.now() });
-}
-export async function clearLastOpenForConversation(conversationId: string, owner: WorkspaceOwner): Promise<void> {
- assertOwner(owner);
- owner.queryClient.removeQueries({ queryKey: owner.key("chat", "latest-created"), predicate: (query) => (query.state.data as LastOpenEntry | undefined)?.conversation_id === conversationId });
-}
-export async function getConvExtras(conversationId: string, owner: WorkspaceOwner): Promise<ConvExtrasEntry | null> {
- assertOwner(owner);
- const key = chatExtrasKey(owner, conversationId);
- const data = owner.queryClient.getQueryData<ChatExtras>(key);
- if (!data?.conversation) return null;
- return { conversation_id: conversationId, artifacts: data.artifacts, conversation_type: data.conversation.type, conversation_title: data.conversation.title, conversation_channel: data.conversation.channel, conversation_created_at: data.conversation.created_at, hasMoreArtifacts: data.hasMoreArtifacts, updatedAt: owner.queryClient.getQueryState(key)?.dataUpdatedAt ?? 0 };
-}
-export async function setConvExtras(conversationId: string, entry: Omit<ConvExtrasEntry, "conversation_id" | "updatedAt">, owner: WorkspaceOwner): Promise<void> {
- assertOwner(owner);
- owner.queryClient.setQueryData<ChatExtras>(chatExtrasKey(owner, conversationId), (data) => ({ conversation: { ...data?.conversation, id: conversationId, agent_id: data?.conversation?.agent_id ?? "", type: entry.conversation_type, title: entry.conversation_title, channel: entry.conversation_channel, created_at: entry.conversation_created_at }, artifacts: entry.artifacts, hasMoreArtifacts: entry.hasMoreArtifacts }));
-}
-export async function clearConvExtras(conversationId: string, owner: WorkspaceOwner): Promise<void> {
- assertOwner(owner);
- owner.queryClient.removeQueries({ queryKey: chatExtrasKey(owner, conversationId), exact: true });
-}
-export async function invalidateCache(conversationId: string, owner: WorkspaceOwner): Promise<void> {
- const token = captureWorkspaceOwner(owner);
- assertWorkspaceOwner(token);
- await owner.queryClient.cancelQueries({ queryKey: chatMessagesKey(owner, conversationId), exact: true });
- assertWorkspaceOwner(token);
- owner.queryClient.removeQueries({ queryKey: chatMessagesKey(owner, conversationId), exact: true });
- await clearConvExtras(conversationId, owner);
- await clearLastOpenForConversation(conversationId, owner);
-}
-export async function clearAllCache(owner: ApplicationOwner): Promise<void> {
- await owner.queryClient.cancelQueries({ queryKey: ["application", owner.userId, "workspace"] });
- owner.queryClient.removeQueries({ queryKey: ["application", owner.userId, "workspace"] });
- await owner.retireDisk();
-}
diff --git a/src/web/src/lib/chat-markdown.test.ts b/src/web/src/lib/chat-markdown.test.ts
deleted file mode 100644
index 7c95322bd..000000000
--- a/src/web/src/lib/chat-markdown.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { decodeChatEntities } from "./chat-markdown";
-
-/**
- * `@tiptap/markdown` HTML-entity-encodes `<` `>` `&` in plain text when
- * serializing. The chat wire format must stay the raw typed string (parity with
- * the old textarea), so the composer decodes exactly those three. These tests
- * lock that behavior and guard the `&amp;`-last ordering.
- */
-describe("decodeChatEntities", () => {
- it("decodes the three HTML entities the serializer emits", () => {
- expect(decodeChatEntities("a &lt; b &amp;&amp; c &gt; d")).toBe("a < b && c > d");
- });
-
- it("decodes <Component /> style text", () => {
- expect(decodeChatEntities("use &lt;Component /&gt; here")).toBe("use <Component /> here");
- });
-
- it("leaves text without entities untouched", () => {
- expect(decodeChatEntities("plain @Alice - list 1. item")).toBe(
- "plain @Alice - list 1. item",
- );
- });
-
- it("decodes &amp; last so a literal typed entity round-trips", () => {
- // User types the literal text "&lt;". The serializer escapes the `&` to
- // "&amp;lt;". Decoding &amp; LAST yields "&lt;" (the typed text), not "<".
- expect(decodeChatEntities("&amp;lt;")).toBe("&lt;");
- });
-
- it("does not touch markdown punctuation", () => {
- expect(decodeChatEntities("a*b_c`d# heading")).toBe("a*b_c`d# heading");
- });
-
- it("handles empty string", () => {
- expect(decodeChatEntities("")).toBe("");
- });
-});
diff --git a/src/web/src/lib/chat-markdown.ts b/src/web/src/lib/chat-markdown.ts
deleted file mode 100644
index 554237eb5..000000000
--- a/src/web/src/lib/chat-markdown.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * The chat wire format is a plain string and must stay byte-identical to what
- * the old textarea sent. But `@tiptap/markdown`'s serializer HTML-entity-encodes
- * the three HTML-significant characters in plain text — `<`→`&lt;`, `>`→`&gt;`,
- * `&`→`&amp;` — so `getMarkdown()` of "x < 5 && y > 3" returns
- * "x &lt; 5 &amp;&amp; y &gt; 3". Markdown punctuation (`*` `_` `` ` `` `#`) is
- * left literal, which is what we want; only these HTML entities leak in.
- *
- * We decode exactly those three back so the outgoing content matches the typed
- * text. `&amp;` is decoded LAST so a literal "&lt;" the user typed (which the
- * serializer emits as "&amp;lt;") round-trips to "&lt;", not "<".
- */
-export function decodeChatEntities(markdown: string): string {
- return markdown
- .replaceAll("&lt;", "<")
- .replaceAll("&gt;", ">")
- .replaceAll("&amp;", "&");
-}
diff --git a/src/web/src/lib/chat-mention-extension.test.ts b/src/web/src/lib/chat-mention-extension.test.ts
deleted file mode 100644
index bbdd12de5..000000000
--- a/src/web/src/lib/chat-mention-extension.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { MarkdownManager } from "@tiptap/markdown";
-import StarterKit from "@tiptap/starter-kit";
-import { buildChatMentionExtension, mentionTokensToHtml } from "./chat-mention-extension";
-
-/**
- * A Mention node serializes to a `@[Name](agentId)` token in markdown — the
- * wire format the backend parses by id. This guards against a TipTap upgrade
- * silently regressing the serializer or adding `\@` escaping.
- */
-
-// StarterKit is a bundle; the MarkdownManager wants flat extensions.
-function flatten(ext: ReturnType<typeof StarterKit.configure>) {
- const out: unknown[] = [];
- const visit = (e: { config?: { addExtensions?: () => unknown[] } }) => {
- if (e?.config?.addExtensions) {
- try {
- for (const c of e.config.addExtensions.call(e)) visit(c as typeof e);
- } catch {
- /* ignore bundles that can't expand without an editor */
- }
- }
- out.push(e);
- };
- visit(ext as never);
- return out;
-}
-
-function serialize(doc: object): string {
- const extensions = [
- ...flatten(StarterKit.configure({})),
- buildChatMentionExtension(),
- ];
- const mgr = new MarkdownManager({ extensions: extensions as never });
- return mgr.serialize(doc as never);
-}
-
-function para(...content: object[]) {
- return { type: "doc", content: [{ type: "paragraph", content }] };
-}
-
-const mention = (id: string, label: string) => ({
- type: "mention",
- attrs: { id, label },
-});
-const text = (t: string) => ({ type: "text", text: t });
-
-describe("chat mention markdown serialization", () => {
- it("serializes a mention to a @[Name](id) token", () => {
- expect(serialize(para(text("hi "), mention("a1", "Alice"), text(" there")))).toBe(
- "hi @[Alice](a1) there",
- );
- });
-
- it("does not escape the @ (no \\@)", () => {
- const md = serialize(para(mention("a1", "Alice")));
- expect(md).toBe("@[Alice](a1)");
- expect(md).not.toContain("\\@");
- });
-
- it("falls back to id in the label slot when label is null/undefined", () => {
- const md = serialize(
- para({ type: "mention", attrs: { id: "agent-7", label: null } }),
- );
- expect(md).toBe("@[agent-7](agent-7)");
- });
-
- it("serializes multiple mentions in one line", () => {
- expect(
- serialize(
- para(mention("a1", "Alice"), text(" and "), mention("b2", "Bob"), text(" hi")),
- ),
- ).toBe("@[Alice](a1) and @[Bob](b2) hi");
- });
-});
-
-describe("mentionTokensToHtml (draft restore)", () => {
- it("converts a token to mention HTML the parseHTML step can rebuild", () => {
- expect(mentionTokensToHtml("Hey @[Ada](ag_ada1) do this")).toBe(
- 'Hey <span data-type="mention" data-id="ag_ada1" data-label="Ada"></span> do this',
- );
- });
-
- it("converts multiple tokens", () => {
- expect(mentionTokensToHtml("@[Ada](ag_1) and @[Bob](ag_2)")).toBe(
- '<span data-type="mention" data-id="ag_1" data-label="Ada"></span> and <span data-type="mention" data-id="ag_2" data-label="Bob"></span>',
- );
- });
-
- it("leaves a normal markdown link untouched", () => {
- const link = "see [docs](https://example.com/a.b:c)";
- expect(mentionTokensToHtml(link)).toBe(link);
- });
-});
diff --git a/src/web/src/lib/chat-mention-extension.ts b/src/web/src/lib/chat-mention-extension.ts
deleted file mode 100644
index 87330d06c..000000000
--- a/src/web/src/lib/chat-mention-extension.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import Mention from "@tiptap/extension-mention";
-import { MENTION_TOKEN_RE } from "@alook/shared";
-
-function escapeAttr(value: string): string {
- return value
- .replaceAll("&", "&amp;")
- .replaceAll('"', "&quot;")
- .replaceAll("<", "&lt;")
- .replaceAll(">", "&gt;");
-}
-
-export function mentionTokensToHtml(value: string): string {
- return value.replace(
- MENTION_TOKEN_RE,
- (_m, label: string, id: string) =>
- `<span data-type="mention" data-id="${escapeAttr(id)}" data-label="${escapeAttr(label)}"></span>`,
- );
-}
-
-/**
- * Mention configured to serialize to a `@[Name](agentId)` token in markdown.
- *
- * `@tiptap/markdown` reads `renderMarkdown` off the extension config via
- * getExtensionField (keyed on the node name "mention"). The token carries the
- * stable agent id so downstream parsing (highlight-mentions, prompt-parser)
- * resolves the exact agent by id instead of guessing by display name.
- * `renderText` keeps copy / getText() emitting the human-readable `@Name`.
- *
- * These two fields aren't in TipTap's NodeConfig types (the markdown plugin
- * reads them dynamically), so the config is cast to the extend param type.
- */
-type MentionExtendConfig = Parameters<typeof Mention.extend>[0];
-
-export function buildChatMentionExtension() {
- return Mention.extend({
- markdownName: "mention",
- renderMarkdown: (node: { attrs: { id: string; label?: string | null } }) =>
- `@[${node.attrs.label ?? node.attrs.id}](${node.attrs.id})`,
- renderText: (node: { attrs: { id: string; label?: string | null } }) =>
- `@${node.attrs.label ?? node.attrs.id}`,
- } as MentionExtendConfig);
-}
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 03edcfc26..cdc7d01d0 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -1,6 +1,6 @@
"use client"
-import { createContext, createElement, useContext, useMemo, useLayoutEffect, type Context, type ReactNode } from "react"
+import { createContext, createElement, useContext, useMemo, type Context, type ReactNode } from "react"
import { ApplicationOwnerProvider, createApplicationOwner } from "@/lib/application-owner"
import { DbProvider, collectionOptions, getLiveQueryHash, liveQueryCollectionOptions, prepareLiveQueryValue, eq, inArray, useLiveQuery as useNativeLiveQuery, type Context as QueryContext, type LiveQueryCollectionConfig } from "@tanstack/react-db"
import { createStore, useSelector } from "@tanstack/react-store"
@@ -107,12 +107,6 @@ export function CommunityDbProvider({
owner.bindAuthentication(() => registry.sessionViewer(), () => registry.retireDisk())
return owner
}, [registry])
- useLayoutEffect(() => {
- const subscription = registry.runtime.lifecycle.subscribe(() => {
- if (!registry.runtime.lifecycle.get().active) application.preferences.setState((state) => ({ ...state, localValues: new Map() }))
- })
- return () => subscription.unsubscribe()
- }, [application, registry])
return createElement(
ApplicationOwnerProvider, { owner: application },
createElement(DbProvider, { client: registry.dbClient },
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index a3e7d0575..1a0d35e5f 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -84,6 +84,7 @@ export const tid = {
statusPill: "community-status-pill",
inviteToken: "community-invite-token",
inviteCopy: "community-invite-copy",
+ inviteExpiredTitle: "community-invite-expired-title",
inviteCard: (token: string) => `community-invite-card-${token}`,
inviteCardAction: (token: string) => `community-invite-card-action-${token}`,
machinePairOpen: "community-machine-pair-open",
diff --git a/src/web/src/lib/file-download-action.ts b/src/web/src/lib/file-download-action.ts
deleted file mode 100644
index f0874e1c1..000000000
--- a/src/web/src/lib/file-download-action.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-"use client"
-
-import { toast } from "sonner"
-import { captureApplicationOwner, assertApplicationOwner, type ApplicationOwner } from "./application-owner"
-import { cancelFileDownload, fileDownloadKey, fileDownloadStatusText, readFileDownloadState, startFileDownload } from "./file-download"
-
-export async function downloadFileWithFeedback(owner: ApplicationOwner, target: { url: string; name: string }, options: { signal?: AbortSignal; assertActive: () => void }): Promise<void> {
- const token = captureApplicationOwner(owner)
- const assert = () => { assertApplicationOwner(token, options.signal); options.assertActive() }
- try { assert() } catch { return }
- const key = fileDownloadKey(owner, target)
- if (readFileDownloadState(owner, key).status === "downloading") {
- await cancelFileDownload(owner, key).catch(() => undefined)
- return
- }
- const id = toast.loading("Downloading…", {
- action: { label: "Cancel", onClick: () => { try { assert(); void cancelFileDownload(owner, key).catch(() => undefined) } catch {} } },
- })
- let result
- try { result = await startFileDownload(owner, target, options.signal); assert() }
- catch { return }
- finally { toast.dismiss(id) }
- const text = fileDownloadStatusText(result)
- if (result.status === "error") toast.error(text, {
- action: { label: "Retry", onClick: () => { try { assert(); void downloadFileWithFeedback(owner, target, options) } catch {} } },
- })
- else if (result.status === "saved" || result.status === "started") toast.success(text)
-}
diff --git a/src/web/src/lib/form-validation.test.ts b/src/web/src/lib/form-validation.test.ts
deleted file mode 100644
index 3608e8683..000000000
--- a/src/web/src/lib/form-validation.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- hasCustomEmailErrors,
- hasWorkspaceFormErrors,
- validateCustomEmailFields,
- validateWorkspaceForm,
-} from "./form-validation";
-
-describe("validateWorkspaceForm", () => {
- it("requires workspace name and slug", () => {
- const errors = validateWorkspaceForm({ name: " ", slug: "" });
-
- expect(errors).toEqual({
- name: "Workspace name is required",
- slug: "Workspace slug is required",
- });
- expect(hasWorkspaceFormErrors(errors)).toBe(true);
- });
-
- it("passes when name and slug are present", () => {
- const errors = validateWorkspaceForm({ name: "Alook", slug: "alook" });
-
- expect(errors).toEqual({});
- expect(hasWorkspaceFormErrors(errors)).toBe(false);
- });
-});
-
-describe("validateCustomEmailFields", () => {
- it("reports specific missing custom email fields", () => {
- const errors = validateCustomEmailFields({
- emailAddress: "",
- imapHost: "",
- imapUsername: "",
- imapPassword: "",
- smtpHost: "",
- smtpUsername: "",
- smtpPassword: "",
- });
-
- expect(errors).toEqual({
- emailAddress: "Email address is required",
- imapHost: "IMAP host is required",
- imapPassword: "IMAP credentials are required",
- smtpHost: "SMTP host is required",
- smtpPassword: "SMTP credentials are required",
- });
- expect(hasCustomEmailErrors(errors)).toBe(true);
- });
-
- it("uses defaulted usernames when validating credentials", () => {
- const errors = validateCustomEmailFields({
- emailAddress: "[email protected]",
- imapHost: "imap.example.com",
- imapUsername: "[email protected]",
- imapPassword: "secret",
- smtpHost: "smtp.example.com",
- smtpUsername: "[email protected]",
- smtpPassword: "secret",
- });
-
- expect(errors).toEqual({});
- expect(hasCustomEmailErrors(errors)).toBe(false);
- });
-});
diff --git a/src/web/src/lib/form-validation.ts b/src/web/src/lib/form-validation.ts
deleted file mode 100644
index 83c4df6f2..000000000
--- a/src/web/src/lib/form-validation.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-export interface WorkspaceFormValidationInput {
- name: string;
- slug: string;
-}
-
-export interface WorkspaceFormErrors {
- name?: string;
- slug?: string;
-}
-
-export function validateWorkspaceForm({
- name,
- slug,
-}: WorkspaceFormValidationInput): WorkspaceFormErrors {
- const errors: WorkspaceFormErrors = {};
-
- if (!name.trim()) {
- errors.name = "Workspace name is required";
- }
-
- if (!slug.trim()) {
- errors.slug = "Workspace slug is required";
- }
-
- return errors;
-}
-
-export function hasWorkspaceFormErrors(errors: WorkspaceFormErrors): boolean {
- return Boolean(errors.name || errors.slug);
-}
-
-export interface CustomEmailValidationInput {
- emailAddress: string;
- imapHost: string;
- imapUsername: string;
- imapPassword: string;
- smtpHost: string;
- smtpUsername: string;
- smtpPassword: string;
-}
-
-export interface CustomEmailErrors {
- emailAddress?: string;
- imapHost?: string;
- imapPassword?: string;
- smtpHost?: string;
- smtpPassword?: string;
-}
-
-export function validateCustomEmailFields({
- emailAddress,
- imapHost,
- imapUsername,
- imapPassword,
- smtpHost,
- smtpUsername,
- smtpPassword,
-}: CustomEmailValidationInput): CustomEmailErrors {
- const errors: CustomEmailErrors = {};
-
- if (!emailAddress.trim()) {
- errors.emailAddress = "Email address is required";
- }
-
- if (!imapHost.trim()) {
- errors.imapHost = "IMAP host is required";
- }
-
- if (!imapUsername.trim() || !imapPassword.trim()) {
- errors.imapPassword = "IMAP credentials are required";
- }
-
- if (!smtpHost.trim()) {
- errors.smtpHost = "SMTP host is required";
- }
-
- if (!smtpUsername.trim() || !smtpPassword.trim()) {
- errors.smtpPassword = "SMTP credentials are required";
- }
-
- return errors;
-}
-
-export function hasCustomEmailErrors(errors: CustomEmailErrors): boolean {
- return Boolean(
- errors.emailAddress ||
- errors.imapHost ||
- errors.imapPassword ||
- errors.smtpHost ||
- errors.smtpPassword,
- );
-}
diff --git a/src/web/src/lib/highlight-mentions.test.ts b/src/web/src/lib/highlight-mentions.test.ts
deleted file mode 100644
index 2c8b2398b..000000000
--- a/src/web/src/lib/highlight-mentions.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { describe, it, expect } from "vitest"
-import { highlightMentions } from "./highlight-mentions"
-import type { Agent } from "@alook/shared"
-
-const agent = (name: string, email_handle: string | null = null): Agent => ({
- id: `ag_${name.toLowerCase()}`,
- workspace_id: "ws_1",
- runtime_id: "rt_1",
- name,
- description: "",
- instructions: "",
- runtime_mode: "daemon",
- runtime_config: {},
- status: "active",
- max_concurrent_tasks: 1,
- email_handle,
- avatar_url: null,
- visibility: "public",
- owner_id: null,
- created_at: "2024-01-01T00:00:00Z",
- updated_at: "2024-01-01T00:00:00Z",
-})
-
-describe("highlightMentions", () => {
- it("wraps basic @AgentName with data-agent-id", () => {
- const result = highlightMentions("Hey @TestBot do this", [agent("TestBot", "testbot")])
- expect(result).toBe('Hey <mention data-agent-id="ag_testbot">@TestBot</mention> do this')
- })
-
- it("wraps only name portion of enriched form", () => {
- const result = highlightMentions("Hey @TestBot ([email protected]) do this", [agent("TestBot", "testbot")])
- expect(result).toBe('Hey <mention data-agent-id="ag_testbot">@TestBot</mention> ([email protected]) do this')
- })
-
- it("leaves non-matching @ as plain text", () => {
- const result = highlightMentions("send to [email protected]", [agent("TestBot")])
- expect(result).toBe("send to [email protected]")
- })
-
- it("wraps multiple mentions with correct agent ids", () => {
- const result = highlightMentions("@Alpha and @Beta", [agent("Alpha", "alpha"), agent("Beta", "beta")])
- expect(result).toBe('<mention data-agent-id="ag_alpha">@Alpha</mention> and <mention data-agent-id="ag_beta">@Beta</mention>')
- })
-
- it("does not wrap unknown agent names", () => {
- const result = highlightMentions("Hey @Unknown", [agent("TestBot")])
- expect(result).toBe("Hey @Unknown")
- })
-
- it("returns unchanged with no @ symbols", () => {
- const result = highlightMentions("Hello world", [agent("TestBot")])
- expect(result).toBe("Hello world")
- })
-
- it("returns unchanged with empty agents", () => {
- const result = highlightMentions("Hey @TestBot", [])
- expect(result).toBe("Hey @TestBot")
- })
-
- it("includes data-agent-id attribute on mention tags", () => {
- const result = highlightMentions("Hello @TestBot", [agent("TestBot")])
- expect(result).toContain('data-agent-id="ag_testbot"')
- })
-
- it("includes correct agent id for each mention when multiple agents are mentioned", () => {
- const agents = [agent("Alice", "alice"), agent("Bob", "bob")]
- const result = highlightMentions("@Alice talk to @Bob", agents)
- expect(result).toContain('data-agent-id="ag_alice"')
- expect(result).toContain('data-agent-id="ag_bob"')
- expect(result).toBe('<mention data-agent-id="ag_alice">@Alice</mention> talk to <mention data-agent-id="ag_bob">@Bob</mention>')
- })
-
- it("wraps a token by its agent id", () => {
- const result = highlightMentions("Hey @[Ada](ag_ada1) do this", [agent("Ada")])
- expect(result).toBe('Hey <mention data-agent-id="ag_ada1">@Ada</mention> do this')
- })
-
- it("locks a token to its id even with two same-name agents", () => {
- const agents = [
- { ...agent("Ada"), id: "ag_ada1" },
- { ...agent("Ada"), id: "ag_ada2" },
- ]
- const result = highlightMentions("@[Ada](ag_ada2)", agents)
- expect(result).toBe('<mention data-agent-id="ag_ada2">@Ada</mention>')
- })
-
- it("wraps a token even when agents is empty (no markdown link leak)", () => {
- const result = highlightMentions("Hey @[Ada](ag_ada1) do this", [])
- expect(result).toBe('Hey <mention data-agent-id="ag_ada1">@Ada</mention> do this')
- expect(result).not.toContain("](ag_ada1)")
- })
-
- it("wraps a token whose agent is unknown (deleted) — still not a markdown link", () => {
- const result = highlightMentions("Hey @[Ada](ag_gone) do this", [agent("TestBot")])
- expect(result).toBe('Hey <mention data-agent-id="ag_gone">@Ada</mention> do this')
- })
-
- it("handles a token mixed with a bare-name mention", () => {
- const result = highlightMentions("@[Ada](ag_ada1) and @Bob", [agent("Bob", "bob")])
- expect(result).toBe('<mention data-agent-id="ag_ada1">@Ada</mention> and <mention data-agent-id="ag_bob">@Bob</mention>')
- })
-
- it("does not treat a normal markdown link as a mention token", () => {
- const link = "see [docs](https://example.com/a.b:c) now"
- expect(highlightMentions(link, [agent("docs")])).toBe(link)
- })
-})
diff --git a/src/web/src/lib/highlight-mentions.ts b/src/web/src/lib/highlight-mentions.ts
deleted file mode 100644
index 8a7fe59af..000000000
--- a/src/web/src/lib/highlight-mentions.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import type { Agent } from "@alook/shared"
-import { MENTION_TOKEN_RE } from "@alook/shared"
-
-function isTrigger(text: string, atIndex: number): boolean {
- if (atIndex === 0) return true
- const prev = text.charCodeAt(atIndex - 1)
- if ((prev >= 48 && prev <= 57) || (prev >= 65 && prev <= 90) || (prev >= 97 && prev <= 122) || prev === 95) return false
- return true
-}
-
-function isBoundary(text: string, endIndex: number): boolean {
- if (endIndex >= text.length) return true
- const next = text.charCodeAt(endIndex)
- if ((next >= 48 && next <= 57) || (next >= 65 && next <= 90) || (next >= 97 && next <= 122) || next === 95) return false
- return true
-}
-
-export function highlightMentions(content: string, agents: Agent[]): string {
- if (!content || !content.includes("@")) return content
-
- // Token pass — id-based, independent of the agents array so a raw
- // `@[Name](agentId)` token never survives into <Streamdown> (where it would
- // render as a markdown link to the id). Text between tokens still runs
- // through the bare-name pass for backward compatibility with historic /
- // externally-sourced `@Name` mentions.
- const re = new RegExp(MENTION_TOKEN_RE.source, "g")
- let result = ""
- let last = 0
- let m: RegExpExecArray | null
- while ((m = re.exec(content)) !== null) {
- result += highlightBareNames(content.slice(last, m.index), agents)
- result += `<mention data-agent-id="${m[2]}">@${m[1]}</mention>`
- last = re.lastIndex
- }
- result += highlightBareNames(content.slice(last), agents)
- return result
-}
-
-function highlightBareNames(content: string, agents: Agent[]): string {
- if (!content || agents.length === 0 || !content.includes("@")) return content
-
- const sorted = agents.slice().sort((a, b) => b.name.length - a.name.length)
-
- interface Match {
- start: number
- end: number
- name: string
- agentId: string
- }
-
- const matches: Match[] = []
-
- for (let i = 0; i < content.length; i++) {
- if (content[i] !== "@") continue
- if (!isTrigger(content, i)) continue
-
- const afterAt = i + 1
- for (const agent of sorted) {
- const nameEnd = afterAt + agent.name.length
- if (nameEnd > content.length) continue
- const slice = content.slice(afterAt, nameEnd)
- if (slice.toLowerCase() !== agent.name.toLowerCase()) continue
-
- // Check if this is the enriched form: @AgentName ([email protected])
- let matchEnd = nameEnd
- const afterName = content.slice(nameEnd)
- const enrichedMatch = afterName.match(/^ \([a-zA-Z0-9-]+@alook\.ai\)/)
- if (enrichedMatch) {
- matchEnd = nameEnd + enrichedMatch[0].length
- }
-
- if (!enrichedMatch && !isBoundary(content, nameEnd)) continue
- if (enrichedMatch && !isBoundary(content, matchEnd)) continue
-
- const overlaps = matches.some(m => i >= m.start && i < m.end)
- if (overlaps) break
-
- matches.push({ start: i, end: nameEnd, name: agent.name, agentId: agent.id })
- break
- }
- }
-
- // Process from end to start
- let result = content
- for (let i = matches.length - 1; i >= 0; i--) {
- const m = matches[i]
- const name = result.slice(m.start, m.end)
- result = result.slice(0, m.start) + `<mention data-agent-id="${m.agentId}">${name}</mention>` + result.slice(m.end)
- }
-
- return result
-}
diff --git a/src/web/src/lib/home-pet-settings.dom.test.tsx b/src/web/src/lib/home-pet-settings.dom.test.tsx
index bc4dab624..c2033edfc 100644
--- a/src/web/src/lib/home-pet-settings.dom.test.tsx
+++ b/src/web/src/lib/home-pet-settings.dom.test.tsx
@@ -1,9 +1,8 @@
import React from "react"
import { beforeEach, describe, expect, it } from "vitest"
import { act, render } from "@/test/react-dom-harness"
-import { PetTab } from "@/app/(app)/w/[slug]/settings/pet-tab"
import { useHomePetSettings, writeHomePetSettings } from "./home-pet-settings"
-import { getCloudCodeMonsterPreset, readCloudCodeMonsterPetPresetId, useCloudCodeMonsterPetPresetId, writeCloudCodeMonsterPetPresetId } from "@/components/home-pet/cloud-code-monster-pet-presets"
+import { readCloudCodeMonsterPetPresetId, useCloudCodeMonsterPetPresetId, writeCloudCodeMonsterPetPresetId } from "@/components/home-pet/cloud-code-monster-pet-presets"
import { CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY } from "@/components/home-pet/cloud-code-monster-pet-constants"
function Probe({ name }: { name: string }) {
const { enabled } = useHomePetSettings()
@@ -12,14 +11,13 @@ function Probe({ name }: { name: string }) {
}
beforeEach(() => { localStorage.clear(); writeHomePetSettings({ enabled: false }); readCloudCodeMonsterPetPresetId() })
describe("native device pet preferences", () => {
- it("actual settings controls publish directly to every consumer", () => {
- const mounted = render(<><PetTab /><Probe name="one" /><Probe name="two" /></>)
- act(() => mounted.getByRole("switch", { name: "Enable pet" }).click())
+ it("device preference writes publish directly to every consumer", () => {
+ const mounted = render(<><Probe name="one" /><Probe name="two" /></>)
+ act(() => writeHomePetSettings({ enabled: true }))
expect(mounted.getByTestId("one").textContent).toBe("true:pet-01")
expect(mounted.getByTestId("two").textContent).toBe("true:pet-01")
act(() => writeCloudCodeMonsterPetPresetId("pet-02"))
expect(mounted.getByTestId("one").textContent).toBe("true:pet-02")
- expect(mounted.getByRole("button", { pressed: true }).textContent).toBe(getCloudCodeMonsterPreset("pet-02").name)
})
it("cross-tab storage and clear update both native selectors", () => {
const mounted = render(<><Probe name="one" /><Probe name="two" /></>)
diff --git a/src/web/src/lib/inbox-filter.test.ts b/src/web/src/lib/inbox-filter.test.ts
deleted file mode 100644
index 3aebfa433..000000000
--- a/src/web/src/lib/inbox-filter.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { createStore } from "@tanstack/store";
-import { QueryClient } from "@tanstack/react-query";
-const owner = {
- userId: "viewer", queryClient: new QueryClient(),
- lifecycle: createStore({ active: true, generation: 0 }),
- preferences: createStore({ inboxFilterTypes: ["user_dm_message"] as import("./inbox-filter").InboxFilterType[], hydrated: true, lastWorkspaceSlug: null as string | null }),
-};
-import { describe, it, expect, beforeEach, vi } from "vitest";
-import {
- getInboxFilterTypes,
- readStoredInboxFilterTypes,
- setInboxFilterTypes,
- INBOX_FILTER_TYPES,
- INBOX_FILTER_LABELS,
- DEFAULT_INBOX_TYPES,
- MANDATORY_INBOX_TYPES,
-} from "./inbox-filter.js";
-
-describe("inbox-filter constants", () => {
- it("INBOX_FILTER_TYPES contains all expected types", () => {
- expect(INBOX_FILTER_TYPES).toContain("user_dm_message");
- expect(INBOX_FILTER_TYPES).toContain("calendar_event");
- expect(INBOX_FILTER_TYPES).toContain("email_notification");
- expect(INBOX_FILTER_TYPES).toHaveLength(3);
- });
-
- it("INBOX_FILTER_LABELS has labels for all types", () => {
- expect(INBOX_FILTER_LABELS.user_dm_message).toBe("DM");
- expect(INBOX_FILTER_LABELS.calendar_event).toBe("Calendar");
- expect(INBOX_FILTER_LABELS.email_notification).toBe("Email");
- });
-
- it("DEFAULT_INBOX_TYPES includes user_dm_message", () => {
- expect(DEFAULT_INBOX_TYPES).toContain("user_dm_message");
- });
-
- it("MANDATORY_INBOX_TYPES includes user_dm_message", () => {
- expect(MANDATORY_INBOX_TYPES).toContain("user_dm_message");
- });
-});
-
-describe("getInboxFilterTypes", () => {
- let storage: Record<string, string>;
-
- beforeEach(() => {
- storage = {};
- vi.stubGlobal("window", {});
- vi.stubGlobal("localStorage", {
- getItem: vi.fn((key: string) => storage[key] ?? null),
- setItem: vi.fn((key: string, value: string) => {
- storage[key] = value;
- }),
- });
- });
-
- it("returns default types when no localStorage value", () => {
- expect(readStoredInboxFilterTypes("viewer")).toEqual(DEFAULT_INBOX_TYPES);
- });
-
- it("returns parsed types from localStorage", () => {
- storage["alook:viewer:inbox-filter-types"] = JSON.stringify(["user_dm_message", "calendar_event"]);
- expect(readStoredInboxFilterTypes("viewer")).toEqual(["user_dm_message", "calendar_event"]);
- });
-
- it("filters out invalid types", () => {
- storage["alook:viewer:inbox-filter-types"] = JSON.stringify(["user_dm_message", "invalid_type"]);
- expect(readStoredInboxFilterTypes("viewer")).toEqual(["user_dm_message"]);
- });
-
- it("returns default when all types invalid", () => {
- storage["alook:viewer:inbox-filter-types"] = JSON.stringify(["invalid1", "invalid2"]);
- expect(readStoredInboxFilterTypes("viewer")).toEqual(DEFAULT_INBOX_TYPES);
- });
-
- it("ensures mandatory types are included", () => {
- storage["alook:viewer:inbox-filter-types"] = JSON.stringify(["calendar_event"]);
- const result = readStoredInboxFilterTypes("viewer");
- expect(result).toContain("user_dm_message");
- expect(result).toContain("calendar_event");
- });
-
- it("returns default on JSON parse error", () => {
- storage["alook:viewer:inbox-filter-types"] = "not-json{{{";
- expect(readStoredInboxFilterTypes("viewer")).toEqual(DEFAULT_INBOX_TYPES);
- });
-
- it("returns default when window is undefined", () => {
- vi.stubGlobal("window", undefined);
- expect(readStoredInboxFilterTypes("viewer")).toEqual(DEFAULT_INBOX_TYPES);
- });
-});
-
-describe("setInboxFilterTypes", () => {
- let storage: Record<string, string>;
-
- beforeEach(() => {
- storage = {};
- vi.stubGlobal("window", {});
- vi.stubGlobal("localStorage", {
- getItem: vi.fn((key: string) => storage[key] ?? null),
- setItem: vi.fn((key: string, value: string) => {
- storage[key] = value;
- }),
- });
- });
-
- it("saves types to localStorage", () => {
- setInboxFilterTypes(owner, ["user_dm_message", "calendar_event"]);
- const saved = JSON.parse(storage["alook:viewer:inbox-filter-types"]);
- expect(saved).toContain("user_dm_message");
- expect(saved).toContain("calendar_event");
- });
-
- it("adds mandatory types if not included", () => {
- setInboxFilterTypes(owner, ["calendar_event"]);
- const saved = JSON.parse(storage["alook:viewer:inbox-filter-types"]);
- expect(saved).toContain("user_dm_message");
- expect(saved).toContain("calendar_event");
- });
-});
-
-describe("scoped preference Store", () => {
- it("publishes to the owner Store and does not read another account's selection", () => {
- setInboxFilterTypes(owner, ["calendar_event"]);
- expect(getInboxFilterTypes(owner)).toEqual(["user_dm_message", "calendar_event"]);
- const other = { ...owner, userId: "other", preferences: createStore({ inboxFilterTypes: [...DEFAULT_INBOX_TYPES], hydrated: true, lastWorkspaceSlug: null as string | null }) };
- expect(getInboxFilterTypes(other)).toEqual(DEFAULT_INBOX_TYPES);
- });
- it("does not write after owner retirement", () => {
- const previous = getInboxFilterTypes(owner);
- owner.lifecycle.setState((state) => ({ ...state, active: false }));
- setInboxFilterTypes(owner, ["email_notification"]);
- expect(getInboxFilterTypes(owner)).toBe(previous);
- });
-});
diff --git a/src/web/src/lib/inbox-filter.ts b/src/web/src/lib/inbox-filter.ts
deleted file mode 100644
index ee18d56e3..000000000
--- a/src/web/src/lib/inbox-filter.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import type { ApplicationOwner } from "./application-owner";
-const storageKey = (userId: string) => `alook:${userId}:inbox-filter-types`;
-
-export const INBOX_FILTER_TYPES = [
- "user_dm_message",
- "calendar_event",
- "email_notification",
-] as const;
-
-export type InboxFilterType = (typeof INBOX_FILTER_TYPES)[number];
-
-export const INBOX_FILTER_LABELS: Record<InboxFilterType, string> = {
- user_dm_message: "DM",
- calendar_event: "Calendar",
- email_notification: "Email",
-};
-
-export const DEFAULT_INBOX_TYPES: InboxFilterType[] = ["user_dm_message"];
-
-export const MANDATORY_INBOX_TYPES: InboxFilterType[] = ["user_dm_message"];
-
-export function readStoredInboxFilterTypes(userId: string): InboxFilterType[] {
- if (typeof window === "undefined") return DEFAULT_INBOX_TYPES;
- try {
- const raw = localStorage.getItem(storageKey(userId));
- if (!raw) return DEFAULT_INBOX_TYPES;
- const parsed = JSON.parse(raw) as string[];
- const valid = parsed.filter((t): t is InboxFilterType =>
- INBOX_FILTER_TYPES.includes(t as InboxFilterType),
- );
- if (valid.length === 0) return DEFAULT_INBOX_TYPES;
- for (const m of MANDATORY_INBOX_TYPES) {
- if (!valid.includes(m)) valid.unshift(m);
- }
- return valid;
- } catch {
- return DEFAULT_INBOX_TYPES;
- }
-}
-
-export function getInboxFilterTypes(owner: ApplicationOwner): InboxFilterType[] {
- return owner.preferences.get().inboxFilterTypes;
-}
-
-export function setInboxFilterTypes(owner: ApplicationOwner, types: InboxFilterType[]): void {
- if (!owner.lifecycle.get().active) return;
- const withMandatory = [...types];
- for (const m of MANDATORY_INBOX_TYPES) {
- if (!withMandatory.includes(m)) withMandatory.unshift(m);
- }
- owner.preferences.setState((state) => ({ ...state, inboxFilterTypes: withMandatory }));
- try { localStorage.setItem(storageKey(owner.userId), JSON.stringify(withMandatory)); } catch {}
-}
diff --git a/src/web/src/lib/mention-agents.test.ts b/src/web/src/lib/mention-agents.test.ts
deleted file mode 100644
index 107bd2957..000000000
--- a/src/web/src/lib/mention-agents.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { describe, it, expect } from "vitest";
-import type { Agent, AgentLink } from "@alook/shared";
-import { relatedAgentIdSet, filterAgentsByQuery, rankMentionAgents } from "./mention-agents";
-
-const agent = (id: string, name: string): Agent =>
- ({ id, name } as Agent);
-
-const link = (source: string, target: string): AgentLink =>
- ({ source_agent_id: source, target_agent_id: target } as AgentLink);
-
-describe("relatedAgentIdSet", () => {
- it("collects linked agents in both directions", () => {
- const links = [link("me", "alice"), link("bob", "me"), link("x", "y")];
- const set = relatedAgentIdSet(links, "me");
- expect([...set].sort()).toEqual(["alice", "bob"]);
- });
-
- it("returns empty when no links touch the current agent", () => {
- expect(relatedAgentIdSet([link("x", "y")], "me").size).toBe(0);
- });
-});
-
-describe("filterAgentsByQuery", () => {
- const list = [agent("1", "Alice"), agent("2", "Albert"), agent("3", "Bob"), agent("4", "Calbert")];
-
- it("returns the list unchanged for an empty query", () => {
- expect(filterAgentsByQuery(list, "")).toBe(list);
- });
-
- it("ranks prefix matches before substring matches", () => {
- // query "al": Alice/Albert start with it; Calbert only contains it
- const names = filterAgentsByQuery(list, "al").map((a) => a.name);
- expect(names).toEqual(["Alice", "Albert", "Calbert"]);
- });
-
- it("is case-insensitive", () => {
- expect(filterAgentsByQuery(list, "BOB").map((a) => a.name)).toEqual(["Bob"]);
- });
-});
-
-describe("rankMentionAgents", () => {
- const agents = [agent("alice", "Alice"), agent("bob", "Bob"), agent("carol", "Carol")];
- const links = [link("me", "carol")]; // carol is related to me
-
- it("puts related agents first, then others", () => {
- const out = rankMentionAgents(agents, links, "me", "").map((a) => a.name);
- expect(out[0]).toBe("Carol");
- expect(out.slice(1).sort()).toEqual(["Alice", "Bob"]);
- });
-
- it("applies the query within both groups", () => {
- const out = rankMentionAgents(
- [agent("ca", "Cara"), agent("co", "Cody"), agent("al", "Alan")],
- [link("me", "ca")],
- "me",
- "c",
- ).map((a) => a.name);
- // related first (Cara), then other matches (Cody); Alan filtered out
- expect(out).toEqual(["Cara", "Cody"]);
- });
-
- it("respects the limit", () => {
- const many = Array.from({ length: 30 }, (_, i) => agent(`a${i}`, `Agent${i}`));
- expect(rankMentionAgents(many, [], "me", "", 20)).toHaveLength(20);
- });
-});
diff --git a/src/web/src/lib/mention-agents.ts b/src/web/src/lib/mention-agents.ts
deleted file mode 100644
index df282cc4d..000000000
--- a/src/web/src/lib/mention-agents.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import type { Agent, AgentLink } from "@alook/shared"
-
-/**
- * Build the set of agent ids that are "related" to the current agent — i.e.
- * directly linked in either direction. Shared by the textarea mention popup
- * hook and the TipTap composer suggestion so both rank related agents first.
- */
-export function relatedAgentIdSet(
- agentLinks: AgentLink[],
- currentAgentId: string,
-): Set<string> {
- const ids = new Set<string>()
- for (const link of agentLinks) {
- if (link.source_agent_id === currentAgentId) ids.add(link.target_agent_id)
- if (link.target_agent_id === currentAgentId) ids.add(link.source_agent_id)
- }
- return ids
-}
-
-/**
- * Filter a list of agents by a query, ranking name-prefix matches before
- * substring matches. Empty query returns the list untouched (caller slices).
- */
-export function filterAgentsByQuery(list: Agent[], query: string): Agent[] {
- if (!query) return list
- const q = query.toLowerCase()
- const startsWith: Agent[] = []
- const includes: Agent[] = []
- for (const a of list) {
- const name = a.name.toLowerCase()
- if (name.startsWith(q)) startsWith.push(a)
- else if (name.includes(q)) includes.push(a)
- }
- return [...startsWith, ...includes]
-}
-
-/**
- * Produce the mention-suggestion order: related agents first (query-filtered),
- * then everyone else (query-filtered), capped at `limit` total. This is the
- * grouped order the TipTap composer feeds into its suggestion list.
- */
-export function rankMentionAgents(
- agents: Agent[],
- agentLinks: AgentLink[],
- currentAgentId: string,
- query: string,
- limit = 20,
-): Agent[] {
- const related = relatedAgentIdSet(agentLinks, currentAgentId)
- const inRelated: Agent[] = []
- const other: Agent[] = []
- for (const a of agents) {
- if (related.has(a.id)) inRelated.push(a)
- else other.push(a)
- }
- return [
- ...filterAgentsByQuery(inRelated, query),
- ...filterAgentsByQuery(other, query),
- ].slice(0, limit)
-}
diff --git a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts b/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts
index 2e1d1fc20..ef45a4d30 100644
--- a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts
+++ b/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts
@@ -186,14 +186,10 @@ describe("cleanupAuthenticatedNativeOauthResidue", () => {
])
})
- it("mounts only behind both authenticated layout gates", () => {
- const appLayout = readFileSync(new URL("../app/(app)/layout.tsx", import.meta.url), "utf8")
+ it("mounts only behind the authenticated Community layout gate", () => {
const communityLayout = readFileSync(new URL("../app/c/layout.tsx", import.meta.url), "utf8")
const communityClient = readFileSync(new URL("../app/c/community-layout-client.tsx", import.meta.url), "utf8")
- expect(appLayout.indexOf("if (!session) redirect")).toBeLessThan(
- appLayout.indexOf("<AuthenticatedNativeOauthCleanup />"),
- )
expect(communityLayout).toContain("await getSession()")
expect(communityClient.indexOf("if (!currentUser)")).toBeLessThan(
communityClient.indexOf("<AuthenticatedNativeOauthCleanup />"),
diff --git a/src/web/src/lib/observability/actions.ts b/src/web/src/lib/observability/actions.ts
index 8bb6186d2..82d3a2269 100644
--- a/src/web/src/lib/observability/actions.ts
+++ b/src/web/src/lib/observability/actions.ts
@@ -6,53 +6,18 @@ export const actionVariants = {
"checkout": "billing.checkout.start",
"portal": "billing.portal.open"
},
- "calendar.command": {
- "create": "calendar.event.create",
- "update": "calendar.event.update",
- "delete": "calendar.event.delete"
- },
"machine.command": {
"delete": "machine.delete",
"update": "machine.update"
},
- "workspace.settings.command": {
- "update": "workspace.settings.update",
- "delete": "workspace.delete"
- },
- "workspace.members.command": {
- "create-invite": "workspace.invite.create",
- "revoke-invite": "workspace.invite.revoke",
- "remove-member": "workspace.member.remove"
- },
"device.authorization.command": {
"approve": "device.authorization.approve",
"deny": "device.authorization.deny"
},
- "chat.control.command": {
- "thread": "chat.thread.create",
- "stop": "chat.task.stop"
- },
"account.deletion.command": {
"code": "account.deletion.code.request",
"delete": "account.delete"
},
- "email.account.command": {
- "create": "email.account.connect",
- "delete": "email.account.delete",
- "sync": "email.account.sync"
- },
- "agent.rail.command": {
- "pin": "agent.pin",
- "unpin": "agent.unpin",
- "reorder-pins": "agent.pins.reorder",
- "reorder-unpinned": "agent.list.reorder"
- },
- "workspace.channel.command": {
- "create": "workspace.channel.create",
- "rename": "workspace.channel.rename",
- "delete": "workspace.channel.delete",
- "reorder": "workspace.channel.reorder"
- },
"server.member.command": {
"role": "server.member.role.change",
"kick": "server.member.kick"
@@ -70,35 +35,6 @@ export const actionVariants = {
"add": "channel.member.add",
"remove": "channel.member.remove"
},
- "chat.session.command": {
- "nap": "chat.session.nap",
- "retry": "chat.task.retry"
- },
- "agent.permission.command": {
- "whitelist-add": "agent.whitelist.add",
- "whitelist-remove": "agent.whitelist.remove",
- "visibility": "agent.visibility.change",
- "grant": "agent.access.grant",
- "revoke": "agent.access.revoke"
- },
- "issue.command": {
- "comment": "issue.comment.create",
- "create": "issue.create",
- "update": "issue.update",
- "delete": "issue.delete"
- },
- "runtime.command": {
- "update": "runtime.update",
- "rescan": "runtime.rescan"
- },
- "agent.link.command": { "create": "agent.link.create", "update": "agent.link.update", "delete": "agent.link.delete" },
- "email.command": { "send": "email.send", "read": "email.read", "delete": "email.delete", "trust": "email.sender.trust" },
- "chat.command": { "persist": "chat.message.persist", "read": "chat.inbox.read" },
- "meeting.command": { "stop": "meeting.stop", "approve": "meeting.approve",
- "create": "meeting.create",
- "update": "meeting.update",
- "delete": "meeting.delete"
- }
} as const
export function resolveActionName(base: string, variables: unknown): string {
diff --git a/src/web/src/lib/observability/auth-client-observability.dom.test.tsx b/src/web/src/lib/observability/auth-client-observability.dom.test.tsx
index d9bb5e177..8739359f8 100644
--- a/src/web/src/lib/observability/auth-client-observability.dom.test.tsx
+++ b/src/web/src/lib/observability/auth-client-observability.dom.test.tsx
@@ -14,13 +14,13 @@ afterEach(async () => {
window.history.replaceState(null, "", "/")
vi.unstubAllEnvs(); vi.unstubAllGlobals()
})
-it("real auth and Application sign-out preserve failure/B ownership and clear only the current successful user's native metadata", async () => {
+it("real auth and community sign-out preserve failure/B ownership and clear only the current successful user's native metadata", async () => {
vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")
vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")
vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))
Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })
document.cookie = "alook_analytics_consent=v1.granted; path=/"
- window.history.replaceState(null, "", "/workspaces")
+ window.history.replaceState(null, "", "/c/me")
let selected: string | null = "account-a"
let mode: "fail" | "hold" | "success" = "fail"
let release!: (response: Response) => void
@@ -41,25 +41,26 @@ it("real auth and Application sign-out preserve failure/B ownership and clear on
throw new Error("Unexpected auth fixture path " + url.pathname)
})
const auth = await import("../auth-client")
- const Application = await import("../application-owner")
- const { useApplicationSignOut } = await import("@/hooks/use-application-sign-out")
+ const { QueryProvider } = await import("@/app/c/QueryProvider")
+ const { useOptionalCommunityDbRegistry } = await import("@/lib/community-db/projections")
+ const { useAccountSignOut } = await import("@/hooks/community/use-account-sign-out")
const { VolatileSessionsManager } = await import("@grafana/faro-web-sdk")
const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")
let logout!: () => Promise<boolean>
- let owner!: ReturnType<typeof Application.useApplicationOwner>
+ let owner!: NonNullable<ReturnType<typeof useOptionalCommunityDbRegistry>>
function Probe() {
- const current = Application.useApplicationOwner(), command = useApplicationSignOut()
+ const current = useOptionalCommunityDbRegistry()!, command = useAccountSignOut()
useLayoutEffect(() => { owner = current; logout = () => command.mutateAsync() }, [current, command])
return <p>Account content</p>
}
- function Root({ id }: { id: string }) { return <Application.ApplicationQueryProvider userId={id}><Probe /></Application.ApplicationQueryProvider> }
+ function Root({ id }: { id: string }) { return <QueryProvider userId={id}><Probe /></QueryProvider> }
await act(async () => { await import("@/instrumentation-client"); mounted = render(<Root id="account-a" />) })
await waitFor(() => expect(auth.currentSessionViewer()).toBe("account-a"))
await waitFor(() => expect(isTelemetryEligible()).toBe(true))
await waitFor(() => expect(sent.some(body => body.meta.user?.id === "account-a")).toBe(true), { timeout: 5000 })
const aSession = VolatileSessionsManager.fetchUserSession()!.sessionId
await act(async () => { await expect(logout()).rejects.toThrow("Auth failed") })
- expect(owner.lifecycle.get().active).toBe(true)
+ expect(owner.runtime.lifecycle.get().active).toBe(true)
expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(aSession)
mode = "hold"
let oldResult!: Promise<unknown>
@@ -68,12 +69,12 @@ it("real auth and Application sign-out preserve failure/B ownership and clear on
await act(async () => { const result = await auth.authClient.signIn.email({ email: "[email protected]", password: "fixture-password" }); expect(result.error).toBeNull() })
await waitFor(() => expect(auth.currentSessionViewer()).toBe("account-b"))
await act(async () => mounted!.rerender(<Root id="account-b" />))
- await waitFor(() => expect(owner.userId).toBe("account-b"))
+ await waitFor(() => expect(owner.accountId).toBe("account-b"))
await waitFor(() => expect(isTelemetryEligible()).toBe(true))
await waitFor(() => expect(VolatileSessionsManager.fetchUserSession()!.sessionId).not.toBe(aSession))
const bSession = VolatileSessionsManager.fetchUserSession()!.sessionId
await act(async () => { release(Response.json({ success: true })); expect(await oldResult).toMatchObject({ name: "AbortError" }) })
- expect(owner.lifecycle.get().active).toBe(true)
+ expect(owner.runtime.lifecycle.get().active).toBe(true)
expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(bSession)
emitTelemetry("business.result", { outcome: "success" })
await waitFor(() => expect(sent.some(body => body.meta.session.id === bSession && body.meta.user?.id === "account-b")).toBe(true), { timeout: 5000 })
diff --git a/src/web/src/lib/observability/client.ts b/src/web/src/lib/observability/client.ts
index e0ed2e2f7..942a3c8a6 100644
--- a/src/web/src/lib/observability/client.ts
+++ b/src/web/src/lib/observability/client.ts
@@ -67,8 +67,7 @@ async function activate() {
if (documentSuspended || !hasAnalyticsConsent() || !validBuildProfile(build)) return
const route = routeTemplate(window.location.href, window.location.origin)
const communityOwner = (route === "/c" || route.startsWith("/c/")) && resolveCommunityModulePlan(window.location.pathname).route !== "public-invite"
- const applicationOwner = route.startsWith("/w/") || ["/workspaces", "/studio/new", "/invite/[token]"].includes(route)
- if (!identityEstablished && (communityOwner || applicationOwner)) return
+ if (!identityEstablished && communityOwner) return
const mayResume = mayResumeNativeSession
sessionId = telemetryId()
configure()
diff --git a/src/web/src/lib/observability/context.test.ts b/src/web/src/lib/observability/context.test.ts
index bbad962de..9bea133c0 100644
--- a/src/web/src/lib/observability/context.test.ts
+++ b/src/web/src/lib/observability/context.test.ts
@@ -128,7 +128,7 @@ describe("original observation ownership", () => {
it("uses business enums and labels unsupported command kinds as a gap", () => {
expect(resolveActionName("billing.redirect", { action: { kind: "checkout", priceId: "PRIVATE" } })).toBe("billing.checkout.start")
expect(resolveActionName("bot.command", { input: { kind: "delete-command" } })).toBe("bot.delete")
- expect(resolveActionName("issue.command", { action: { kind: "comment" } })).toBe("issue.comment.create")
+ expect(resolveActionName("server.member.command", { action: { kind: "kick" } })).toBe("server.member.kick")
expect(resolveActionName("billing.redirect", { action: { kind: "PRIVATE" } })).toBe("command.unknown")
})
it("adopts a gesture into router transport on the same action without a duplicate start", () => {
diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.ts
index d7b2d5da2..276f26038 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -14,37 +14,14 @@ export const pageRoutes = [
"/c/me/machines",
"/c/onboarding-preview",
"/device",
- "/invite/[token]",
"/landing-legacy",
"/onboarding-preview",
"/pricing",
"/pricing-concept",
"/privacy",
"/sign-in",
- "/studio/new",
"/templates",
"/templates/[id]",
- "/w/[slug]",
- "/w/[slug]/agents",
- "/w/[slug]/agents/[id]",
- "/w/[slug]/agents/[id]/activity",
- "/w/[slug]/agents/[id]/chat",
- "/w/[slug]/agents/[id]/chat/[convId]",
- "/w/[slug]/agents/[id]/email",
- "/w/[slug]/agents/[id]/files",
- "/w/[slug]/agents/[id]/meetings",
- "/w/[slug]/agents/new",
- "/w/[slug]/calendar",
- "/w/[slug]/flags",
- "/w/[slug]/help/email-setup",
- "/w/[slug]/home",
- "/w/[slug]/issues",
- "/w/[slug]/runtimes",
- "/w/[slug]/settings",
- "/w/[slug]/traces",
- "/w/[slug]/traces/[traceId]",
- "/w/[slug]/unread",
- "/workspaces"
] as const
export const apiRoutes = [
@@ -305,22 +282,6 @@ export const actionNames = [
"account.deletion.code.request",
"account.deletion.command",
"account.sign_out",
- "agent.access.grant",
- "agent.access.revoke",
- "agent.create",
- "agent.instruction.save",
- "agent.link.command",
- "agent.list.reorder",
- "agent.permission.command",
- "agent.pin",
- "agent.pins.reorder",
- "agent.rail.command",
- "agent.task.retry",
- "agent.unpin",
- "agent.update",
- "agent.visibility.change",
- "agent.whitelist.add",
- "agent.whitelist.remove",
"attachment.download",
"attachment.prepare",
"attachment.upload",
@@ -344,10 +305,6 @@ export const actionNames = [
"bot.session.reset",
"bot.update",
"cache.clear",
- "calendar.command",
- "calendar.event.create",
- "calendar.event.delete",
- "calendar.event.update",
"category.create",
"category.delete",
"category.reorder",
@@ -365,14 +322,6 @@ export const actionNames = [
"channel.move",
"channel.rename",
"channel.reorder",
- "chat.command",
- "chat.control.command",
- "chat.message.send",
- "chat.session.command",
- "chat.session.nap",
- "chat.task.retry",
- "chat.task.stop",
- "chat.thread.create",
"command.unknown",
"community.command",
"community.onboarding.initialize",
@@ -381,38 +330,22 @@ export const actionNames = [
"device.authorization.deny",
"dm.message.send",
"dm.open",
- "email.account.command",
- "email.account.connect",
- "email.account.delete",
- "email.account.sync",
- "email.send",
"forum.tags.update",
"forum.thread.create",
"forum.thread.delete",
"inbox.read_all",
"invitation.copy",
"invitation.send",
- "issue.command",
- "issue.comment.create",
- "issue.create",
- "issue.delete",
- "issue.update",
"machine.agents.reset",
"machine.command",
"machine.delete",
"machine.pair.generate",
"machine.pair.launch",
"machine.update",
- "meeting.command",
- "meeting.create",
- "meeting.delete",
- "meeting.update",
"mention.dismiss",
"message.compose.send",
"message.edit",
"message.export",
- "message.flag.remove",
- "message.flag.toggle",
"message.mark",
"message.mark.command",
"message.pin",
@@ -426,15 +359,11 @@ export const actionNames = [
"message_send",
"navigation",
"notification.channel.update",
- "notification.permission.request",
"notification.server.update",
"notification.settings.command",
"profile.avatar.upload",
"profile.update",
"router_transition",
- "runtime.command",
- "runtime.rescan",
- "runtime.update",
"server.create",
"server.delete",
"server.icon.upload",
@@ -448,94 +377,21 @@ export const actionNames = [
"server.member.role.change",
"server.rail.reorder",
"server.update",
- "studio.agent.create",
- "studio.onboarding.finish",
"ui_interaction",
- "workspace.channel.command",
- "workspace.channel.create",
- "workspace.channel.delete",
- "workspace.channel.rename",
- "workspace.channel.reorder",
- "workspace.create",
- "workspace.delete",
- "workspace.instruction.save",
- "workspace.invite.accept",
- "workspace.invite.create",
- "workspace.invite.revoke",
- "workspace.member.remove",
- "workspace.members.command",
- "workspace.settings.command",
- "workspace.settings.update"
-, "agent.link.create", "agent.link.update", "agent.link.delete", "email.command", "email.read", "email.delete", "email.sender.trust", "chat.message.persist", "chat.inbox.read", "meeting.stop", "meeting.approve"
-, "friend.command", "friend.owner_decision.command", "friend.request.send", "friend.request.accept", "friend.request.reject", "friend.remove", "friend.request.cancel", "friend.request.approve", "friend.request.deny", "user.block", "user.unblock"
+ "friend.command",
+ "friend.owner_decision.command",
+ "friend.request.send",
+ "friend.request.accept",
+ "friend.request.reject",
+ "friend.remove",
+ "friend.request.cancel",
+ "friend.request.approve",
+ "friend.request.deny",
+ "user.block",
+ "user.unblock"
] as const
export const mutationCoverage = [
- {
- "file": "src/web/src/app/(app)/invite/[token]/page.tsx",
- "owner": "InvitePage",
- "action": "workspace.invite.accept"
- },
- {
- "file": "src/web/src/app/(app)/studio/new/client.tsx",
- "owner": "StudioOnboardingInner",
- "action": "studio.agent.create"
- },
- {
- "file": "src/web/src/app/(app)/studio/new/client.tsx",
- "owner": "StudioOnboardingInner",
- "action": "studio.onboarding.finish"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx",
- "owner": "ActivityRow",
- "action": "agent.task.retry"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx",
- "owner": "AgentEmailSurface",
- "action": "email.send"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/agents/new/page.tsx",
- "owner": "CreateAgentPage",
- "action": "agent.create"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/calendar/page.tsx",
- "owner": "CalendarPage",
- "action": "calendar.command"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/home/page.tsx",
- "owner": "AgentCanvas",
- "action": "agent.link.command"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx",
- "owner": "GeneralTab",
- "action": "workspace.settings.command"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx",
- "owner": "InstructionTab",
- "action": "workspace.instruction.save"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx",
- "owner": "MembersTab",
- "action": "workspace.members.command"
- },
- {
- "file": "src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx",
- "owner": "NotificationTab",
- "action": "notification.permission.request"
- },
- {
- "file": "src/web/src/app/(app)/workspaces/client.tsx",
- "owner": "WorkspaceListClient",
- "action": "workspace.create"
- },
{
"file": "src/web/src/app/c/invite/[token]/invite-accept-client.tsx",
"owner": "InviteAcceptInner",
@@ -546,16 +402,6 @@ export const mutationCoverage = [
"owner": "DeviceAuthPageInner",
"action": "device.authorization.command"
},
- {
- "file": "src/web/src/components/agent-chat/agent-chat-view.tsx",
- "owner": "AgentChatView",
- "action": "chat.control.command"
- },
- {
- "file": "src/web/src/components/agent-edit-form.tsx",
- "owner": "AgentEditForm",
- "action": "agent.instruction.save"
- },
{
"file": "src/web/src/components/community/machines/machine-list.tsx",
"owner": "MachineList",
@@ -626,26 +472,6 @@ export const mutationCoverage = [
"owner": "InviteDialog",
"action": "invitation.copy"
},
- {
- "file": "src/web/src/components/custom-email-form.tsx",
- "owner": "CustomEmailForm",
- "action": "email.account.command"
- },
- {
- "file": "src/web/src/contexts/agent-context.tsx",
- "owner": "useAgentContext",
- "action": "agent.update"
- },
- {
- "file": "src/web/src/contexts/agent-context.tsx",
- "owner": "useAgentContext",
- "action": "agent.rail.command"
- },
- {
- "file": "src/web/src/contexts/channel-context.tsx",
- "owner": "useChannel",
- "action": "workspace.channel.command"
- },
{
"file": "src/web/src/hooks/community/mutations/dm.ts",
"owner": "useCreateOrGetDm",
@@ -786,65 +612,10 @@ export const mutationCoverage = [
"owner": "useSetBotNotificationSetting",
"action": "bot.notification.update"
},
- {
- "file": "src/web/src/hooks/use-agent-chat.ts",
- "owner": "useAgentChat",
- "action": "chat.command"
- },
- {
- "file": "src/web/src/hooks/use-agent-chat.ts",
- "owner": "useAgentChat",
- "action": "chat.message.send"
- },
- {
- "file": "src/web/src/hooks/use-agent-chat.ts",
- "owner": "useAgentChat",
- "action": "chat.session.command"
- },
- {
- "file": "src/web/src/hooks/use-application-sign-out.ts",
- "owner": "useApplicationSignOut",
- "action": "account.sign_out"
- },
{
"file": "src/web/src/hooks/use-file-attachments.ts",
"owner": "useFileAttachments",
"action": "attachment.prepare"
- },
- {
- "file": "src/web/src/hooks/use-message-flags.ts",
- "owner": "useMessageFlags",
- "action": "message.flag.toggle"
- },
- {
- "file": "src/web/src/hooks/workspace/use-agent-permission-command.ts",
- "owner": "useAgentPermissionCommand",
- "action": "agent.permission.command"
- },
- {
- "file": "src/web/src/hooks/workspace/use-inbox.ts",
- "owner": "useMarkAllInboxRead",
- "action": "inbox.read_all"
- },
- {
- "file": "src/web/src/hooks/workspace/use-inbox.ts",
- "owner": "useUnflagWorkspaceMessage",
- "action": "message.flag.remove"
- },
- {
- "file": "src/web/src/hooks/workspace/use-issue-command.ts",
- "owner": "useIssueCommand",
- "action": "issue.command"
- },
- {
- "file": "src/web/src/hooks/workspace/use-runtime-command.ts",
- "owner": "useRuntimeCommand",
- "action": "runtime.command"
- },
- {
- "file": "src/web/src/hooks/workspace/use-workspace-meetings.ts",
- "owner": "useWorkspaceMeetings",
- "action": "meeting.command"
}
] as const
@@ -946,7 +717,10 @@ export const capabilityLimits = {
ssr_source: "server-rendered source unknown unless an explicit owner supplies evidence",
} as const
-const routeMatchers = [...pageRoutes, ...apiRoutes].sort((a,b) => b.split("/").length-a.split("/").length || b.split("/").filter(part => !part.startsWith("[")).length-a.split("/").filter(part => !part.startsWith("[")).length || a.localeCompare(b)).map(template => ({template, pattern:new RegExp("^" + template.split("/").map(part => part.startsWith("[...") ? ".+" : part.startsWith("[") ? "[^/]+" : part.replace(/[.*+?^$(){}|\\]/g, "\\$&")).join("/") + "/?$")}))
+const routeMatchers = [...pageRoutes, ...apiRoutes].sort((a,b) => b.split("/").length-a.split("/").length || b.split("/").filter(part => !part.startsWith("[")).length-a.split("/").filter(part => !part.startsWith("[")).length || a.localeCompare(b)).map(template => {
+ const pattern = template.split("/").slice(1).map(part => part.startsWith("[[...") ? "(?:/.*)?" : "/" + (part.startsWith("[...") ? ".+" : part.startsWith("[") ? "[^/]+" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))).join("")
+ return { template, pattern: new RegExp("^" + pattern + "/?$") }
+})
export function routeTemplate(input: string, origin = "https://alook.ai"): string {
try {
const url = new URL(input, origin)
diff --git a/src/web/src/lib/observability/provider-auth-null.dom.test.tsx b/src/web/src/lib/observability/provider-auth-null.dom.test.tsx
index 4e455c2d3..862b39b99 100644
--- a/src/web/src/lib/observability/provider-auth-null.dom.test.tsx
+++ b/src/web/src/lib/observability/provider-auth-null.dom.test.tsx
@@ -17,26 +17,27 @@ afterEach(async () => {
window.history.replaceState(null, "", "/")
vi.unstubAllEnvs(); vi.unstubAllGlobals()
})
-it("both actual account Providers retain pending/error and newer B, then retire telemetry on current confirmed SDK anonymous identity", async () => {
+it("public and community Providers retain pending/error and newer B, then retire telemetry on current confirmed SDK anonymous identity", async () => {
vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")
vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")
vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))
Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })
document.cookie = "alook_analytics_consent=v1.granted; path=/"
- window.history.replaceState(null, "", "/workspaces")
+ window.history.replaceState(null, "", "/pricing")
const sent: Array<{ meta: { session: { id: string }; user?: { id: string } } }> = []
vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => { if (init?.body) sent.push(JSON.parse(String(init.body))); return new Response(null, { status: 204 }) }))
const { bootstrapObservability } = await import("./client")
const { QueryProvider } = await import("@/app/c/QueryProvider")
- const { ApplicationQueryProvider } = await import("../application-owner")
+ const { PublicQueryProvider } = await import("../application-owner")
const { VolatileSessionsManager } = await import("@grafana/faro-web-sdk")
const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")
bootstrapObservability("web")
const known = (id: string): Identity => ({ data: { user: { id } }, isPending: false, error: null })
const restoring = new Map<string, boolean>()
function Probe({ id }: { id: string }) { const pending = useIsRestoring(); useLayoutEffect(() => { restoring.set(id, pending) }, [id, pending]); return <p>{id}</p> }
- for (const kind of ["application", "community"] as const) {
- const Provider = kind === "application" ? ApplicationQueryProvider : QueryProvider
+ function PublicProvider({ children }: { userId: string; children: React.ReactNode }) { return <PublicQueryProvider>{children}</PublicQueryProvider> }
+ for (const kind of ["public", "community"] as const) {
+ const Provider = kind === "public" ? PublicProvider : QueryProvider
function Root({ id, identity }: { id: string; identity: Identity }) { return <identityInput.Provider value={identity}><Provider userId={id}><Probe id={id} /></Provider></identityInput.Provider> }
const a = kind + "-a", b = kind + "-b"
viewer = a
diff --git a/src/web/src/lib/observability/regions.dom.test.tsx b/src/web/src/lib/observability/regions.dom.test.tsx
index 793f3f646..ec4de2326 100644
--- a/src/web/src/lib/observability/regions.dom.test.tsx
+++ b/src/web/src/lib/observability/regions.dom.test.tsx
@@ -12,13 +12,13 @@ vi.mock("next/navigation", () => ({ usePathname: () => "/", useSearchParams: ()
const events: Array<{ name: string; attributes: Record<string, string> }> = []
let client: QueryClient
async function emptyResponse() {
- const request = startRequest("/api/agents"), response = new Response("[]")
+ const request = startRequest("/api/community/bots"), response = new Response("[]")
requestHeaders(request, response)
return readObservedResponse(response, () => response.json()) as Promise<unknown[]>
}
function Panel({ name }: { name: string }) {
const resource = useQuery({ queryKey: [name], queryFn: emptyResponse })
- useObservedQueryRegion(name === "active" ? "files" : "settings", resource, resource.data?.length)
+ useObservedQueryRegion(name === "active" ? "messages" : "settings", resource, resource.data?.length)
return <p>{name}: {resource.isPending ? "loading" : "empty"}</p>
}
afterEach(async () => { await act(async () => { retireTelemetry(); clearActions(); disposeQueryDiagnostics(client); client.clear() }) })
@@ -29,7 +29,7 @@ it("observes actual settled empty Query values only after a retained Base UI pan
installTelemetrySink(event => events.push(event))
const view = render(<QueryClientProvider client={client}><Tabs defaultValue="active"><TabsList><TabsTrigger value="active">Active</TabsTrigger><TabsTrigger value="retained">Retained</TabsTrigger></TabsList><TabsContent value="active" keepMounted><Panel name="active" /></TabsContent><TabsContent value="retained" keepMounted><Panel name="retained" /></TabsContent></Tabs></QueryClientProvider>)
await waitFor(() => expect(client.getQueryData(["retained"])).toEqual([]))
- await waitFor(() => expect(events.filter(event => event.name === "region.ready_commit" && event.attributes.region === "files")).toHaveLength(1))
+ await waitFor(() => expect(events.filter(event => event.name === "region.ready_commit" && event.attributes.region === "messages")).toHaveLength(1))
expect(events.filter(event => event.name === "region.ready_commit" && event.attributes.region === "settings")).toHaveLength(0)
const empty = events.find(event => event.name === "region.ready_commit")!
expect(empty.attributes).toMatchObject({ row_count: "0", outcome: "empty", source: "network" })
diff --git a/src/web/src/lib/observability/sanitize.test.ts b/src/web/src/lib/observability/sanitize.test.ts
index 9dfcd1acd..9aec1d8aa 100644
--- a/src/web/src/lib/observability/sanitize.test.ts
+++ b/src/web/src/lib/observability/sanitize.test.ts
@@ -8,6 +8,9 @@ const origin = "https://alook.ai", session = "safe-session"
const meta = { sdk: { name: "faro-web", version: "2.12.1", integrations: [{ name: "SECRET", version: "SECRET" }] }, session: { id: session }, page: { url: origin + "/c/invite/SECRET?token=SECRET#SECRET" }, user: { email: "[email protected]", fullName: "SECRET" } }
describe("outbound whitelist", () => {
it("templates IDs, never exposes query or external arbitrary URLs", () => {
+ for (const path of ["/w/private/agents/a/chat/b?token=SECRET", "/w", "/workspaces", "/studio/new?token=SECRET", "/invite/SECRET"]) {
+ expect(routeTemplate(path, origin)).toBe("/unmapped")
+ }
expect(routeTemplate("/c/invite/SECRET?token=SECRET", origin)).toBe("/c/invite/[token]")
expect(routeTemplate("/api/community/messages/SECRET/reactions/PRIVATE", origin)).toBe("/api/community/messages/[id]/reactions/[emoji]")
expect(routeTemplate("https://private.example/SECRET", origin)).toBe("/external")
diff --git a/src/web/src/lib/observability/schema.ts b/src/web/src/lib/observability/schema.ts
index f735d5fe6..00780d5c3 100644
--- a/src/web/src/lib/observability/schema.ts
+++ b/src/web/src/lib/observability/schema.ts
@@ -26,7 +26,7 @@ const enumValues: Record<string, ReadonlySet<string>> = Object.fromEntries(Objec
request_reason: ["foreground", "background", "restore_invalidate", "pagination", "command", "router", "unknown"],
request_kind: ["api", "rsc", "resource", "document", "external", "unknown"],
method: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
- region: ["shell", "rail", "sidebar", "messages", "forum", "thread_opener", "friends", "bots", "machines", "members", "settings", "calendar", "billing", "workspaces", "files", "file_preview", "traces", "trace_detail", "agents", "issues", "email", "chat", "runtimes", "inbox", "activity", "meetings", "email_body", "issue_detail", "page"],
+ region: ["shell", "rail", "sidebar", "messages", "forum", "thread_opener", "friends", "bots", "machines", "members", "settings", "billing", "file_preview", "inbox", "page"],
visibility: ["visible", "hidden", "unknown"],
capability: ["available", "limited", "unavailable"],
drop_reason: ["early_queue_full", "transport_failure", "withdrawal", "account_switch", "stale_session", "sdk_load", "invalid_config", "unload_unknown"],
diff --git a/src/web/src/lib/query-persister.race.test.ts b/src/web/src/lib/query-persister.race.test.ts
index e7dd33a92..fec31b350 100644
--- a/src/web/src/lib/query-persister.race.test.ts
+++ b/src/web/src/lib/query-persister.race.test.ts
@@ -108,7 +108,7 @@ describe("qualified native owner disk retirement", () => {
const original = createIdbPersister("A")
await original.restoreClient()
await original.retireAccount()
- const fresh = createIdbPersister("A", "application")
+ const fresh = createIdbPersister("A")
await fresh.restoreClient()
await original.retireAccount()
expect(await fresh.isCurrent()).toBe(true)
diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.ts
index 586939406..549c3d169 100644
--- a/src/web/src/lib/query-persister.ts
+++ b/src/web/src/lib/query-persister.ts
@@ -1,7 +1,6 @@
import { clearLegacyChatCaches, getLegacyChatCacheSizeBytes } from "@/lib/legacy-chat-persistence"
import { observeRestoreRead, observeRestoreDecode } from "@/lib/observability/restore"
import { createStore as createNativeStore } from "@tanstack/store"
-import { scrubApplicationClient } from "@/lib/workspace-chat-persistence"
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"
import type {
PersistedClient,
@@ -246,7 +245,7 @@ function namespaceFor(userId: string | null): string {
}
/** Storage sub-key for the persister blob within a user's namespace. */
-export type PersistDomain = "community" | "application"
+type PersistDomain = "community" | "application"
export const CACHE_INVALIDATION_STORAGE_KEY = "alook:qc:invalidation"
export const cacheInvalidation = createNativeStore(0)
function publishCacheInvalidation() {
@@ -354,8 +353,8 @@ async function withEligiblePersister<T>(
}
/** Native TanStack persister, qualified against durable device/account epochs. */
-export function createIdbPersister(userId: string | null, domain: PersistDomain = "community"): QualifiedPersister {
- const key = blobKeyFor(userId, domain)
+export function createIdbPersister(userId: string | null): QualifiedPersister {
+ const key = blobKeyFor(userId)
const eligibility = qualifyPersister(key, userId)
// An unavailable IDB must also fail restore through the provider's onError;
// attach a handler immediately so qualification cannot reject unobserved.
@@ -376,8 +375,8 @@ export function createIdbPersister(userId: string | null, domain: PersistDomain
),
},
key: "alook-query-cache",
- serialize: (client) => JSON.stringify(domain === "application" ? scrubApplicationClient(client, userId) : scrubDehydratedClient(client, userId)),
- deserialize: (raw) => observeRestoreDecode(persister, () => domain === "application" ? scrubApplicationClient(JSON.parse(raw) as PersistedClient, userId) : scrubDehydratedClient(JSON.parse(raw) as PersistedClient, userId), domain === "application" ? PERSIST_BUSTER + "-application" : PERSIST_BUSTER, PERSIST_MAX_AGE_MS),
+ serialize: (client) => JSON.stringify(scrubDehydratedClient(client, userId)),
+ deserialize: (raw) => observeRestoreDecode(persister, () => scrubDehydratedClient(JSON.parse(raw) as PersistedClient, userId), PERSIST_BUSTER, PERSIST_MAX_AGE_MS),
})
return Object.assign(persister, {
isCurrent: () => withEligiblePersister(key, userId, eligibility, "readonly", false, async () => true),
diff --git a/src/web/src/lib/query-receipt.test.ts b/src/web/src/lib/query-receipt.test.ts
deleted file mode 100644
index e67bf50d8..000000000
--- a/src/web/src/lib/query-receipt.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { afterEach, describe, expect, it } from "vitest"
-import { QueryClient, QueryObserver, dehydrate, skipToken } from "@tanstack/react-query"
-import { captureQueryReceipt, withQueryReceipt, reconcileQueryReceipt } from "./query-receipt"
-
-const clients: QueryClient[] = []
-function client() {
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false, structuralSharing: reconcileQueryReceipt } } })
- clients.push(qc)
- return qc
-}
-afterEach(() => { for (const qc of clients.splice(0)) qc.clear() })
-
-describe("native Query final publication", () => {
- it.each(["changed", "equal", "aba"])("preserves a newer %s write after a held HTTP response", async (mode) => {
- const qc = client(), key = ["entity"]
- qc.setQueryData(key, { title: "before" })
- let finish!: (value: { title: string }) => void
- const response = new Promise<{ title: string }>((resolve) => { finish = resolve })
- const pending = qc.fetchQuery({ queryKey: key, queryFn: async () => {
- const receipt = captureQueryReceipt(qc, key)
- return withQueryReceipt(await response, receipt)
- } })
- qc.setQueryData(key, { title: "live" })
- if (mode === "equal") qc.setQueryData(key, { title: "live" })
- if (mode === "aba") qc.setQueryData(key, { title: "before" })
- finish({ title: "stale HTTP" })
- await pending
- expect(qc.getQueryData(key)).toEqual({ title: mode === "aba" ? "before" : "live" })
- })
-
- it("publishes current HTTP data and strips its publication metadata", async () => {
- const qc = client(), key = ["current"]
- await qc.fetchQuery({ queryKey: key, queryFn: async () => withQueryReceipt({ title: "HTTP" }, captureQueryReceipt(qc, key)) })
- expect(qc.getQueryData(key)).toEqual({ title: "HTTP" })
- expect(Object.getOwnPropertySymbols(qc.getQueryData(key)!)).toHaveLength(0)
- expect(JSON.stringify(dehydrate(qc))).toContain("HTTP")
- })
-
- it("does not publish into a recreated resource with the same key", () => {
- const qc = client(), key = ["recreated"]
- qc.setQueryData(key, { title: "old" })
- const receipt = captureQueryReceipt(qc, key)
- qc.removeQueries({ queryKey: key, exact: true })
- qc.setQueryData(key, { title: "replacement" })
- qc.setQueryData(key, withQueryReceipt({ title: "late" }, receipt))
- expect(qc.getQueryData(key)).toEqual({ title: "replacement" })
- })
-
- it("uses the domain merge at the native write boundary after a concurrent addition", async () => {
- const qc = client(), key = ["rows"]
- qc.setQueryData(key, [{ id: "same", value: "before" }])
- let finish!: () => void
- const response = new Promise<void>((resolve) => { finish = resolve })
- const pending = qc.fetchQuery({ queryKey: key, queryFn: async () => {
- const receipt = captureQueryReceipt(qc, key)
- await response
- return withQueryReceipt([{ id: "same", value: "stale" }, { id: "HTTP", value: "new" }], receipt,
- (previous, incoming) => [...new Map([...(incoming as Array<{ id: string }>), ...(previous as Array<{ id: string }>)].map((row) => [row.id, row])).values()])
- } })
- qc.setQueryData(key, [{ id: "same", value: "live" }, { id: "WS", value: "new" }])
- finish(); await pending
- expect(qc.getQueryData(key)).toEqual([{ id: "same", value: "live" }, { id: "HTTP", value: "new" }, { id: "WS", value: "new" }])
- })
-
- it("retains native defaults when a canonical display observer has no queryFn", () => {
- const qc = client(), key = ["display"]
- qc.setQueryDefaults(key, { structuralSharing: reconcileQueryReceipt })
- qc.setQueryData(key, { title: "old" })
- const receipt = captureQueryReceipt(qc, key)
- const observer = new QueryObserver(qc, { queryKey: key, queryFn: skipToken, enabled: false })
- const release = observer.subscribe(() => undefined)
- qc.setQueryData(key, { title: "live" })
- qc.setQueryData(key, withQueryReceipt({ title: "late" }, receipt))
- expect(observer.getCurrentResult().data).toEqual({ title: "live" })
- release(); observer.destroy()
- })
-})
diff --git a/src/web/src/lib/query-receipt.ts b/src/web/src/lib/query-receipt.ts
deleted file mode 100644
index 932daff56..000000000
--- a/src/web/src/lib/query-receipt.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { replaceEqualDeep, type Query, type QueryClient, type QueryKey } from "@tanstack/react-query"
-
-const publication = Symbol("native-query-publication")
-export type QueryReceipt = { client: QueryClient; queryKey: QueryKey; resource: Query | undefined; writes: number }
-
-export function captureQueryReceipt(client: QueryClient, queryKey: QueryKey): QueryReceipt {
- const resource = client.getQueryCache().find({ queryKey, exact: true })
- return { client, queryKey, resource, writes: resource?.state.dataUpdateCount ?? 0 }
-}
-export function isQueryReceiptCurrent(receipt: QueryReceipt) {
- const current = receipt.client.getQueryCache().find({ queryKey: receipt.queryKey, exact: true })
- return current === receipt.resource && (current?.state.dataUpdateCount ?? 0) === receipt.writes
-}
-export function withQueryReceipt<T extends object>(value: T, receipt: QueryReceipt, merge?: (previous: unknown, incoming: unknown) => unknown): T {
- const data = Array.isArray(value) ? [...value] : { ...value }
- Object.defineProperty(data, publication, { value: { receipt, merge } })
- return data as T
-}
-export function reconcileQueryReceipt(previous: unknown, incoming: unknown) {
- if (!incoming || typeof incoming !== "object") return replaceEqualDeep(previous, incoming)
- const proof = (incoming as { [publication]?: { receipt: QueryReceipt; merge?: (previous: unknown, incoming: unknown) => unknown } })[publication]
- if (!proof) return replaceEqualDeep(previous, incoming)
- const value = Array.isArray(incoming) ? [...incoming] : { ...incoming }
- if (isQueryReceiptCurrent(proof.receipt)) return replaceEqualDeep(previous, value)
- const resource = proof.receipt.client.getQueryCache().find({ queryKey: proof.receipt.queryKey, exact: true })
- if (resource !== proof.receipt.resource || !proof.merge) return previous
- return replaceEqualDeep(previous, proof.merge(previous, value))
-}
diff --git a/src/web/src/lib/runtime-display.test.ts b/src/web/src/lib/runtime-display.test.ts
deleted file mode 100644
index c2330d278..000000000
--- a/src/web/src/lib/runtime-display.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { runtimeDisplayName, GENERIC_RUNTIME_NAME } from "./runtime-display";
-
-describe("runtimeDisplayName", () => {
- it("maps known providers to friendly names", () => {
- expect(runtimeDisplayName("claude")).toBe("Claude Code");
- expect(runtimeDisplayName("codex")).toBe("Codex");
- expect(runtimeDisplayName("grok")).toBe("Grok Build");
- expect(runtimeDisplayName("opencode")).toBe("OpenCode");
- });
-
- it("falls back to the generic label for undefined / null", () => {
- expect(runtimeDisplayName(undefined)).toBe(GENERIC_RUNTIME_NAME);
- expect(runtimeDisplayName(null)).toBe(GENERIC_RUNTIME_NAME);
- expect(runtimeDisplayName("")).toBe(GENERIC_RUNTIME_NAME);
- });
-
- it("falls back to the generic label for unknown slugs", () => {
- expect(runtimeDisplayName("unknown-runtime")).toBe(GENERIC_RUNTIME_NAME);
- expect(runtimeDisplayName("CLAUDE")).toBe(GENERIC_RUNTIME_NAME); // case-sensitive by design
- });
-
- it("generic label reads as a sentence fragment", () => {
- expect(GENERIC_RUNTIME_NAME).toBe("the agent runtime");
- });
-});
diff --git a/src/web/src/lib/runtime-display.ts b/src/web/src/lib/runtime-display.ts
deleted file mode 100644
index c16afda6f..000000000
--- a/src/web/src/lib/runtime-display.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Friendly display names for agent-runtime providers.
- *
- * Used to attribute runtime errors in the chat UI so the user can see an error
- * came from the agent runtime CLI on their machine (Claude Code / Codex /
- * OpenCode) — not from Alook itself. See issue #236.
- */
-const PROVIDER_DISPLAY_NAMES: Record<string, string> = {
- claude: "Claude Code",
- codex: "Codex",
- grok: "Grok Build",
- opencode: "OpenCode",
-};
-
-/** Generic label when the provider is unknown / missing / legacy. */
-export const GENERIC_RUNTIME_NAME = "the agent runtime";
-
-export function runtimeDisplayName(provider?: string | null): string {
- if (!provider) return GENERIC_RUNTIME_NAME;
- return PROVIDER_DISPLAY_NAMES[provider] ?? GENERIC_RUNTIME_NAME;
-}
diff --git a/src/web/src/lib/safe-redirect.test.ts b/src/web/src/lib/safe-redirect.test.ts
index 42cefcd6d..ec39b78d6 100644
--- a/src/web/src/lib/safe-redirect.test.ts
+++ b/src/web/src/lib/safe-redirect.test.ts
@@ -7,6 +7,12 @@ describe("safe redirect paths", () => {
"/c/me/machines?tab=active",
"/sign-in?redirect=%2Fc%2Fme",
"/search?q=100%25",
+ "/w",
+ "/%77/sample/home?token=private",
+ "/w/sample/home?token=private",
+ "/workspaces",
+ "/studio/new?template=a&workspace_id=private",
+ "/invite/old-token",
])("accepts a local path: %s", (path) => {
expect(isSafeRedirectPath(path)).toBe(true);
expect(safeRedirectPath(path)).toBe(path);
@@ -29,4 +35,9 @@ describe("safe redirect paths", () => {
expect(isSafeRedirectPath(path)).toBe(false);
expect(safeRedirectPath(path)).toBe("/c/me");
});
+
+ it("retains the default and explicit fallback for missing return paths", () => {
+ expect(safeRedirectPath(null)).toBe("/c/me");
+ expect(safeRedirectPath(undefined, "/c/me/machines")).toBe("/c/me/machines");
+ });
});
diff --git a/src/web/src/lib/safe-redirect.ts b/src/web/src/lib/safe-redirect.ts
index 3f06d7602..de651ba3a 100644
--- a/src/web/src/lib/safe-redirect.ts
+++ b/src/web/src/lib/safe-redirect.ts
@@ -1,7 +1 @@
-import {
- isSafeRedirectPath as sharedIsSafeRedirectPath,
- safeRedirectPath as sharedSafeRedirectPath,
-} from "@alook/shared";
-
-export const isSafeRedirectPath = sharedIsSafeRedirectPath;
-export const safeRedirectPath = sharedSafeRedirectPath;
+export { isSafeRedirectPath, safeRedirectPath } from "@alook/shared";
diff --git a/src/web/src/lib/sdk-identity-retirement.dom.test.tsx b/src/web/src/lib/sdk-identity-retirement.dom.test.tsx
index 32f14aaaa..65e8cd400 100644
--- a/src/web/src/lib/sdk-identity-retirement.dom.test.tsx
+++ b/src/web/src/lib/sdk-identity-retirement.dom.test.tsx
@@ -5,7 +5,7 @@ import { QueryClient, useIsRestoring, useQueryClient } from "@tanstack/react-que
import { get, set } from "idb-keyval"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, render, waitFor } from "@/test/react-dom-harness"
-import { ApplicationQueryProvider, useApplicationOwner, type ApplicationOwner } from "./application-owner"
+import { PublicQueryProvider, useApplicationOwner, type ApplicationOwner } from "./application-owner"
import { QueryProvider } from "@/app/c/QueryProvider"
import { clearAllPersistedCaches, createIdbPersister } from "./query-persister"
import { getCommunityDbRegistry, type CommunityDbRegistry } from "./community-db/collections"
@@ -19,7 +19,7 @@ function AppProbe() { const restoring = useIsRestoring(); const current = useApp
function CommunityProbe() { const restoring = useIsRestoring(); const client = useQueryClient(); const current = getCommunityDbRegistry(client)!; useLayoutEffect(() => { community = current; clients.push(client) }); return <p data-restoring={String(restoring)}>Community</p> }
function Root({ kind, id, show = true }: { kind: "application" | "community"; id: string; show?: boolean }) {
if (!show) return <p>Other route</p>
- return kind === "application" ? <ApplicationQueryProvider userId={id}><AppProbe /></ApplicationQueryProvider> : <QueryProvider userId={id}><CommunityProbe /></QueryProvider>
+ return kind === "application" ? <PublicQueryProvider><AppProbe /></PublicQueryProvider> : <QueryProvider userId={id}><CommunityProbe /></QueryProvider>
}
const payload = { timestamp: Date.now(), buster: "v3", clientState: { queries: [], mutations: [] } }
beforeEach(async () => { await act(async () => { await clearAllPersistedCaches(); }) ; sdk.session = { data: { user: { id: "A" } }, isPending: false, error: null }; const real = window; vi.stubGlobal("window", new Proxy(real, { get: (target, key) => key === "location" ? { reload: vi.fn(), assign: vi.fn() } : Reflect.get(target, key, target) })) })
@@ -34,7 +34,7 @@ describe.each(["application", "community"] as const)("%s original public SDK ide
await waitFor(() => expect(kind === "application" ? application?.userId : community?.accountId).toBe("A"))
await waitFor(() => expect(view.getByText(kind === "application" ? "Application" : "Community")).toHaveAttribute("data-restoring", "false"))
const old = kind === "application" ? application : community
- const a = createIdbPersister("A"), b = createIdbPersister("B", "application")
+ const a = createIdbPersister("A"), b = createIdbPersister("B")
await act(async () => { await a.persistClient(payload); }) ; await act(async () => { await b.persistClient(payload); }) ; await act(async () => { await set("alook:qc:v2:A:client", "old A"); }) ; await act(async () => { await set("alook:qc:v2:B:client", "old B") })
sdk.session = { data: { user: { id: "B" } }, isPending: false, error: null }
await act(async () => view.rerender(<Root kind={kind} id="B" />))
diff --git a/src/web/src/lib/sdk-public-identity.dom.test.tsx b/src/web/src/lib/sdk-public-identity.dom.test.tsx
index db0184ee7..214146e55 100644
--- a/src/web/src/lib/sdk-public-identity.dom.test.tsx
+++ b/src/web/src/lib/sdk-public-identity.dom.test.tsx
@@ -38,12 +38,12 @@ beforeAll(async () => {
Community = await import("@/app/c/QueryProvider")
})
afterAll(() => { vi.unstubAllGlobals(); for (const owner of Object.values(owners)) owner.queryClient.clear() })
-function Probe({ kind }: { kind: string }) { const owner = Application.useApplicationOwner(); const pending = useIsRestoring(); useLayoutEffect(() => { owners[kind] = owner; restoring[kind] = pending }); return <output>{owner.userId}</output> }
+function Probe() { const owner = Application.useApplicationOwner(); const kind = owner.userId; const pending = useIsRestoring(); useLayoutEffect(() => { owners[kind] = owner; restoring[kind] = pending }); return <output>{owner.userId}</output> }
function CommunityProbe() { const current = getCommunityDbRegistry(useQueryClient())!; useLayoutEffect(() => { registry = current }); return <output>Community</output> }
-function Root({ id }: { id: string }) { return <Application.ApplicationQueryProvider userId={id}><Probe kind={id} /></Application.ApplicationQueryProvider> }
+function Root() { return <Application.PublicQueryProvider><Probe /></Application.PublicQueryProvider> }
describe("real BetterAuth public session input", () => {
it("public signIn.email updates real useSession and retires original account before B root mounts", async () => {
- const view = render(<Root id="A" />)
+ const view = render(<Root />)
await waitFor(() => expect(restoring.A).toBe(false))
await waitFor(() => expect(auth.authClient.$store.atoms.session.get()).toMatchObject({ isPending: false, error: null, data: { user: { id: "A" } } }))
const a = createIdbPersister("A"), b = createIdbPersister("B")
@@ -52,7 +52,7 @@ describe("real BetterAuth public session input", () => {
await waitFor(() => expect(owners.A.sessionViewer()).toBe("B"))
await waitFor(async () => expect(await a.isCurrent()).toBe(false))
expect(await get("alook:qc:v2:A:client")).toBeUndefined(); expect(await get("alook:qc:v2:B:client")).toBe("old B")
- await act(async () => view.rerender(<Root id="B" />))
+ await act(async () => view.rerender(<Root />))
await waitFor(() => expect(restoring.B).toBe(false))
await waitFor(() => expect(owners.B?.sessionViewer()).toBe("B")); expect(owners.B.lifecycle.get().active).toBe(true); expect(await b.isCurrent()).toBe(true)
})
diff --git a/src/web/src/lib/templates/types.ts b/src/web/src/lib/templates/types.ts
index b82e2db25..699314223 100644
--- a/src/web/src/lib/templates/types.ts
+++ b/src/web/src/lib/templates/types.ts
@@ -1,4 +1,13 @@
-import type { ScenarioMemberPreset, ScenarioId } from "@/components/studio-onboarding/scenario-presets";
+type ScenarioId = "software-dev" | "content-research" | "personal-assistant" | "sales-outreach" | "customer-support" | "custom";
+
+type MemberRole = "leader" | "researcher" | "engineer" | "assistant";
+
+interface ScenarioMemberPreset {
+ role: MemberRole;
+ description: string;
+ instructions: string;
+ relationship?: string;
+}
export type TemplateCategory = "Developer" | "Content Creator" | "Knowledge Worker" | "Freelancer";
diff --git a/src/web/src/lib/utils.ts b/src/web/src/lib/utils.ts
index f608f2678..3eae35590 100644
--- a/src/web/src/lib/utils.ts
+++ b/src/web/src/lib/utils.ts
@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
-import { resolveMode, cliCommand, updateCommand, daemonCommand, isTauri, isMobile, devWsDoPort, type AlookMode } from "@alook/shared"
+import { resolveMode, cliCommand, daemonCommand, isTauri, isMobile, devWsDoPort, type AlookMode } from "@alook/shared"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
@@ -47,7 +47,3 @@ export function cliCmd(): string {
export function daemonStartCmd(): string {
return daemonCommand(getMode())
}
-
-export function updateCmd(): string {
- return updateCommand(getMode())
-}
diff --git a/src/web/src/lib/workspace-chat-events.ts b/src/web/src/lib/workspace-chat-events.ts
deleted file mode 100644
index 1a6153656..000000000
--- a/src/web/src/lib/workspace-chat-events.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { TaskApi, TaskMessageResponse, WsMessage } from "@alook/shared"
-import { assertWorkspaceOwner, captureWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { appendCachedMessage, chatExtrasKey, type ChatExtras } from "./chat-cache"
-
-export function publishWorkspaceChatEvent(owner: WorkspaceOwner, message: WsMessage) {
- const token = captureWorkspaceOwner(owner)
- assertWorkspaceOwner(token)
- const qc = owner.queryClient
- if (message.type === "task.created") {
- const task = message.task as TaskApi
- qc.setQueryData(owner.key("chat", "task", task.id), task)
- qc.setQueryData(owner.key("chat", "active-task", message.conversationId), { id: task.id })
- } else if (message.type === "task.updated") {
- qc.setQueryData<TaskApi>(owner.key("chat", "task", message.taskId), (task) => task ? { ...task, status: message.status } : task)
- } else if (message.type === "task.messages") {
- qc.setQueryData<TaskMessageResponse[]>(owner.key("chat", "task-messages", message.taskId), (rows) => [...new Map([...(rows ?? []), ...message.messages].map((row) => [row.seq, row])).values()].sort((a, b) => a.seq - b.seq))
- } else if (message.type === "conversation.message") {
- void appendCachedMessage(message.conversationId, message.message, owner).catch(() => undefined)
- } else if (message.type === "artifact.uploaded") {
- qc.setQueryData<ChatExtras>(chatExtrasKey(owner, message.conversationId), (data) => ({ conversation: data?.conversation ?? null, artifacts: [...new Map([...(data?.artifacts ?? []), message.artifact].map((row) => [row.id, row])).values()], hasMoreArtifacts: data?.hasMoreArtifacts ?? false }))
- }
-}
diff --git a/src/web/src/lib/workspace-chat-flags.ts b/src/web/src/lib/workspace-chat-flags.ts
deleted file mode 100644
index d03bf0308..000000000
--- a/src/web/src/lib/workspace-chat-flags.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { replaceEqualDeep } from "@tanstack/react-query"
-
-export type ChatFlagsData = { ids: string[]; revision?: number; writes?: Record<string, { flagged: boolean; revision: number }>; requestRevision?: number }
-export function reconcileChatFlags(previous: unknown, incoming: unknown): unknown {
- const next = incoming as ChatFlagsData | undefined
- const old = previous as ChatFlagsData | undefined
- if (next?.requestRevision === undefined) return replaceEqualDeep(previous, incoming)
- const { requestRevision, ...data } = next
- const ids = new Set(data.ids)
- const writes: NonNullable<ChatFlagsData["writes"]> = {}
- for (const [id, write] of Object.entries(old?.writes ?? {})) {
- if (write.revision <= requestRevision) continue
- if (write.flagged) ids.add(id); else ids.delete(id)
- writes[id] = write
- }
- return replaceEqualDeep(previous, { ...data, ids: [...ids], revision: old?.revision ?? 0, writes })
-}
diff --git a/src/web/src/lib/workspace-chat-load.test.ts b/src/web/src/lib/workspace-chat-load.test.ts
deleted file mode 100644
index 80b14c54c..000000000
--- a/src/web/src/lib/workspace-chat-load.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { afterEach, describe, expect, it } from "vitest"
-import type { Conversation, Message, TaskApi, WsMessage } from "@alook/shared"
-import { createApplicationOwner } from "./application-owner"
-import { createWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import { captureChatLoad, settleChatLoad } from "./workspace-chat-load"
-import { publishWorkspaceChatEvent } from "./workspace-chat-events"
-import { chatExtrasKey, chatMessagesKey, sortedChatMessages, type ChatExtras, mergeCachedMessages } from "./chat-cache"
-
-const owners: WorkspaceOwner[] = []
-function owner() { const value = createWorkspaceOwner(createApplicationOwner("viewer"), "workspace", "workspace"); owners.push(value); return value }
-const conversation: Conversation = { id: "conv", agent_id: "agent", title: "conversation", type: "agent_chat", channel: "general", created_at: "2026-10-01T00:00:00Z" }
-const message: Message = { id: "message", conversation_id: "conv", role: "assistant", content: "HTTP", task_id: "task", attachment_ids: null, created_at: "2026-10-01T00:00:01Z" }
-const task: TaskApi = { id: "task", agent_id: "agent", runtime_id: "runtime", conversation_id: "conv", workspace_id: "workspace", prompt: "hello", status: "queued", priority: 0, dispatched_at: null, started_at: null, completed_at: null, result: null, error: null, created_at: "2026-10-01T00:00:00Z", type: "chat" }
-const response = () => ({ conversation, artifacts: [], active_task: task, task_messages: [], messages: [message], has_more_messages: false, has_more_artifacts: false })
-afterEach(() => { for (const value of owners.splice(0)) value.queryClient.clear() })
-
-describe("canonical chat load and central workspace WS", () => {
- it("retains a message and task updated by WS while the init response is held", async () => {
- const value = owner(), qc = value.queryClient
- qc.setQueryData(value.key("chat", "task", "task"), task)
- qc.setQueryData(chatExtrasKey(value, "conv"), { conversation, artifacts: [], hasMoreArtifacts: false } satisfies ChatExtras)
- await mergeCachedMessages("conv", [message], false, value)
- const tickets = captureChatLoad(value)
- publishWorkspaceChatEvent(value, { type: "conversation.message", conversationId: "conv", message: { ...message, content: "new WS" } } as WsMessage)
- publishWorkspaceChatEvent(value, { type: "task.updated", taskId: "task", status: "completed" } as WsMessage)
- const result = settleChatLoad(value, response(), tickets)
- expect(result.messages).toMatchObject([{ content: "new WS" }])
- expect(result.active_task?.status).toBe("completed")
- expect(sortedChatMessages(qc.getQueryData(chatMessagesKey(value, "conv")))).toMatchObject([{ content: "new WS" }])
- })
-
- it("publishes WS into canonical resources even before a chat panel opens", () => {
- const value = owner(), tickets = captureChatLoad(value)
- publishWorkspaceChatEvent(value, { type: "task.created", conversationId: "conv", task: { ...task, status: "running" } } as WsMessage)
- publishWorkspaceChatEvent(value, { type: "conversation.message", conversationId: "conv", message: { ...message, content: "first WS" } } as WsMessage)
- const result = settleChatLoad(value, response(), tickets)
- expect(result.active_task?.status).toBe("running")
- expect(result.messages).toMatchObject([{ content: "first WS" }])
- })
-
- it("does not overwrite a recreated conversation or task resource", async () => {
- const value = owner(), qc = value.queryClient
- qc.setQueryData(chatExtrasKey(value, "conv"), { conversation, artifacts: [], hasMoreArtifacts: false })
- qc.setQueryData(value.key("chat", "task", "task"), task)
- await mergeCachedMessages("conv", [message], false, value)
- const tickets = captureChatLoad(value)
- qc.removeQueries({ queryKey: value.key("chat") })
- qc.setQueryData(chatExtrasKey(value, "conv"), { conversation: { ...conversation, title: "replacement" }, artifacts: [], hasMoreArtifacts: false })
- qc.setQueryData(value.key("chat", "task", "task"), { ...task, status: "failed" })
- await mergeCachedMessages("conv", [{ ...message, content: "replacement" }], false, value)
- settleChatLoad(value, response(), tickets)
- expect(qc.getQueryData<ChatExtras>(chatExtrasKey(value, "conv"))?.conversation?.title).toBe("replacement")
- expect(qc.getQueryData<TaskApi>(value.key("chat", "task", "task"))?.status).toBe("failed")
- expect(sortedChatMessages(qc.getQueryData(chatMessagesKey(value, "conv")))[0].content).toBe("replacement")
- })
-})
diff --git a/src/web/src/lib/workspace-chat-load.ts b/src/web/src/lib/workspace-chat-load.ts
deleted file mode 100644
index 55c5bc490..000000000
--- a/src/web/src/lib/workspace-chat-load.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { Artifact, Conversation, Message, TaskApi, TaskMessageResponse } from "@alook/shared"
-import type { WorkspaceOwner } from "@/contexts/workspace-context"
-import { captureQueryReceipt, isQueryReceiptCurrent } from "./query-receipt"
-import { chatExtrasKey, chatMessagesKey, mergeCachedMessages, sortedChatMessages, type ChatExtras, type ChatMessagesData } from "./chat-cache"
-
-export function captureChatLoad(owner: WorkspaceOwner) {
- return new Map(owner.queryClient.getQueryCache().findAll({ queryKey: owner.key("chat") }).map((query) => [JSON.stringify(query.queryKey), { receipt: captureQueryReceipt(owner.queryClient, query.queryKey), liveRevision: (query.state.data as ChatMessagesData | undefined)?.liveRevision ?? 0 }]))
-}
-type ChatLoad = { conversation: Conversation; artifacts: Artifact[]; active_task: TaskApi | null; task_messages: TaskMessageResponse[]; messages?: Message[] | null; has_more_messages: boolean; has_more_artifacts: boolean; root_message?: Message | null }
-export function settleChatLoad<T extends ChatLoad>(owner: WorkspaceOwner, data: T, tickets: ReturnType<typeof captureChatLoad>): T {
- const qc = owner.queryClient, id = data.conversation.id
- const eligible = (key: readonly unknown[]) => {
- const ticket = tickets.get(JSON.stringify(key))?.receipt
- return ticket ? isQueryReceiptCurrent(ticket) : !qc.getQueryCache().find({ queryKey: key, exact: true })
- }
- const extrasKey = chatExtrasKey(owner, id)
- const currentExtras = qc.getQueryData<ChatExtras>(extrasKey)
- const originalExtras = tickets.get(JSON.stringify(extrasKey))?.receipt.resource
- const sameExtras = originalExtras ? qc.getQueryCache().find({ queryKey: extrasKey, exact: true }) === originalExtras : !currentExtras || !currentExtras.conversation
- const extrasEligible = eligible(extrasKey)
- if (sameExtras) qc.setQueryData<ChatExtras>(extrasKey, (current) => extrasEligible
- ? { conversation: data.conversation, artifacts: data.artifacts, hasMoreArtifacts: data.has_more_artifacts }
- : { conversation: current?.conversation ?? data.conversation, artifacts: [...new Map([...data.artifacts, ...(current?.artifacts ?? [])].map((row) => [row.id, row])).values()], hasMoreArtifacts: current?.hasMoreArtifacts ?? data.has_more_artifacts })
- const messagesKey = chatMessagesKey(owner, id), currentMessages = qc.getQueryData<ChatMessagesData>(messagesKey)
- const messageTicket = tickets.get(JSON.stringify(messagesKey))
- const originalMessages = messageTicket?.receipt.resource
- const sameMessages = originalMessages ? qc.getQueryCache().find({ queryKey: messagesKey, exact: true }) === originalMessages : !currentMessages || (currentMessages.liveRevision ?? 0) > 0
- if (data.messages && sameMessages) {
- const rows = data.messages.filter((row) => (currentMessages?.liveMessageRevisions?.[row.id] ?? 0) <= (messageTicket?.liveRevision ?? 0))
- void mergeCachedMessages(id, rows, data.has_more_messages, owner).catch(() => undefined)
- }
- if (data.active_task) {
- const key = owner.key("chat", "task", data.active_task.id)
- if (eligible(key)) qc.setQueryData(key, data.active_task)
- const messagesKey = owner.key("chat", "task-messages", data.active_task.id)
- if (eligible(messagesKey)) qc.setQueryData(messagesKey, data.task_messages)
- else {
- const ticket = tickets.get(JSON.stringify(messagesKey))?.receipt
- if (!ticket || qc.getQueryCache().find({ queryKey: messagesKey, exact: true }) === ticket.resource) qc.setQueryData<TaskMessageResponse[]>(messagesKey, (rows) => [...new Map([...data.task_messages, ...(rows ?? [])].map((row) => [row.seq, row])).values()].sort((a, b) => a.seq - b.seq))
- }
- }
- if (data.root_message) {
- const root = data.root_message, key = chatMessagesKey(owner, root.conversation_id)
- const ticket = tickets.get(JSON.stringify(key)), current = qc.getQueryData<ChatMessagesData>(key)
- const original = ticket?.receipt.resource
- if ((!original || qc.getQueryCache().find({ queryKey: key, exact: true }) === original) && (current?.liveMessageRevisions?.[root.id] ?? 0) <= (ticket?.liveRevision ?? 0)) void mergeCachedMessages(root.conversation_id, [root], null, owner).catch(() => undefined)
- }
- const activeKey = owner.key("chat", "active-task", id)
- if (eligible(activeKey)) qc.setQueryData(activeKey, { id: data.active_task?.id ?? null })
- const activeId = qc.getQueryData<{ id: string | null }>(activeKey)?.id
- const extras = qc.getQueryData<ChatExtras>(extrasKey)
- const messages = new Map(sortedChatMessages(qc.getQueryData<ChatMessagesData>(messagesKey)).map((row) => [row.id, row]))
- return { ...data, conversation: extras?.conversation ?? data.conversation, artifacts: extras?.artifacts ?? [], has_more_artifacts: extras?.hasMoreArtifacts ?? false,
- messages: data.messages?.flatMap((row) => messages.get(row.id) ?? []), active_task: activeId ? qc.getQueryData<TaskApi>(owner.key("chat", "task", activeId)) ?? null : null,
- task_messages: activeId ? qc.getQueryData<TaskMessageResponse[]>(owner.key("chat", "task-messages", activeId)) ?? [] : [],
- }
-}
diff --git a/src/web/src/lib/workspace-chat-persistence.test.ts b/src/web/src/lib/workspace-chat-persistence.test.ts
deleted file mode 100644
index a577c28e6..000000000
--- a/src/web/src/lib/workspace-chat-persistence.test.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import "fake-indexeddb/auto"
-import { QueryClient, dehydrate, hydrate } from "@tanstack/react-query"
-import { persistQueryClientSave } from "@tanstack/react-query-persist-client"
-import { describe, expect, it } from "vitest"
-import { createIdbPersister, clearPersistedCache, clearAllPersistedCaches, PERSIST_BUSTER } from "./query-persister"
-import { createApplicationOwner } from "./application-owner"
-import { createWorkspaceOwner } from "@/contexts/workspace-context"
-import { chatMessagesKey, chatExtrasKey, chatLatestKey, mergeCachedMessages, setConvExtras, setLastOpenConversation, getCachedMessages, getConvExtras } from "./chat-cache"
-import { MAX_WORKSPACE_CACHED_CONVERSATIONS, MAX_WORKSPACE_CACHED_MESSAGES, shouldPersistApplicationQuery, scrubApplicationClient } from "./workspace-chat-persistence"
-import { communityKeys } from "./query-keys"
-
-function owner(user: string, workspace = "workspace") { return createWorkspaceOwner(createApplicationOwner(user), workspace, workspace) }
-function message(id: string, conversation = "conv") { return { id, conversation_id: conversation, role: "user" as const, content: id, task_id: null, attachment_ids: null, created_at: new Date(Date.UTC(2026, 9, 1, 0, Number(id))).toISOString() } }
-async function seed(workspace: ReturnType<typeof owner>, conversation = "conv") {
- await mergeCachedMessages(conversation, [message("1", conversation)], false, workspace, 1)
- await setConvExtras(conversation, { artifacts: [], conversation_type: "agent_chat", conversation_title: "Title", conversation_channel: "general", conversation_created_at: "2026-10-01T00:00:00Z", hasMoreArtifacts: false }, workspace)
- await setLastOpenConversation("agent", "general", { conversation_id: conversation, newestMessageId: "1", serverMessageCount: 1 }, workspace)
-}
-async function save(queryClient: QueryClient, persister: ReturnType<typeof createIdbPersister>, application = false) {
- await persistQueryClientSave({ queryClient, persister, buster: PERSIST_BUSTER, dehydrateOptions: { shouldDehydrateQuery: (q) => !application || shouldPersistApplicationQuery(q.queryKey) } })
-}
-
-describe("independent native payloads and shared original account eligibility", () => {
- it("two real clients save and restore their own warm facts without replacing the other payload", async () => {
- const user = "two-domains"
- await clearPersistedCache(user)
- const workspace = owner(user)
- await seed(workspace)
- const community = new QueryClient()
- community.setQueryData(communityKeys.communityDbCollection(user, "servers"), [{ id: "server", name: "Server", icon: null, position: 0, discriminator: "1234", description: "", official: false, isOwner: true, unread: false, mentions: 0, ownerId: user }])
- const app = createIdbPersister(user, "application")
- const social = createIdbPersister(user)
- await save(workspace.queryClient, app, true)
- await save(community, social)
- const restoredApp = owner(user)
- const appPayload = await createIdbPersister(user, "application").restoreClient()
- expect(appPayload?.clientState.queries).toHaveLength(3)
- hydrate(restoredApp.queryClient, appPayload!.clientState)
- const restoredCommunity = new QueryClient()
- const socialPayload = await createIdbPersister(user).restoreClient()
- hydrate(restoredCommunity, socialPayload!.clientState)
- expect(await getCachedMessages("conv", restoredApp)).toHaveLength(1)
- expect(await getConvExtras("conv", restoredApp)).toMatchObject({ conversation_title: "Title" })
- expect(restoredCommunity.getQueryData(communityKeys.communityDbCollection(user, "servers"))).toMatchObject([{ id: "server" }])
- expect(restoredApp.queryClient.getQueryData(communityKeys.communityDbCollection(user, "servers"))).toBeUndefined()
- await clearPersistedCache(user)
- await save(workspace.queryClient, app, true)
- await save(community, social)
- expect(await createIdbPersister(user, "application").restoreClient()).toBeUndefined()
- expect(await createIdbPersister(user).restoreClient()).toBeUndefined()
- for (const client of [workspace.queryClient, community, restoredApp.queryClient, restoredCommunity]) client.clear()
- })
-
- it.each(["account", "device"])("%s clear fences both original writers before their first payload", async (scope) => {
- const user = `unwritten-${scope}`
- const a = createIdbPersister(user, "application"), c = createIdbPersister(user)
- await Promise.all([a.restoreClient(), c.restoreClient()])
- if (scope === "account") await clearPersistedCache(user)
- else await clearAllPersistedCaches()
- const blank = { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(new QueryClient()) }
- await Promise.all([a.persistClient(blank), c.persistClient(blank)])
- expect(await createIdbPersister(user, "application").restoreClient()).toBeUndefined()
- expect(await createIdbPersister(user).restoreClient()).toBeUndefined()
- })
-
- it("bounds workspace restore and removes dangling cards/pointers while keeping the live cache intact", async () => {
- const workspace = owner("bounded-workspace")
- for (let i = 0; i < MAX_WORKSPACE_CACHED_CONVERSATIONS + 2; i++) {
- const id = `conv-${i}`
- await seed(workspace, id)
- for (const key of [chatMessagesKey(workspace, id), chatExtrasKey(workspace, id)]) {
- const data = workspace.queryClient.getQueryData(key)
- workspace.queryClient.setQueryData(key, data, { updatedAt: i + 1 })
- }
- }
- await mergeCachedMessages("conv-51", Array.from({ length: MAX_WORKSPACE_CACHED_MESSAGES + 5 }, (_, i) => message(String(i), "conv-51")), false, workspace)
- await setLastOpenConversation("agent", "old-channel", { conversation_id: "conv-0", newestMessageId: "1", serverMessageCount: 1 }, workspace)
- const persister = createIdbPersister(workspace.application.userId, "application")
- await save(workspace.queryClient, persister, true)
- const fresh = owner(workspace.application.userId)
- hydrate(fresh.queryClient, (await persister.restoreClient())!.clientState)
- expect(await getCachedMessages("conv-0", fresh)).toBeNull()
- expect(await getConvExtras("conv-0", fresh)).toBeNull()
- expect(fresh.queryClient.getQueryData(chatLatestKey(fresh, "agent", "old-channel"))).toBeUndefined()
- expect(await getCachedMessages("conv-51", fresh)).toHaveLength(MAX_WORKSPACE_CACHED_MESSAGES)
- expect((fresh.queryClient.getQueryData(chatMessagesKey(fresh, "conv-51")) as { pages: Array<{ hasMore: boolean }> }).pages[0].hasMore).toBe(true)
- expect(await getCachedMessages("conv-51", workspace)).toHaveLength(MAX_WORKSPACE_CACHED_MESSAGES + 5)
- expect(fresh.queryClient.getQueryData(chatLatestKey(fresh, "agent", "general"))).toMatchObject({ conversation_id: "conv-51" })
- workspace.queryClient.clear(); fresh.queryClient.clear()
- })
-
- it.each(["attachments", "page", "count"])("rejects the entire incomplete message snapshot: %s", async (damage) => {
- const workspace = owner(`damaged-${damage}`)
- await seed(workspace)
- const key = chatMessagesKey(workspace, "conv")
- const data = workspace.queryClient.getQueryData(key) as { pages: Array<{ messages: unknown[]; hasMore: boolean }>; serverMessageCount: number }
- if (damage === "attachments") data.pages[0].messages.push({ ...message("2"), attachment_ids: [123] })
- if (damage === "page") data.pages.push({ messages: null, hasMore: false } as never)
- if (damage === "count") data.serverMessageCount = -1
- const scrubbed = scrubApplicationClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(workspace.queryClient) }, workspace.application.userId)
- expect(scrubbed.clientState.queries.some((query) => JSON.stringify(query.queryKey) === JSON.stringify(key))).toBe(false)
- workspace.queryClient.clear()
- })
-
- it("drops an incomplete Artifact and marks the card list incomplete", async () => {
- const workspace = owner("damaged-artifact")
- await seed(workspace)
- const key = chatExtrasKey(workspace, "conv")
- workspace.queryClient.setQueryData(key, (data: { conversation: unknown; artifacts: unknown[] }) => ({ ...data, artifacts: [{ id: "artifact", conversation_id: "conv", filename: "bad.pdf", content_type: "application/pdf" }], hasMoreArtifacts: false }))
- const scrubbed = scrubApplicationClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(workspace.queryClient) }, workspace.application.userId)
- expect(scrubbed.clientState.queries.find((query) => JSON.stringify(query.queryKey) === JSON.stringify(key))?.state.data).toMatchObject({ artifacts: [], hasMoreArtifacts: true })
- workspace.queryClient.clear()
- })
-
- it("rejects foreign account snapshots in the application payload", async () => {
- const foreign = owner("foreign-account")
- await seed(foreign)
- const persister = createIdbPersister("current-account", "application")
- await save(foreign.queryClient, persister, true)
- expect((await persister.restoreClient())?.clientState.queries).toHaveLength(0)
- foreign.queryClient.clear()
- })
-})
diff --git a/src/web/src/lib/workspace-chat-persistence.ts b/src/web/src/lib/workspace-chat-persistence.ts
deleted file mode 100644
index 4a3b9a3dd..000000000
--- a/src/web/src/lib/workspace-chat-persistence.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { cachedMessageSchema, cachedArtifactSchema, cachedConversationSchema } from "./workspace-chat-wire"
-import type { PersistedClient } from "@tanstack/react-query-persist-client"
-import type { ChatExtras, ChatMessagesData } from "@/lib/chat-cache"
-
-export const MAX_WORKSPACE_CACHED_CONVERSATIONS = 50
-export const MAX_WORKSPACE_CACHED_MESSAGES = 200
-export function shouldPersistApplicationQuery(key: readonly unknown[]) {
- return key[0] === "application" && typeof key[1] === "string" && key[2] === "workspace" && typeof key[3] === "string" && key[4] === "chat" && (
- key.length === 7 && (key[5] === "messages" || key[5] === "extras") && typeof key[6] === "string" && key[6] !== "__none__"
- || key.length === 8 && key[5] === "latest-created" && typeof key[6] === "string" && typeof key[7] === "string"
- )
-}
-export function scrubApplicationClient(client: PersistedClient, userId: string | null): PersistedClient {
- const candidates = client.clientState.queries.filter((query) => userId && query.queryKey[1] === userId && shouldPersistApplicationQuery(query.queryKey))
- const retained = new Set<string>()
- const counts = new Map<string, number>()
- for (const query of candidates.slice().sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt)) {
- if (query.queryKey[5] === "latest-created") continue
- const workspace = String(query.queryKey[3])
- const id = `${workspace}:${query.queryKey[6]}`
- if (retained.has(id)) continue
- const count = counts.get(workspace) ?? 0
- if (count >= MAX_WORKSPACE_CACHED_CONVERSATIONS) continue
- retained.add(id)
- counts.set(workspace, count + 1)
- }
- const queries: typeof client.clientState.queries = []
- for (const query of candidates) {
- const key = query.queryKey
- const id = `${key[3]}:${key[6]}`
- if (key[5] === "messages" && retained.has(id)) {
- const data = query.state.data as ChatMessagesData | undefined
- if (!data || !Array.isArray(data.pages) || !Number.isInteger(data.serverMessageCount) || data.serverMessageCount < 0) continue
- let corrupt = false
- const byId = new Map<string, ChatMessagesData["pages"][number]["messages"][number]>()
- for (const page of data.pages) {
- if (!page || !Array.isArray(page.messages) || typeof page.hasMore !== "boolean") { corrupt = true; continue }
- for (const row of page.messages) {
- const parsed = cachedMessageSchema.safeParse(row)
- if (!parsed.success || parsed.data.conversation_id !== key[6] || parsed.data.id.startsWith("temp-")) { corrupt = true; continue }
- byId.set(parsed.data.id, parsed.data)
- }
- }
- if (corrupt) continue
- const all = [...byId.values()].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id))
- const messages = all.slice(-MAX_WORKSPACE_CACHED_MESSAGES)
- const bounded: ChatMessagesData = { pages: [{ messages, hasMore: all.length > messages.length || data.pages.at(-1)?.hasMore === true }], pageParams: [null], serverMessageCount: data.serverMessageCount }
- queries.push({ ...query, state: { ...query.state, data: bounded } })
- } else if (key[5] === "extras" && retained.has(id)) {
- const data = query.state.data as ChatExtras | undefined
- const conversation = cachedConversationSchema.safeParse(data?.conversation)
- if (!data || !conversation.success || conversation.data.id !== key[6] || !Array.isArray(data.artifacts)) continue
- const artifacts = data.artifacts.flatMap((row) => {
- const parsed = cachedArtifactSchema.safeParse(row)
- return parsed.success && parsed.data.conversation_id === key[6] ? [parsed.data] : []
- })
- queries.push({ ...query, state: { ...query.state, data: { conversation: conversation.data, artifacts, hasMoreArtifacts: artifacts.length < data.artifacts.length || data.hasMoreArtifacts === true } satisfies ChatExtras } })
- } else if (key[5] === "latest-created") {
- const data = query.state.data as { conversation_id?: string; serverMessageCount?: number; newestMessageId?: string | null } | undefined
- if (!data || typeof data.conversation_id !== "string" || !retained.has(`${key[3]}:${data.conversation_id}`) || typeof data.serverMessageCount !== "number" || !Number.isInteger(data.serverMessageCount) || data.serverMessageCount < 0 || !(typeof data.newestMessageId === "string" || data.newestMessageId === null)) continue
- queries.push(query)
- }
- }
- return { ...client, clientState: { ...client.clientState, mutations: [], queries } }
-}
diff --git a/src/web/src/lib/workspace-chat-reconciliation.ts b/src/web/src/lib/workspace-chat-reconciliation.ts
deleted file mode 100644
index 5eb4164cd..000000000
--- a/src/web/src/lib/workspace-chat-reconciliation.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { replaceEqualDeep } from "@tanstack/react-query"
-import type { ChatMessagesData } from "./chat-cache"
-
-export function reconcileChatMessages(previous: unknown, incoming: unknown): ChatMessagesData {
- const old = previous as ChatMessagesData | undefined
- const next = incoming as ChatMessagesData
- const revisions = next.pages.flatMap((page) => page.requestRevision === undefined ? [] : [page.requestRevision])
- if (!revisions.length) return replaceEqualDeep(old, next)
- const started = Math.min(...revisions)
- const live = (old?.pages ?? []).flatMap((page) => page.messages).filter((row) => (old?.liveMessageRevisions?.[row.id] ?? 0) > started)
- const liveIds = new Set(live.map((row) => row.id))
- const pages = next.pages.map(({ requestRevision: _, ...page }, index) => ({
- ...page,
- messages: [...page.messages.filter((row) => !liveIds.has(row.id)), ...(!index ? live : [])].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)),
- }))
- return replaceEqualDeep(old, { ...next, pages, serverMessageCount: old?.serverMessageCount ?? 0, liveRevision: old?.liveRevision ?? 0, liveMessageRevisions: old?.liveMessageRevisions ?? {} })
-}
diff --git a/src/web/src/lib/workspace-chat-wire.ts b/src/web/src/lib/workspace-chat-wire.ts
deleted file mode 100644
index 82672f920..000000000
--- a/src/web/src/lib/workspace-chat-wire.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { z } from "zod"
-import type { Conversation, Message, Artifact } from "@alook/shared"
-const timestamp = z.string().refine((value) => Number.isFinite(Date.parse(value)))
-export const cachedConversationSchema = z.object({
- id: z.string().min(1), agent_id: z.string(), title: z.string(), type: z.string(), channel: z.string(),
- parent_message_id: z.string().nullable().optional(), thread_title: z.string().optional(),
- created_at: timestamp, message_count: z.number().int().nonnegative().optional(),
-}) satisfies z.ZodType<Conversation>
-export const cachedMessageSchema = z.object({
- id: z.string().min(1), conversation_id: z.string().min(1), role: z.enum(["user", "assistant", "event"]),
- content: z.string(), task_id: z.string().nullable(), attachment_ids: z.array(z.string()).nullable(),
- metadata: z.record(z.string(), z.unknown()).nullable().optional(), status: z.literal("active").optional(), created_at: timestamp,
-}) satisfies z.ZodType<Message>
-export const cachedArtifactSchema = z.object({
- id: z.string().min(1), conversation_id: z.string().min(1), agent_id: z.string(), filename: z.string(),
- content_type: z.string(), size: z.number().nonnegative(), source: z.string(), has_thumbnail: z.boolean(), created_at: timestamp,
-}) satisfies z.ZodType<Artifact>
diff --git a/src/web/src/lib/workspace-flag-count.ts b/src/web/src/lib/workspace-flag-count.ts
deleted file mode 100644
index 55248acde..000000000
--- a/src/web/src/lib/workspace-flag-count.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { replaceEqualDeep } from "@tanstack/react-query"
-import type { WorkspaceOwner } from "@/contexts/workspace-context"
-
-export type FlagCountData = { count: number; confirmedCount?: number; revision?: number; pending?: Record<string, { delta: number; revision: number }>; requestRevision?: number }
-const visibleCount = (confirmed: number, pending: NonNullable<FlagCountData["pending"]>) => Math.max(0, confirmed + Object.values(pending).reduce((sum, write) => sum + write.delta, 0))
-export function reconcileFlagCount(previous: unknown, incoming: unknown): unknown {
- const next = incoming as FlagCountData | undefined
- const old = previous as FlagCountData | undefined
- if (next?.requestRevision === undefined) return replaceEqualDeep(previous, incoming)
- const pending = Object.fromEntries(Object.entries(old?.pending ?? {}).filter(([, write]) => write.revision > next.requestRevision!))
- return replaceEqualDeep(previous, { count: visibleCount(next.count, pending), confirmedCount: next.count, revision: old?.revision ?? 0, pending })
-}
-export function beginFlagCountWrite(owner: WorkspaceOwner, delta: number) {
- let ticket = ""
- owner.queryClient.setQueryData<FlagCountData>(owner.key("flag-count"), (previous) => {
- const revision = (previous?.revision ?? 0) + 1
- ticket = String(revision)
- const pending = { ...previous?.pending, [ticket]: { delta, revision } }
- const confirmedCount = previous?.confirmedCount ?? previous?.count ?? 0
- return { confirmedCount, revision, pending, count: visibleCount(confirmedCount, pending) }
- })
- return { ticket, query: owner.queryClient.getQueryCache().find({ queryKey: owner.key("flag-count"), exact: true }) }
-}
-export function rollbackFlagCountWrite(owner: WorkspaceOwner, write: ReturnType<typeof beginFlagCountWrite>) {
- const current = owner.queryClient.getQueryCache().find({ queryKey: owner.key("flag-count"), exact: true })
- if (!write.query || current !== write.query) return
- const ticket = write.ticket
- owner.queryClient.setQueryData<FlagCountData>(owner.key("flag-count"), (previous) => {
- if (!previous?.pending?.[ticket]) return previous
- const { [ticket]: _removed, ...pending } = previous.pending
- const confirmedCount = previous.confirmedCount ?? previous.count
- return { ...previous, pending, count: visibleCount(confirmedCount, pending) }
- })
-}
diff --git a/src/web/src/lib/workspace-issue-events.ts b/src/web/src/lib/workspace-issue-events.ts
deleted file mode 100644
index e795cd18a..000000000
--- a/src/web/src/lib/workspace-issue-events.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import type { WsMessage, Issue } from "@alook/shared"
-import type { IssueListItem } from "@/lib/api"
-import { captureWorkspaceOwner, assertWorkspaceOwner, type WorkspaceOwner } from "@/contexts/workspace-context"
-import type { WorkspaceIssueDetail } from "./workspace-issue-reconciliation"
-
-export function publishWorkspaceIssueEvent(owner: WorkspaceOwner, message: WsMessage) {
- const qc = owner.queryClient
- const token = captureWorkspaceOwner(owner)
- assertWorkspaceOwner(token)
- const invalidate = (key: readonly unknown[]) => {
- void qc.cancelQueries({ queryKey: key }).then(() => { assertWorkspaceOwner(token); return qc.invalidateQueries({ queryKey: key }) }).catch(() => undefined)
- }
- if (message.type === "task.updated") {
- invalidate(owner.key("chat", "task", message.taskId))
- for (const query of qc.getQueryCache().findAll({ queryKey: owner.key("issues", "detail") })) {
- const detail = query.state.data as WorkspaceIssueDetail | undefined
- if (detail && (detail.issue.latest_task_id === message.taskId || detail.issue.agent_id === message.agentId)) invalidate(query.queryKey)
- }
- for (const query of qc.getQueryCache().findAll({ queryKey: owner.key("issues", "list") })) {
- const rows = query.state.data as IssueListItem[] | undefined
- if (Array.isArray(rows) && (rows.length === 0 || rows.some((row) => row.latest_task_id === message.taskId || row.agent_id === message.agentId))) invalidate(query.queryKey)
- }
- return
- }
- if (message.type !== "conversation.message" && message.type !== "issue.comment") return
- const eventStatus = message.type === "conversation.message" && message.message.role === "event" && message.message.content.startsWith("Issue status changed:") ? message.message.content.match(/-> (\w+)/)?.[1] as Issue["status"] | undefined : undefined
- for (const query of qc.getQueryCache().findAll({ queryKey: owner.key("issues", "detail") })) {
- const previous = query.state.data as WorkspaceIssueDetail | undefined
- if (!previous) continue
- let next = previous
- const fields: NonNullable<WorkspaceIssueDetail["liveFields"]> = {}
- const revision = (previous.liveRevision ?? 0) + 1
- if (message.type === "conversation.message" && previous.issue.conversation_id === message.conversationId) {
- if (!previous.messages.some((row) => row.id === message.message.id)) { next = { ...next, messages: [...next.messages, message.message] }; fields.messages = revision }
- if (eventStatus && message.message.created_at >= previous.issue.updated_at && eventStatus !== previous.issue.status) { next = { ...next, issue: { ...next.issue, status: eventStatus, updated_at: message.message.created_at } }; fields.issue = revision }
- }
- if (message.type === "issue.comment" && previous.issue.id === message.issueId && !previous.comments.some((row) => row.id === message.comment.id)) { next = { ...next, comments: [...next.comments, message.comment] }; fields.comments = revision }
- if (next !== previous) qc.setQueryData(query.queryKey, { ...next, liveRevision: revision, liveFields: { ...previous.liveFields, ...fields } })
- }
- if (message.type === "conversation.message" && eventStatus) {
- for (const query of qc.getQueryCache().findAll({ queryKey: owner.key("issues", "list") })) {
- if (!Array.isArray(query.state.data)) continue
- qc.setQueryData<IssueListItem[]>(query.queryKey, (rows) => rows?.map((row) => row.conversation_id === message.conversationId && message.message.created_at >= row.updated_at ? { ...row, status: eventStatus, updated_at: message.message.created_at } : row))
- }
- invalidate(owner.key("issues", "list"))
- }
-}
diff --git a/src/web/src/lib/workspace-issue-reconciliation.ts b/src/web/src/lib/workspace-issue-reconciliation.ts
deleted file mode 100644
index e4c4afbfc..000000000
--- a/src/web/src/lib/workspace-issue-reconciliation.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { replaceEqualDeep } from "@tanstack/react-query"
-import type { IssueDetailResponse } from "@/lib/api"
-
-export type WorkspaceIssueDetail = IssueDetailResponse & { liveRevision?: number; liveFields?: Partial<Record<"issue" | "messages" | "comments" | "artifacts", number>>; requestRevision?: number }
-export function reconcileWorkspaceIssue(previous: unknown, incoming: unknown): unknown {
- const next = incoming as WorkspaceIssueDetail | undefined
- const old = previous as WorkspaceIssueDetail | undefined
- if (next?.requestRevision === undefined) return replaceEqualDeep(previous, incoming)
- const { requestRevision, ...data } = next
- if (!old) return replaceEqualDeep(previous, data)
- const live = (field: keyof NonNullable<WorkspaceIssueDetail["liveFields"]>) => (old.liveFields?.[field] ?? 0) > requestRevision
- const merge = <T extends { id: string }>(before: T[], after: T[]) => [...new Map([...after, ...before].map((row) => [row.id, row])).values()]
- return replaceEqualDeep(previous, {
- ...data, liveRevision: old.liveRevision, liveFields: old.liveFields,
- issue: live("issue") ? old.issue : data.issue,
- messages: live("messages") ? merge(old.messages, data.messages).sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)) : data.messages,
- comments: live("comments") ? merge(old.comments, data.comments) : data.comments,
- artifacts: live("artifacts") ? merge(old.artifacts, data.artifacts) : data.artifacts,
- })
-}
diff --git a/src/web/src/middleware.test.ts b/src/web/src/middleware.test.ts
index ebf67c181..08dca1c82 100644
--- a/src/web/src/middleware.test.ts
+++ b/src/web/src/middleware.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
+import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(async () => ({ env: {} })),
@@ -10,7 +11,7 @@ vi.mock("@/lib/auth", () => ({
getAuth: vi.fn(() => ({ api: { getSession: mockGetSession } })),
}));
-import { middleware } from "./middleware";
+import { config, middleware } from "./middleware";
/** Build a request with controllable forwarded-proto + headers. */
function makeReq(url: string, headers: Record<string, string> = {}) {
@@ -22,15 +23,15 @@ describe("middleware", () => {
describe("HTTPS enforcement", () => {
it("301-redirects http → https for non-local hosts", async () => {
- const req = makeReq("http://example.com/w/foo", { "x-forwarded-proto": "http" });
+ const req = makeReq("http://example.com/c/me", { "x-forwarded-proto": "http" });
const res = await middleware(req);
expect(res.status).toBe(301);
- expect(res.headers.get("location")).toBe("https://example.com/w/foo");
+ expect(res.headers.get("location")).toBe("https://example.com/c/me");
});
it("does NOT force https for localhost", async () => {
mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });
- const req = makeReq("http://localhost/w/foo", { "x-forwarded-proto": "http" });
+ const req = makeReq("http://localhost/c/me", { "x-forwarded-proto": "http" });
const res = await middleware(req);
// localhost is exempt → falls through to auth handling (sign-in redirect), not a 301 https redirect
expect(res.headers.get("location")).not.toContain("https://localhost")
@@ -38,29 +39,30 @@ describe("middleware", () => {
it("does NOT force https for 127.x", async () => {
mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });
- const req = makeReq("http://127.0.0.1/w/foo", { "x-forwarded-proto": "http" });
+ const req = makeReq("http://127.0.0.1/c/me", { "x-forwarded-proto": "http" });
const res = await middleware(req);
expect(res.status).not.toBe(301);
});
});
describe("auth-required routes", () => {
- it("redirects to /sign-in with redirect param when unauthenticated", async () => {
- mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });
- const req = makeReq("https://app.com/w/foo?tab=x", { "x-forwarded-proto": "https" });
- const res = await middleware(req);
- const loc = new URL(res.headers.get("location")!);
- expect(loc.pathname).toBe("/sign-in");
- expect(loc.searchParams.get("redirect")).toBe("/w/foo?tab=x");
+ it.each(["/w", "/w/sample/home", "/w/sample.name/home", "/w/sample/agents/a/chat/b", "/w/sample/%broken", "/%77/sample/home", "/workspaces", "/dashboard", "/studio/new", "/studio/new/", "/invite/old-token"])("leaves deleted frontend path %s to ordinary route handling without looking up a session", async path => {
+ for (const response of [null, { user: { id: "viewer" } }]) {
+ mockGetSession.mockResolvedValue({ headers: new Headers({ "set-cookie": "session=renewed; Path=/" }), response });
+ const res = await middleware(makeReq(`https://app.com${path}?token=private&workspace_id=private`));
+ expect(res.headers.get("location")).toBeNull();
+ expect(res.headers.get("x-middleware-next")).toBe("1");
+ expect(res.headers.get("set-cookie")).toBeNull();
+ expect(mockGetSession).not.toHaveBeenCalled();
+ }
});
-
- it("omits redirect param when returnTo is /workspaces", async () => {
+ it("redirects to /sign-in with redirect param when unauthenticated", async () => {
mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });
- const req = makeReq("https://app.com/workspaces", { "x-forwarded-proto": "https" });
+ const req = makeReq("https://app.com/c/me?tab=x", { "x-forwarded-proto": "https" });
const res = await middleware(req);
const loc = new URL(res.headers.get("location")!);
expect(loc.pathname).toBe("/sign-in");
- expect(loc.searchParams.get("redirect")).toBeNull();
+ expect(loc.searchParams.get("redirect")).toBe("/c/me?tab=x");
});
it("passes through authenticated requests and forwards refreshed cookies", async () => {
@@ -70,7 +72,7 @@ describe("middleware", () => {
headers: setHeaders,
response: { user: { id: "u1" } },
});
- const req = makeReq("https://app.com/dashboard", { "x-forwarded-proto": "https" });
+ const req = makeReq("https://app.com/c/me", { "x-forwarded-proto": "https" });
const res = await middleware(req);
// NextResponse.next() — no redirect location
expect(res.headers.get("location")).toBeNull();
@@ -103,6 +105,15 @@ describe("middleware", () => {
});
});
+ describe("Next route matcher", () => {
+ it.each(["/c/me", "/sign-in", "/w", "/studio/new"])("runs the ordinary middleware matcher for %s", url => {
+ expect(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url })).toBe(true);
+ });
+ it.each(["/favicon.ico", "/_next/static/chunk.js", "/images/logo.png", "/about.pdf", "/w/sample.name/home", "/w/sample/agents/a.name/chat/b.json"])("retains the ordinary dotted-path exclusion for %s", url => {
+ expect(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url })).toBe(false);
+ });
+ });
+
describe("sign-in redirect when already authenticated (isSafeRedirect guard)", () => {
async function signInWith(redirectParam: string | null) {
mockGetSession.mockResolvedValue({
@@ -115,9 +126,9 @@ describe("middleware", () => {
return new URL(res.headers.get("location")!);
}
- it("accepts a safe same-origin relative path (/w/foo)", async () => {
- const loc = await signInWith("/w/foo");
- expect(loc.pathname).toBe("/w/foo");
+ it("keeps a supplied safe same-origin return path", async () => {
+ const loc = await signInWith("/removed/page");
+ expect(loc.pathname).toBe("/removed/page");
});
it("rejects protocol-relative //evil.com → falls back to /c/me", async () => {
diff --git a/src/web/src/middleware.ts b/src/web/src/middleware.ts
index f5c56280e..4da21b12b 100644
--- a/src/web/src/middleware.ts
+++ b/src/web/src/middleware.ts
@@ -1,9 +1,9 @@
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { getAuth } from "@/lib/auth"
-import { isSafeRedirectPath } from "@/lib/safe-redirect"
+import { safeRedirectPath } from "@/lib/safe-redirect"
-const AUTH_REQUIRED_PREFIXES = ["/invite/", "/w/", "/workspaces", "/dashboard", "/c/"]
+const AUTH_REQUIRED_PREFIXES = ["/c/"]
// Paths that stay public even though they'd otherwise match an auth-required
// prefix. The invite landing page is preview-first: a logged-out user must be
@@ -39,10 +39,7 @@ export async function middleware(request: NextRequest) {
if (!result?.response) {
const signInUrl = new URL("/sign-in", request.url)
- const returnTo = pathname + request.nextUrl.search
- if (returnTo !== "/workspaces") {
- signInUrl.searchParams.set("redirect", returnTo)
- }
+ signInUrl.searchParams.set("redirect", pathname + request.nextUrl.search)
return NextResponse.redirect(signInUrl)
}
@@ -63,11 +60,7 @@ export async function middleware(request: NextRequest) {
if (result?.response) {
const redirect = request.nextUrl.searchParams.get("redirect")
- const target = redirect && isSafeRedirectPath(redirect)
- ? new URL(redirect, request.url)
- // Default landing for an already-signed-in visitor hitting /sign-in:
- // community home. `/workspaces` was the retired legacy (v0) surface.
- : new URL("/c/me", request.url)
+ const target = new URL(safeRedirectPath(redirect), request.url)
const res = NextResponse.redirect(target)
for (const cookie of result.headers.getSetCookie()) {
res.headers.append("Set-Cookie", cookie)
diff --git a/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts b/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts
index fcb2af1e7..00412bd8c 100644
--- a/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts
+++ b/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts
@@ -155,90 +155,22 @@ test("Community owns ordinary context menus and preserves native exceptions", as
expect(writes).toEqual([])
})
-test("workspace menus keep custom behavior while editors and escapes stay native", async ({ asUser }) => {
- const { context, page } = await asUser("alice", { viewport: { width: 1280, height: 720 } })
- const suffix = Date.now().toString(36)
- const slug = `context-policy-${suffix}`
- const workspaceResponse = await context.request.post("/api/workspaces", {
- data: { name: `Context Policy ${suffix}`, slug },
- })
- expect(workspaceResponse.status()).toBe(201)
- const workspace = await workspaceResponse.json() as { id: string; slug: string }
- const onboardedResponse = await context.request.post(`/api/workspaces/${workspace.id}/onboarded`)
- expect(onboardedResponse.status()).toBe(200)
-
- const titles = [`Context alpha ${suffix}`, `Context beta ${suffix}`]
- for (const title of titles) {
- const issueResponse = await context.request.post(`/api/issues?workspace_id=${workspace.id}`, {
- data: { title, description: "" },
- })
- expect(issueResponse.status()).toBe(201)
- }
-
- const writes: string[] = []
- page.on("request", (request) => {
- if (!["GET", "HEAD", "OPTIONS"].includes(request.method())) {
- writes.push(`${request.method()} ${new URL(request.url()).pathname}`)
- }
- })
- await page.goto(`/w/${workspace.slug}/issues`, { waitUntil: "commit" })
- await expect(page.getByRole("heading", { name: "Issues" })).toBeVisible({ timeout: 20_000 })
- const first = page.locator('[data-slot="context-menu-trigger"]').filter({ hasText: titles[0] }).first()
- const second = page.locator('[data-slot="context-menu-trigger"]').filter({ hasText: titles[1] }).first()
- await expect(first).toBeVisible()
- await expect(second).toBeVisible()
-
- await rightClickDisposition(page, first, true)
- await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()
- await dismissContextMenu(page)
-
- await first.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))
- await rightClickDisposition(page, first, false)
- await expect(visibleContextMenu(page)).toHaveCount(0)
-
- await first.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))
- await dispatchSecondaryPointer(first, "pointerdown", 41)
- await page.waitForTimeout(50)
- await page.evaluate(() => window.dispatchEvent(new Event("blur")))
- await page.waitForTimeout(50)
- await first.evaluate((element) => element.removeAttribute("data-native-context-menu"))
- await rightClickDisposition(page, first, true)
- await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()
- await dismissContextMenu(page)
-
- await first.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))
- await dispatchSecondaryPointer(first, "pointerdown", 51)
- await page.waitForTimeout(50)
- await first.evaluate((element) => element.removeAttribute("data-native-context-menu"))
- await rightClickDisposition(page, second, true)
- await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()
- await dismissContextMenu(page)
- await page.evaluate(() => window.dispatchEvent(new Event("blur")))
- await page.waitForTimeout(50)
-
- await rightClickDisposition(page, first, true)
- await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()
- await dismissContextMenu(page)
-
- await first.focus()
- await page.keyboard.press("Shift+F10")
- await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()
- await dismissContextMenu(page)
-
- await page.getByRole("button", { name: "New issue" }).click()
- const titleEditor = page.getByPlaceholder("New issue")
- await expect(titleEditor).toBeVisible()
- await rightClickDisposition(page, titleEditor, false)
- await page.keyboard.press("Escape")
- expect(writes).toEqual([])
-})
-
test("public, auth, and invite routes remain browser owned", async ({ page, asUser }) => {
+ const invitePath = "/c/invite/not-a-real-token"
+ let inviteDocuments = 0
+ page.on("request", request => {
+ if (request.isNavigationRequest() && request.frame() === page.mainFrame() && new URL(request.url()).pathname === invitePath) inviteDocuments += 1
+ })
for (const route of ["/", "/sign-in", "/c/invite/not-a-real-token"]) {
await page.goto(route, { waitUntil: "commit" })
await expect(page.locator("body")).toBeVisible()
+ if (route === invitePath) {
+ await expect(page.getByTestId(tid.inviteExpiredTitle)).toBeVisible()
+ await expect(page.getByTestId(tid.inviteExpiredTitle)).toHaveText("This invite has expired")
+ }
await rightClickDisposition(page, await installOrdinaryProbe(page), false)
}
+ expect(inviteDocuments).toBe(1)
const authenticated = await asUser("alice")
await authenticated.page.goto("/invite/not-a-real-token", { waitUntil: "commit" })
diff --git a/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts b/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts
deleted file mode 100644
index e2c590bf9..000000000
--- a/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-import { readFile } from "node:fs/promises"
-import type { Locator } from "@playwright/test"
-import { test, expect } from "./_fixtures/community-fixture"
-import { solidPngFixture, structuredJpegFixture } from "../fixtures/media"
-
-const ARTIFACT_IMAGE = solidPngFixture(800, 450, [39, 111, 191])
-const ARTIFACT_THUMBNAIL = structuredJpegFixture(320, 180)
-
-async function expectStableFrame(frame: Locator, expected: { width: number; height: number }) {
- await expect.poll(async () => {
- const box = await frame.boundingBox()
- return box ? { width: box.width, height: box.height } : null
- }).toEqual(expected)
-}
-
-test("Workspace artifact thumbnails and full images hold geometry through failure and exact-URL retry", async ({ asUser }, testInfo) => {
- test.setTimeout(180_000)
- const { context, page } = await asUser("alice", { viewport: { width: 1280, height: 800 } })
- const suffix = Date.now().toString(36)
- const slug = `remote-image-${suffix}`
-
- const workspaceResponse = await context.request.post("/api/workspaces", {
- data: { name: `Remote image ${suffix}`, slug },
- })
- expect(workspaceResponse.status()).toBe(201)
- const workspace = await workspaceResponse.json() as { id: string; slug: string }
- const onboardedResponse = await context.request.post(`/api/workspaces/${workspace.id}/onboarded`)
- expect(onboardedResponse.status()).toBe(200)
-
- const tokenResponse = await context.request.post(`/api/machine-tokens?workspace_id=${workspace.id}`, {
- data: { name: `remote-image-${suffix}` },
- })
- expect(tokenResponse.status()).toBe(201)
- const { token } = await tokenResponse.json() as { token: string }
- const activationResponse = await context.request.post("/api/machine-tokens/activate", {
- data: {
- token,
- hostname: `remote-image-${suffix}`,
- runtimes: [{ type: "codex", version: "e2e" }],
- },
- })
- expect(activationResponse.status()).toBe(200)
- const activation = await activationResponse.json() as { runtimes: Array<{ id: string }> }
-
- const agentResponse = await context.request.post(`/api/agents?workspace_id=${workspace.id}`, {
- data: {
- name: `Remote Image ${suffix}`,
- description: "",
- instructions: "",
- runtime_id: activation.runtimes[0]!.id,
- },
- })
- expect(agentResponse.status()).toBe(201)
- const agent = await agentResponse.json() as { id: string }
- const conversationResponse = await context.request.post(
- `/api/agents/${agent.id}/conversation?workspace_id=${workspace.id}`,
- { data: {} },
- )
- expect(conversationResponse.status()).toBe(200)
- const conversation = await conversationResponse.json() as { id: string }
-
- const messageResponse = await context.request.post(
- `/api/conversations/${conversation.id}/messages?workspace_id=${workspace.id}`,
- {
- multipart: {
- content: "Review this artifact",
- file: {
- name: "artifact.png",
- mimeType: "image/png",
- buffer: ARTIFACT_IMAGE,
- },
- "thumbnail:0": {
- name: "thumbnail.jpg",
- mimeType: "image/jpeg",
- buffer: ARTIFACT_THUMBNAIL,
- },
- },
- },
- )
- expect([201, 500]).toContain(messageResponse.status())
-
- let releaseThumbnailFailure!: () => void
- const thumbnailGate = new Promise<void>((resolve) => { releaseThumbnailFailure = resolve })
- let thumbnailRequests = 0
- await page.route("**/api/artifacts/*/thumbnail?*", async (route) => {
- if (route.request().method() !== "GET") return route.continue()
- thumbnailRequests += 1
- if (thumbnailRequests === 1) {
- await thumbnailGate
- return route.fulfill({ status: 503, body: "thumbnail unavailable" })
- }
- return route.continue()
- })
-
- await page.goto(`/w/${workspace.slug}/agents/${agent.id}`, { waitUntil: "commit" })
- const thumbnail = page.locator('img[alt="artifact.png"][src*="/thumbnail"]')
- await expect(thumbnail).toHaveAttribute("data-remote-image-state", "pending", { timeout: 20_000 })
- const thumbnailFrame = thumbnail.locator("xpath=ancestor::*[@data-remote-image-frame][1]")
- const thumbnailPendingBox = await thumbnailFrame.boundingBox()
- expect(thumbnailPendingBox).not.toBeNull()
- const thumbnailSize = {
- width: thumbnailPendingBox!.width,
- height: thumbnailPendingBox!.height,
- }
-
- releaseThumbnailFailure()
- await expect(thumbnail).toHaveAttribute("data-remote-image-state", "error")
- await expect(thumbnailFrame.getByRole("button", { name: "Retry" })).toBeVisible()
- await expectStableFrame(thumbnailFrame, thumbnailSize)
- const thumbnailUrl = await thumbnail.getAttribute("src")
- await thumbnailFrame.getByRole("button", { name: "Retry" }).click()
- await expect.poll(() => thumbnailRequests).toBe(2)
- await expect(thumbnail).toHaveAttribute("src", thumbnailUrl!)
- await expect(thumbnail).toHaveAttribute("data-remote-image-state", "ready")
- await expectStableFrame(thumbnailFrame, thumbnailSize)
- await page.unroute("**/api/artifacts/*/thumbnail?*")
-
- let releaseContentFailure!: () => void
- const contentGate = new Promise<void>((resolve) => { releaseContentFailure = resolve })
- let contentRequests = 0
- await page.route("**/api/artifacts/*/content?*", async (route) => {
- if (route.request().method() !== "GET") return route.continue()
- contentRequests += 1
- if (contentRequests === 1) {
- await contentGate
- return route.fulfill({ status: 503, body: "content unavailable" })
- }
- return route.continue()
- })
-
- await page.getByRole("button", { name: "Open artifact.png" }).first().click()
- const fullImage = page.locator('img[alt="artifact.png"][src*="/content"]')
- await expect(fullImage).toHaveAttribute("data-remote-image-state", "pending")
- await expect(page.getByRole("button", { name: "Download artifact.png" })).toBeVisible()
- const contentFrame = fullImage.locator("xpath=ancestor::*[@data-remote-image-frame][1]")
- const contentPendingBox = await contentFrame.boundingBox()
- expect(contentPendingBox).not.toBeNull()
- const contentSize = {
- width: contentPendingBox!.width,
- height: contentPendingBox!.height,
- }
-
- releaseContentFailure()
- await expect(fullImage).toHaveAttribute("data-remote-image-state", "error")
- await expectStableFrame(contentFrame, contentSize)
- const contentUrl = await fullImage.getAttribute("src")
- await contentFrame.getByRole("button", { name: "Retry" }).click()
- await expect.poll(() => contentRequests).toBe(2)
- await expect(fullImage).toHaveAttribute("src", contentUrl!)
- await expect(fullImage).toHaveAttribute("data-remote-image-state", "ready")
- await expectStableFrame(contentFrame, contentSize)
- const downloadStarted = page.waitForEvent("download")
- await page.getByRole("button", { name: "Download artifact.png" }).click()
- const download = await downloadStarted
- expect(download.suggestedFilename()).toBe("artifact.png")
- const savedPath = testInfo.outputPath("artifact.png")
- await download.saveAs(savedPath)
- expect(await readFile(savedPath)).toEqual(ARTIFACT_IMAGE)
- await expect(page.getByRole("button", { name: "Download artifact.png" }).getByRole("status")).toHaveText("Download started")
- await page.getByRole("button", { name: "Close image" }).click()
- await expect(fullImage).toHaveCount(0)
-})
diff --git a/src/web/src/test/e2e-ui/56-retired-workspace-links.spec.ts b/src/web/src/test/e2e-ui/56-retired-workspace-links.spec.ts
new file mode 100644
index 000000000..023d4c13f
--- /dev/null
+++ b/src/web/src/test/e2e-ui/56-retired-workspace-links.spec.ts
@@ -0,0 +1,30 @@
+import type { Page } from "@playwright/test"
+import { test, expect } from "./_fixtures/community-fixture"
+
+const deletedRoutes = ["/w", "/w/sample/home", "/w/sample.name/home", "/w/sample/agents/a/chat/b", "/workspaces", "/studio/new", "/invite/not-a-community-token"]
+
+async function expectDeletedFrontend(page: Page) {
+ const legacyRequests: string[] = []
+ page.on("request", request => {
+ const path = new URL(request.url()).pathname
+ if (/^\/api\/(?:workspaces|studios|invite|agents|conversations)(?:\/|$)/.test(path)) legacyRequests.push(path)
+ })
+ for (const path of deletedRoutes) {
+ const response = await page.goto(`${path}?token=private&workspace_id=private`, { waitUntil: "commit" })
+ expect(response?.status()).toBe(404)
+ expect(response?.request().redirectedFrom()).toBeNull()
+ expect(new URL(page.url()).pathname).toBe(path)
+ await expect(page.getByText("The page you're looking for doesn't exist or has been moved. Check the address and try again.", { exact: true })).toBeVisible()
+ await expect(page.getByText("Workspace invitations have been retired", { exact: true })).toHaveCount(0)
+ }
+ expect(legacyRequests).toEqual([])
+}
+
+test("authenticated deleted workspace links return ordinary 404s without legacy API calls", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await expectDeletedFrontend(page)
+})
+
+test("anonymous deleted workspace links return ordinary 404s without a login redirect", async ({ page }) => {
+ await expectDeletedFrontend(page)
+})