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。

perf(device-link): 降低共享任务列表轮询频率

david8c554050c071
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
index a2eb098434..dcafb58ad9 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
@@ -104,3 +104,51 @@ describe('sharedTask Main HTTP adapter', () => {
await expect(sharedTaskApi.close('sharedTask')).rejects.toThrow('account or region changed');
});
});
+
+// The host runtime and the guest directory both list shares; one request must
+// serve both, without ever surviving a write or crossing an account boundary.
+describe('sharedTask Main list reuse', () => {
+ const listed = (id: string) => ({ sharedTasks: [{ sharedTaskId: id, sessionId: 'session', ownerAccountId: 'owner', hostDeviceId: 'desktop', title: 'Task', revision: 1 }] });
+ const listCalls = () => http.mock.calls.filter(([path]) => path === '/api/device-link/shared-tasks').length;
+ it('shares concurrent and recent reads, but not across accounts or after a write', async () => {
+ state.key = 'list-reuse:1';
+ http.mockImplementation(async (path: string) => path.endsWith('/close') ? { sharedTaskId: 'a', status: 'closed' } : listed('a'));
+ const [first, second] = await Promise.all([sharedTaskApi.list(), sharedTaskApi.list()]);
+ expect(second).toBe(first);
+ await sharedTaskApi.list();
+ expect(listCalls()).toBe(1);
+ state.key = 'list-reuse:2';
+ await sharedTaskApi.list();
+ expect(listCalls()).toBe(2);
+ await sharedTaskApi.close('a');
+ await sharedTaskApi.list();
+ expect(listCalls()).toBe(3);
+ });
+ it('does not reuse a read that overlaps an in-flight write, nor a failed read', async () => {
+ state.key = 'list-reuse:3';
+ let finishClose!: () => void;
+ http.mockImplementation((path: string) => path.endsWith('/close')
+ ? new Promise(resolve => { finishClose = () => resolve({ sharedTaskId: 'a', status: 'closed' }); })
+ : Promise.resolve(listed('a')));
+ const closing = sharedTaskApi.close('a');
+ await sharedTaskApi.list();
+ finishClose(); await closing;
+ await sharedTaskApi.list();
+ expect(listCalls()).toBe(2);
+ state.key = 'list-reuse:4';
+ http.mockRejectedValueOnce(Object.assign(new Error('offline'), { code: 'NETWORK_ERROR' }));
+ await expect(sharedTaskApi.list()).rejects.toThrow('DEVICE_LINK_NOT_CONNECTED');
+ await expect(sharedTaskApi.list()).resolves.toHaveLength(1);
+ expect(listCalls()).toBe(4);
+ });
+ it('treats a cached list as stale after the clock moves backwards', async () => {
+ state.key = 'list-reuse:5';
+ http.mockResolvedValue(listed('a'));
+ await sharedTaskApi.list();
+ const now = vi.spyOn(Date, 'now').mockReturnValue(Date.now() - 3_600_000);
+ try {
+ await sharedTaskApi.list();
+ expect(listCalls()).toBe(2);
+ } finally { now.mockRestore(); }
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts
index 6a99135cd6..60aba87e70 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts
@@ -160,6 +160,57 @@ describe('task host sharedTask lifecycle', () => {
expect(api.close).toHaveBeenCalledWith('sharedTask');
expect(api.get).not.toHaveBeenCalled();
});
+ // Idle hosts stop polling the server; open shares and unconfirmed closures keep it.
+ it('needs server authority only while a share is open or a closure is unconfirmed', async () => {
+ serverDetail = { ...detail(), status: 'closed' };
+ await host.restore();
+ expect(host.needsAuthorityRefresh()).toBe(false);
+ // Another process archived a task; the server has not confirmed that closure.
+ records.set('archived', { sharedTaskId: 'archived', sessionId: 'old', terminal: true, snapshot: null });
+ await host.restore(false);
+ expect(host.needsAuthorityRefresh()).toBe(true);
+ await host.restore();
+ expect(host.needsAuthorityRefresh()).toBe(false);
+ serverDetail = detail();
+ await host.open('session');
+ expect(host.needsAuthorityRefresh()).toBe(true);
+ api.close.mockRejectedValueOnce(new Error('offline'));
+ await expect(host.close('sharedTask')).rejects.toThrow('offline');
+ expect(host.needsAuthorityRefresh()).toBe(true);
+ api.close.mockImplementation(async () => { serverDetail = { ...detail(2), status: 'closed', guests: [] }; });
+ await host.restore();
+ expect(api.close).toHaveBeenLastCalledWith('sharedTask');
+ expect(host.needsAuthorityRefresh()).toBe(false);
+ });
+ it('does not settle a share created while a list request was in flight', async () => {
+ serverDetail = { ...detail(), status: 'closed' };
+ await host.restore();
+ // The server built this list before the create committed; it returns after.
+ let finishList!: (items: unknown[]) => void;
+ api.list.mockImplementationOnce(() => new Promise(resolve => { finishList = resolve; }));
+ const restoring = host.restore();
+ await vi.waitFor(() => expect(finishList).toBeTypeOf('function'));
+ serverDetail = detail();
+ let finishGet!: () => void;
+ api.get.mockImplementationOnce(() => new Promise(resolve => { finishGet = () => resolve(serverDetail); }));
+ const opening = host.open('session');
+ await vi.waitFor(() => expect(finishGet).toBeTypeOf('function'));
+ finishList([]); await restoring;
+ finishGet(); await opening;
+ api.close.mockRejectedValueOnce(new Error('offline'));
+ await expect(host.close('sharedTask')).rejects.toThrow('offline');
+ // The unconfirmed close must keep the server retry scheduled.
+ expect(host.needsAuthorityRefresh()).toBe(true);
+ });
+ it('rechecks the server after a create whose response was lost', async () => {
+ serverDetail = { ...detail(), status: 'closed' };
+ await host.restore();
+ api.create.mockRejectedValueOnce(new Error('timeout'));
+ await expect(host.open('session')).rejects.toThrow('timeout');
+ expect(host.needsAuthorityRefresh()).toBe(true);
+ await host.restore();
+ expect(host.needsAuthorityRefresh()).toBe(false);
+ });
it('allows first sharing after an unshared task is archived and restored', async () => {
await host.closeLocallyForBoundary('session');
options.readSession = vi.fn(async (id) => ({ id, title: 'Task', status: 'archived' }));
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
index d9d6a66cd5..0d5275ff7b 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
@@ -4,6 +4,7 @@ type HostRecord = {
options: { creationState: unknown; isCurrent(): boolean; revoke(sharedTaskId: string, memberId?: string): void;
readSession(sessionId: string): Promise<{ id: string; source?: string | null } | null> };
restore: ReturnType<typeof vi.fn>;
+ needsAuthorityRefresh: ReturnType<typeof vi.fn>;
dispose: ReturnType<typeof vi.fn>;
closeLocallyForBoundary: ReturnType<typeof vi.fn>;
};
@@ -36,6 +37,7 @@ vi.mock('../sharedTaskDispatch.js', () => ({ setSharedTaskDispatchHost: state.di
vi.mock('../sharedTaskHost.js', () => ({
SharedTaskHost: class {
restore = vi.fn(async () => undefined);
+ needsAuthorityRefresh = vi.fn(() => false);
closeLocallyForBoundary = vi.fn(async () => ['sharedTask-a', 'sharedTask-b']);
// The real Host disposes each existing grant through this callback.
dispose = vi.fn(async () => { this.options.revoke('sharedTask-a'); });
@@ -54,7 +56,8 @@ import {
} from '../sharedTaskRuntime';
function start() {
- const client = { hasServerCapability: () => true, getStatus: () => 'online', start: vi.fn(), stop: vi.fn(), revoke: vi.fn() };
+ const client = { hasServerCapability: () => true, getStatus: () => 'online', getConnectionEpoch: () => 1,
+ start: vi.fn(), stop: vi.fn(), revoke: vi.fn() };
startSharedTaskRuntime({ client: client as never, revoke: client.revoke, changed: vi.fn() });
return client;
}
@@ -133,6 +136,36 @@ describe('shared runtime stable owner recommit', () => {
await closeSharedTaskForTask('session', {});
expect(state.journalClose).toHaveBeenCalledOnce();
});
+ // Every online Desktop runs this; idle hosts must not read the server each tick.
+ it('reads the server once per start or reconnect, then only while the host needs authority', async () => {
+ const relay = start();
+ const host = state.hosts[0];
+ const serverReads = () => host.restore.mock.calls.filter(([network]) => network).length;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(serverReads()).toBe(1);
+ expect(host.restore).toHaveBeenCalledTimes(13);
+ host.needsAuthorityRefresh.mockReturnValue(true);
+ await vi.advanceTimersByTimeAsync(35_000);
+ expect(serverReads()).toBe(3);
+ host.needsAuthorityRefresh.mockReturnValue(false);
+ // A reconnect that finished between ticks is never observed offline.
+ relay.getConnectionEpoch = () => 2;
+ host.restore.mockRejectedValueOnce(new Error('offline'));
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(serverReads()).toBe(4);
+ // A failed sync retries after the server interval, not on every local tick.
+ await vi.advanceTimersByTimeAsync(25_000);
+ expect(serverReads()).toBe(4);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(serverReads()).toBe(5);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(serverReads()).toBe(5);
+ // A clock set back an hour must not postpone the next needed read.
+ host.needsAuthorityRefresh.mockReturnValue(true);
+ vi.setSystemTime(Date.now() - 3_600_000);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(serverReads()).toBe(6);
+ });
it('reconciles profile-local terminal changes while relay is offline', async () => {
const relay = start();
relay.getStatus = () => 'connecting';
diff --git a/apps/desktop/src/main/device-link/sharedTaskApi.ts b/apps/desktop/src/main/device-link/sharedTaskApi.ts
index 0aa7785e9f..411f95946a 100644
--- a/apps/desktop/src/main/device-link/sharedTaskApi.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskApi.ts
@@ -1,10 +1,22 @@
-import { buildSharedTaskInvitationLink, createSharedTaskApi, parseSharedTaskInvitation, sharedTaskAccountName, SharedTaskScopeChangedError } from '@cindy/device-link';
+import { buildSharedTaskInvitationLink, createSharedTaskApi, parseSharedTaskInvitation, sharedTaskAccountName, SharedTaskScopeChangedError, type SharedTaskListItem } from '@cindy/device-link';
import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { getAccessToken, getActiveAuthRealm, getAuthState, getCurrentUserId } from '../authManager.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { serverApiFetch } from '../serverApiClient.js';
import { throwIpcError } from '../utils/ipcValidate.js';
+// The host runtime and the guest directory both read the same account list.
+// Concurrent and closely spaced reads share one request; any write, including
+// one still in flight, makes earlier lists unusable.
+const LIST_REUSE_MS = 5_000;
+let listWrites = 0;
+let listCache: { key: string; writes: number; settledAt: number | null; result: Promise<SharedTaskListItem[]> } | null = null;
+function trackListWrite<T>(method: string, work: () => Promise<T>): Promise<T> {
+ if (method === 'GET') return work();
+ listWrites++;
+ return work().finally(() => { listWrites++; });
+}
+
/** Main-owned adapter. Tokens remain inside the existing authenticated HTTP client. */
const accountApi = createSharedTaskApi({
captureScope() {
@@ -15,7 +27,7 @@ const accountApi = createSharedTaskApi({
},
async request(path, options) {
try {
- return await serverApiFetch<unknown>(path, {
+ return await trackListWrite(options.method, () => serverApiFetch<unknown>(path, {
method: options.method,
body: options.body,
// Executed before EACH physical attempt, including automatic token refresh.
@@ -30,7 +42,7 @@ const accountApi = createSharedTaskApi({
redactErrorDetails: true,
allowedRedactedErrorCodes: ['NOT_FOUND', 'CONFLICT', 'PERMISSION_DENIED', 'INVALID_PARAMS', 'RATE_LIMITED',
'SHARED_TASK_HOST_LIMIT', 'SHARED_TASK_JOIN_LIMIT', 'SHARED_TASK_GUEST_LIMIT', 'SHARED_TASK_SELF_JOIN'],
- });
+ }));
} catch (error) {
const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;
if (code === 'SHARED_TASK_HOST_LIMIT' || code === 'SHARED_TASK_JOIN_LIMIT' || code === 'SHARED_TASK_GUEST_LIMIT') {
@@ -49,6 +61,19 @@ const accountApi = createSharedTaskApi({
export const sharedTaskApi = {
...accountApi,
+ list(): Promise<SharedTaskListItem[]> {
+ // Signed-out or boundary callers fail inside the adapter, never from cache.
+ if (!getAuthState().isAuthenticated || isAppSessionBoundaryPending()) return accountApi.list();
+ const key = [activeOwnerScopeKey(), getActiveAuthRealm(), getClientEndpoint('deviceLinkApiBaseUrl')].join('\n');
+ const cached = listCache;
+ // A negative age means the clock moved backwards; treat that list as stale.
+ const age = cached?.settledAt == null ? 0 : Date.now() - cached.settledAt;
+ if (cached && cached.key === key && cached.writes === listWrites && age >= 0 && age < LIST_REUSE_MS) return cached.result;
+ const entry: NonNullable<typeof listCache> = { key, writes: listWrites, settledAt: null, result: accountApi.list() };
+ listCache = entry;
+ entry.result.then(() => { entry.settledAt = Date.now(); }, () => { if (listCache === entry) listCache = null; });
+ return entry.result;
+ },
async invite(sharedTaskId: string) {
const endpoint = getClientEndpoint('deviceLinkApiBaseUrl');
const result = await accountApi.invite(sharedTaskId);
@@ -74,11 +99,11 @@ export function captureSharedTaskBoundaryClose(ownerAccountId: string, region: R
const endpoint = getClientEndpoint('deviceLinkApiBaseUrl');
const api = createSharedTaskApi({
captureScope: () => ({ isCurrent: () => true }),
- request: (path, options) => serverApiFetch<unknown>(path, {
+ request: (path, options) => trackListWrite(options.method, () => serverApiFetch<unknown>(path, {
method: options.method, body: options.body, token, baseUrl: endpoint,
skipAutoRefresh: true, skipSessionInvalidation: true, timeoutMs: 3_000,
cache: 'no-store', redactErrorDetails: true, logLabel: '/api/device-link/shared-tasks',
- }),
+ })),
});
return (sharedTaskId: string) => api.close(sharedTaskId);
}
diff --git a/apps/desktop/src/main/device-link/sharedTaskHost.ts b/apps/desktop/src/main/device-link/sharedTaskHost.ts
index 32ddd9d7d3..888b3d9df8 100644
--- a/apps/desktop/src/main/device-link/sharedTaskHost.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskHost.ts
@@ -49,6 +49,11 @@ export class SharedTaskHost {
// Keep failed writes too: disposal must not report durability after a disk error.
private readonly closeWrites = new Map<string, Promise<void>>();
private readonly reconciliation = new Map<string, Map<string, () => void>>();
+ // Scheduling only: closed IDs the server has confirmed absent or closed.
+ private readonly settled = new Set<string>();
+ private journalIds: string[] = [];
+ private failedCreates = 0;
+ private listedAfterFailedCreates = 0;
constructor(private readonly options: SharedTaskHostOptions) {
const lifecycle: SharedTaskCreationState = options.creationState ?? { pending: new Map(), identities: new Map() };
this.creating = lifecycle.pending;
@@ -182,6 +187,10 @@ export class SharedTaskHost {
try {
created = await creating;
rememberCreated(created.sharedTaskId);
+ } catch (error) {
+ // A lost response may still have created a share this host never learned.
+ this.failedCreates++;
+ throw error;
} finally { this.creating.delete(creating); }
if (this.boundaryClosed || this.closedSessions.has(sessionId)) {
// The boundary drains this request, journals the identity and closes it
@@ -211,10 +220,23 @@ export class SharedTaskHost {
}
}
+ /**
+ * Whether server authority can still differ from this host: an active or
+ * pending share, or a local closure the server has not confirmed. Never
+ * grants or revokes access; it only decides whether the next restore polls.
+ */
+ needsAuthorityRefresh(): boolean {
+ if (this.creating.size || this.failedCreates !== this.listedAfterFailedCreates) return true;
+ for (const [id, entry] of this.entries) if (!this.closed.has(id) && entry.detail?.status === 'active') return true;
+ for (const id of [...this.closed, ...this.created.keys(), ...this.journalIds]) if (!this.settled.has(id)) return true;
+ return false;
+ }
+
async restore(allowNetwork = true): Promise<void> {
this.assertCurrent();
const journal = await this.options.journal.latest();
this.assertCurrent();
+ this.journalIds = journal.map((item) => item.sharedTaskId);
// Shared profile writers hand off terminal changes through the journal.
// Close access objects as well as the index so existing captures also expire.
for (const item of journal) if (item.terminal) this.revokeLocally(item.sharedTaskId);
@@ -235,6 +257,10 @@ export class SharedTaskHost {
}
}
if (!allowNetwork) return;
+ // Only IDs known before the list was requested can be judged by it; an ID
+ // learned mid-request may be missing from a list the server built earlier.
+ const candidates = [...this.journalIds, ...this.created.keys(), ...this.closed];
+ const failedCreates = this.failedCreates;
const active = await this.options.api.list();
this.assertCurrent();
const owned = active.filter((item) => item.ownerAccountId === this.options.ownerAccountId && item.hostDeviceId === this.options.hostDeviceId);
@@ -248,6 +274,11 @@ export class SharedTaskHost {
this.assertCurrent();
}
}
+ // An open share stays unsettled; the entry check keeps polling it.
+ const ownedIds = new Set(owned.map((item) => item.sharedTaskId));
+ for (const id of candidates) {
+ if (!ownedIds.has(id) && (this.closed.has(id) || !this.entries.has(id))) this.settled.add(id);
+ }
for (const item of owned) {
this.assertCurrent();
// Covers a create that reached the server but was never accepted/journaled
@@ -263,8 +294,11 @@ export class SharedTaskHost {
// Retry a previous explicit close that was persisted before connectivity
// failed. A process restart itself never closes an active sharedTask.
await this.options.api.close(item.sharedTaskId);
+ this.settled.add(item.sharedTaskId);
} else await this.refresh(item.sharedTaskId);
}
+ // The owned list above included any orphan of those failed creates.
+ this.listedAfterFailedCreates = failedCreates;
}
detail(sharedTaskId: string): SharedTaskDetail | null {
@@ -334,6 +368,7 @@ export class SharedTaskHost {
const closing = persisted.then(async () => {
this.assertCurrent();
await this.options.api.close(sharedTaskId);
+ this.settled.add(sharedTaskId);
});
this.options.revoke(sharedTaskId);
this.options.changed(sharedTaskId);
diff --git a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
index e0e120fd43..36b66a917a 100644
--- a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
@@ -17,6 +17,8 @@ import { SharedTaskHost, type SharedTaskCreationState } from './sharedTaskHost.j
import { setSharedTaskDispatchHost } from './sharedTaskDispatch.js';
const log = createLogger('shared-task');
+const LOCAL_JOURNAL_REFRESH_MS = 5_000;
+const SERVER_AUTHORITY_REFRESH_MS = 30_000;
interface Binding {
host: SharedTaskHost;
stop(): Promise<void>;
@@ -85,19 +87,43 @@ export function startSharedTaskRuntime(options: {
preservePeerLinks = true;
startSharedTaskRuntime(options);
};
+ // Server reads happen once per start or reconnect, then only while this host
+ // has a share or an unconfirmed closure. Guest arrival and the manage dialog
+ // still refresh a share immediately through the Host.
+ let syncRequested = true;
+ // The connection epoch also catches a reconnect that completed between ticks.
+ let seenConnectionEpoch: number | undefined;
+ let lastServerReadAt: number | undefined;
+ const serverReadDue = () => {
+ if (lastServerReadAt === undefined) return true;
+ const elapsed = Date.now() - lastServerReadAt;
+ // A clock set backwards must not postpone authority reads indefinitely.
+ return elapsed < 0 || elapsed >= SERVER_AUTHORITY_REFRESH_MS;
+ };
const refresh = async () => {
if (!current()) { rebindIfStable(); return; }
if (refreshing || !current()) return;
refreshing = true;
+ const online = options.client.hasServerCapability(SHARED_TASK_CAPABILITY) && options.client.getStatus() === 'online';
+ const connectionEpoch = options.client.getConnectionEpoch();
+ if (online && connectionEpoch !== seenConnectionEpoch) {
+ seenConnectionEpoch = connectionEpoch;
+ syncRequested = true;
+ lastServerReadAt = undefined;
+ }
+ const allowNetwork = online && serverReadDue() && (syncRequested || host.needsAuthorityRefresh());
try {
// Local terminal records must revoke captures even while HTTP/relay is down.
- await host.restore(options.client.hasServerCapability(SHARED_TASK_CAPABILITY) &&
- options.client.getStatus() === 'online');
+ await host.restore(allowNetwork);
+ if (allowNetwork) syncRequested = false;
+ }
+ catch { if (current()) log.debug('sharedTask authority refresh unavailable; retrying later'); }
+ finally {
+ if (allowNetwork) lastServerReadAt = Date.now();
+ refreshing = false;
}
- catch { if (current()) log.debug('sharedTask authority refresh unavailable; retrying on next tick'); }
- finally { refreshing = false; }
};
- const timer = setInterval(() => { void refresh(); }, 5_000);
+ const timer = setInterval(() => { void refresh(); }, LOCAL_JOURNAL_REFRESH_MS);
timer.unref?.();
binding = { host, dbEpoch: db.clientEpoch, database: db.client, creationState, ownerAccountId, region, current, rebindIfStable, stop() {
stopped = true;
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
index fca9b3650e..54b75eff7b 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
@@ -21,6 +21,7 @@ import { remoteProjectsStore, isRemoteDeviceMarkedDisconnected } from './remoteP
import { sharedTaskErrorKey } from './sharedTaskCompatibility';
import { closeOwnedSharedTask } from './closeOwnedSharedTask';
import { filterVisibleSharedTasks } from './sharedTaskVisibility';
+import { notifySharedTaskMembershipChanged } from './useSharedTaskTasks';
type Tab = 'join' | 'joined' | 'owned';
type Target = { sessionId: string; title: string; deviceId?: string; sharedTaskId?: string; guestId?: string; connect?: boolean };
@@ -232,6 +233,8 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
setConfirm(null); await loadDetail(snapshot.target); restore(confirmationOrigin.current);
} else {
await window.electronAPI.sharedTask.account({ action: 'leave', sharedTaskId: snapshot.item.sharedTaskId });
+ // A directory read already in flight may still list it; reread after.
+ notifySharedTaskMembershipChanged();
if (!current()) return;
const peer = sharedTaskHostPeer(snapshot.item.sharedTaskId, snapshot.item.hostDeviceId);
resetRemoteDataOwnerPushFence(peer);
@@ -249,6 +252,7 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
void run(async current => {
try {
const result = await window.electronAPI.sharedTask.account({ action: 'join', invitation: invitation.trim(), displayName: sharedTaskAccountName(user?.name) }) as { sharedTaskId: string };
+ notifySharedTaskMembershipChanged();
if (!current()) return;
const joinedDetail = await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId: result.sharedTaskId }) as SharedTaskDetail;
if (!current()) return;
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskExitDialog.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskExitDialog.tsx
index 37ddce0369..0eed71c35f 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTaskExitDialog.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskExitDialog.tsx
@@ -8,6 +8,7 @@ import { toast } from '@/lib/toast';
import { remoteProjectsStore } from './remoteProjectsStore';
import { sharedTaskErrorKey } from './sharedTaskCompatibility';
import { closeOwnedSharedTask } from './closeOwnedSharedTask';
+import { notifySharedTaskMembershipChanged } from './useSharedTaskTasks';
export type SharedTaskExitTarget =
| { kind: 'close'; sharedTaskId: string; title: string; hostDeviceId?: string }
@@ -41,6 +42,8 @@ export function SharedTaskExitDialog({ target, onDismiss, onComplete }: {
try {
if (target.kind === 'leave') {
await window.electronAPI.sharedTask.account({ action: 'leave', sharedTaskId: target.sharedTaskId });
+ // A directory read already in flight may still list it; reread after.
+ notifySharedTaskMembershipChanged();
} else {
const closed = await closeOwnedSharedTask(target.sharedTaskId, target.hostDeviceId, current);
if (!current()) return;
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsx
index 5ef4c2e066..efe17f104f 100644
--- a/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsx
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsx
@@ -4,13 +4,13 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { sharedTaskHostPeer } from '@cindy/device-link';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
-import { useSharedTaskTasks } from '../useSharedTaskTasks';
+import { notifySharedTaskMembershipChanged, useSharedTaskTasks } from '../useSharedTaskTasks';
const state = vi.hoisted(() => ({
account: vi.fn(), openLink: vi.fn(), closeLink: vi.fn(), invoke: vi.fn(),
subscribe: vi.fn(), unsubscribe: vi.fn(), setSessions: vi.fn(), removeDevice: vi.fn(),
disconnected: vi.fn(), bind: vi.fn(), reset: vi.fn(),
- rawSessions: vi.fn(),
+ rawSessions: vi.fn(), status: undefined as undefined | ((state: { status: string }) => void),
}));
vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ isAuthenticated: true, dataOwnerId: 'guest', dataOwnerRecoveryEpoch: 0 }) }));
vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { findById: vi.fn() } }));
@@ -36,6 +36,7 @@ beforeEach(() => {
Object.assign(window, { electronAPI: { sharedTask: { account: state.account }, deviceLink: {
openLink: state.openLink, closeLink: state.closeLink, invoke: state.invoke,
subscribe: state.subscribe, unsubscribe: state.unsubscribe,
+ onStatusChanged: (listener: typeof state.status) => { state.status = listener; return () => { state.status = undefined; }; },
} } });
root = createRoot(document.createElement('div'));
});
@@ -100,7 +101,7 @@ it('retries a failed disabled membership leave on the next authority poll', asyn
await render();
expect(state.closeLink).not.toHaveBeenCalled();
expect(state.setSessions).not.toHaveBeenCalled();
- await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
expect(state.account.mock.calls.filter(([command]) => command.action === 'leave')).toHaveLength(2);
expect(state.closeLink).toHaveBeenCalledExactlyOnceWith(peer);
expect(state.setSessions).not.toHaveBeenCalled();
@@ -127,3 +128,22 @@ it('does not clean up a new account after a late disabled membership leave respo
expect(state.removeDevice).not.toHaveBeenCalled();
expect(state.setSessions).not.toHaveBeenCalled();
});
+
+it('rereads the guest directory on join, reconnect and return instead of a fixed 5 s poll', async () => {
+ state.invoke.mockResolvedValue({ id: task.sessionId, source: 'desktop' });
+ const lists = () => state.account.mock.calls.filter(([command]) => command.action === 'list').length;
+ await render();
+ await act(async () => vi.advanceTimersByTimeAsync(29_999));
+ expect(lists()).toBe(1);
+ await act(async () => { notifySharedTaskMembershipChanged(); });
+ expect(lists()).toBe(2);
+ await act(async () => { state.status?.({ status: 'online' }); });
+ expect(lists()).toBe(3);
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });
+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });
+ await act(async () => vi.advanceTimersByTimeAsync(10 * 60_000));
+ expect(lists()).toBe(3);
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' });
+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });
+ expect(lists()).toBe(4);
+});
diff --git a/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts
index fc7bdbf490..6fba0cca6f 100644
--- a/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts
+++ b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts
@@ -1,5 +1,5 @@
import { useEffect } from 'react';
-import { sharedTaskHostPeer, parseSharedTaskPeer, type SharedTaskListItem } from '@cindy/device-link';
+import { sharedTaskHostPeer, parseSharedTaskPeer, startSharedTaskListPoller, type SharedTaskListItem } from '@cindy/device-link';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { useAuth } from '@/contexts/AuthContext';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
@@ -8,6 +8,15 @@ import { remoteProjectsStore } from './remoteProjectsStore';
import { bindSharedTaskPushOwner, resetRemoteDataOwnerPushFence } from '@/lib/remoteDataOwnerPushFence';
import { leaveHiddenSharedTask } from './sharedTaskVisibility';
+const membershipChangedEvent = 'cindy:shared-task-membership-changed';
+// Dispatched by notifySharedTaskEnded when a host revokes this guest.
+const accessEndedEvent = 'cindy:shared-task-access-ended';
+
+/** Rereads the guest directory now, e.g. after joining on this device. */
+export function notifySharedTaskMembershipChanged(): void {
+ window.dispatchEvent(new Event(membershipChangedEvent));
+}
+
/** SharedTask peers have their own authority list, independent of the user's device directory. */
export function useSharedTaskTasks(): void {
const { isAuthenticated, dataOwnerId, dataOwnerRecoveryEpoch } = useAuth();
@@ -17,14 +26,12 @@ export function useSharedTaskTasks(): void {
let disposed = false;
const owner = getDataOwnerGeneration();
const currentOwner = () => !disposed && isDataOwnerGenerationCurrent(owner);
- let busy = false;
const linked = new Map<string, string>();
- const poll = async () => {
- if (busy || !currentOwner()) return;
- busy = true;
+ const poll = async (): Promise<number | null> => {
+ if (!currentOwner()) return null;
try {
const sharedTasks = await window.electronAPI.sharedTask.account({ action: 'list' }) as SharedTaskListItem[];
- if (!currentOwner()) return;
+ if (!currentOwner()) return null;
const current = new Set(sharedTasks.map((sharedTask) => sharedTaskHostPeer(sharedTask.sharedTaskId, sharedTask.hostDeviceId)));
for (const id of remoteProjectsStore.getAllDeviceIds()) {
if (!parseSharedTaskPeer(id) || current.has(id)) continue;
@@ -34,7 +41,7 @@ export function useSharedTaskTasks(): void {
void window.electronAPI.deviceLink.closeLink(id);
}
for (const sharedTask of sharedTasks) {
- if (!currentOwner()) return;
+ if (!currentOwner()) return null;
const peer = sharedTaskHostPeer(sharedTask.sharedTaskId, sharedTask.hostDeviceId);
try {
const known = remoteProjectsStore.getDeviceSessions(peer).find(session => session.id === sharedTask.sessionId);
@@ -46,13 +53,13 @@ export function useSharedTaskTasks(): void {
bindSharedTaskPushOwner(peer, sharedTask.ownerAccountId);
if (!linked.has(peer)) {
await window.electronAPI.deviceLink.openLink(peer);
- if (!currentOwner()) return;
+ if (!currentOwner()) return null;
await window.electronAPI.deviceLink.subscribe(peer, ['session:' + sharedTask.sessionId]);
- if (!currentOwner()) return;
+ if (!currentOwner()) return null;
linked.set(peer, sharedTask.sessionId);
}
const session = await window.electronAPI.deviceLink.invoke(peer, 'local-db:sessions:get', [sharedTask.sessionId]) as Session;
- if (!currentOwner()) return;
+ if (!currentOwner()) return null;
if (session?.id !== sharedTask.sessionId) throw new Error('SharedTask task mismatch');
if (!CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) {
await leaveHiddenSharedTask(sharedTask, currentOwner);
@@ -61,18 +68,30 @@ export function useSharedTaskTasks(): void {
}
remoteProjectsStore.setDeviceSessions(peer, sharedTask.title, [session]);
} catch {
- if (!currentOwner()) return;
+ if (!currentOwner()) return null;
remoteProjectsStore.markDeviceDisconnected(peer);
}
}
- } catch { /* No authority response is not evidence of departure. */ }
- finally { busy = false; }
+ return sharedTasks.length;
+ } catch { return null; /* No authority response is not evidence of departure. */ }
};
- void poll();
- const timer = setInterval(() => { void poll(); }, 5_000);
+ const poller = startSharedTaskListPoller({ poll, isVisible: () => document.visibilityState !== 'hidden' });
+ const refresh = () => poller.refresh();
+ const visibilityChanged = () => poller.visibilityChanged();
+ // Window focus is deliberately ignored: switching windows is too frequent.
+ document.addEventListener('visibilitychange', visibilityChanged);
+ window.addEventListener(membershipChangedEvent, refresh);
+ window.addEventListener(accessEndedEvent, refresh);
+ const offStatus = window.electronAPI.deviceLink.onStatusChanged((state) => {
+ if (state.status === 'online') refresh();
+ });
return () => {
disposed = true;
- clearInterval(timer);
+ poller.dispose();
+ document.removeEventListener('visibilitychange', visibilityChanged);
+ window.removeEventListener(membershipChangedEvent, refresh);
+ window.removeEventListener(accessEndedEvent, refresh);
+ offStatus();
for (const [peer, sessionId] of linked) {
if (!isDataOwnerGenerationCurrent(owner)) break;
void window.electronAPI.deviceLink.unsubscribe(peer, ['session:' + sessionId]).catch(() => undefined);
diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsx
index f5f483732e..0475753f04 100644
--- a/apps/mobile/app/shared-session.tsx
+++ b/apps/mobile/app/shared-session.tsx
@@ -12,6 +12,7 @@ import { goBackGuarded } from '@/utils/backGuard';
import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { useSharedTaskApi } from '@/device-link/useSharedTaskApi';
+import { notifySharedTaskMembershipChanged } from '@/device-link/sharedTaskMembershipSignal';
import { filterVisibleSharedTasks } from '@/device-link/sharedTaskVisibility';
import { sharedTaskErrorKey } from '@/device-link/sharedTaskCompatibility';
import { isSharedTaskGone } from '@/device-link/sharedTaskAccessWatch';
@@ -230,6 +231,7 @@ export default function SharedSessionScreen() {
const parsed = parseSharedTaskInvitation(input, DEVICE_LINK_API_BASE_URL);
if (!parsed.ok) { setNotice(t(parsed.reason === 'different-server' ? 'sharedTask.invitationDifferentServer' : 'sharedTask.invalid')); return; }
const joined = await api.join(parsed.invitation, sharedTaskAccountName(user?.name));
+ notifySharedTaskMembershipChanged();
if (!current()) return;
const detail = await api.get(joined.sharedTaskId);
if (!current()) return;
@@ -292,6 +294,7 @@ export default function SharedSessionScreen() {
failed.push(item);
}
}
+ if (closed.size) notifySharedTaskMembershipChanged();
if (!current()) return;
setOwned((value) => value.filter((item) => !closed.has(item.sharedTaskId)));
const failedCount = failed.length;
@@ -299,6 +302,7 @@ export default function SharedSessionScreen() {
}, true, { items: items.map((item) => item.title + ' · ' + deviceName(item.hostDeviceId)), note: t('sharedTask.closeAllScopeNote') });
const leave = () => confirm(t('sharedTask.leaveTitle'), t('sharedTask.leaveBody'), t('sharedTask.leaveKeep'), t('sharedTask.leave'), async (current) => {
await api.leave(guestId!);
+ notifySharedTaskMembershipChanged();
if (!current()) return;
if (guestTarget) { link.closeLink(guestTarget); remoteSessionStore.removeDevice(guestTarget); }
router.replace('/devices');
@@ -306,6 +310,7 @@ export default function SharedSessionScreen() {
const taskCard = <View style={styles.taskRow}><FileText size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.taskTitle}>{title}</Text><Text style={styles.metadata}>{task?.deviceLinkDeviceName ?? t('sharedTask.runsOnHostDevice')}</Text></View></View>;
const leaveListed = (item: SharedTaskListItem) => confirm(t('sharedTask.leaveTitle'), t('sharedTask.leaveBody'), t('sharedTask.leaveKeep'), t('sharedTask.leave'), async current => {
await api.leave(item.sharedTaskId);
+ notifySharedTaskMembershipChanged();
if (!current()) return;
const target = sharedTaskHostPeer(item.sharedTaskId, item.hostDeviceId);
link.closeLink(target); remoteSessionStore.removeDevice(target);
diff --git a/apps/mobile/src/__tests__/useSharedTasks.test.tsx b/apps/mobile/src/__tests__/useSharedTasks.test.tsx
index 3f2222eb8e..01a14fb9d8 100644
--- a/apps/mobile/src/__tests__/useSharedTasks.test.tsx
+++ b/apps/mobile/src/__tests__/useSharedTasks.test.tsx
@@ -3,6 +3,7 @@ import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { useSharedTasks } from '../device-link/useSharedTasks';
+import { notifySharedTaskMembershipChanged } from '../device-link/sharedTaskMembershipSignal';
import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { sharedTaskHostPeer, type SharedTaskListItem } from '@cindy/device-link';
import type { RemoteSession } from '@/session/types';
@@ -14,7 +15,15 @@ const state = vi.hoisted(() => ({
api: { list: vi.fn<() => Promise<SharedTaskListItem[]>>(async () => []), leave: vi.fn() },
revoked: vi.fn(),
store: { getSessions: vi.fn<() => RemoteSession[]>(() => []), removeDevice: vi.fn(), setDeviceSessions: vi.fn() },
+ appState: 'active', appStateListener: undefined as undefined | (() => void),
}));
+vi.mock('react-native', () => ({ AppState: {
+ get currentState() { return state.appState; },
+ addEventListener: (_: string, listener: () => void) => {
+ state.appStateListener = listener;
+ return { remove: () => { state.appStateListener = undefined; } };
+ },
+} }));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => state.auth }));
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => state.link }));
vi.mock('@/device-link/useSharedTaskApi', () => ({ useSharedTaskApi: () => state.api }));
@@ -32,6 +41,7 @@ beforeEach(() => {
state.auth.isAuthenticated = true; state.auth.accountGeneration = 1;
setMobileAuthOwner('owner');
state.link.status = 'online'; state.link.sharedTaskAvailable = false;
+ state.appState = 'active';
root = createRoot(document.createElement('div'));
});
const owned = { sharedTaskId: 'owned', sessionId: 'owned-task', ownerAccountId: 'owner', hostDeviceId: 'desktop', title: 'My share', revision: 1 };
@@ -48,7 +58,7 @@ it('discovers owner shares without opening guest links or requiring remote contr
state.link.status = 'online'; state.api.list.mockRejectedValue(new Error('offline')); await render();
expect(ownedTasks).toEqual([confirmedOwned]);
state.api.list.mockResolvedValue([]);
- await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ await act(async () => vi.advanceTimersByTimeAsync(60_000));
expect(ownedTasks).toEqual([]);
expect(state.store.removeDevice).not.toHaveBeenCalled();
expect(state.link.closeLink).not.toHaveBeenCalled();
@@ -85,7 +95,7 @@ it('retries membership cleanup on the next restore poll after a leave failure',
await render();
expect(state.api.leave).toHaveBeenCalledTimes(1);
expect(state.store.setDeviceSessions).not.toHaveBeenCalled();
- await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
expect(state.api.leave).toHaveBeenCalledTimes(2);
expect(state.link.closeLink).toHaveBeenCalledWith(sharedTaskHostPeer('joined', 'desktop'));
});
@@ -120,7 +130,7 @@ it('hides the previous account shares and ignores its late list response', async
await render(); expect(ownedTasks).toEqual([confirmedOwned]);
let finish!: (value: SharedTaskListItem[]) => void;
state.api.list.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
- await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
setMobileAuthOwner('other'); state.auth.accountGeneration++;
state.api.list.mockResolvedValue([]); await render();
expect(ownedTasks).toEqual([]);
@@ -150,7 +160,7 @@ it('keeps an offline unknown share hidden and resumes ordinary discovery after s
state.link.invoke.mockRejectedValueOnce(new Error('offline'));
await render(); expect(ownedTasks).toEqual([]);
state.link.invoke.mockResolvedValue({ id: owned.sessionId });
- await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
expect(ownedTasks).toEqual([{ ...owned, source: null }]);
expect(state.link.openLink).not.toHaveBeenCalled();
});
@@ -169,7 +179,7 @@ it('does not poll an old relay, resumes after upgrade, and pauses without deleti
expect(state.api.list).not.toHaveBeenCalled();
state.link.sharedTaskAvailable = true; await render();
expect(state.api.list).toHaveBeenCalledTimes(1);
- await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ await act(async () => vi.advanceTimersByTimeAsync(60_000));
expect(state.api.list).toHaveBeenCalledTimes(2);
state.link.status = 'connecting'; state.link.sharedTaskAvailable = undefined; await render();
await act(async () => vi.advanceTimersByTimeAsync(15_000));
@@ -177,3 +187,17 @@ it('does not poll an old relay, resumes after upgrade, and pauses without deleti
expect(state.store.removeDevice).not.toHaveBeenCalled();
expect(state.link.closeLink).not.toHaveBeenCalled();
});
+it('pauses in the background and rereads on return or after joining, not every 5 s', async () => {
+ state.link.sharedTaskAvailable = true;
+ await render();
+ await act(async () => vi.advanceTimersByTimeAsync(59_999));
+ expect(state.api.list).toHaveBeenCalledTimes(1);
+ await act(async () => { notifySharedTaskMembershipChanged(); });
+ expect(state.api.list).toHaveBeenCalledTimes(2);
+ state.appState = 'background'; state.appStateListener?.();
+ await act(async () => vi.advanceTimersByTimeAsync(10 * 60_000));
+ expect(state.api.list).toHaveBeenCalledTimes(2);
+ state.appState = 'active';
+ await act(async () => { state.appStateListener?.(); });
+ expect(state.api.list).toHaveBeenCalledTimes(3);
+});
diff --git a/apps/mobile/src/device-link/sharedTaskMembershipSignal.ts b/apps/mobile/src/device-link/sharedTaskMembershipSignal.ts
new file mode 100644
index 0000000000..621820aa47
--- /dev/null
+++ b/apps/mobile/src/device-link/sharedTaskMembershipSignal.ts
@@ -0,0 +1,11 @@
+const listeners = new Set<() => void>();
+
+/** Rereads the shared-task directory now, e.g. after joining or leaving on this phone. */
+export function notifySharedTaskMembershipChanged(): void {
+ for (const listener of listeners) listener();
+}
+
+export function onSharedTaskMembershipChanged(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+}
diff --git a/apps/mobile/src/device-link/useLeaveSharedTask.ts b/apps/mobile/src/device-link/useLeaveSharedTask.ts
index 1ebf416b7b..a31b1ed457 100644
--- a/apps/mobile/src/device-link/useLeaveSharedTask.ts
+++ b/apps/mobile/src/device-link/useLeaveSharedTask.ts
@@ -10,6 +10,7 @@ import { useSharedTaskApi } from './useSharedTaskApi';
import { sharedTaskErrorKey } from './sharedTaskCompatibility';
import { markDeviceAccessRevoked } from './accessRevoked';
import { revokedDevicesStore } from './revokedDevicesStore';
+import { notifySharedTaskMembershipChanged } from './sharedTaskMembershipSignal';
/** Exit directly from task details; cancelling never navigates or reloads the task. */
export function useLeaveSharedTask({ deviceId, enabled, onLeft, onError }: {
@@ -45,6 +46,8 @@ export function useLeaveSharedTask({ deviceId, enabled, onLeft, onError }: {
if (!accepted || !current() || revokedDevicesStore.has(deviceId)) return;
setBusy(true);
await api.leave(peer.sharedTaskId);
+ // A directory read already in flight may still list it; reread after.
+ notifySharedTaskMembershipChanged();
if (!current()) return;
markDeviceAccessRevoked(deviceId);
closeLink(deviceId);
diff --git a/apps/mobile/src/device-link/useSharedTasks.ts b/apps/mobile/src/device-link/useSharedTasks.ts
index ffe13632a5..89b8f807f1 100644
--- a/apps/mobile/src/device-link/useSharedTasks.ts
+++ b/apps/mobile/src/device-link/useSharedTasks.ts
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
-import { isSharedTaskPeer, sharedTaskHostPeer, type SharedTaskListItem } from '@cindy/device-link';
+import { AppState } from 'react-native';
+import { isSharedTaskPeer, sharedTaskHostPeer, startSharedTaskListPoller, type SharedTaskListItem } from '@cindy/device-link';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { useAuth } from '@/auth/AuthContext';
import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
@@ -8,6 +9,7 @@ import type { RemoteSession } from '@/session/types';
import { useDeviceLink } from './DeviceLinkContext';
import { useSharedTaskApi } from './useSharedTaskApi';
import { filterVisibleSharedTasks, leaveHiddenSharedTask } from './sharedTaskVisibility';
+import { onSharedTaskMembershipChanged } from './sharedTaskMembershipSignal';
/** Shared tasks have their own account authority list, separate from paired devices. */
export function useSharedTasks(): readonly SharedTaskListItem[] {
@@ -16,21 +18,20 @@ export function useSharedTasks(): readonly SharedTaskListItem[] {
const { openLink, closeLink, invoke, status, sharedTaskAvailable } = useDeviceLink();
const [owned, setOwned] = useState<{ owner: ReturnType<typeof getMobileAuthOwner>; tasks: SharedTaskListItem[] } | null>(null);
useEffect(() => {
+ // Reconnecting reruns this effect, which reads immediately.
if (!isAuthenticated || status !== 'online' || sharedTaskAvailable !== true) return;
const owner = getMobileAuthOwner();
let disposed = false;
- let busy = false;
const current = () => !disposed && isMobileAuthOwnerCurrent(owner);
- const poll = async () => {
- if (busy || !current()) return;
- busy = true;
+ const poll = async (): Promise<number | null> => {
+ if (!current()) return null;
try {
const all = await api.list();
- if (!current()) return;
+ if (!current()) return null;
const visibleOwned = await filterVisibleSharedTasks(
all.filter(task => task.ownerAccountId === owner.accountId), owner.accountId, { openLink, closeLink, invoke }, current, api.leave,
);
- if (!current()) return;
+ if (!current()) return null;
setOwned({ owner, tasks: visibleOwned });
const tasks = all.filter(task => task.ownerAccountId !== owner.accountId);
const peers = new Set(tasks.map((task) => sharedTaskHostPeer(task.sharedTaskId, task.hostDeviceId)));
@@ -42,7 +43,7 @@ export function useSharedTasks(): readonly SharedTaskListItem[] {
}
}
for (const task of tasks) {
- if (!current()) return;
+ if (!current()) return null;
const peer = sharedTaskHostPeer(task.sharedTaskId, task.hostDeviceId);
try {
const known = remoteSessionStore.getSessions().find(session => session.id === task.sessionId && session.deviceLinkDeviceId === peer);
@@ -51,9 +52,9 @@ export function useSharedTasks(): readonly SharedTaskListItem[] {
continue;
}
await openLink(peer);
- if (!current()) return;
+ if (!current()) return null;
const session = await invoke<RemoteSession>(peer, 'local-db:sessions:get', [task.sessionId]);
- if (!current()) return;
+ if (!current()) return null;
if (session.id !== task.sessionId) continue;
if (!CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) {
await leaveHiddenSharedTask(task, closeLink, api.leave, current);
@@ -62,12 +63,18 @@ export function useSharedTasks(): readonly SharedTaskListItem[] {
remoteSessionStore.setDeviceSessions(peer, task.title, [session]);
} catch { /* Keep offline history; only the authority list removes membership. */ }
}
- } catch { /* A transient authority failure is not evidence of departure. */ }
- finally { busy = false; }
+ return all.length;
+ } catch { return null; /* A transient authority failure is not evidence of departure. */ }
+ };
+ const poller = startSharedTaskListPoller({ poll, isVisible: () => AppState.currentState === 'active' });
+ const offMembership = onSharedTaskMembershipChanged(() => poller.refresh());
+ const subscription = AppState.addEventListener('change', () => poller.visibilityChanged());
+ return () => {
+ disposed = true;
+ poller.dispose();
+ offMembership();
+ subscription.remove();
};
- void poll();
- const timer = setInterval(() => { void poll(); }, 5_000);
- return () => { disposed = true; clearInterval(timer); };
}, [accountGeneration, api, closeLink, invoke, isAuthenticated, openLink, sharedTaskAvailable, status]);
return isAuthenticated && owned && isMobileAuthOwnerCurrent(owned.owner) ? owned.tasks : [];
}
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index 621c321cbd..a63ff6f51c 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -63,7 +63,8 @@
- 房主设备的 relay 连接确认离线后有 60 秒重连宽限,期间重连保留共享、邀请与成员关系;持续离线超过宽限后由下一轮服务端扫描关闭(正常情况下确认离线后 60–90 秒)。关闭后重新上线不会恢复旧共享,需显式重新开启并发送新邀请。主动关闭与登出的显式关闭请求不等待宽限。已由新连接接管的旧连接退出不算离线;TTL 内短暂网络抖动不承诺立即判定。
- 服务端是成员关系权威;主机保存恢复与关闭记录。迟到响应、旧快照、缓存和重连不能恢复已撤销访问。
- 访客断线保留成员关系,重连后可继续访问仍有效的共享;不能影响其他访客或同账号远控。
-- 正常断开触发关闭;relay 崩溃、路由过期或关闭落库失败由服务端每 30 秒扫描补偿。访客当前通过约 5 秒轮询更新界面;服务端授权在关闭提交后立即失效。
+- 正常断开触发关闭;relay 崩溃、路由过期或关闭落库失败由服务端每 30 秒扫描补偿。服务端授权在关闭提交后立即失效。
+- 共享目录轮询(2026-10-22 起,降低空闲请求):Desktop 与 Mobile 的共享目录在窗口隐藏或 App 退到后台时暂停;目录为空时约 60 秒、有共享时约 30 秒读取一次;本机加入或退出共享、回到前台(距上次读取满 10 秒)、重新连上服务器时立即读取,Mobile 在本机批量关闭共享后、Desktop 在访问被结束时也立即读取。Desktop 只看窗口是否可见,不因窗口获得焦点而读取。另一台设备上加入的共享最长约 60 秒后出现;任务内容仍由房主实时推送,不受此间隔影响。Desktop 主进程内同时或 5 秒内的目录读取合并为一次;本机发出的共享写请求(开启、加入、退出、移除、关闭)会使之前的结果失效,其他设备的写入不在此列;缓存按账号、区域与服务端地址隔离,系统时间回拨时视为过期。
- 不承诺撤回访客已经看到或下载的内容。
## 实现约束
@@ -76,7 +77,7 @@
- Agent/模型/推理设置的房主专属限制由房主 Desktop 执行,生效需要房主升级;新版访客界面也禁用修改入口。旧访客连接新版房主时,设置请求沿用现有权限错误返回;不修改 wire 格式、同账号 allowlist 或服务端成员关系。
- 新协议以能力协商开放;缺少能力提示升级。两区域独立,不默认跨区域加入。
- 关闭记录必须落入原 profile 的 journal 后才能释放数据库;本地同步撤权,服务端失败下次恢复重试。
-- 同一 profile 的非 relay 持有实例归档/删除任务,也必须写入该 profile 的共享关闭记录,并以操作开始时捕获的账号凭证尝试关闭服务端共享。Host 在既有 5 秒刷新周期先消化本地关闭记录、使现有授权捕获失效,再查询服务端;relay 离线或服务端读取失败不能跳过本地撤权。此机制只关闭对应共享,不重启 relay 或影响其他任务。
+- 同一 profile 的非 relay 持有实例归档/删除任务,也必须写入该 profile 的共享关闭记录,并以操作开始时捕获的账号凭证尝试关闭服务端共享。Host 在既有 5 秒刷新周期先消化本地关闭记录、使现有授权捕获失效(只读本地数据库,不联网);relay 离线或服务端读取失败不能跳过本地撤权。服务端只在启动或每次 relay 重新连接(按连接代次判断)后读取一次,之后仅当本机有活跃或创建中的共享、有服务端尚未确认的关闭、或有创建请求失败(响应可能丢失)尚未被之后的列表核对时,每 30 秒读取一次;只有列表请求发出前已知的共享 ID 才会据该列表被视为已确认;访客连接、打开管理窗口与移除成员仍立即刷新对应共享。此机制只关闭对应共享,不重启 relay 或影响其他任务。
- 覆盖式任务文件导入属于旧任务的终态变更:被替换的旧任务图及其共享关闭记录在同一数据库事务提交,失败一起回滚;成功后再通知本机共享运行时撤权。即使成功回执丢失或进程切换,持有 relay 的实例仍可从持久记录完成关闭,新导入任务不继承旧共享。
- 登出时等待已发出的创建请求收尾,迟到的创建 ID 也必须先落关闭记录;在线关闭仅使用退出账号的固定凭证与端点,不刷新或影响新账号。
- 移除请求未获确认前暂停该成员访问;网络失败须以服务端状态恢复。临时暂停或同账号新增设备造成的旧授权失效返回可重试错误,只有确认撤权才从访客端移除任务。
diff --git a/packages/device-link/src/__tests__/sharedTaskListPoller.test.ts b/packages/device-link/src/__tests__/sharedTaskListPoller.test.ts
new file mode 100644
index 0000000000..6b8b413cb4
--- /dev/null
+++ b/packages/device-link/src/__tests__/sharedTaskListPoller.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { startSharedTaskListPoller } from '../sharedTaskListPoller.js';
+
+// Guards the request budget of the guest directory that every signed-in
+// Desktop and phone runs; a 5 s fixed poll here overloaded auth on 2026-10-22.
+let visible: boolean;
+let poll: ReturnType<typeof vi.fn<() => Promise<number | null>>>;
+const reads = () => poll.mock.calls.length;
+beforeEach(() => {
+ vi.useFakeTimers();
+ visible = true;
+ poll = vi.fn(async () => 0);
+});
+afterEach(() => { vi.useRealTimers(); });
+
+it('reads every 60 s while empty, every 30 s with shares, and keeps the cadence on failure', async () => {
+ const poller = startSharedTaskListPoller({ poll, isVisible: () => visible });
+ await vi.advanceTimersByTimeAsync(59_999);
+ expect(reads()).toBe(1);
+ poll.mockResolvedValue(2);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(reads()).toBe(2);
+ poll.mockResolvedValue(null);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(reads()).toBe(3);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(reads()).toBe(4);
+ poller.dispose();
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(reads()).toBe(4);
+});
+
+it('pauses while hidden and rereads on return only when the last read is stale', async () => {
+ const poller = startSharedTaskListPoller({ poll, isVisible: () => visible });
+ await vi.advanceTimersByTimeAsync(0);
+ visible = false; poller.visibilityChanged();
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(reads()).toBe(1);
+ visible = true; poller.visibilityChanged();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(reads()).toBe(2);
+ // A quick focus bounce reuses the fresh read and keeps the timer.
+ visible = false; poller.visibilityChanged();
+ visible = true; poller.visibilityChanged();
+ await vi.advanceTimersByTimeAsync(59_999);
+ expect(reads()).toBe(2);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(reads()).toBe(3);
+ poller.dispose();
+});
+
+it('does not start hidden, and a refresh while hidden reads on return even after a recent read', async () => {
+ visible = false;
+ const poller = startSharedTaskListPoller({ poll, isVisible: () => visible });
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(reads()).toBe(0);
+ visible = true; poller.visibilityChanged();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(reads()).toBe(1);
+ visible = false; poller.visibilityChanged();
+ poller.refresh();
+ visible = true; poller.visibilityChanged();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(reads()).toBe(2);
+ // A clock set backwards does not suppress the read on return either.
+ visible = false; poller.visibilityChanged();
+ vi.setSystemTime(Date.now() - 3_600_000);
+ visible = true; poller.visibilityChanged();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(reads()).toBe(3);
+ poller.dispose();
+});
+
+it('runs a refresh requested during a read once more after it, never concurrently', async () => {
+ let finish!: (count: number) => void;
+ poll.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const poller = startSharedTaskListPoller({ poll, isVisible: () => visible });
+ poller.refresh(); poller.refresh();
+ expect(reads()).toBe(1);
+ finish(0);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(reads()).toBe(2);
+ await vi.advanceTimersByTimeAsync(59_999);
+ expect(reads()).toBe(2);
+ poller.dispose();
+});
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 165f65ece0..c05042f5ed 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -41,6 +41,7 @@ export * from "./filePeerRuntime.js";
export { FILE_PEER_RUNTIME_SOURCE } from "./filePeerRuntimeSource.js";
export * from "./sharedTask.js";
export * from "./sharedTaskApi.js";
+export * from "./sharedTaskListPoller.js";
export * from "./sharedTaskInvitation.js";
export * from "./sharedTaskProbe.js";
export * from "./providerShareApi.js";
diff --git a/packages/device-link/src/sharedTaskListPoller.ts b/packages/device-link/src/sharedTaskListPoller.ts
new file mode 100644
index 0000000000..071773015c
--- /dev/null
+++ b/packages/device-link/src/sharedTaskListPoller.ts
@@ -0,0 +1,67 @@
+/**
+ * Cadence of the account shared-task directory on controlling clients. It only
+ * discovers memberships: the server and the hosting Desktop enforce access, and
+ * task content arrives through host pushes, independent of this interval.
+ */
+export const SHARED_TASK_LIST_ACTIVE_MS = 30_000;
+export const SHARED_TASK_LIST_IDLE_MS = 60_000;
+/** Returning to the foreground does not reread a list this recent. */
+export const SHARED_TASK_LIST_RESUME_MIN_MS = 10_000;
+
+export interface SharedTaskListPoller {
+ /** Read now, e.g. after joining or reconnecting; while hidden, read on return. */
+ refresh(): void;
+ /** Call on foreground/background changes; reading pauses while hidden. */
+ visibilityChanged(): void;
+ dispose(): void;
+}
+
+export function startSharedTaskListPoller(options: {
+ /** Resolves to the number of listed shared tasks, or null when the read failed. */
+ poll(): Promise<number | null>;
+ isVisible(): boolean;
+}): SharedTaskListPoller {
+ let disposed = false;
+ let busy = false;
+ let again = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let delay = SHARED_TASK_LIST_IDLE_MS;
+ let lastReadAt = Number.NEGATIVE_INFINITY;
+ const cancel = () => { clearTimeout(timer); timer = undefined; };
+ const schedule = () => {
+ cancel();
+ if (disposed || busy || !options.isVisible()) return;
+ timer = setTimeout(() => { void run(); }, delay);
+ };
+ const run = async () => {
+ if (disposed) return;
+ // A refresh requested mid-read (e.g. a join) must not be lost to that read.
+ if (busy) { again = true; return; }
+ cancel();
+ busy = true;
+ try {
+ do {
+ again = false;
+ lastReadAt = Date.now();
+ const count = await options.poll().catch(() => null);
+ if (count !== null) delay = count > 0 ? SHARED_TASK_LIST_ACTIVE_MS : SHARED_TASK_LIST_IDLE_MS;
+ } while (again && !disposed);
+ } finally { busy = false; }
+ schedule();
+ };
+ if (options.isVisible()) void run();
+ return {
+ refresh() {
+ if (options.isVisible()) void run();
+ else lastReadAt = Number.NEGATIVE_INFINITY;
+ },
+ visibilityChanged() {
+ if (!options.isVisible()) { cancel(); return; }
+ const elapsed = Date.now() - lastReadAt;
+ // A negative interval means the clock moved backwards; read rather than trust it.
+ if (elapsed < 0 || elapsed >= SHARED_TASK_LIST_RESUME_MIN_MS) void run();
+ else schedule();
+ },
+ dispose() { disposed = true; cancel(); },
+ };
+}