Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

Reapply "feat: workspace URL refactor v2 + rollback-safe compat layer (#1138)" (#1139) (#1141)

Naiyuan Qingfe358feff0b4
diff --git a/HANDOFF_ARCHITECTURE_AUDIT.md b/HANDOFF_ARCHITECTURE_AUDIT.md
new file mode 100644
index 0000000000..4cab6a5b0b
--- /dev/null
+++ b/HANDOFF_ARCHITECTURE_AUDIT.md
@@ -0,0 +1,383 @@
+# Architecture Audit — Workspace & Realtime Cache
+
+> 基于代码审计整理的 4 个任务。优先级:P0 一个、P1 一个、P2 两个。每个任务都包含问题、根因、受影响的 issue、复现步骤、修复方案、改动范围。
+
+---
+
+## 任务 1 — [P0] 空闲后列表数据陈旧
+
+**关联 issue**:[#951](https://github.com/multica-ai/multica/issues/951)
+
+### 问题
+
+用户登录后静置一段时间,Issue 列表里缺失一部分数据(其他成员期间新建/变更的 issue 不出现)。登出再登入可以恢复。`ec5af33b` 声称 "Closes #951",但 issue 仍为 OPEN 状态 —— 因为它只修了 401 一种场景,没修 WS 半开这一种。
+
+### 根因
+
+系统把 cache 新鲜度的全部责任压给了 WebSocket 推送:
+
+- `packages/core/query-client.ts:7` — `staleTime: Infinity`,cache 永不主动过期
+- `packages/core/query-client.ts:9` — `refetchOnWindowFocus: false`,tab 重新获得焦点也不 refetch
+- 依赖 WS 推送 `issue:created` / `issue:updated` 事件 invalidate cache
+
+但 WS 层存在一个**不对称**:
+
+- **服务端**:`server/internal/realtime/hub.go:83-96, 420-475` 有 54s ping / 60s pongWait,会清理死连接
+- **客户端**:`packages/core/api/ws-client.ts`(142 行全貌)**完全没有心跳检测**,只靠 `onclose` 事件触发重连
+
+浏览器原生 `WebSocket` API 不把 ping/pong 帧暴露给 JS,所以 JS 层无法主动探测 "半开" 连接。当 NAT / 负载均衡器 / 笔记本睡眠导致 TCP 连接被静默切断时:
+
+1. 浏览器 `readyState` 仍是 `OPEN`
+2. `onclose` 不触发
+3. `ws-client.ts:70-73` 的 3 秒重连逻辑不跑
+4. `packages/core/realtime/use-realtime-sync.ts:462-487` 的 `onReconnect` 全量 invalidate 不跑
+5. 期间的 WS 事件进黑洞
+6. cache 保持旧快照
+
+### 复现
+
+**浏览器 DevTools 里的 "Block request URL" 不行** —— 那会触发 `onclose`,走正常重连 → 不复现。真正的半开需要在网络层静默丢包。
+
+**方法 A(推荐,最接近真实场景)**:macOS 用 pfctl 丢包
+
+```bash
+# 假设后端在 8080
+sudo pfctl -E
+echo "block drop out quick proto tcp to any port 8080" | sudo pfctl -f -
+
+# 观察:
+# - Console 里没有 "disconnected, reconnecting in 3s" 日志
+# - Network 里 WS 连接仍显示 Pending / 101
+# 用另一个账号/CLI 创建一个 issue
+# 回到原客户端: 列表不更新
+# 登出再登入: 列表恢复完整
+
+sudo pfctl -d # 解除
+```
+
+**方法 B(不动网络)**:临时修改代码,在 `packages/core/api/ws-client.ts:52` 的 `onmessage` 处理器里加一行 `return;` 在前面,吞掉所有入站消息。效果等价于半开。
+
+### 修复方案(三个选项,推荐 C)
+
+#### 选项 A — 浏览器端心跳探活(治本,改动大)
+
+在 `ws-client.ts` 加客户端侧的心跳检测:记录 `lastMessageTime`,定时器检查若超过 N 秒没收到任何消息就主动 `ws.close()`,触发现有重连逻辑。
+
+- 优点:从根本上解决半开问题
+- 缺点:浏览器原生 API 没有 ping 能力,需要服务端配合发"应用层 heartbeat"消息供客户端更新 `lastMessageTime`;服务端改 + 客户端改
+
+#### 选项 B — Page Visibility API 触发 invalidate(治标,改动小)
+
+在 `packages/core/platform/core-provider.tsx` 加 `visibilitychange` 监听,tab 重新可见时强制 `queryClient.invalidateQueries({ queryKey: issueKeys.all(wsId) })`(及其他关键 key)。
+
+- 优点:~10 行代码,能兜住 80% 场景(睡眠、切后台 tab)
+- 缺点:treats symptom, 不是真正的半开检测;对"一直保持 tab 可见但网络层断了"的场景无效
+
+#### 选项 C — **A + B 组合**(推荐)
+
+- 短期上 B,立刻止血
+- 中期上 A,把 cache 新鲜度从"只信 WS"改成"WS 是优化,Visibility 是兜底"
+- 可选加 `refetchOnWindowFocus: true` 或把 `staleTime` 改成一个有限值(比如 5 min),作为第三层保险
+
+### 改动范围
+
+| 方案 | 文件 | 改动规模 |
+|---|---|---|
+| B | `packages/core/platform/core-provider.tsx` | ~10 行 |
+| A 客户端 | `packages/core/api/ws-client.ts` | ~30 行 |
+| A 服务端 | `server/internal/realtime/hub.go` | 加 app-level heartbeat message |
+
+### 验证
+
+修完之后:
+
+1. 跑方法 A 复现流程,确认数据不再丢失
+2. 加 e2e 测试:模拟 `document.dispatchEvent(new Event('visibilitychange'))` + 验证 issue list 被 refetch
+
+---
+
+## 任务 2 — [P1] Workspace 不在 URL 路径中
+
+**关联 issue**:MUL-723(slug 不在 URL)、MUL-43(切换 workspace 报错)、MUL-509(手机端无法切换)
+
+> **注意**:审计中提到的 MUL-43 / MUL-476 issue 编号需要当面核对一次 —— agent 查询 GitHub 后返回的标题对不上(看起来是别的 PR)。交接时请让执行人以具体症状为准。
+
+### 问题
+
+当前 workspace 身份完全靠 `X-Workspace-ID` HTTP header + Zustand store + localStorage 承载,URL 里没有 workspace 信息。所有路径都是 `/issues`、`/issues/:id` 这种 workspace-agnostic 的。
+
+### 根因
+
+**数据库和 API 已经支持 slug**:
+
+- `server/migrations/001_init.up.sql:15-23` — workspace 表有 `slug TEXT UNIQUE NOT NULL`
+- `server/pkg/db/queries/workspace.sql:11-13` — 有 `GetWorkspaceBySlug` 查询
+- `packages/core/types/workspace.ts:8-19` — Workspace 类型里有 slug 字段
+
+**但前端路由和导航层没用它**:
+
+- Web 路由:`apps/web/app/(dashboard)/` 下 25 个 route file 都是 workspace-implicit
+- Desktop 路由:`apps/desktop/src/renderer/src/routes.tsx:71-143` 同样
+- Navigation 适配器 `apps/web/platform/navigation.tsx` 直接透传 `router.push`,没有任何 workspace 前缀逻辑
+
+**workspace 切换只靠 sidebar UI**(`packages/views/layout/app-sidebar.tsx:284-286`):
+
+```tsx
+if (ws.id !== workspace?.id) {
+ push("/issues"); // 硬跳 /issues(workspace-implicit!)
+ switchWorkspace(ws); // 然后改 store
+}
+```
+
+这种设计使得:
+
+- 手机端因为没 sidebar UI,也没 URL 层切换入口,**完全切不了 workspace**(MUL-509)
+- 把 `/issues/xxx` 链接发给处于不同 workspace 的同事,会打开错误 workspace 下的 issue,或找不到报错(MUL-43 系列)
+- 分享链接没有 workspace 上下文,接收方必须先手动切对 workspace
+
+### 复现
+
+1. **MUL-723**:登录 → 观察地址栏,没有任何 workspace 标识
+2. **MUL-43**:
+ - 加入两个 workspace A 和 B
+ - 在 A 中打开某个 issue `/issues/abc123`
+ - 切到 B,URL 不变 → 访问失败 / 显示错数据
+3. **MUL-509**:手机浏览器打开,尝试切 workspace → 无法切换(UI 不显示 sidebar 触发器或触发器无法切)
+
+### 修复方案(三个选项,推荐 A)
+
+#### 选项 A — `/ws/:slug/...` URL 前缀(根本方案,推荐)
+
+所有路径加上 workspace slug 前缀。例如 `/issues/abc123` → `/ws/my-team/issues/abc123`。
+
+**要改的地方**:
+
+1. **Web 路由目录结构**:`apps/web/app/(dashboard)/` 下全部搬到 `apps/web/app/(dashboard)/ws/[slug]/...`(~25 个文件)
+2. **Desktop 路由**:`apps/desktop/src/renderer/src/routes.tsx:71-143` 给所有路径加 `/ws/:slug` 前缀
+3. **Navigation 适配器**:
+ - `apps/web/platform/navigation.tsx` — `push(path)` 内部前置 `/ws/${workspace.slug}`,`pathname` 读取时去掉前缀
+ - `apps/desktop/src/renderer/src/platform/navigation.tsx` — 同上
+4. **Sidebar 切换逻辑**:`packages/views/layout/app-sidebar.tsx:284-286` 改成 `push('/ws/${ws.slug}/issues')`(或依赖适配器自动加前缀就不用改)
+5. **服务端中间件**:`server/internal/middleware/workspace.go:41-46` 增加 "从 URL path 解析 slug → 查 ID → 校验 membership" 的逻辑,header 继续作为 fallback(迁移期兼容)
+
+**预计改动**:~50-100 个文件(大部分是 route 搬迁,不是逻辑改动)、~5-7 人天
+
+**不改也能工作的部分**:
+- `packages/core/api/client.ts` — 仍旧走 header,不用改
+- 所有 `packages/views/` 下的组件 —— 它们用 `useNavigation().push()` 抽象,适配器层处理前缀就行
+
+**风险**:
+- 旧的 bookmark URL 失效(如果产品还没正式 ship,问题不大)
+- E2E 测试需要更新所有 URL 断言
+
+#### 选项 B — `?ws=slug` query param(折中)
+
+URL 形如 `/issues?ws=my-team`。改动更小(~30 个文件),URL 丑但向后兼容。推荐度低于 A。
+
+#### 选项 C — 只修症状不动架构
+
+在 `switchWorkspace` 和各个 query 之间加 debounce、error boundary 等 workaround。不解决根因,技术债越攒越多。**不推荐**。
+
+### 改动范围(选项 A)
+
+| 模块 | 文件数 | 备注 |
+|---|---|---|
+| Web routes | ~25 | 目录搬迁 |
+| Desktop routes | 1 | 路径前缀 |
+| Navigation adapters | 2 | 前缀逻辑 |
+| Server middleware | 1-2 | slug → ID 解析 |
+| 组件(不用改) | 30-40 | 用 `useNavigation` 的不受影响 |
+| E2E tests | 20-30 | URL 断言更新 |
+
+---
+
+## 任务 3 — [P1] Workspace 切换时 navigation 状态未隔离
+
+**关联 issue**:MUL-43(切换报错)、MUL-476(本地缓存未按 workspace 隔离)
+
+> 同上,这两个编号建议交接时核对症状。
+
+### 问题
+
+绝大多数 workspace-scoped 的 Zustand store 都正确使用了 `createWorkspaceAwareStorage`(key 后缀加 wsId 自动隔离),但 **`useNavigationStore` 是个例外**:它持久化了 `lastPath`,但用的是 global storage,切换 workspace 后里面仍是上个 workspace 的路径。
+
+### 根因
+
+**`packages/core/navigation/store.ts:15-31`**:
+
+```typescript
+export const useNavigationStore = create<NavigationState>()(
+ persist(
+ (set) => ({
+ lastPath: "/issues",
+ onPathChange: (path) => { /* ... */ set({ lastPath: path }); },
+ }),
+ {
+ name: "multica_navigation",
+ storage: createJSONStorage(() => createPersistStorage(defaultStorage)), // ← 这里用的是 global,不是 workspace-aware
+ partialize: (state) => ({ lastPath: state.lastPath }),
+ }
+ )
+);
+// ← 没有调 registerForWorkspaceRehydration
+```
+
+**对比:其他 store 都是正确的**:
+
+| Store | 是否 workspace-aware | 是否注册 rehydration |
+|---|---|---|
+| useNavigationStore | ❌ | ❌ |
+| useIssuesScopeStore | ✅ | ✅ |
+| useIssueDraftStore | ✅ | ✅ |
+| useRecentIssuesStore | ✅ | ✅ |
+| useIssueViewStore | ✅ | ✅ |
+| myIssuesViewStore | ✅ | ✅ |
+| useChatStore | ✅(手动用 wsKey)| ✅ |
+
+另外 `packages/core/platform/storage-cleanup.ts:10-19` 的 `WORKSPACE_SCOPED_KEYS` 列表里也漏了 `multica_navigation`。
+
+**现有的 workaround**:`packages/views/layout/app-sidebar.tsx:285` 切 workspace 时硬跳到 `/issues`,正是为了绕开这个 bug。修好 navigation store 之后这行 hack 可以删掉。
+
+### 复现
+
+1. 在 workspace A 中打开一个具体 issue `/issues/abc123`
+2. 切到 workspace B
+3. 观察:如果没有 sidebar 的硬跳 workaround,会尝试恢复到 `/issues/abc123`,但那个 issue 不属于 B,导致 404 或错误
+
+目前因为有硬跳 workaround,症状表现为"切 workspace 后总是回到 issue 首页"—— 这本身也是 bug(用户期望记住上次位置)。
+
+### 修复方案(推荐 Option C:组合)
+
+**三处改动**:
+
+1. `packages/core/navigation/store.ts:28` —— 把 `createPersistStorage(defaultStorage)` 改成 `createWorkspaceAwareStorage(defaultStorage)`
+2. 同文件在末尾加:`registerForWorkspaceRehydration(() => useNavigationStore.persist.rehydrate());`
+3. `packages/core/platform/storage-cleanup.ts:10-19` 的 `WORKSPACE_SCOPED_KEYS` 数组里加 `"multica_navigation"`
+
+**可选**:清理 `packages/views/layout/app-sidebar.tsx:285` 的 `push("/issues")` workaround(改完之后不再需要)。
+
+### 改动范围
+
+| 文件 | 改动 |
+|---|---|
+| `packages/core/navigation/store.ts` | 改 storage 类型、加 rehydration 注册(~3 行) |
+| `packages/core/platform/storage-cleanup.ts` | 数组加一行 |
+| `packages/core/platform/workspace-storage.test.ts` | 加 rehydration 的单测 |
+| `packages/views/layout/app-sidebar.tsx`(可选) | 移除硬跳 workaround |
+
+**风险**:极低。只是把 navigation store 对齐到其他 store 已经在用的模式。
+
+---
+
+## 任务 4 — [P2] Workspace 生命周期副作用散落
+
+**关联 issue**:MUL-727(创建后闪页)、MUL-728(删除确认)、MUL-820(接受邀请不自动切)
+
+### 问题
+
+创建 / 删除 / 切换 / 加入 workspace 的副作用分散在 mutation 的 `onSuccess` 和各处 UI 回调里,没有统一抽象。几个具体 bug:
+
+### 4.1 MUL-727 — 创建 workspace 后闪一下 `/issues` 再跳 `/onboarding`
+
+**根因**:两个 `onSuccess` 回调同时跑,顺序不确定。
+
+- `packages/core/workspace/mutations.ts:7-21` 的 `useCreateWorkspace.onSuccess` 里调了 `switchWorkspace(newWs)` —— 同步改 Zustand,`/issues` 路由开始用新 workspace 渲染
+- `packages/views/modals/create-workspace.tsx:68-70` 的 UI `onSuccess` 里调了 `router.push("/onboarding")` —— 异步 schedule 导航
+
+于是:`/issues` 先渲染(闪一下)→ 导航到 `/onboarding`。
+
+**修复**:把 `switchWorkspace` 从 mutation 里拿出来,让 UI 层主导。在 `create-workspace.tsx` 的 `onSuccess` 里先 `switchWorkspace` 再 `push`,保证同一个微任务里完成。
+
+**文件**:`packages/core/workspace/mutations.ts`、`packages/views/modals/create-workspace.tsx`、可能 `packages/views/onboarding/step-workspace.tsx`
+
+### 4.2 MUL-728 — 删除 workspace 的"缺少确认"
+
+**核查结果**:`packages/views/settings/components/workspace-tab.tsx:102-119, 236-255` **已经有 AlertDialog 确认**了。
+
+**真实问题**:删除成功后**没有导航**,用户停在 `/settings`,而当前 workspace 已经是删除后系统挑的另一个。
+
+**修复**:在 `handleDeleteWorkspace` 的 `onConfirm` 成功分支里加 `push("/issues")`。
+
+**文件**:`packages/views/settings/components/workspace-tab.tsx`(加一行)
+
+### 4.3 MUL-820 — 接受邀请不自动切换 workspace
+
+**核查结果**:有两条路径:
+
+- ✅ `/invite/:id` 独立页(`packages/views/invite/invite-page.tsx:32-52`)是**正确的**:accept → switchWorkspace → push("/issues")
+- ❌ **Sidebar 下拉里的 "Join" 按钮**(`packages/views/layout/app-sidebar.tsx:203-209, 321-324`)**是错的**:只 invalidate cache,不切也不跳
+
+**修复(推荐 Option 2)**:Sidebar 的 "Join" 改成跳转到 `/invite/:id` 页面,不再就地接受。单一入口、单一行为。
+
+```tsx
+<DropdownMenuItem onClick={() => push(`/invite/${inv.id}`)}>
+ {inv.workspace_name}
+</DropdownMenuItem>
+```
+
+**文件**:`packages/views/layout/app-sidebar.tsx`(~10 行)
+
+### 复现
+
+| Issue | 步骤 |
+|---|---|
+| MUL-727 | 创建新 workspace → 仔细看是否闪了一下 `/issues` 再跳 `/onboarding` |
+| MUL-728 | 删除当前 workspace → 观察删完后是否留在 `/settings` 页面(BUG: 没有自动跳走) |
+| MUL-820 | 被邀请用户登录 → sidebar 下拉 → 点 "Join" → 观察当前 workspace 是否切过去(BUG: 不切)|
+
+### 长期架构建议(可选)
+
+抽一个 `useWorkspaceLifecycle` hook 统一管这些副作用。Agent 报告里有完整设计,文件:`packages/core/workspace/hooks.ts`(新建)。但建议先修 MUL-727/728/820 三个具体 bug,hook 抽象作为后续迭代。
+
+### 改动范围
+
+| Issue | 文件 | 改动规模 |
+|---|---|---|
+| MUL-727 | mutations.ts + create-workspace.tsx | ~10 行 |
+| MUL-728 | workspace-tab.tsx | ~1 行 |
+| MUL-820 | app-sidebar.tsx | ~10 行 |
+
+---
+
+## 总览
+
+| 任务 | Issue | 优先级 | 预估规模 | 风险 |
+|---|---|---|---|---|
+| 1. WS 半开 + 陈旧 cache | #951 | **P0** | Option B ~10 行;Option C ~1-2 天 | 低 |
+| 2. Workspace URL 化 | MUL-723/43/509 | P1 | 5-7 人天(大部分是搬迁)| 中(影响面大、e2e 要改)|
+| 3. Navigation store 隔离 | MUL-43/476 | P1 | ~0.5 天 | 低 |
+| 4. Workspace 生命周期 bug | MUL-727/728/820 | P2 | ~1 天 | 低 |
+
+### 建议推进顺序
+
+1. **立刻做**:任务 1 的 Option B(visibilitychange 触发 invalidate)—— 代码最少、收益最明显,能当天止血
+2. **同步开始**:任务 3(navigation store 隔离)—— 影响小、风险低、顺便清掉一个 workaround
+3. **规划立项**:任务 2(URL 化)—— 大改造,需要单独开一个 iteration
+4. **次要修补**:任务 4 的三个小 bug —— 可以拆成独立 PR,各自 review
+
+### 重要澄清
+
+- **Issue 编号核对**:MUL-43 / MUL-476 的编号需要核对一次,agent 查询 GitHub 返回的标题看起来对不上(可能是内部 issue tracker 编号 vs GitHub 编号混用)。以症状为准。
+- **MUL-728 实际状态**:确认对话框已经存在,真实缺的是"删除后跳走"。
+- **MUL-820 实际状态**:`/invite/:id` 页面路径工作正常,只是 sidebar 下拉按钮坏了。
+
+### 所有关键代码位置索引
+
+```
+packages/core/query-client.ts:7-10 # staleTime: Infinity
+packages/core/api/ws-client.ts:1-142 # 客户端 WS,无心跳
+packages/core/realtime/use-realtime-sync.ts:462-487 # onReconnect 全量 invalidate
+packages/core/platform/core-provider.tsx # 加 visibilitychange 的位置
+packages/core/navigation/store.ts:15-31 # lastPath 未隔离
+packages/core/platform/storage-cleanup.ts:10-19 # WORKSPACE_SCOPED_KEYS
+packages/core/workspace/store.ts:43-77 # hydrateWorkspace / switchWorkspace
+packages/core/workspace/mutations.ts:7-57 # create/leave/delete 三个 mutation
+packages/views/layout/app-sidebar.tsx:203-324 # 侧边栏切 workspace、接受邀请入口
+packages/views/modals/create-workspace.tsx:63-82 # 创建 workspace 入口
+packages/views/settings/components/workspace-tab.tsx:102-119 # 删除 workspace 入口
+packages/views/invite/invite-page.tsx:32-52 # 接受邀请正确实现参考
+
+server/internal/realtime/hub.go:83-96 # 服务端 WS 心跳
+server/internal/middleware/workspace.go:41-46 # wsId resolution
+server/migrations/001_init.up.sql:15-23 # workspace.slug 已存在
+```
diff --git a/apps/desktop/build/icon.ico b/apps/desktop/build/icon.ico
new file mode 100644
index 0000000000..72c391ebcc
Binary files /dev/null and b/apps/desktop/build/icon.ico differ
diff --git a/apps/desktop/build/icon.png b/apps/desktop/build/icon.png
new file mode 100644
index 0000000000..cf9e8b2c87
Binary files /dev/null and b/apps/desktop/build/icon.png differ
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index 1b5c0e9a1b..3b0997959e 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -1,7 +1,8 @@
import { useEffect, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
import { CoreProvider } from "@multica/core/platform";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { workspaceKeys } from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
import { ThemeProvider } from "@multica/ui/components/common/theme-provider";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
@@ -13,8 +14,9 @@ import { UpdateNotification } from "./components/update-notification";
function AppContent() {
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
+ const qc = useQueryClient();
// Deep-link login runs loginWithToken → syncToken → listWorkspaces →
- // hydrateWorkspace sequentially. loginWithToken sets user+isLoading=false
+ // setQueryData sequentially. loginWithToken sets user+isLoading=false
// as soon as getMe resolves, which would cause DesktopShell to mount
// before the workspace list is hydrated and briefly see `!workspace`.
// This local flag keeps the loading screen up until the whole chain
@@ -36,16 +38,20 @@ function AppContent() {
setBootstrapping(true);
try {
await useAuthStore.getState().loginWithToken(token);
+ // Seed React Query cache with the workspace list so the index-route
+ // redirect (routes.tsx `IndexRedirect`) can resolve the initial
+ // destination without a second fetch. Workspace side-effects
+ // (setCurrentWorkspace, persist namespace) are synced later by
+ // WorkspaceRouteLayout when the URL resolves.
const wsList = await api.listWorkspaces();
- const lastWsId = localStorage.getItem("multica_workspace_id");
- useWorkspaceStore.getState().hydrateWorkspace(wsList, lastWsId);
+ qc.setQueryData(workspaceKeys.list(), wsList);
} catch {
// Token invalid or expired — user stays on login page
} finally {
setBootstrapping(false);
}
});
- }, []);
+ }, [qc]);
// Sync token and start the daemon whenever the user logs in.
useEffect(() => {
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 4e7a638ad3..faafd8f1c0 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from "react";
+import { useEffect, useSyncExternalStore } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@multica/ui/lib/utils";
import { useTabHistory } from "@/hooks/use-tab-history";
@@ -9,13 +9,13 @@ import {
useSidebar,
} from "@multica/ui/components/ui/sidebar";
import { ModalRegistry } from "@multica/views/modals/registry";
-import { AppSidebar, DashboardGuard } from "@multica/views/layout";
+import { AppSidebar } from "@multica/views/layout";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
import { ChatFab, ChatWindow } from "@multica/views/chat";
import { StepWorkspace } from "@multica/views/onboarding";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { WorkspaceSlugProvider } from "@multica/core/paths";
+import { getCurrentSlug, subscribeToCurrentSlug } from "@multica/core/platform";
import { DesktopNavigationProvider } from "@/platform/navigation";
-import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { OnboardingGate } from "./onboarding-gate";
import { TabBar } from "./tab-bar";
import { TabContent } from "./tab-content";
@@ -89,44 +89,46 @@ export function DesktopShell() {
useInternalLinkHandler();
useActiveTitleSync();
- const workspace = useWorkspaceStore((s) => s.workspace);
+ // Reactive read of current workspace slug from the platform singleton.
+ // On first mount, slug is null until WorkspaceRouteLayout (inside the tab
+ // router) sets it. Once set, the sidebar and other shell-level components
+ // can resolve workspace-scoped paths via useWorkspacePaths().
+ const slug = useSyncExternalStore(subscribeToCurrentSlug, getCurrentSlug, () => null);
return (
<DesktopNavigationProvider>
<OnboardingGate
- hasWorkspace={!!workspace}
onboarding={(onComplete) => (
<div className="flex min-h-screen items-center justify-center overflow-auto bg-background px-6 py-12">
<StepWorkspace onNext={onComplete} />
</div>
)}
>
- <DashboardGuard
- loginPath="/login"
- loadingFallback={
- <div className="flex h-screen items-center justify-center">
- <MulticaIcon className="size-6 animate-pulse" />
- </div>
- }
- >
+ {/* WorkspaceSlugProvider accepts null — components that need slug
+ use useWorkspaceSlug() (nullable) or useRequiredWorkspaceSlug()
+ (throws). TabContent MUST always render so the tab router can
+ mount WorkspaceRouteLayout, which calls setCurrentWorkspace()
+ to populate the slug. The sidebar gates on slug being present
+ to avoid the useRequiredWorkspaceSlug throw. */}
+ <WorkspaceSlugProvider slug={slug}>
<div className="flex h-screen">
<SidebarProvider className="flex-1">
- <AppSidebar topSlot={<SidebarTopBar />} searchSlot={<SearchTrigger />} />
+ {slug && <AppSidebar topSlot={<SidebarTopBar />} searchSlot={<SearchTrigger />} />}
{/* Right side: header + content container */}
<div className="flex flex-1 min-w-0 flex-col">
<MainTopBar />
{/* Content area with inset styling — relative so ChatWindow/ChatFab are constrained here */}
<div className="relative flex flex-1 min-h-0 flex-col overflow-hidden mr-2 mb-2 ml-0.5 rounded-xl shadow-sm bg-background">
<TabContent />
- <ChatWindow />
- <ChatFab />
+ {slug && <ChatWindow />}
+ {slug && <ChatFab />}
</div>
</div>
</SidebarProvider>
</div>
- <ModalRegistry />
- <SearchCommand />
- </DashboardGuard>
+ {slug && <ModalRegistry />}
+ {slug && <SearchCommand />}
+ </WorkspaceSlugProvider>
</OnboardingGate>
</DesktopNavigationProvider>
);
diff --git a/apps/desktop/src/renderer/src/components/onboarding-gate.test.tsx b/apps/desktop/src/renderer/src/components/onboarding-gate.test.tsx
index 9d5171d3d7..670f33bc74 100644
--- a/apps/desktop/src/renderer/src/components/onboarding-gate.test.tsx
+++ b/apps/desktop/src/renderer/src/components/onboarding-gate.test.tsx
@@ -1,73 +1,91 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, act } from "@testing-library/react";
-import { useState } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { workspaceKeys } from "@multica/core/workspace/queries";
import { OnboardingGate } from "./onboarding-gate";
-describe("OnboardingGate", () => {
- it("renders children when a workspace exists at mount", () => {
- render(
+// Prevent actual API calls — the tests seed data via setQueryData.
+vi.mock("@multica/core/api", () => ({
+ api: {
+ listWorkspaces: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+function createTestQueryClient(
+ workspaces: Array<{ id: string; slug: string }> = [],
+) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ // Seed the workspace list so the gate can read it synchronously.
+ qc.setQueryData(workspaceKeys.list(), workspaces);
+ return qc;
+}
+
+function renderGate(
+ qc: QueryClient,
+ onboarding?: (onComplete: () => void) => React.ReactNode,
+) {
+ return render(
+ <QueryClientProvider client={qc}>
<OnboardingGate
- hasWorkspace={true}
- onboarding={() => <div data-testid="wizard">wizard</div>}
+ onboarding={
+ onboarding ??
+ ((onComplete) => (
+ <button type="button" data-testid="finish" onClick={onComplete}>
+ wizard
+ </button>
+ ))
+ }
>
<div data-testid="main">main shell</div>
- </OnboardingGate>,
- );
+ </OnboardingGate>
+ </QueryClientProvider>,
+ );
+}
+
+describe("OnboardingGate", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("renders children when workspaces exist in cache", () => {
+ const qc = createTestQueryClient([{ id: "ws-1", slug: "my-team" }]);
+ renderGate(qc);
expect(screen.getByTestId("main")).toBeInTheDocument();
- expect(screen.queryByTestId("wizard")).not.toBeInTheDocument();
+ expect(screen.queryByText("wizard")).not.toBeInTheDocument();
});
- it("keeps the wizard mounted even after hasWorkspace flips to true mid-flow", () => {
- // Controls the hasWorkspace prop from outside so we can simulate
- // step 0 of the wizard creating a workspace while steps 1-3 still need
- // to render. The gate should ignore the prop change and hold the wizard.
- function Harness() {
- const [hasWorkspace, setHasWorkspace] = useState(false);
- return (
- <>
- <button
- type="button"
- data-testid="grant-workspace"
- onClick={() => setHasWorkspace(true)}
- >
- grant
- </button>
- <OnboardingGate
- hasWorkspace={hasWorkspace}
- onboarding={() => <div data-testid="wizard">wizard</div>}
- >
- <div data-testid="main">main shell</div>
- </OnboardingGate>
- </>
- );
- }
-
- render(<Harness />);
- expect(screen.getByTestId("wizard")).toBeInTheDocument();
+ it("renders onboarding when workspace list is empty", () => {
+ const qc = createTestQueryClient([]);
+ renderGate(qc);
+ expect(screen.getByText("wizard")).toBeInTheDocument();
+ expect(screen.queryByTestId("main")).not.toBeInTheDocument();
+ });
+
+ it("keeps the wizard mounted even after workspaces appear in cache mid-flow", () => {
+ const qc = createTestQueryClient([]);
+ renderGate(qc);
+
+ expect(screen.getByText("wizard")).toBeInTheDocument();
+
+ // Simulate the onboarding wizard creating a workspace mid-flow.
act(() => {
- screen.getByTestId("grant-workspace").click();
+ qc.setQueryData(workspaceKeys.list(), [
+ { id: "ws-new", slug: "new-team" },
+ ]);
});
- // Prop change alone does not dismiss the wizard — only onComplete does.
- expect(screen.getByTestId("wizard")).toBeInTheDocument();
+ // Wizard should still be visible — only onComplete dismisses it.
+ expect(screen.getByText("wizard")).toBeInTheDocument();
expect(screen.queryByTestId("main")).not.toBeInTheDocument();
});
it("transitions to children after the wizard calls onComplete", () => {
- render(
- <OnboardingGate
- hasWorkspace={false}
- onboarding={(onComplete) => (
- <button type="button" data-testid="finish" onClick={onComplete}>
- finish
- </button>
- )}
- >
- <div data-testid="main">main shell</div>
- </OnboardingGate>,
- );
+ const qc = createTestQueryClient([]);
+ renderGate(qc);
expect(screen.getByTestId("finish")).toBeInTheDocument();
diff --git a/apps/desktop/src/renderer/src/components/onboarding-gate.tsx b/apps/desktop/src/renderer/src/components/onboarding-gate.tsx
index 764e05172a..f1c2a07159 100644
--- a/apps/desktop/src/renderer/src/components/onboarding-gate.tsx
+++ b/apps/desktop/src/renderer/src/components/onboarding-gate.tsx
@@ -1,29 +1,36 @@
import { useState, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { workspaceListOptions } from "@multica/core/workspace/queries";
/**
- * Renders `onboarding` as a full-screen takeover when the user logs in
- * without a workspace, otherwise renders `children`.
+ * Renders `onboarding` as a full-screen takeover when the user has no
+ * workspaces, otherwise renders `children`.
*
- * The "needs onboarding" decision is frozen at first mount via the lazy
- * useState initializer so the onboarding view controls its own exit: the
- * onboarding component calls the `onComplete` callback when it's ready to
- * hand off to `children`, instead of getting unmounted the moment the
- * workspace store updates.
+ * Reads the workspace list directly from React Query — this works regardless
+ * of whether a WorkspaceSlugProvider is mounted, unlike useCurrentWorkspace()
+ * which depends on slug context from the router tree.
*
- * Assumes `hasWorkspace` is definitive at first render: desktop only mounts
- * DesktopShell after AppContent's bootstrapping flag resolves, so the first
- * render of this component reflects the actual server state.
+ * The onboarding decision is frozen at first mount via the lazy useState
+ * initializer: this way the onboarding wizard controls its own exit by
+ * calling the `onComplete` callback, instead of being unmounted the moment
+ * the workspace list updates mid-flow (e.g. after the user creates their
+ * first workspace in step 1 but still has steps 2-3 to complete).
+ *
+ * The frozen decision only triggers when the initial query has settled AND
+ * the list is empty. While the list is loading, children are rendered
+ * (the shell shows its own loading state).
*/
export function OnboardingGate({
- hasWorkspace,
onboarding,
children,
}: {
- hasWorkspace: boolean;
onboarding: (onComplete: () => void) => ReactNode;
children: ReactNode;
}) {
- const [initialNeedsOnboarding] = useState(() => !hasWorkspace);
+ const { data: workspaces, isFetched } = useQuery(workspaceListOptions());
+ const hasWorkspaces = !isFetched || (workspaces?.length ?? 0) > 0;
+
+ const [initialNeedsOnboarding] = useState(() => !hasWorkspaces);
const [onboardingDone, setOnboardingDone] = useState(false);
if (initialNeedsOnboarding && !onboardingDone) {
diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
new file mode 100644
index 0000000000..51c6384424
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
@@ -0,0 +1,60 @@
+import { useEffect, useRef } from "react";
+import { Outlet, useNavigate, useParams } from "react-router-dom";
+import { useQuery } from "@tanstack/react-query";
+import { WorkspaceSlugProvider, paths } from "@multica/core/paths";
+import { workspaceBySlugOptions } from "@multica/core/workspace";
+import {
+ setCurrentWorkspace,
+ rehydrateAllWorkspaceStores,
+} from "@multica/core/platform";
+import { useAuthStore } from "@multica/core/auth";
+
+/**
+ * Desktop equivalent of apps/web/app/[workspaceSlug]/layout.tsx.
+ *
+ * Reads :workspaceSlug from react-router params, resolves it to a Workspace
+ * object via the React Query list cache, and syncs the URL-derived workspace
+ * into the platform singleton (slug + UUID). Children (DashboardGuard +
+ * dashboard layout) handle auth check, loading, and workspace-not-found.
+ */
+export function WorkspaceRouteLayout() {
+ const { workspaceSlug } = useParams<{ workspaceSlug: string }>();
+ const navigate = useNavigate();
+ const user = useAuthStore((s) => s.user);
+ const isAuthLoading = useAuthStore((s) => s.isLoading);
+
+ const { data: workspace, isFetched: listFetched } = useQuery({
+ ...workspaceBySlugOptions(workspaceSlug ?? ""),
+ enabled: !!user && !!workspaceSlug,
+ });
+
+ // Render-phase sync (same pattern as web layout).
+ const syncedSlugRef = useRef<string | null>(null);
+ if (workspace && workspaceSlug && syncedSlugRef.current !== workspaceSlug) {
+ setCurrentWorkspace(workspaceSlug, workspace.id);
+ rehydrateAllWorkspaceStores();
+ // Double-write legacy localStorage key for rollback compatibility — see
+ // apps/web/app/[workspaceSlug]/layout.tsx for the full rationale.
+ try {
+ localStorage.setItem("multica_workspace_id", workspace.id);
+ } catch {
+ // non-critical
+ }
+ syncedSlugRef.current = workspaceSlug;
+ }
+
+ // Slug doesn't resolve → onboarding. Skip when user is null.
+ useEffect(() => {
+ if (!user) return;
+ if (listFetched && !workspace) navigate(paths.onboarding(), { replace: true });
+ }, [user, listFetched, workspace, navigate]);
+
+ if (isAuthLoading) return null;
+ if (!workspaceSlug) return null;
+
+ return (
+ <WorkspaceSlugProvider slug={workspaceSlug}>
+ <Outlet />
+ </WorkspaceSlugProvider>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/pages/login.tsx b/apps/desktop/src/renderer/src/pages/login.tsx
index 8420aabeba..df8ab5ac51 100644
--- a/apps/desktop/src/renderer/src/pages/login.tsx
+++ b/apps/desktop/src/renderer/src/pages/login.tsx
@@ -4,8 +4,6 @@ import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
const WEB_URL = import.meta.env.VITE_APP_URL || "http://localhost:3000";
export function DesktopLoginPage() {
- const lastWorkspaceId = localStorage.getItem("multica_workspace_id");
-
const handleGoogleLogin = () => {
// Open web login page in the default browser with platform=desktop flag.
// The web callback will redirect back via multica:// deep link with the token.
@@ -23,9 +21,9 @@ export function DesktopLoginPage() {
/>
<LoginPage
logo={<MulticaIcon bordered size="lg" />}
- lastWorkspaceId={lastWorkspaceId}
onSuccess={() => {
- // Auth store update triggers AppContent re-render → shows DesktopShell
+ // Auth store update triggers AppContent re-render → shows DesktopShell.
+ // Initial workspace navigation happens in routes.tsx via IndexRedirect.
}}
onGoogleLogin={handleGoogleLogin}
/>
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index 33431f4c34..ab16785f14 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -6,6 +6,7 @@ import {
useMatches,
} from "react-router-dom";
import type { RouteObject } from "react-router-dom";
+import { useQuery } from "@tanstack/react-query";
import { IssueDetailPage } from "./pages/issue-detail-page";
import { ProjectDetailPage } from "./pages/project-detail-page";
import { AutopilotDetailPage } from "./pages/autopilot-detail-page";
@@ -22,8 +23,11 @@ import { SettingsPage } from "@multica/views/settings";
import { OnboardingWizard } from "@multica/views/onboarding";
import { InvitePage } from "@multica/views/invite";
import { useNavigation } from "@multica/views/navigation";
+import { paths } from "@multica/core/paths";
+import { workspaceListOptions } from "@multica/core/workspace/queries";
import { Server } from "lucide-react";
import { DaemonSettingsTab } from "./components/daemon-settings-tab";
+import { WorkspaceRouteLayout } from "./components/workspace-route-layout";
/**
* Sets document.title from the deepest matched route's handle.title.
@@ -57,7 +61,37 @@ function PageShell() {
function OnboardingRoute() {
const nav = useNavigation();
- return <OnboardingWizard onComplete={() => nav.push("/issues")} />;
+ return (
+ <OnboardingWizard
+ onComplete={(ws) => nav.push(paths.workspace(ws.slug).issues())}
+ />
+ );
+}
+
+/**
+ * Root index route: resolves the URL-less `/` path to a concrete destination.
+ *
+ * Runs both on first login (App.tsx seeded the cache) and on app reopen
+ * (AuthInitializer seeded the cache). Reading from React Query avoids
+ * duplicate fetches across tabs — each tab's memory router hits this
+ * component independently but the query is deduped.
+ *
+ * Sends first-time users without any workspace to onboarding, everyone
+ * else to their first workspace's issues page. Persisted tab paths that
+ * already carry a workspace slug bypass this component entirely.
+ */
+function IndexRedirect() {
+ const { data: wsList, isFetched } = useQuery(workspaceListOptions());
+
+ // Wait for the query to settle so we don't redirect to onboarding on
+ // the initial render before the seeded/fetched data arrives.
+ if (!isFetched) return null;
+
+ const firstWorkspace = wsList?.[0];
+ if (firstWorkspace) {
+ return <Navigate to={paths.workspace(firstWorkspace.slug).issues()} replace />;
+ }
+ return <Navigate to={paths.onboarding()} replace />;
}
function InviteRoute() {
@@ -67,51 +101,24 @@ function InviteRoute() {
return <InvitePage invitationId={id} />;
}
-/** Route definitions shared by all tabs (no layout wrapper). */
+/**
+ * Route definitions shared by all tabs.
+ *
+ * Structure mirrors the web app's [workspaceSlug]/... layout: all dashboard
+ * pages live under /:workspaceSlug, with WorkspaceRouteLayout resolving the
+ * slug to a workspace and syncing side-effects (api client, persist namespace,
+ * Zustand mirror). Global (pre-workspace) routes — onboarding and invite —
+ * sit at the top level alongside the workspace wrapper.
+ */
export const appRoutes: RouteObject[] = [
{
element: <PageShell />,
children: [
- { index: true, element: <Navigate to="/issues" replace /> },
- { path: "issues", element: <IssuesPage />, handle: { title: "Issues" } },
- {
- path: "issues/:id",
- element: <IssueDetailPage />,
- handle: { title: "Issue" },
- },
- {
- path: "projects",
- element: <ProjectsPage />,
- handle: { title: "Projects" },
- },
- {
- path: "projects/:id",
- element: <ProjectDetailPage />,
- handle: { title: "Project" },
- },
- {
- path: "autopilots",
- element: <AutopilotsPage />,
- handle: { title: "Autopilot" },
- },
- {
- path: "autopilots/:id",
- element: <AutopilotDetailPage />,
- handle: { title: "Autopilot" },
- },
- {
- path: "my-issues",
- element: <MyIssuesPage />,
- handle: { title: "My Issues" },
- },
- {
- path: "runtimes",
- element: <RuntimesPage topSlot={<DaemonRuntimeCard />} />,
- handle: { title: "Runtimes" },
- },
- { path: "skills", element: <SkillsPage />, handle: { title: "Skills" } },
- { path: "agents", element: <AgentsPage />, handle: { title: "Agents" } },
- { path: "inbox", element: <InboxPage />, handle: { title: "Inbox" } },
+ // Top-level index: no slug yet. `IndexRedirect` reads the workspace
+ // list from React Query cache (seeded by AuthInitializer on reopen
+ // or App.tsx on deep-link login) and bounces to the first
+ // workspace's issues page — or onboarding if the user has none.
+ { index: true, element: <IndexRedirect /> },
{
path: "onboarding",
element: <OnboardingRoute />,
@@ -123,20 +130,66 @@ export const appRoutes: RouteObject[] = [
handle: { title: "Accept Invite" },
},
{
- path: "settings",
- element: (
- <SettingsPage
- extraAccountTabs={[
- {
- value: "daemon",
- label: "Daemon",
- icon: Server,
- content: <DaemonSettingsTab />,
- },
- ]}
- />
- ),
- handle: { title: "Settings" },
+ path: ":workspaceSlug",
+ element: <WorkspaceRouteLayout />,
+ children: [
+ { index: true, element: <Navigate to="issues" replace /> },
+ { path: "issues", element: <IssuesPage />, handle: { title: "Issues" } },
+ {
+ path: "issues/:id",
+ element: <IssueDetailPage />,
+ handle: { title: "Issue" },
+ },
+ {
+ path: "projects",
+ element: <ProjectsPage />,
+ handle: { title: "Projects" },
+ },
+ {
+ path: "projects/:id",
+ element: <ProjectDetailPage />,
+ handle: { title: "Project" },
+ },
+ {
+ path: "autopilots",
+ element: <AutopilotsPage />,
+ handle: { title: "Autopilot" },
+ },
+ {
+ path: "autopilots/:id",
+ element: <AutopilotDetailPage />,
+ handle: { title: "Autopilot" },
+ },
+ {
+ path: "my-issues",
+ element: <MyIssuesPage />,
+ handle: { title: "My Issues" },
+ },
+ {
+ path: "runtimes",
+ element: <RuntimesPage topSlot={<DaemonRuntimeCard />} />,
+ handle: { title: "Runtimes" },
+ },
+ { path: "skills", element: <SkillsPage />, handle: { title: "Skills" } },
+ { path: "agents", element: <AgentsPage />, handle: { title: "Agents" } },
+ { path: "inbox", element: <InboxPage />, handle: { title: "Inbox" } },
+ {
+ path: "settings",
+ element: (
+ <SettingsPage
+ extraAccountTabs={[
+ {
+ value: "daemon",
+ label: "Daemon",
+ icon: Server,
+ content: <DaemonSettingsTab />,
+ },
+ ]}
+ />
+ ),
+ handle: { title: "Settings" },
+ },
+ ],
},
],
},
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index fcf805f792..6842b44d7b 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -3,6 +3,7 @@ import { createJSONStorage, persist } from "zustand/middleware";
import { arrayMove } from "@dnd-kit/sortable";
import { createPersistStorage, defaultStorage } from "@multica/core/platform";
import { createSafeId } from "@multica/core/utils";
+import { isGlobalPath } from "@multica/core/paths";
import type { DataRouter } from "react-router-dom";
import { createTabRouter } from "../routes";
@@ -45,29 +46,50 @@ interface TabStore {
// ---------------------------------------------------------------------------
const ROUTE_ICONS: Record<string, string> = {
- "/inbox": "Inbox",
- "/my-issues": "CircleUser",
- "/issues": "ListTodo",
- "/projects": "FolderKanban",
- "/agents": "Bot",
- "/runtimes": "Monitor",
- "/skills": "BookOpenText",
- "/settings": "Settings",
+ inbox: "Inbox",
+ "my-issues": "CircleUser",
+ issues: "ListTodo",
+ projects: "FolderKanban",
+ autopilots: "ListTodo",
+ agents: "Bot",
+ runtimes: "Monitor",
+ skills: "BookOpenText",
+ settings: "Settings",
};
-/** Resolve a route icon. Title is NOT determined here — it comes from document.title. */
+/**
+ * Resolve a route icon from a pathname. Title is NOT determined here — it
+ * comes from document.title.
+ *
+ * Path shape after the workspace URL refactor:
+ * - workspace-scoped: `/{workspaceSlug}/{route}/...` → use segment index 1
+ * - global (onboarding/invite/auth/login): `/{route}/...` → use segment index 0
+ *
+ * `isGlobalPath` is the single source of truth for which prefixes are global.
+ */
export function resolveRouteIcon(pathname: string): string {
- return ROUTE_ICONS[pathname]
- ?? (pathname.startsWith("/issues/") ? "ListTodo" : undefined)
- ?? (pathname.startsWith("/projects/") ? "FolderKanban" : undefined)
- ?? "ListTodo";
+ const segments = pathname.split("/").filter(Boolean);
+ const routeSegment = isGlobalPath(pathname)
+ ? (segments[0] ?? "")
+ : (segments[1] ?? "");
+ return ROUTE_ICONS[routeSegment] ?? "ListTodo";
}
// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------
-const DEFAULT_PATH = "/issues";
+/**
+ * Sentinel path for new tabs with no explicit destination. The tab store is
+ * workspace-implicit — it doesn't know which workspace is active, so it can't
+ * build a `/:slug/issues` path itself. Instead we hand off to the router: `/`
+ * matches the top-level index route, which redirects to the workspace default
+ * (slug-aware redirect lives in routes.tsx / App.tsx).
+ *
+ * `title` and `icon` on the placeholder tab get overwritten by
+ * useTabRouterSync + useActiveTitleSync once the redirect resolves.
+ */
+const DEFAULT_PATH = "/";
function createId(): string {
return createSafeId();
@@ -177,12 +199,28 @@ export const useTabStore = create<TabStore>()(
| undefined;
if (!persisted?.tabs?.length) return currentState;
- const tabs: Tab[] = persisted.tabs.map((tab) => ({
- ...tab,
- router: createTabRouter(tab.path),
- historyIndex: 0,
- historyLength: 1,
- }));
+ const tabs: Tab[] = persisted.tabs.map((tab) => {
+ // Migration: pre-refactor tab paths like "/issues/abc" lack a
+ // workspace slug prefix. These would 404 in the new router.
+ // Reset to "/" so IndexRedirect picks the right workspace.
+ let path = tab.path;
+ if (path !== "/" && !isGlobalPath(path)) {
+ const segments = path.split("/").filter(Boolean);
+ const firstSegment = segments[0] ?? "";
+ // If the first segment IS a known route name (e.g. "issues",
+ // "projects"), it's an old-format path missing the slug prefix.
+ if (ROUTE_ICONS[firstSegment]) {
+ path = "/";
+ }
+ }
+ return {
+ ...tab,
+ path,
+ router: createTabRouter(path),
+ historyIndex: 0,
+ historyLength: 1,
+ };
+ });
// Validate activeTabId — fall back to first tab if stale
const activeTabId = tabs.some((t) => t.id === persisted.activeTabId)
diff --git a/apps/web/app/(auth)/invite/[id]/page.tsx b/apps/web/app/(auth)/invite/[id]/page.tsx
index fc6ded9a07..fe8e3b162f 100644
--- a/apps/web/app/(auth)/invite/[id]/page.tsx
+++ b/apps/web/app/(auth)/invite/[id]/page.tsx
@@ -3,6 +3,7 @@
import { useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import { useAuthStore } from "@multica/core/auth";
+import { paths } from "@multica/core/paths";
import { InvitePage } from "@multica/views/invite";
export default function InviteAcceptPage() {
@@ -14,7 +15,9 @@ export default function InviteAcceptPage() {
// Redirect to login if not authenticated, with a redirect back to this page.
useEffect(() => {
if (!isLoading && !user) {
- router.replace(`/login?next=/invite/${params.id}`);
+ router.replace(
+ `${paths.login()}?next=${encodeURIComponent(paths.invite(params.id))}`,
+ );
}
}, [isLoading, user, router, params.id]);
diff --git a/apps/web/app/(auth)/login/page.test.tsx b/apps/web/app/(auth)/login/page.test.tsx
index 9bf8d8db89..007659f6b3 100644
--- a/apps/web/app/(auth)/login/page.test.tsx
+++ b/apps/web/app/(auth)/login/page.test.tsx
@@ -11,13 +11,10 @@ function createWrapper() {
);
}
-const { mockSendCode, mockVerifyCode, mockHydrateWorkspace } = vi.hoisted(
- () => ({
- mockSendCode: vi.fn(),
- mockVerifyCode: vi.fn(),
- mockHydrateWorkspace: vi.fn(),
- }),
-);
+const { mockSendCode, mockVerifyCode } = vi.hoisted(() => ({
+ mockSendCode: vi.fn(),
+ mockVerifyCode: vi.fn(),
+}));
// Mock next/navigation
vi.mock("next/navigation", () => ({
@@ -47,16 +44,6 @@ vi.mock("@/features/auth/auth-cookie", () => ({
setLoggedInCookie: vi.fn(),
}));
-// Mock workspace store — shared LoginPage uses getState().hydrateWorkspace
-vi.mock("@multica/core/workspace", () => {
- const wsState = { hydrateWorkspace: mockHydrateWorkspace };
- const useWorkspaceStore = Object.assign(
- (selector: (s: typeof wsState) => unknown) => selector(wsState),
- { getState: () => wsState },
- );
- return { useWorkspaceStore };
-});
-
// Mock api
vi.mock("@multica/core/api", () => ({
api: {
diff --git a/apps/web/app/(auth)/login/page.tsx b/apps/web/app/(auth)/login/page.tsx
index 78de1dd63e..bfcd9cdd8b 100644
--- a/apps/web/app/(auth)/login/page.tsx
+++ b/apps/web/app/(auth)/login/page.tsx
@@ -2,8 +2,11 @@
import { Suspense, useEffect } from "react";
import { useSearchParams, useRouter } from "next/navigation";
+import { useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+import { paths } from "@multica/core/paths";
+import type { Workspace } from "@multica/core/types";
import { setLoggedInCookie } from "@/features/auth/auth-cookie";
import { LoginPage, validateCliCallback } from "@multica/views/auth";
@@ -11,6 +14,7 @@ const googleClientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;
function LoginPageContent() {
const router = useRouter();
+ const qc = useQueryClient();
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
const searchParams = useSearchParams();
@@ -18,30 +22,46 @@ function LoginPageContent() {
const cliCallbackRaw = searchParams.get("cli_callback");
const cliState = searchParams.get("cli_state") || "";
const platform = searchParams.get("platform");
- const nextUrl = searchParams.get("next") || "/issues";
+ // `next` carries a protected URL the user was originally headed to
+ // (e.g. /invite/{id}). With URL-driven workspaces there is no legacy
+ // "/issues" default — if `next` is absent we decide after login based on
+ // the user's workspace list.
+ const nextUrl = searchParams.get("next");
- // Already authenticated — redirect to dashboard (skip if CLI callback)
+ // Already authenticated — honor ?next= or fall back to first workspace /
+ // onboarding. Skip this entire path when the user arrived to authorize the CLI.
useEffect(() => {
- if (!isLoading && user && !cliCallbackRaw) {
+ if (isLoading || !user || cliCallbackRaw) return;
+ if (nextUrl) {
router.replace(nextUrl);
+ return;
}
- }, [isLoading, user, router, nextUrl, cliCallbackRaw]);
-
- const lastWorkspaceId =
- typeof window !== "undefined"
- ? localStorage.getItem("multica_workspace_id")
- : null;
+ const list = qc.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];
+ const [first] = list;
+ router.replace(
+ first ? paths.workspace(first.slug).issues() : paths.onboarding(),
+ );
+ }, [isLoading, user, router, nextUrl, cliCallbackRaw, qc]);
const handleSuccess = () => {
- const ws = useWorkspaceStore.getState().workspace;
- router.push(ws ? nextUrl : "/onboarding");
+ if (nextUrl) {
+ router.push(nextUrl);
+ return;
+ }
+ // The LoginPage view populates the workspace list cache before calling
+ // onSuccess, so it's safe to read here.
+ const list = qc.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];
+ const [first] = list;
+ router.push(
+ first ? paths.workspace(first.slug).issues() : paths.onboarding(),
+ );
};
// Build Google OAuth state: encode platform + next URL so the callback
// can redirect to the right place after login.
const googleState = [
platform === "desktop" ? "platform:desktop" : "",
- nextUrl !== "/issues" ? `next:${nextUrl}` : "",
+ nextUrl ? `next:${nextUrl}` : "",
]
.filter(Boolean)
.join(",") || undefined;
@@ -63,7 +83,6 @@ function LoginPageContent() {
? { url: cliCallbackRaw, state: cliState }
: undefined
}
- lastWorkspaceId={lastWorkspaceId}
onTokenObtained={setLoggedInCookie}
/>
);
diff --git a/apps/web/app/(auth)/onboarding/page.tsx b/apps/web/app/(auth)/onboarding/page.tsx
index 6afcfecc1e..51b711039f 100644
--- a/apps/web/app/(auth)/onboarding/page.tsx
+++ b/apps/web/app/(auth)/onboarding/page.tsx
@@ -3,6 +3,7 @@
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@multica/core/auth";
+import { paths } from "@multica/core/paths";
import { OnboardingWizard } from "@multica/views/onboarding";
export default function OnboardingPage() {
@@ -12,12 +13,14 @@ export default function OnboardingPage() {
// Redirect to login if not authenticated
useEffect(() => {
- if (!isLoading && !user) router.replace("/login");
+ if (!isLoading && !user) router.replace(paths.login());
}, [isLoading, user, router]);
if (isLoading || !user) return null;
return (
- <OnboardingWizard onComplete={() => router.push("/issues")} />
+ <OnboardingWizard
+ onComplete={(ws) => router.push(paths.workspace(ws.slug).issues())}
+ />
);
}
diff --git a/apps/web/app/(landing)/page.tsx b/apps/web/app/(landing)/page.tsx
index 5735211b77..293108031d 100644
--- a/apps/web/app/(landing)/page.tsx
+++ b/apps/web/app/(landing)/page.tsx
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { MulticaLanding } from "@/features/landing/components/multica-landing";
+import { RedirectIfAuthenticated } from "@/features/landing/components/redirect-if-authenticated";
export const metadata: Metadata = {
title: {
@@ -19,5 +20,10 @@ export const metadata: Metadata = {
};
export default function LandingPage() {
- return <MulticaLanding />;
+ return (
+ <>
+ <RedirectIfAuthenticated />
+ <MulticaLanding />
+ </>
+ );
}
diff --git a/apps/web/app/(dashboard)/agents/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/agents/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/agents/page.tsx
diff --git a/apps/web/app/(dashboard)/autopilots/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/autopilots/[id]/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/autopilots/[id]/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/autopilots/[id]/page.tsx
diff --git a/apps/web/app/(dashboard)/autopilots/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/autopilots/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/autopilots/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/autopilots/page.tsx
diff --git a/apps/web/app/(dashboard)/inbox/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/inbox/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/inbox/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/inbox/page.tsx
diff --git a/apps/web/app/(dashboard)/issues/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/issues/[id]/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/issues/[id]/page.tsx
diff --git a/apps/web/app/(dashboard)/issues/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/issues/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx
diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
similarity index 90%
rename from apps/web/app/(dashboard)/layout.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
index f7d32b79d3..a2ecebf9e6 100644
--- a/apps/web/app/(dashboard)/layout.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
@@ -11,8 +11,6 @@ export default function Layout({ children }: { children: React.ReactNode }) {
loadingIndicator={<MulticaIcon className="size-6" />}
searchSlot={<SearchTrigger />}
extra={<><SearchCommand /><ChatWindow /><ChatFab /></>}
- onboardingPath="/onboarding"
- loginPath="/login"
>
{children}
</DashboardLayout>
diff --git a/apps/web/app/(dashboard)/loading.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/loading.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/loading.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/loading.tsx
diff --git a/apps/web/app/(dashboard)/my-issues/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/my-issues/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/my-issues/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/my-issues/page.tsx
diff --git a/apps/web/app/(dashboard)/projects/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/projects/[id]/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/projects/[id]/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/projects/[id]/page.tsx
diff --git a/apps/web/app/(dashboard)/projects/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/projects/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/projects/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/projects/page.tsx
diff --git a/apps/web/app/(dashboard)/runtimes/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/runtimes/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/runtimes/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/runtimes/page.tsx
diff --git a/apps/web/app/(dashboard)/settings/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/settings/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/settings/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/settings/page.tsx
diff --git a/apps/web/app/(dashboard)/skills/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/skills/page.tsx
similarity index 100%
rename from apps/web/app/(dashboard)/skills/page.tsx
rename to apps/web/app/[workspaceSlug]/(dashboard)/skills/page.tsx
diff --git a/apps/web/app/[workspaceSlug]/layout.tsx b/apps/web/app/[workspaceSlug]/layout.tsx
new file mode 100644
index 0000000000..6fabd5dd24
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/layout.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import { use, useEffect, useRef } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { WorkspaceSlugProvider, paths } from "@multica/core/paths";
+import { workspaceBySlugOptions } from "@multica/core/workspace";
+import {
+ setCurrentWorkspace,
+ rehydrateAllWorkspaceStores,
+} from "@multica/core/platform";
+import { useAuthStore } from "@multica/core/auth";
+
+export default function WorkspaceLayout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<{ workspaceSlug: string }>;
+}) {
+ const { workspaceSlug } = use(params);
+ const user = useAuthStore((s) => s.user);
+ const isAuthLoading = useAuthStore((s) => s.isLoading);
+ const router = useRouter();
+
+ // Resolve workspace by slug from the React Query list cache.
+ // Enabled only when user is authenticated — otherwise the list query isn't seeded.
+ const { data: workspace, isFetched: listFetched } = useQuery({
+ ...workspaceBySlugOptions(workspaceSlug),
+ enabled: !!user,
+ });
+
+ // Render-phase sync: set the current workspace slug + UUID into the
+ // platform singleton BEFORE children render. This ensures the first
+ // child query's X-Workspace-Slug header is already correct.
+ // The ref guard prevents re-running on every render.
+ const syncedSlugRef = useRef<string | null>(null);
+ if (workspace && syncedSlugRef.current !== workspaceSlug) {
+ setCurrentWorkspace(workspaceSlug, workspace.id);
+ rehydrateAllWorkspaceStores();
+ syncedSlugRef.current = workspaceSlug;
+ }
+
+ // Cookie write (last_workspace_slug) — proxy reads it on next page load.
+ // ALSO write legacy localStorage["multica_workspace_id"] for forward/back
+ // compatibility: if this version ever gets reverted to the pre-refactor
+ // build, the legacy code reads that localStorage key to know which
+ // workspace to attach to API requests. Without double-writing, a rollback
+ // would leave returning users with empty data (API calls would have no
+ // X-Workspace-ID header). Forward compatible — new code ignores this key.
+ useEffect(() => {
+ if (!workspace || typeof document === "undefined") return;
+ const oneYear = 60 * 60 * 24 * 365;
+ const secure = location.protocol === "https:" ? "; Secure" : "";
+ document.cookie = `last_workspace_slug=${encodeURIComponent(workspaceSlug)}; path=/; max-age=${oneYear}; SameSite=Lax${secure}`;
+ try {
+ localStorage.setItem("multica_workspace_id", workspace.id);
+ } catch {
+ // localStorage may be unavailable in restricted contexts; non-critical.
+ }
+ }, [workspace, workspaceSlug]);
+
+ // Slug doesn't match any workspace the user has access to → onboarding.
+ // Wait for the list query to settle so we don't bounce on first render.
+ // Skip when user is null — DashboardGuard handles the /login redirect.
+ useEffect(() => {
+ if (!user) return;
+ if (listFetched && !workspace) router.replace(paths.onboarding());
+ }, [user, listFetched, workspace, router]);
+
+ // Auth still loading → render nothing (let DashboardGuard show its loader).
+ if (isAuthLoading) return null;
+
+ return (
+ <WorkspaceSlugProvider slug={workspaceSlug}>
+ {children}
+ </WorkspaceSlugProvider>
+ );
+}
diff --git a/apps/web/app/auth/callback/page.tsx b/apps/web/app/auth/callback/page.tsx
index 31f437961f..d458c63b66 100644
--- a/apps/web/app/auth/callback/page.tsx
+++ b/apps/web/app/auth/callback/page.tsx
@@ -4,8 +4,8 @@ import { Suspense, useEffect, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
import { workspaceKeys } from "@multica/core/workspace/queries";
+import { paths } from "@multica/core/paths";
import { api } from "@multica/core/api";
import {
Card,
@@ -22,7 +22,6 @@ function CallbackContent() {
const searchParams = useSearchParams();
const qc = useQueryClient();
const loginWithGoogle = useAuthStore((s) => s.loginWithGoogle);
- const hydrateWorkspace = useWorkspaceStore((s) => s.hydrateWorkspace);
const [error, setError] = useState("");
const [desktopToken, setDesktopToken] = useState<string | null>(null);
@@ -64,17 +63,21 @@ function CallbackContent() {
.then(async () => {
const wsList = await api.listWorkspaces();
qc.setQueryData(workspaceKeys.list(), wsList);
- const lastWsId = localStorage.getItem("multica_workspace_id");
- const ws = await hydrateWorkspace(wsList, lastWsId);
- // Honor the ?next= redirect if present (e.g. /invite/{id})
- const defaultDest = ws ? "/issues" : "/onboarding";
+ // URL is now the source of truth for the current workspace — the
+ // [workspaceSlug]/layout syncs stores + cookie once we navigate.
+ // Honor ?next= first (e.g. came from /invite/{id}), otherwise land
+ // in the first workspace's issues, or /onboarding if the user has none.
+ const [first] = wsList;
+ const defaultDest = first
+ ? paths.workspace(first.slug).issues()
+ : paths.onboarding();
router.push(nextUrl || defaultDest);
})
.catch((err) => {
setError(err instanceof Error ? err.message : "Login failed");
});
}
- }, [searchParams, loginWithGoogle, hydrateWorkspace, router, qc]);
+ }, [searchParams, loginWithGoogle, router, qc]);
if (desktopToken) {
return (
@@ -111,7 +114,7 @@ function CallbackContent() {
<CardDescription>{error}</CardDescription>
</CardHeader>
<CardContent className="flex justify-center">
- <a href="/login" className="text-primary underline-offset-4 hover:underline">
+ <a href={paths.login()} className="text-primary underline-offset-4 hover:underline">
Back to login
</a>
</CardContent>
diff --git a/apps/web/features/landing/components/how-it-works-section.tsx b/apps/web/features/landing/components/how-it-works-section.tsx
index 6bfc68a2c0..5718c78553 100644
--- a/apps/web/features/landing/components/how-it-works-section.tsx
+++ b/apps/web/features/landing/components/how-it-works-section.tsx
@@ -41,7 +41,7 @@ export function HowItWorksSection() {
</div>
<div className="mt-14 flex flex-wrap items-center gap-4">
- <Link href={user ? "/issues" : "/login"} className={heroButtonClassName("solid")}>
+ <Link href={user ? "/" : "/login"} className={heroButtonClassName("solid")}>
{user ? t.header.dashboard : t.howItWorks.cta}
</Link>
<Link
diff --git a/apps/web/features/landing/components/landing-footer.tsx b/apps/web/features/landing/components/landing-footer.tsx
index 94649a90f4..003c1d7cd7 100644
--- a/apps/web/features/landing/components/landing-footer.tsx
+++ b/apps/web/features/landing/components/landing-footer.tsx
@@ -48,7 +48,7 @@ export function LandingFooter() {
</div>
<div className="mt-6">
<Link
- href={user ? "/issues" : "/login"}
+ href={user ? "/" : "/login"}
className="inline-flex items-center justify-center rounded-[11px] bg-white px-5 py-2.5 text-[13px] font-semibold text-[#0a0d12] transition-colors hover:bg-white/88"
>
{user ? t.header.dashboard : t.footer.cta}
diff --git a/apps/web/features/landing/components/landing-header.tsx b/apps/web/features/landing/components/landing-header.tsx
index cd5fdcdcf2..4e3427f4eb 100644
--- a/apps/web/features/landing/components/landing-header.tsx
+++ b/apps/web/features/landing/components/landing-header.tsx
@@ -54,7 +54,7 @@ export function LandingHeader({
{t.header.github}
</Link>
<Link
- href={user ? "/issues" : "/login"}
+ href={user ? "/" : "/login"}
className={headerButtonClassName("solid", variant)}
>
{user ? t.header.dashboard : t.header.login}
diff --git a/apps/web/features/landing/components/landing-hero.tsx b/apps/web/features/landing/components/landing-hero.tsx
index 37df9074be..f489f03e0d 100644
--- a/apps/web/features/landing/components/landing-hero.tsx
+++ b/apps/web/features/landing/components/landing-hero.tsx
@@ -41,7 +41,7 @@ export function LandingHero() {
</p>
<div className="mt-8 flex flex-wrap items-center justify-center gap-3">
- <Link href={user ? "/issues" : "/login"} className={heroButtonClassName("solid")}>
+ <Link href={user ? "/" : "/login"} className={heroButtonClassName("solid")}>
{user ? t.header.dashboard : t.hero.cta}
</Link>
<Link
diff --git a/apps/web/features/landing/components/redirect-if-authenticated.tsx b/apps/web/features/landing/components/redirect-if-authenticated.tsx
new file mode 100644
index 0000000000..57e011ba78
--- /dev/null
+++ b/apps/web/features/landing/components/redirect-if-authenticated.tsx
@@ -0,0 +1,45 @@
+"use client";
+
+import { useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { useQuery } from "@tanstack/react-query";
+import { useAuthStore } from "@multica/core/auth";
+import { workspaceListOptions } from "@multica/core/workspace";
+import { paths } from "@multica/core/paths";
+
+/**
+ * Client-side fallback redirect for authenticated visitors on the landing page.
+ *
+ * The primary path for logged-in users hitting `/` is a server-side redirect
+ * in the Next.js proxy/middleware, driven by the `last_workspace_slug` cookie.
+ * That cookie is set by the workspace layout on every visit. But on *first
+ * login* — before the user has ever visited a workspace — the cookie is
+ * absent, so the proxy falls through to the landing page. This component
+ * covers that gap: once auth is resolved and the workspace list has loaded,
+ * push the user into their workspace (or onboarding if they have none).
+ *
+ * Renders nothing. Uses `router.replace` so the landing page never enters
+ * browser history for authenticated users.
+ */
+export function RedirectIfAuthenticated() {
+ const router = useRouter();
+ const user = useAuthStore((s) => s.user);
+ const isLoading = useAuthStore((s) => s.isLoading);
+
+ const { data: list } = useQuery({
+ ...workspaceListOptions(),
+ enabled: !!user,
+ });
+
+ useEffect(() => {
+ if (isLoading || !user || !list) return;
+ const [first] = list;
+ if (!first) {
+ router.replace(paths.onboarding());
+ return;
+ }
+ router.replace(paths.workspace(first.slug).issues());
+ }, [isLoading, user, list, router]);
+
+ return null;
+}
diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts
index 215360bf9b..3eb107c3fc 100644
--- a/apps/web/proxy.ts
+++ b/apps/web/proxy.ts
@@ -1,10 +1,81 @@
-import { NextResponse } from "next/server";
-import type { NextRequest } from "next/server";
+import { NextResponse, type NextRequest } from "next/server";
+
+// Old workspace-scoped route segments that existed before the URL refactor
+// (pre-#1131). Any URL with these as the FIRST segment is a legacy URL that
+// needs to be rewritten to /{slug}/{route}/... so old bookmarks, deep links,
+// and post-revert-and-reapply users don't hit 404.
+const LEGACY_ROUTE_SEGMENTS = new Set([
+ "issues",
+ "projects",
+ "agents",
+ "inbox",
+ "my-issues",
+ "autopilots",
+ "runtimes",
+ "skills",
+ "settings",
+]);
+
+// Next.js 16 renamed `middleware` → `proxy`. The runtime API is identical.
+export function proxy(req: NextRequest) {
+ const { pathname } = req.nextUrl;
+ const hasSession = req.cookies.has("multica_logged_in");
+ const lastSlug = req.cookies.get("last_workspace_slug")?.value;
+
+ // --- Legacy URL redirect: /issues/... → /{slug}/issues/... ---
+ // Old bookmarks and clients that hit us before the slug migration would
+ // otherwise 404 since the route moved under [workspaceSlug].
+ const firstSegment = pathname.split("/")[1] ?? "";
+ if (LEGACY_ROUTE_SEGMENTS.has(firstSegment)) {
+ const url = req.nextUrl.clone();
+
+ if (!hasSession) {
+ url.pathname = "/login";
+ return NextResponse.redirect(url);
+ }
+
+ if (lastSlug) {
+ // Preserve deep-link path + query: /issues/abc → /{lastSlug}/issues/abc
+ url.pathname = `/${lastSlug}${pathname}`;
+ return NextResponse.redirect(url);
+ }
+
+ // Logged-in but no cookie yet (first login since slug migration, or
+ // cookie cleared). Bounce to root; the root-path logic below picks a
+ // workspace and writes the cookie, then future hits short-circuit here.
+ url.pathname = "/";
+ return NextResponse.redirect(url);
+ }
+
+ // --- Root path: redirect logged-in users to their last workspace ---
+ if (pathname === "/") {
+ if (!hasSession) return NextResponse.next();
+
+ if (lastSlug) {
+ const url = req.nextUrl.clone();
+ url.pathname = `/${lastSlug}/issues`;
+ return NextResponse.redirect(url);
+ }
+
+ // No last_workspace_slug cookie → let landing page pick the first workspace
+ // client-side (features/landing/components/redirect-if-authenticated.tsx).
+ return NextResponse.next();
+ }
-export function proxy(_request: NextRequest) {
return NextResponse.next();
}
export const config = {
- matcher: ["/"],
+ matcher: [
+ "/",
+ "/issues/:path*",
+ "/projects/:path*",
+ "/agents/:path*",
+ "/inbox/:path*",
+ "/my-issues/:path*",
+ "/autopilots/:path*",
+ "/runtimes/:path*",
+ "/skills/:path*",
+ "/settings/:path*",
+ ],
};
diff --git a/apps/web/test/helpers.tsx b/apps/web/test/helpers.tsx
index 8ed9aec9dd..78ac11cbe2 100644
--- a/apps/web/test/helpers.tsx
+++ b/apps/web/test/helpers.tsx
@@ -78,7 +78,6 @@ export const mockAuthValue: Record<string, any> = {
isLoading: false,
login: vi.fn(),
logout: vi.fn(),
- switchWorkspace: vi.fn(),
updateWorkspace: vi.fn(),
updateCurrentUser: vi.fn(),
getMemberName: (userId: string) => {
diff --git a/docs/plans/2026-04-15-workspace-slug-url-refactor.md b/docs/plans/2026-04-15-workspace-slug-url-refactor.md
new file mode 100644
index 0000000000..62eb83103b
--- /dev/null
+++ b/docs/plans/2026-04-15-workspace-slug-url-refactor.md
@@ -0,0 +1,1819 @@
+# Workspace Slug URL Refactor Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Make the URL the single source of truth for workspace context by moving from workspace-agnostic URLs (`/issues`) to slug-scoped URLs (`/{workspaceSlug}/issues`).
+
+**Architecture:** URL carries the workspace slug as the first path segment. All derived state (API client workspace id, persist-store namespace, Zustand "current workspace" selector) flows from URL → React Query cache → derived hook. Switching workspace becomes navigation, never a state mutation. Web uses Next.js `[workspaceSlug]` dynamic segment; desktop mirrors with react-router `:workspaceSlug` param. `useWorkspaceStore.workspace` / `hydrateWorkspace` / `switchWorkspace` actions are removed in favor of URL-driven selectors.
+
+**Tech Stack:** Next.js 15 App Router, react-router 6 (desktop memory router), TanStack Query, Zustand (persist + URL-driven), Go/Chi (backend, slug reserved-word validation only).
+
+**Branch:** `NevilleQingNY/workspace-url-refactor` (from latest `main`).
+
+**Scope:** One atomic PR. Intermediate states are not runnable because URL structure changes atomically. Develop in a worktree, self-test exhaustively, one review, merge.
+
+---
+
+## Why This Refactor
+
+Current state (measured, not claimed):
+
+- Workspace identity lives in 4 synchronized copies: `localStorage["multica_workspace_id"]`, `useWorkspaceStore.workspace`, `api._workspaceId`, `_currentWsId` module var in `packages/core/platform/workspace-storage.ts`. Any hand-synchronization drift = bug.
+- URL `/issues/abc` has no workspace marker. A link shared across workspaces opens with the receiver's cached workspace → 404 or wrong data.
+- `localStorage["multica_workspace_id"]` is a single global key. Two tabs on different workspaces overwrite each other on refresh.
+- `useCreateWorkspace` / `useLeaveWorkspace` / `useDeleteWorkspace` call `switchWorkspace` / `hydrateWorkspace` inside `onSuccess`. This causes observable UX bugs (MUL-727 flash, MUL-728 no-navigate, MUL-820 sidebar Join).
+- Mobile has no workspace switcher because switching lives only in sidebar UI, not in the URL (MUL-509).
+
+Issues this PR closes: **MUL-43**, **MUL-509**, **MUL-723**, **MUL-727**, **MUL-728**, **MUL-820**. Out of scope: **#951** (WS half-open — unrelated realtime issue).
+
+---
+
+## Work Breakdown
+
+| Category | Count | Notes |
+|---|---|---|
+| New files to create | 5 | Path builder, derived hooks, middleware, new layout, reserved slugs |
+| Files moved (route restructure) | ~11 | `app/(dashboard)/*` → `app/[workspaceSlug]/(dashboard)/*` |
+| Files heavily modified | ~8 | workspace store, mutations, sidebar, navigation store, link-handler, desktop routes, desktop nav adapter, auth initializer |
+| Mechanical replace (path callsites) | ~20 | `push("/issues")` → `push(paths.issues())` etc. |
+| Backend | 1 | Reserved-slug validation in workspace handler |
+| E2E tests | ~20-30 assertions | URL assertions updated |
+| Deleted references to `multica_workspace_id` | ~10 | After URL becomes source of truth |
+
+---
+
+## Architecture: Before vs After
+
+### Before (current)
+
+```
+User action → switchWorkspace(ws) → mutates:
+ 1. api._workspaceId
+ 2. _currentWsId (module var)
+ 3. localStorage["multica_workspace_id"]
+ 4. useWorkspaceStore.workspace
+ 5. Rehydrates all workspace-namespaced persist stores
+→ push("/issues") [URL does not change workspace]
+```
+
+### After (target)
+
+```
+User action → push(paths.workspace(newSlug).issues())
+→ Next.js routes to app/[workspaceSlug]/(dashboard)/issues/page
+→ app/[workspaceSlug]/layout.tsx reads params.workspaceSlug
+→ resolves from React Query workspace list → Workspace object
+→ useEffect syncs:
+ 1. api.setWorkspaceId(ws.id)
+ 2. setCurrentWorkspaceId(ws.id)
+ 3. rehydrateAllWorkspaceStores()
+→ WorkspaceIdProvider supplies id to subtree (unchanged interface)
+```
+
+**Invariants enforced:**
+- No file reads `localStorage["multica_workspace_id"]` after this PR — it stops being written too.
+- `useWorkspaceStore.workspace` is removed. Callers use `useCurrentWorkspace()` which reads URL + React Query.
+- `switchWorkspace` / `hydrateWorkspace` removed. Workspace transitions = navigation only.
+- Every path expression in shared code goes through `paths.*` builder. No hardcoded `/issues` strings outside the builder module.
+
+---
+
+## Phase 1: Foundation — Backend + Core Path Utilities (Tasks 1–5)
+
+### Task 1: Backend reserved-slug validation
+
+**Files:**
+- Modify: `server/internal/handler/workspace.go` (around line 18, 146-154)
+- Create: `server/internal/handler/workspace_reserved_slugs.go`
+- Test: `server/internal/handler/workspace_test.go` (append test)
+
+**Step 1: Write failing test**
+
+Append to `server/internal/handler/workspace_test.go`:
+
+```go
+func TestCreateWorkspace_RejectsReservedSlug(t *testing.T) {
+ ctx, testHandler := setupTest(t)
+ user := createTestUser(ctx, t, testHandler.Queries, "[email protected]")
+
+ for _, reserved := range []string{"login", "onboarding", "invite", "api", "settings", "admin", "auth", "signup", "logout", "_next", "favicon.ico", "robots.txt", "sitemap.xml"} {
+ body := fmt.Sprintf(`{"name":"Test","slug":"%s"}`, reserved)
+ req := httptest.NewRequest("POST", "/api/workspaces", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req = req.WithContext(context.WithValue(req.Context(), userContextKey, user))
+ w := httptest.NewRecorder()
+
+ testHandler.CreateWorkspace(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("slug %q: expected 400, got %d", reserved, w.Code)
+ }
+ }
+}
+```
+
+**Step 2: Run test to verify it fails**
+
+```bash
+cd server && go test ./internal/handler/ -run TestCreateWorkspace_RejectsReservedSlug -v
+```
+
+Expected: FAIL (slugs currently pass)
+
+**Step 3: Create reserved slugs module**
+
+Create `server/internal/handler/workspace_reserved_slugs.go`:
+
+```go
+package handler
+
+// reservedSlugs are workspace slugs that would collide with frontend top-level
+// routes. The frontend URL shape is /{workspaceSlug}/... so any slug that
+// matches a top-level route (e.g. /login, /api) would be unreachable.
+//
+// Keep this list in sync with packages/core/paths/reserved-slugs.ts.
+var reservedSlugs = map[string]bool{
+ // Auth + onboarding routes
+ "login": true,
+ "logout": true,
+ "signup": true,
+ "onboarding": true,
+ "invite": true,
+ "auth": true,
+
+ // Reserved for future platform routes
+ "api": true,
+ "admin": true,
+ "settings": true,
+ "help": true,
+ "about": true,
+ "pricing": true,
+ "changelog": true,
+
+ // Next.js / hosting internals
+ "_next": true,
+ "favicon.ico": true,
+ "robots.txt": true,
+ "sitemap.xml": true,
+ "manifest.json": true,
+ ".well-known": true,
+}
+
+func isReservedSlug(slug string) bool {
+ return reservedSlugs[slug]
+}
+```
+
+**Step 4: Wire validation into handler**
+
+In `server/internal/handler/workspace.go`, modify `CreateWorkspace` (around line 151-154, right after the regex check):
+
+```go
+if !workspaceSlugPattern.MatchString(req.Slug) {
+ http.Error(w, "slug must be lowercase alphanumeric with hyphens", http.StatusBadRequest)
+ return
+}
+if isReservedSlug(req.Slug) {
+ http.Error(w, "slug is reserved", http.StatusBadRequest)
+ return
+}
+```
+
+**Step 5: Run test to verify it passes**
+
+```bash
+cd server && go test ./internal/handler/ -run TestCreateWorkspace_RejectsReservedSlug -v
+```
+
+Expected: PASS
+
+**Step 6: Commit**
+
+```bash
+git add server/internal/handler/workspace.go server/internal/handler/workspace_reserved_slugs.go server/internal/handler/workspace_test.go
+git commit -m "feat(workspace): reject reserved slugs on creation"
+```
+
+---
+
+### Task 2: Frontend reserved slugs + path builder module
+
+**Files:**
+- Create: `packages/core/paths/reserved-slugs.ts`
+- Create: `packages/core/paths/paths.ts`
+- Create: `packages/core/paths/index.ts`
+- Test: `packages/core/paths/paths.test.ts`
+
+**Step 1: Write failing test**
+
+Create `packages/core/paths/paths.test.ts`:
+
+```ts
+import { describe, it, expect } from "vitest";
+import { paths, isGlobalPath } from "./paths";
+
+describe("paths.workspace(slug)", () => {
+ const ws = paths.workspace("acme");
+
+ it("builds dashboard paths with slug prefix", () => {
+ expect(ws.issues()).toBe("/acme/issues");
+ expect(ws.issueDetail("abc-123")).toBe("/acme/issues/abc-123");
+ expect(ws.projects()).toBe("/acme/projects");
+ expect(ws.projectDetail("p1")).toBe("/acme/projects/p1");
+ expect(ws.autopilots()).toBe("/acme/autopilots");
+ expect(ws.autopilotDetail("a1")).toBe("/acme/autopilots/a1");
+ expect(ws.agents()).toBe("/acme/agents");
+ expect(ws.inbox()).toBe("/acme/inbox");
+ expect(ws.myIssues()).toBe("/acme/my-issues");
+ expect(ws.runtimes()).toBe("/acme/runtimes");
+ expect(ws.skills()).toBe("/acme/skills");
+ expect(ws.settings()).toBe("/acme/settings");
+ });
+
+ it("URL-encodes special characters in ids", () => {
+ expect(ws.issueDetail("id with space")).toBe("/acme/issues/id%20with%20space");
+ });
+});
+
+describe("paths (global)", () => {
+ it("builds global paths without slug", () => {
+ expect(paths.login()).toBe("/login");
+ expect(paths.onboarding()).toBe("/onboarding");
+ expect(paths.invite("inv-1")).toBe("/invite/inv-1");
+ expect(paths.authCallback()).toBe("/auth/callback");
+ });
+});
+
+describe("isGlobalPath", () => {
+ it("returns true for pre-workspace routes", () => {
+ expect(isGlobalPath("/login")).toBe(true);
+ expect(isGlobalPath("/onboarding")).toBe(true);
+ expect(isGlobalPath("/invite/abc")).toBe(true);
+ expect(isGlobalPath("/auth/callback")).toBe(true);
+ });
+
+ it("returns false for workspace-scoped paths", () => {
+ expect(isGlobalPath("/acme/issues")).toBe(false);
+ expect(isGlobalPath("/")).toBe(false);
+ });
+});
+```
+
+**Step 2: Run test to verify it fails**
+
+```bash
+pnpm --filter @multica/core exec vitest run paths/paths.test.ts
+```
+
+Expected: FAIL (module not found)
+
+**Step 3: Implement reserved-slugs**
+
+Create `packages/core/paths/reserved-slugs.ts`:
+
+```ts
+/**
+ * Slugs reserved because they collide with frontend top-level routes.
+ * Keep in sync with server/internal/handler/workspace_reserved_slugs.go.
+ */
+export const RESERVED_SLUGS = new Set([
+ // Auth + onboarding
+ "login",
+ "logout",
+ "signup",
+ "onboarding",
+ "invite",
+ "auth",
+
+ // Reserved for future platform routes
+ "api",
+ "admin",
+ "settings",
+ "help",
+ "about",
+ "pricing",
+ "changelog",
+
+ // Next.js / hosting internals
+ "_next",
+ "favicon.ico",
+ "robots.txt",
+ "sitemap.xml",
+ "manifest.json",
+ ".well-known",
+]);
+
+export function isReservedSlug(slug: string): boolean {
+ return RESERVED_SLUGS.has(slug);
+}
+```
+
+**Step 4: Implement paths builder**
+
+Create `packages/core/paths/paths.ts`:
+
+```ts
+/**
+ * Centralized URL path builder. All navigation in shared packages (packages/views)
+ * MUST go through this module — no hardcoded string paths.
+ *
+ * Two kinds of paths:
+ * - workspace-scoped: paths.workspace(slug).xxx() — carry workspace in URL
+ * - global: paths.login(), paths.onboarding(), paths.invite(id) — pre-workspace routes
+ */
+
+const encode = (id: string) => encodeURIComponent(id);
+
+function workspaceScoped(slug: string) {
+ const ws = `/${encode(slug)}`;
+ return {
+ root: () => `${ws}/issues`,
+ issues: () => `${ws}/issues`,
+ issueDetail: (id: string) => `${ws}/issues/${encode(id)}`,
+ projects: () => `${ws}/projects`,
+ projectDetail: (id: string) => `${ws}/projects/${encode(id)}`,
+ autopilots: () => `${ws}/autopilots`,
+ autopilotDetail: (id: string) => `${ws}/autopilots/${encode(id)}`,
+ agents: () => `${ws}/agents`,
+ inbox: () => `${ws}/inbox`,
+ myIssues: () => `${ws}/my-issues`,
+ runtimes: () => `${ws}/runtimes`,
+ skills: () => `${ws}/skills`,
+ settings: () => `${ws}/settings`,
+ };
+}
+
+export const paths = {
+ workspace: workspaceScoped,
+
+ // Global (pre-workspace) routes
+ login: () => "/login",
+ onboarding: () => "/onboarding",
+ invite: (id: string) => `/invite/${encode(id)}`,
+ authCallback: () => "/auth/callback",
+ root: () => "/",
+};
+
+export type WorkspacePaths = ReturnType<typeof workspaceScoped>;
+
+const GLOBAL_PREFIXES = ["/login", "/onboarding", "/invite/", "/auth/", "/logout", "/signup"];
+
+export function isGlobalPath(path: string): boolean {
+ return GLOBAL_PREFIXES.some((p) => path === p || path.startsWith(p));
+}
+```
+
+**Step 5: Create index barrel**
+
+Create `packages/core/paths/index.ts`:
+
+```ts
+export { paths, isGlobalPath } from "./paths";
+export type { WorkspacePaths } from "./paths";
+export { RESERVED_SLUGS, isReservedSlug } from "./reserved-slugs";
+```
+
+**Step 6: Export from core root**
+
+Modify `packages/core/package.json` exports (if there's an explicit exports map; otherwise this is consumed via `@multica/core/paths`).
+
+Also add to any root barrel if present. Check `packages/core/index.ts`:
+
+```bash
+cat packages/core/index.ts | grep -n export
+```
+
+If path exports are listed there, add `export * from "./paths";`.
+
+**Step 7: Run tests**
+
+```bash
+pnpm --filter @multica/core exec vitest run paths/paths.test.ts
+```
+
+Expected: PASS
+
+**Step 8: Commit**
+
+```bash
+git add packages/core/paths/
+git commit -m "feat(paths): add workspace path builder and reserved slugs"
+```
+
+---
+
+### Task 3: Derived workspace hooks (URL-driven)
+
+**Files:**
+- Create: `packages/core/paths/hooks.ts`
+- Modify: `packages/core/paths/index.ts` (add hook exports)
+- Test: `packages/core/paths/hooks.test.tsx`
+
+These hooks replace `useWorkspaceStore((s) => s.workspace)` callsites. They read workspace slug from URL (via a platform-provided source) + workspace list from React Query, and return a derived result.
+
+**Step 1: Define `WorkspaceSlugProvider` interface**
+
+Because `packages/core/` cannot import `next/navigation` or `react-router-dom`, the slug must come from a platform-provided Context. This mirrors how `WorkspaceIdProvider` works today.
+
+**Step 2: Write failing test**
+
+Create `packages/core/paths/hooks.test.tsx`:
+
+```tsx
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { WorkspaceSlugProvider, useWorkspaceSlug, useCurrentWorkspace } from "./hooks";
+import { workspaceKeys } from "../workspace/queries";
+
+function setup(slug: string | null, wsList: any[] = []) {
+ const qc = new QueryClient();
+ qc.setQueryData(workspaceKeys.list(), wsList);
+ return function Wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={qc}>
+ <WorkspaceSlugProvider slug={slug}>{children}</WorkspaceSlugProvider>
+ </QueryClientProvider>
+ );
+ };
+}
+
+describe("useWorkspaceSlug", () => {
+ it("returns the provided slug", () => {
+ function Probe() {
+ return <div>{useWorkspaceSlug() ?? "null"}</div>;
+ }
+ render(<Probe />, { wrapper: setup("acme") });
+ expect(screen.getByText("acme")).toBeInTheDocument();
+ });
+
+ it("returns null when no slug is provided", () => {
+ function Probe() {
+ return <div>{useWorkspaceSlug() ?? "null"}</div>;
+ }
+ render(<Probe />, { wrapper: setup(null) });
+ expect(screen.getByText("null")).toBeInTheDocument();
+ });
+});
+
+describe("useCurrentWorkspace", () => {
+ const acme = { id: "id-1", slug: "acme", name: "Acme", description: null, context: null, settings: {}, repos: [], issue_prefix: "ACM", created_at: "", updated_at: "" };
+
+ it("resolves workspace from slug and list", () => {
+ function Probe() {
+ const ws = useCurrentWorkspace();
+ return <div>{ws?.name ?? "none"}</div>;
+ }
+ render(<Probe />, { wrapper: setup("acme", [acme]) });
+ expect(screen.getByText("Acme")).toBeInTheDocument();
+ });
+
+ it("returns null when slug does not match any workspace", () => {
+ function Probe() {
+ const ws = useCurrentWorkspace();
+ return <div>{ws?.name ?? "none"}</div>;
+ }
+ render(<Probe />, { wrapper: setup("bogus", [acme]) });
+ expect(screen.getByText("none")).toBeInTheDocument();
+ });
+});
+```
+
+**Step 3: Run test to verify failure**
+
+```bash
+pnpm --filter @multica/core exec vitest run paths/hooks.test.tsx
+```
+
+Expected: FAIL (module not found)
+
+**Step 4: Implement hooks**
+
+Create `packages/core/paths/hooks.ts`:
+
+```tsx
+"use client";
+
+import { createContext, useContext, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { Workspace } from "../types";
+import { workspaceListOptions } from "../workspace/queries";
+import { paths, type WorkspacePaths } from "./paths";
+
+/**
+ * Context for the current workspace slug (from URL).
+ * Platform layer (apps/web or apps/desktop) must provide this.
+ */
+const WorkspaceSlugContext = createContext<string | null>(null);
+
+export function WorkspaceSlugProvider({
+ slug,
+ children,
+}: {
+ slug: string | null;
+ children: ReactNode;
+}) {
+ return (
+ <WorkspaceSlugContext.Provider value={slug}>
+ {children}
+ </WorkspaceSlugContext.Provider>
+ );
+}
+
+/** Current workspace slug from URL, or null outside workspace-scoped routes. */
+export function useWorkspaceSlug(): string | null {
+ return useContext(WorkspaceSlugContext);
+}
+
+/** Same as useWorkspaceSlug, but throws if called outside a workspace route. */
+export function useRequiredWorkspaceSlug(): string {
+ const slug = useWorkspaceSlug();
+ if (!slug) {
+ throw new Error("useRequiredWorkspaceSlug called outside workspace-scoped route");
+ }
+ return slug;
+}
+
+/**
+ * The currently-selected workspace, derived from URL slug + React Query list.
+ * Returns null if slug is missing or doesn't match any workspace in the list.
+ */
+export function useCurrentWorkspace(): Workspace | null {
+ const slug = useWorkspaceSlug();
+ const { data: list = [] } = useQuery(workspaceListOptions());
+ if (!slug) return null;
+ return list.find((w) => w.slug === slug) ?? null;
+}
+
+/**
+ * Path builder bound to the current workspace. Throws if called outside a
+ * workspace route (use paths.workspace(slug) manually for cross-workspace links).
+ */
+export function useWorkspacePaths(): WorkspacePaths {
+ const slug = useRequiredWorkspaceSlug();
+ return paths.workspace(slug);
+}
+```
+
+**Step 5: Update index barrel**
+
+Modify `packages/core/paths/index.ts`:
+
+```ts
+export { paths, isGlobalPath } from "./paths";
+export type { WorkspacePaths } from "./paths";
+export { RESERVED_SLUGS, isReservedSlug } from "./reserved-slugs";
+export {
+ WorkspaceSlugProvider,
+ useWorkspaceSlug,
+ useRequiredWorkspaceSlug,
+ useCurrentWorkspace,
+ useWorkspacePaths,
+} from "./hooks";
+```
+
+**Step 6: Run tests**
+
+```bash
+pnpm --filter @multica/core exec vitest run paths/
+```
+
+Expected: PASS
+
+**Step 7: Commit**
+
+```bash
+git add packages/core/paths/
+git commit -m "feat(paths): add URL-driven workspace hooks"
+```
+
+---
+
+### Task 4: Collapse `useWorkspaceStore` to read-only shell
+
+Remove `hydrateWorkspace` / `switchWorkspace` / `clearWorkspace`. Keep `updateWorkspace` only (used on rename). The `workspace` field is kept temporarily but will be driven by the new layout — not written by user actions.
+
+**Note:** This is a breaking change for many callsites. Phase 3 replaces all callers. This task only updates the store's public API; the callers still compile because `workspace` property remains.
+
+**Files:**
+- Modify: `packages/core/workspace/store.ts`
+- Modify: `packages/core/workspace/mutations.ts` (remove `switchWorkspace` / `hydrateWorkspace` calls)
+- Modify: `packages/core/platform/auth-initializer.tsx` (remove `hydrateWorkspace` call and localStorage read)
+- Modify: `apps/desktop/src/renderer/src/App.tsx` (remove same)
+- Modify: `apps/web/app/auth/callback/page.tsx` (remove same)
+- Modify: `apps/web/app/(auth)/login/page.tsx` (remove same)
+
+**Step 1: Rewrite store**
+
+Replace `packages/core/workspace/store.ts`:
+
+```ts
+import { create } from "zustand";
+import type { Workspace } from "../types";
+
+interface WorkspaceState {
+ /** Current workspace. Written only by the workspace layout (URL-driven). */
+ workspace: Workspace | null;
+}
+
+interface WorkspaceActions {
+ /** Set the current workspace. Called by the URL-bound layout. */
+ setWorkspace: (ws: Workspace | null) => void;
+ /** Update the current workspace in place (e.g. after rename). */
+ updateWorkspace: (ws: Workspace) => void;
+}
+
+export type WorkspaceStore = WorkspaceState & WorkspaceActions;
+
+export function createWorkspaceStore() {
+ return create<WorkspaceStore>((set) => ({
+ workspace: null,
+ setWorkspace: (ws) => set({ workspace: ws }),
+ updateWorkspace: (ws) =>
+ set((state) => ({
+ workspace: state.workspace?.id === ws.id ? ws : state.workspace,
+ })),
+ }));
+}
+```
+
+Note: `api` and `storage` parameters are gone. The store no longer touches `api._workspaceId` or localStorage. The layout does.
+
+**Step 2: Update store instantiation**
+
+Find where `createWorkspaceStore` is called:
+
+```bash
+grep -rn "createWorkspaceStore" packages/ apps/
+```
+
+Expected callsites: one in `packages/core/platform/core-provider.tsx` (or wherever the singleton is created). Update the call to drop arguments:
+
+Replace `createWorkspaceStore(api, { storage })` with `createWorkspaceStore()`.
+
+**Step 3: Clean up mutations**
+
+Modify `packages/core/workspace/mutations.ts`:
+
+```ts
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { Workspace } from "../types";
+import { api } from "../api";
+import { workspaceKeys, workspaceListOptions } from "./queries";
+
+export function useCreateWorkspace() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (data: { name: string; slug: string; description?: string }) =>
+ api.createWorkspace(data),
+ onSuccess: (newWs) => {
+ qc.setQueryData(workspaceKeys.list(), (old: Workspace[] = []) => [...old, newWs]);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: workspaceKeys.list() });
+ },
+ });
+}
+
+export function useLeaveWorkspace() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (workspaceId: string) => api.leaveWorkspace(workspaceId),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: workspaceKeys.list() });
+ },
+ });
+}
+
+export function useDeleteWorkspace() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (workspaceId: string) => api.deleteWorkspace(workspaceId),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: workspaceKeys.list() });
+ },
+ });
+}
+```
+
+The UI callers (create-workspace modal, settings page) handle navigation in their own `onSuccess` callbacks — that pattern continues but without the mutation calling `switchWorkspace`.
+
+**Step 4: Simplify auth-initializer**
+
+Modify `packages/core/platform/auth-initializer.tsx`:
+
+- Delete: `const wsId = storage.getItem("multica_workspace_id");`
+- Delete: `useWorkspaceStore.getState().hydrateWorkspace(wsList, wsId);` (both branches)
+- Delete: `storage.removeItem("multica_workspace_id");` (in catch block)
+
+The initializer just loads user + workspace list into React Query. Workspace selection now happens in the URL layout.
+
+Full replacement:
+
+```tsx
+"use client";
+
+import { useEffect, type ReactNode } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { getApi } from "../api";
+import { useAuthStore } from "../auth";
+import { configStore } from "../config";
+import { workspaceKeys } from "../workspace/queries";
+import { createLogger } from "../logger";
+import { defaultStorage } from "./storage";
+import type { StorageAdapter } from "../types/storage";
+
+const logger = createLogger("auth");
+
+export function AuthInitializer({
+ children,
+ onLogin,
+ onLogout,
+ storage = defaultStorage,
+ cookieAuth,
+}: {
+ children: ReactNode;
+ onLogin?: () => void;
+ onLogout?: () => void;
+ storage?: StorageAdapter;
+ cookieAuth?: boolean;
+}) {
+ const qc = useQueryClient();
+
+ useEffect(() => {
+ const api = getApi();
+
+ api.getConfig().then((cfg) => {
+ if (cfg.cdn_domain) configStore.getState().setCdnDomain(cfg.cdn_domain);
+ }).catch(() => { /* config is optional */ });
+
+ if (cookieAuth) {
+ Promise.all([api.getMe(), api.listWorkspaces()])
+ .then(([user, wsList]) => {
+ onLogin?.();
+ useAuthStore.setState({ user, isLoading: false });
+ qc.setQueryData(workspaceKeys.list(), wsList);
+ })
+ .catch((err) => {
+ logger.error("cookie auth init failed", err);
+ onLogout?.();
+ useAuthStore.setState({ user: null, isLoading: false });
+ });
+ return;
+ }
+
+ const token = storage.getItem("multica_token");
+ if (!token) {
+ onLogout?.();
+ useAuthStore.setState({ isLoading: false });
+ return;
+ }
+
+ api.setToken(token);
+
+ Promise.all([api.getMe(), api.listWorkspaces()])
+ .then(([user, wsList]) => {
+ onLogin?.();
+ useAuthStore.setState({ user, isLoading: false });
+ qc.setQueryData(workspaceKeys.list(), wsList);
+ })
+ .catch((err) => {
+ logger.error("auth init failed", err);
+ api.setToken(null);
+ storage.removeItem("multica_token");
+ onLogout?.();
+ useAuthStore.setState({ user: null, isLoading: false });
+ });
+ }, []);
+
+ return <>{children}</>;
+}
+```
+
+**Step 5: Commit**
+
+```bash
+git add packages/core/workspace/store.ts packages/core/workspace/mutations.ts packages/core/platform/auth-initializer.tsx packages/core/platform/core-provider.tsx
+git commit -m "refactor(core): remove imperative workspace switching APIs"
+```
+
+*Note: this commit does not yet build, because 20+ callers still reference `switchWorkspace` etc. We fix them in Phase 3. Use `git commit --no-verify` if a pre-commit build check blocks; otherwise stage this alongside Phase 3 Task 11.*
+
+**If pre-commit hook fails:** Do NOT bypass. Continue to Task 11 first, then commit all together in one larger commit. Re-sequence tasks if needed — the intent is atomic per-logical-unit, not strict commit ordering.
+
+---
+
+### Task 5: Add `api.getWorkspaceBySlug` client method (frontend only)
+
+We don't need a new backend endpoint because the workspace list is already fetched. But the frontend needs a helper for the layout to resolve slug → workspace cleanly without duplicating `list.find` everywhere.
+
+**Files:**
+- Modify: `packages/core/workspace/queries.ts`
+
+**Step 1: Add selector helper**
+
+Append to `packages/core/workspace/queries.ts`:
+
+```ts
+import { queryOptions } from "@tanstack/react-query";
+// ... existing imports
+
+/** Query options that resolves the workspace matching the given slug from the list. */
+export function workspaceBySlugOptions(slug: string) {
+ return queryOptions({
+ ...workspaceListOptions(),
+ select: (list: Workspace[]) => list.find((w) => w.slug === slug) ?? null,
+ });
+}
+```
+
+**Step 2: Commit**
+
+```bash
+git add packages/core/workspace/queries.ts
+git commit -m "feat(workspace): add workspaceBySlugOptions selector"
+```
+
+---
+
+## Phase 2: Web Routing Restructure (Tasks 6–10)
+
+### Task 6: Move `(dashboard)` routes under `[workspaceSlug]`
+
+**Files moved** (use `git mv` to preserve history):
+
+```bash
+mkdir -p apps/web/app/\[workspaceSlug\]
+git mv apps/web/app/\(dashboard\) apps/web/app/\[workspaceSlug\]/\(dashboard\)
+```
+
+After the move, structure is:
+
+```
+apps/web/app/
+├── (auth)/ # unchanged
+├── (landing)/ # unchanged
+├── auth/callback/ # unchanged
+├── [workspaceSlug]/
+│ ├── layout.tsx # NEW — created in next task
+│ └── (dashboard)/
+│ ├── layout.tsx # moved from old (dashboard)/layout.tsx
+│ ├── issues/
+│ ├── projects/
+│ ├── autopilots/
+│ ├── agents/
+│ ├── inbox/
+│ ├── my-issues/
+│ ├── runtimes/
+│ ├── skills/
+│ └── settings/
+├── layout.tsx # unchanged
+└── page.tsx # modified later for redirect
+```
+
+**Commit:**
+
+```bash
+git add -A
+git commit -m "refactor(web): move dashboard routes under [workspaceSlug] segment"
+```
+
+---
+
+### Task 7: Create `[workspaceSlug]/layout.tsx` with slug-driven side effects
+
+**Files:**
+- Create: `apps/web/app/[workspaceSlug]/layout.tsx`
+
+**Step 1: Implementation**
+
+```tsx
+"use client";
+
+import { use, useEffect } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { notFound } from "next/navigation";
+import { api } from "@multica/core/api";
+import {
+ WorkspaceSlugProvider,
+ workspaceBySlugOptions,
+} from "@multica/core/paths";
+import { useWorkspaceStore } from "@multica/core/workspace";
+import { setCurrentWorkspaceId, rehydrateAllWorkspaceStores } from "@multica/core/platform/workspace-storage";
+import { useAuthStore } from "@multica/core/auth";
+
+export default function WorkspaceLayout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<{ workspaceSlug: string }>;
+}) {
+ const { workspaceSlug } = use(params);
+ const user = useAuthStore((s) => s.user);
+ const isLoading = useAuthStore((s) => s.isLoading);
+
+ // Don't resolve workspace until auth is settled — list query is enabled only
+ // when user is present (see queries.ts).
+ const { data: workspace, isFetched } = useQuery({
+ ...workspaceBySlugOptions(workspaceSlug),
+ enabled: !!user,
+ });
+
+ // Sync URL-derived workspace into API client + persist namespace + Zustand mirror.
+ useEffect(() => {
+ if (!workspace) return;
+ api.setWorkspaceId(workspace.id);
+ setCurrentWorkspaceId(workspace.id);
+ rehydrateAllWorkspaceStores();
+ useWorkspaceStore.getState().setWorkspace(workspace);
+
+ // Write non-HttpOnly cookie for middleware to read on root-path redirect.
+ if (typeof document !== "undefined") {
+ document.cookie = `last_workspace_slug=${encodeURIComponent(workspaceSlug)}; path=/; max-age=${60 * 60 * 24 * 365}; SameSite=Lax`;
+ }
+ }, [workspace, workspaceSlug]);
+
+ if (isLoading) return null; // DashboardGuard below shows its own loader
+ if (isFetched && !workspace) notFound();
+
+ return (
+ <WorkspaceSlugProvider slug={workspaceSlug}>
+ {children}
+ </WorkspaceSlugProvider>
+ );
+}
+```
+
+**Step 2: Verify route compiles**
+
+```bash
+pnpm --filter @multica/web build 2>&1 | head -40
+```
+
+Expected: may fail because of Phase 3 missing pieces, but the route file itself should be valid. Check for syntax errors.
+
+**Step 3: Commit**
+
+```bash
+git add apps/web/app/\[workspaceSlug\]/layout.tsx
+git commit -m "feat(web): add [workspaceSlug] layout for URL-driven workspace"
+```
+
+---
+
+### Task 8: Update root `app/page.tsx` — redirect logged-in users
+
+**Files:**
+- Modify: `apps/web/app/page.tsx` (or `apps/web/app/(landing)/page.tsx` — check which is the real root)
+- Verify: the landing page still renders for logged-out users
+
+**Check current root:**
+
+```bash
+ls apps/web/app/page.tsx 2>/dev/null || ls apps/web/app/\(landing\)/page.tsx
+```
+
+**Implementation:**
+
+If root is the landing page group, `middleware.ts` (next task) handles the redirect before this page renders. No change needed here.
+
+If there's a separate `apps/web/app/page.tsx` that redirects, update it to use middleware too. Confirm which case applies:
+
+```bash
+cat apps/web/app/page.tsx 2>/dev/null
+```
+
+**Commit:** Only if changes are made. Otherwise skip.
+
+---
+
+### Task 9: Add Next.js middleware for root redirect
+
+**Files:**
+- Create: `apps/web/middleware.ts`
+
+**Step 1: Implementation**
+
+```ts
+import { NextResponse, type NextRequest } from "next/server";
+
+// Paths that should not be touched by middleware (assets, API, auth callbacks).
+const PUBLIC_PREFIXES = [
+ "/_next",
+ "/api",
+ "/auth/",
+ "/login",
+ "/signup",
+ "/onboarding",
+ "/invite/",
+ "/favicon",
+ "/robots.txt",
+ "/sitemap.xml",
+ "/manifest.json",
+];
+
+function isPublic(pathname: string): boolean {
+ return PUBLIC_PREFIXES.some((p) => pathname === p || pathname.startsWith(p));
+}
+
+export function middleware(req: NextRequest) {
+ const { pathname } = req.nextUrl;
+
+ // Only handle the root "/"
+ if (pathname !== "/") return NextResponse.next();
+ if (isPublic(pathname)) return NextResponse.next();
+
+ // Check auth cookie (HttpOnly, set by /login). We can't read its value,
+ // but we can check presence — if there's no session cookie, show landing.
+ const hasSession = req.cookies.has("multica_session");
+ if (!hasSession) return NextResponse.next();
+
+ // Logged-in user at /: redirect to last workspace's issues page.
+ const lastSlug = req.cookies.get("last_workspace_slug")?.value;
+ if (lastSlug) {
+ const url = req.nextUrl.clone();
+ url.pathname = `/${lastSlug}/issues`;
+ return NextResponse.redirect(url);
+ }
+
+ // No last-workspace cookie yet (first login) — let the landing page render.
+ // Client code will redirect to /{firstWorkspace.slug}/issues after auth loads.
+ return NextResponse.next();
+}
+
+export const config = {
+ matcher: ["/"],
+};
+```
+
+**Step 2: Confirm auth cookie name**
+
+```bash
+grep -rn "multica_session\|setLoggedInCookie\|cookie" apps/web/features/auth/
+```
+
+Find the actual cookie name. Update `middleware.ts` if it's different (likely `multica_logged_in` or similar — the cookie only needs to indicate presence, not carry auth).
+
+**Step 3: Commit**
+
+```bash
+git add apps/web/middleware.ts
+git commit -m "feat(web): middleware redirect to last workspace on root"
+```
+
+---
+
+### Task 10: Client-side redirect for logged-in users without `last_workspace_slug`
+
+For users who log in for the first time (no cookie yet), the root page's landing component should redirect when workspace list loads.
+
+**Files:**
+- Modify: `apps/web/app/(landing)/page.tsx` or wherever the landing component lives
+- Or create: a small `<RedirectIfAuthenticated>` component and wrap landing
+
+**Implementation option:** add a client effect in the landing page:
+
+```tsx
+"use client";
+
+import { useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { useAuthStore } from "@multica/core/auth";
+import { useQuery } from "@tanstack/react-query";
+import { workspaceListOptions } from "@multica/core/workspace";
+import { paths } from "@multica/core/paths";
+
+function useRedirectLoggedIn() {
+ const router = useRouter();
+ const user = useAuthStore((s) => s.user);
+ const isLoading = useAuthStore((s) => s.isLoading);
+ const { data: list } = useQuery({ ...workspaceListOptions(), enabled: !!user });
+
+ useEffect(() => {
+ if (isLoading || !user || !list) return;
+ if (list.length === 0) {
+ router.replace(paths.onboarding());
+ } else {
+ router.replace(paths.workspace(list[0].slug).issues());
+ }
+ }, [isLoading, user, list, router]);
+}
+```
+
+Invoke `useRedirectLoggedIn()` at the top of the landing page component.
+
+**Commit:**
+
+```bash
+git add apps/web/app/\(landing\)/page.tsx
+git commit -m "feat(web): client redirect from landing to first workspace when authenticated"
+```
+
+---
+
+## Phase 3: Replace All Path Callsites (Tasks 11–18)
+
+Mechanical replacements. Each task handles one cluster.
+
+### Task 11: Update `app-sidebar.tsx` — workspace switcher and menu items
+
+**File:** `packages/views/layout/app-sidebar.tsx`
+
+**Changes:**
+
+1. Replace `useWorkspaceStore((s) => s.workspace)` with `useCurrentWorkspace()`
+2. Replace `useWorkspaceStore((s) => s.switchWorkspace)` import — DELETE the line (no longer exists)
+3. Replace workspace switcher click handler:
+
+**Before (around line 284-287):**
+
+```tsx
+if (ws.id !== workspace?.id) {
+ push("/issues");
+ switchWorkspace(ws);
+}
+```
+
+**After:**
+
+```tsx
+if (ws.id !== workspace?.id) {
+ push(paths.workspace(ws.slug).issues());
+}
+```
+
+4. Replace hardcoded menu paths. Search for all `"/issues"`, `"/projects"`, etc. in the file. Menu items (around lines 73-87):
+
+**Before:**
+
+```tsx
+{ title: "Inbox", url: "/inbox", icon: Inbox },
+{ title: "My Issues", url: "/my-issues", icon: User },
+{ title: "Issues", url: "/issues", icon: ListTodo },
+// ...
+```
+
+**After:**
+
+```tsx
+const p = useWorkspacePaths();
+const menuItems = [
+ { title: "Inbox", url: p.inbox(), icon: Inbox },
+ { title: "My Issues", url: p.myIssues(), icon: User },
+ { title: "Issues", url: p.issues(), icon: ListTodo },
+ // ...
+];
+```
+
+5. Replace pin navigation (around line 105):
+
+**Before:**
+
+```tsx
+push(`/${pinType}s/${pin.item_id}`);
+```
+
+**After:**
+
+```tsx
+push(pinType === "issue" ? p.issueDetail(pin.item_id) : p.projectDetail(pin.item_id));
+```
+
+6. Replace logout's `clearWorkspace` call (line 223):
+
+**Before:**
+
+```tsx
+const logout = () => {
+ queryClient.clear();
+ authLogout();
+ useWorkspaceStore.getState().clearWorkspace();
+};
+```
+
+**After:**
+
+```tsx
+const logout = () => {
+ queryClient.clear();
+ authLogout();
+ useWorkspaceStore.getState().setWorkspace(null);
+};
+```
+
+7. The `push("/issues")` inside the switch handler at line 289 becomes `push(paths.workspace(ws.slug).issues())` (already covered in change #3).
+
+**Commit:**
+
+```bash
+git add packages/views/layout/app-sidebar.tsx
+git commit -m "refactor(sidebar): workspace switcher uses URL navigation"
+```
+
+---
+
+### Task 12: Update `use-dashboard-guard.ts`
+
+**File:** `packages/views/layout/use-dashboard-guard.ts`
+
+**Changes:**
+
+1. Replace `useWorkspaceStore((s) => s.workspace)` with `useCurrentWorkspace()`
+2. Replace `/login`, `/onboarding` string paths with `paths.login()`, `paths.onboarding()`
+
+**Commit:**
+
+```bash
+git add packages/views/layout/use-dashboard-guard.ts
+git commit -m "refactor(dashboard-guard): use URL-derived workspace"
+```
+
+---
+
+### Task 13: Update issues components
+
+**Files:**
+- `packages/views/issues/components/issue-detail.tsx` (lines 327, 469, 532, 552, 589, 608)
+- `packages/views/issues/components/issues-page.tsx` (lines 29, 41)
+- `packages/views/my-issues/components/my-issues-page.tsx` (line 30)
+
+**Changes per file:**
+
+`issue-detail.tsx`:
+- Line 327: `useWorkspaceStore((s) => s.workspace)` → `useCurrentWorkspace()`
+- Lines 469, 532, 552: `"/issues"` → `paths.issues()` (use `useWorkspacePaths`)
+- Lines 589, 608: `` `/issues/${id}` `` → `paths.issueDetail(id)`
+
+`issues-page.tsx`:
+- Line 29: `useWorkspaceStore((s) => s.workspace)` → `useCurrentWorkspace()`
+- Line 41: `useWorkspaceStore.subscribe` — THIS IS A PROBLEM. `filter-workspace-sync` subscribes to store changes. Refactor: replace with a URL-based effect that invalidates filters when `wsId` changes.
+
+For line 41, read the full context:
+
+```bash
+grep -n -A 10 "initFilterWorkspaceSync" packages/views/issues/components/issues-page.tsx
+grep -rn "initFilterWorkspaceSync" packages/
+```
+
+If this is used only to clear filter state on workspace change, convert to a `useEffect(() => { clearFilters(); }, [wsId])` pattern where wsId comes from `useWorkspaceId()`.
+
+`my-issues-page.tsx`:
+- Line 30: same replacement
+
+**Commit:**
+
+```bash
+git add packages/views/issues/ packages/views/my-issues/
+git commit -m "refactor(views/issues): use path builder and URL-derived workspace"
+```
+
+---
+
+### Task 14: Update projects, autopilots, agents components
+
+**Files:**
+- `packages/views/projects/components/projects-page.tsx` (line 252, 303)
+- `packages/views/projects/components/project-detail.tsx` (lines 185, 237, 266)
+- `packages/views/autopilots/components/autopilot-detail-page.tsx` (lines 405, 421)
+- `packages/views/agents/components/*` (check for path references)
+
+**Changes per file** (same pattern):
+- `useWorkspaceStore((s) => s.workspace)` → `useCurrentWorkspace()`
+- Hardcoded paths → `paths.xxx()` via `useWorkspacePaths()`
+
+**Commit:**
+
+```bash
+git add packages/views/projects/ packages/views/autopilots/ packages/views/agents/
+git commit -m "refactor(views): projects/autopilots/agents use path builder"
+```
+
+---
+
+### Task 15: Update search, modals, editor extensions
+
+**Files:**
+- `packages/views/search/search-command.tsx` (lines 84-91, 232-234)
+- `packages/views/modals/create-issue.tsx` (line 134)
+- `packages/views/modals/create-workspace.tsx` (line 70)
+- `packages/views/editor/extensions/mention-suggestion.tsx` (line 222)
+
+**Changes:**
+
+`search-command.tsx`:
+- Lines 84-91 menu routes → `paths.xxx()`
+- Lines 232-234 result navigation → `paths.projectDetail(...)` / `paths.issueDetail(...)`
+
+`create-issue.tsx`:
+- Line 134: `` `/issues/${issue.id}` `` → `paths.issueDetail(issue.id)` via `useWorkspacePaths()`
+
+`create-workspace.tsx`:
+- Line 70: `"/onboarding"` — this is a global path. Stays as `paths.onboarding()`.
+- If the modal creates a workspace and then navigates INTO it: the `onSuccess` should push to `paths.workspace(newWs.slug).issues()` instead of `/onboarding`. Verify product intent.
+
+`mention-suggestion.tsx`:
+- Line 222: `useWorkspaceStore.getState().workspace?.id` — this runs outside React render (inside a TipTap extension factory). Need a different approach.
+
+Option: the factory receives `wsId` as a parameter. Change `createMentionSuggestion(qc)` signature to `createMentionSuggestion(qc, getWorkspaceId)` where `getWorkspaceId` is a callback that reads current workspace id. Update callers to pass `() => api._workspaceId` or use a subscribable source.
+
+Simpler option for this PR: keep using `useWorkspaceStore.getState().workspace?.id` for now — the store's `workspace` field is still written by the layout's `setWorkspace` call, so it works. Revisit if we want to fully remove the store later.
+
+**Decision for this PR:** keep the `useWorkspaceStore.getState().workspace?.id` read since it works. Only change component-level reads (those use `useCurrentWorkspace()`).
+
+**Commit:**
+
+```bash
+git add packages/views/search/ packages/views/modals/ packages/views/editor/
+git commit -m "refactor(views): search/modals/editor use path builder"
+```
+
+---
+
+### Task 16: Update invite / onboarding pages
+
+**Files:**
+- `packages/views/invite/invite-page.tsx` (lines 20, 42, 46, 88, 120)
+- `packages/views/onboarding/onboarding-wizard.tsx` (lines 24, 28)
+- `apps/web/app/(auth)/login/page.tsx` (line 32)
+- `apps/web/app/(auth)/invite/[id]/page.tsx`
+- `apps/web/app/auth/callback/page.tsx` (line 67, 71)
+
+**Changes:**
+
+`invite-page.tsx`:
+- Line 20: `switchWorkspace` import — DELETE (no longer exists)
+- Line 42: `switchWorkspace(ws)` → DELETE. Then line 46 pushes to `paths.workspace(ws.slug).issues()` (use the newly-joined workspace's slug).
+- Lines 88, 120: `push("/issues")` — target depends on context. If user already has a workspace, push to current-workspace issues. If not, push to `/onboarding`. Read the component logic carefully.
+
+`onboarding-wizard.tsx`:
+- Line 24, 28: same `useCurrentWorkspace()` replacement
+
+`auth/callback/page.tsx`:
+- Line 67: `localStorage.getItem("multica_workspace_id")` → DELETE
+- Line 71: after auth success, navigate to `paths.workspace(wsList[0].slug).issues()` (or `paths.onboarding()` if list is empty) — pick first workspace as default landing. The middleware cookie will update on next visit.
+
+`(auth)/login/page.tsx`:
+- Line 32: `localStorage.getItem("multica_workspace_id")` → DELETE
+- Login success redirect: same logic as auth callback.
+
+**Commit:**
+
+```bash
+git add packages/views/invite/ packages/views/onboarding/ apps/web/app/
+git commit -m "refactor(auth-flow): remove localStorage workspace id, use URL navigation"
+```
+
+---
+
+### Task 17: Update link-handler for internal markdown links
+
+**File:** `packages/views/editor/utils/link-handler.ts`
+
+When a markdown link like `[foo](/issues/abc)` is clicked inside an issue's content, it dispatches `multica:navigate` with path `/issues/abc`. After the refactor, this is not a valid route — it needs workspace slug.
+
+**Change:**
+
+`openLink` should detect workspace-scoped paths without slug and dispatch an event that the layout layer can prepend the current slug to. Or, add a slug-prepend helper that callers use.
+
+Simplest: change `openLink` to accept a current slug and prepend:
+
+```ts
+import { paths, isGlobalPath } from "@multica/core/paths";
+
+/** Open a link — internal paths dispatch multica:navigate, external open new tab. */
+export function openLink(href: string, currentSlug?: string | null): void {
+ if (href.startsWith("/")) {
+ // Workspace-scoped path without slug → prepend current slug
+ let path = href;
+ if (!isGlobalPath(path) && currentSlug && !path.startsWith(`/${currentSlug}/`)) {
+ // Detect paths like /issues/abc (missing slug) vs /acme/issues/abc (already has slug)
+ // Heuristic: path's first segment matches a known top-level dashboard route
+ const firstSegment = path.split("/")[1];
+ if (["issues", "projects", "autopilots", "agents", "inbox", "my-issues", "runtimes", "skills", "settings"].includes(firstSegment)) {
+ path = `/${currentSlug}${path}`;
+ }
+ }
+ window.dispatchEvent(
+ new CustomEvent("multica:navigate", { detail: { path } }),
+ );
+ } else {
+ window.open(href, "_blank", "noopener,noreferrer");
+ }
+}
+
+export function isMentionHref(href: string | null | undefined): href is string {
+ return !!href && href.startsWith("mention://");
+}
+```
+
+Update callers of `openLink` (content-editor, readonly-content, link-hover-card) to pass the current slug from `useWorkspaceSlug()`.
+
+**Commit:**
+
+```bash
+git add packages/views/editor/utils/link-handler.ts packages/views/editor/
+git commit -m "refactor(editor): link-handler prepends current workspace slug"
+```
+
+---
+
+### Task 18: Update `NavigationStore.lastPath`
+
+**File:** `packages/core/navigation/store.ts`
+
+After the refactor, `lastPath` storing `/acme/issues/123` is still useful for "remember last page on refresh within same workspace", but it needs to either:
+- Store workspace-relative path (`/issues/123`) and prepend slug on restore, OR
+- Store absolute path and rely on workspace-aware persist namespace (already true for drafts).
+
+**Decision:** storing absolute path `/acme/issues/123` in a workspace-namespaced store is simplest. It already works across workspace switches because the persist key is suffixed by wsId. The audit's Task 3 (`useNavigationStore` not workspace-aware) is now easy to fix.
+
+**Changes:**
+
+```ts
+"use client";
+
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../platform/workspace-storage";
+import { defaultStorage } from "../platform/storage";
+
+const EXCLUDED_PREFIXES = ["/login", "/pair/", "/invite/", "/onboarding", "/auth/"];
+
+interface NavigationState {
+ lastPath: string | null;
+ onPathChange: (path: string) => void;
+}
+
+export const useNavigationStore = create<NavigationState>()(
+ persist(
+ (set) => ({
+ lastPath: null,
+ onPathChange: (path: string) => {
+ if (!EXCLUDED_PREFIXES.some((prefix) => path.startsWith(prefix))) {
+ set({ lastPath: path });
+ }
+ },
+ }),
+ {
+ name: "multica_navigation",
+ storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
+ partialize: (state) => ({ lastPath: state.lastPath }),
+ }
+ )
+);
+
+registerForWorkspaceRehydration(() => useNavigationStore.persist.rehydrate());
+```
+
+Also update `packages/core/platform/storage-cleanup.ts`:
+
+```ts
+// Add "multica_navigation" to WORKSPACE_SCOPED_KEYS array
+```
+
+**Commit:**
+
+```bash
+git add packages/core/navigation/store.ts packages/core/platform/storage-cleanup.ts
+git commit -m "fix(navigation-store): isolate lastPath per workspace"
+```
+
+---
+
+## Phase 4: Desktop (Tasks 19–22)
+
+### Task 19: Add `:workspaceSlug` to desktop routes
+
+**File:** `apps/desktop/src/renderer/src/routes.tsx`
+
+**Changes:**
+
+Update route definitions (lines 71-143) to wrap dashboard paths under `:workspaceSlug`:
+
+```tsx
+const router = createMemoryRouter([
+ { path: "/login", element: <LoginPage /> },
+ { path: "/onboarding", element: <OnboardingPage /> },
+ { path: "/invite/:id", element: <InvitePage /> },
+ {
+ path: "/:workspaceSlug",
+ element: <WorkspaceRouteLayout />, // NEW — mirrors web's [workspaceSlug]/layout.tsx
+ children: [
+ { path: "issues", element: <IssuesPage /> },
+ { path: "issues/:id", element: <IssueDetailPage /> },
+ { path: "projects", element: <ProjectsPage /> },
+ { path: "projects/:id", element: <ProjectDetailPage /> },
+ { path: "autopilots", element: <AutopilotsPage /> },
+ { path: "autopilots/:id", element: <AutopilotDetailPage /> },
+ { path: "agents", element: <AgentsPage /> },
+ { path: "inbox", element: <InboxPage /> },
+ { path: "my-issues", element: <MyIssuesPage /> },
+ { path: "runtimes", element: <RuntimesPage /> },
+ { path: "skills", element: <SkillsPage /> },
+ { path: "settings", element: <SettingsPage /> },
+ ],
+ },
+]);
+```
+
+Create `WorkspaceRouteLayout` component that mirrors the web `[workspaceSlug]/layout.tsx` — reads `useParams()`, resolves workspace, provides `WorkspaceSlugProvider`.
+
+**Commit:**
+
+```bash
+git add apps/desktop/src/renderer/src/routes.tsx
+git commit -m "refactor(desktop): add :workspaceSlug to all dashboard routes"
+```
+
+---
+
+### Task 20: Desktop tab store — workspace-aware paths
+
+**File:** `apps/desktop/src/renderer/src/stores/tab-store.ts`
+
+The tab system's paths now include slug naturally (because routes require slug). Main changes:
+
+1. `ROUTE_ICONS` map keys should match first post-slug segment, not first segment.
+
+Change the `resolveRouteIcon` function (lines 47-64) to split the path, skip the slug segment, and match the next segment:
+
+```ts
+function resolveRouteIcon(path: string): LucideIcon {
+ // Path shape: /{slug}/issues/... → strip slug, take next segment
+ const segments = path.split("/").filter(Boolean);
+ const routeSegment = segments[1] ?? "";
+ return ROUTE_ICONS[routeSegment] ?? Square;
+}
+```
+
+2. Default tab on app startup: when the user logs in, open `/{defaultSlug}/issues` instead of `/issues`.
+
+Find where the initial tab is created (in `App.tsx` or `DesktopShell`), update to read the first workspace's slug.
+
+**Commit:**
+
+```bash
+git add apps/desktop/src/renderer/src/stores/tab-store.ts apps/desktop/src/renderer/src/
+git commit -m "refactor(desktop/tabs): workspace-aware tab paths"
+```
+
+---
+
+### Task 21: Desktop navigation adapter — `getShareableUrl` includes slug
+
+**File:** `apps/desktop/src/renderer/src/platform/navigation.tsx`
+
+Current (line 67, 110): `getShareableUrl: (path: string) => \`https://www.multica.ai${path}\``
+
+After the refactor, `path` already contains slug (because the tab's memory router uses slug), so the existing implementation is correct. **No change needed.**
+
+However, double-check by testing: open an issue, click "copy link", paste it. Verify it's `https://www.multica.ai/{slug}/issues/{id}`.
+
+If the web URL domain is configurable (e.g. different staging domains), extract the domain to an env var:
+
+```tsx
+const WEB_URL = import.meta.env.VITE_WEB_URL || "https://www.multica.ai";
+// ...
+getShareableUrl: (path: string) => `${WEB_URL}${path}`,
+```
+
+**Commit (if changed):**
+
+```bash
+git add apps/desktop/src/renderer/src/platform/navigation.tsx
+git commit -m "refactor(desktop/nav): make shareable URL domain configurable"
+```
+
+---
+
+### Task 22: Desktop App.tsx — remove localStorage workspace id
+
+**File:** `apps/desktop/src/renderer/src/App.tsx`
+
+**Changes:**
+
+Lines 29-31 currently do:
+
+```tsx
+const wsList = await api.listWorkspaces();
+const lastWsId = localStorage.getItem("multica_workspace_id");
+useWorkspaceStore.getState().hydrateWorkspace(wsList, lastWsId);
+```
+
+Replace with: no explicit workspace selection. The URL (memory router) carries the workspace, and the initial route selects the first workspace's slug.
+
+```tsx
+const wsList = await api.listWorkspaces();
+if (wsList.length > 0) {
+ // Navigate to first workspace's dashboard
+ router.navigate(paths.workspace(wsList[0].slug).issues());
+} else {
+ router.navigate(paths.onboarding());
+}
+```
+
+Make sure `router` is accessible here — or dispatch the navigation event from a provider.
+
+**Commit:**
+
+```bash
+git add apps/desktop/src/renderer/src/App.tsx
+git commit -m "refactor(desktop): URL-driven workspace, remove localStorage read"
+```
+
+---
+
+## Phase 5: Verification & Cleanup (Tasks 23–27)
+
+### Task 23: Remove all `multica_workspace_id` references
+
+Run:
+
+```bash
+grep -rn "multica_workspace_id" packages/ apps/ | grep -v ".test." | grep -v "docs/plans/"
+```
+
+Each result should be gone or replaced. Verify:
+- `packages/core/workspace/store.ts` — gone (step 4)
+- `packages/core/platform/auth-initializer.tsx` — gone (step 4)
+- `packages/core/platform/core-provider.tsx` — check any remaining reads
+- `apps/desktop/src/renderer/src/App.tsx` — gone (step 22)
+- `apps/desktop/src/renderer/src/pages/login.tsx` — check
+- `apps/web/app/auth/callback/page.tsx` — gone (step 16)
+- `apps/web/app/(auth)/login/page.tsx` — gone (step 16)
+- `e2e/auth.spec.ts` — test cleanup, should use the new cookie
+
+Commit cleanups:
+
+```bash
+git add -A
+git commit -m "chore: remove all multica_workspace_id references"
+```
+
+---
+
+### Task 24: TypeScript check
+
+```bash
+pnpm typecheck
+```
+
+Expected: PASS. Fix any type errors surfaced by the refactor.
+
+Common issues to expect:
+- `useWorkspaceStore((s) => s.switchWorkspace)` — the store no longer has this method. Replace with URL navigation.
+- `useWorkspaceStore.getState().hydrateWorkspace(...)` — same.
+- Any function signature that took `workspaceId` from the store but should now take it via `useWorkspaceId()`.
+
+---
+
+### Task 25: Unit tests
+
+```bash
+pnpm test
+```
+
+Expected: PASS. Tests that mocked `useWorkspaceStore.workspace` need updating to mock `useCurrentWorkspace()` directly, or provide a mock workspace list via React Query setup.
+
+Check each of these test files:
+
+```bash
+grep -rln "useWorkspaceStore" packages/views/ apps/
+```
+
+Update each to the new mocking pattern.
+
+---
+
+### Task 26: E2E tests
+
+**File:** `e2e/**/*.spec.ts`
+
+Find all URL assertions:
+
+```bash
+grep -rn "/issues\|/projects\|/inbox\|/settings" e2e/
+```
+
+Update each to include the workspace slug. Use the test workspace's slug from the fixture.
+
+Example transform:
+
+```ts
+// Before
+await page.goto("/issues");
+await expect(page).toHaveURL(/\/issues\/[a-f0-9-]+/);
+
+// After
+const ws = await api.getTestWorkspace();
+await page.goto(`/${ws.slug}/issues`);
+await expect(page).toHaveURL(new RegExp(`/${ws.slug}/issues/[a-f0-9-]+`));
+```
+
+Run E2E:
+
+```bash
+make dev # background, wait for ready
+pnpm exec playwright test
+```
+
+Expected: all tests pass.
+
+---
+
+### Task 27: Full verification pipeline
+
+```bash
+make check
+```
+
+Runs: typecheck + unit tests + Go tests + E2E. Must pass end-to-end before declaring done.
+
+---
+
+## Phase 6: Manual QA Checklist (Pre-Deploy)
+
+Before pushing to test environment, verify each scenario manually in local dev:
+
+- [ ] Log in fresh → lands on `/{firstWorkspace.slug}/issues`
+- [ ] Click around (issues, projects, settings) → URL updates with slug
+- [ ] Open 2 tabs at different workspaces → each tab shows correct data on refresh (no cross-pollution)
+- [ ] Copy URL from tab A, paste in tab B → correct workspace's data loads
+- [ ] Workspace switcher in sidebar → navigates, URL updates, no flash
+- [ ] Create new workspace → slug validation rejects reserved words (`login`, `api`, etc.)
+- [ ] Create new workspace → successful creation navigates to new workspace's issues
+- [ ] Delete current workspace → navigates to another workspace (no stuck on `/settings`)
+- [ ] Leave workspace → same
+- [ ] Accept invite via email link → navigates into invited workspace's issues
+- [ ] Accept invite via sidebar "Join" dropdown → same path (no stale behavior)
+- [ ] Share link from Copy Link → opens correctly in another user's browser
+- [ ] Log out → returns to landing
+- [ ] Mobile view → workspace switching works (even without sidebar open)
+- [ ] Markdown link `[foo](/issues/abc)` in comment → navigates within current workspace
+- [ ] Desktop: open multiple tabs, each with workspace path → tabs persist across app restart
+- [ ] Desktop: copy-link generates `https://www.multica.ai/{slug}/issues/{id}`
+- [ ] Back/forward buttons → history is preserved correctly
+
+---
+
+## Phase 7: Deploy to Test Environment
+
+### Task 28: Push to test env
+
+```bash
+git push origin NevilleQingNY/workspace-url-refactor
+```
+
+Open PR against `main`. CI runs full test suite.
+
+Deploy to test environment (per project deployment procedure — typically via PR preview or staging deploy).
+
+**Staging verification (1-2 days):**
+- Team members use test environment
+- Watch for regressions in bug tracker
+- Confirm MUL-43, MUL-509, MUL-723, MUL-727, MUL-728, MUL-820 are fixed
+- Verify no new issues emerge in navigation, workspace switching, or data loading
+
+### Task 29: Merge to main
+
+After staging verification passes, merge PR to `main`. Production deploy follows normal CI/CD flow.
+
+---
+
+## Rollback Plan
+
+If a critical regression is discovered in production:
+
+1. Revert the PR via `git revert <merge-commit>`.
+2. Deploy the revert.
+3. Users with stored `last_workspace_slug` cookie are unaffected (cookie is ignored by old code).
+4. URLs in external bookmarks (e.g. `/acme/issues/abc`) become 404. Since product has no real users, impact is minimal. If it matters: add a one-time middleware that strips the first segment and redirects.
+
+---
+
+## Out of Scope (Explicit)
+
+The following are NOT part of this PR:
+
+- **#951 (WS half-open cache stale)** — unrelated realtime problem. Separate plan.
+- **Slug rename support** — backend currently forbids slug updates. If product later wants renameable slugs, needs separate migration (URL redirects for old slugs).
+- **Backend slug-based API routes** — backend stays on UUID. Frontend resolves slug → id via workspace list.
+- **Cross-workspace linking in mentions** — `mention://` protocol already carries UUID only. If/when product wants rich cross-workspace references, that's a separate design.
+- **Multi-workspace-tab UX on desktop** — desktop can now technically support multiple workspace tabs open, but UI promoting this pattern is future work.
+
+---
+
+## Progress Tracking
+
+Use TaskCreate during execution to track per-task progress. Commit after each task unless explicitly batching. Run `make check` before the final push.
+
+**Estimated timeline:**
+- Phase 1 (Foundation): ~0.5 day
+- Phase 2 (Web routes): ~0.5 day
+- Phase 3 (Path callsites): ~1 day
+- Phase 4 (Desktop): ~0.5 day
+- Phase 5 (Verification): ~0.5-1 day (depending on test fixture updates)
+- Phase 6-7 (QA + deploy): ~1-2 days in staging
+
+**Total: ~4-5 engineer-days** (with AI-assisted code generation + careful review).
diff --git a/docs/workspace-url-refactor-proposal.md b/docs/workspace-url-refactor-proposal.md
new file mode 100644
index 0000000000..25d8a7df57
--- /dev/null
+++ b/docs/workspace-url-refactor-proposal.md
@@ -0,0 +1,109 @@
+# Workspace URL 化重构 — 项目汇报
+
+**日期**:2026-04-15
+**作者**:Naiyuan
+**状态**:调研完成,待评审
+
+---
+
+## 一、为什么要做
+
+当前 workspace 上下文完全靠 `X-Workspace-ID` HTTP header + Zustand store + localStorage 承载,URL 里**不含任何 workspace 信息**。所有路径都是 `/issues`、`/issues/:id` 这种 workspace-agnostic 的。
+
+这个设计已经在产品里直接表现为 3 个已知问题:
+
+1. **分享链接不可靠**(MUL-43):`/issues/abc` 发给另一个成员,会用他自己 localStorage 里的 workspace 去解析,导致 404 或看到错误 workspace 的数据
+2. **手机端无法切 workspace**(MUL-509):切换只靠 sidebar UI,手机端不展开 sidebar 就没有切换入口
+3. **多 tab 互相覆盖**:`multica_workspace_id` 是全局 localStorage key,两个 tab 打开不同 workspace 会互相污染
+
+除了这 3 个显性 bug,架构上的"多份 workspace 状态拷贝互相同步"也带来一些隐性问题(创建 workspace 闪页、切换 workspace 时 cache 竞态等),积累时间越长后续改动越难。
+
+行业惯例(Linear / Notion / Vercel / GitHub)都是 `/{workspace-slug}/...` 的 URL 形态,把 URL 当作 workspace 的唯一来源。这是我们应该对齐的最佳实践。
+
+## 二、调研结论
+
+### 好消息:基础设施已经就位
+
+- 数据库 `workspace.slug` 字段已经存在(`TEXT UNIQUE NOT NULL`),用户创建时手动指定且不可修改
+- 后端已有 `GetWorkspaceBySlug` 查询
+- 前端 `Workspace` 类型已包含 `slug` 字段
+- Web 端认证已经切换为 HttpOnly cookie 模式,Next.js middleware 可读到登录态
+
+也就是说这次改造**不需要大量后端改动**,主要是前端路由和状态管理的重新组织。
+
+### 坏消息:范围比最初估计大
+
+初看以为只是"URL 前缀加个 slug",调研后发现必须一起做的事情有:
+
+1. **URL 路由重组**:web 端所有 dashboard 路由迁到 `app/[workspaceSlug]/(dashboard)/*`;desktop 端所有 react-router 路由加 `/:workspaceSlug` 前缀
+2. **状态管理清理**:删除 `useWorkspaceStore.workspace` 作为独立状态,改为从 URL 派生;删除 `hydrateWorkspace` / `switchWorkspace` actions(切 workspace 变成纯导航);删除 `localStorage["multica_workspace_id"]`
+3. **所有路径引用替换**:`push("/issues")` 改为 path builder(`paths.issues()`),影响 ~25 个组件文件
+4. **Mutation 副作用重构**:`useCreateWorkspace` / `useLeaveWorkspace` / `useDeleteWorkspace` 里的 `switchWorkspace` 调用全部移除(这些调用正是 MUL-727 闪页、MUL-728 删除后不跳转、MUL-820 接受邀请不切 workspace 等一系列 bug 的根因)
+5. **桌面端 tab 系统适配**:tab 路径天然包含 workspace,切 workspace = 开新 tab 或导航,不再有全局切换动作
+6. **Shareable URL 修复**:桌面端 `getShareableUrl` 当前生成 `https://www.multica.ai/issues/abc`(缺 slug),需要更新
+7. **后端保留词校验**:slug 不能和前端顶级路由冲突(`login`、`onboarding`、`invite`、`api`、`settings` 等),后端创建时校验
+8. **内部 markdown 链接兼容**:issue 评论里写的 `[foo](/issues/abc)` 触发的 `multica:navigate` 事件需要自动补当前 workspace slug
+
+### 不需要改的(边界已确认)
+
+- 邮件邀请链接 `/invite/{id}` — 接受邀请是 pre-workspace 流程,不需要 slug
+- `mention://type/id` 协议 — 只存 UUID,workspace-agnostic
+- CLI 登录 URL — `/login` 也是 pre-workspace,不需要 slug
+- 后端 API 路径 — 保持 `/api/workspaces/{id}`,slug 仅用于前端 URL
+- 桌面端 `multica://auth/callback` — 认证回调,不涉及 workspace
+
+## 三、方案要点
+
+**核心原则**:URL 是 workspace 上下文的唯一 source of truth,其他状态都是派生态。
+
+**URL 形状**:`/{workspace-slug}/issues/{id}` (和 Linear / Notion 一致)
+
+**切换 workspace = 导航**:sidebar 下拉改为 `<Link href="/{new-slug}/issues">`,不再有命令式的 `switchWorkspace` 函数。这样一次性消除前面列出的一大批 mutation 副作用 bug。
+
+**预估影响面**:~30-35 个文件,其中约 20 个是机械替换(hardcoded 路径 → path builder),真正需要思考的核心逻辑改动集中在 5-6 个文件。
+
+**一个 PR 合并**:中间状态不可运行(URL 结构是原子变化),不拆 PR。worktree 里充分开发和自测,一次 review 合并。
+
+## 四、执行与测试计划
+
+### 执行阶段
+
+1. **本周内**:完成方案详细实施文档(精确到文件 / 行号 / 代码片段)
+2. **下一步**:在独立 worktree 上开发,AI 辅助写代码,过程中人工 review
+3. **开发完成后**:本地跑全套验证(`make check` — TypeScript + 单测 + Go 测试 + E2E)
+
+### 测试阶段
+
+1. **本地自测**:
+ - 已知功能路径(创建 / 浏览 / 搜索 issue,切换 workspace,接受邀请,分享链接)
+ - 已知 bug 场景(MUL-43 / MUL-509 / MUL-727 / MUL-820)逐一验证已修复
+ - 多 tab 场景(两个 tab 打开不同 workspace 互不影响)
+2. **测试环境部署**:本地通过后发测试环境,全员试用几天,观察:
+ - 是否有回归(特别是导航流、创建/删除 workspace、邀请流程)
+ - URL 使用感受(分享、收藏、刷新)
+3. **灰度 / 生产**:测试环境稳定后推生产
+
+### 风险提示
+
+- **唯一的硬中断点**:现有的 `/issues` 等 URL 在重构后会 404(产品还没正式 ship、用户量可忽略,所以不做兼容性重定向)
+- **E2E 测试断言**:约 20-30 处 URL 断言需要更新
+- **后端保留词清单**:如果现有 workspace 里有名字撞到保留词的(例如正好叫 `settings`),需要提前 migrate(可能性极低,因 slug 限制较严)
+
+## 五、附注
+
+这次重构会**顺带修掉**以下已登记 issue,不需要单独开 PR:
+
+| Issue | 修复方式 |
+|---|---|
+| MUL-43(切换 workspace 报错 / 分享链接失效) | URL 带 slug,根本解决 |
+| MUL-509(手机端无法切 workspace) | 切换变导航,手机能点链接就能切 |
+| MUL-723(workspace 不在 URL) | 核心目标 |
+| MUL-727(创建 workspace 闪 /issues) | 删除 mutation 里的 switchWorkspace 副作用 |
+| MUL-728(删除 workspace 后留在 /settings) | 删除成功后 navigate 到下一个 workspace |
+| MUL-820(sidebar Join 不切 workspace) | Join 改成跳转到 `/invite/{id}` 走统一路径 |
+
+不在本次范围内的:Issue #951(WebSocket 半开导致 cache 陈旧)—— 这是 realtime 层独立问题,单独 PR 处理。
+
+---
+
+**当前状态**:准备进入详细实施方案撰写,预计完成后再同步一次。
diff --git a/e2e/auth.spec.ts b/e2e/auth.spec.ts
index fabcf96eb6..c8f0d469a6 100644
--- a/e2e/auth.spec.ts
+++ b/e2e/auth.spec.ts
@@ -24,10 +24,12 @@ test.describe("Authentication", () => {
await page.goto("/login");
await page.evaluate(() => {
localStorage.removeItem("multica_token");
- localStorage.removeItem("multica_workspace_id");
});
- await page.goto("/issues");
+ // Visit a workspace-scoped route; DashboardGuard should redirect to /login.
+ // The slug here need not exist — the guard runs before workspace resolution
+ // for unauthenticated users.
+ await page.goto("/e2e-workspace/issues");
await page.waitForURL("**/login", { timeout: 10000 });
});
diff --git a/e2e/comments.spec.ts b/e2e/comments.spec.ts
index 68f55251b5..cbfb43cb82 100644
--- a/e2e/comments.spec.ts
+++ b/e2e/comments.spec.ts
@@ -16,8 +16,9 @@ test.describe("Comments", () => {
});
test("can add a comment on an issue", async ({ page }) => {
- // Wait for issues to load and click first one
- const issueLink = page.locator('a[href^="/issues/"]').first();
+ // Wait for issues to load and click first one. `*=` matches both legacy
+ // `/issues/{id}` and URL-refactored `/{slug}/issues/{id}` hrefs.
+ const issueLink = page.locator('a[href*="/issues/"]').first();
await expect(issueLink).toBeVisible({ timeout: 5000 });
await issueLink.click();
await page.waitForURL(/\/issues\/[\w-]+/);
@@ -42,7 +43,7 @@ test.describe("Comments", () => {
});
test("comment submit button is disabled when empty", async ({ page }) => {
- const issueLink = page.locator('a[href^="/issues/"]').first();
+ const issueLink = page.locator('a[href*="/issues/"]').first();
await expect(issueLink).toBeVisible({ timeout: 5000 });
await issueLink.click();
await page.waitForURL(/\/issues\/[\w-]+/);
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index e972fe47e7..10ff0e9973 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -7,7 +7,10 @@
import "./env";
import pg from "pg";
-const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? `http://localhost:${process.env.PORT ?? "8080"}`;
+// `||` (not `??`) so an empty `NEXT_PUBLIC_API_URL=` in .env still falls
+// back to localhost. dotenv sets unset-vs-empty both as "" — treating them
+// the same matches user intent.
+const API_BASE = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;
const DATABASE_URL = process.env.DATABASE_URL ?? "postgres://multica:multica@localhost:5432/multica?sslmode=disable";
interface TestWorkspace {
@@ -18,6 +21,7 @@ interface TestWorkspace {
export class TestApiClient {
private token: string | null = null;
+ private workspaceSlug: string | null = null;
private workspaceId: string | null = null;
private createdIssueIds: string[] = [];
@@ -86,11 +90,16 @@ export class TestApiClient {
this.workspaceId = id;
}
+ setWorkspaceSlug(slug: string) {
+ this.workspaceSlug = slug;
+ }
+
async ensureWorkspace(name = "E2E Workspace", slug = "e2e-workspace") {
const workspaces = await this.getWorkspaces();
const workspace = workspaces.find((item) => item.slug === slug) ?? workspaces[0];
if (workspace) {
this.workspaceId = workspace.id;
+ this.workspaceSlug = workspace.slug;
return workspace;
}
@@ -150,7 +159,8 @@ export class TestApiClient {
...((init?.headers as Record<string, string>) ?? {}),
};
if (this.token) headers["Authorization"] = `Bearer ${this.token}`;
- if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
+ if (this.workspaceSlug) headers["X-Workspace-Slug"] = this.workspaceSlug;
+ else if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
return fetch(`${API_BASE}${path}`, { ...init, headers });
}
}
diff --git a/e2e/helpers.ts b/e2e/helpers.ts
index d36d2bc1cd..8dc212d42e 100644
--- a/e2e/helpers.ts
+++ b/e2e/helpers.ts
@@ -9,19 +9,25 @@ const DEFAULT_E2E_WORKSPACE = "e2e-workspace";
* Log in as the default E2E user and ensure the workspace exists first.
* Authenticates via API (send-code → DB read → verify-code), then injects
* the token into localStorage so the browser session is authenticated.
+ *
+ * Returns the E2E workspace slug so callers can build workspace-scoped URLs.
*/
-export async function loginAsDefault(page: Page) {
+export async function loginAsDefault(page: Page): Promise<string> {
const api = new TestApiClient();
await api.login(DEFAULT_E2E_EMAIL, DEFAULT_E2E_NAME);
- await api.ensureWorkspace("E2E Workspace", DEFAULT_E2E_WORKSPACE);
+ const workspace = await api.ensureWorkspace(
+ "E2E Workspace",
+ DEFAULT_E2E_WORKSPACE,
+ );
const token = api.getToken();
await page.goto("/login");
await page.evaluate((t) => {
localStorage.setItem("multica_token", t);
}, token);
- await page.goto("/issues");
+ await page.goto(`/${workspace.slug}/issues`);
await page.waitForURL("**/issues", { timeout: 10000 });
+ return workspace.slug;
}
/**
diff --git a/e2e/issues.spec.ts b/e2e/issues.spec.ts
index 48b4d4ffac..d675a5abdb 100644
--- a/e2e/issues.spec.ts
+++ b/e2e/issues.spec.ts
@@ -65,8 +65,10 @@ test.describe("Issues", () => {
// Reload to see the new issue
await page.reload();
- // Navigate to the issue detail
- const issueLink = page.locator(`a[href="/issues/${issue.id}"]`);
+ // Navigate to the issue detail. Use a suffix match so the selector works
+ // whether the href is legacy `/issues/{id}` or URL-refactored
+ // `/{slug}/issues/{id}`.
+ const issueLink = page.locator(`a[href$="/issues/${issue.id}"]`);
await expect(issueLink).toBeVisible({ timeout: 5000 });
await issueLink.click();
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 8edaf5b6a4..2df899b98c 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -66,6 +66,7 @@ import type {
} from "../types";
import { type Logger, noopLogger } from "../logger";
import { createRequestId } from "../utils";
+import { getCurrentSlug } from "../platform/workspace-storage";
export interface ApiClientOptions {
logger?: Logger;
@@ -92,7 +93,6 @@ export class ApiError extends Error {
export class ApiClient {
private baseUrl: string;
private token: string | null = null;
- private workspaceId: string | null = null;
private logger: Logger;
private options: ApiClientOptions;
@@ -110,10 +110,6 @@ export class ApiClient {
this.token = token;
}
- setWorkspaceId(id: string | null) {
- this.workspaceId = id;
- }
-
private readCsrfToken(): string | null {
if (typeof document === "undefined") return null;
const match = document.cookie
@@ -125,7 +121,8 @@ export class ApiClient {
private authHeaders(): Record<string, string> {
const headers: Record<string, string> = {};
if (this.token) headers["Authorization"] = `Bearer ${this.token}`;
- if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
+ const slug = getCurrentSlug();
+ if (slug) headers["X-Workspace-Slug"] = slug;
const csrf = this.readCsrfToken();
if (csrf) headers["X-CSRF-Token"] = csrf;
return headers;
@@ -133,7 +130,10 @@ export class ApiClient {
private handleUnauthorized() {
this.token = null;
- this.workspaceId = null;
+ // Workspace id is owned by the URL-driven workspace-storage singleton
+ // (set by [workspaceSlug]/layout.tsx). On 401, the auth flow navigates
+ // to /login which leaves the workspace route, and the next workspace
+ // entry will overwrite the id. No clear needed here.
this.options.onUnauthorized?.();
}
@@ -231,8 +231,7 @@ export class ApiClient {
const search = new URLSearchParams();
if (params?.limit) search.set("limit", String(params.limit));
if (params?.offset) search.set("offset", String(params.offset));
- const wsId = params?.workspace_id ?? this.workspaceId;
- if (wsId) search.set("workspace_id", wsId);
+ if (params?.workspace_id) search.set("workspace_id", params.workspace_id);
if (params?.status) search.set("status", params.status);
if (params?.priority) search.set("priority", params.priority);
if (params?.assignee_id) search.set("assignee_id", params.assignee_id);
@@ -263,9 +262,7 @@ export class ApiClient {
}
async createIssue(data: CreateIssueRequest): Promise<Issue> {
- const search = new URLSearchParams();
- if (this.workspaceId) search.set("workspace_id", this.workspaceId);
- return this.fetch(`/api/issues?${search}`, {
+ return this.fetch("/api/issues", {
method: "POST",
body: JSON.stringify(data),
});
@@ -396,8 +393,7 @@ export class ApiClient {
// Agents
async listAgents(params?: { workspace_id?: string; include_archived?: boolean }): Promise<Agent[]> {
const search = new URLSearchParams();
- const wsId = params?.workspace_id ?? this.workspaceId;
- if (wsId) search.set("workspace_id", wsId);
+ if (params?.workspace_id) search.set("workspace_id", params.workspace_id);
if (params?.include_archived) search.set("include_archived", "true");
return this.fetch(`/api/agents?${search}`);
}
@@ -430,8 +426,7 @@ export class ApiClient {
async listRuntimes(params?: { workspace_id?: string; owner?: "me" }): Promise<AgentRuntime[]> {
const search = new URLSearchParams();
- const wsId = params?.workspace_id ?? this.workspaceId;
- if (wsId) search.set("workspace_id", wsId);
+ if (params?.workspace_id) search.set("workspace_id", params.workspace_id);
if (params?.owner) search.set("owner", params.owner);
return this.fetch(`/api/runtimes?${search}`);
}
@@ -788,9 +783,7 @@ export class ApiClient {
}
async createProject(data: CreateProjectRequest): Promise<Project> {
- const search = new URLSearchParams();
- if (this.workspaceId) search.set("workspace_id", this.workspaceId);
- return this.fetch(`/api/projects?${search}`, {
+ return this.fetch("/api/projects", {
method: "POST",
body: JSON.stringify(data),
});
diff --git a/packages/core/api/ws-client.ts b/packages/core/api/ws-client.ts
index dae5b91808..f139cada0e 100644
--- a/packages/core/api/ws-client.ts
+++ b/packages/core/api/ws-client.ts
@@ -7,7 +7,7 @@ export class WSClient {
private ws: WebSocket | null = null;
private baseUrl: string;
private token: string | null = null;
- private workspaceId: string | null = null;
+ private workspaceSlug: string | null = null;
private cookieAuth = false;
private handlers = new Map<WSEventType, Set<EventHandler>>();
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
@@ -22,9 +22,9 @@ export class WSClient {
this.cookieAuth = options?.cookieAuth ?? false;
}
- setAuth(token: string | null, workspaceId: string) {
+ setAuth(token: string | null, workspaceSlug: string) {
this.token = token;
- this.workspaceId = workspaceId;
+ this.workspaceSlug = workspaceSlug;
}
connect() {
@@ -33,8 +33,8 @@ export class WSClient {
// proxies, CDNs, and browser history. In cookie mode the HttpOnly cookie
// is sent automatically with the upgrade request. In token mode the token
// is delivered as the first WebSocket message after the connection opens.
- if (this.workspaceId)
- url.searchParams.set("workspace_id", this.workspaceId);
+ if (this.workspaceSlug)
+ url.searchParams.set("workspace_slug", this.workspaceSlug);
this.ws = new WebSocket(url.toString());
diff --git a/packages/core/auth/store.ts b/packages/core/auth/store.ts
index 4f3cc3f65c..41240845a4 100644
--- a/packages/core/auth/store.ts
+++ b/packages/core/auth/store.ts
@@ -1,6 +1,7 @@
import { create } from "zustand";
import type { User, StorageAdapter } from "../types";
import type { ApiClient } from "../api/client";
+import { setCurrentWorkspace } from "../platform/workspace-storage";
export interface AuthStoreOptions {
api: ApiClient;
@@ -58,7 +59,7 @@ export function createAuthStore(options: AuthStoreOptions) {
set({ user, isLoading: false });
} catch {
api.setToken(null);
- api.setWorkspaceId(null);
+ setCurrentWorkspace(null, null);
storage.removeItem("multica_token");
set({ user: null, isLoading: false });
}
@@ -107,7 +108,7 @@ export function createAuthStore(options: AuthStoreOptions) {
}
storage.removeItem("multica_token");
api.setToken(null);
- api.setWorkspaceId(null);
+ setCurrentWorkspace(null, null);
onLogout?.();
set({ user: null });
},
diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.ts
index 5e028ee2cb..5dc5d1f195 100644
--- a/packages/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -3,10 +3,10 @@ import { api } from "../api";
// NOTE on workspace scoping:
// `wsId` is used only as part of queryKey for cache isolation per workspace.
-// The actual workspace context comes from ApiClient's X-Workspace-ID header,
-// which is set by useWorkspaceStore.switchWorkspace(). Callers must ensure the
-// header is in sync with the wsId they pass here — otherwise cache writes will
-// be misattributed during a workspace switch race window.
+// The actual workspace context comes from ApiClient's X-Workspace-Slug header,
+// which is set by the URL-driven [workspaceSlug] layout. Callers must ensure
+// the header is in sync with the wsId they pass here — otherwise cache writes
+// will be misattributed during a workspace switch race window.
export const chatKeys = {
all: (wsId: string) => ["chat", wsId] as const,
diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.ts
index e8a50f894c..b68a02a92e 100644
--- a/packages/core/chat/store.ts
+++ b/packages/core/chat/store.ts
@@ -1,6 +1,6 @@
import { create } from "zustand";
import type { StorageAdapter } from "../types";
-import { getCurrentWorkspaceId, registerForWorkspaceRehydration } from "../platform/workspace-storage";
+import { getCurrentSlug, registerForWorkspaceRehydration } from "../platform/workspace-storage";
import { createLogger } from "../logger";
const logger = createLogger("chat.store");
@@ -90,8 +90,8 @@ export function createChatStore(options: ChatStoreOptions) {
const { storage } = options;
const wsKey = (base: string) => {
- const wsId = getCurrentWorkspaceId();
- return wsId ? `${base}:${wsId}` : base;
+ const slug = getCurrentSlug();
+ return slug ? `${base}:${slug}` : base;
};
const store = create<ChatState>((set, get) => ({
diff --git a/packages/core/hooks.tsx b/packages/core/hooks.tsx
index 06724067d9..98026c8d5a 100644
--- a/packages/core/hooks.tsx
+++ b/packages/core/hooks.tsx
@@ -1,25 +1,17 @@
"use client";
-import { createContext, useContext } from "react";
-
-const WorkspaceIdContext = createContext<string | null>(null);
-
-export function WorkspaceIdProvider({
- wsId,
- children,
-}: {
- wsId: string;
- children: React.ReactNode;
-}) {
- return (
- <WorkspaceIdContext.Provider value={wsId}>
- {children}
- </WorkspaceIdContext.Provider>
- );
-}
+import { useCurrentWorkspace } from "./paths/hooks";
+/**
+ * Returns the current workspace UUID. Throws if called outside a workspace route.
+ *
+ * Implementation: derives from useCurrentWorkspace() (URL slug + React Query list).
+ * No longer backed by a React Context — the WorkspaceIdProvider has been removed
+ * as part of the slug-first refactor. The throw semantics are preserved so existing
+ * callers that depend on non-null don't need guard code.
+ */
export function useWorkspaceId(): string {
- const wsId = useContext(WorkspaceIdContext);
- if (!wsId) throw new Error("useWorkspaceId: no workspace selected — wrap in WorkspaceIdProvider");
- return wsId;
+ const ws = useCurrentWorkspace();
+ if (!ws) throw new Error("useWorkspaceId: no workspace selected — ensure component renders inside a workspace route");
+ return ws.id;
}
diff --git a/packages/core/index.ts b/packages/core/index.ts
index de332455d7..465470a4b5 100644
--- a/packages/core/index.ts
+++ b/packages/core/index.ts
@@ -1,3 +1,3 @@
-export { useWorkspaceId, WorkspaceIdProvider } from "./hooks";
+export { useWorkspaceId } from "./hooks";
export { createQueryClient } from "./query-client";
export { QueryProvider } from "./provider";
diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.ts
index 19af5fc550..50216036df 100644
--- a/packages/core/issues/stores/index.ts
+++ b/packages/core/issues/stores/index.ts
@@ -17,8 +17,7 @@ export {
createIssueViewStore,
viewStoreSlice,
viewStorePersistOptions,
- registerViewStoreForWorkspaceSync,
- initFilterWorkspaceSync,
+ useClearFiltersOnWorkspaceChange,
SORT_OPTIONS,
CARD_PROPERTY_OPTIONS,
type ViewMode,
diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.ts
index daf6ca93c1..3cb19182f7 100644
--- a/packages/core/issues/stores/view-store.ts
+++ b/packages/core/issues/stores/view-store.ts
@@ -1,5 +1,6 @@
"use client";
+import { useEffect, useRef } from "react";
import { create } from "zustand";
import { createStore, type StoreApi } from "zustand/vanilla";
import { createJSONStorage, persist } from "zustand/middleware";
@@ -215,43 +216,23 @@ export const useIssueViewStore = create<IssueViewState>()(
registerForWorkspaceRehydration(() => useIssueViewStore.persist.rehydrate());
-// Clear filters on all registered view stores when workspace switches.
-const _syncedStores = new Set<StoreApi<IssueViewState>>();
-let _workspaceSyncInitialized = false;
-
/**
- * Register a view store to clear filters on workspace switch.
+ * Clears the given view store's filters whenever the workspace id changes.
*
- * @param store - The view store to register.
- * @param subscribeToWorkspace - Optional: a function that subscribes to workspace
- * changes and calls the callback with the new workspace ID. The app layer should
- * provide this to avoid a circular dependency on the workspace store.
- * Example: `(cb) => useWorkspaceStore.subscribe(s => cb(s.workspace?.id))`
+ * URL-driven: wsId arrives from `useWorkspaceId()` (Context fed by the
+ * `[workspaceSlug]` route). We track the previous id via ref so the first
+ * render doesn't wipe persisted filters — clearing only fires on transitions
+ * from one defined workspace to another.
*/
-export function registerViewStoreForWorkspaceSync(
- store: StoreApi<IssueViewState>,
- subscribeToWorkspace?: (callback: (workspaceId: string | undefined) => void) => void,
+export function useClearFiltersOnWorkspaceChange(
+ store: StoreApi<IssueViewState> | { getState: () => IssueViewState },
+ wsId: string | undefined,
) {
- _syncedStores.add(store);
- if (_workspaceSyncInitialized) return;
- _workspaceSyncInitialized = true;
-
- if (subscribeToWorkspace) {
- let prevId: string | undefined;
- subscribeToWorkspace((id) => {
- if (prevId && id !== prevId) {
- for (const s of _syncedStores) s.getState().clearFilters();
- }
- prevId = id;
- });
- }
- // TODO: If no subscribeToWorkspace is provided, the workspace sync is a no-op.
- // The app layer (apps/web) should call this with the workspace store subscription
- // to wire up filter clearing on workspace switch.
+ const prevIdRef = useRef<string | undefined>(undefined);
+ useEffect(() => {
+ if (prevIdRef.current && wsId && wsId !== prevIdRef.current) {
+ store.getState().clearFilters();
+ }
+ prevIdRef.current = wsId;
+ }, [wsId, store]);
}
-
-/** Backward-compatible alias — registers the global singleton for workspace sync. */
-export const initFilterWorkspaceSync = (
- subscribeToWorkspace?: (callback: (workspaceId: string | undefined) => void) => void,
-) =>
- registerViewStoreForWorkspaceSync(useIssueViewStore, subscribeToWorkspace);
diff --git a/packages/core/navigation/store.test.ts b/packages/core/navigation/store.test.ts
new file mode 100644
index 0000000000..a9dce8d539
--- /dev/null
+++ b/packages/core/navigation/store.test.ts
@@ -0,0 +1,36 @@
+import { describe, it, expect } from "vitest";
+
+// EXCLUDED_PREFIXES is private to store.ts but checked here via behavior.
+// We assert that every global path prefix is also excluded from lastPath
+// persistence — otherwise lastPath could contain /login etc, and on next
+// app load we'd "restore" a user to the login page.
+describe("useNavigationStore.lastPath excludes global paths", () => {
+ it("does not persist /login, /onboarding, /invite/, /auth/, /logout, /signup", async () => {
+ const { useNavigationStore } = await import("./store");
+ const globalPrefixes = [
+ "/login",
+ "/logout",
+ "/signup",
+ "/onboarding",
+ "/invite/abc",
+ "/auth/callback",
+ ];
+
+ for (const path of globalPrefixes) {
+ // Reset to a known sentinel so we can detect any write.
+ useNavigationStore.setState({ lastPath: "/sentinel" });
+ useNavigationStore.getState().onPathChange(path);
+ expect(
+ useNavigationStore.getState().lastPath,
+ `${path} should not be persisted as lastPath (would restore user to a global route)`,
+ ).toBe("/sentinel");
+ }
+ });
+
+ it("does persist workspace-scoped paths", async () => {
+ const { useNavigationStore } = await import("./store");
+ useNavigationStore.setState({ lastPath: null });
+ useNavigationStore.getState().onPathChange("/acme/issues");
+ expect(useNavigationStore.getState().lastPath).toBe("/acme/issues");
+ });
+});
diff --git a/packages/core/navigation/store.ts b/packages/core/navigation/store.ts
index 6f2d3d2779..77b659bfb8 100644
--- a/packages/core/navigation/store.ts
+++ b/packages/core/navigation/store.ts
@@ -2,21 +2,35 @@
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
-import { createPersistStorage } from "../platform/persist-storage";
+import {
+ createWorkspaceAwareStorage,
+ registerForWorkspaceRehydration,
+} from "../platform/workspace-storage";
import { defaultStorage } from "../platform/storage";
-const EXCLUDED_PREFIXES = ["/login", "/pair/", "/invite/"];
+// Paths that should not be persisted as "last visited":
+// - Auth flows (/login, /signup, /logout)
+// - Pre-workspace routes (/onboarding, /auth/, /invite/)
+// - Pair flow (/pair/)
+const EXCLUDED_PREFIXES = [
+ "/login",
+ "/signup",
+ "/logout",
+ "/onboarding",
+ "/auth/",
+ "/invite/",
+ "/pair/",
+];
interface NavigationState {
- lastPath: string;
+ lastPath: string | null;
onPathChange: (path: string) => void;
}
export const useNavigationStore = create<NavigationState>()(
persist(
(set) => ({
- lastPath: "/issues",
-
+ lastPath: null,
onPathChange: (path: string) => {
if (!EXCLUDED_PREFIXES.some((prefix) => path.startsWith(prefix))) {
set({ lastPath: path });
@@ -25,8 +39,11 @@ export const useNavigationStore = create<NavigationState>()(
}),
{
name: "multica_navigation",
- storage: createJSONStorage(() => createPersistStorage(defaultStorage)),
+ storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
partialize: (state) => ({ lastPath: state.lastPath }),
- }
- )
+ },
+ ),
);
+
+// Workspace-aware: re-read lastPath when current workspace changes.
+registerForWorkspaceRehydration(() => useNavigationStore.persist.rehydrate());
diff --git a/packages/core/package.json b/packages/core/package.json
index 37f63bbafe..0628d3c4af 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -55,6 +55,7 @@
"./realtime": "./realtime/index.ts",
"./navigation": "./navigation/index.ts",
"./modals": "./modals/index.ts",
+ "./paths": "./paths/index.ts",
"./hooks": "./hooks.tsx",
"./hooks/*": "./hooks/*.ts",
"./query-client": "./query-client.ts",
diff --git a/packages/core/paths/consistency.test.ts b/packages/core/paths/consistency.test.ts
new file mode 100644
index 0000000000..e284d5fb51
--- /dev/null
+++ b/packages/core/paths/consistency.test.ts
@@ -0,0 +1,93 @@
+import { describe, it, expect } from "vitest";
+import { paths, isGlobalPath } from "./paths";
+import { RESERVED_SLUGS } from "./reserved-slugs";
+
+// C4 — link-handler's WORKSPACE_ROUTE_SEGMENTS must match paths.workspace's
+// parameterless method names. We can't import WORKSPACE_ROUTE_SEGMENTS here
+// because link-handler is in packages/views (no inverse import allowed), so
+// we hardcode the expected list and assert paths.workspace produces the same
+// keys. If you change either, BOTH need to be updated — the test catches drift.
+describe("paths.workspace() shape", () => {
+ it("exposes the expected parameterless workspace route methods", () => {
+ const ws = paths.workspace("__probe__");
+ const parameterlessRoutes = Object.entries(ws)
+ .filter(([, fn]) => typeof fn === "function" && fn.length === 0)
+ .map(([key]) => key);
+
+ expect(new Set(parameterlessRoutes)).toEqual(
+ new Set([
+ "root",
+ "issues",
+ "projects",
+ "autopilots",
+ "agents",
+ "inbox",
+ "myIssues",
+ "runtimes",
+ "skills",
+ "settings",
+ ]),
+ );
+ });
+
+ it("each parameterless route emits /{slug}/{segment}", () => {
+ const ws = paths.workspace("acme");
+ // Check that none of the parameterless paths embed a leaked literal
+ // and that their second URL segment matches the method name's kebab-case.
+ const expectedSegments: Array<[string, string]> = [
+ ["issues", "issues"],
+ ["projects", "projects"],
+ ["autopilots", "autopilots"],
+ ["agents", "agents"],
+ ["inbox", "inbox"],
+ ["myIssues", "my-issues"],
+ ["runtimes", "runtimes"],
+ ["skills", "skills"],
+ ["settings", "settings"],
+ ];
+ const wsAsAny = ws as unknown as Record<string, () => string>;
+ for (const [method, segment] of expectedSegments) {
+ const fn = wsAsAny[method];
+ expect(typeof fn).toBe("function");
+ expect(fn!()).toBe(`/acme/${segment}`);
+ }
+ });
+});
+
+// C5 — invariants between the global/reserved lists.
+describe("global path / reserved slug consistency", () => {
+ // If a path is "global" (never workspace-scoped), the slug name underlying it
+ // must be reserved — otherwise a user could create a workspace with that slug
+ // and shadow the global route's URL space.
+ //
+ // GLOBAL_PREFIXES from paths.ts is private — we re-derive the list from
+ // probing isGlobalPath. Order matters: keep this list in sync with paths.ts.
+ const globalPrefixes = [
+ "/login",
+ "/logout",
+ "/signup",
+ "/onboarding",
+ "/invite/",
+ "/auth/",
+ ];
+
+ it("isGlobalPath agrees with the canonical global prefix list", () => {
+ for (const prefix of globalPrefixes) {
+ expect(isGlobalPath(prefix)).toBe(true);
+ }
+ expect(isGlobalPath("/acme/issues")).toBe(false);
+ expect(isGlobalPath("/")).toBe(false);
+ });
+
+ it("every global prefix's first path segment is a reserved slug", () => {
+ for (const prefix of globalPrefixes) {
+ const firstSegment = prefix.split("/").filter(Boolean)[0];
+ if (!firstSegment) continue;
+ expect(
+ RESERVED_SLUGS.has(firstSegment),
+ `'${firstSegment}' is a global path prefix but not a reserved slug — ` +
+ `a workspace could be created with this slug and shadow the global route`,
+ ).toBe(true);
+ }
+ });
+});
diff --git a/packages/core/paths/hooks.tsx b/packages/core/paths/hooks.tsx
new file mode 100644
index 0000000000..6777fb5ae5
--- /dev/null
+++ b/packages/core/paths/hooks.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { createContext, useContext, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { Workspace } from "../types";
+import { workspaceListOptions } from "../workspace/queries";
+import { paths, type WorkspacePaths } from "./paths";
+
+/**
+ * Context for the current workspace slug (read from URL by the platform layer).
+ *
+ * apps/web populates this from Next.js `params.workspaceSlug` in
+ * [workspaceSlug]/layout.tsx. apps/desktop populates it from react-router's
+ * `useParams()` in the workspace route layout.
+ *
+ * packages/core/ cannot import next/navigation or react-router-dom directly,
+ * so the slug arrives via this Context — mirroring how WorkspaceIdProvider
+ * already works for workspace IDs.
+ */
+const WorkspaceSlugContext = createContext<string | null>(null);
+
+export function WorkspaceSlugProvider({
+ slug,
+ children,
+}: {
+ slug: string | null;
+ children: ReactNode;
+}) {
+ return (
+ <WorkspaceSlugContext.Provider value={slug}>
+ {children}
+ </WorkspaceSlugContext.Provider>
+ );
+}
+
+/** Current workspace slug from URL, or null outside workspace-scoped routes. */
+export function useWorkspaceSlug(): string | null {
+ return useContext(WorkspaceSlugContext);
+}
+
+/** Same as useWorkspaceSlug, but throws if called outside a workspace route. */
+export function useRequiredWorkspaceSlug(): string {
+ const slug = useWorkspaceSlug();
+ if (!slug) {
+ throw new Error(
+ "useRequiredWorkspaceSlug called outside a workspace-scoped route",
+ );
+ }
+ return slug;
+}
+
+/**
+ * The currently-selected workspace, derived from URL slug + React Query list.
+ * Returns null if slug is missing or doesn't match any workspace in the list.
+ */
+export function useCurrentWorkspace(): Workspace | null {
+ const slug = useWorkspaceSlug();
+ const { data: list = [] } = useQuery(workspaceListOptions());
+ if (!slug) return null;
+ return list.find((w) => w.slug === slug) ?? null;
+}
+
+/**
+ * Path builder bound to the current workspace. Throws if called outside a
+ * workspace route — for cross-workspace links use paths.workspace(slug) directly.
+ */
+export function useWorkspacePaths(): WorkspacePaths {
+ const slug = useRequiredWorkspaceSlug();
+ return paths.workspace(slug);
+}
diff --git a/packages/core/paths/index.ts b/packages/core/paths/index.ts
new file mode 100644
index 0000000000..de15fceffc
--- /dev/null
+++ b/packages/core/paths/index.ts
@@ -0,0 +1,10 @@
+export { paths, isGlobalPath } from "./paths";
+export type { WorkspacePaths } from "./paths";
+export { RESERVED_SLUGS, isReservedSlug } from "./reserved-slugs";
+export {
+ WorkspaceSlugProvider,
+ useWorkspaceSlug,
+ useRequiredWorkspaceSlug,
+ useCurrentWorkspace,
+ useWorkspacePaths,
+} from "./hooks";
diff --git a/packages/core/paths/paths.test.ts b/packages/core/paths/paths.test.ts
new file mode 100644
index 0000000000..0a2590aae7
--- /dev/null
+++ b/packages/core/paths/paths.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from "vitest";
+import { paths, isGlobalPath } from "./paths";
+
+describe("paths.workspace(slug)", () => {
+ const ws = paths.workspace("acme");
+
+ it("builds dashboard paths with slug prefix", () => {
+ expect(ws.issues()).toBe("/acme/issues");
+ expect(ws.issueDetail("abc-123")).toBe("/acme/issues/abc-123");
+ expect(ws.projects()).toBe("/acme/projects");
+ expect(ws.projectDetail("p1")).toBe("/acme/projects/p1");
+ expect(ws.autopilots()).toBe("/acme/autopilots");
+ expect(ws.autopilotDetail("a1")).toBe("/acme/autopilots/a1");
+ expect(ws.agents()).toBe("/acme/agents");
+ expect(ws.inbox()).toBe("/acme/inbox");
+ expect(ws.myIssues()).toBe("/acme/my-issues");
+ expect(ws.runtimes()).toBe("/acme/runtimes");
+ expect(ws.skills()).toBe("/acme/skills");
+ expect(ws.settings()).toBe("/acme/settings");
+ });
+
+ it("URL-encodes special characters in ids", () => {
+ expect(ws.issueDetail("id with space")).toBe("/acme/issues/id%20with%20space");
+ });
+});
+
+describe("paths (global)", () => {
+ it("builds global paths without slug", () => {
+ expect(paths.login()).toBe("/login");
+ expect(paths.onboarding()).toBe("/onboarding");
+ expect(paths.invite("inv-1")).toBe("/invite/inv-1");
+ expect(paths.authCallback()).toBe("/auth/callback");
+ });
+});
+
+describe("isGlobalPath", () => {
+ it("returns true for pre-workspace routes", () => {
+ expect(isGlobalPath("/login")).toBe(true);
+ expect(isGlobalPath("/onboarding")).toBe(true);
+ expect(isGlobalPath("/invite/abc")).toBe(true);
+ expect(isGlobalPath("/auth/callback")).toBe(true);
+ });
+
+ it("returns false for workspace-scoped paths", () => {
+ expect(isGlobalPath("/acme/issues")).toBe(false);
+ expect(isGlobalPath("/")).toBe(false);
+ });
+});
diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.ts
new file mode 100644
index 0000000000..dcaa56e70a
--- /dev/null
+++ b/packages/core/paths/paths.ts
@@ -0,0 +1,55 @@
+/**
+ * Centralized URL path builder. All navigation in shared packages (packages/views)
+ * MUST go through this module — no hardcoded string paths.
+ *
+ * Two kinds of paths:
+ * - workspace-scoped: paths.workspace(slug).xxx() — carry workspace in URL
+ * - global: paths.login(), paths.onboarding(), paths.invite(id) — pre-workspace routes
+ *
+ * Why pure functions + builder pattern:
+ * - Changing a route shape (e.g. adding workspace slug prefix) becomes a single-file edit
+ * - IDs are always URL-encoded here so callers can't forget
+ * - Zero runtime deps means this module is safe in Node (tests) and browsers
+ */
+
+const encode = (id: string) => encodeURIComponent(id);
+
+function workspaceScoped(slug: string) {
+ const ws = `/${encode(slug)}`;
+ return {
+ root: () => `${ws}/issues`,
+ issues: () => `${ws}/issues`,
+ issueDetail: (id: string) => `${ws}/issues/${encode(id)}`,
+ projects: () => `${ws}/projects`,
+ projectDetail: (id: string) => `${ws}/projects/${encode(id)}`,
+ autopilots: () => `${ws}/autopilots`,
+ autopilotDetail: (id: string) => `${ws}/autopilots/${encode(id)}`,
+ agents: () => `${ws}/agents`,
+ inbox: () => `${ws}/inbox`,
+ myIssues: () => `${ws}/my-issues`,
+ runtimes: () => `${ws}/runtimes`,
+ skills: () => `${ws}/skills`,
+ settings: () => `${ws}/settings`,
+ };
+}
+
+export const paths = {
+ workspace: workspaceScoped,
+
+ // Global (pre-workspace) routes
+ login: () => "/login",
+ onboarding: () => "/onboarding",
+ invite: (id: string) => `/invite/${encode(id)}`,
+ authCallback: () => "/auth/callback",
+ root: () => "/",
+};
+
+export type WorkspacePaths = ReturnType<typeof workspaceScoped>;
+
+// Prefixes — not slug names — because we match against full URL paths.
+// A path is global if it equals or begins with any of these.
+const GLOBAL_PREFIXES = ["/login", "/onboarding", "/invite/", "/auth/", "/logout", "/signup"];
+
+export function isGlobalPath(path: string): boolean {
+ return GLOBAL_PREFIXES.some((p) => path === p || path.startsWith(p));
+}
diff --git a/packages/core/paths/reserved-slugs.ts b/packages/core/paths/reserved-slugs.ts
new file mode 100644
index 0000000000..95bd6c13c1
--- /dev/null
+++ b/packages/core/paths/reserved-slugs.ts
@@ -0,0 +1,49 @@
+/**
+ * Slugs reserved because they collide with frontend top-level routes.
+ * Keep in sync with server/internal/handler/workspace_reserved_slugs.go.
+ */
+export const RESERVED_SLUGS = new Set([
+ // Auth + onboarding
+ "login",
+ "logout",
+ "signup",
+ "onboarding",
+ "invite",
+ "auth",
+
+ // Reserved for future platform routes
+ "api",
+ "admin",
+ "help",
+ "about",
+ "pricing",
+ "changelog",
+
+ // Dashboard route segments. Even though Next.js's route specificity
+ // would technically resolve /{slug}/{view} correctly, having a workspace
+ // slug equal to a route name (e.g. slug="issues") makes URLs visually
+ // ambiguous — /issues/abc reads as either "issue abc in workspace
+ // 'issues'" or "issue abc in some workspace". Reserve to avoid the
+ // ambiguity entirely.
+ "issues",
+ "projects",
+ "autopilots",
+ "agents",
+ "inbox",
+ "my-issues",
+ "runtimes",
+ "skills",
+ "settings",
+
+ // Next.js / hosting internals
+ "_next",
+ "favicon.ico",
+ "robots.txt",
+ "sitemap.xml",
+ "manifest.json",
+ ".well-known",
+]);
+
+export function isReservedSlug(slug: string): boolean {
+ return RESERVED_SLUGS.has(slug);
+}
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 1340df6120..802288131f 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -4,11 +4,11 @@ import { useEffect, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { getApi } from "../api";
import { useAuthStore } from "../auth";
-import { useWorkspaceStore } from "../workspace";
import { configStore } from "../config";
import { workspaceKeys } from "../workspace/queries";
import { createLogger } from "../logger";
import { defaultStorage } from "./storage";
+import { setCurrentWorkspace } from "./workspace-storage";
import type { StorageAdapter } from "../types/storage";
const logger = createLogger("auth");
@@ -30,7 +30,6 @@ export function AuthInitializer({
useEffect(() => {
const api = getApi();
- const wsId = storage.getItem("multica_workspace_id");
// Fetch app config (CDN domain, etc.) in the background — non-blocking.
api.getConfig().then((cfg) => {
@@ -40,12 +39,16 @@ export function AuthInitializer({
if (cookieAuth) {
// Cookie mode: the HttpOnly cookie is sent automatically by the browser.
// Call the API to check if the session is still valid.
+ //
+ // Seed the workspace list into React Query so the URL-driven layout can
+ // resolve the slug without a second fetch. The active workspace itself
+ // is derived from the URL by [workspaceSlug]/layout.tsx — no imperative
+ // selection here.
Promise.all([api.getMe(), api.listWorkspaces()])
.then(([user, wsList]) => {
onLogin?.();
useAuthStore.setState({ user, isLoading: false });
qc.setQueryData(workspaceKeys.list(), wsList);
- useWorkspaceStore.getState().hydrateWorkspace(wsList, wsId);
})
.catch((err) => {
logger.error("cookie auth init failed", err);
@@ -69,16 +72,15 @@ export function AuthInitializer({
.then(([user, wsList]) => {
onLogin?.();
useAuthStore.setState({ user, isLoading: false });
- // Seed React Query cache so components don't need a second fetch
+ // Seed React Query cache so the URL-driven layout can resolve the
+ // slug without a second fetch.
qc.setQueryData(workspaceKeys.list(), wsList);
- useWorkspaceStore.getState().hydrateWorkspace(wsList, wsId);
})
.catch((err) => {
logger.error("auth init failed", err);
api.setToken(null);
- api.setWorkspaceId(null);
+ setCurrentWorkspace(null, null);
storage.removeItem("multica_token");
- storage.removeItem("multica_workspace_id");
onLogout?.();
useAuthStore.setState({ user: null, isLoading: false });
});
diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsx
index b6205c04cb..5695f6ebce 100644
--- a/packages/core/platform/core-provider.tsx
+++ b/packages/core/platform/core-provider.tsx
@@ -4,7 +4,6 @@ import { useMemo } from "react";
import { ApiClient } from "../api/client";
import { setApiInstance } from "../api";
import { createAuthStore, registerAuthStore } from "../auth";
-import { createWorkspaceStore, registerWorkspaceStore } from "../workspace";
import { createChatStore, registerChatStore } from "../chat";
import { WSProvider } from "../realtime";
import { QueryProvider } from "../provider";
@@ -18,7 +17,6 @@ import type { StorageAdapter } from "../types/storage";
// Vite HMR preserves module-level state, so these survive hot reloads.
let initialized = false;
let authStore: ReturnType<typeof createAuthStore>;
-let workspaceStore: ReturnType<typeof createWorkspaceStore>;
let chatStore: ReturnType<typeof createChatStore>;
function initCore(
apiBaseUrl: string,
@@ -33,7 +31,6 @@ function initCore(
logger: createLogger("api"),
onUnauthorized: () => {
storage.removeItem("multica_token");
- storage.removeItem("multica_workspace_id");
},
});
setApiInstance(api);
@@ -43,15 +40,14 @@ function initCore(
const token = storage.getItem("multica_token");
if (token) api.setToken(token);
}
- const wsId = storage.getItem("multica_workspace_id");
- if (wsId) api.setWorkspaceId(wsId);
+ // Workspace identity is URL-driven: the [workspaceSlug] layout resolves
+ // the slug and calls setCurrentWorkspace(slug, wsId) on mount. The api
+ // client reads the slug from that singleton for the X-Workspace-Slug
+ // header. No boot-time hydration from storage is required.
authStore = createAuthStore({ api, storage, onLogin, onLogout, cookieAuth });
registerAuthStore(authStore);
- workspaceStore = createWorkspaceStore(api, { storage });
- registerWorkspaceStore(workspaceStore);
-
chatStore = createChatStore({ storage });
registerChatStore(chatStore);
@@ -78,7 +74,6 @@ export function CoreProvider({
<WSProvider
wsUrl={wsUrl}
authStore={authStore}
- workspaceStore={workspaceStore}
storage={storage}
cookieAuth={cookieAuth}
>
diff --git a/packages/core/platform/index.ts b/packages/core/platform/index.ts
index 1e59186aee..5955c1055c 100644
--- a/packages/core/platform/index.ts
+++ b/packages/core/platform/index.ts
@@ -3,5 +3,5 @@ export type { CoreProviderProps } from "./types";
export { AuthInitializer } from "./auth-initializer";
export { defaultStorage } from "./storage";
export { createPersistStorage } from "./persist-storage";
-export { createWorkspaceAwareStorage, setCurrentWorkspaceId, getCurrentWorkspaceId, registerForWorkspaceRehydration, rehydrateAllWorkspaceStores } from "./workspace-storage";
+export { createWorkspaceAwareStorage, setCurrentWorkspace, getCurrentSlug, getCurrentWsId, subscribeToCurrentSlug, registerForWorkspaceRehydration, rehydrateAllWorkspaceStores } from "./workspace-storage";
export { clearWorkspaceStorage } from "./storage-cleanup";
diff --git a/packages/core/platform/storage-cleanup.test.ts b/packages/core/platform/storage-cleanup.test.ts
index 5bfbfc9256..a5905b0700 100644
--- a/packages/core/platform/storage-cleanup.test.ts
+++ b/packages/core/platform/storage-cleanup.test.ts
@@ -19,6 +19,7 @@ describe("clearWorkspaceStorage", () => {
expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:activeSessionId:ws_123");
expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:drafts:ws_123");
expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:expanded:ws_123");
- expect(adapter.removeItem).toHaveBeenCalledTimes(8);
+ expect(adapter.removeItem).toHaveBeenCalledWith("multica_navigation:ws_123");
+ expect(adapter.removeItem).toHaveBeenCalledTimes(9);
});
});
diff --git a/packages/core/platform/storage-cleanup.ts b/packages/core/platform/storage-cleanup.ts
index fa4e877002..eb9a58bb65 100644
--- a/packages/core/platform/storage-cleanup.ts
+++ b/packages/core/platform/storage-cleanup.ts
@@ -1,7 +1,7 @@
import type { StorageAdapter } from "../types/storage";
/**
- * Keys that are namespaced per workspace (stored as `${key}:${wsId}`).
+ * Keys that are namespaced per workspace (stored as `${key}:${slug}`).
*
* IMPORTANT: When adding a new workspace-scoped persist store or storage key,
* add its key here so that workspace deletion and logout properly clean it up.
@@ -16,14 +16,15 @@ const WORKSPACE_SCOPED_KEYS = [
"multica:chat:activeSessionId",
"multica:chat:drafts",
"multica:chat:expanded",
+ "multica_navigation",
];
-/** Remove all workspace-scoped storage entries for the given workspace. */
+/** Remove all workspace-scoped storage entries for the given workspace slug. */
export function clearWorkspaceStorage(
adapter: StorageAdapter,
- wsId: string,
+ slug: string,
) {
for (const key of WORKSPACE_SCOPED_KEYS) {
- adapter.removeItem(`${key}:${wsId}`);
+ adapter.removeItem(`${key}:${slug}`);
}
}
diff --git a/packages/core/platform/workspace-storage.test.ts b/packages/core/platform/workspace-storage.test.ts
index cf396ea1c1..6b7e763afc 100644
--- a/packages/core/platform/workspace-storage.test.ts
+++ b/packages/core/platform/workspace-storage.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from "vitest";
-import { createWorkspaceAwareStorage, setCurrentWorkspaceId } from "./workspace-storage";
+import { createWorkspaceAwareStorage, setCurrentWorkspace } from "./workspace-storage";
import type { StorageAdapter } from "../types/storage";
function mockAdapter(): StorageAdapter {
@@ -12,50 +12,50 @@ function mockAdapter(): StorageAdapter {
}
afterEach(() => {
- setCurrentWorkspaceId(null);
+ setCurrentWorkspace(null, null);
});
describe("workspace-aware storage", () => {
it("uses plain key when no workspace is set", () => {
const adapter = mockAdapter();
- setCurrentWorkspaceId(null);
+ setCurrentWorkspace(null, null);
const storage = createWorkspaceAwareStorage(adapter);
storage.setItem("draft", "data");
expect(adapter.setItem).toHaveBeenCalledWith("draft", "data");
});
- it("namespaces key when workspace is set", () => {
+ it("namespaces key with slug when workspace is set", () => {
const adapter = mockAdapter();
- setCurrentWorkspaceId("ws_abc");
+ setCurrentWorkspace("acme", "ws_abc");
const storage = createWorkspaceAwareStorage(adapter);
storage.setItem("draft", "data");
- expect(adapter.setItem).toHaveBeenCalledWith("draft:ws_abc", "data");
+ expect(adapter.setItem).toHaveBeenCalledWith("draft:acme", "data");
storage.getItem("draft");
- expect(adapter.getItem).toHaveBeenCalledWith("draft:ws_abc");
+ expect(adapter.getItem).toHaveBeenCalledWith("draft:acme");
});
it("follows workspace changes dynamically", () => {
const adapter = mockAdapter();
const storage = createWorkspaceAwareStorage(adapter);
- setCurrentWorkspaceId("ws_1");
+ setCurrentWorkspace("team-a", "ws_1");
storage.setItem("draft", "v1");
- expect(adapter.setItem).toHaveBeenCalledWith("draft:ws_1", "v1");
+ expect(adapter.setItem).toHaveBeenCalledWith("draft:team-a", "v1");
- setCurrentWorkspaceId("ws_2");
+ setCurrentWorkspace("team-b", "ws_2");
storage.setItem("draft", "v2");
- expect(adapter.setItem).toHaveBeenCalledWith("draft:ws_2", "v2");
+ expect(adapter.setItem).toHaveBeenCalledWith("draft:team-b", "v2");
});
- it("removeItem uses current workspace", () => {
+ it("removeItem uses current workspace slug", () => {
const adapter = mockAdapter();
- setCurrentWorkspaceId("ws_x");
+ setCurrentWorkspace("dev", "ws_x");
const storage = createWorkspaceAwareStorage(adapter);
storage.removeItem("draft");
- expect(adapter.removeItem).toHaveBeenCalledWith("draft:ws_x");
+ expect(adapter.removeItem).toHaveBeenCalledWith("draft:dev");
});
});
diff --git a/packages/core/platform/workspace-storage.ts b/packages/core/platform/workspace-storage.ts
index c148bb499e..74ea1640d2 100644
--- a/packages/core/platform/workspace-storage.ts
+++ b/packages/core/platform/workspace-storage.ts
@@ -1,11 +1,69 @@
import type { StateStorage } from "zustand/middleware";
import type { StorageAdapter } from "../types/storage";
+// Paired module vars — always set/cleared together by the workspace layout.
+// _currentSlug is the primary identifier (matches the URL segment).
+// _currentWsId is derived (from the React Query workspace list) and used for
+// query keys and path-embedded API calls where UUID is required.
+let _currentSlug: string | null = null;
let _currentWsId: string | null = null;
+
const _rehydrateFns: Array<() => void> = [];
+const _slugSubscribers = new Set<(slug: string | null) => void>();
+let _pendingNotify = false;
+let _pendingRehydrate = false;
-export function setCurrentWorkspaceId(wsId: string | null) {
+/**
+ * Set both the current workspace slug and UUID at once.
+ * Called by the workspace layout's render-phase ref guard.
+ * Notifies slug subscribers (e.g. WSProvider via useSyncExternalStore).
+ */
+export function setCurrentWorkspace(slug: string | null, wsId: string | null) {
+ const slugChanged = _currentSlug !== slug;
+ _currentSlug = slug;
_currentWsId = wsId;
+ if (slugChanged && !_pendingNotify) {
+ _pendingNotify = true;
+ // Defer and deduplicate subscriber notifications:
+ // 1. Defer: avoids "cannot update component B while rendering A"
+ // (React 19 render-phase restriction).
+ // 2. Deduplicate: rapid A→B switches only notify once with the
+ // final slug, avoiding a wasted WS connect+disconnect cycle.
+ // The module vars are already updated synchronously above, so
+ // authHeaders() and getCurrentSlug() return the correct value
+ // immediately — subscribers are only for async consumers like
+ // WSProvider that need to reconnect the WebSocket.
+ queueMicrotask(() => {
+ _pendingNotify = false;
+ const current = _currentSlug;
+ for (const fn of _slugSubscribers) {
+ fn(current);
+ }
+ });
+ }
+}
+
+/** Current workspace slug (from URL). */
+export function getCurrentSlug(): string | null {
+ return _currentSlug;
+}
+
+/** Current workspace UUID (derived from slug + workspace list cache). */
+export function getCurrentWsId(): string | null {
+ return _currentWsId;
+}
+
+/**
+ * Subscribe to changes of the current workspace slug. Returns an unsubscribe
+ * function. Designed for React's `useSyncExternalStore` (WSProvider reconnect).
+ */
+export function subscribeToCurrentSlug(
+ fn: (slug: string | null) => void,
+): () => void {
+ _slugSubscribers.add(fn);
+ return () => {
+ _slugSubscribers.delete(fn);
+ };
}
/** Register a persist store's rehydrate function to be called on workspace switch. */
@@ -13,24 +71,34 @@ export function registerForWorkspaceRehydration(fn: () => void) {
_rehydrateFns.push(fn);
}
-/** Rehydrate all registered workspace-scoped persist stores from the new namespace. */
+/**
+ * Rehydrate all registered workspace-scoped persist stores from the new
+ * namespace. Deferred to a microtask + deduplicated for the same reason
+ * as slug subscriber notification: Zustand persist rehydrate synchronously
+ * setState()s the store, which schedules updates on any component
+ * subscribed to that store. Calling this from a component's render phase
+ * would violate React 19's "no cross-component updates during render"
+ * rule. Persist stores can tolerate one microtask of staleness — they're
+ * UI preferences, not security-critical state.
+ */
export function rehydrateAllWorkspaceStores() {
- for (const fn of _rehydrateFns) {
- fn();
- }
-}
-
-export function getCurrentWorkspaceId(): string | null {
- return _currentWsId;
+ if (_pendingRehydrate) return;
+ _pendingRehydrate = true;
+ queueMicrotask(() => {
+ _pendingRehydrate = false;
+ for (const fn of _rehydrateFns) {
+ fn();
+ }
+ });
}
/**
- * Storage that automatically namespaces keys with the current workspace ID.
- * Reads _currentWsId at call time, so it follows workspace switches dynamically.
+ * Storage that automatically namespaces keys with the current workspace slug.
+ * Reads _currentSlug at call time, so it follows workspace switches dynamically.
*/
export function createWorkspaceAwareStorage(adapter: StorageAdapter): StateStorage {
const resolve = (key: string) =>
- _currentWsId ? `${key}:${_currentWsId}` : key;
+ _currentSlug ? `${key}:${_currentSlug}` : key;
return {
getItem: (key) => adapter.getItem(resolve(key)),
diff --git a/packages/core/realtime/provider.tsx b/packages/core/realtime/provider.tsx
index 872f7a1b9b..4547532a21 100644
--- a/packages/core/realtime/provider.tsx
+++ b/packages/core/realtime/provider.tsx
@@ -6,13 +6,17 @@ import {
useEffect,
useState,
useCallback,
+ useSyncExternalStore,
type ReactNode,
} from "react";
import { WSClient } from "../api/ws-client";
import type { WSEventType, StorageAdapter } from "../types";
import type { StoreApi, UseBoundStore } from "zustand";
import type { AuthState } from "../auth/store";
-import type { WorkspaceStore } from "../workspace/store";
+import {
+ getCurrentSlug,
+ subscribeToCurrentSlug,
+} from "../platform/workspace-storage";
import { createLogger } from "../logger";
import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
@@ -31,8 +35,6 @@ export interface WSProviderProps {
wsUrl: string;
/** Platform-created auth store instance */
authStore: UseBoundStore<StoreApi<AuthState>>;
- /** Platform-created workspace store instance */
- workspaceStore: UseBoundStore<StoreApi<WorkspaceStore>>;
/** Platform-specific storage adapter for reading auth tokens */
storage: StorageAdapter;
/** When true, use HttpOnly cookies instead of token query param for WS auth. */
@@ -45,17 +47,25 @@ export function WSProvider({
children,
wsUrl,
authStore,
- workspaceStore,
storage,
cookieAuth,
onToast,
}: WSProviderProps) {
const user = authStore((s) => s.user);
- const workspace = workspaceStore((s) => s.workspace);
+ // Reactive read of the current workspace slug (URL-driven singleton in
+ // packages/core/platform/workspace-storage.ts). When the workspace switches,
+ // the useEffect below tears down the old WS connection and opens a new one
+ // bound to the new workspace slug. SSR snapshot is `null` because this
+ // provider only renders client-side under CoreProvider.
+ const wsSlug = useSyncExternalStore(
+ subscribeToCurrentSlug,
+ getCurrentSlug,
+ () => null,
+ );
const [wsClient, setWsClient] = useState<WSClient | null>(null);
useEffect(() => {
- if (!user || !workspace) return;
+ if (!user || !wsSlug) return;
// In token mode we need a token from storage; in cookie mode the HttpOnly
// cookie is sent automatically with the WS upgrade request.
@@ -66,7 +76,7 @@ export function WSProvider({
logger: createLogger("ws"),
cookieAuth,
});
- ws.setAuth(token, workspace.id);
+ ws.setAuth(token, wsSlug);
setWsClient(ws);
ws.connect();
@@ -74,9 +84,9 @@ export function WSProvider({
ws.disconnect();
setWsClient(null);
};
- }, [user, workspace, wsUrl, storage, cookieAuth]);
+ }, [user, wsSlug, wsUrl, storage, cookieAuth]);
- const stores: RealtimeSyncStores = { authStore, workspaceStore };
+ const stores: RealtimeSyncStores = { authStore };
// Centralized WS -> store sync (uses state so it re-subscribes when WS changes)
useRealtimeSync(wsClient, stores, onToast);
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index f6d3babc52..5cf39d4057 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -5,10 +5,10 @@ import { useQueryClient } from "@tanstack/react-query";
import type { WSClient } from "../api/ws-client";
import type { StoreApi, UseBoundStore } from "zustand";
import type { AuthState } from "../auth/store";
-import type { WorkspaceStore } from "../workspace/store";
import { createLogger } from "../logger";
import { clearWorkspaceStorage } from "../platform/storage-cleanup";
import { defaultStorage } from "../platform/storage";
+import { getCurrentWsId, getCurrentSlug } from "../platform/workspace-storage";
import { issueKeys } from "../issues/queries";
import { projectKeys } from "../projects/queries";
import { pinKeys } from "../pins/queries";
@@ -23,6 +23,7 @@ import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged } from "../inb
import { inboxKeys } from "../inbox/queries";
import { workspaceKeys, workspaceListOptions } from "../workspace/queries";
import { chatKeys } from "../chat/queries";
+import { paths } from "../paths";
import type {
MemberAddedPayload,
WorkspaceDeletedPayload,
@@ -54,7 +55,6 @@ const logger = createLogger("realtime-sync");
export interface RealtimeSyncStores {
authStore: UseBoundStore<StoreApi<AuthState>>;
- workspaceStore: UseBoundStore<StoreApi<WorkspaceStore>>;
}
/**
@@ -79,7 +79,7 @@ export function useRealtimeSync(
stores: RealtimeSyncStores,
onToast?: (message: string, type?: "info" | "error") => void,
) {
- const { authStore, workspaceStore } = stores;
+ const { authStore } = stores;
const qc = useQueryClient();
// Main sync: onAny -> refreshMap with debounce
useEffect(() => {
@@ -87,39 +87,39 @@ export function useRealtimeSync(
const refreshMap: Record<string, () => void> = {
inbox: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) onInboxInvalidate(qc, wsId);
},
agent: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
},
member: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });
},
workspace: () => {
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
},
skill: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });
},
project: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
},
pin: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
const userId = authStore.getState().user?.id;
if (wsId && userId) qc.invalidateQueries({ queryKey: pinKeys.all(wsId, userId) });
},
daemon: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
},
autopilot: () => {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });
},
};
@@ -166,7 +166,7 @@ export function useRealtimeSync(
const unsubIssueUpdated = ws.on("issue:updated", (p) => {
const { issue } = p as IssueUpdatedPayload;
if (!issue?.id) return;
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) {
onIssueUpdated(qc, wsId, issue);
if (issue.status) {
@@ -178,21 +178,21 @@ export function useRealtimeSync(
const unsubIssueCreated = ws.on("issue:created", (p) => {
const { issue } = p as IssueCreatedPayload;
if (!issue) return;
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) onIssueCreated(qc, wsId, issue);
});
const unsubIssueDeleted = ws.on("issue:deleted", (p) => {
const { issue_id } = p as IssueDeletedPayload;
if (!issue_id) return;
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) onIssueDeleted(qc, wsId, issue_id);
});
const unsubInboxNew = ws.on("inbox:new", (p) => {
const { item } = p as InboxNewPayload;
if (!item) return;
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) onInboxNew(qc, wsId, item);
});
@@ -260,16 +260,34 @@ export function useRealtimeSync(
// --- Side-effect handlers (toast, navigation) ---
+ // After the current workspace disappears (deleted or we were kicked out),
+ // navigate to another workspace the user still has access to, or to
+ // onboarding. We use a full-page navigation: this reliably tears down any
+ // in-flight queries / subscriptions tied to the dead workspace without
+ // relying on framework-specific routers from here in core.
+ const relocateAfterWorkspaceLoss = async (lostWsId: string) => {
+ const wsList = await qc.fetchQuery({
+ ...workspaceListOptions(),
+ staleTime: 0,
+ });
+ const next = wsList.find((w) => w.id !== lostWsId);
+ const target = next ? paths.workspace(next.slug).issues() : paths.onboarding();
+ if (typeof window !== "undefined") {
+ window.location.assign(target);
+ }
+ };
+
const unsubWsDeleted = ws.on("workspace:deleted", (p) => {
const { workspace_id } = p as WorkspaceDeletedPayload;
- clearWorkspaceStorage(defaultStorage, workspace_id);
- const currentWs = workspaceStore.getState().workspace;
- if (currentWs?.id === workspace_id) {
+ // Event payload has UUID; look up slug from cached workspace list
+ // since clearWorkspaceStorage keys are namespaced by slug.
+ const wsList = qc.getQueryData<{ id: string; slug: string }[]>(workspaceKeys.list()) ?? [];
+ const deletedSlug = wsList.find((w) => w.id === workspace_id)?.slug;
+ if (deletedSlug) clearWorkspaceStorage(defaultStorage, deletedSlug);
+ if (getCurrentWsId() === workspace_id) {
logger.warn("current workspace deleted, switching");
onToast?.("This workspace was deleted", "info");
- qc.fetchQuery({ ...workspaceListOptions(), staleTime: 0 }).then((wsList) => {
- workspaceStore.getState().hydrateWorkspace(wsList);
- });
+ relocateAfterWorkspaceLoss(workspace_id);
}
});
@@ -277,13 +295,14 @@ export function useRealtimeSync(
const { user_id } = p as MemberRemovedPayload;
const myUserId = authStore.getState().user?.id;
if (user_id === myUserId) {
- const wsId = workspaceStore.getState().workspace?.id;
- if (wsId) clearWorkspaceStorage(defaultStorage, wsId);
- logger.warn("removed from workspace, switching");
- onToast?.("You were removed from this workspace", "info");
- qc.fetchQuery({ ...workspaceListOptions(), staleTime: 0 }).then((wsList) => {
- workspaceStore.getState().hydrateWorkspace(wsList);
- });
+ const slug = getCurrentSlug();
+ const wsId = getCurrentWsId();
+ if (slug && wsId) {
+ clearWorkspaceStorage(defaultStorage, slug);
+ logger.warn("removed from workspace, switching");
+ onToast?.("You were removed from this workspace", "info");
+ relocateAfterWorkspaceLoss(wsId);
+ }
}
});
@@ -312,14 +331,14 @@ export function useRealtimeSync(
// invitation:accepted / declined / revoked — refresh invitation lists
const unsubInvitationAccepted = ws.on("invitation:accepted", () => {
- const currentWsId = workspaceStore.getState().workspace?.id;
+ const currentWsId = getCurrentWsId();
if (currentWsId) {
qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
qc.invalidateQueries({ queryKey: workspaceKeys.members(currentWsId) });
}
});
const unsubInvitationDeclined = ws.on("invitation:declined", () => {
- const currentWsId = workspaceStore.getState().workspace?.id;
+ const currentWsId = getCurrentWsId();
if (currentWsId) {
qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
}
@@ -357,11 +376,11 @@ export function useRealtimeSync(
// Helpers reused by chat lifecycle handlers.
const invalidatePendingAggregate = () => {
- const id = workspaceStore.getState().workspace?.id;
+ const id = getCurrentWsId();
if (id) qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(id) });
};
const invalidateSessionLists = () => {
- const id = workspaceStore.getState().workspace?.id;
+ const id = getCurrentWsId();
if (id) {
qc.invalidateQueries({ queryKey: chatKeys.sessions(id) });
qc.invalidateQueries({ queryKey: chatKeys.allSessions(id) });
@@ -457,7 +476,7 @@ export function useRealtimeSync(
timers.forEach(clearTimeout);
timers.clear();
};
- }, [ws, qc, authStore, workspaceStore, onToast]);
+ }, [ws, qc, authStore, onToast]);
// Reconnect -> refetch all data to recover missed events
useEffect(() => {
@@ -466,7 +485,7 @@ export function useRealtimeSync(
const unsub = ws.onReconnect(async () => {
logger.info("reconnected, refetching all data");
try {
- const wsId = workspaceStore.getState().workspace?.id;
+ const wsId = getCurrentWsId();
if (wsId) {
qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
@@ -484,5 +503,5 @@ export function useRealtimeSync(
});
return unsub;
- }, [ws, qc, workspaceStore]);
+ }, [ws, qc]);
}
diff --git a/packages/core/workspace/index.ts b/packages/core/workspace/index.ts
index b02f220565..4e9f5df488 100644
--- a/packages/core/workspace/index.ts
+++ b/packages/core/workspace/index.ts
@@ -1,41 +1,3 @@
-export * from "./store";
export * from "./queries";
export * from "./mutations";
export * from "./hooks";
-
-import type { createWorkspaceStore as CreateWorkspaceStoreFn } from "./store";
-
-type WorkspaceStoreInstance = ReturnType<typeof CreateWorkspaceStoreFn>;
-
-/** Module-level singleton — set once at app boot via `registerWorkspaceStore()`. */
-let _store: WorkspaceStoreInstance | null = null;
-
-/**
- * Register the workspace store instance created by the app.
- * Must be called at boot before any component renders.
- */
-export function registerWorkspaceStore(store: WorkspaceStoreInstance) {
- _store = store;
-}
-
-/**
- * Singleton accessor — a Zustand hook backed by the registered instance.
- * Supports `useWorkspaceStore(selector)` and `useWorkspaceStore.getState()`.
- */
-export const useWorkspaceStore: WorkspaceStoreInstance = new Proxy(
- (() => {}) as unknown as WorkspaceStoreInstance,
- {
- apply(_target, _thisArg, args) {
- if (!_store)
- throw new Error(
- "Workspace store not initialised — call registerWorkspaceStore() first",
- );
- return (_store as unknown as (...a: unknown[]) => unknown)(...args);
- },
- get(_target, prop) {
- // Allow property inspection (HMR/React Refresh) before registration
- if (!_store) return undefined;
- return Reflect.get(_store, prop);
- },
- },
-);
diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.ts
index b4b80fdbd6..f23bb7f964 100644
--- a/packages/core/workspace/mutations.ts
+++ b/packages/core/workspace/mutations.ts
@@ -1,18 +1,23 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Workspace } from "../types";
import { api } from "../api";
-import { workspaceKeys, workspaceListOptions } from "./queries";
-import { useWorkspaceStore } from "./index";
+import { workspaceKeys } from "./queries";
export function useCreateWorkspace() {
const qc = useQueryClient();
return useMutation({
mutationFn: (data: { name: string; slug: string; description?: string }) =>
api.createWorkspace(data),
+ // Seed the workspace list cache BEFORE callers navigate to /{newWs.slug}/issues.
+ // The destination [workspaceSlug]/layout queries by slug from this cache;
+ // without seeding, it would briefly show "loading" before the background
+ // invalidation completes. TanStack Query guarantees this onSuccess runs
+ // before mutateAsync's resolver / before any callback-style onSuccess
+ // passed to mutate(), so any caller that navigates after the mutation
+ // resolves will see the seeded data synchronously. Switching workspaces
+ // is pure navigation now — no imperative store writes needed.
onSuccess: (newWs) => {
- // Add to cache before switching so sidebar list is consistent on first render
qc.setQueryData(workspaceKeys.list(), (old: Workspace[] = []) => [...old, newWs]);
- useWorkspaceStore.getState().switchWorkspace(newWs);
},
onSettled: () => {
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
@@ -24,14 +29,6 @@ export function useLeaveWorkspace() {
const qc = useQueryClient();
return useMutation({
mutationFn: (workspaceId: string) => api.leaveWorkspace(workspaceId),
- onSuccess: async (_, workspaceId) => {
- const currentWsId = useWorkspaceStore.getState().workspace?.id;
- if (currentWsId === workspaceId) {
- // staleTime: 0 forces a real network fetch — cache still has the left workspace
- const wsList = await qc.fetchQuery({ ...workspaceListOptions(), staleTime: 0 });
- useWorkspaceStore.getState().hydrateWorkspace(wsList);
- }
- },
onSettled: () => {
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
},
@@ -42,14 +39,6 @@ export function useDeleteWorkspace() {
const qc = useQueryClient();
return useMutation({
mutationFn: (workspaceId: string) => api.deleteWorkspace(workspaceId),
- onSuccess: async (_, workspaceId) => {
- const currentWsId = useWorkspaceStore.getState().workspace?.id;
- if (currentWsId === workspaceId) {
- // staleTime: 0 forces a real network fetch — cache still has the deleted workspace
- const wsList = await qc.fetchQuery({ ...workspaceListOptions(), staleTime: 0 });
- useWorkspaceStore.getState().hydrateWorkspace(wsList);
- }
- },
onSettled: () => {
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
},
diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.ts
index 1a0c03329e..54cf948239 100644
--- a/packages/core/workspace/queries.ts
+++ b/packages/core/workspace/queries.ts
@@ -1,5 +1,6 @@
import { queryOptions } from "@tanstack/react-query";
import { api } from "../api";
+import type { Workspace } from "../types";
export const workspaceKeys = {
all: (wsId: string) => ["workspaces", wsId] as const,
@@ -19,6 +20,14 @@ export function workspaceListOptions() {
});
}
+/** Resolves the workspace whose slug matches, from the cached workspace list. */
+export function workspaceBySlugOptions(slug: string) {
+ return queryOptions({
+ ...workspaceListOptions(),
+ select: (list: Workspace[]) => list.find((w) => w.slug === slug) ?? null,
+ });
+}
+
export function memberListOptions(wsId: string) {
return queryOptions({
queryKey: workspaceKeys.members(wsId),
diff --git a/packages/core/workspace/store.ts b/packages/core/workspace/store.ts
deleted file mode 100644
index b001d01762..0000000000
--- a/packages/core/workspace/store.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { create } from "zustand";
-import type { Workspace, StorageAdapter } from "../types";
-import type { ApiClient } from "../api/client";
-import { createLogger } from "../logger";
-import { setCurrentWorkspaceId, rehydrateAllWorkspaceStores } from "../platform/workspace-storage";
-
-const logger = createLogger("workspace-store");
-
-interface WorkspaceStoreOptions {
- storage?: StorageAdapter;
-}
-
-interface WorkspaceState {
- workspace: Workspace | null;
-}
-
-interface WorkspaceActions {
- /**
- * Pick a workspace from a list and set it as current.
- * The list itself is NOT stored here — it lives in React Query.
- */
- hydrateWorkspace: (
- wsList: Workspace[],
- preferredWorkspaceId?: string | null,
- ) => Workspace | null;
- /** Switch to a workspace. Caller provides the full object (from React Query). */
- switchWorkspace: (ws: Workspace) => void;
- /** Update current workspace data in place (e.g. after rename). */
- updateWorkspace: (ws: Workspace) => void;
- clearWorkspace: () => void;
-}
-
-export type WorkspaceStore = WorkspaceState & WorkspaceActions;
-
-export function createWorkspaceStore(api: ApiClient, options?: WorkspaceStoreOptions) {
- const storage = options?.storage;
-
- return create<WorkspaceStore>((set) => ({
- // Only the currently selected workspace (UI state).
- // The workspace list is server state and lives in React Query.
- workspace: null,
-
- hydrateWorkspace: (wsList, preferredWorkspaceId) => {
- const nextWorkspace =
- (preferredWorkspaceId
- ? wsList.find((item) => item.id === preferredWorkspaceId)
- : null) ??
- wsList[0] ??
- null;
-
- if (!nextWorkspace) {
- api.setWorkspaceId(null);
- setCurrentWorkspaceId(null);
- rehydrateAllWorkspaceStores();
- storage?.removeItem("multica_workspace_id");
- set({ workspace: null });
- return null;
- }
-
- api.setWorkspaceId(nextWorkspace.id);
- setCurrentWorkspaceId(nextWorkspace.id);
- rehydrateAllWorkspaceStores();
- storage?.setItem("multica_workspace_id", nextWorkspace.id);
- set({ workspace: nextWorkspace });
- logger.debug("hydrate workspace", nextWorkspace.name, nextWorkspace.id);
-
- return nextWorkspace;
- },
-
- switchWorkspace: (ws) => {
- logger.info("switching to", ws.id);
- api.setWorkspaceId(ws.id);
- setCurrentWorkspaceId(ws.id);
- rehydrateAllWorkspaceStores();
- storage?.setItem("multica_workspace_id", ws.id);
- set({ workspace: ws });
- },
-
- updateWorkspace: (ws) => {
- set((state) => ({
- workspace: state.workspace?.id === ws.id ? ws : state.workspace,
- }));
- },
-
- clearWorkspace: () => {
- api.setWorkspaceId(null);
- setCurrentWorkspaceId(null);
- rehydrateAllWorkspaceStores();
- set({ workspace: null });
- },
- }));
-}
diff --git a/packages/views/auth/login-page.test.tsx b/packages/views/auth/login-page.test.tsx
index 7da2038eaf..8e1bf64d5c 100644
--- a/packages/views/auth/login-page.test.tsx
+++ b/packages/views/auth/login-page.test.tsx
@@ -8,7 +8,6 @@ import userEvent from "@testing-library/user-event";
const mockSendCode = vi.hoisted(() => vi.fn());
const mockVerifyCode = vi.hoisted(() => vi.fn());
-const mockHydrateWorkspace = vi.hoisted(() => vi.fn());
const mockApiListWorkspaces = vi.hoisted(() => vi.fn());
const mockApiVerifyCode = vi.hoisted(() => vi.fn());
const mockApiSetToken = vi.hoisted(() => vi.fn());
@@ -39,20 +38,6 @@ vi.mock("@multica/core/auth", () => ({
),
}));
-vi.mock("@multica/core/workspace", () => ({
- useWorkspaceStore: Object.assign(
- (selector?: (s: unknown) => unknown) => {
- const state = { hydrateWorkspace: mockHydrateWorkspace };
- return selector ? selector(state) : state;
- },
- {
- getState: () => ({
- hydrateWorkspace: mockHydrateWorkspace,
- }),
- },
- ),
-}));
-
vi.mock("@multica/core/api", () => ({
api: {
listWorkspaces: mockApiListWorkspaces,
@@ -224,11 +209,10 @@ describe("LoginPage", () => {
// Code verification
// -------------------------------------------------------------------------
- it("calls verifyCode, listWorkspaces, hydrateWorkspace, then onSuccess", async () => {
+ it("calls verifyCode, seeds workspace list cache, then onSuccess", async () => {
mockSendCode.mockResolvedValueOnce(undefined);
mockVerifyCode.mockResolvedValueOnce(undefined);
mockApiListWorkspaces.mockResolvedValueOnce([{ id: "ws-1" }]);
- mockHydrateWorkspace.mockReturnValueOnce({ id: "ws-1" });
render(<LoginPage onSuccess={onSuccess} />);
@@ -253,9 +237,11 @@ describe("LoginPage", () => {
"123456",
);
expect(mockApiListWorkspaces).toHaveBeenCalled();
- expect(mockHydrateWorkspace).toHaveBeenCalledWith(
+ // The workspace list is seeded into React Query so onSuccess can read
+ // it synchronously to compute a destination URL.
+ expect(mockSetQueryData).toHaveBeenCalledWith(
+ expect.arrayContaining(["workspaces", "list"]),
[{ id: "ws-1" }],
- undefined,
);
expect(onSuccess).toHaveBeenCalled();
});
@@ -620,7 +606,6 @@ describe("LoginPage", () => {
mockSendCode.mockResolvedValueOnce(undefined);
mockVerifyCode.mockResolvedValueOnce(undefined);
mockApiListWorkspaces.mockResolvedValueOnce([{ id: "ws-1" }]);
- mockHydrateWorkspace.mockReturnValueOnce({ id: "ws-1" });
const onTokenObtained = vi.fn();
render(
@@ -674,43 +659,6 @@ describe("LoginPage", () => {
).toBeInTheDocument();
});
- // -------------------------------------------------------------------------
- // lastWorkspaceId
- // -------------------------------------------------------------------------
-
- it("passes lastWorkspaceId to hydrateWorkspace", async () => {
- mockSendCode.mockResolvedValueOnce(undefined);
- mockVerifyCode.mockResolvedValueOnce(undefined);
- mockApiListWorkspaces.mockResolvedValueOnce([
- { id: "ws-1" },
- { id: "ws-2" },
- ]);
- mockHydrateWorkspace.mockReturnValueOnce({ id: "ws-2" });
-
- render(
- <LoginPage onSuccess={onSuccess} lastWorkspaceId="ws-2" />,
- );
-
- const user = userEvent.setup();
- await user.type(screen.getByLabelText(/email/i), "[email protected]");
- await user.click(screen.getByRole("button", { name: /continue/i }));
-
- await waitFor(() => {
- expect(
- screen.getByText(/check your email/i),
- ).toBeInTheDocument();
- });
-
- const otpInput = getOTPInput();
- await user.type(otpInput, "123456");
-
- await waitFor(() => {
- expect(mockHydrateWorkspace).toHaveBeenCalledWith(
- [{ id: "ws-1" }, { id: "ws-2" }],
- "ws-2",
- );
- });
- });
});
// ---------------------------------------------------------------------------
diff --git a/packages/views/auth/login-page.tsx b/packages/views/auth/login-page.tsx
index 862aee60ad..c25c71114b 100644
--- a/packages/views/auth/login-page.tsx
+++ b/packages/views/auth/login-page.tsx
@@ -19,7 +19,6 @@ import {
InputOTPSlot,
} from "@multica/ui/components/ui/input-otp";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
import { workspaceKeys } from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
import type { User } from "@multica/core/types";
@@ -45,14 +44,13 @@ interface CliCallbackConfig {
interface LoginPageProps {
/** Logo element rendered above the title */
logo?: ReactNode;
- /** Called after successful login + workspace hydration */
+ /** Called after successful login. The workspace list is seeded into React
+ * Query before this fires, so the caller can compute a destination URL. */
onSuccess: () => void;
/** Google OAuth config. Omit to disable Google login. */
google?: GoogleAuthConfig;
/** CLI callback config for authorizing CLI tools. */
cliCallback?: CliCallbackConfig;
- /** Preferred workspace ID to restore after login. */
- lastWorkspaceId?: string | null;
/** Called after a token is obtained (e.g. to set cookies). */
onTokenObtained?: () => void;
/** Override Google login handler (e.g. desktop opens browser externally). When provided, renders the Google button even if `google` config is omitted. */
@@ -98,7 +96,6 @@ export function LoginPage({
onSuccess,
google,
cliCallback,
- lastWorkspaceId,
onTokenObtained,
onGoogleLogin,
}: LoginPageProps) {
@@ -200,11 +197,12 @@ export function LoginPage({
return;
}
- // Normal path
+ // Normal path: seed the workspace list into the Query cache so the
+ // caller's onSuccess can read it synchronously to compute a destination
+ // URL (first workspace's slug, or onboarding).
await useAuthStore.getState().verifyCode(email, value);
const wsList = await api.listWorkspaces();
qc.setQueryData(workspaceKeys.list(), wsList);
- useWorkspaceStore.getState().hydrateWorkspace(wsList, lastWorkspaceId);
onTokenObtained?.();
onSuccess();
} catch (err) {
@@ -215,7 +213,7 @@ export function LoginPage({
setLoading(false);
}
},
- [email, onSuccess, cliCallback, lastWorkspaceId, onTokenObtained, qc],
+ [email, onSuccess, cliCallback, onTokenObtained, qc],
);
const handleResend = async () => {
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index 4cce1bc5a3..da1ec11649 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -13,6 +13,7 @@ import {
} from "@multica/core/autopilots/mutations";
import { agentListOptions } from "@multica/core/workspace/queries";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { useNavigation, AppLink } from "../../navigation";
import { PageHeader } from "../../layout/page-header";
@@ -58,6 +59,7 @@ const RUN_STATUS_CONFIG: Record<string, { label: string; color: string; icon: ty
};
function RunRow({ run }: { run: AutopilotRun }) {
+ const wsPaths = useWorkspacePaths();
const cfg = (RUN_STATUS_CONFIG[run.status] ?? RUN_STATUS_CONFIG["issue_created"])!;
const StatusIcon = cfg.icon;
@@ -68,7 +70,7 @@ function RunRow({ run }: { run: AutopilotRun }) {
<span className="w-16 shrink-0 text-xs text-muted-foreground capitalize">{run.source}</span>
<span className="flex-1 min-w-0 text-xs text-muted-foreground truncate">
{run.issue_id ? (
- <AppLink href={`/issues/${run.issue_id}`} className="hover:underline">
+ <AppLink href={wsPaths.issueDetail(run.issue_id)} className="hover:underline">
Issue linked
</AppLink>
) : run.failure_reason ? (
@@ -356,6 +358,7 @@ function AddTriggerDialog({
export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
const wsId = useWorkspaceId();
+ const wsPaths = useWorkspacePaths();
const router = useNavigation();
const { getActorName } = useActorName();
@@ -401,7 +404,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
try {
await deleteAutopilot.mutateAsync(autopilotId);
toast.success("Autopilot deleted");
- router.push("/autopilots");
+ router.push(wsPaths.autopilots());
} catch {
toast.error("Failed to delete autopilot");
}
@@ -417,7 +420,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
{/* Header */}
<PageHeader className="justify-between px-5">
<div className="flex items-center gap-2">
- <AppLink href="/autopilots" className="text-muted-foreground hover:text-foreground transition-colors">
+ <AppLink href={wsPaths.autopilots()} className="text-muted-foreground hover:text-foreground transition-colors">
<Zap className="h-4 w-4" />
</AppLink>
<span className="text-muted-foreground">/</span>
diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsx
index 71ae286df9..b6948726fc 100644
--- a/packages/views/autopilots/components/autopilots-page.tsx
+++ b/packages/views/autopilots/components/autopilots-page.tsx
@@ -7,6 +7,7 @@ import { autopilotListOptions } from "@multica/core/autopilots/queries";
import { useCreateAutopilot, useCreateAutopilotTrigger } from "@multica/core/autopilots/mutations";
import { agentListOptions } from "@multica/core/workspace/queries";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { AppLink } from "../../navigation";
import { ActorAvatar } from "../../common/actor-avatar";
@@ -144,13 +145,14 @@ const EXECUTION_MODE_LABELS: Record<string, string> = {
function AutopilotRow({ autopilot }: { autopilot: Autopilot }) {
const { getActorName } = useActorName();
+ const wsPaths = useWorkspacePaths();
const statusCfg = (STATUS_CONFIG[autopilot.status] ?? STATUS_CONFIG["active"])!;
const StatusIcon = statusCfg.icon;
return (
<div className="group/row flex h-11 items-center gap-2 px-5 text-sm transition-colors hover:bg-accent/40">
<AppLink
- href={`/autopilots/${autopilot.id}`}
+ href={wsPaths.autopilotDetail(autopilot.id)}
className="flex min-w-0 flex-1 items-center gap-2"
>
<Zap className="h-4 w-4 shrink-0 text-muted-foreground" />
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 80f5630aed..354b4405e0 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -35,6 +35,7 @@ import {
import { useEditor, EditorContent } from "@tiptap/react";
import { cn } from "@multica/ui/lib/utils";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
+import { useWorkspaceSlug } from "@multica/core/paths";
import { useQueryClient } from "@tanstack/react-query";
import { createEditorExtensions } from "./extensions";
import { uploadAndInsertFile } from "./extensions/file-upload";
@@ -114,6 +115,13 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const prevContentRef = useRef(defaultValue);
const lastEmittedRef = useRef<string | null>(null);
+ // Current workspace slug kept in a ref so the click handler always sees the
+ // latest value without recreating the editor. Used by openLink to prefix
+ // legacy /issues/... style paths that lack a workspace slug.
+ const workspaceSlug = useWorkspaceSlug();
+ const workspaceSlugRef = useRef(workspaceSlug);
+ workspaceSlugRef.current = workspaceSlug;
+
// Keep refs in sync without recreating editor
onUpdateRef.current = onUpdate;
onSubmitRef.current = onSubmit;
@@ -166,7 +174,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
if (!href || isMentionHref(href)) return false;
event.preventDefault();
- openLink(href);
+ openLink(href, workspaceSlugRef.current);
return true;
},
},
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 91c71314e6..9a3f857cce 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -11,7 +11,7 @@ import {
import { ReactRenderer } from "@tiptap/react";
import { computePosition, offset, flip, shift } from "@floating-ui/dom";
import type { QueryClient } from "@tanstack/react-query";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { getCurrentWsId } from "@multica/core/platform";
import { issueKeys } from "@multica/core/issues/queries";
import { workspaceKeys } from "@multica/core/workspace/queries";
import type { Issue, ListIssuesResponse, MemberWithUser, Agent } from "@multica/core/types";
@@ -219,7 +219,10 @@ export function createMentionSuggestion(qc: QueryClient): Omit<
> {
return {
items: ({ query }) => {
- const wsId = useWorkspaceStore.getState().workspace?.id;
+ // Read workspace id imperatively because this runs in TipTap factory scope
+ // (outside React render). getCurrentWsId() is the non-React
+ // singleton set by the URL-driven workspace layout.
+ const wsId = getCurrentWsId();
const members: MemberWithUser[] = wsId ? qc.getQueryData(workspaceKeys.members(wsId)) ?? [] : [];
const agents: Agent[] = wsId ? qc.getQueryData(workspaceKeys.agents(wsId)) ?? [] : [];
const issues: Issue[] = wsId
diff --git a/packages/views/editor/extensions/mention-view.tsx b/packages/views/editor/extensions/mention-view.tsx
index 6d7b7cc5d1..3335ca8170 100644
--- a/packages/views/editor/extensions/mention-view.tsx
+++ b/packages/views/editor/extensions/mention-view.tsx
@@ -23,6 +23,7 @@ import type { NodeViewProps } from "@tiptap/react";
import { useQuery } from "@tanstack/react-query";
import { issueListOptions, issueDetailOptions } from "@multica/core/issues/queries";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import { useNavigation } from "../../navigation";
import { StatusIcon } from "../../issues/components/status-icon";
@@ -52,6 +53,7 @@ function IssueMention({
fallbackLabel?: string;
}) {
const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
const { data: issues = [] } = useQuery(issueListOptions(wsId));
const { push, openInNewTab } = useNavigation();
const listIssue = issues.find((i) => i.id === issueId);
@@ -63,7 +65,7 @@ function IssueMention({
const issue = listIssue ?? detailIssue;
- const issuePath = `/issues/${issueId}`;
+ const issuePath = p.issueDetail(issueId);
const tabTitle = issue ? `${issue.identifier}: ${issue.title}` : undefined;
const handleClick = (e: React.MouseEvent) => {
e.preventDefault();
@@ -82,7 +84,7 @@ function IssueMention({
if (!issue) {
return (
- <a href={`/issues/${issueId}`} onClick={handleClick} className={cardClass}>
+ <a href={issuePath} onClick={handleClick} className={cardClass}>
<span className="font-medium text-muted-foreground">
{fallbackLabel ?? issueId.slice(0, 8)}
</span>
@@ -91,7 +93,7 @@ function IssueMention({
}
return (
- <a href={`/issues/${issueId}`} onClick={handleClick} className={cardClass}>
+ <a href={issuePath} onClick={handleClick} className={cardClass}>
<StatusIcon status={issue.status} className="h-3.5 w-3.5 shrink-0" />
<span className="font-medium text-muted-foreground shrink-0">{issue.identifier}</span>
<span className="text-foreground truncate">{issue.title}</span>
diff --git a/packages/views/editor/link-hover-card.tsx b/packages/views/editor/link-hover-card.tsx
index a9ad890b45..bd99e4570d 100644
--- a/packages/views/editor/link-hover-card.tsx
+++ b/packages/views/editor/link-hover-card.tsx
@@ -15,6 +15,7 @@ import { computePosition, offset, flip, shift } from "@floating-ui/dom";
import { ExternalLink, Copy } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@multica/ui/components/ui/button";
+import { useWorkspaceSlug } from "@multica/core/paths";
import { openLink, isMentionHref } from "./utils/link-handler";
function truncateUrl(url: string, max = 48): string {
@@ -133,6 +134,7 @@ function LinkHoverCard({
}) {
const [pos, setPos] = useState({ top: 0, left: 0 });
const [positioned, setPositioned] = useState(false);
+ const slug = useWorkspaceSlug();
// Position the card when the portal div is mounted (ref callback).
// Using useEffect would race with portal rendering — the div might
@@ -177,7 +179,7 @@ function LinkHoverCard({
const handleOpen = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
- openLink(href);
+ openLink(href, slug);
};
return createPortal(
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index 3d5bd7f771..2731d3e735 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -30,6 +30,7 @@ import { toHtml } from "hast-util-to-html";
import { Maximize2, Download, Link as LinkIcon, FileText } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
+import { useWorkspacePaths, useWorkspaceSlug } from "@multica/core/paths";
import { useNavigation } from "../navigation";
import { IssueMentionCard } from "../issues/components/issue-mention-card";
import { ImageLightbox } from "./extensions/image-view";
@@ -89,7 +90,8 @@ function urlTransform(url: string): string {
function IssueMentionLink({ issueId, label }: { issueId: string; label?: string }) {
const { push, openInNewTab } = useNavigation();
- const path = `/issues/${issueId}`;
+ const p = useWorkspacePaths();
+ const path = p.issueDetail(issueId);
return (
<span
className="inline align-middle"
@@ -110,39 +112,50 @@ function IssueMentionLink({ issueId, label }: { issueId: string; label?: string
);
}
-const components: Partial<Components> = {
- // Links — route mention:// to mention components, others show preview card
- a: ({ href, children }) => {
- if (isMentionHref(href)) {
- const match = href.match(
- /^mention:\/\/(member|agent|issue|all)\/(.+)$/,
- );
- if (match?.[1] === "issue" && match[2]) {
- const label =
- typeof children === "string"
- ? children
- : Array.isArray(children)
- ? children.join("")
- : undefined;
- return <IssueMentionLink issueId={match[2]} label={label} />;
- }
- // Member / agent / all mentions
- return <span className="mention">{children}</span>;
+// Named component so it can call useWorkspaceSlug() — arrow function inlined
+// inside `components` below would still work, but extracting it keeps the
+// hook usage explicit and avoids hook-in-object-literal surprises.
+function ReadonlyLink({
+ href,
+ children,
+}: {
+ href?: string;
+ children?: React.ReactNode;
+}) {
+ const slug = useWorkspaceSlug();
+
+ if (isMentionHref(href)) {
+ const match = href.match(/^mention:\/\/(member|agent|issue|all)\/(.+)$/);
+ if (match?.[1] === "issue" && match[2]) {
+ const label =
+ typeof children === "string"
+ ? children
+ : Array.isArray(children)
+ ? children.join("")
+ : undefined;
+ return <IssueMentionLink issueId={match[2]} label={label} />;
}
+ // Member / agent / all mentions
+ return <span className="mention">{children}</span>;
+ }
- // Regular links — open directly on click
- return (
- <a
- href={href}
- onClick={(e) => {
- e.preventDefault();
- if (href) openLink(href);
- }}
- >
- {children}
- </a>
- );
- },
+ // Regular links — open directly on click
+ return (
+ <a
+ href={href}
+ onClick={(e) => {
+ e.preventDefault();
+ if (href) openLink(href, slug);
+ }}
+ >
+ {children}
+ </a>
+ );
+}
+
+const components: Partial<Components> = {
+ // Links — route mention:// to mention components, others show preview card
+ a: ReadonlyLink,
// Images — centered with toolbar + lightbox (matches Tiptap ImageView NodeView)
img: function ReadonlyImage({ src, alt }) {
diff --git a/packages/views/editor/utils/link-handler.ts b/packages/views/editor/utils/link-handler.ts
index 6ffe465263..240aef9209 100644
--- a/packages/views/editor/utils/link-handler.ts
+++ b/packages/views/editor/utils/link-handler.ts
@@ -5,11 +5,54 @@
* (react-markdown link component), and link-hover-card (Open button).
*/
-/** Open a link — internal paths dispatch multica:navigate, external open new tab. */
-export function openLink(href: string): void {
+import { isGlobalPath } from "@multica/core/paths";
+
+/**
+ * Top-level workspace-scoped routes. Used to detect "/{route}/..." paths that
+ * were authored without a workspace slug — we prepend the current slug so they
+ * resolve correctly under the new /{slug}/{route}/... URL shape.
+ *
+ * Why a hardcoded allowlist: the heuristic must be conservative. A path like
+ * "/acme/issues/abc" already has a slug (first segment "acme" isn't a known
+ * route), so leaving it alone is correct. A path like "/foo/bar" where "foo"
+ * isn't a known route is ambiguous — we don't rewrite it, treating the author
+ * as intentional. Only "/issues/..." style paths get auto-prefixed.
+ */
+const WORKSPACE_ROUTE_SEGMENTS = new Set([
+ "issues",
+ "projects",
+ "autopilots",
+ "agents",
+ "inbox",
+ "my-issues",
+ "runtimes",
+ "skills",
+ "settings",
+]);
+
+/**
+ * Open a link — internal paths dispatch multica:navigate, external open new tab.
+ *
+ * If `currentSlug` is provided and `href` is a workspace-scoped path lacking a
+ * slug (e.g. "/issues/abc" instead of "/{slug}/issues/abc"), the slug is
+ * prepended. This is for legacy markdown content authored before the URL
+ * refactor, or future content where users forget the slug when pasting.
+ */
+export function openLink(href: string, currentSlug?: string | null): void {
if (href.startsWith("/")) {
+ let path = href;
+ if (currentSlug && !isGlobalPath(path)) {
+ const firstSegment = path.split("/")[1];
+ if (firstSegment && WORKSPACE_ROUTE_SEGMENTS.has(firstSegment)) {
+ // Path looks like /issues/abc (no slug) — prepend current slug.
+ path = `/${currentSlug}${path}`;
+ }
+ // Otherwise the first segment is either already a slug (e.g. "acme" in
+ // "/acme/issues") or something unknown (e.g. "/foo"). Leave it alone —
+ // the user wrote what they meant.
+ }
window.dispatchEvent(
- new CustomEvent("multica:navigate", { detail: { path: href } }),
+ new CustomEvent("multica:navigate", { detail: { path } }),
);
} else {
window.open(href, "_blank", "noopener,noreferrer");
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 9dd6251905..d0a34de624 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -4,6 +4,7 @@ import { useState, useEffect, useCallback, useMemo } from "react";
import { useDefaultLayout } from "react-resizable-panels";
import { useQuery } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import {
inboxListOptions,
deduplicateInboxItems,
@@ -51,6 +52,7 @@ import { typeLabels } from "./inbox-detail-label";
export function InboxPage() {
const { searchParams, replace } = useNavigation();
const urlIssue = searchParams.get("issue") ?? "";
+ const wsPaths = useWorkspacePaths();
const [selectedKey, setSelectedKeyState] = useState(() => urlIssue);
@@ -61,9 +63,10 @@ export function InboxPage() {
const setSelectedKey = useCallback((key: string) => {
setSelectedKeyState(key);
- const url = key ? `/inbox?issue=${key}` : "/inbox";
+ const inboxPath = wsPaths.inbox();
+ const url = key ? `${inboxPath}?issue=${key}` : inboxPath;
replace(url);
- }, [replace]);
+ }, [replace, wsPaths]);
const wsId = useWorkspaceId();
const { data: rawItems = [], isLoading: loading } = useQuery(inboxListOptions(wsId));
diff --git a/packages/views/invite/invite-page.tsx b/packages/views/invite/invite-page.tsx
index 89327ba7f9..2d1ab16102 100644
--- a/packages/views/invite/invite-page.tsx
+++ b/packages/views/invite/invite-page.tsx
@@ -1,11 +1,13 @@
"use client";
import { useState } from "react";
-import { useQuery } from "@tanstack/react-query";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@multica/core/api";
-import { useWorkspaceStore } from "@multica/core/workspace";
-import { workspaceKeys, workspaceListOptions } from "@multica/core/workspace/queries";
-import { useQueryClient } from "@tanstack/react-query";
+import {
+ workspaceKeys,
+ workspaceListOptions,
+} from "@multica/core/workspace/queries";
+import { paths } from "@multica/core/paths";
import { useNavigation } from "../navigation";
import { Button } from "@multica/ui/components/ui/button";
import { Card, CardContent } from "@multica/ui/components/ui/card";
@@ -17,7 +19,6 @@ export interface InvitePageProps {
export function InvitePage({ invitationId }: InvitePageProps) {
const { push } = useNavigation();
- const switchWorkspace = useWorkspaceStore((s) => s.switchWorkspace);
const qc = useQueryClient();
const [accepting, setAccepting] = useState(false);
const [declining, setDeclining] = useState(false);
@@ -29,21 +30,31 @@ export function InvitePage({ invitationId }: InvitePageProps) {
queryFn: () => api.getInvitation(invitationId),
});
+ // Workspace list for the fallback "Go to dashboard" destinations. The invite
+ // page is a pre-workspace global route so we can't rely on WorkspaceSlugProvider.
+ const { data: wsList = [] } = useQuery(workspaceListOptions());
+ const fallbackDest =
+ wsList[0] ? paths.workspace(wsList[0].slug).issues() : paths.onboarding();
+
const handleAccept = async () => {
setAccepting(true);
setError(null);
try {
await api.acceptInvitation(invitationId);
setDone("accepted");
- // Refresh workspace list and switch to the new workspace.
- const wsList = await qc.fetchQuery({ ...workspaceListOptions(), staleTime: 0 });
- const ws = wsList.find((w) => w.id === invitation?.workspace_id);
- if (ws) {
- switchWorkspace(ws);
- }
+ // Fetch the refreshed workspace list so we know the joined workspace's slug.
+ const nextList = await qc.fetchQuery({
+ ...workspaceListOptions(),
+ staleTime: 0,
+ });
+ const joined = nextList.find((w) => w.id === invitation?.workspace_id);
qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
- // Navigate to the workspace after a short delay for the success state.
- setTimeout(() => push("/issues"), 1000);
+ // Navigate into the joined workspace. The [workspaceSlug]/layout will
+ // sync api client, stores, and the last_workspace_slug cookie from the URL.
+ const dest = joined
+ ? paths.workspace(joined.slug).issues()
+ : fallbackDest;
+ setTimeout(() => push(dest), 1000);
} catch (e) {
setError(e instanceof Error ? e.message : "Failed to accept invitation");
} finally {
@@ -83,9 +94,9 @@ export function InvitePage({ invitationId }: InvitePageProps) {
</div>
<h2 className="text-lg font-semibold">Invitation not found</h2>
<p className="text-sm text-muted-foreground text-center">
- This invitation may have expired, been revoked, or doesn't belong to your account.
+ This invitation may have expired, been revoked, or doesn&apos;t belong to your account.
</p>
- <Button variant="outline" onClick={() => push("/issues")}>
+ <Button variant="outline" onClick={() => push(fallbackDest)}>
Go to dashboard
</Button>
</CardContent>
@@ -116,8 +127,8 @@ export function InvitePage({ invitationId }: InvitePageProps) {
<Card className="w-full max-w-md">
<CardContent className="flex flex-col items-center gap-4 py-12">
<h2 className="text-lg font-semibold">Invitation declined</h2>
- <p className="text-sm text-muted-foreground">You won't be added to this workspace.</p>
- <Button variant="outline" onClick={() => push("/issues")}>
+ <p className="text-sm text-muted-foreground">You won&apos;t be added to this workspace.</p>
+ <Button variant="outline" onClick={() => push(fallbackDest)}>
Go to dashboard
</Button>
</CardContent>
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 4e5c124344..42694e2a5c 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -10,6 +10,7 @@ import type { Issue, UpdateIssueRequest } from "@multica/core/types";
import { CalendarDays } from "lucide-react";
import { ActorAvatar } from "../../common/actor-avatar";
import { useUpdateIssue } from "@multica/core/issues/mutations";
+import { useWorkspacePaths } from "@multica/core/paths";
import { PriorityIcon } from "./priority-icon";
import { PriorityPicker, AssigneePicker, DueDatePicker } from "./pickers";
import { PRIORITY_CONFIG } from "@multica/core/issues/config";
@@ -186,6 +187,7 @@ const animateLayoutChanges: AnimateLayoutChanges = (args) => {
};
export const DraggableBoardCard = memo(function DraggableBoardCard({ issue, childProgress }: { issue: Issue; childProgress?: ChildProgress }) {
+ const p = useWorkspacePaths();
const {
attributes,
listeners,
@@ -213,7 +215,7 @@ export const DraggableBoardCard = memo(function DraggableBoardCard({ issue, chil
className={isDragging ? "opacity-30" : ""}
>
<AppLink
- href={`/issues/${issue.id}`}
+ href={p.issueDetail(issue.id)}
className={`group block transition-colors ${isDragging ? "pointer-events-none" : ""}`}
>
<BoardCardContent issue={issue} editable childProgress={childProgress} />
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 625dae1e1b..3a8f6b81a7 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -3,7 +3,13 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue, TimelineEntry } from "@multica/core/types";
-import { WorkspaceIdProvider } from "@multica/core/hooks";
+// useWorkspaceId() derives from useCurrentWorkspace (relative import inside
+// @multica/core/hooks.tsx). vi.mock("@multica/core/paths") only intercepts
+// the bare-specifier, not the internal relative import. Mock the hooks module
+// directly so the bridge hook returns the test UUID.
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
// ---------------------------------------------------------------------------
// Mocks
@@ -23,28 +29,6 @@ vi.mock("@multica/core/auth", () => ({
createAuthStore: vi.fn(),
}));
-// Mock @multica/core/workspace
-vi.mock("@multica/core/workspace", () => ({
- useWorkspaceStore: Object.assign(
- (selector?: any) => {
- const state = {
- workspace: { id: "ws-1", name: "Test WS", slug: "test" },
- agents: [],
- members: [],
- };
- return selector ? selector(state) : state;
- },
- {
- getState: () => ({
- workspace: { id: "ws-1", name: "Test WS", slug: "test" },
- agents: [],
- members: [],
- }),
- },
- ),
- registerWorkspaceStore: vi.fn(),
-}));
-
// Mock @multica/core/workspace/hooks
vi.mock("@multica/core/workspace/hooks", () => ({
useActorName: () => ({
@@ -74,8 +58,26 @@ vi.mock("@multica/core/workspace/queries", () => ({
queryKey: ["workspaces", "ws-1", "assignee-frequency"],
queryFn: () => Promise.resolve([]),
}),
+ workspaceListOptions: () => ({
+ queryKey: ["workspaces"],
+ queryFn: () => Promise.resolve([{ id: "ws-1", name: "Test WS", slug: "test" }]),
+ }),
}));
+// Mock @multica/core/paths — after the URL-driven workspace refactor,
+// useCurrentWorkspace / useWorkspacePaths derive from the workspace slug in
+// URL Context. Tests don't mount a real route, so we short-circuit to fixtures.
+vi.mock("@multica/core/paths", async () => {
+ const actual = await vi.importActual<typeof import("@multica/core/paths")>(
+ "@multica/core/paths",
+ );
+ return {
+ ...actual,
+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Test WS", slug: "test" }),
+ useWorkspacePaths: () => actual.paths.workspace("test"),
+ };
+});
+
// Mock navigation
vi.mock("../../navigation", () => ({
AppLink: ({ children, href, ...props }: any) => (
@@ -342,9 +344,7 @@ function renderIssueDetail(issueId = "issue-1") {
const queryClient = createTestQueryClient();
return render(
<QueryClientProvider client={queryClient}>
- <WorkspaceIdProvider wsId="ws-1">
- <IssueDetail issueId={issueId} />
- </WorkspaceIdProvider>
+ <IssueDetail issueId={issueId} />
</QueryClientProvider>,
);
}
@@ -407,7 +407,9 @@ describe("IssueDetail (shared)", () => {
});
const wsLink = screen.getByText("Test WS");
- expect(wsLink.closest("a")).toHaveAttribute("href", "/issues");
+ // After the URL-driven workspace refactor, issue paths are scoped under
+ // /<workspaceSlug>/issues.
+ expect(wsLink.closest("a")).toHaveAttribute("href", "/test/issues");
});
it("renders properties sidebar with status, priority, assignee, due date", async () => {
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index b0622a4e17..b4383ee77d 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -70,7 +70,7 @@ import { AgentLiveCard, TaskRunHistory } from "./agent-live-card";
import { BacklogAgentHintDialog } from "./backlog-agent-hint-dialog";
import { useQuery } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
import { issueListOptions, issueDetailOptions, childIssuesOptions, issueUsageOptions } from "@multica/core/issues/queries";
@@ -328,7 +328,8 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
const router = useNavigation();
const user = useAuthStore((s) => s.user);
const userId = useAuthStore((s) => s.user?.id);
- const workspace = useWorkspaceStore((s) => s.workspace);
+ const workspace = useCurrentWorkspace();
+ const paths = useWorkspacePaths();
// Issue navigation — read from TQ list cache
const wsId = useWorkspaceId();
@@ -488,7 +489,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
await deleteIssueMutation.mutateAsync(issue!.id);
toast.success("Issue deleted");
if (onDelete) onDelete();
- else router.push("/issues");
+ else router.push(paths.issues());
} catch {
toast.error("Failed to delete issue");
setDeleting(false);
@@ -551,7 +552,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-sm text-muted-foreground">
<p>This issue does not exist or has been deleted in this workspace.</p>
{!onDelete && (
- <Button variant="outline" size="sm" onClick={() => router.push("/issues")}>
+ <Button variant="outline" size="sm" onClick={() => router.push(paths.issues())}>
<ChevronLeft className="mr-1 h-3.5 w-3.5" />
Back to Issues
</Button>
@@ -602,7 +603,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
</button>
{parentIssueOpen && <div className="pl-2">
<AppLink
- href={`/issues/${parentIssue.id}`}
+ href={paths.issueDetail(parentIssue.id)}
className="flex items-center gap-1.5 rounded-md px-2 py-1.5 -mx-2 text-xs hover:bg-accent/50 transition-colors group"
>
<StatusIcon status={parentIssue.status} className="h-3.5 w-3.5 shrink-0" />
@@ -678,7 +679,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
{workspace && (
<>
<AppLink
- href="/issues"
+ href={paths.issues()}
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
>
{workspace.name}
@@ -686,6 +687,17 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
<ChevronRight className="h-3 w-3 text-muted-foreground/50 shrink-0" />
</>
)}
+ {parentIssue && (
+ <>
+ <AppLink
+ href={paths.issueDetail(parentIssue.id)}
+ className="text-muted-foreground hover:text-foreground transition-colors truncate shrink-0"
+ >
+ {parentIssue.identifier}
+ </AppLink>
+ <ChevronRight className="h-3 w-3 text-muted-foreground/50 shrink-0" />
+ </>
+ )}
<span className="shrink-0">
{issue.identifier}
</span>
@@ -1003,7 +1015,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
{parentIssue && (
<AppLink
- href={`/issues/${parentIssue.id}`}
+ href={paths.issueDetail(parentIssue.id)}
className="mt-2 inline-flex max-w-full items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors group/parent"
>
<span className="font-medium shrink-0">Sub-issue of</span>
@@ -1133,7 +1145,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
return (
<AppLink
key={child.id}
- href={`/issues/${child.id}`}
+ href={paths.issueDetail(child.id)}
className="flex items-center gap-2.5 px-3 py-2 hover:bg-accent/50 transition-colors group/row"
>
<StatusIcon
diff --git a/packages/views/issues/components/issue-mention-card.tsx b/packages/views/issues/components/issue-mention-card.tsx
index 4275a833fd..a9de774db3 100644
--- a/packages/views/issues/components/issue-mention-card.tsx
+++ b/packages/views/issues/components/issue-mention-card.tsx
@@ -4,6 +4,7 @@ import { AppLink } from "../../navigation";
import { useQuery } from "@tanstack/react-query";
import { issueListOptions, issueDetailOptions } from "@multica/core/issues/queries";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import { StatusIcon } from "./status-icon";
interface IssueMentionCardProps {
@@ -14,6 +15,7 @@ interface IssueMentionCardProps {
export function IssueMentionCard({ issueId, fallbackLabel }: IssueMentionCardProps) {
const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
const { data: issues = [] } = useQuery(issueListOptions(wsId));
const listIssue = issues.find((i) => i.id === issueId);
@@ -29,7 +31,7 @@ export function IssueMentionCard({ issueId, fallbackLabel }: IssueMentionCardPro
if (!issue) {
return (
<AppLink
- href={`/issues/${issueId}`}
+ href={p.issueDetail(issueId)}
className="issue-mention inline-flex items-center gap-1.5 rounded-md border mx-0.5 px-2 py-0.5 text-xs hover:bg-accent transition-colors cursor-pointer max-w-72"
>
<span className="font-medium text-muted-foreground">
@@ -41,7 +43,7 @@ export function IssueMentionCard({ issueId, fallbackLabel }: IssueMentionCardPro
return (
<AppLink
- href={`/issues/${issueId}`}
+ href={p.issueDetail(issueId)}
className="issue-mention inline-flex items-center gap-1.5 rounded-md border mx-0.5 px-2 py-0.5 text-xs hover:bg-accent transition-colors cursor-pointer max-w-72"
>
<StatusIcon status={issue.status} className="h-3.5 w-3.5 shrink-0" />
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index e61b641a77..55e17f924b 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -2,7 +2,9 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue } from "@multica/core/types";
-import { WorkspaceIdProvider } from "@multica/core/hooks";
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
// ---------------------------------------------------------------------------
// Mocks
@@ -22,27 +24,19 @@ vi.mock("@multica/core/auth", () => ({
createAuthStore: vi.fn(),
}));
-// Mock @multica/core/workspace
-vi.mock("@multica/core/workspace", () => ({
- useWorkspaceStore: Object.assign(
- (selector?: any) => {
- const state = {
- workspace: { id: "ws-1", name: "Test WS", slug: "test" },
- agents: [],
- members: [],
- };
- return selector ? selector(state) : state;
- },
- {
- getState: () => ({
- workspace: { id: "ws-1", name: "Test WS", slug: "test" },
- agents: [],
- members: [],
- }),
- },
- ),
- registerWorkspaceStore: vi.fn(),
-}));
+// Mock @multica/core/paths — after the URL-driven workspace refactor,
+// useCurrentWorkspace derives from the workspace slug in URL Context. Tests
+// don't mount a real route, so we short-circuit to a fixed fixture.
+vi.mock("@multica/core/paths", async () => {
+ const actual = await vi.importActual<typeof import("@multica/core/paths")>(
+ "@multica/core/paths",
+ );
+ return {
+ ...actual,
+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Test WS", slug: "test" }),
+ useWorkspacePaths: () => actual.paths.workspace("test"),
+ };
+});
// Mock @multica/views/navigation (AppLink + useNavigation)
vi.mock("../../navigation", () => ({
@@ -134,8 +128,7 @@ const mockViewState = {
};
vi.mock("@multica/core/issues/stores/view-store", () => ({
- initFilterWorkspaceSync: vi.fn(),
- registerViewStoreForWorkspaceSync: vi.fn(),
+ useClearFiltersOnWorkspaceChange: () => {},
viewStorePersistOptions: () => ({ name: "test", storage: undefined, partialize: (s: any) => s }),
viewStoreSlice: vi.fn(),
useIssueViewStore: Object.assign(
@@ -340,7 +333,7 @@ function renderWithQuery(ui: React.ReactElement) {
});
return render(
<QueryClientProvider client={qc}>
- <WorkspaceIdProvider wsId="ws-1">{ui}</WorkspaceIdProvider>
+ {ui}
</QueryClientProvider>,
);
}
diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsx
index 38d03bf6c7..263ffec732 100644
--- a/packages/views/issues/components/issues-page.tsx
+++ b/packages/views/issues/components/issues-page.tsx
@@ -6,12 +6,12 @@ import { ChevronRight, ListTodo } from "lucide-react";
import type { IssueStatus } from "@multica/core/types";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { useQuery } from "@tanstack/react-query";
-import { useIssueViewStore, initFilterWorkspaceSync } from "@multica/core/issues/stores/view-store";
+import { useIssueViewStore, useClearFiltersOnWorkspaceChange } from "@multica/core/issues/stores/view-store";
import { useIssuesScopeStore } from "@multica/core/issues/stores/issues-scope-store";
import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
import { filterIssues } from "../utils/filter";
import { BOARD_STATUSES } from "@multica/core/issues/config";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace } from "@multica/core/paths";
import { WorkspaceAvatar } from "../../workspace/workspace-avatar";
import { useWorkspaceId } from "@multica/core/hooks";
import { issueListOptions, childIssueProgressOptions } from "@multica/core/issues/queries";
@@ -27,7 +27,7 @@ export function IssuesPage() {
const wsId = useWorkspaceId();
const { data: allIssues = [], isLoading: loading } = useQuery(issueListOptions(wsId));
- const workspace = useWorkspaceStore((s) => s.workspace);
+ const workspace = useCurrentWorkspace();
const scope = useIssuesScopeStore((s) => s.scope);
const viewMode = useIssueViewStore((s) => s.viewMode);
const statusFilters = useIssueViewStore((s) => s.statusFilters);
@@ -38,9 +38,8 @@ export function IssuesPage() {
const projectFilters = useIssueViewStore((s) => s.projectFilters);
const includeNoProject = useIssueViewStore((s) => s.includeNoProject);
- useEffect(() => {
- initFilterWorkspaceSync((cb) => useWorkspaceStore.subscribe((s) => cb(s.workspace?.id)));
- }, []);
+ // Clear filter state when switching between workspaces (URL-driven).
+ useClearFiltersOnWorkspaceChange(useIssueViewStore, wsId);
useEffect(() => {
useIssueSelectionStore.getState().clear();
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index a000f94d8b..e7eee98a47 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -5,6 +5,7 @@ import { AppLink } from "../../navigation";
import type { Issue } from "@multica/core/types";
import { ActorAvatar } from "../../common/actor-avatar";
import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";
+import { useWorkspacePaths } from "@multica/core/paths";
import { PriorityIcon } from "./priority-icon";
import { ProgressRing } from "./progress-ring";
@@ -29,6 +30,7 @@ export const ListRow = memo(function ListRow({
}) {
const selected = useIssueSelectionStore((s) => s.selectedIds.has(issue.id));
const toggle = useIssueSelectionStore((s) => s.toggle);
+ const p = useWorkspacePaths();
return (
<div
@@ -51,7 +53,7 @@ export const ListRow = memo(function ListRow({
/>
</div>
<AppLink
- href={`/issues/${issue.id}`}
+ href={p.issueDetail(issue.id)}
className="flex flex-1 items-center gap-2 min-w-0"
>
<span className="w-16 shrink-0 text-xs text-muted-foreground">
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index 0059bb361a..27681414f4 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -66,7 +66,7 @@ import {
PopoverTrigger,
} from "@multica/ui/components/ui/popover";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace, useWorkspacePaths, paths } from "@multica/core/paths";
import { workspaceListOptions, myInvitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { inboxKeys, deduplicateInboxItems } from "@multica/core/inbox/queries";
@@ -75,24 +75,39 @@ import { useModalStore } from "@multica/core/modals";
import { useMyRuntimesNeedUpdate } from "@multica/core/runtimes/hooks";
import { pinListOptions } from "@multica/core/pins/queries";
import { useDeletePin, useReorderPins } from "@multica/core/pins/mutations";
-import type { PinnedItem } from "@multica/core/types";
+import type { PinnedItem, Workspace } from "@multica/core/types";
+import { clearWorkspaceStorage, defaultStorage } from "@multica/core/platform";
-const personalNav = [
- { href: "/inbox", label: "Inbox", icon: Inbox },
- { href: "/my-issues", label: "My Issues", icon: CircleUser },
+// Nav items reference WorkspacePaths method names so they can be resolved
+// against the current workspace slug at render time (see AppSidebar body).
+// Only parameterless paths are valid nav destinations.
+type NavKey =
+ | "inbox"
+ | "myIssues"
+ | "issues"
+ | "projects"
+ | "autopilots"
+ | "agents"
+ | "runtimes"
+ | "skills"
+ | "settings";
+
+const personalNav: { key: NavKey; label: string; icon: typeof Inbox }[] = [
+ { key: "inbox", label: "Inbox", icon: Inbox },
+ { key: "myIssues", label: "My Issues", icon: CircleUser },
];
-const workspaceNav = [
- { href: "/issues", label: "Issues", icon: ListTodo },
- { href: "/projects", label: "Projects", icon: FolderKanban },
- { href: "/autopilots", label: "Autopilot", icon: Zap },
- { href: "/agents", label: "Agents", icon: Bot },
+const workspaceNav: { key: NavKey; label: string; icon: typeof Inbox }[] = [
+ { key: "issues", label: "Issues", icon: ListTodo },
+ { key: "projects", label: "Projects", icon: FolderKanban },
+ { key: "autopilots", label: "Autopilot", icon: Zap },
+ { key: "agents", label: "Agents", icon: Bot },
];
-const configureNav = [
- { href: "/runtimes", label: "Runtimes", icon: Monitor },
- { href: "/skills", label: "Skills", icon: BookOpenText },
- { href: "/settings", label: "Settings", icon: Settings },
+const configureNav: { key: NavKey; label: string; icon: typeof Inbox }[] = [
+ { key: "runtimes", label: "Runtimes", icon: Monitor },
+ { key: "skills", label: "Skills", icon: BookOpenText },
+ { key: "settings", label: "Settings", icon: Settings },
];
function DraftDot() {
@@ -101,7 +116,7 @@ function DraftDot() {
return <span className="absolute top-0 right-0 size-1.5 rounded-full bg-brand" />;
}
-function SortablePinItem({ pin, pathname, onUnpin }: { pin: PinnedItem; pathname: string; onUnpin: () => void }) {
+function SortablePinItem({ pin, href, pathname, onUnpin }: { pin: PinnedItem; href: string; pathname: string; onUnpin: () => void }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: pin.id });
const wasDragged = useRef(false);
@@ -110,7 +125,6 @@ function SortablePinItem({ pin, pathname, onUnpin }: { pin: PinnedItem; pathname
}, [isDragging]);
const style = { transform: CSS.Transform.toString(transform), transition };
- const href = pin.item_type === "issue" ? `/issues/${pin.item_id}` : `/projects/${pin.item_id}`;
const isActive = pathname === href;
const label = pin.item_type === "issue" && pin.identifier ? `${pin.identifier} ${pin.title}` : pin.title;
@@ -183,8 +197,8 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
const user = useAuthStore((s) => s.user);
const userId = useAuthStore((s) => s.user?.id);
const authLogout = useAuthStore((s) => s.logout);
- const workspace = useWorkspaceStore((s) => s.workspace);
- const switchWorkspace = useWorkspaceStore((s) => s.switchWorkspace);
+ const workspace = useCurrentWorkspace();
+ const p = useWorkspacePaths();
const { data: workspaces = [] } = useQuery(workspaceListOptions());
const { data: myInvitations = [] } = useQuery(myInvitationListOptions());
@@ -222,9 +236,24 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
const queryClient = useQueryClient();
const acceptInvitationMut = useMutation({
mutationFn: (id: string) => api.acceptInvitation(id),
- onSuccess: () => {
+ // After accepting an invitation, navigate INTO the newly-joined workspace.
+ // Otherwise the user stays on their current workspace and just sees the
+ // new one appear in the dropdown — silent and confusing (this is MUL-820).
+ onSuccess: async (_, invitationId) => {
+ const invitation = myInvitations.find((i) => i.id === invitationId);
queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
- queryClient.invalidateQueries({ queryKey: workspaceKeys.list() });
+ // staleTime: 0 forces a real network fetch — we need the joined workspace
+ // in the list before we can resolve its slug for navigation.
+ const list = await queryClient.fetchQuery({
+ ...workspaceListOptions(),
+ staleTime: 0,
+ });
+ const joined = invitation
+ ? list.find((w) => w.id === invitation.workspace_id)
+ : null;
+ if (joined) {
+ push(paths.workspace(joined.slug).issues());
+ }
},
});
const declineInvitationMut = useMutation({
@@ -234,9 +263,26 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
},
});
const logout = () => {
+ // Clear workspace-scoped storage for every workspace this user has access to,
+ // before clearing the React Query cache (which holds the workspace list).
+ // Otherwise per-workspace drafts/chat/etc would leak to the next user on this device.
+ const cachedWorkspaces =
+ queryClient.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];
+ for (const ws of cachedWorkspaces) {
+ clearWorkspaceStorage(defaultStorage, ws.slug);
+ }
+ // Clear the last-workspace-slug cookie. Otherwise on a shared device the
+ // next user gets redirected by the proxy to the previous user's last
+ // workspace (then bounced to /onboarding by the layout — flash + confusing).
+ if (typeof document !== "undefined") {
+ document.cookie = "last_workspace_slug=; path=/; max-age=0; SameSite=Lax";
+ }
+ // Clear desktop tab state. Tab paths can contain issue UUIDs which must
+ // not survive across user sessions on a shared machine. No-op on web
+ // (web doesn't write this key).
+ defaultStorage.removeItem("multica_tabs");
queryClient.clear();
authLogout();
- useWorkspaceStore.getState().clearWorkspace();
};
// Global "C" shortcut to open create-issue modal (like Linear)
@@ -253,7 +299,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
if (useModalStore.getState().modal) return;
e.preventDefault();
// Auto-fill project when on a project detail page
- const projectMatch = pathname.match(/^\/projects\/([^/]+)$/);
+ const projectMatch = pathname.match(/^\/[^/]+\/projects\/([^/]+)$/);
const data = projectMatch ? { project_id: projectMatch[1] } : undefined;
useModalStore.getState().open("create-issue", data);
}
@@ -300,12 +346,9 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
{workspaces.map((ws) => (
<DropdownMenuItem
key={ws.id}
- onClick={() => {
- if (ws.id !== workspace?.id) {
- push("/issues");
- switchWorkspace(ws);
- }
- }}
+ render={
+ <AppLink href={paths.workspace(ws.slug).issues()} />
+ }
>
<WorkspaceAvatar name={ws.name} size="sm" />
<span className="flex-1 truncate">{ws.name}</span>
@@ -400,12 +443,13 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
<SidebarGroupContent>
<SidebarMenu className="gap-0.5">
{personalNav.map((item) => {
- const isActive = pathname === item.href;
+ const href = p[item.key]();
+ const isActive = pathname === href;
return (
- <SidebarMenuItem key={item.href}>
+ <SidebarMenuItem key={item.key}>
<SidebarMenuButton
isActive={isActive}
- render={<AppLink href={item.href} />}
+ render={<AppLink href={href} />}
className="text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground"
>
<item.icon />
@@ -443,6 +487,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
<SortablePinItem
key={pin.id}
pin={pin}
+ href={pin.item_type === "issue" ? p.issueDetail(pin.item_id) : p.projectDetail(pin.item_id)}
pathname={pathname}
onUnpin={() => deletePin.mutate({ itemType: pin.item_type, itemId: pin.item_id })}
/>
@@ -461,12 +506,13 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
<SidebarGroupContent>
<SidebarMenu className="gap-0.5">
{workspaceNav.map((item) => {
- const isActive = pathname === item.href;
+ const href = p[item.key]();
+ const isActive = pathname === href;
return (
- <SidebarMenuItem key={item.href}>
+ <SidebarMenuItem key={item.key}>
<SidebarMenuButton
isActive={isActive}
- render={<AppLink href={item.href} />}
+ render={<AppLink href={href} />}
className="text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground"
>
<item.icon />
@@ -484,12 +530,13 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
<SidebarGroupContent>
<SidebarMenu className="gap-0.5">
{configureNav.map((item) => {
- const isActive = pathname === item.href;
+ const href = p[item.key]();
+ const isActive = pathname === href;
return (
- <SidebarMenuItem key={item.href}>
+ <SidebarMenuItem key={item.key}>
<SidebarMenuButton
isActive={isActive}
- render={<AppLink href={item.href} />}
+ render={<AppLink href={href} />}
className="text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground"
>
<item.icon />
diff --git a/packages/views/layout/dashboard-guard.tsx b/packages/views/layout/dashboard-guard.tsx
index 5d71ebecd3..f2533ac12d 100644
--- a/packages/views/layout/dashboard-guard.tsx
+++ b/packages/views/layout/dashboard-guard.tsx
@@ -1,39 +1,32 @@
"use client";
import type { ReactNode } from "react";
-import { WorkspaceIdProvider } from "@multica/core/hooks";
import { useDashboardGuard } from "./use-dashboard-guard";
interface DashboardGuardProps {
children: ReactNode;
- /** Path to redirect to when user is not authenticated */
- loginPath?: string;
- /** Path to redirect to when user has no workspace (onboarding) */
- onboardingPath?: string;
/** Rendered when auth or workspace is loading */
loadingFallback?: ReactNode;
}
/**
- * Shared guard + provider wrapper for dashboard layouts.
+ * Shared guard for dashboard layouts.
*
- * Handles: auth check → workspace check → WorkspaceIdProvider.
+ * Handles: auth check → workspace check → render children.
* Both web and desktop layouts compose their own UI structure inside this.
+ *
+ * WorkspaceIdProvider has been removed — useWorkspaceId() now derives from
+ * the URL slug via useCurrentWorkspace(). The guard still gates on workspace
+ * being resolved so downstream components can safely call useWorkspaceId().
*/
export function DashboardGuard({
children,
- loginPath = "/",
- onboardingPath,
loadingFallback = null,
}: DashboardGuardProps) {
- const { user, isLoading, workspace } = useDashboardGuard(loginPath, onboardingPath);
+ const { user, isLoading, workspace } = useDashboardGuard();
if (isLoading || !workspace) return <>{loadingFallback}</>;
if (!user) return null;
- return (
- <WorkspaceIdProvider wsId={workspace.id}>
- {children}
- </WorkspaceIdProvider>
- );
+ return <>{children}</>;
}
diff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsx
index a114f06a6e..9ab955e61c 100644
--- a/packages/views/layout/dashboard-layout.tsx
+++ b/packages/views/layout/dashboard-layout.tsx
@@ -14,10 +14,6 @@ interface DashboardLayoutProps {
searchSlot?: ReactNode;
/** Loading indicator */
loadingIndicator?: ReactNode;
- /** Path to redirect when user is not authenticated */
- loginPath?: string;
- /** Path to redirect when user has no workspace */
- onboardingPath?: string;
}
export function DashboardLayout({
@@ -25,13 +21,9 @@ export function DashboardLayout({
extra,
searchSlot,
loadingIndicator,
- loginPath,
- onboardingPath,
}: DashboardLayoutProps) {
return (
<DashboardGuard
- loginPath={loginPath}
- onboardingPath={onboardingPath}
loadingFallback={
<div className="flex h-svh items-center justify-center">
{loadingIndicator}
diff --git a/packages/views/layout/index.ts b/packages/views/layout/index.ts
index f0effc8950..8b8163f4fb 100644
--- a/packages/views/layout/index.ts
+++ b/packages/views/layout/index.ts
@@ -2,3 +2,4 @@ export { AppSidebar } from "./app-sidebar";
export { DashboardGuard } from "./dashboard-guard";
export { DashboardLayout } from "./dashboard-layout";
export { useDashboardGuard } from "./use-dashboard-guard";
+export { WorkspaceLoader } from "./workspace-loader";
diff --git a/packages/views/layout/use-dashboard-guard.ts b/packages/views/layout/use-dashboard-guard.ts
index 18234b5c23..e495d8b74b 100644
--- a/packages/views/layout/use-dashboard-guard.ts
+++ b/packages/views/layout/use-dashboard-guard.ts
@@ -1,27 +1,49 @@
"use client";
import { useEffect } from "react";
+import { useQuery } from "@tanstack/react-query";
import { useNavigationStore } from "@multica/core/navigation";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace, paths } from "@multica/core/paths";
+import { workspaceListOptions } from "@multica/core/workspace";
import { useNavigation } from "../navigation";
-export function useDashboardGuard(loginPath = "/", onboardingPath?: string) {
+/**
+ * Auth + workspace gate for the dashboard.
+ *
+ * Redirect logic:
+ * - Auth still loading → wait
+ * - Not logged in → /login
+ * - Logged in but workspace list not yet loaded → wait (don't bounce to /onboarding)
+ * - Logged in but URL slug doesn't resolve to any workspace → /onboarding
+ *
+ * We read the workspace list query state directly (rather than relying on
+ * useCurrentWorkspace's null return) so we can distinguish "list loading"
+ * from "slug not found". Otherwise users could see a transient redirect
+ * to /onboarding before their workspace list arrives.
+ */
+export function useDashboardGuard() {
const { pathname, replace } = useNavigation();
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
- const workspace = useWorkspaceStore((s) => s.workspace);
+ const workspace = useCurrentWorkspace();
+ const { isFetched: workspaceListFetched } = useQuery({
+ ...workspaceListOptions(),
+ enabled: !!user,
+ });
useEffect(() => {
if (isLoading) return;
if (!user) {
- replace(loginPath);
+ replace(paths.login());
return;
}
- if (!workspace && onboardingPath) {
- replace(onboardingPath);
+ // Wait for workspace list to settle before deciding "no workspace".
+ if (!workspaceListFetched) return;
+ if (!workspace) {
+ replace(paths.onboarding());
}
- }, [user, isLoading, workspace, replace, loginPath, onboardingPath]);
+ }, [user, isLoading, workspaceListFetched, workspace, replace]);
useEffect(() => {
useNavigationStore.getState().onPathChange(pathname);
diff --git a/packages/views/layout/workspace-loader.tsx b/packages/views/layout/workspace-loader.tsx
new file mode 100644
index 0000000000..133f4b4c62
--- /dev/null
+++ b/packages/views/layout/workspace-loader.tsx
@@ -0,0 +1,34 @@
+"use client";
+
+import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
+
+/**
+ * Full-screen workspace loader. Renders IN PLACE OF the dashboard during:
+ * - initial dashboard mount (workspace resolving from URL slug + list cache)
+ * - workspace switch (refetching core workspace data with the new header)
+ *
+ * This is a GATE, not an overlay — sidebar/content do not render behind it.
+ * The gate only opens once the current workspace id has been set on the
+ * workspace-storage singleton AND all core queries for the target
+ * workspace have been freshly fetched.
+ */
+export function WorkspaceLoader({ name }: { name?: string | null }) {
+ return (
+ <div
+ className="flex h-svh w-full items-center justify-center bg-background"
+ aria-live="polite"
+ role="status"
+ >
+ <div className="flex flex-col items-center gap-4">
+ <MulticaIcon className="size-8 animate-pulse" />
+ {name ? (
+ <p className="text-sm text-muted-foreground">
+ Loading <span className="font-medium text-foreground">{name}</span>…
+ </p>
+ ) : (
+ <p className="text-sm text-muted-foreground">Loading workspace…</p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index 0c72645715..2ed33f0e74 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -29,14 +29,11 @@ vi.mock("../navigation", () => ({
useNavigation: () => ({ push: mockPush }),
}));
-vi.mock("@multica/core/workspace", () => ({
- useWorkspaceStore: Object.assign(
- (selector?: (state: { workspace: { name: string } }) => unknown) => {
- const state = { workspace: { name: "Test Workspace" } };
- return selector ? selector(state) : state;
- },
- { getState: () => ({ workspace: { name: "Test Workspace" } }) },
- ),
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ name: "Test Workspace" }),
+ useWorkspacePaths: () => ({
+ issueDetail: (id: string) => `/ws-test/issues/${id}`,
+ }),
}));
vi.mock("@multica/core/issues/stores/draft-store", () => ({
@@ -223,7 +220,7 @@ describe("CreateIssueModal", () => {
await user.click(screen.getByRole("button", { name: "View issue" }));
- expect(mockPush).toHaveBeenCalledWith("/issues/issue-123");
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/issues/issue-123");
expect(mockToastDismiss).toHaveBeenCalledWith("toast-1");
});
});
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index a1bb687bbd..7b92491084 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -17,7 +17,7 @@ import { ContentEditor, type ContentEditorRef, TitleEditor, useFileDropZone, Fil
import { StatusIcon, StatusPicker, PriorityPicker, AssigneePicker, DueDatePicker } from "../issues/components";
import { BacklogAgentHintContent } from "../issues/components/backlog-agent-hint-dialog";
import { ProjectPicker } from "../projects/components/project-picker";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";
import { useCreateIssue, useUpdateIssue } from "@multica/core/issues/mutations";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
@@ -54,7 +54,8 @@ function PillButton({
export function CreateIssueModal({ onClose, data }: { onClose: () => void; data?: Record<string, unknown> | null }) {
const router = useNavigation();
- const workspaceName = useWorkspaceStore((s) => s.workspace?.name);
+ const p = useWorkspacePaths();
+ const workspaceName = useCurrentWorkspace()?.name;
const draft = useIssueDraftStore((s) => s.draft);
const setDraft = useIssueDraftStore((s) => s.setDraft);
@@ -144,7 +145,7 @@ export function CreateIssueModal({ onClose, data }: { onClose: () => void; data?
type="button"
className="ml-7 mt-2 text-sm text-primary hover:underline cursor-pointer"
onClick={() => {
- router.push(`/issues/${issue.id}`);
+ router.push(p.issueDetail(issue.id));
toast.dismiss(t);
}}
>
diff --git a/packages/views/modals/create-workspace.test.tsx b/packages/views/modals/create-workspace.test.tsx
index 51bab10bd7..a90ce7045a 100644
--- a/packages/views/modals/create-workspace.test.tsx
+++ b/packages/views/modals/create-workspace.test.tsx
@@ -89,12 +89,15 @@ describe("CreateWorkspaceModal", () => {
);
});
- it("continues onboarding after successful creation", async () => {
+ it("navigates into the newly created workspace after success", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
mockCreateWorkspaceMutate.mockImplementation(
- (_data: unknown, options: { onSuccess: () => void }) => {
- options.onSuccess();
+ (
+ _data: unknown,
+ options: { onSuccess: (ws: { slug: string }) => void },
+ ) => {
+ options.onSuccess({ slug: "my-team" });
},
);
@@ -104,6 +107,6 @@ describe("CreateWorkspaceModal", () => {
await user.click(screen.getByRole("button", { name: "Create workspace" }));
expect(onClose).toHaveBeenCalled();
- expect(mockPush).toHaveBeenCalledWith("/onboarding");
+ expect(mockPush).toHaveBeenCalledWith("/my-team/issues");
});
});
diff --git a/packages/views/modals/create-workspace.tsx b/packages/views/modals/create-workspace.tsx
index 860f5379e7..9f6547e366 100644
--- a/packages/views/modals/create-workspace.tsx
+++ b/packages/views/modals/create-workspace.tsx
@@ -16,6 +16,7 @@ import {
} from "@multica/ui/components/ui/dialog";
import { Card, CardContent } from "@multica/ui/components/ui/card";
import { useCreateWorkspace } from "@multica/core/workspace/mutations";
+import { paths } from "@multica/core/paths";
import {
WORKSPACE_SLUG_CONFLICT_ERROR,
WORKSPACE_SLUG_FORMAT_ERROR,
@@ -62,12 +63,23 @@ export function CreateWorkspaceModal({ onClose }: { onClose: () => void }) {
const handleCreate = () => {
if (!canSubmit) return;
+ // The modal is only reachable from an authenticated workspace context
+ // (via the global modal registry). After creating a new workspace the
+ // user should land INSIDE it at its issues page, not in /onboarding —
+ // onboarding exists only for users with zero workspaces. Navigation is the
+ // only way to switch workspaces now (URL is the source of truth), so the
+ // push below is sufficient — no imperative store writes needed.
createWorkspace.mutate(
{ name: name.trim(), slug: slug.trim() },
{
- onSuccess: () => {
+ onSuccess: (newWs) => {
onClose();
- router.push("/onboarding");
+ // Navigate INTO the new workspace. The mutation's own onSuccess
+ // (in core/workspace/mutations.ts) runs before this callback and
+ // has already seeded the workspace list cache, so the destination
+ // [workspaceSlug]/layout will resolve newWs.slug → workspace
+ // synchronously without a loading flash.
+ router.push(paths.workspace(newWs.slug).issues());
},
onError: (error) => {
if (isWorkspaceSlugConflict(error)) {
diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsx
index a7756f7938..e9ec1d8d6f 100644
--- a/packages/views/my-issues/components/my-issues-page.tsx
+++ b/packages/views/my-issues/components/my-issues-page.tsx
@@ -7,7 +7,7 @@ import { ChevronRight, ListTodo } from "lucide-react";
import type { IssueStatus } from "@multica/core/types";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace } from "@multica/core/paths";
import { WorkspaceAvatar } from "../../workspace/workspace-avatar";
import { useQuery } from "@tanstack/react-query";
import { agentListOptions } from "@multica/core/workspace/queries";
@@ -18,7 +18,7 @@ import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-st
import { BoardView } from "../../issues/components/board-view";
import { ListView } from "../../issues/components/list-view";
import { BatchActionToolbar } from "../../issues/components/batch-action-toolbar";
-import { registerViewStoreForWorkspaceSync } from "@multica/core/issues/stores/view-store";
+import { useClearFiltersOnWorkspaceChange } from "@multica/core/issues/stores/view-store";
import { useWorkspaceId } from "@multica/core/hooks";
import { myIssueListOptions, childIssueProgressOptions, type MyIssuesFilter } from "@multica/core/issues/queries";
import { useUpdateIssue, useLoadMoreDoneIssues } from "@multica/core/issues/mutations";
@@ -28,7 +28,7 @@ import { MyIssuesHeader } from "./my-issues-header";
export function MyIssuesPage() {
const user = useAuthStore((s) => s.user);
- const workspace = useWorkspaceStore((s) => s.workspace);
+ const workspace = useCurrentWorkspace();
const wsId = useWorkspaceId();
const { data: agents = [] } = useQuery(agentListOptions(wsId));
@@ -37,9 +37,8 @@ export function MyIssuesPage() {
const priorityFilters = useStore(myIssuesViewStore, (s) => s.priorityFilters);
const scope = useStore(myIssuesViewStore, (s) => s.scope);
- useEffect(() => {
- registerViewStoreForWorkspaceSync(myIssuesViewStore);
- }, []);
+ // Clear filter state when switching between workspaces (URL-driven).
+ useClearFiltersOnWorkspaceChange(myIssuesViewStore, wsId);
useEffect(() => {
useIssueSelectionStore.getState().clear();
diff --git a/packages/views/onboarding/onboarding-wizard.test.tsx b/packages/views/onboarding/onboarding-wizard.test.tsx
index 0d461cd30b..f043078690 100644
--- a/packages/views/onboarding/onboarding-wizard.test.tsx
+++ b/packages/views/onboarding/onboarding-wizard.test.tsx
@@ -1,19 +1,13 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
-
-const mockWorkspaceState = vi.hoisted(() => ({
- workspace: null as { id: string } | null,
-}));
-
-vi.mock("@multica/core/workspace", () => ({
- useWorkspaceStore: Object.assign(
- (selector?: (state: typeof mockWorkspaceState) => unknown) =>
- selector ? selector(mockWorkspaceState) : mockWorkspaceState,
- {
- getState: () => mockWorkspaceState,
- },
- ),
-}));
+import {
+ QueryClient,
+ QueryClientProvider,
+ type QueryClient as QC,
+} from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import type { Workspace } from "@multica/core/types";
+import { workspaceKeys } from "@multica/core/workspace/queries";
vi.mock("./step-workspace", () => ({
StepWorkspace: ({ onNext }: { onNext: () => void }) => (
@@ -37,15 +31,49 @@ vi.mock("./step-complete", () => ({
StepComplete: () => <div>Complete step</div>,
}));
+// Stub the list query so the wizard reads whatever we seeded in the cache.
+// `listWorkspaces` returns a promise that never resolves so the seeded cache
+// data isn't overwritten by a background refetch during the test.
+vi.mock("@multica/core/api", () => ({
+ api: {
+ listWorkspaces: vi.fn(() => new Promise(() => {})),
+ },
+}));
+
import { OnboardingWizard } from "./onboarding-wizard";
+function makeWorkspace(id: string, slug = id): Workspace {
+ return {
+ id,
+ name: id,
+ slug,
+ created_at: "",
+ updated_at: "",
+ } as Workspace;
+}
+
+function renderWithCache(
+ wsList: Workspace[],
+ onComplete = vi.fn(),
+): { qc: QC } {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ qc.setQueryData(workspaceKeys.list(), wsList);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+ render(<OnboardingWizard onComplete={onComplete} />, { wrapper });
+ return { qc };
+}
+
describe("OnboardingWizard", () => {
beforeEach(() => {
- mockWorkspaceState.workspace = null;
+ vi.clearAllMocks();
});
it("starts at workspace creation when no workspace exists", () => {
- render(<OnboardingWizard onComplete={vi.fn()} />);
+ renderWithCache([]);
expect(
screen.getByRole("button", { name: "Finish workspace" }),
@@ -53,32 +81,48 @@ describe("OnboardingWizard", () => {
});
it("continues setup when a workspace already exists", () => {
- mockWorkspaceState.workspace = { id: "ws-123" };
-
- render(<OnboardingWizard onComplete={vi.fn()} />);
+ renderWithCache([makeWorkspace("ws-123")]);
expect(screen.getByText("Runtime step for ws-123")).toBeInTheDocument();
});
it("continues setup when the workspace becomes available after mount", async () => {
- const { rerender } = render(<OnboardingWizard onComplete={vi.fn()} />);
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ qc.setQueryData(workspaceKeys.list(), []);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+
+ render(<OnboardingWizard onComplete={vi.fn()} />, { wrapper });
expect(
screen.getByRole("button", { name: "Finish workspace" }),
).toBeInTheDocument();
- mockWorkspaceState.workspace = { id: "ws-456" };
- rerender(<OnboardingWizard onComplete={vi.fn()} />);
+ // Simulate useCreateWorkspace adding the new workspace to the list cache.
+ qc.setQueryData(workspaceKeys.list(), [makeWorkspace("ws-456")]);
expect(
await screen.findByText("Runtime step for ws-456"),
).toBeInTheDocument();
});
- it("does not skip runtime when workspace creation also switches workspace", () => {
- render(<OnboardingWizard onComplete={vi.fn()} />);
+ it("does not skip runtime when workspace creation also advances step", () => {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ qc.setQueryData(workspaceKeys.list(), []);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+
+ render(<OnboardingWizard onComplete={vi.fn()} />, { wrapper });
- mockWorkspaceState.workspace = { id: "ws-789" };
+ // Mutation's onSuccess populates the cache first, then the step-workspace
+ // mock calls onNext — we should land on step 1 (runtime), never step 2.
+ qc.setQueryData(workspaceKeys.list(), [makeWorkspace("ws-789")]);
fireEvent.click(screen.getByRole("button", { name: "Finish workspace" }));
expect(screen.getByText("Runtime step for ws-789")).toBeInTheDocument();
diff --git a/packages/views/onboarding/onboarding-wizard.tsx b/packages/views/onboarding/onboarding-wizard.tsx
index 256e75d9ac..02413e47e4 100644
--- a/packages/views/onboarding/onboarding-wizard.tsx
+++ b/packages/views/onboarding/onboarding-wizard.tsx
@@ -1,8 +1,9 @@
"use client";
import { useCallback, useEffect, useState } from "react";
-import { useWorkspaceStore } from "@multica/core/workspace";
-import type { Agent } from "@multica/core/types";
+import { useQuery } from "@tanstack/react-query";
+import { workspaceListOptions } from "@multica/core/workspace/queries";
+import type { Agent, Workspace } from "@multica/core/types";
import { StepWorkspace } from "./step-workspace";
import { StepRuntime } from "./step-runtime";
import { StepAgent } from "./step-agent";
@@ -16,16 +17,30 @@ const STEPS = [
] as const;
export interface OnboardingWizardProps {
- onComplete: () => void;
+ /**
+ * Called when the user finishes the wizard. The just-configured workspace is
+ * passed so the caller can navigate into it (/{slug}/issues). Onboarding is a
+ * pre-workspace global route, so the URL has no slug while it runs.
+ */
+ onComplete: (workspace: Workspace) => void;
}
export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {
- const [step, setStep] = useState(() =>
- useWorkspaceStore.getState().workspace ? 1 : 0,
- );
- const [createdAgent, setCreatedAgent] = useState<Agent | null>(null);
+ // Canonical source for workspace existence: the React Query list cache. The
+ // onboarding route itself is global (no slug in URL), so useCurrentWorkspace
+ // can't help here — we read the list directly. `useCreateWorkspace` adds the
+ // new workspace to this cache in its onSuccess, so step 0 → step 1 happens
+ // once the list query is populated.
+ const { data: wsList = [] } = useQuery(workspaceListOptions());
+ // A user arriving at /onboarding normally has 0 workspaces. After the first
+ // step they have exactly one. In the rare case the list already has entries
+ // (e.g. the user manually navigated to /onboarding), pick the most recent —
+ // that's the one the onboarding flow should configure.
+ const workspace: Workspace | null = wsList[wsList.length - 1] ?? null;
+ const wsId = workspace?.id ?? null;
- const wsId = useWorkspaceStore((s) => s.workspace?.id) ?? null;
+ const [step, setStep] = useState(() => (workspace ? 1 : 0));
+ const [createdAgent, setCreatedAgent] = useState<Agent | null>(null);
useEffect(() => {
if (step === 0 && wsId) {
@@ -102,11 +117,11 @@ export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {
onAgentCreated={setCreatedAgent}
/>
)}
- {step === 3 && wsId && (
+ {step === 3 && workspace && (
<StepComplete
- wsId={wsId}
+ wsId={workspace.id}
agent={createdAgent}
- onEnter={onComplete}
+ onEnter={() => onComplete(workspace)}
/>
)}
</div>
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index 666277023d..239669d6be 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -16,7 +16,7 @@ import { issueListOptions, childIssueProgressOptions } from "@multica/core/issue
import { useUpdateIssue } from "@multica/core/issues/mutations";
import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";
import { useWorkspaceId } from "@multica/core/hooks";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { PROJECT_STATUS_ORDER, PROJECT_STATUS_CONFIG, PROJECT_PRIORITY_ORDER, PROJECT_PRIORITY_CONFIG } from "@multica/core/projects/config";
import { BOARD_STATUSES } from "@multica/core/issues/config";
@@ -183,9 +183,11 @@ function ProjectIssuesContent({ projectIssues }: { projectIssues: Issue[] }) {
export function ProjectDetail({ projectId }: { projectId: string }) {
const wsId = useWorkspaceId();
+ const wsPaths = useWorkspacePaths();
const router = useNavigation();
const userId = useAuthStore((s) => s.user?.id);
- const workspaceName = useWorkspaceStore((s) => s.workspace?.name);
+ const workspace = useCurrentWorkspace();
+ const workspaceName = workspace?.name;
const { data: project, isLoading } = useQuery(projectDetailOptions(wsId, projectId));
const { data: allIssues = [] } = useQuery(issueListOptions(wsId));
const { data: members = [] } = useQuery(memberListOptions(wsId));
@@ -247,10 +249,10 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
deleteProject.mutate(project.id, {
onSuccess: () => {
toast.success("Project deleted");
- router.push("/projects");
+ router.push(wsPaths.projects());
},
});
- }, [project, deleteProject, router]);
+ }, [project, deleteProject, router, wsPaths]);
if (isLoading) {
return (
@@ -494,7 +496,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
<div className="flex h-full flex-col">
<PageHeader className="gap-2 bg-background text-sm">
<div className="flex flex-1 items-center gap-1.5 min-w-0">
- <AppLink href="/projects" className="text-muted-foreground hover:text-foreground transition-colors shrink-0">
+ <AppLink href={wsPaths.projects()} className="text-muted-foreground hover:text-foreground transition-colors shrink-0">
{workspaceName ?? "Projects"}
</AppLink>
<ChevronRight className="h-3 w-3 text-muted-foreground/50 shrink-0" />
diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsx
index 644b91d6cd..7725c880ce 100644
--- a/packages/views/projects/components/projects-page.tsx
+++ b/packages/views/projects/components/projects-page.tsx
@@ -7,7 +7,7 @@ import { projectListOptions } from "@multica/core/projects/queries";
import { useCreateProject, useUpdateProject } from "@multica/core/projects/mutations";
import { PROJECT_STATUS_CONFIG, PROJECT_STATUS_ORDER, PROJECT_PRIORITY_CONFIG, PROJECT_PRIORITY_ORDER } from "@multica/core/projects/config";
import { useWorkspaceId } from "@multica/core/hooks";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";
import { AppLink, useNavigation } from "../../navigation";
import { ActorAvatar } from "../../common/actor-avatar";
@@ -52,6 +52,7 @@ function formatRelativeDate(date: string): string {
function ProjectRow({ project }: { project: Project }) {
const wsId = useWorkspaceId();
+ const wsPaths = useWorkspacePaths();
const statusCfg = PROJECT_STATUS_CONFIG[project.status];
const priorityCfg = PROJECT_PRIORITY_CONFIG[project.priority];
const updateProject = useUpdateProject();
@@ -76,7 +77,7 @@ function ProjectRow({ project }: { project: Project }) {
<div className="group/row flex h-11 items-center gap-2 px-5 text-sm transition-colors hover:bg-accent/40">
{/* Icon + Name (navigates to detail) */}
<AppLink
- href={`/projects/${project.id}`}
+ href={wsPaths.projectDetail(project.id)}
className="flex min-w-0 flex-1 items-center gap-2"
>
<span className="shrink-0 w-[24px] text-center text-base">{project.icon || "📁"}</span>
@@ -250,7 +251,9 @@ function PillButton({
function CreateProjectDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
const router = useNavigation();
- const workspaceName = useWorkspaceStore((s) => s.workspace?.name);
+ const workspace = useCurrentWorkspace();
+ const workspaceName = workspace?.name;
+ const wsPaths = useWorkspacePaths();
const wsId = useWorkspaceId();
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
@@ -301,7 +304,7 @@ function CreateProjectDialog({ open, onOpenChange }: { open: boolean; onOpenChan
setLeadType(undefined);
setLeadId(undefined);
toast.success("Project created");
- router.push(`/projects/${project.id}`);
+ router.push(wsPaths.projectDetail(project.id));
} catch {
toast.error("Failed to create project");
} finally {
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsx
index e91f13382d..23fcb21050 100644
--- a/packages/views/search/search-command.test.tsx
+++ b/packages/views/search/search-command.test.tsx
@@ -31,6 +31,21 @@ vi.mock("@multica/core", () => ({
useWorkspaceId: () => "ws-test",
}));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ inbox: () => "/ws-test/inbox",
+ myIssues: () => "/ws-test/my-issues",
+ issues: () => "/ws-test/issues",
+ projects: () => "/ws-test/projects",
+ agents: () => "/ws-test/agents",
+ runtimes: () => "/ws-test/runtimes",
+ skills: () => "/ws-test/skills",
+ settings: () => "/ws-test/settings",
+ issueDetail: (id: string) => `/ws-test/issues/${id}`,
+ projectDetail: (id: string) => `/ws-test/projects/${id}`,
+ }),
+}));
+
vi.mock("@multica/core/issues/queries", () => ({
issueListOptions: () => ({ queryKey: ["issues", "ws-test", "list"], enabled: false }),
}));
@@ -110,7 +125,7 @@ describe("SearchCommand", () => {
const settingsItem = await screen.findByText("Settings");
await user.click(settingsItem);
- expect(mockPush).toHaveBeenCalledWith("/settings");
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/settings");
expect(useSearchStore.getState().open).toBe(false);
});
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index 02c9c3702e..98d1db1367 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -23,6 +23,8 @@ import { api } from "@multica/core/api";
import { useRecentIssuesStore } from "@multica/core/issues/stores";
import { issueListOptions } from "@multica/core/issues/queries";
import { useWorkspaceId } from "@multica/core";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { WorkspacePaths } from "@multica/core/paths";
import { StatusIcon } from "../issues/components";
import { STATUS_CONFIG } from "@multica/core/issues/config";
import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";
@@ -73,22 +75,35 @@ function HighlightText({ text, query }: { text: string; query: string }) {
);
}
+// Nav items reference WorkspacePaths method names so they can be resolved
+// against the current workspace slug at render time (see SearchCommand body).
+// Only parameterless paths are valid nav destinations.
+type NavKey =
+ | "inbox"
+ | "myIssues"
+ | "issues"
+ | "projects"
+ | "agents"
+ | "runtimes"
+ | "skills"
+ | "settings";
+
interface NavPage {
- href: string;
+ key: NavKey;
label: string;
icon: LucideIcon;
keywords: string[];
}
const navPages: NavPage[] = [
- { href: "/inbox", label: "Inbox", icon: Inbox, keywords: ["inbox", "notifications"] },
- { href: "/my-issues", label: "My Issues", icon: CircleUser, keywords: ["my", "issues", "assigned"] },
- { href: "/issues", label: "Issues", icon: ListTodo, keywords: ["issues", "tasks", "bugs"] },
- { href: "/projects", label: "Projects", icon: FolderKanban, keywords: ["projects", "kanban"] },
- { href: "/agents", label: "Agents", icon: Bot, keywords: ["agents", "bots", "ai"] },
- { href: "/runtimes", label: "Runtimes", icon: Monitor, keywords: ["runtimes", "environments"] },
- { href: "/skills", label: "Skills", icon: BookOpenText, keywords: ["skills", "library"] },
- { href: "/settings", label: "Settings", icon: Settings, keywords: ["settings", "config", "preferences"] },
+ { key: "inbox", label: "Inbox", icon: Inbox, keywords: ["inbox", "notifications"] },
+ { key: "myIssues", label: "My Issues", icon: CircleUser, keywords: ["my", "issues", "assigned"] },
+ { key: "issues", label: "Issues", icon: ListTodo, keywords: ["issues", "tasks", "bugs"] },
+ { key: "projects", label: "Projects", icon: FolderKanban, keywords: ["projects", "kanban"] },
+ { key: "agents", label: "Agents", icon: Bot, keywords: ["agents", "bots", "ai"] },
+ { key: "runtimes", label: "Runtimes", icon: Monitor, keywords: ["runtimes", "environments"] },
+ { key: "skills", label: "Skills", icon: BookOpenText, keywords: ["skills", "library"] },
+ { key: "settings", label: "Settings", icon: Settings, keywords: ["settings", "config", "preferences"] },
];
interface SearchResults {
@@ -102,6 +117,7 @@ export function SearchCommand() {
const setOpen = useSearchStore((s) => s.setOpen);
const recentItems = useRecentIssuesStore((s) => s.items);
const wsId = useWorkspaceId();
+ const p: WorkspacePaths = useWorkspacePaths();
const { data: allIssues = [] } = useQuery(issueListOptions(wsId));
const recentIssues = useMemo(() => {
@@ -229,20 +245,21 @@ export function SearchCommand() {
(value: string) => {
setOpen(false);
if (value.startsWith("project:")) {
- push(`/projects/${value.slice(8)}`);
+ // value is "project:<id>" — slice off the 8-char prefix to extract the id.
+ push(p.projectDetail(value.slice(8)));
} else {
- push(`/issues/${value}`);
+ push(p.issueDetail(value));
}
},
- [push, setOpen],
+ [push, setOpen, p],
);
const handlePageSelect = useCallback(
- (href: string) => {
+ (key: NavKey) => {
setOpen(false);
- push(href);
+ push(p[key]());
},
- [push, setOpen],
+ [push, setOpen, p],
);
return (
@@ -286,9 +303,9 @@ export function SearchCommand() {
</div>
{filteredPages.map((page) => (
<CommandPrimitive.Item
- key={page.href}
- value={`page:${page.href}`}
- onSelect={() => handlePageSelect(page.href)}
+ key={page.key}
+ value={`page:${page.key}`}
+ onSelect={() => handlePageSelect(page.key)}
className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
>
<page.icon className="size-4 shrink-0 text-muted-foreground" />
diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsx
index af234f6f5f..9dbdc4ed5e 100644
--- a/packages/views/settings/components/members-tab.tsx
+++ b/packages/views/settings/components/members-tab.tsx
@@ -38,8 +38,8 @@ import {
import { toast } from "sonner";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useCurrentWorkspace } from "@multica/core/paths";
import { memberListOptions, invitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
@@ -185,7 +185,7 @@ function InvitationRow({
export function MembersTab() {
const user = useAuthStore((s) => s.user);
- const workspace = useWorkspaceStore((s) => s.workspace);
+ const workspace = useCurrentWorkspace();
const qc = useQueryClient();
const wsId = useWorkspaceId();
const { data: members = [] } = useQuery(memberListOptions(wsId));
diff --git a/packages/views/settings/components/repositories-tab.tsx b/packages/views/settings/components/repositories-tab.tsx
index 4d406b8b2f..dc6add015e 100644
--- a/packages/views/settings/components/repositories-tab.tsx
+++ b/packages/views/settings/components/repositories-tab.tsx
@@ -6,20 +6,20 @@ import { Input } from "@multica/ui/components/ui/input";
import { Button } from "@multica/ui/components/ui/button";
import { Card, CardContent } from "@multica/ui/components/ui/card";
import { toast } from "sonner";
-import { useQuery } from "@tanstack/react-query";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
-import type { WorkspaceRepo } from "@multica/core/types";
+import type { Workspace, WorkspaceRepo } from "@multica/core/types";
export function RepositoriesTab() {
const user = useAuthStore((s) => s.user);
- const workspace = useWorkspaceStore((s) => s.workspace);
+ const workspace = useCurrentWorkspace();
const wsId = useWorkspaceId();
+ const qc = useQueryClient();
const { data: members = [] } = useQuery(memberListOptions(wsId));
- const updateWorkspace = useWorkspaceStore((s) => s.updateWorkspace);
const [repos, setRepos] = useState<WorkspaceRepo[]>(workspace?.repos ?? []);
const [saving, setSaving] = useState(false);
@@ -36,7 +36,9 @@ export function RepositoriesTab() {
setSaving(true);
try {
const updated = await api.updateWorkspace(workspace.id, { repos });
- updateWorkspace(updated);
+ qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>
+ old?.map((ws) => (ws.id === updated.id ? updated : ws)),
+ );
toast.success("Repositories saved");
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to save repositories");
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index 778bcf01f9..9ce7b392ed 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -3,7 +3,7 @@
import React from "react";
import { User, Palette, Key, Settings, Users, FolderGit2 } from "lucide-react";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";
-import { useWorkspaceStore } from "@multica/core/workspace";
+import { useCurrentWorkspace } from "@multica/core/paths";
import { AccountTab } from "./account-tab";
import { AppearanceTab } from "./appearance-tab";
import { TokensTab } from "./tokens-tab";
@@ -36,7 +36,7 @@ interface SettingsPageProps {
}
export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
- const workspaceName = useWorkspaceStore((s) => s.workspace?.name);
+ const workspaceName = useCurrentWorkspace()?.name;
return (
<Tabs defaultValue="profile" orientation="vertical" className="flex-1 min-h-0 gap-0">
diff --git a/packages/views/settings/components/workspace-tab.tsx b/packages/views/settings/components/workspace-tab.tsx
index 9ee1f51a0c..e88cbe5175 100644
--- a/packages/views/settings/components/workspace-tab.tsx
+++ b/packages/views/settings/components/workspace-tab.tsx
@@ -20,22 +20,46 @@ import {
import { toast } from "sonner";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { useWorkspaceStore } from "@multica/core/workspace";
import { useLeaveWorkspace, useDeleteWorkspace } from "@multica/core/workspace/mutations";
import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import {
+ memberListOptions,
+ workspaceKeys,
+ workspaceListOptions,
+} from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
+import { paths } from "@multica/core/paths";
import type { Workspace } from "@multica/core/types";
+import { useNavigation } from "../../navigation";
export function WorkspaceTab() {
const user = useAuthStore((s) => s.user);
- const workspace = useWorkspaceStore((s) => s.workspace);
+ const workspace = useCurrentWorkspace();
const wsId = useWorkspaceId();
const { data: members = [] } = useQuery(memberListOptions(wsId));
const qc = useQueryClient();
- const updateWorkspace = useWorkspaceStore((s) => s.updateWorkspace);
const leaveWorkspace = useLeaveWorkspace();
const deleteWorkspace = useDeleteWorkspace();
+ const navigation = useNavigation();
+
+ /**
+ * After leaving/deleting the current workspace, send the user to a safe URL:
+ * another workspace they still have access to, or onboarding if they have none.
+ * The list is freshly fetched (staleTime: 0) because the cache still contains
+ * the just-removed workspace until the background invalidation resolves.
+ */
+ const navigateAwayFromCurrentWorkspace = async () => {
+ const wsList = await qc.fetchQuery({
+ ...workspaceListOptions(),
+ staleTime: 0,
+ });
+ const remaining = wsList.filter((w) => w.id !== workspace?.id);
+ const next = remaining[0];
+ navigation.push(
+ next ? paths.workspace(next.slug).issues() : paths.onboarding(),
+ );
+ };
const [name, setName] = useState(workspace?.name ?? "");
const [description, setDescription] = useState(workspace?.description ?? "");
@@ -68,7 +92,6 @@ export function WorkspaceTab() {
description,
context,
});
- updateWorkspace(updated);
qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>
old?.map((ws) => (ws.id === updated.id ? updated : ws)),
);
@@ -90,6 +113,7 @@ export function WorkspaceTab() {
setActionId("leave");
try {
await leaveWorkspace.mutateAsync(workspace.id);
+ await navigateAwayFromCurrentWorkspace();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to leave workspace");
} finally {
@@ -109,6 +133,7 @@ export function WorkspaceTab() {
setActionId("delete-workspace");
try {
await deleteWorkspace.mutateAsync(workspace.id);
+ await navigateAwayFromCurrentWorkspace();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to delete workspace");
} finally {
diff --git a/packages/views/workspace/paths-hooks.test.tsx b/packages/views/workspace/paths-hooks.test.tsx
new file mode 100644
index 0000000000..a6f15240ab
--- /dev/null
+++ b/packages/views/workspace/paths-hooks.test.tsx
@@ -0,0 +1,92 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ WorkspaceSlugProvider,
+ useWorkspaceSlug,
+ useCurrentWorkspace,
+} from "@multica/core/paths";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+import type { Workspace } from "@multica/core/types";
+
+// Hook tests for @multica/core/paths live here because packages/core/ runs
+// Vitest in node environment (no jsdom). packages/views/ already has jsdom +
+// @testing-library/react configured, so it's the correct home per CLAUDE.md
+// testing rules ("shared UI components live in packages/views/*.test.tsx").
+
+function makeWorkspace(over: Partial<Workspace>): Workspace {
+ return {
+ id: "id-default",
+ name: "Default",
+ slug: "default",
+ description: null,
+ context: null,
+ settings: {},
+ repos: [],
+ issue_prefix: "DEF",
+ created_at: "",
+ updated_at: "",
+ ...over,
+ };
+}
+
+function setup(slug: string | null, wsList: Workspace[] = []) {
+ const qc = new QueryClient();
+ qc.setQueryData(workspaceKeys.list(), wsList);
+ return function Wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={qc}>
+ <WorkspaceSlugProvider slug={slug}>{children}</WorkspaceSlugProvider>
+ </QueryClientProvider>
+ );
+ };
+}
+
+describe("useWorkspaceSlug", () => {
+ it("returns the provided slug", () => {
+ function Probe() {
+ return <div data-testid="slug">{useWorkspaceSlug() ?? "null"}</div>;
+ }
+ render(<Probe />, { wrapper: setup("acme") });
+ expect(screen.getByTestId("slug").textContent).toBe("acme");
+ });
+
+ it("returns null when no slug is provided", () => {
+ function Probe() {
+ return <div data-testid="slug">{useWorkspaceSlug() ?? "null"}</div>;
+ }
+ render(<Probe />, { wrapper: setup(null) });
+ expect(screen.getByTestId("slug").textContent).toBe("null");
+ });
+});
+
+describe("useCurrentWorkspace", () => {
+ const acme = makeWorkspace({ id: "id-1", slug: "acme", name: "Acme" });
+
+ it("resolves workspace from slug and list", () => {
+ function Probe() {
+ const ws = useCurrentWorkspace();
+ return <div data-testid="name">{ws?.name ?? "none"}</div>;
+ }
+ render(<Probe />, { wrapper: setup("acme", [acme]) });
+ expect(screen.getByTestId("name").textContent).toBe("Acme");
+ });
+
+ it("returns null when slug does not match any workspace", () => {
+ function Probe() {
+ const ws = useCurrentWorkspace();
+ return <div data-testid="name">{ws?.name ?? "none"}</div>;
+ }
+ render(<Probe />, { wrapper: setup("bogus", [acme]) });
+ expect(screen.getByTestId("name").textContent).toBe("none");
+ });
+
+ it("returns null when no slug is provided", () => {
+ function Probe() {
+ const ws = useCurrentWorkspace();
+ return <div data-testid="name">{ws?.name ?? "none"}</div>;
+ }
+ render(<Probe />, { wrapper: setup(null, [acme]) });
+ expect(screen.getByTestId("name").textContent).toBe("none");
+ });
+});
diff --git a/packages/views/workspace/slug.test.ts b/packages/views/workspace/slug.test.ts
new file mode 100644
index 0000000000..810a2a947e
--- /dev/null
+++ b/packages/views/workspace/slug.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from "vitest";
+import { nameToWorkspaceSlug } from "./slug";
+
+describe("nameToWorkspaceSlug", () => {
+ it("lowercases ASCII names and joins words with hyphens", () => {
+ expect(nameToWorkspaceSlug("My Team")).toBe("my-team");
+ expect(nameToWorkspaceSlug("Acme Inc")).toBe("acme-inc");
+ expect(nameToWorkspaceSlug("Project X-1")).toBe("project-x-1");
+ });
+
+ it("strips leading and trailing hyphens", () => {
+ expect(nameToWorkspaceSlug("---test---")).toBe("test");
+ expect(nameToWorkspaceSlug(" Hello ")).toBe("hello");
+ });
+
+ it("collapses multiple non-alphanumeric runs into a single hyphen", () => {
+ expect(nameToWorkspaceSlug("foo!!!bar")).toBe("foo-bar");
+ expect(nameToWorkspaceSlug("a.b.c")).toBe("a-b-c");
+ });
+
+ // Regression: previously fell back to literal "workspace" — caused two
+ // separate non-ASCII-named workspaces on the same instance to 409 (slug
+ // taken) and silently surfaced a confusing "/workspace/issues" URL.
+ it("returns empty string for non-ASCII-only names", () => {
+ expect(nameToWorkspaceSlug("测试")).toBe("");
+ expect(nameToWorkspaceSlug("こんにちは")).toBe("");
+ expect(nameToWorkspaceSlug("🚀")).toBe("");
+ expect(nameToWorkspaceSlug("مرحبا")).toBe("");
+ });
+
+ it("returns empty string for symbol-only names", () => {
+ expect(nameToWorkspaceSlug("---")).toBe("");
+ expect(nameToWorkspaceSlug("!!!")).toBe("");
+ expect(nameToWorkspaceSlug(" ")).toBe("");
+ });
+
+ it("preserves ASCII characters even when mixed with non-ASCII", () => {
+ expect(nameToWorkspaceSlug("测试 Team")).toBe("team");
+ expect(nameToWorkspaceSlug("Project 测试 1")).toBe("project-1");
+ });
+});
diff --git a/packages/views/workspace/slug.ts b/packages/views/workspace/slug.ts
index 040efe27a5..6f027ba3fe 100644
--- a/packages/views/workspace/slug.ts
+++ b/packages/views/workspace/slug.ts
@@ -6,13 +6,21 @@ export const WORKSPACE_SLUG_FORMAT_ERROR =
export const WORKSPACE_SLUG_CONFLICT_ERROR =
"That workspace URL is already taken.";
+/**
+ * Auto-generate a slug from a workspace name.
+ *
+ * Returns empty string when the name produces no valid characters (e.g.
+ * Chinese / Japanese / emoji-only names). The form leaves the slug field
+ * empty in this case and the user must type one — this is preferable to a
+ * hardcoded fallback like "workspace" which (a) silently chooses a useless
+ * URL slug and (b) causes 409 conflicts for the second non-ASCII-named
+ * workspace on the same instance.
+ */
export function nameToWorkspaceSlug(name: string): string {
- return (
- name
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "") || "workspace"
- );
+ return name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "");
}
export function isWorkspaceSlugConflict(error: unknown): boolean {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 287c812faf..0d6365af65 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -87,7 +87,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
r.Use(cors.Handler(cors.Options{
AllowedOrigins: origins,
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
- AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Workspace-ID", "X-Request-ID", "X-Agent-ID", "X-Task-ID", "X-CSRF-Token"},
+ AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Workspace-ID", "X-Workspace-Slug", "X-Request-ID", "X-Agent-ID", "X-Task-ID", "X-CSRF-Token"},
AllowCredentials: true,
MaxAge: 300,
}))
@@ -101,8 +101,15 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
// WebSocket
mc := &membershipChecker{queries: queries}
pr := &patResolver{queries: queries}
+ slugResolver := realtime.SlugResolver(func(ctx context.Context, slug string) (string, error) {
+ ws, err := queries.GetWorkspaceBySlug(ctx, slug)
+ if err != nil {
+ return "", err
+ }
+ return util.UUIDToString(ws.ID), nil
+ })
r.Get("/ws", func(w http.ResponseWriter, r *http.Request) {
- realtime.HandleWebSocket(hub, mc, pr, w, r)
+ realtime.HandleWebSocket(hub, mc, pr, slugResolver, w, r)
})
// Local file serving (when using local storage)
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 068076bb0e..9ec9bd4b03 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -152,6 +152,10 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "slug must contain only lowercase letters, numbers, and hyphens")
return
}
+ if isReservedSlug(req.Slug) {
+ writeError(w, http.StatusBadRequest, "slug is reserved")
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
diff --git a/server/internal/handler/workspace_reserved_slugs.go b/server/internal/handler/workspace_reserved_slugs.go
new file mode 100644
index 0000000000..9ad867bf61
--- /dev/null
+++ b/server/internal/handler/workspace_reserved_slugs.go
@@ -0,0 +1,49 @@
+package handler
+
+// reservedSlugs are workspace slugs that would collide with frontend top-level
+// routes. The frontend URL shape is /{workspaceSlug}/... so any slug that
+// matches a top-level route (e.g. /login, /api) would be unreachable.
+//
+// Keep this list in sync with packages/core/paths/reserved-slugs.ts.
+var reservedSlugs = map[string]bool{
+ // Auth + onboarding routes
+ "login": true,
+ "logout": true,
+ "signup": true,
+ "onboarding": true,
+ "invite": true,
+ "auth": true,
+
+ // Reserved for future platform routes
+ "api": true,
+ "admin": true,
+ "help": true,
+ "about": true,
+ "pricing": true,
+ "changelog": true,
+
+ // Dashboard route segments. Reserved to avoid URL ambiguity — a
+ // workspace named "issues" with /issues/abc URL reads as either
+ // "issue abc in workspace 'issues'" or "issue abc in some workspace".
+ "issues": true,
+ "projects": true,
+ "autopilots": true,
+ "agents": true,
+ "inbox": true,
+ "my-issues": true,
+ "runtimes": true,
+ "skills": true,
+ "settings": true,
+
+ // Next.js / hosting internals
+ "_next": true,
+ "favicon.ico": true,
+ "robots.txt": true,
+ "sitemap.xml": true,
+ "manifest.json": true,
+ ".well-known": true,
+}
+
+func isReservedSlug(slug string) bool {
+ return reservedSlugs[slug]
+}
diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.go
new file mode 100644
index 0000000000..d76e9a24d0
--- /dev/null
+++ b/server/internal/handler/workspace_test.go
@@ -0,0 +1,48 @@
+package handler
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestCreateWorkspace_RejectsReservedSlug(t *testing.T) {
+ reserved := []string{
+ // Auth + onboarding (covered by migration 043 audit)
+ "login",
+ "onboarding",
+ "invite",
+ "api",
+ "settings",
+ "admin",
+ "auth",
+ "signup",
+ "logout",
+ "_next",
+ "favicon.ico",
+ "robots.txt",
+ "sitemap.xml",
+ // Dashboard route segments (covered by migration 045 audit)
+ "issues",
+ "projects",
+ "agents",
+ "inbox",
+ "my-issues",
+ }
+
+ for _, slug := range reserved {
+ t.Run(slug, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/workspaces", map[string]any{
+ "name": fmt.Sprintf("Test %s", slug),
+ "slug": slug,
+ })
+ testHandler.CreateWorkspace(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("slug %q: expected 400, got %d: %s", slug, w.Code, w.Body.String())
+ }
+ })
+ }
+}
diff --git a/server/internal/middleware/workspace.go b/server/internal/middleware/workspace.go
index b9b3ee7cde..193a39b651 100644
--- a/server/internal/middleware/workspace.go
+++ b/server/internal/middleware/workspace.go
@@ -2,6 +2,7 @@ package middleware
import (
"context"
+ "errors"
"net/http"
"github.com/go-chi/chi/v5"
@@ -38,11 +39,50 @@ func SetMemberContext(ctx context.Context, workspaceID string, member db.Member)
return ctx
}
-func resolveWorkspaceID(r *http.Request) string {
- if id := r.URL.Query().Get("workspace_id"); id != "" {
- return id
+// errWorkspaceNotFound is returned when a slug was provided but doesn't match
+// any workspace. This lets the middleware distinguish "no identifier provided"
+// (400) from "identifier provided but invalid" (404).
+var errWorkspaceNotFound = errors.New("workspace not found")
+
+// workspaceResolver extracts a workspace UUID from the request.
+// Returns ("", nil) if no workspace identifier was provided at all.
+// Returns ("", errWorkspaceNotFound) if a slug was provided but doesn't exist.
+// Returns (uuid, nil) on success.
+type workspaceResolver func(r *http.Request) (string, error)
+
+// resolveWorkspaceUUID builds a resolver that accepts slug-first identification.
+//
+// Priority:
+// 1. X-Workspace-Slug header / ?workspace_slug query → GetWorkspaceBySlug → UUID
+// 2. X-Workspace-ID header / ?workspace_id query → UUID directly (CLI/daemon compat)
+//
+// TODO: cache slug→UUID lookup (slug is immutable, safe to cache with short TTL)
+func resolveWorkspaceUUID(queries *db.Queries) workspaceResolver {
+ return func(r *http.Request) (string, error) {
+ // Slug path (preferred — frontend sends this after the URL refactor)
+ if slug := r.URL.Query().Get("workspace_slug"); slug != "" {
+ ws, err := queries.GetWorkspaceBySlug(r.Context(), slug)
+ if err != nil {
+ return "", errWorkspaceNotFound
+ }
+ return util.UUIDToString(ws.ID), nil
+ }
+ if slug := r.Header.Get("X-Workspace-Slug"); slug != "" {
+ ws, err := queries.GetWorkspaceBySlug(r.Context(), slug)
+ if err != nil {
+ return "", errWorkspaceNotFound
+ }
+ return util.UUIDToString(ws.ID), nil
+ }
+ // UUID fallback (CLI, daemon, legacy clients)
+ if id := r.URL.Query().Get("workspace_id"); id != "" {
+ return id, nil
+ }
+ if id := r.Header.Get("X-Workspace-ID"); id != "" {
+ return id, nil
+ }
+ return "", nil
}
- return r.Header.Get("X-Workspace-ID")
}
func writeError(w http.ResponseWriter, status int, msg string) {
@@ -51,41 +91,53 @@ func writeError(w http.ResponseWriter, status int, msg string) {
w.Write([]byte(`{"error":"` + msg + `"}`))
}
-// RequireWorkspaceMember resolves the workspace ID from query param or
-// X-Workspace-ID header, validates membership, and injects the member
-// and workspace ID into the request context.
+// RequireWorkspaceMember resolves the workspace from slug (preferred) or UUID
+// (fallback), validates membership, and injects the member and workspace ID
+// into the request context.
func RequireWorkspaceMember(queries *db.Queries) func(http.Handler) http.Handler {
- return buildMiddleware(queries, resolveWorkspaceID, nil)
+ return buildMiddleware(queries, resolveWorkspaceUUID(queries), nil)
}
// RequireWorkspaceRole is like RequireWorkspaceMember but additionally checks
// that the member has one of the specified roles.
func RequireWorkspaceRole(queries *db.Queries, roles ...string) func(http.Handler) http.Handler {
- return buildMiddleware(queries, resolveWorkspaceID, roles)
+ return buildMiddleware(queries, resolveWorkspaceUUID(queries), roles)
}
// RequireWorkspaceMemberFromURL resolves the workspace ID from a chi URL
// parameter, validates membership, and injects into context.
func RequireWorkspaceMemberFromURL(queries *db.Queries, param string) func(http.Handler) http.Handler {
- return buildMiddleware(queries, func(r *http.Request) string {
- return chi.URLParam(r, param)
+ return buildMiddleware(queries, func(r *http.Request) (string, error) {
+ id := chi.URLParam(r, param)
+ if id == "" {
+ return "", nil
+ }
+ return id, nil
}, nil)
}
// RequireWorkspaceRoleFromURL is like RequireWorkspaceMemberFromURL but
// additionally checks that the member has one of the specified roles.
func RequireWorkspaceRoleFromURL(queries *db.Queries, param string, roles ...string) func(http.Handler) http.Handler {
- return buildMiddleware(queries, func(r *http.Request) string {
- return chi.URLParam(r, param)
+ return buildMiddleware(queries, func(r *http.Request) (string, error) {
+ id := chi.URLParam(r, param)
+ if id == "" {
+ return "", nil
+ }
+ return id, nil
}, roles)
}
-func buildMiddleware(queries *db.Queries, resolve func(*http.Request) string, roles []string) func(http.Handler) http.Handler {
+func buildMiddleware(queries *db.Queries, resolve workspaceResolver, roles []string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- workspaceID := resolve(r)
+ workspaceID, resolveErr := resolve(r)
+ if resolveErr != nil {
+ writeError(w, http.StatusNotFound, "workspace not found")
+ return
+ }
if workspaceID == "" {
- writeError(w, http.StatusBadRequest, "workspace_id is required")
+ writeError(w, http.StatusBadRequest, "workspace_id or workspace_slug is required")
return
}
diff --git a/server/internal/realtime/hub.go b/server/internal/realtime/hub.go
index 21aff29255..54d0019c68 100644
--- a/server/internal/realtime/hub.go
+++ b/server/internal/realtime/hub.go
@@ -21,6 +21,10 @@ type MembershipChecker interface {
IsMember(ctx context.Context, userID, workspaceID string) bool
}
+// SlugResolver translates a workspace slug to its UUID. Used by HandleWebSocket
+// to accept slug-based identification from the frontend.
+type SlugResolver func(ctx context.Context, slug string) (workspaceID string, err error)
+
// PATResolver resolves a Personal Access Token to a user ID.
// Returns the user ID and true if the token is valid, or ("", false) otherwise.
type PATResolver interface {
@@ -350,10 +354,21 @@ func firstMessageAuth(conn *websocket.Conn) (string, string) {
}
// HandleWebSocket upgrades an HTTP connection to WebSocket with cookie or first-message auth.
-func HandleWebSocket(hub *Hub, mc MembershipChecker, pr PATResolver, w http.ResponseWriter, r *http.Request) {
+// resolveSlug may be nil if slug-based identification is not needed (e.g. in tests).
+func HandleWebSocket(hub *Hub, mc MembershipChecker, pr PATResolver, resolveSlug SlugResolver, w http.ResponseWriter, r *http.Request) {
workspaceID := r.URL.Query().Get("workspace_id")
if workspaceID == "" {
- http.Error(w, `{"error":"workspace_id required"}`, http.StatusUnauthorized)
+ if slug := r.URL.Query().Get("workspace_slug"); slug != "" && resolveSlug != nil {
+ resolved, err := resolveSlug(r.Context(), slug)
+ if err != nil {
+ http.Error(w, `{"error":"workspace not found"}`, http.StatusNotFound)
+ return
+ }
+ workspaceID = resolved
+ }
+ }
+ if workspaceID == "" {
+ http.Error(w, `{"error":"workspace_id or workspace_slug required"}`, http.StatusBadRequest)
return
}
diff --git a/server/internal/realtime/hub_test.go b/server/internal/realtime/hub_test.go
index 6f97788411..d38ab4a8fb 100644
--- a/server/internal/realtime/hub_test.go
+++ b/server/internal/realtime/hub_test.go
@@ -44,7 +44,7 @@ func newTestHub(t *testing.T) (*Hub, *httptest.Server) {
mc := &mockMembershipChecker{}
mux := http.NewServeMux()
mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
- HandleWebSocket(hub, mc, nil, w, r)
+ HandleWebSocket(hub, mc, nil, nil, w, r)
})
server := httptest.NewServer(mux)
return hub, server
diff --git a/server/migrations/043_audit_reserved_slugs.down.sql b/server/migrations/043_audit_reserved_slugs.down.sql
new file mode 100644
index 0000000000..17b9418c3f
--- /dev/null
+++ b/server/migrations/043_audit_reserved_slugs.down.sql
@@ -0,0 +1 @@
+-- No-op: 043 is an audit-only migration. Nothing to roll back.
diff --git a/server/migrations/043_audit_reserved_slugs.up.sql b/server/migrations/043_audit_reserved_slugs.up.sql
new file mode 100644
index 0000000000..a497dea969
--- /dev/null
+++ b/server/migrations/043_audit_reserved_slugs.up.sql
@@ -0,0 +1,35 @@
+-- Audit existing workspace slugs against the reserved-words list.
+--
+-- After the URL refactor, workspace URLs are /{slug}/... where slug must not
+-- collide with frontend top-level routes (login, onboarding, api, etc.).
+-- The CreateWorkspace handler now rejects new reserved slugs, but pre-refactor
+-- data could already contain conflicting slugs. This migration fails loudly
+-- so deploy is blocked until those workspaces are renamed or deleted.
+--
+-- Keep the slug list in sync with:
+-- - server/internal/handler/workspace_reserved_slugs.go
+-- - packages/core/paths/reserved-slugs.ts
+
+DO $$
+DECLARE
+ conflict_count INT;
+ conflict_list TEXT;
+BEGIN
+ SELECT
+ COUNT(*),
+ string_agg(slug, ', ' ORDER BY slug)
+ INTO conflict_count, conflict_list
+ FROM workspace
+ WHERE slug IN (
+ -- Auth + onboarding
+ 'login', 'logout', 'signup', 'onboarding', 'invite', 'auth',
+ -- Reserved for future platform routes
+ 'api', 'admin', 'settings', 'help', 'about', 'pricing', 'changelog',
+ -- Next.js / hosting internals
+ '_next', 'favicon.ico', 'robots.txt', 'sitemap.xml', 'manifest.json', '.well-known'
+ );
+
+ IF conflict_count > 0 THEN
+ RAISE EXCEPTION 'Found % workspace(s) with reserved slugs: %. Rename or delete before deploying.', conflict_count, conflict_list;
+ END IF;
+END $$;
diff --git a/server/migrations/044_fix_workspace_fallback_slug.down.sql b/server/migrations/044_fix_workspace_fallback_slug.down.sql
new file mode 100644
index 0000000000..cf6b47804e
--- /dev/null
+++ b/server/migrations/044_fix_workspace_fallback_slug.down.sql
@@ -0,0 +1,3 @@
+-- Cannot reverse the slug rename — the original 'workspace' slug is lost
+-- and we'd risk colliding multiple workspaces on the same value.
+-- This migration is intentionally one-way.
diff --git a/server/migrations/044_fix_workspace_fallback_slug.up.sql b/server/migrations/044_fix_workspace_fallback_slug.up.sql
new file mode 100644
index 0000000000..f66ac22d42
--- /dev/null
+++ b/server/migrations/044_fix_workspace_fallback_slug.up.sql
@@ -0,0 +1,24 @@
+-- Cleanup for the "workspace" auto-generated slug fallback bug.
+--
+-- The frontend's nameToWorkspaceSlug() previously fell back to the literal
+-- string "workspace" when the input name produced no valid slug characters
+-- (Chinese / Japanese / emoji / Arabic names all stripped to empty by the
+-- /[^a-z0-9]+/g regex). This meant the first non-ASCII-named workspace on
+-- any instance silently got slug = "workspace" and (a) showed a confusing
+-- /workspace/{view} URL after the URL refactor, (b) blocked subsequent
+-- non-ASCII-named workspaces with 409 conflicts on the unique slug index.
+--
+-- The frontend bug is fixed in
+-- packages/views/workspace/slug.ts (commit d5c9613f)
+-- but pre-existing data with slug = 'workspace' must be migrated. Renaming
+-- to 'workspace-<8 hex chars>' preserves URL stability for the few users
+-- already on it while ensuring uniqueness if multiple instances had this
+-- workspace (e.g. local dev DBs across the team).
+--
+-- For other broken slugs (numeric-only, emoji-only, etc.) we don't migrate
+-- here because they are valid per the regex and the user might have chosen
+-- them intentionally. Only the literal "workspace" fallback is patched.
+
+UPDATE workspace
+SET slug = 'workspace-' || substring(replace(id::text, '-', '') from 1 for 8)
+WHERE slug = 'workspace';
diff --git a/server/migrations/045_audit_dashboard_route_slugs.down.sql b/server/migrations/045_audit_dashboard_route_slugs.down.sql
new file mode 100644
index 0000000000..0095fe94e3
--- /dev/null
+++ b/server/migrations/045_audit_dashboard_route_slugs.down.sql
@@ -0,0 +1 @@
+-- No-op: 045 is an audit-only migration. Nothing to roll back.
diff --git a/server/migrations/045_audit_dashboard_route_slugs.up.sql b/server/migrations/045_audit_dashboard_route_slugs.up.sql
new file mode 100644
index 0000000000..2b3e4693bc
--- /dev/null
+++ b/server/migrations/045_audit_dashboard_route_slugs.up.sql
@@ -0,0 +1,34 @@
+-- Audit existing workspace slugs against the dashboard route segment names.
+--
+-- Migration 043 audited the auth/onboarding/hosting reserved words. This one
+-- adds the dashboard route segments (issues / projects / agents / inbox /
+-- my-issues / runtimes / skills / autopilots) — slug = any of these would
+-- produce visually ambiguous URLs after the URL refactor (e.g. /issues/abc
+-- could mean "issue abc in workspace 'issues'" or "issue abc in some
+-- workspace"). Reserve to avoid the confusion.
+--
+-- "settings" was already reserved by 043, no need to repeat.
+--
+-- Keep this slug list in sync with:
+-- - server/internal/handler/workspace_reserved_slugs.go
+-- - packages/core/paths/reserved-slugs.ts
+
+DO $$
+DECLARE
+ conflict_count INT;
+ conflict_list TEXT;
+BEGIN
+ SELECT
+ COUNT(*),
+ string_agg(slug, ', ' ORDER BY slug)
+ INTO conflict_count, conflict_list
+ FROM workspace
+ WHERE slug IN (
+ 'issues', 'projects', 'autopilots', 'agents',
+ 'inbox', 'my-issues', 'runtimes', 'skills'
+ );
+
+ IF conflict_count > 0 THEN
+ RAISE EXCEPTION 'Found % workspace(s) with slugs that collide with dashboard routes: %. Rename or delete before deploying.', conflict_count, conflict_list;
+ END IF;
+END $$;