Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix(host): 云端执行带默认桌面通知的伙伴计划
保留项目计划的随行通知设置,云端执行关闭桌面通知。切换确认和伙伴设置说明通知限制,接手未恢复的计划展示数量与原因。暂时无法确认主力时保留计时轮次,确认归属后才派发。

Assisted-by: Cindy (https://cindy.app)
Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>
  • Loading branch information
dashhuang committed Nov 30, 2026
commit 678fd237b53ef2899d24d0e69b5ede59537826b2
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useRef } from 'react';
import { AppFrame, forbid, mountPage, subscription } from '../../ui-page/harness';
import { BotHomeComputerSetting } from '../../../src/renderer/features/bots/BotHomeComputerSetting';
import { RemoteBotSettings } from '../../../src/renderer/features/bots/RemoteBotSettings';
import i18n from '../../../src/renderer/i18n';
import { REMOTE_RESOURCE_GET_CHANNEL } from '@cindy/device-link';

const cloud = { deviceId: 'cloud-device-000000000000000000000001', name: 'Cloud Cindy', online: true };
const buddy = { id: 'fixture-buddy', name: 'Mia' };
const remote = {
...buddy, deviceId: cloud.deviceId, deviceName: cloud.name, online: true, avatar: '🦉',
avatarColor: 'violet', description: '', preview: '', activityAt: 0, sessionId: 'fixture-main-task',
};

function ProjectSettings() {
const beforeCloseRef = useRef<(() => Promise<boolean>) | null>(null);
return <RemoteBotSettings bot={remote} beforeCloseRef={beforeCloseRef} onDeleted={() => {}} />;
}

