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。

Merge upstream/main and preserve local-first companion entry behavior

Chris40a559efd31e
diff --cc apps/desktop/src/renderer/features/bots/BotSessionView.tsx
index 44b862e5b2,aaafb5903c..c701e576d3
--- a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
@@@ -13,12 -12,13 +12,13 @@@ import { useCompanionArrivalNotice } fr
import { CompanionShadowBanner } from './CompanionShadowBanner';
import type { ComposerBotMention } from '@/lib/fileTypes';
import { getBotLastReadAt, markBotRead } from './botReadState';
-import { useBotProfiles } from './botStore';
+import { getBotProfiles, useBotProfiles } from './botStore';
import type { BotChatIdentity } from './BotSessionContentHeader';
import type { BotChatBinding } from './botChatPresentation';
- import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';
import { BotDmThreadHost } from './BotDmThreadHost';
import { useBotPluginFocusedSession } from './useBotPluginFocusedSession';
+ import { canonicalBotSession } from './botSessionOwners';
+ import { standardSessionRoute } from '@/lib/orcaSessionIdentity';
type BotSessionGate =
| { kind: 'loading' }
@@@ -30,10 -30,10 +30,11 @@@
isCanonical: boolean;
/** Read position captured before opening advances it; null when entry had no unread replies. */
unreadBoundaryAt: number | null;
+ verified: boolean;
}
| { kind: 'unavailable' }
- | { kind: 'error'; message: string };
+ | { kind: 'ordinary' }
+ | { kind: 'error'; reason: ReturnType<typeof sessionEntryFailure> };
function readBotChatIdentity(bot: unknown, botId: string): BotChatIdentity {
const candidate = (bot ?? {}) as { name?: unknown; avatar?: unknown; avatarColor?: unknown; templateId?: unknown };
@@@ -86,20 -85,10 +87,20 @@@ export function BotSessionView()
function BotSessionGateView() {
const readOwner = useRef(getDataOwnerGeneration());
const { t } = useTranslation();
- const navigate = useNavigate();
+ const location = useLocation();
const { botId, sessionId } = useParams();
const [reloadVersion, setReloadVersion] = useState(0);
- const [gate, setGate] = useState<BotSessionGate>({ kind: 'loading' });
+ const [gate, setGate] = useState<BotSessionGate>(() => {
+ const profiles = getBotProfiles();
+ const profile = profiles.find(bot => bot.id === botId && bot.status === 'active');
- const projection = profile?.sessions.find(row => row.id === sessionId && row.kind === 'chat' && row.status === 'active');
- if (!profile || !projection || !sessionId) return { kind: 'loading' };
++ const projection = profile ? canonicalBotSession(profile) : undefined;
++ if (!profile || !projection || projection.id !== sessionId || projection.status !== 'active' || !sessionId) return { kind: 'loading' };
+ // The already-read local roster selects a display; fresh validation still
+ // controls writes and read receipts. Mount the existing message cache now.
+ return { kind: 'ready', verified: false, identity: { ...readBotChatIdentity(profile, profile.id), sessionId },
+ isCanonical: projection.role === 'canonical', unreadBoundaryAt: projection.role === 'canonical' && ((profile as { unreadCount?: number }).unreadCount ?? 0) > 0 ? getBotLastReadAt(profile.id) : null,
+ mentions: profiles.map(bot => readBotMention(bot, profile.id)).filter((bot): bot is ComposerBotMention => bot !== null) };
+ });
// The companion now runs on its main computer: this copy's main task is read only.
const cloud = useCompanionCloud();
const shadowed = cloud.demotedBotIds.includes(botId ?? '');
@@@ -148,10 -135,13 +148,13 @@@
cancelled = true;
};
}
- setGate({ kind: 'loading' });
+ setGate(previous => previous.kind === 'ready' ? { ...previous, verified: false } : { kind: 'loading' });
const lastReadAt = getBotLastReadAt(botId);
void Promise.all([
- window.electronAPI.localDb.bots.get(botId),
+ window.electronAPI.localDb.bots.get(botId).catch((error: unknown) => {
+ if (sessionEntryFailure(error) === 'missing') return null;
+ throw error;
+ }),
window.electronAPI.localDb.bots.list(
lastReadAt === null ? undefined : { lastReadAtByBotId: { [botId]: lastReadAt } },
),
@@@ -212,11 -195,10 +209,11 @@@
})
.catch((error: unknown) => {
if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
- const message = error instanceof Error ? error.message : String(error);
- const denied = /NOT_FOUND|FORBIDDEN|PERMISSION_DENIED/.test(message);
- setGate(previous => denied ? { kind: 'unavailable' } : previous.kind === 'ready'
- ? { ...previous, verified: false } : { kind: 'error', message });
- setGate({
- kind: 'error',
- reason: sessionEntryFailure(error),
- });
++ const reason = sessionEntryFailure(error);
++ const denied = reason !== 'failed' || /NOT_FOUND|FORBIDDEN|PERMISSION_DENIED/.test(String(error));
++ setGate(previous => denied ? { kind: 'error', reason: reason === 'failed' ? 'denied' : reason }
++ : previous.kind === 'ready' ? { ...previous, verified: false } : { kind: 'error', reason });
+ if (!denied) retry = setTimeout(() => { if (isDataOwnerGenerationCurrent(owner)) setReloadVersion(value => value + 1); }, 5_000);
});
return () => {
cancelled = true;
@@@ -225,9 -206,12 +222,12 @@@
}, [botId, reloadVersion, sessionId]);
const onReadThrough = useCallback((at: number) => {
- if (isDataOwnerGenerationCurrent(readOwner.current) && gate.kind === 'ready' && gate.isCanonical && botId && gate.identity.sessionId === sessionId) markBotRead(botId, at);
+ if (isDataOwnerGenerationCurrent(readOwner.current) && gate.kind === 'ready' && gate.verified && gate.isCanonical && botId && gate.identity.sessionId === sessionId) markBotRead(botId, at);
}, [botId, gate, sessionId]);
+ if (gate.kind === 'ordinary' && sessionId) {
+ return <Navigate to={`${standardSessionRoute(sessionId)}${location.search ?? ''}`} state={location.state} replace />;
+ }
if (gate.kind === 'loading') {
return (
<main className="flex h-full items-center justify-center bg-[var(--surface)]">
@@@ -241,51 -225,10 +241,10 @@@
);
}
if (gate.kind !== 'ready' || !sessionId) {
- const failed = gate.kind === 'error';
- return (
- <main className="flex h-full items-center justify-center bg-[var(--surface)] p-6">
- <section className="w-full max-w-md rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-5 text-center">
- <CircleAlert size={24} className="mx-auto text-[var(--text-danger)]" aria-hidden />
- <h1 className="mt-3 text-16 font-medium text-[var(--text-primary)]">
- {t(failed ? 'bots.sessionLoadFailedTitle' : 'bots.sessionUnavailableTitle')}
- </h1>
- <p className="mt-2 break-words text-12 leading-5 text-[var(--text-secondary)] [overflow-wrap:anywhere]">
- {failed
- ? t('bots.sessionLoadFailedDescription')
- : t('bots.sessionUnavailableDescription')}
- </p>
- {failed && gate.message ? (
- <p className="mt-3 max-h-24 overflow-y-auto whitespace-pre-wrap rounded-lg bg-[var(--surface)] px-3 py-2 text-left text-11 text-[var(--text-danger)] [overflow-wrap:anywhere]">
- {gate.message}
- </p>
- ) : null}
- <div className="mt-4 flex flex-wrap justify-center gap-2">
- <button
- type="button"
- onClick={() => navigate(botId ? `/bots/${botId}` : '/bots')}
- className="inline-flex h-9 items-center gap-2 rounded-lg border border-[var(--border-default)] px-3 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]"
- >
- <ArrowLeft size={14} />
- {t('bots.backToBot')}
- </button>
- {failed ? (
- <Button
- variant="cta"
- size="lg"
- compact
- type="button"
- onClick={() => setReloadVersion((value) => value + 1)}
- >
- <RefreshCcw size={14} />
- {t('bots.retry')}
- </Button>
- ) : null}
- </div>
- </section>
- </main>
- );
+ return <SessionEntryError reason={gate.kind === 'error' ? gate.reason : 'missing'}
+ onRetry={() => setReloadVersion((value) => value + 1)} />;
}
- const readOnly = shadowed && gate.isCanonical;
+ const readOnly = !gate.verified || (shadowed && gate.isCanonical);
return (
<main className="relative flex h-full min-w-0 overflow-hidden bg-[var(--surface)]">
{/* 私聊话题只属于本机的伙伴主对话;只读副本没有话题。 */}
diff --cc apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
index 939105516e,117cf33e15..3b118a404b
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
@@@ -1,8 -1,9 +1,9 @@@
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { Button } from '@/components/ui/button';
import { REMOTE_RESOURCE_GET_CHANNEL, type RemoteResourceGetRequest } from '@cindy/device-link';
-import { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
+import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react';
- import { useParams } from 'react-router-dom';
+ import { Navigate, useLocation, useParams } from 'react-router-dom';
+ import { standardSessionRoute } from '@/lib/orcaSessionIdentity';
import { useTranslation } from 'react-i18next';
import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
@@@ -23,26 -23,18 +23,29 @@@ const CloudCompanionOfflineView = lazy(
/** How long an open chat stays in place while its main computer cannot be reached. */
export const CLOUD_HOME_GRACE_MS = 15_000;
- /** The session id comes from the host's collection, never from an arbitrary URL. */
+ /** Verify companion identity with its host; pinned task links never adopt a replacement chat. */
export function RemoteBotSessionView() {
- const { deviceId, botId } = useParams();
++ const { deviceId, botId, sessionId: requestedSessionId } = useParams();
+ const owner = getDataOwnerGeneration();
- return <RemoteBotSessionGate key={JSON.stringify([owner.dataOwnerId, owner.generation, deviceId, botId])} />;
++ return <RemoteBotSessionGate key={JSON.stringify([owner.dataOwnerId, owner.generation, deviceId, botId, requestedSessionId])} />;
+}
+
+function RemoteBotSessionGate() {
- const { deviceId, botId } = useParams();
+ const { deviceId, botId, sessionId: requestedSessionId } = useParams();
+ const location = useLocation();
+ const [originalTask, setOriginalTask] = useState(false);
const { t } = useTranslation();
const bots = useRemoteBots();
const bot = bots.find((row) => row.id === botId && row.deviceId === deviceId);
const cloud = useCompanionCloud();
const deviceList = useDeviceLinkDeviceList();
const cloudActor = cloudCompanionAt(cloud, deviceId, botId);
- const [ready, setReady] = useState<(RemoteBot & { sessionId: string; canonicalChat: true }) | null>(null);
+ const [ready, setReady] = useState<(RemoteBot & { sessionId: string; canonicalChat: true }) | null>(() => {
- if (!bot?.sessionId || !deviceId || remoteProjectsStore.getSessionDeviceId(bot.sessionId) !== deviceId) return null;
++ if (!bot?.sessionId || !deviceId || (requestedSessionId && requestedSessionId !== bot.sessionId)
++ || remoteProjectsStore.getSessionDeviceId(bot.sessionId) !== deviceId) return null;
+ const session = remoteProjectsStore.getDeviceSessions(deviceId).find(row => row.id === bot.sessionId);
+ return session?.source === 'bot' && session.status === 'active' ? { ...bot, sessionId: bot.sessionId, canonicalChat: true } : null;
+ });
const [validatedSessionId, setValidatedSessionId] = useState<string | null | undefined>(null);
const [failed, setFailed] = useState(false);
const [retry, setRetry] = useState(0);
@@@ -52,8 -44,8 +55,9 @@@
let disposed = false;
const owner = getDataOwnerGeneration();
setFailed(false);
+ setOriginalTask(false);
if (!deviceId || !bot?.online) return;
+ setValidatedSessionId(null);
const request: RemoteResourceGetRequest = {
client: { protocolVersion: 1, primitives: ['status', 'session-link'] },
ref: { collectionId: 'teammates', kind: 'bot', id: bot.id },
@@@ -71,8 -62,12 +75,12 @@@
deviceId,
bot.deviceName,
);
- if (resolved.id !== bot.id || !resolved.sessionId) throw new Error('Companion is not ready');
+ if (!resolved || resolved.id !== bot.id || !resolved.sessionId) { setReady(null); throw new Error('Companion is not ready'); }
const canonicalId = resolved.sessionId;
+ if (requestedSessionId && canonicalId !== requestedSessionId) {
+ setOriginalTask(true);
+ return;
+ }
const existingOrigin = remoteProjectsStore.getSessionDeviceId(canonicalId);
if (existingOrigin && existingOrigin !== deviceId)
throw new Error('Conflicting remote session owner');
@@@ -109,26 -99,16 +117,25 @@@
return () => {
disposed = true;
};
- }, [deviceId, botId, sessionId, bot?.online, bot?.deviceName, retry]);
+ }, [deviceId, botId, sessionId, bot?.online, bot?.deviceName, retry, requestedSessionId]);
+ useEffect(() => {
+ if (!failed || !bot?.online || !ready) return;
+ const timer = setTimeout(() => setRetry(value => value + 1), 5_000);
+ return () => clearTimeout(timer);
+ }, [failed, bot?.online, ready]);
+ const identity = useMemo(() => ready ? { ...ready, canonicalChat: !failed && validatedSessionId === bot?.sessionId } : null,
+ [ready, failed, validatedSessionId, bot?.sessionId]);
+
const acknowledge = useCallback((at: number) => {
- if (isDataOwnerGenerationCurrent(readOwner.current) && bot?.online && !failed && ready?.id === bot.id && ready.deviceId === bot.deviceId
+ if ((!requestedSessionId || ready?.sessionId === requestedSessionId) && !originalTask && isDataOwnerGenerationCurrent(readOwner.current) && bot?.online && !failed && ready?.id === bot.id && ready.deviceId === bot.deviceId
&& validatedSessionId === bot.sessionId) {
markRemoteBotRead(bot.deviceId, bot.id, Math.min(at, bot.lastReplyAt ?? 0));
}
- }, [bot, failed, ready, validatedSessionId]);
+ }, [bot, failed, ready, validatedSessionId, requestedSessionId, originalTask]);
- const liveChat = !!bot && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
- // Like a local companion chat: once the chat is shown, the island card for this Session is read.
- useBotIslandVisibleSession(liveChat ? ready!.sessionId : null);
- const liveChat = !originalTask && (!requestedSessionId || requestedSessionId === ready?.sessionId) && !!bot && !failed && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
++ const liveChat = !originalTask && (!requestedSessionId || requestedSessionId === ready?.sessionId)
++ && !!bot && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
const homeAway = !!cloudActor && !!deviceId && !!botId && cloudActor.homeDeviceId !== cloud.selfDeviceId
&& (!bot || (!bot.online && bot.connectionKnown !== false));
// Like IM, a brief drop keeps the open chat in place (cloud-companions.md §3.1).
diff --cc apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
index 3e6c4340ad,d2e546733e..4107b9c588
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
@@@ -10,9 -10,10 +10,11 @@@ const h = vi.hoisted(() => (
pin: vi.fn(),
merge: vi.fn(),
view: vi.fn(),
+ navigate: vi.fn(),
+ requestedSessionId: undefined as string | undefined,
online: true,
listed: true,
+ cached: false,
lastReplyAt: 0,
devices: null as Array<{ deviceId: string; online: boolean; remoteControlEnabled: boolean }> | null,
cloud: { enabled: false, selfDeviceId: null, humanActorId: null, actors: [], demotedBotIds: [] } as import('../../../../shared/companionCloud').CompanionCloudSnapshot,
@@@ -59,9 -64,10 +65,11 @@@ vi.mock('@/features/cc-agent/CCAgentSes
import { CLOUD_HOME_GRACE_MS, RemoteBotSessionView } from '../RemoteBotSessionView';
beforeEach(() => {
h.markRead.mockClear();
+ h.navigate.mockReset();
+ h.requestedSessionId = undefined;
h.online = true;
h.listed = true;
+ h.cached = false;
h.lastReplyAt = 0;
h.cloud = { enabled: false, selfDeviceId: null, humanActorId: null, actors: [], demotedBotIds: [] };
h.devices = null;
diff --cc apps/mobile/src/__tests__/BotGroupList.test.tsx
index ebf5282f6e,ebf5282f6e..b0bfad17d5
--- a/apps/mobile/src/__tests__/BotGroupList.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupList.test.tsx
@@@ -186,8 -186,8 +186,14 @@@ describe('create from the home teammat
expect(node.textContent).toContain('groupChat.create.minMembers(min=2)');
expect(h.invoke).not.toHaveBeenCalled();
await act(async () => { h.inputs['botGroup.create.name'].onChangeText(' 官网 '); });
-- await click('botGroup.create.member.abu');
++ // Equal timestamps now have a stable identity tie-breaker. Select in the
++ // reverse order so the assertion still proves list order, not click order.
++ expect([...node.querySelectorAll('[data-testid^="botGroup.create.member."]')]
++ .map(entry => entry.getAttribute('data-testid'))).toEqual([
++ 'botGroup.create.member.abu', 'botGroup.create.member.mimi', 'botGroup.create.member.xiaoman',
++ ]);
await click('botGroup.create.member.mimi');
++ await click('botGroup.create.member.abu');
h.invoke.mockResolvedValueOnce({ effects: [
{ kind: 'refresh-collection', collectionId: 'bot-groups' },
{ kind: 'navigate', target: { kind: 'resource', ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g9' } } },
@@@ -196,7 -196,7 +202,7 @@@
const request = h.invoke.mock.calls[0]!;
expect(request[0]).toBe('mac');
expect(request[1]).toBe('maker:remote-resources:invoke');
-- expect(request[2][0]).toMatchObject({ collectionId: 'bot-groups', actionId: 'create', input: { name: '官网', botIds: ['mimi', 'abu'] } });
++ expect(request[2][0]).toMatchObject({ collectionId: 'bot-groups', actionId: 'create', input: { name: '官网', botIds: ['abu', 'mimi'] } });
expect(byId('botGroup.create')).toBeNull();
expect(onGroupCreated).toHaveBeenCalledWith(mac, 'g9');
});