Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 协同 Lead/Worker 往返改走回退,不再改写导航栈 (#5470)
Yunjin Zhang282c38885f9e
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 1244ae289a..503065ad7d 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -567,6 +567,10 @@ import {switchDrawerSessionInPlace,type SessionRouteParamsNavigation,} from '@/session/sessionDrawerNavigation';+import {+ navigateToCollabSession,+ type CollabSessionStateLike,+} from '@/session/collabSessionNavigation';import type { RemoteSessionListItem } from '@/session/sessionList';import {findMobileMessageSearchHits,@@ -995,7 +999,12 @@ export default function SessionScreen() {const visualFocusComposer = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualFocusComposer) === '1';const visualOpenSearch = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualOpenSearch) === '1';const visualSearchQuery = MOBILE_VISUAL_MOCK_ENABLED ? readRouteParam(params.visualSearchQuery) : null;- const navigation = useNavigation<SessionRouteParamsNavigation & { isFocused(): boolean }>();+ const navigation = useNavigation<SessionRouteParamsNavigation & {+ isFocused(): boolean;+ // useNavigation 返回的 navigation 对象没有 getRootState(那是容器 ref 的方法),+ // 这里只需要本 route 所属 navigator 的 state —— session 路由直属 root stack。+ getState(): CollabSessionStateLike | undefined;+ }>();useEffect(() => subscribeCredentialSwitchOutcome((outcome) => {if (outcome.deviceId !== deviceId || outcome.sessionId !== sessionId || !navigation.isFocused()) return;Alert.alert(t(outcome.kind === 'applied' ? 'models.switchOutcome.applied' : 'models.switchOutcome.failed'));@@ -2057,13 +2066,36 @@ export default function SessionScreen() {currentSession,);// 协同(Orca):+ 面板「协同模式」二级视图 + Lead / Worker 导航。团队真身在被控端。+ // Lead <-> Worker 往返不能用 push:session 路由带 getId,同 id 的 PUSH 会被 StackRouter+ // 「复用 + 移到栈顶」,返回手势就落回 Worker,且每往返一次改写一次栈内 Screen 顺序+ // (Android 白屏)。已在栈里 → dismissTo 回退,不在栈里 → push。理由与不变量见+ // collabSessionNavigation.ts。const openCollabSession = useCallback((targetSessionId: string) => {- if (!deviceId || !targetSessionId || targetSessionId === sessionId) return;- router.push({- pathname: '/sessions/[sessionId]',- params: { sessionId: targetSessionId, deviceId, deviceName },- });- }, [deviceId, deviceName, router, sessionId]);+ if (!deviceId || !targetSessionId) return;+ navigateToCollabSession(+ {+ getState: () => navigation.getState(),+ push: (target) => router.push({+ pathname: '/sessions/[sessionId]',+ params: {+ sessionId: target.sessionId,+ deviceId: target.deviceId,+ deviceName: target.deviceName,+ },+ }),+ dismissTo: (target) => router.dismissTo({+ pathname: '/sessions/[sessionId]',+ params: {+ sessionId: target.sessionId,+ deviceId: target.deviceId,+ deviceName: target.deviceName,+ },+ }),+ },+ { sessionId: targetSessionId, deviceId, deviceName },+ sessionId,+ );+ }, [deviceId, deviceName, navigation, router, sessionId]);// 来源目录在协同 hook 之后才取得(它依赖 Worker 选择器是否打开),经 ref 在提交时读。const collabProvidersRef = useRef<readonly ProviderView[] | null>(null);const collab = useSessionOrcaCollab({diff --git a/apps/mobile/src/__tests__/collabSessionNavigation.test.ts b/apps/mobile/src/__tests__/collabSessionNavigation.test.tsnew file mode 100644index 0000000000..bf8f50e0f7--- /dev/null+++ b/apps/mobile/src/__tests__/collabSessionNavigation.test.ts@@ -0,0 +1,315 @@+import { readFileSync } from "node:fs";+import { resolve } from "node:path";++import { describe, expect, it, vi } from "vitest";+import {+ SESSION_ROUTE_NAME,+ findStackedSessionRoute,+ navigateToCollabSession,+ planCollabSessionNavigation,+ type CollabSessionNavigator,+ type CollabSessionRouteLike,+ type CollabSessionStateLike,+ type CollabSessionTarget,+} from "@/session/collabSessionNavigation";+import { recentTaskKey } from "@/session/recentTasks";+// 真实 router 实现:本 bug 的机制就在它的 PUSH 分支里,用真件跑一遍才能防回归。+import { StackRouter } from "expo-router/build/react-navigation/routers/StackRouter";++// Windows checkout 下源码可能是 CRLF;断言跨平台统一按 LF 归一。+const readTextLf = (...args: Parameters<typeof readFileSync>): string =>+ String(readFileSync(...args)).replace(/\r\n/g, "\n");++const lead: CollabSessionTarget = {+ sessionId: "lead-1",+ deviceId: "pc",+ deviceName: "PC",+};+const worker: CollabSessionTarget = {+ sessionId: "worker-1",+ deviceId: "pc",+ deviceName: "PC",+};+const deviceList: CollabSessionTarget = {+ sessionId: "device-list",+ deviceId: "pc",+ deviceName: "PC",+};++const route = (+ target: CollabSessionTarget,+ key: string,+): CollabSessionRouteLike => ({+ name: SESSION_ROUTE_NAME,+ key,+ params: target,+});++const stack = (+ ...routes: CollabSessionRouteLike[]+): CollabSessionStateLike => ({ routes });++function fakeNavigator(state: CollabSessionStateLike | undefined) {+ return {+ getState: () => state,+ push: vi.fn(),+ dismissTo: vi.fn(),+ };+}++describe("collaboration session navigation decision", () => {+ it("falls back (popTo) when the target session is already on the stack", () => {+ const navigator = fakeNavigator(+ stack(route(lead, "L"), route(worker, "W")),+ );++ expect(navigateToCollabSession(navigator, lead, "worker-1")).toBe("popTo");+ // 硬约束:栈里已有目标任务时绝不 push —— 那会把「返回 Lead」变成栈重排。+ expect(navigator.push).not.toHaveBeenCalled();+ expect(navigator.dismissTo).toHaveBeenCalledExactlyOnceWith(lead);+ });++ it("pushes only when the target session is not on the stack yet", () => {+ const navigator = fakeNavigator(+ stack(route(lead, "L"), route(worker, "W")),+ );+ const fresh: CollabSessionTarget = { ...lead, sessionId: "worker-2" };++ expect(navigateToCollabSession(navigator, fresh, "worker-1")).toBe("push");+ expect(navigator.dismissTo).not.toHaveBeenCalled();+ expect(navigator.push).toHaveBeenCalledExactlyOnceWith(fresh);+ });++ it("does nothing on the current session, a missing device or a missing session id", () => {+ const withState = fakeNavigator(stack(route(lead, "L")));++ expect(navigateToCollabSession(withState, lead, "lead-1")).toBe("noop");+ expect(+ navigateToCollabSession(withState, { ...worker, deviceId: "" }, "lead-1"),+ ).toBe("noop");+ expect(+ navigateToCollabSession(+ withState,+ { ...worker, sessionId: "" },+ "lead-1",+ ),+ ).toBe("noop");+ expect(withState.push).not.toHaveBeenCalled();+ expect(withState.dismissTo).not.toHaveBeenCalled();++ // 拿不到导航状态时退化成 push:这是旧行为,不会凭空回退到某个猜测的屏。+ const stateless = fakeNavigator(undefined);+ expect(navigateToCollabSession(stateless, lead, "worker-1")).toBe("push");+ expect(stateless.push).toHaveBeenCalledOnce();+ });++ it("matches the stacked route with the same id the Stack getId derives", () => {+ // 跨电脑的同名任务不算命中;嵌套 navigator 也要找得到。+ const nested: CollabSessionStateLike = {+ routes: [+ route(lead, "L"),+ { name: "tabs", state: stack(route(lead, "NESTED")) },+ ],+ };+ const otherDevice: CollabSessionTarget = { ...lead, deviceId: "other-pc" };++ expect(findStackedSessionRoute(nested, lead)).toBe(true);+ expect(findStackedSessionRoute(nested, otherDevice)).toBe(false);+ expect(planCollabSessionNavigation(nested, lead, "lead-1")).toBe("noop");+ expect(planCollabSessionNavigation(nested, otherDevice, "worker-1")).toBe(+ "push",+ );+ expect(recentTaskKey({ deviceId: "pc", sessionId: "lead-1" })).toBe(+ recentTaskKey(lead),+ );+ });+});++// 用真实 StackRouter 跑一遍 Lead <-> Worker 往返,把生产现象钉成断言:+// 旧口径(每次 push)返回手势落回 Worker;新口径(dismissTo 回退)返回手势落回列表。+describe("collaboration navigation against the real StackRouter", () => {+ const getId = ({ params }: { params?: Record<string, unknown> }) =>+ recentTaskKey(params ?? {});+ const routerConfig = {+ routeNames: [SESSION_ROUTE_NAME],+ routeParamList: {},+ routeGetIdList: { [SESSION_ROUTE_NAME]: getId },+ };+ interface TestRoute {+ key: string;+ name: string;+ params?: Record<string, unknown>;+ state?: unknown;+ }+ interface TestState {+ index: number;+ key: string;+ routeNames: string[];+ routes: TestRoute[];+ preloadedRoutes: TestRoute[];+ stale: boolean;+ type: "stack";+ }+ const startState = (): TestState => ({+ index: 0,+ key: "Stack-root",+ routeNames: [SESSION_ROUTE_NAME],+ routes: [{ ...(route(deviceList, "DEVICES") as TestRoute) }],+ preloadedRoutes: [],+ stale: false,+ type: "stack",+ });+ const sessionIds = (state: TestState) =>+ state.routes.map((item) => String((item.params ?? {}).sessionId));+ const toParams = (target: CollabSessionTarget) => ({+ sessionId: target.sessionId,+ deviceId: target.deviceId,+ deviceName: target.deviceName,+ });++ /** 真 router + 真 action:供 navigator 的 push / dismissTo 落地。 */+ const createDriver = () => {+ const router = StackRouter({});+ let state = startState();+ const apply = (action: unknown) => {+ const next = router.getStateForAction(+ state as never,+ action as never,+ routerConfig as never,+ );+ if (next) state = next as TestState;+ };+ return {+ get state() {+ return state;+ },+ apply,+ push: (target: CollabSessionTarget) =>+ apply({+ type: "PUSH",+ payload: { name: SESSION_ROUTE_NAME, params: toParams(target) },+ }),+ dismissTo: (target: CollabSessionTarget) =>+ apply({+ type: "POP_TO",+ payload: { name: SESSION_ROUTE_NAME, params: toParams(target) },+ }),+ };+ };++ /**+ * 生产路径:每次跳转都由 navigateToCollabSession 自己读栈决定动作,测试不复刻+ * 判断逻辑 —— 否则决策口改成 push 也不会让这里变红。`currentSessionId` 跟着前进,+ * 与真实会话页传入的是同一个值。每一步都录一帧栈快照,供逐步断言。+ */+ const driveThroughDecision = () => {+ const driver = createDriver();+ const navigator: CollabSessionNavigator = {+ getState: () => driver.state as unknown as CollabSessionStateLike,+ push: driver.push,+ dismissTo: driver.dismissTo,+ };+ const steps: { plan: string; stack: string[] }[] = [];+ const open = (target: CollabSessionTarget, currentSessionId: string) => {+ const plan = navigateToCollabSession(navigator, target, currentSessionId);+ steps.push({ plan, stack: [...sessionIds(driver.state)] });+ };++ open(lead, deviceList.sessionId);+ open(worker, lead.sessionId);+ open(lead, worker.sessionId);+ open(worker, lead.sessionId);+ open(lead, worker.sessionId);+ const beforeBack = [...sessionIds(driver.state)];+ driver.apply({ type: "GO_BACK" });+ return { steps, beforeBack, afterBack: sessionIds(driver.state) };+ };++ /**+ * 回归对照:故意绕过决策口,把每次跳转都做成旧的裸 PUSH,用来证明上面的断言确实+ * 能捕捉这个缺陷(若哪天 push 行为不再改写历史,这条会一起变绿,说明对照组该重写)。+ * 它不是生产路径。同样逐步录快照。+ */+ const driveWithLegacyPush = () => {+ const driver = createDriver();+ const steps: { stack: string[] }[] = [];+ const open = (target: CollabSessionTarget) => {+ driver.push(target);+ steps.push({ stack: [...sessionIds(driver.state)] });+ };+ open(lead);+ open(worker);+ open(lead);+ open(worker);+ open(lead);+ const beforeBack = [...sessionIds(driver.state)];+ driver.apply({ type: "GO_BACK" });+ return { steps, beforeBack, afterBack: sessionIds(driver.state) };+ };++ it("reproduces the reordered history when a stacked session is pushed again", () => {+ const legacy = driveWithLegacyPush();+ // 逐步对账:前两步正常压栈,第一次「返回 Lead」开始把顺序对调。+ expect(legacy.steps.map((step) => step.stack)).toEqual([+ ["device-list", "lead-1"],+ ["device-list", "lead-1", "worker-1"],+ ["device-list", "worker-1", "lead-1"],+ ["device-list", "lead-1", "worker-1"],+ ["device-list", "worker-1", "lead-1"],+ ]);+ // 「返回 Lead」把 Lead 提到顶、Worker 掉到它下面 —— 用户看到的「右滑又进了 Worker」。+ expect(legacy.beforeBack).toEqual(["device-list", "worker-1", "lead-1"]);+ expect(legacy.afterBack).toEqual(["device-list", "worker-1"]);+ });++ it("keeps the history truthful when a stacked session is popped back to", () => {+ const fixed = driveThroughDecision();+ // 逐步对账:两轮都真的发生了(Worker 先压栈、返回时回退),首次进 Worker 与+ // 复位后的二次进 Worker 各自可验,不会因为只看末态而漏掉中间跳转。+ expect(fixed.steps.map((step) => step.plan)).toEqual([+ "push",+ "push",+ "popTo",+ "push",+ "popTo",+ ]);+ expect(fixed.steps.map((step) => step.stack)).toEqual([+ ["device-list", "lead-1"],+ ["device-list", "lead-1", "worker-1"],+ ["device-list", "lead-1"],+ ["device-list", "lead-1", "worker-1"],+ ["device-list", "lead-1"],+ ]);+ expect(fixed.beforeBack).toEqual(["device-list", "lead-1"]);+ expect(fixed.afterBack).toEqual(["device-list"]);+ });+});++// 调用点契约:协同跳转必须经过上面的决策口,不能再有裸 push。+describe("collaboration navigation wiring", () => {+ const source = readTextLf(+ resolve(process.cwd(), "app/sessions/[sessionId].tsx"),+ "utf8",+ );+ const start = source.indexOf("const openCollabSession = useCallback");+ const end = source.indexOf("// 来源目录在协同 hook 之后才取得", start);++ it("routes collab navigation through the popTo/push decision", () => {+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ const block = source.slice(start, end);+ expect(source).toContain("} from '@/session/collabSessionNavigation';");+ expect(source).toContain("navigateToCollabSession,");+ expect(source).toContain("type CollabSessionStateLike,");+ expect(block).toContain("navigateToCollabSession(");+ expect(block).toContain("getState: () => navigation.getState(),");+ expect(block).toContain("push: (target) => router.push({");+ expect(block).toContain("dismissTo: (target) => router.dismissTo({");+ // 旧的裸 push(直接拿目标 id 组 params)已不存在:那正是命中「同 id 复用 + 移到栈顶」的那一行。+ expect(block).not.toContain(+ "params: { sessionId: targetSessionId, deviceId, deviceName }",+ );+ // getRootState 只存在于容器 ref,useNavigation 返回的对象上没有:写了就是运行时 TypeError。+ expect(source).not.toContain("navigation.getRootState()");+ });+});diff --git a/apps/mobile/src/session/collabSessionNavigation.ts b/apps/mobile/src/session/collabSessionNavigation.tsnew file mode 100644index 0000000000..c020010e79--- /dev/null+++ b/apps/mobile/src/session/collabSessionNavigation.ts@@ -0,0 +1,109 @@+/**+ * 协同(Orca)Lead / Worker 之间的任务跳转决策。+ *+ * 为什么不能一律 `router.push`:`sessions/[sessionId]` 配了 `getId`(见 `app/_layout.tsx`),+ * 同一 (deviceId, sessionId) 恒得同一个 route id。expo-router 内联 react-navigation 的+ * StackRouter 在 PUSH 命中「栈里已有同 id route」时不新增,而是把那个 route **从栈中删掉再+ * 追加到栈顶**(`StackRouter.js` 的 `routes.filter(...)` + `routes.push({...route, params})`)。+ * 于是「返回 Lead」并不是回退:Lead 被提到顶,Worker 被挤到它下面,紧接着的返回手势落回+ * Worker;而且每往返一次就改写一次栈内 Screen 顺序 —— Android native-stack 面对「已存在的+ * Screen 换了位置」只能走 fragment 替换生命周期,正是 `sessionDrawerNavigation.ts` 记录的+ * Android crash / 白屏入口。生产表现:往返两轮后右滑返回白屏且点不动。+ *+ * 因此这里的口径是:目标已在栈里 → `dismissTo`(POP_TO,真回退,只截断、不改顺序);+ * 不在栈里 → `push`。两者都不动已有 route 的相对顺序,Android 上也不再进入 Screen 替换。+ */+import { recentTaskKey } from "@/session/recentTasks";++export const SESSION_ROUTE_NAME = "sessions/[sessionId]";++export interface CollabSessionTarget {+ deviceId: string;+ deviceName: string;+ sessionId: string;+}++/** 导航状态里我们关心的那部分(route 形状按未知处理,不绑 react-navigation 类型)。 */+export interface CollabSessionRouteLike {+ key?: unknown;+ name?: unknown;+ params?: unknown;+ /** 嵌套 navigator 的子状态;沿途找得到目标任务才算命中。 */+ state?: CollabSessionStateLike;+}++export interface CollabSessionStateLike {+ routes?: readonly CollabSessionRouteLike[];+ state?: CollabSessionStateLike;+}++export interface CollabSessionNavigator {+ /** 包含本 route 的 navigator 的 state(session 路由直属 root stack,即栈里有哪些任务)。 */+ getState(): CollabSessionStateLike | undefined;+ push(target: CollabSessionTarget): void;+ /** 回退到目标那一屏(expo-router `dismissTo` → StackRouter POP_TO)。 */+ dismissTo(target: CollabSessionTarget): void;+}++export type CollabSessionNavigationPlan = "noop" | "popTo" | "push";++const isTargetRoute = (+ route: CollabSessionRouteLike,+ target: CollabSessionTarget,+): boolean => {+ if (route.name !== SESSION_ROUTE_NAME) return false;+ const params = (route.params ?? {}) as {+ deviceId?: unknown;+ sessionId?: unknown;+ };+ // 与 getId 同一把尺子:deviceId + sessionId。跨电脑的同名任务不算命中。+ return recentTaskKey(params) === recentTaskKey(target);+};++/** 目标任务是否已经在导航栈里(深度优先,兼容嵌套 navigator)。 */+export function findStackedSessionRoute(+ state: CollabSessionStateLike | undefined | null,+ target: CollabSessionTarget,+): boolean {+ for (const route of state?.routes ?? []) {+ if (isTargetRoute(route, target)) return true;+ if (findStackedSessionRoute(route.state, target)) return true;+ }+ return false;+}++export function planCollabSessionNavigation(+ state: CollabSessionStateLike | undefined | null,+ target: CollabSessionTarget,+ currentSessionId: string,+): CollabSessionNavigationPlan {+ // 就在这一屏:什么都不派发(与既有守卫一致)。+ if (+ !target.deviceId ||+ !target.sessionId ||+ target.sessionId === currentSessionId+ )+ return "noop";+ return findStackedSessionRoute(state, target) ? "popTo" : "push";+}++/**+ * 协同跳转的执行口。返回实际采取的动作,便于调用点与测试各自断言。+ *+ * 硬约束:**栈里已有目标任务时只走 dismissTo,绝不 push** —— push 会命中 StackRouter 的+ * 「同 id 复用 + 移到栈顶」,把返回历史改写掉。+ */+export function navigateToCollabSession(+ navigator: CollabSessionNavigator,+ target: CollabSessionTarget,+ currentSessionId: string,+): CollabSessionNavigationPlan {+ const plan = planCollabSessionNavigation(+ navigator.getState(),+ target,+ currentSessionId,+ );+ if (plan === "popTo") navigator.dismissTo(target);+ else if (plan === "push") navigator.push(target);+ return plan;+}