void mountPage({
route: '/bots/fixture-buddy',
host: ctx => ({
maker: {
getCompanionCloudState: async () => ({
enabled: ctx.case === 'default', selfDeviceId: 'fixture-desktop', humanActorId: 'fixture-account',
demotedBotIds: [], actors: [{ id: 'fixture-actor', externalId: buddy.id, name: buddy.name, homeDeviceId: 'fixture-desktop' }],
}),
getCompanionHomeChoices: async () => ({
homeDeviceId: 'fixture-desktop', mode: 'local', targets: [cloud],
}),
switchCompanionHome: forbid('maker.switchCompanionHome'),
},
deviceLink: {
onRemotePush: subscription('remotePush'),
async invoke(_device: string, channel: string) {
if (channel !== REMOTE_RESOURCE_GET_CHANNEL) throw new Error('Unexpected settings action');
const t = i18n.t.bind(i18n);
const status = t('scheduler.presentation.status.active');
const issue = t('logic.errors.scheduleRemoteAgentLocationUnsupported');
const skipped = t('bots.cloud.projectSchedules.skipped', { count: 1 });
return {
ref: { collectionId: 'teammates', kind: 'bot', id: buddy.id },
revision: 'fixture-revision',
display: { title: buddy.name },
blocks: [{
id: 'project-automations',
primitive: 'markdown',
title: t('bots.cloud.projectSchedules.title'),
fallbackMarkdown: [
t('bots.cloud.projectDesktopNotificationUnavailable'), skipped + '\n' + issue,
`• Daily reading notes · ${status}`,
].join('\n\n'),
}],
};
},
},
}),
render: ctx => (
<AppFrame header={false}>
{ctx.case === 'default' ? <BotHomeComputerSetting bot={buddy} /> : <ProjectSettings />}
</AppFrame>
),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// The real Desktop controls consume the same read-only settings block shape as the Host fixture.
export default {
name: 'companion-project-automations',
entry: './companion-project-automations-fixture.tsx',
viewport: { width: 720, height: 480 },
real: 'BotHomeComputerSetting, ConfirmDialog, RemoteBotSettings, remote resource parser, themes and translations',
notCovered: 'The device and plan responses are synthetic. Host import, execution, and hand-back are checked separately against SQLite and Device Link.',
cases: {
default: { about: 'Confirm moving the buddy to Cloud Cindy' },
plans: { about: 'Read project plans and an unsupported route on Cloud Cindy' },
},
async check(page, ui) {
const notificationNote = await ui.t('bots.cloud.projectDesktopNotificationUnavailable');
if (ui.case === 'default') {
await page.getByTestId('bot-home-computer-row').click();
await page.getByRole('menuitem', { name: await ui.t('bots.cloud.switchTo', { device: 'Cloud Cindy' }) }).click();
const confirm = page.getByRole('alertdialog');
await confirm.getByText(await ui.t('bots.cloud.switchDescription', { name: 'Mia', device: 'Cloud Cindy' })).waitFor();
if (ui.role !== 'before') await confirm.getByText(notificationNote, { exact: true }).waitFor();
return;
}
await page.getByRole('button', { name: await ui.t('bots.cloud.projectSchedules.title') }).click();
await page.getByRole('heading', { name: await ui.t('bots.cloud.projectSchedules.title') }).waitFor();
await page.getByText(await ui.t('logic.errors.scheduleRemoteAgentLocationUnsupported'), { exact: false }).waitFor();
await page.getByText(notificationNote, { exact: false }).waitFor();
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -637,13 +637,18 @@ describe('materializeCompanion', () => {
const { api } = cloud([profilePref, { key: readyKey, value: value('daily') },
{ key: unsupportedKey, value: value('other-device') }]);
const { state } = memoryState();
const { host } = fakeLocal({ applyAutomations: vi.fn(async () => ['other-device']) });
const { host } = fakeLocal({ applyAutomations: vi.fn(async () => new Map([['other-device', 'agent-location' as const]])) });
await materializeCompanion({ api, state, host, actor, roomId: async () => ROOM });
const entry = state.bot('bot_mia');
expect(entry?.demoted).toBeUndefined();
expect(entry?.prefs[readyKey]).toMatchObject({ local: true });
expect(entry?.prefs[unsupportedKey]?.local).not.toBe(true);
expect(entry?.restoreBlockedKeys).toEqual([unsupportedKey]);
expect(entry?.automationRestoreIssues).toEqual({ [unsupportedKey]: 'agent-location' });
const updated = fakeLocal({ applyAutomations: vi.fn(async () => new Map()) });
await materializeCompanion({ api, state, host: updated.host, actor, roomId: async () => ROOM });
expect(state.bot('bot_mia')?.automationRestoreIssues).toBeUndefined();
expect(state.bot('bot_mia')?.restoreBlockedKeys).toBeUndefined();
});

describe('capability setup', () => {
Expand Down
22 changes: 13 additions & 9 deletions apps/desktop/src/main/companion-cloud/materialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type { BotSkillFile } from '../maker-ipc/botSkillFiles.js';
import { companionSkillFileFetch, parseCompanionSkillFiles } from './skillFiles.js';
import type { CompanionBotState, CompanionCloudState } from './state.js';
import { readCompanionRows, storedValueHash, type CompanionStore } from './store.js';
import { errorCode, isTransientAttachmentFailure, type CompanionApi, type CompanionLog } from './types.js';
import { errorCode, isTransientAttachmentFailure, type CompanionApi, type CompanionAutomationRestoreIssue, type CompanionLog } from './types.js';
import {
COMPANION_AUTOMATION_PREFIX, COMPANION_CAPABILITIES_KEY, COMPANION_MEMORY_PREFIX, COMPANION_PROFILE_KEY, COMPANION_PROJECT_CARRYOVER_KEY,
COMPANION_PROJECT_RULES_KEY, COMPANION_ROUTINE_PREFIX, COMPANION_SKILL_FILES_PREFIX, COMPANION_SKILL_PREFIX, COMPANION_TODO_PREFIX,
Expand Down Expand Up @@ -99,8 +99,9 @@ export interface CompanionMaterializeHost {
* The project's automations (`companion.automation.v1:<configId>`): each value is upserted by its
* config id with its paused state, a tombstone (`value: null`) removes it.
*/
/** IDs whose definitions could not be restored on this computer. */
applyAutomations?: (botId: string, rows: Array<{ id: string; value: unknown }>, fence: CompanionWriteFence) => Promise<string[] | void>;
/** IDs and safe reason codes for definitions that could not restore here. */
applyAutomations?: (botId: string, rows: Array<{ id: string; value: unknown }>, fence: CompanionWriteFence) =>
Promise<ReadonlyMap<string, CompanionAutomationRestoreIssue> | void>;
/**
* Merging a copy: its project rules are added to this teammate's own under a heading naming
* where they came from; rules already included write nothing.
Expand Down Expand Up @@ -288,7 +289,7 @@ export async function materializeCompanion(input: {
const profileRow = prefs.get(COMPANION_PROFILE_KEY);
if (profileRow && profile) applied.set(COMPANION_PROFILE_KEY, { hash: valueHash(profileRow.value), revision: profileRow.revision });
const failedKeys = new Set<string>();
const skippedAutomationKeys = new Set<string>();
const skippedAutomationKeys = new Map<string, CompanionAutomationRestoreIssue>();
const apply = async (kind: string, keys: readonly string[], run: () => Promise<void>) => {
try { await run(); } catch (error) {
if (errorCode(error) === 'OWNER_CHANGED') throw error;
Expand Down Expand Up @@ -415,11 +416,12 @@ export async function materializeCompanion(input: {
const automationRows = [...prefs].filter(([key]) => key.startsWith(COMPANION_AUTOMATION_PREFIX));
if (automationRows.length && host.applyAutomations) {
await apply('automation', automationRows.map(([key]) => key), async () => {
const skipped = new Set(await step(() => host.applyAutomations!(botId,
automationRows.map(([key, row]) => ({ id: key.slice(COMPANION_AUTOMATION_PREFIX.length), value: row.value })), fence)) ?? []);
const skipped = await step(() => host.applyAutomations!(botId,
automationRows.map(([key, row]) => ({ id: key.slice(COMPANION_AUTOMATION_PREFIX.length), value: row.value })), fence));
for (const [key, row] of automationRows) {
if (skipped.has(key.slice(COMPANION_AUTOMATION_PREFIX.length))) {
skippedAutomationKeys.add(key);
const issue = skipped?.get(key.slice(COMPANION_AUTOMATION_PREFIX.length));
if (issue) {
skippedAutomationKeys.set(key, issue);
} else {
applied.set(key, { hash: row.value === null ? TOMBSTONE_HASH : valueHash(row.value), revision: row.revision });
}
Expand Down Expand Up @@ -480,7 +482,9 @@ export async function materializeCompanion(input: {
for (const key of failedKeys) blocked.add(key);
// A well-formed automation can be unsupported on the new main. Retain its
// cloud value for hand-back, even when the rest of the take-over succeeds.
for (const key of skippedAutomationKeys) blocked.add(key);
for (const key of skippedAutomationKeys.keys()) blocked.add(key);
if (skippedAutomationKeys.size) entry.automationRestoreIssues = Object.fromEntries(skippedAutomationKeys);
else delete entry.automationRestoreIssues;
if (blocked.size) entry.restoreBlockedKeys = [...blocked]; else delete entry.restoreBlockedKeys;
if (!keepCursor) entry.mirror = { sessionId, ...cursor };
if (needsRebuild) entry.pendingRebuild = true;
Expand Down
21 changes: 13 additions & 8 deletions apps/desktop/src/main/companion-cloud/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
*
* The file and scheduler side is injected (host.ts) so the rules here stay testable.
*/
import { errorCode, type CompanionLog } from './types.js';
import { parseScheduleUnsupportedReason } from '@cindy/maker-shared/schedule-errors';
import { errorCode, type CompanionAutomationRestoreIssue, type CompanionLog } from './types.js';
import {
COMPANION_AUTOMATION_PREFIX, COMPANION_PROJECT_CARRYOVER_KEY, COMPANION_PROJECT_RULES_KEY, canonicalJson, type CompanionPreferenceValue,
} from './uploader.js';
Expand Down Expand Up @@ -149,30 +150,30 @@ function localRoute(config: ProjectAutomationValue['config'], selfDeviceId: stri
export async function applyProjectAutomations(input: {
botId: string; rows: Array<{ id: string; value: unknown }>; io: CompanionProjectIo;
selfDeviceId: string | null; assertCurrent: () => void; log?: CompanionLog;
}): Promise<string[]> {
}): Promise<Map<string, CompanionAutomationRestoreIssue>> {
const { io } = input;
const unrestored: string[] = [];
const unrestored = new Map<string, CompanionAutomationRestoreIssue>();
const workingDir = await io.prepareProject(input.botId, input.assertCurrent);
input.assertCurrent();
const current = new Map((await io.automations(workingDir)).map(entry => [entry.config.id, entry]));
async function keepUnrestored(id: string, here: ProjectAutomationEntry | undefined) {
async function keepUnrestored(id: string, here: ProjectAutomationEntry | undefined, reason: CompanionAutomationRestoreIssue) {
// The former local definition may still be active from before a hand-over.
// Keep the newer cloud value and prevent the old prompt from running here.
input.assertCurrent();
if (here && !here.paused) await io.setAutomationPaused(workingDir, id, true);
unrestored.push(id);
unrestored.set(id, reason);
}
for (const { id, value } of input.rows) {
input.assertCurrent();
if (!CONFIG_ID.test(id)) { unrestored.push(id); continue; }
if (!CONFIG_ID.test(id)) { unrestored.set(id, 'configuration'); continue; }
const here = current.get(id);
if (value === null) {
if (here) await io.removeAutomation(workingDir, id);
continue;
}
const arrived = readAutomation(id, value);
if (!arrived) {
await keepUnrestored(id, here);
await keepUnrestored(id, here, 'configuration');
input.log?.warn('Buddy automation skipped: unreadable definition');
continue;
}
Expand All @@ -184,7 +185,11 @@ export async function applyProjectAutomations(input: {
if (!here || canonicalJson(here.config) !== canonicalJson(config)) {
try { await io.upsertAutomation(workingDir, config); } catch (error) {
if ((error as { code?: unknown } | null)?.code !== 'INVALID_PARAMS') throw error;
await keepUnrestored(id, here);
const reason = error instanceof Error
? parseScheduleUnsupportedReason(error.message.replace(/^\[INVALID_PARAMS\] /, ''))
: undefined;
await keepUnrestored(id, here, reason === 'agent-location' || reason === 'bound-model-selection'
? reason : 'configuration');
input.log?.warn('Buddy automation skipped: invalid definition');
continue;
}
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/main/companion-cloud/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { z } from 'zod';
import { ownerScopedUserDataPath } from '../appSessionState.js';
import { userDataPath } from '../userDataPath.js';
import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
import type { CompanionLog } from './types.js';
import { companionAutomationRestoreIssues, type CompanionLog } from './types.js';

/** One id per Cindy installation, shared by the desktop and Node Host assemblies. */
export function companionInstallationId(): string {
Expand Down Expand Up @@ -71,6 +71,8 @@ const bot = z.object({
storeSeeded: z.boolean().optional(),
/** Local restore failed for these cloud keys. No local value or deletion may replace them. */
restoreBlockedKeys: z.array(z.string()).optional(),
/** Last take-over's unsupported project schedules, for the settings projection. */
automationRestoreIssues: z.record(z.string(), z.enum(companionAutomationRestoreIssues)).optional(),
/** This computer gave the companion away; never re-register it as home here. */
demoted: z.boolean().optional(),
/** Cloud history was added while the canonical Session was busy; rebuild at the next idle point. */
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/main/companion-cloud/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/** The Chat Server request function owned by chatServer.ts (account/endpoint bound). */
export type CompanionApi = <T>(route: string, method?: string, data?: unknown, actorId?: string) => Promise<T>;

export const companionAutomationRestoreIssues = ['agent-location', 'bound-model-selection', 'configuration'] as const;
export type CompanionAutomationRestoreIssue = typeof companionAutomationRestoreIssues[number];

export interface CompanionLog {
warn: (message: string, meta?: Record<string, unknown>) => void;
info?: (message: string, meta?: Record<string, unknown>) => void;
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/main/scheduler-host/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export interface SchedulerHostRuntime<Deps extends SchedulerHostStartDeps> {
projectAutomations?: boolean | 'explicit';
/** Existing teammate projects sync directly; deleted ones cannot be recreated by late writes. */
getTeammateProjectState?(workingDir: string): Promise<TeammateProjectState | null>;
defaultProjectDesktopNotification?: boolean;
supportsProjectDesktopNotification?: boolean;
validateProjectSchedule?: ConstructorParameters<typeof ProjectAutomationLoader>[0]['validateSchedule'];
/** Advances task activity & wakes snooze on host-level failure notifications (plugin stops and stall-guard forced failures). */
touchUserSendInDb?: (sessionId: string, atMs?: number) => Promise<void>;
Expand Down Expand Up @@ -263,7 +263,7 @@ export function createSchedulerHost<Deps extends SchedulerHostStartDeps>(runtime
getDb: deps.getDb,
logger: deps.logger,
...(runtime.getTeammateProjectState ? { getTeammateProjectState: runtime.getTeammateProjectState } : {}),
defaultDesktopNotification: runtime.defaultProjectDesktopNotification,
supportsDesktopNotification: runtime.supportsProjectDesktopNotification,
validateSchedule: runtime.validateProjectSchedule,
});
// archived 兜底要 scheduler.pause/update,runner 反向持有 scheduler
Expand Down
Loading