Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 同账号 token 续期不再把主界面踢去登录页 (#3056)

Dashe8caa24a36f4
diff --git a/apps/desktop/src/main/__tests__/authSameOwnerRefreshUi.test.ts b/apps/desktop/src/main/__tests__/authSameOwnerRefreshUi.test.ts
new file mode 100644
index 0000000000..22e28a9794
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/authSameOwnerRefreshUi.test.ts
@@ -0,0 +1,66 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+/**
+ * Same-owner access-token refresh must not bounce the renderer to /login.
+ *
+ * 2026-08-20: packaged 0.1.56 logged `r:tapdb logout` →
+ * `App session is switching` → `LocalDbGate` remount every ~55 minutes. The
+ * trigger was `withCloudOwnerCommit` broadcasting `snapshotLoggedOutAuthState()`
+ * during Ghost projection repair on a stable cloud owner.
+ */
+describe('same-owner token refresh keeps the signed-in shell', () => {
+ const authSource = readFileSync(resolve(process.cwd(), 'src/main/authManager.ts'), 'utf8').replace(
+ /\r\n/g,
+ '\n',
+ );
+
+ it('does not broadcast a logged-out snapshot for same-owner Ghost repair', () => {
+ const start = authSource.indexOf('async function withCloudOwnerCommit');
+ const end = authSource.indexOf('async function withAccountFreeOwnerCommit', start);
+ const body = authSource.slice(start, end);
+
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ expect(body).toContain('if (ownerChanged) {\n notifyRendererAuthBoundaryPending();');
+ expect(body).toContain('enterOwnerChangeShellPending();');
+ expect(body).toContain('heldOwnerChangeShell = true;');
+ expect(body).toContain('if (heldOwnerChangeShell) leaveOwnerChangeShellPending();');
+ expect(body).toContain('releaseBoundary = beginAppSessionBoundary();');
+ expect(body.indexOf('notifyRendererAuthBoundaryPending();')).toBeLessThan(
+ body.indexOf('enterOwnerChangeShellPending();'),
+ );
+ expect(body.indexOf('if (ownerChanged)')).toBeLessThan(body.indexOf('notifyRendererAuthBoundaryPending();'));
+ expect(body.indexOf('notifyRendererAuthBoundaryPending();')).toBeLessThan(
+ body.indexOf('releaseBoundary = beginAppSessionBoundary();'),
+ );
+ // The unguarded call that remounted the shell every refresh cycle.
+ expect(body).not.toContain(
+ 'prepareTransition: async ({ ownerChanged }) => {\n notifyRendererAuthBoundaryPending();',
+ );
+ });
+
+ it('keeps canEnterApp true for IPC pending, but not a real owner-change shell', () => {
+ const start = authSource.indexOf('function snapshotAuthState(): AuthState {');
+ const end = authSource.indexOf('function snapshotLoggedOutAuthState', start);
+ const body = authSource.slice(start, end);
+
+ expect(body).toContain(
+ "canEnterApp: appSession.mode !== 'signed-out' && !isOwnerChangeShellPending()",
+ );
+ expect(body).not.toContain('!isAppSessionBoundaryPending()');
+ });
+
+ it('still fakes a signed-out snapshot for a real owner change or logout', () => {
+ const cloudStart = authSource.indexOf('async function withCloudOwnerCommit');
+ const cloudEnd = authSource.indexOf('async function withAccountFreeOwnerCommit', cloudStart);
+ const accountFreeStart = cloudEnd;
+ const accountFreeEnd = authSource.indexOf('async function recoverAccountFreeOwnerAtStartup', accountFreeStart);
+
+ expect(authSource.slice(cloudStart, cloudEnd)).toContain('notifyRendererAuthBoundaryPending();');
+ expect(authSource.slice(accountFreeStart, accountFreeEnd)).toContain(
+ 'notifyRendererAuthBoundaryPending();',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index cf8a495e2e..946f4a1a8c 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -297,6 +297,22 @@ let pendingAuthRealm: AuthRegion | null = null;
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
let refreshPromise: Promise<boolean> | null = null;
let sessionInvalidationPromise: Promise<void> | null = null;
+// Real owner change / logout: keep the renderer fail-closed even if a late
+// notifyRenderer() races the teardown. Same-owner Ghost repair must not set
+// this — that was the 55-minute /login flash.
+let ownerChangeShellPendingDepth = 0;
+
+function enterOwnerChangeShellPending(): void {
+ ownerChangeShellPendingDepth += 1;
+}
+
+function leaveOwnerChangeShellPending(): void {
+ ownerChangeShellPendingDepth = Math.max(0, ownerChangeShellPendingDepth - 1);
+}
+
+function isOwnerChangeShellPending(): boolean {
+ return ownerChangeShellPendingDepth > 0;
+}
/**
* 设备标识。默认绑定物理机(machineIdSync)。
*
@@ -860,6 +876,7 @@ async function withCloudOwnerCommit<T>(opts: {
return withGhostSkillProjectionReadOnlyOwner(opts.nextOwnerId, opts.commit);
}
let releaseBoundary: (() => void) | null = null;
+ let heldOwnerChangeShell = false;
// A same-owner projection repair tears down the owner-bound Ghost runtime but
// keeps the same mode/owner, so commitActiveAppSession's same-owner early
// return would NOT advance the owner generation — stale async work that
@@ -873,7 +890,14 @@ async function withCloudOwnerCommit<T>(opts: {
previousOwnerId: opts.previousOwnerId,
nextOwnerId: opts.nextOwnerId,
prepareTransition: async ({ ownerChanged }) => {
- notifyRendererAuthBoundaryPending();
+ // Same-owner Ghost repair (token refresh when the durable projection is
+ // unstable) is not a logout. Broadcasting snapshotLoggedOutAuthState()
+ // here bounced ProtectedRoute to /login every ~55 minutes.
+ if (ownerChanged) {
+ notifyRendererAuthBoundaryPending();
+ enterOwnerChangeShellPending();
+ heldOwnerChangeShell = true;
+ }
releaseBoundary = beginAppSessionBoundary();
if (ownerChanged) {
await opts.prepareTransition();
@@ -901,6 +925,7 @@ async function withCloudOwnerCommit<T>(opts: {
} finally {
const release = releaseBoundary as (() => void) | null;
release?.();
+ if (heldOwnerChangeShell) leaveOwnerChangeShellPending();
if (release) notifyRenderer();
}
if (committed) requestStableOwnerPostCommit('owner-commit');
@@ -929,6 +954,7 @@ async function withAccountFreeOwnerCommit(opts: {
}): Promise<void> {
let authCleared = opts.authAlreadyCleared ?? false;
let releaseBoundary: (() => void) | null = null;
+ let heldOwnerChangeShell = false;
// Same-owner account-free repair tears down the owner-bound Ghost runtime but
// keeps the same mode/owner, so commitActiveAppSession's same-owner early
// return would NOT advance the owner generation — stale async work that
@@ -966,6 +992,8 @@ async function withAccountFreeOwnerCommit(opts: {
nextOwnerId: opts.nextMode === 'local' ? LOCAL_DATA_OWNER_ID : null,
prepareTransition: async ({ ownerChanged }) => {
notifyRendererAuthBoundaryPending();
+ enterOwnerChangeShellPending();
+ heldOwnerChangeShell = true;
releaseBoundary = beginAppSessionBoundary();
if (ownerChanged) {
if (!authSessionTeardown) {
@@ -1034,6 +1062,7 @@ async function withAccountFreeOwnerCommit(opts: {
} finally {
const release = releaseBoundary as (() => void) | null;
release?.();
+ if (heldOwnerChangeShell) leaveOwnerChangeShellPending();
if (release && notify) notifyRenderer();
}
@@ -1695,7 +1724,9 @@ function snapshotAuthState(): AuthState {
mode: appSession.mode,
dataOwnerId: appSession.dataOwnerId,
ownerGeneration: appSession.generation,
- canEnterApp: appSession.mode !== 'signed-out' && !isAppSessionBoundaryPending(),
+ // IPC pending is not a logout. Real owner change / logout still holds the
+ // shell closed so a late notifyRenderer() cannot remount the outgoing owner.
+ canEnterApp: appSession.mode !== 'signed-out' && !isOwnerChangeShellPending(),
isAuthenticated: isCloudAuthenticated,
isCanary: currentUser !== null && canaryFlagStore.read(),
deviceId,
diff --git a/apps/desktop/src/renderer/components/auth/ProtectedRoute.tsx b/apps/desktop/src/renderer/components/auth/ProtectedRoute.tsx
index 7a530cf069..cbe9fbbf72 100644
--- a/apps/desktop/src/renderer/components/auth/ProtectedRoute.tsx
+++ b/apps/desktop/src/renderer/components/auth/ProtectedRoute.tsx
@@ -6,7 +6,10 @@ export function ProtectedRoute() {
const { canEnterApp, isInitializing, dataOwnerId } = useAuth();
if (isInitializing) return null;
+ // canEnterApp is false for a real signed-out session and while a real owner
+ // change is in flight. Same-owner token refresh keeps it true.
if (!canEnterApp) return <Navigate to="/login" replace />;
+
// Owner changes must remount the protected tree so transient New Maker
// drafts and other route-local state cannot leak across data namespaces.
return <Outlet key={dataOwnerId ?? 'signed-out'} />;
diff --git a/apps/desktop/src/renderer/components/auth/__tests__/ProtectedRoute.test.tsx b/apps/desktop/src/renderer/components/auth/__tests__/ProtectedRoute.test.tsx
new file mode 100644
index 0000000000..5dcb3cd32e
--- /dev/null
+++ b/apps/desktop/src/renderer/components/auth/__tests__/ProtectedRoute.test.tsx
@@ -0,0 +1,92 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const authState = vi.hoisted(() => ({
+ current: {
+ mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
+ isInitializing: false,
+ dataOwnerId: 'user-1' as string | null,
+ canEnterApp: true,
+ },
+}));
+
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => authState.current,
+}));
+
+import { ProtectedRoute } from '../ProtectedRoute';
+
+function renderAt(path: string) {
+ return render(
+ <MemoryRouter initialEntries={[path]}>
+ <Routes>
+ <Route path="/login" element={<div data-testid="login-page" />} />
+ <Route element={<ProtectedRoute />}>
+ <Route path="/" element={<div data-testid="app-shell" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+}
+
+describe('ProtectedRoute', () => {
+ afterEach(() => {
+ cleanup();
+ authState.current = {
+ mode: 'cloud',
+ isInitializing: false,
+ dataOwnerId: 'user-1',
+ canEnterApp: true,
+ };
+ });
+
+ it('keeps the shell mounted while same-owner refresh still allows entry', () => {
+ authState.current = {
+ mode: 'cloud',
+ isInitializing: false,
+ dataOwnerId: 'user-1',
+ canEnterApp: true,
+ };
+ renderAt('/');
+ expect(screen.getByTestId('app-shell')).toBeTruthy();
+ expect(screen.queryByTestId('login-page')).toBeNull();
+ });
+
+ it('leaves the shell during a real owner-change window', () => {
+ authState.current = {
+ mode: 'cloud',
+ isInitializing: false,
+ dataOwnerId: 'user-1',
+ canEnterApp: false,
+ };
+ renderAt('/');
+ expect(screen.getByTestId('login-page')).toBeTruthy();
+ expect(screen.queryByTestId('app-shell')).toBeNull();
+ });
+
+ it('sends a real signed-out session to login', () => {
+ authState.current = {
+ mode: 'signed-out',
+ isInitializing: false,
+ dataOwnerId: null,
+ canEnterApp: false,
+ };
+ renderAt('/');
+ expect(screen.getByTestId('login-page')).toBeTruthy();
+ expect(screen.queryByTestId('app-shell')).toBeNull();
+ });
+
+ it('lets local mode enter the app without a Cindy account', () => {
+ authState.current = {
+ mode: 'local',
+ isInitializing: false,
+ dataOwnerId: 'local-v1',
+ canEnterApp: true,
+ };
+ renderAt('/');
+ expect(screen.getByTestId('app-shell')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index 9e70a99ba3..1416c23c3f 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -31,7 +31,7 @@ import { GhostPluginPage } from '@/features/plugin/GhostPluginPage';
* GuestRoute (未登录)
* └── /login → LoginPage
*
- * ProtectedRoute (已登录) — 仅校验 isAuthenticated
+ * ProtectedRoute (已登录) — 校验 canEnterApp(真登出或换号窗口)
* └── LocalDbGate → 等 localDb.ensureReady(按 userId 切库)
* └── MainLayout → 主功能区
* ├── / → Navigate to /cc-agent