Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(discord): 增加上下线通知设置 (#1770)
nanaco99fd492e7704
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 7b2612195b..121f96363f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1666,6 +1666,7 @@ contextBridge.exposeInMainWorld('electronAPI', {| { kind: 'conflict'; appId: string }| { kind: 'error'; reason: string };ownerUserId: string | null;+ lifecycleAnnouncement: boolean;}> => ipcRenderer.invoke('discordBot:get-status'),setConfig: (payload: {token: string;@@ -1693,6 +1694,10 @@ contextBridge.exposeInMainWorld('electronAPI', {| { kind: 'conflict'; appId: string }| { kind: 'error'; reason: string };}> => ipcRenderer.invoke('discordBot:disconnect'),+ setLifecycleAnnouncement: (enabled: boolean): Promise<{+ ok: boolean;+ lifecycleAnnouncement: boolean;+ }> => ipcRenderer.invoke('discordBot:set-lifecycle-announcement', { enabled }),checkSessionAuth: (): Promise<DiscordBotSessionAuthCheckWire> =>ipcRenderer.invoke('discordBot:check-session-auth'),onStatusChange: fanOutDiscordBotStatusChange,diff --git a/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx b/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsxindex eb876fee11..76c7e9c4b4 100644--- a/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx@@ -7,6 +7,7 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { useDiscordBot } from '@/hooks/useDiscordBot';import { ImChannelSettingsCard, useImChannelSettingsSummary } from './ImChannelSettingsCard';import { ImDefaultSettingsSection } from './ImDefaultSettingsSection';+import { ImLifecycleAnnouncementSection } from './ImLifecycleAnnouncementSection';const DISCORD_DEVELOPER_PORTAL_URL = 'https://discord.com/developers/applications';@@ -49,6 +50,8 @@ export function DiscordBotSection({ownerUserId,setOwnerUserId,status,+ lifecycleAnnouncement,+ setLifecycleAnnouncement,validationError,isSaving,isDisconnecting,@@ -265,6 +268,19 @@ export function DiscordBotSection({</div>)}+ {hasSavedCreds && (+ <>+ <div className="h-px w-full bg-[var(--border-default)]" />+ <ImLifecycleAnnouncementSection+ label={t('settings.discordBot.lifecycleAnnouncement.label')}+ cellLabel={t('settings.discordBot.lifecycleAnnouncement.cellLabel')}+ hint={t('settings.discordBot.lifecycleAnnouncement.hint')}+ checked={lifecycleAnnouncement}+ onCheckedChange={setLifecycleAnnouncement}+ />+ </>+ )}+<div className="border-t border-[var(--settings-theme-card-border)] pt-3"><buttontype="button"diff --git a/apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx b/apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsxindex 80df4ad928..3010e981d0 100644--- a/apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx+++ b/apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx@@ -1,8 +1,7 @@import { useTranslation } from 'react-i18next';-import { cn } from '@/lib/utils';-import { Switch } from '@/components/ui/switch';import { useFeishuBot } from '@/hooks/useFeishuBot';+import { ImLifecycleAnnouncementSection } from './ImLifecycleAnnouncementSection';export function FeishuBotNotificationSection() {const {@@ -15,36 +14,12 @@ export function FeishuBotNotificationSection() {if (!hasSavedCreds) return null;return (- <div className="flex flex-col gap-[14px]">- <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">- {t('settings.feishuBot.lifecycleAnnouncement.label')}- </h2>-- <div- className={cn(- 'flex items-center justify-between gap-3 rounded-xl p-5',- 'bg-[var(--settings-theme-card-bg)]',- 'border border-[var(--settings-theme-card-border)]',- )}- >- <div className="flex min-w-0 flex-col gap-1">- <p- className="text-13 font-medium text-[var(--settings-section-sublabel)]"- style={{ letterSpacing: '0.12px' }}- >- {t('settings.feishuBot.lifecycleAnnouncement.cellLabel')}- </p>- <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">- {t('settings.feishuBot.lifecycleAnnouncement.hint')}- </p>- </div>-- <Switch- checked={lifecycleAnnouncement}- onCheckedChange={setLifecycleAnnouncement}- aria-label={t('settings.feishuBot.lifecycleAnnouncement.label')}- />- </div>- </div>+ <ImLifecycleAnnouncementSection+ label={t('settings.feishuBot.lifecycleAnnouncement.label')}+ cellLabel={t('settings.feishuBot.lifecycleAnnouncement.cellLabel')}+ hint={t('settings.feishuBot.lifecycleAnnouncement.hint')}+ checked={lifecycleAnnouncement}+ onCheckedChange={setLifecycleAnnouncement}+ />);}diff --git a/apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx b/apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsxnew file mode 100644index 0000000000..2509e52f0c--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx@@ -0,0 +1,44 @@+import { Switch } from '@/components/ui/switch';+import { cn } from '@/lib/utils';++export function ImLifecycleAnnouncementSection(props: {+ label: string;+ cellLabel: string;+ hint: string;+ checked: boolean;+ onCheckedChange: (enabled: boolean) => void;+}) {+ return (+ <div className="flex flex-col gap-[14px]">+ <h2 className="select-none text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">+ {props.label}+ </h2>++ <div+ className={cn(+ 'flex items-center justify-between gap-3 rounded-xl p-5',+ 'bg-[var(--settings-theme-card-bg)]',+ 'border border-[var(--settings-theme-card-border)]',+ )}+ >+ <div className="flex min-w-0 select-none flex-col gap-1">+ <p+ className="text-13 font-medium text-[var(--settings-section-sublabel)]"+ style={{ letterSpacing: '0.12px' }}+ >+ {props.cellLabel}+ </p>+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">+ {props.hint}+ </p>+ </div>++ <Switch+ checked={props.checked}+ onCheckedChange={props.onCheckedChange}+ aria-label={props.label}+ />+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.tsindex 92a0598f2c..9f10a9ba5f 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.ts@@ -27,10 +27,34 @@ vi.mock('@/lib/logger', () => ({}),}));-function installDiscordApi(status: DiscordBotTransportStatus = { kind: 'idle' }) {+function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++function installDiscordApi(+ status: DiscordBotTransportStatus = { kind: 'idle' },+ lifecycleAnnouncement = true,+ getStatusOverride?: () => Promise<{+ status: DiscordBotTransportStatus;+ ownerUserId: string | null;+ lifecycleAnnouncement: boolean;+ }>,+) {const listeners = new Set<(update: { status: DiscordBotTransportStatus }) => void>();const api = {- getStatus: vi.fn(async () => ({ status, ownerUserId: '12345678901234567' })),+ getStatus: vi.fn(+ getStatusOverride ?? (async () => ({+ status,+ ownerUserId: '12345678901234567',+ lifecycleAnnouncement,+ })),+ ),setConfig: vi.fn(async (payload: { token: string; ownerUserId: string }) => ({status: { kind: 'connecting' } as DiscordBotTransportStatus,saveErrorStatus: undefined as DiscordBotTransportStatus | undefined,@@ -38,6 +62,10 @@ function installDiscordApi(status: DiscordBotTransportStatus = { kind: 'idle' })payload,})),disconnect: vi.fn(async () => ({ status: { kind: 'idle' } as DiscordBotTransportStatus })),+ setLifecycleAnnouncement: vi.fn(async (enabled: boolean) => ({+ ok: true,+ lifecycleAnnouncement: enabled,+ })),onStatusChange: vi.fn((cb: (update: { status: DiscordBotTransportStatus }) => void) => {listeners.add(cb);return () => listeners.delete(cb);@@ -146,4 +174,135 @@ describe('useDiscordBot', () => {expect(result.current.ownerUserId).toBe('');expect(result.current.status.kind).toBe('idle');});++ it('loads and updates the lifecycle announcement preference', async () => {+ const api = installDiscordApi({ kind: 'connected', appId: 'MakerBot#1234' }, false);+ const { result } = renderHook(() => useDiscordBot());++ await waitFor(() => expect(result.current.lifecycleAnnouncement).toBe(false));++ act(() => {+ result.current.setLifecycleAnnouncement(true);+ });++ expect(result.current.lifecycleAnnouncement).toBe(true);+ expect(api.setLifecycleAnnouncement).toHaveBeenCalledWith(true);+ });++ it('preserves a newer lifecycle toggle in cache after an in-flight status read resolves', async () => {+ let resolveStatus!: (value: {+ status: DiscordBotTransportStatus;+ ownerUserId: string | null;+ lifecycleAnnouncement: boolean;+ }) => void;+ const statusPromise = new Promise<{+ status: DiscordBotTransportStatus;+ ownerUserId: string | null;+ lifecycleAnnouncement: boolean;+ }>((resolve) => {+ resolveStatus = resolve;+ });+ const api = installDiscordApi();+ const hydrated = renderHook(() => useDiscordBot());++ await waitFor(() => expect(hydrated.result.current.ownerUserId).toBe('12345678901234567'));+ hydrated.unmount();++ api.getStatus.mockReturnValueOnce(statusPromise);+ const current = renderHook(() => useDiscordBot());++ await waitFor(() => expect(api.getStatus).toHaveBeenCalledTimes(2));+ act(() => {+ current.result.current.setLifecycleAnnouncement(false);+ });++ await act(async () => {+ resolveStatus({+ status: { kind: 'connected', appId: 'MakerBot#1234' },+ ownerUserId: '12345678901234567',+ lifecycleAnnouncement: true,+ });+ await statusPromise;+ await Promise.resolve();+ });++ expect(current.result.current.lifecycleAnnouncement).toBe(false);+ expect(api.setLifecycleAnnouncement).toHaveBeenCalledWith(false);+ current.unmount();++ api.getStatus.mockImplementationOnce(() => new Promise(() => {}));+ const remounted = renderHook(() => useDiscordBot());+ expect(remounted.result.current.lifecycleAnnouncement).toBe(false);+ });++ it('preserves a newer lifecycle toggle in cache after an in-flight connect resolves', async () => {+ const api = installDiscordApi();+ const connectResult = deferred<{+ status: DiscordBotTransportStatus;+ saveErrorStatus: DiscordBotTransportStatus | undefined;+ ownerUserId: string;+ payload: { token: string; ownerUserId: string };+ }>();+ api.setConfig.mockReturnValueOnce(connectResult.promise);+ const current = renderHook(() => useDiscordBot());++ await waitFor(() => expect(current.result.current.ownerUserId).toBe('12345678901234567'));+ act(() => {+ current.result.current.setToken('bot-token');+ });++ let pendingConnect!: Promise<boolean>;+ act(() => {+ pendingConnect = current.result.current.connect();+ });+ await waitFor(() => expect(api.setConfig).toHaveBeenCalledTimes(1));++ act(() => {+ current.result.current.setLifecycleAnnouncement(false);+ });++ await act(async () => {+ connectResult.resolve({+ status: { kind: 'connected', appId: 'MakerBot#1234' },+ saveErrorStatus: undefined,+ ownerUserId: '12345678901234567',+ payload: { token: 'bot-token', ownerUserId: '12345678901234567' },+ });+ await pendingConnect;+ });++ current.unmount();+ api.getStatus.mockImplementationOnce(() => new Promise(() => {}));+ const remounted = renderHook(() => useDiscordBot());+ expect(remounted.result.current.lifecycleAnnouncement).toBe(false);+ });++ it('preserves a newer lifecycle toggle in cache after an in-flight disconnect resolves', async () => {+ const api = installDiscordApi({ kind: 'connected', appId: 'MakerBot#1234' });+ const disconnectResult = deferred<{ status: DiscordBotTransportStatus }>();+ api.disconnect.mockReturnValueOnce(disconnectResult.promise);+ const current = renderHook(() => useDiscordBot());++ await waitFor(() => expect(current.result.current.status.kind).toBe('connected'));++ let pendingDisconnect!: Promise<void>;+ act(() => {+ pendingDisconnect = current.result.current.disconnect();+ });+ await waitFor(() => expect(api.disconnect).toHaveBeenCalledTimes(1));++ act(() => {+ current.result.current.setLifecycleAnnouncement(false);+ });++ await act(async () => {+ disconnectResult.resolve({ status: { kind: 'idle' } });+ await pendingDisconnect;+ });++ current.unmount();+ api.getStatus.mockImplementationOnce(() => new Promise(() => {}));+ const remounted = renderHook(() => useDiscordBot());+ expect(remounted.result.current.lifecycleAnnouncement).toBe(false);+ });});diff --git a/apps/desktop/src/renderer/hooks/useDiscordBot.ts b/apps/desktop/src/renderer/hooks/useDiscordBot.tsindex 34c528caa3..bcf0103f44 100644--- a/apps/desktop/src/renderer/hooks/useDiscordBot.ts+++ b/apps/desktop/src/renderer/hooks/useDiscordBot.ts@@ -1,4 +1,4 @@-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';@@ -10,6 +10,7 @@ const OWNER_USER_ID_PATTERN = /^\d{17,20}$/;interface DiscordBotCache {ownerUserId: string;status: DiscordBotTransportStatus;+ lifecycleAnnouncement: boolean;}let cachedState: DiscordBotCache | null = null;@@ -20,6 +21,8 @@ export interface UseDiscordBotReturn {ownerUserId: string;setOwnerUserId: (v: string) => void;status: DiscordBotTransportStatus;+ lifecycleAnnouncement: boolean;+ setLifecycleAnnouncement: (enabled: boolean) => void;validationError: string | null;isSaving: boolean;isDisconnecting: boolean;@@ -35,22 +38,35 @@ export function useDiscordBot(): UseDiscordBotReturn {const [status, setStatus] = useState<DiscordBotTransportStatus>(() => cachedState?.status ?? { kind: 'idle' },);+ const [lifecycleAnnouncement, setLifecycleAnnouncementState] = useState(+ () => cachedState?.lifecycleAnnouncement ?? true,+ );const [validationError, setValidationError] = useState<string | null>(null);const [isSaving, setIsSaving] = useState(false);const [isDisconnecting, setIsDisconnecting] = useState(false);+ const lifecycleRequestVersionRef = useRef(0);useEffect(() => {let cancelled = false;+ const lifecycleReadVersion = lifecycleRequestVersionRef.current;void (async () => {try {const state = await window.electronAPI.discordBot.getStatus();if (cancelled) return;const nextOwnerUserId = state.ownerUserId ?? '';+ const nextLifecycleAnnouncement = state.lifecycleAnnouncement !== false;+ const lifecycleReadIsCurrent = lifecycleReadVersion === lifecycleRequestVersionRef.current;setStatus(state.status);setOwnerUserIdState(nextOwnerUserId);+ if (lifecycleReadIsCurrent) {+ setLifecycleAnnouncementState(nextLifecycleAnnouncement);+ }cachedState = {ownerUserId: nextOwnerUserId,status: state.status,+ lifecycleAnnouncement: lifecycleReadIsCurrent+ ? nextLifecycleAnnouncement+ : (cachedState?.lifecycleAnnouncement ?? true),};} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -68,6 +84,7 @@ export function useDiscordBot(): UseDiscordBotReturn {cachedState = {ownerUserId: cachedState?.ownerUserId ?? '',status: update.status,+ lifecycleAnnouncement: cachedState?.lifecycleAnnouncement ?? true,};});return unsub;@@ -83,6 +100,31 @@ export function useDiscordBot(): UseDiscordBotReturn {setValidationError(null);}, []);+ const setLifecycleAnnouncement = useCallback((enabled: boolean) => {+ const previous = lifecycleAnnouncement;+ const requestVersion = ++lifecycleRequestVersionRef.current;+ setLifecycleAnnouncementState(enabled);+ cachedState = {+ ownerUserId: cachedState?.ownerUserId ?? '',+ status: cachedState?.status ?? { kind: 'idle' },+ lifecycleAnnouncement: enabled,+ };+ void window.electronAPI.discordBot.setLifecycleAnnouncement(enabled).then((result) => {+ if (requestVersion !== lifecycleRequestVersionRef.current) return;+ if (result.ok && result.lifecycleAnnouncement === enabled) return;+ setLifecycleAnnouncementState(result.lifecycleAnnouncement);+ if (cachedState) {+ cachedState = { ...cachedState, lifecycleAnnouncement: result.lifecycleAnnouncement };+ }+ }).catch((err) => {+ if (requestVersion !== lifecycleRequestVersionRef.current) return;+ const msg = err instanceof Error ? err.message : String(err);+ log.error('setLifecycleAnnouncement failed:', msg);+ setLifecycleAnnouncementState(previous);+ if (cachedState) cachedState = { ...cachedState, lifecycleAnnouncement: previous };+ });+ }, [lifecycleAnnouncement]);+const connect = useCallback(async () => {if (isSaving) return false;const trimmedToken = token.trim();@@ -110,6 +152,7 @@ export function useDiscordBot(): UseDiscordBotReturn {cachedState = {ownerUserId: canonicalOwnerUserId,status: result.status,+ lifecycleAnnouncement: cachedState?.lifecycleAnnouncement ?? lifecycleAnnouncement,};if (result.saveErrorStatus?.kind === 'error' || result.status.kind === 'error') {toast.error(t('logic.toasts.discordBotConnectFailed'));@@ -125,7 +168,7 @@ export function useDiscordBot(): UseDiscordBotReturn {} finally {setIsSaving(false);}- }, [isSaving, ownerUserId, t, token]);+ }, [isSaving, lifecycleAnnouncement, ownerUserId, t, token]);const disconnect = useCallback(async () => {if (isDisconnecting) return;@@ -139,6 +182,7 @@ export function useDiscordBot(): UseDiscordBotReturn {cachedState = {ownerUserId: '',status: result.status,+ lifecycleAnnouncement: cachedState?.lifecycleAnnouncement ?? lifecycleAnnouncement,};toast.success(t('logic.toasts.discordBotDisconnected'));} catch (err) {@@ -148,7 +192,7 @@ export function useDiscordBot(): UseDiscordBotReturn {} finally {setIsDisconnecting(false);}- }, [isDisconnecting, t]);+ }, [isDisconnecting, lifecycleAnnouncement, t]);const canConnect =token.trim().length > 0 &&@@ -162,6 +206,8 @@ export function useDiscordBot(): UseDiscordBotReturn {ownerUserId,setOwnerUserId,status,+ lifecycleAnnouncement,+ setLifecycleAnnouncement,validationError,isSaving,isDisconnecting,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a0e321332a..7368ad1dd8 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1833,6 +1833,11 @@"confirm": "Unbind","cancel": "Cancel"},+ "lifecycleAnnouncement": {+ "label": "Online/Offline Notifications",+ "cellLabel": "Message Notifications",+ "hint": "Have the Discord Bot send a message when this device goes online or offline"+ },"ownerNotice": {"linked": "✅ All linked. Just send a message when you're ready.","disconnected": "🔌 Unlinked. Link again whenever you need me.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 698e8f6c80..e729fe026c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1832,6 +1832,11 @@"confirm": "連携解除","cancel": "キャンセル"},+ "lifecycleAnnouncement": {+ "label": "オンライン・オフライン通知",+ "cellLabel": "メッセージ通知",+ "hint": "このデバイスのオンライン・オフライン時に Discord Bot から通知メッセージを送信します"+ },"ownerNotice": {"linked": "✅ 連携できました。準備できたらそのまま話しかけてください。","disconnected": "🔌 連携を解除しました。必要になったらまたつないでください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex c9c80ea855..2d10501ba3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1832,6 +1832,11 @@"confirm": "연동 해제","cancel": "취소"},+ "lifecycleAnnouncement": {+ "label": "온라인/오프라인 알림",+ "cellLabel": "메시지 알림",+ "hint": "이 기기가 온라인 또는 오프라인 상태가 되면 Discord Bot이 알림 메시지를 보냅니다"+ },"ownerNotice": {"linked": "✅ 연동됐어요. 준비되면 바로 말을 걸어 주세요.","disconnected": "🔌 연동을 해제했어요. 필요할 때 다시 연결하면 됩니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 513798b673..16fac33a07 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1832,6 +1832,11 @@"confirm": "解绑","cancel": "取消"},+ "lifecycleAnnouncement": {+ "label": "上下线通知",+ "cellLabel": "消息通知",+ "hint": "上下线时由 Discord Bot 发送通知消息"+ },"ownerNotice": {"linked": "✅ 关联好啦,直接开聊就行~","disconnected": "🔌 已断开关联啦,需要时再连上就行~",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 5cd317b12e..5a7fc53a2d 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1894,6 +1894,7 @@ interface ElectronAPI {getStatus: () => Promise<{status: DiscordBotTransportStatus;ownerUserId: string | null;+ lifecycleAnnouncement: boolean;}>;setConfig: (payload: { token: string; ownerUserId: string }) => Promise<{status: DiscordBotTransportStatus;@@ -1903,6 +1904,10 @@ interface ElectronAPI {disconnect: () => Promise<{status: DiscordBotTransportStatus;}>;+ setLifecycleAnnouncement: (enabled: boolean) => Promise<{+ ok: boolean;+ lifecycleAnnouncement: boolean;+ }>;checkSessionAuth: () => Promise<DiscordBotSessionAuthCheckResult>;onStatusChange: (callback: (update: { status: DiscordBotTransportStatus }) => void,diff --git a/packages/lizi-im/src/discord/__tests__/inbound.test.ts b/packages/lizi-im/src/discord/__tests__/inbound.test.tsindex b46a22b049..ecba9f5c68 100644--- a/packages/lizi-im/src/discord/__tests__/inbound.test.ts+++ b/packages/lizi-im/src/discord/__tests__/inbound.test.ts@@ -279,6 +279,90 @@ describe('DiscordIM inbound pipeline', () => {);});+ it('defers lifecycle preference reads until explicit init', async () => {+ const host = makeHost({+ initialSecrets: [['discord-bot-lifecycle-announcement', 'false']],+ });+ const readSecret = vi.spyOn(host.secrets, 'read');+ const im = new DiscordIM(host);++ expect(readSecret).not.toHaveBeenCalled();++ im.registerIpc();+ await im.init();++ expect(readSecret).toHaveBeenCalledWith('discord-bot-lifecycle-announcement');+ await expect(host.invoke('discordBot:get-status')).resolves.toMatchObject({+ lifecycleAnnouncement: false,+ });+ });++ it('reads the persisted lifecycle preference from IPC before init', async () => {+ const host = makeHost({+ initialSecrets: [['discord-bot-lifecycle-announcement', 'false']],+ });+ const readSecret = vi.spyOn(host.secrets, 'read');+ const im = new DiscordIM(host);++ expect(readSecret).not.toHaveBeenCalled();++ im.registerIpc();++ await expect(host.invoke('discordBot:get-status')).resolves.toMatchObject({+ lifecycleAnnouncement: false,+ });+ expect(readSecret).toHaveBeenCalledWith('discord-bot-lifecycle-announcement');+ });++ it('rolls back a pre-init lifecycle write failure to the persisted preference', async () => {+ const host = makeHost({+ initialSecrets: [['discord-bot-lifecycle-announcement', 'false']],+ write: (name, value, secrets) => {+ if (name === 'discord-bot-lifecycle-announcement') return false;+ secrets.set(name, value);+ return true;+ },+ });+ const im = new DiscordIM(host);+ im.registerIpc();++ await expect(+ host.invoke('discordBot:set-lifecycle-announcement', { enabled: true }),+ ).resolves.toEqual({+ ok: false,+ lifecycleAnnouncement: false,+ });+ expect(host.readSecret('discord-bot-lifecycle-announcement')).toBe('false');+ });++ it('rolls back a post-init lifecycle write failure to the persisted preference', async () => {+ let rejectLifecycleWrites = false;+ const host = makeHost({+ initialSecrets: [['discord-bot-lifecycle-announcement', 'false']],+ write: (name, value, secrets) => {+ if (name === 'discord-bot-lifecycle-announcement' && rejectLifecycleWrites) return false;+ secrets.set(name, value);+ return true;+ },+ });+ const im = new DiscordIM(host);+ im.registerIpc();+ await im.init();++ // Simulate the active account's persisted preference changing after init,+ // leaving the runtime cache stale until the next explicit lifecycle load.+ expect(host.secrets.write('discord-bot-lifecycle-announcement', 'true')).toBe(true);+ rejectLifecycleWrites = true;++ await expect(+ host.invoke('discordBot:set-lifecycle-announcement', { enabled: false }),+ ).resolves.toEqual({+ ok: false,+ lifecycleAnnouncement: true,+ });+ expect(host.readSecret('discord-bot-lifecycle-announcement')).toBe('true');+ });+it('silently drops non-owner DM messages', async () => {const gateway = makeGateway();const im = new DiscordIM(makeHost(), {@@ -762,6 +846,7 @@ describe('DiscordIM inbound pipeline', () => {},});+ im.registerIpc();await im.init();await flushMicrotasks();@@ -769,6 +854,180 @@ describe('DiscordIM inbound pipeline', () => {expect(host.readSecret('discord-bot-runtime-active')).toBeTruthy();});+ it('suppresses all lifecycle notices and clears a dirty marker when disabled', async () => {+ const channel = makeChannel('dm-1');+ const gateway = makeGateway({ client: makeClient(channel) });+ gateway.connect.mockImplementationOnce(async () => {+ gateway.emitStatus({ kind: 'connected', appId: 'bot#0000' });+ });+ const host = makeHost({+ initialSecrets: [+ ['discord-bot-token', 'token'],+ ['discord-owner-user-id', 'user-1'],+ ['discord-bot-runtime-active', 'previous-run'],+ ['discord-bot-lifecycle-announcement', 'false'],+ ],+ });+ const im = new DiscordIM(host, {+ ownerNoticeText: (phase) => `localized:${phase}`,+ gatewayFactory: (handlers) => {+ gateway.setHandlers(handlers);+ return gateway;+ },+ });++ im.registerIpc();+ await im.init();+ await flushMicrotasks();+ await im.dispose();++ expect(channel.send).not.toHaveBeenCalled();+ expect(host.readSecret('discord-bot-runtime-active')).toBeNull();+ await expect(host.invoke('discordBot:get-status')).resolves.toMatchObject({+ lifecycleAnnouncement: false,+ });+ });++ it('invalidates a queued dirty-runtime notice when lifecycle announcements are disabled', async () => {+ const fetchStarted = deferred();+ const releaseFetch = deferred();+ const channel = makeChannel('dm-1');+ const client = {+ users: {+ fetch: vi.fn(async () => {+ fetchStarted.resolve();+ await releaseFetch.promise;+ return { createDM: vi.fn(async () => channel) };+ }),+ },+ };+ const gateway = makeGateway({ client });+ gateway.connect.mockImplementationOnce(async () => {+ gateway.emitStatus({ kind: 'connected', appId: 'bot#0000' });+ });+ const host = makeHost({+ initialSecrets: [+ ['discord-bot-token', 'token'],+ ['discord-owner-user-id', 'user-1'],+ ['discord-bot-runtime-active', 'previous-run'],+ ],+ });+ const im = new DiscordIM(host, {+ ownerNoticeText: (phase) => `localized:${phase}`,+ gatewayFactory: (handlers) => {+ gateway.setHandlers(handlers);+ return gateway;+ },+ });++ im.registerIpc();+ await im.init();+ await fetchStarted.promise;++ await host.invoke('discordBot:set-lifecycle-announcement', { enabled: false });+ expect(host.readSecret('discord-bot-lifecycle-announcement')).toBe('false');+ releaseFetch.resolve();+ await flushMicrotasks();+ await im.dispose();++ expect(channel.send).not.toHaveBeenCalled();+ expect(host.readSecret('discord-bot-runtime-active')).toBeNull();+ });++ it('keeps linked and disconnected confirmations enabled when lifecycle notices are disabled', async () => {+ const channel = makeChannel('dm-1');+ const gateway = makeGateway({ client: makeClient(channel) });+ gateway.connect.mockImplementationOnce(async () => {+ gateway.emitStatus({ kind: 'connected', appId: 'bot#0000' });+ });+ const host = makeHost({+ initialSecrets: [+ ['discord-bot-token', 'token'],+ ['discord-owner-user-id', 'user-1'],+ ['discord-bot-runtime-active', 'previous-run'],+ ['discord-bot-lifecycle-announcement', 'false'],+ ],+ });+ const im = new DiscordIM(host, {+ ownerNoticeText: (phase) => `localized:${phase}`,+ gatewayFactory: (handlers) => {+ gateway.setHandlers(handlers);+ return gateway;+ },+ });++ im.registerIpc();+ await host.invoke('discordBot:set-config', {+ token: 'new-token',+ ownerUserId: 'user-1',+ });++ expect(host.readSecret('discord-bot-runtime-active')).toBeNull();+ await host.invoke('discordBot:disconnect');++ expect(channel.send.mock.calls.map(([payload]) => payload)).toEqual([+ 'localized:linked',+ 'localized:disconnected',+ ]);+ expect(host.readSecret('discord-bot-lifecycle-announcement')).toBe('false');+ });++ it('rejects an invalid lifecycle announcement payload without changing the preference', async () => {+ const host = makeHost({+ initialSecrets: [['discord-bot-lifecycle-announcement', 'false']],+ });+ const im = new DiscordIM(host);+ im.registerIpc();+ await im.init();++ await expect(host.invoke('discordBot:set-lifecycle-announcement', {}))+ .rejects.toThrow('[INVALID_PARAMS] enabled must be a boolean');+ await expect(host.invoke('discordBot:get-status')).resolves.toMatchObject({+ lifecycleAnnouncement: false,+ });+ expect(host.readSecret('discord-bot-lifecycle-announcement')).toBe('false');+ });++ it('does not leave a dirty runtime marker when an in-flight offline notice is invalidated', async () => {+ const offlineStarted = deferred();+ const releaseOffline = deferred();+ const channel = makeChannel('dm-1');+ channel.send+ .mockResolvedValueOnce({ id: 'm-online' })+ .mockImplementationOnce(async (payload: unknown) => {+ expect(payload).toBe('localized:offline');+ offlineStarted.resolve();+ await releaseOffline.promise;+ return { id: 'm-offline' };+ });+ const gateway = makeGateway({ client: makeClient(channel) });+ gateway.connect.mockImplementationOnce(async () => {+ gateway.emitStatus({ kind: 'connected', appId: 'bot#0000' });+ });+ const host = makeHost();+ const im = new DiscordIM(host, {+ ownerNoticeText: (phase) => `localized:${phase}`,+ gatewayFactory: (handlers) => {+ gateway.setHandlers(handlers);+ return gateway;+ },+ });++ im.registerIpc();+ await im.init();+ await flushMicrotasks();+ expect(host.readSecret('discord-bot-runtime-active')).toBeTruthy();++ const disposing = im.dispose();+ await offlineStarted.promise;+ await host.invoke('discordBot:set-lifecycle-announcement', { enabled: false });+ await host.invoke('discordBot:set-lifecycle-announcement', { enabled: true });+ releaseOffline.resolve();+ await disposing;++ expect(host.readSecret('discord-bot-runtime-active')).toBeNull();+ });+it('does not repeat runtime online notice on transient gateway reconnect', async () => {const channel = makeChannel('dm-1');const gateway = makeGateway({ client: makeClient(channel) });@@ -1666,6 +1925,7 @@ describe('DiscordIM inbound pipeline', () => {appId: 'bot#0000',},ownerUserId: 'user-1',+ lifecycleAnnouncement: true,});});});diff --git a/packages/lizi-im/src/discord/index.ts b/packages/lizi-im/src/discord/index.tsindex d07bd4f80b..12382ba526 100644--- a/packages/lizi-im/src/discord/index.ts+++ b/packages/lizi-im/src/discord/index.ts@@ -36,6 +36,7 @@ import { startStreaming } from './streamingText.js';const TOKEN_SECRET_KEY = 'discord-bot-token';const OWNER_USER_ID_SECRET_KEY = 'discord-owner-user-id';const RUNTIME_ACTIVE_SECRET_KEY = 'discord-bot-runtime-active';+const LIFECYCLE_ANNOUNCEMENT_SECRET_KEY = 'discord-bot-lifecycle-announcement';const MAX_OUTBOUND_FILE_BYTES = 8 * 1024 * 1024;const DISCORD_CREATE_MESSAGE_MAX_BYTES = 25 * 1024 * 1024;// Leave room for multipart framing/content; Discord also caps bot message uploads by file count.@@ -92,6 +93,8 @@ export class DiscordIM extends BaseIM implements ChannelIM {private pendingOfflineNotice = false;private runtimeOnlineAnnounced = false;private runtimeOnlineNotice: Promise<void> | null = null;+ private lifecycleAnnouncementEnabled = true;+ private lifecycleNoticeVersion = 0;private disposing = false;constructor(host: IMHost, private readonly opts: DiscordIMOptions = {}) {@@ -116,14 +119,19 @@ export class DiscordIM extends BaseIM implements ChannelIM {this.suppressNextOnlineNotice = false;this.runtimeOnlineNotice = null;this.runtimeOnlineAnnounced = false;+ this.lifecycleNoticeVersion += 1;+ this.lifecycleAnnouncementEnabled = this.readLifecycleAnnouncement();const token = this.host.secrets.read(TOKEN_SECRET_KEY)?.trim() ?? '';this.ownerUserId = this.host.secrets.read(OWNER_USER_ID_SECRET_KEY)?.trim() ?? '';+ if (!this.lifecycleAnnouncementEnabled) {+ this.clearRuntimeActiveMarker();+ }if (!token) {this.setStatus({ kind: 'idle' });return;}- this.pendingOfflineNotice = Boolean(+ this.pendingOfflineNotice = this.lifecycleAnnouncementEnabled && Boolean(this.ownerUserId && this.host.secrets.read(RUNTIME_ACTIVE_SECRET_KEY),);@@ -153,6 +161,9 @@ export class DiscordIM extends BaseIM implements ChannelIM {});this.host.ipc.handle('discordBot:set-config', async (payload) => {+ // IPC handlers are registered before init(). Sync the persisted preference+ // before any gateway status can queue a lifecycle notice or write its marker.+ this.applyLifecycleAnnouncement(this.readLifecycleAnnouncement());const config = isRecord(payload) ? payload : {};const token = typeof config.token === 'string' ? config.token.trim() : '';const ownerUserId =@@ -217,11 +228,31 @@ export class DiscordIM extends BaseIM implements ChannelIM {return configResult();});+ // Renderer IPC can run after handler registration but before init(). Read the+ // persisted preference here instead of exposing the constructor default.this.host.ipc.handle('discordBot:get-status', () => ({status: this.status,ownerUserId: this.ownerUserId || null,+ lifecycleAnnouncement: this.readLifecycleAnnouncement(),}));+ this.host.ipc.handle('discordBot:set-lifecycle-announcement', (payload) => {+ if (!isRecord(payload) || typeof payload.enabled !== 'boolean') {+ return this.host.ipc.throwIpcError('INVALID_PARAMS', 'enabled must be a boolean');+ }+ const enabled = payload.enabled;+ if (!this.writeLifecycleAnnouncement(enabled)) {+ return {+ ok: false,+ // Roll back to the persisted source of truth, which may differ from+ // the runtime cache before init or after an external account change.+ lifecycleAnnouncement: this.readLifecycleAnnouncement(),+ };+ }+ this.applyLifecycleAnnouncement(enabled);+ return { ok: true, lifecycleAnnouncement: enabled };+ });+this.host.ipc.handle('discordBot:disconnect', async () => {this.configVersion += 1;const disconnectedNoticeConfigVersion = this.configVersion;@@ -423,6 +454,58 @@ export class DiscordIM extends BaseIM implements ChannelIM {this.host.secrets.write(key, previousValue);}+ private readLifecycleAnnouncement(): boolean {+ return this.host.secrets.read(LIFECYCLE_ANNOUNCEMENT_SECRET_KEY) !== 'false';+ }++ private writeLifecycleAnnouncement(enabled: boolean): boolean {+ try {+ if (!this.host.secrets.isAvailable()) return false;+ return this.host.secrets.write(LIFECYCLE_ANNOUNCEMENT_SECRET_KEY, String(enabled));+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ this.log.warn(`discord lifecycle announcement preference write threw: ${msg}`);+ return false;+ }+ }++ private applyLifecycleAnnouncement(enabled: boolean): void {+ if (this.lifecycleAnnouncementEnabled === enabled) {+ if (!enabled) {+ this.pendingOfflineNotice = false;+ this.clearRuntimeActiveMarker();+ } else if (+ !this.disposing &&+ this.status.kind === 'connected' &&+ this.ownerUserId &&+ this.gateway.client+ ) {+ this.markRuntimeActive();+ }+ return;+ }++ this.lifecycleAnnouncementEnabled = enabled;+ this.lifecycleNoticeVersion += 1;+ this.runtimeOnlineNotice = null;+ this.runtimeOnlineAnnounced = false;+ this.pendingOfflineNotice = false;+ this.suppressNextOnlineNotice = false;++ if (!enabled) {+ this.clearRuntimeActiveMarker();+ return;+ }+ if (+ !this.disposing &&+ this.status.kind === 'connected' &&+ this.ownerUserId &&+ this.gateway.client+ ) {+ this.markRuntimeActive();+ }+ }+private async reconnectPreviousGateway(previousToken: string | null): Promise<void> {const token = previousToken?.trim() ?? '';if (!token) return;@@ -457,6 +540,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {}private shouldQueueRuntimeOnlineNotice(): boolean {+ if (!this.lifecycleAnnouncementEnabled) return false;if (this.runtimeOnlineNotice) return false;return this.suppressNextOnlineNotice || this.pendingOfflineNotice || !this.runtimeOnlineAnnounced;}@@ -464,9 +548,11 @@ export class DiscordIM extends BaseIM implements ChannelIM {private queueRuntimeOnlineNotice(): void {const expectedConfigVersion = this.configVersion;const expectedOwnerUserId = this.ownerUserId;+ const expectedLifecycleNoticeVersion = this.lifecycleNoticeVersion;const notice = this.announceRuntimeOnline(expectedConfigVersion,expectedOwnerUserId,+ expectedLifecycleNoticeVersion,).catch((err) => {const msg = err instanceof Error ? err.message : String(err);this.log.warn(`discord runtime online notice failed: ${msg}`);@@ -514,8 +600,13 @@ export class DiscordIM extends BaseIM implements ChannelIM {private async announceRuntimeOnline(expectedConfigVersion: number,expectedOwnerUserId: string,+ expectedLifecycleNoticeVersion: number,): Promise<void> {- if (!this.isOwnerNoticeCurrent(expectedConfigVersion, expectedOwnerUserId)) {+ if (!this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ )) {return;}@@ -528,9 +619,17 @@ export class DiscordIM extends BaseIM implements ChannelIM {const sent = await this.sendOwnerNotice(expectedOwnerUserId,'offlineNotice',- () => this.isOwnerNoticeCurrent(expectedConfigVersion, expectedOwnerUserId),+ () => this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ ),);- if (!this.isOwnerNoticeCurrent(expectedConfigVersion, expectedOwnerUserId)) {+ if (!this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ )) {return;}if (sent) {@@ -538,7 +637,11 @@ export class DiscordIM extends BaseIM implements ChannelIM {}}- if (!this.isOwnerNoticeCurrent(expectedConfigVersion, expectedOwnerUserId)) {+ if (!this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ )) {return;}if (this.disposing) return;@@ -551,9 +654,17 @@ export class DiscordIM extends BaseIM implements ChannelIM {const sent = await this.sendOwnerNotice(expectedOwnerUserId,'online',- () => this.isOwnerNoticeCurrent(expectedConfigVersion, expectedOwnerUserId),+ () => this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ ),);- if (!this.isOwnerNoticeCurrent(expectedConfigVersion, expectedOwnerUserId)) {+ if (!this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ )) {return;}if (sent) {@@ -573,19 +684,51 @@ export class DiscordIM extends BaseIM implements ChannelIM {);}+ private isLifecycleNoticeCurrent(+ expectedConfigVersion: number,+ expectedOwnerUserId: string,+ expectedLifecycleNoticeVersion: number,+ ): boolean {+ return Boolean(+ this.lifecycleAnnouncementEnabled &&+ this.lifecycleNoticeVersion === expectedLifecycleNoticeVersion &&+ this.isOwnerNoticeCurrent(expectedConfigVersion, expectedOwnerUserId),+ );+ }+private async announceRuntimeOffline(deadlineMs?: number): Promise<void> {+ if (!this.lifecycleAnnouncementEnabled) {+ this.pendingOfflineNotice = false;+ this.clearRuntimeActiveMarker();+ return;+ }if (!this.ownerUserId) return;if (!this.gateway.client) return;if (!this.host.secrets.read(RUNTIME_ACTIVE_SECRET_KEY) && this.status.kind !== 'connected') return;+ const expectedConfigVersion = this.configVersion;+ const expectedOwnerUserId = this.ownerUserId;+ const expectedLifecycleNoticeVersion = this.lifecycleNoticeVersion;const timeoutMs = deadlineMs !== undefined? Math.min(RUNTIME_OFFLINE_NOTICE_TIMEOUT_MS, Math.max(0, deadlineMs - Date.now())): RUNTIME_OFFLINE_NOTICE_TIMEOUT_MS;const sent = await this.sendOwnerNoticeWithTimeout(- this.ownerUserId,+ expectedOwnerUserId,'offline',timeoutMs,+ () => this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ ),);+ if (!this.isLifecycleNoticeCurrent(+ expectedConfigVersion,+ expectedOwnerUserId,+ expectedLifecycleNoticeVersion,+ )) {+ return;+ }if (sent && !this.pendingOfflineNotice) {this.clearRuntimeActiveMarker();} else {@@ -595,6 +738,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {private markRuntimeActive(): void {try {+ if (!this.lifecycleAnnouncementEnabled) return;if (!this.host.secrets.isAvailable()) return;const ok = this.host.secrets.write(RUNTIME_ACTIVE_SECRET_KEY, String(Date.now()));if (!ok) this.log.warn('discord runtime active marker write failed');