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。

feat(teammates): streamline glance tasks outputs and due todos

zqchrisc8fa30787708
diff --git a/apps/desktop/scripts/fixtures/teammate-glance/glance-fixture.tsx b/apps/desktop/scripts/fixtures/teammate-glance/glance-fixture.tsx
index f13203c4e7..3e1cd45017 100644
--- a/apps/desktop/scripts/fixtures/teammate-glance/glance-fixture.tsx
+++ b/apps/desktop/scripts/fixtures/teammate-glance/glance-fixture.tsx
@@ -19,7 +19,7 @@ const today = todoLocalDate(new Date(), zone);
const friday = new Date(Date.now() + 3 * 86_400_000).toISOString().slice(0, 10);
function items(caseName: string): TeammateTodo[] {
- if (caseName === 'new') return [];
+ if (caseName === 'new' || caseName === 'activity') return [];
return [
todo('t1', 'Reply to MagicLizi about the release date 回 MagicLizi 的邮件,确认发版时间', 'mail', 'MagicLizi', {
sourceDeadline: { kind: 'date', date: today, timeZone: zone },
@@ -56,7 +56,7 @@ mountPage({
<BotSessionContentHeaderRegistration
bot={ctx.case === 'new'
? { id: 'bot-new', name: '葫芦', sessionId: 'chat-new', canonicalChat: true }
- : { id: 'cindy-default', name: 'Cindy', templateId: 'cindy', sessionId: 'chat-1', canonicalChat: true }}
+ : { id: 'cindy-default', name: 'Cindy', avatar: 'cindy://avatar/preset/cindy', templateId: 'cindy', sessionId: 'chat-1', canonicalChat: true }}
/>
<div className="min-h-0 flex-1 p-6" data-ui-page-subject />
</AppFrame>
diff --git a/apps/desktop/scripts/fixtures/teammate-glance/ui-page.mjs b/apps/desktop/scripts/fixtures/teammate-glance/ui-page.mjs
index 715afee0e8..8796b742bd 100644
--- a/apps/desktop/scripts/fixtures/teammate-glance/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/teammate-glance/ui-page.mjs
@@ -12,10 +12,15 @@ export default {
notCovered:
'Live todo/delegation data, cloud companion home switching, remote teammates over device-link, sending the quoted todo or 帮我查查, toggling the daily check, opening files',
stubs: {
+ 'src/renderer/features/device-link/refreshRemoteSessions': `export const refreshRemoteDeviceSessions=async()=> 'done';`,
+ 'src/renderer/hooks/useCCSessions': `const tasks=[{id:'task-1',title:'整理项目反馈',status:'active',updatedAt:'2026-10-28T10:00:00Z'}, {id:'task-2',title:'完善手机任务入口',status:'active',updatedAt:'2026-10-28T09:00:00Z'}];export const useCCSessions=()=>({sessions:${data}.case==='new'?[]:tasks});`,
+ 'src/renderer/features/bots/botFollowScopes': { partial: `export const useTaskCreatorIndex=()=>new Map(['task-1','task-2'].map(id=>[JSON.stringify([null,id]),new Set([JSON.stringify(['teammate','cindy'])])]));` },
+ 'src/renderer/contexts/PrRefsContext': { partial: `export const usePrRefsForSessions=ids=>ids.length?[{sessionId:'task-1',owner:'example',repo:'app',prNumber:42,lastSeenAt:${now + 1}}]:[]; export const usePrStatuses=()=>({statuses:new Map([['example/app#42',{ok:true,status:'merged',title:'修复伙伴任务的跨设备入口'}]]),successfulStatuses:new Map()});` },
+ 'src/renderer/lib/sessionAttentionStore': { partial: `export const useSessionAttentionKind=id=>id==='task-1'?'done':undefined;` },
'src/renderer/features/bots/botStore': {
partial: `export const useBotProfiles=()=>${data}.case==='new'?[]:[{id:'cindy-default',name:'Cindy',templateId:'cindy',status:'active',sessionId:'chat-1'}];export const useBotUnreadCounts=()=>({});`,
},
- 'src/renderer/features/bots/useRemoteBots': `export const useRemoteBots=()=>${data}.case==='new'?[]:[
+ 'src/renderer/features/bots/useRemoteBots': `export const useRemoteCindyIds=()=>new Set(); export const useRemoteBots=()=>${data}.case==='new'?[]:[
{id:'cindy-default',name:'Cindy',deviceId:'mini',deviceName:'Mac-mini',online:true,sessionId:'r1',avatar:'',status:'active'},
{id:'cindy-default',name:'Cindy',deviceId:'mbp',deviceName:'Chris-MBP-M5',online:false,sessionId:'r2',avatar:'',status:'active'},
{id:'cindy-default',name:'Cindy',deviceId:'imac',deviceName:'Office iMac',online:false,sessionId:'r3',avatar:'',status:'active'}];`,
@@ -30,14 +35,15 @@ export default {
cases: {
default: { about: 'Cindy on several computers, todos with one due today, finished deliverables' },
menu: { about: 'Right-clicking a todo offers only Delete' },
- new: { about: 'A new teammate: Computers, and the todo block with only 帮我查查 and the daily switch; no outputs' },
+ new: { about: 'Empty teammate: only Computers; no todo suggestions or outputs' },
+ activity: { about: 'No todos, attributed recent tasks, unread result and true PR title' },
},
async ready(page) {
await page.getByTestId('bot-glance-button').waitFor();
},
async check(page, ui) {
const button = page.getByTestId('bot-glance-button');
- if (ui.case !== 'new') {
+ if (ui.case !== 'new' && ui.case !== 'activity') {
await page.waitForFunction(() =>
document.querySelector('[data-testid="bot-glance-button"] span[aria-hidden]') !== null,
);
@@ -48,19 +54,27 @@ export default {
await popover.waitFor();
if (ui.case === 'new') {
assert.equal(await page.getByTestId('bot-glance-todo').count(), 0, 'no todo rows');
- assert.equal(await page.getByTestId('bot-glance-check').count(), 1, '帮我查查 even without todos');
- assert.equal(await page.getByTestId('bot-glance-daily-check').count(), 1, 'daily switch');
+ assert.equal(await page.getByTestId('bot-glance-check').count(), 0, 'no check prompt when empty');
+ assert.equal(await page.getByTestId('bot-glance-daily-check').count(), 0, 'no daily prompt');
assert.equal(await page.getByTestId('bot-glance-output').count(), 0, 'no outputs block');
assert.equal(await page.getByTestId('bot-glance-computer').count(), 1, 'only this computer');
await ui.capture('open');
return;
}
- assert.equal(await page.getByTestId('bot-glance-todo').count(), 5, 'five todos before Show more');
+ if (ui.case === 'activity') {
+ assert.equal(await page.getByTestId('bot-glance-task').count(), 2);
+ assert.equal(await page.getByTestId('bot-glance-pr').count(), 1);
+ assert.equal(await page.getByTestId('bot-glance-check').count(), 0);
+ await ui.capture('open');
+ return;
+ }
+ assert.equal(await page.getByTestId('bot-glance-todo').count(), 2, 'two todos leave room for recent tasks');
assert.equal(await page.getByTestId('bot-glance-check').count(), 1, '帮我查查 first in the todo block');
- assert.equal(await page.getByTestId('bot-glance-output').count(), 3, 'three outputs before Show more');
+ assert.equal(await popover.locator('[data-testid="bot-glance-output"], [data-testid="bot-glance-pr"]').count(), 3, 'three mixed outputs before Show more');
assert.equal(await page.getByTestId('bot-glance-computer').count(), 2, 'offline computers folded');
const box = await popover.boundingBox();
assert.ok(box.width <= 360 && box.x + box.width <= ui.viewport.width, 'popover stays inside the window');
+ assert.ok(box.y >= 0 && box.y + box.height <= ui.viewport.height + 1, 'popover uses available height without leaving the window');
if (ui.case === 'menu') {
await page.getByTestId('bot-glance-todo').nth(1).click({ button: 'right' });
await page.getByRole('menuitem').first().waitFor();
diff --git a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
index 6bf9401077..31323ae73d 100644
--- a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
+++ b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
@@ -616,6 +616,18 @@ export function usePrRefsForSession(sessionId: string): SessionPrRef[] {
);
}
+/** Bounded multi-task views reuse the same refs cache; unrelated changes keep the snapshot stable. */
+export function usePrRefsForSessions(sessionIds: readonly string[]): SessionPrRef[] {
+ const store = useContext(PrStoreContext);
+ const previous = useRef<SessionPrRef[]>([]);
+ const read = () => {
+ const next = sessionIds.flatMap(id => store.getRefs(id).slice(0, MAX_STATUS_QUERIES));
+ if (next.length !== previous.current.length || next.some((ref, i) => ref !== previous.current[i])) previous.current = next;
+ return previous.current;
+ };
+ return useSyncExternalStore(store.subscribe, read, read);
+}
+
/** 单个 PR 的状态(按会话 + prStatusKey 订阅;结果未变时引用稳定)。列表行徽标专用。 */
export function usePrStatus(sessionId: string, key: string): PrStatusResult | undefined {
const store = useContext(PrStoreContext);
diff --git a/apps/desktop/src/renderer/features/bots/BotGlancePopover.tsx b/apps/desktop/src/renderer/features/bots/BotGlancePopover.tsx
index 72cc7bb48a..3efceb6a7b 100644
--- a/apps/desktop/src/renderer/features/bots/BotGlancePopover.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGlancePopover.tsx
@@ -1,19 +1,13 @@
-/**
- * 伙伴「近况」浮层(伙伴聊天头部的网格按钮)。只有三块,没有内容的块整块不出现:
- * - 电脑:伙伴在哪台上运行,点另一台在线的电脑就换过去;离线的收进「离线 N 台」。
- * 云端伙伴换主力电脑沿用原来的确认流程;Cindy 的多台副本直接打开那台上的她。
- * - 待办:主人要做的事。第一行「帮我查查」让伙伴现在去已连接的来源里找新待办(作为主人的一句话发进对话),
- * 下面一行开关让伙伴每个工作日早上自己查一次。待办本身没有按钮:点一条就作为引用放进输入框,
- * 由主人一句话交代;右键只能删除(可撤销)。到期的那条在期限前带红点,入口在主人还没看过时也亮同样的红点。
- * - 输出内容:伙伴开的任务做完时留下的成品文件,点开即打开;别的电脑上的打开来源任务。
+/** Partner glance: existing computer controls, nonempty owner todos, attributed tasks and outputs.
+ * Task attention and PR state are read-only projections of the ordinary task list stores.
*/
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react';
-import { Check, ChevronDown, LayoutGrid, Monitor, ScanSearch } from 'lucide-react';
+import { Check, ChevronDown, LayoutGrid, Monitor, ScanSearch, MessageCircle, GitPullRequest, X } from 'lucide-react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { buildTodoReferenceHref } from '@cindy/maker-shared/agent-input-projection';
-import { todoDateLabel, todoDue, type TeammateTodo } from '@cindy/maker-shared/teammate-todo';
+import { todoDateLabel, todoDue, todoDueSoon, type TeammateTodo } from '@cindy/maker-shared/teammate-todo';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { FileTypeIcon } from '@/components/ui/file-type-icon';
@@ -24,12 +18,20 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
-import { Switch } from '@/components/ui/switch';
+import { AttentionDot } from '@/components/sidebar/AttentionDot';
+import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
+import { useCCSessions } from '@/hooks/useCCSessions';
+import { usePrActions, usePrRefsForSessions, usePrStatuses } from '@/contexts/PrRefsContext';
+import { prStatusKey, sessionPrUrl, type SessionPrRef } from '@cindy/maker-shared';
+import { PR_STATUS_ICON, PR_STATUS_COLOR } from '@/features/cc-agent/gitContextPrVisuals';
+import { sessionActivityMs } from '@/features/cc-agent/lib/dateSessionGrouping';
+import { matchesTaskCreators, useTaskCreatorIndex } from './botFollowScopes';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import type { Session } from '@/lib/ccAgent.types';
import { makerChatStore } from '@/lib/makerChatStore';
import * as sessionService from '@/lib/sessionService';
-import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { remoteProjectsStore, useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';
+import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';
import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
import { insertTodoReferenceIntoComposer } from '@/lib/composerActionsBus';
import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
@@ -45,7 +47,7 @@ import { isBotPrimaryGeneratedFile } from './botGeneratedArtifacts';
import { useBotProfiles, useBotUnreadCounts } from './botStore';
import { cloudRemoteBots, withoutCloudCompanions, withoutShadowedBots } from './companionCloudPresentation';
import { useCompanionCloud } from './companionCloudStore';
-import { cindyDeviceKey, cindyDeviceOptions, isCindyDeviceBot } from './cindyDeviceRoster';
+import { cindyDeviceKey, cindyDeviceOptions, isCindyDeviceBot, taskCreatorFilterKey } from './cindyDeviceRoster';
import {
dueTodos,
hasUnseenDue,
@@ -55,10 +57,11 @@ import {
useGlanceTodos,
type GlanceTodoHost,
} from './botGlanceTodos';
-import { useRemoteBots } from './useRemoteBots';
+import { useRemoteBots, useRemoteCindyIds } from './useRemoteBots';
/** 每块先列几条,其余收进「显示更多」。 */
-const TODO_PREVIEW = 5;
+const TODO_PREVIEW = 2;
+const TASK_PREVIEW = 5;
const OUTPUT_PREVIEW = 3;
const OUTPUT_LIMIT = 30;
@@ -67,10 +70,10 @@ function useToggle(): [boolean, () => void] {
return [open, () => setOpen((value) => !value)];
}
-function Section({ label, children, divided = true }: { label: string; children: ReactNode; divided?: boolean }) {
+function Section({ label, children, divided = true, action }: { label: string; children: ReactNode; divided?: boolean; action?: ReactNode }) {
return (
- <section className={cn('px-2 py-2', divided && 'border-t border-[var(--border-default)]')}>
- <h3 className="px-2 pb-1 pt-0.5 text-12 font-normal text-[var(--text-tertiary)]">{label}</h3>
+ <section className={cn('px-2 py-1.5', divided && 'border-t border-[var(--border-default)]')}>
+ <div className="flex items-center justify-between px-2 pb-1 pt-0.5"><h3 className="text-12 font-normal text-[var(--text-tertiary)]">{label}</h3>{action}</div>
<div className="flex flex-col">{children}</div>
</section>
);
@@ -80,6 +83,7 @@ function Row({
icon,
title,
meta,
+ inlineMeta = false,
trailing,
muted = false,
onClick,
@@ -90,6 +94,7 @@ function Row({
icon?: ReactNode;
title: string;
meta?: string;
+ inlineMeta?: boolean;
trailing?: ReactNode;
muted?: boolean;
onClick?: () => void;
@@ -102,22 +107,23 @@ function Row({
{icon ? (
<span className="flex w-5 shrink-0 justify-center text-[var(--text-secondary)]">{icon}</span>
) : null}
- <span className="min-w-0 flex-1">
+ <span className={cn('min-w-0 flex-1', inlineMeta && 'flex items-baseline gap-2')}>
<span
title={title}
className={cn(
- 'block truncate text-13',
+ 'block min-w-0 truncate text-13 leading-5',
+ inlineMeta && 'flex-1',
muted ? 'text-[var(--text-secondary)]' : 'text-[var(--text-primary)]',
)}
>
{title}
</span>
- {meta ? <span title={meta} className="block truncate text-12 text-[var(--text-tertiary)]">{meta}</span> : null}
+ {meta ? <span title={meta} className={cn('block truncate text-12 leading-4 text-[var(--text-tertiary)]', inlineMeta && 'max-w-[40%] shrink-0')}>{meta}</span> : null}
</span>
{trailing ? <span className="flex shrink-0 items-center gap-1.5 pl-2 text-12 text-[var(--text-secondary)]">{trailing}</span> : null}
</>
);
- const className = 'flex min-h-11 w-full items-center gap-3 rounded-lg px-2 py-1.5 text-left';
+ const className = 'flex min-h-8 w-full items-center gap-3 rounded-lg px-2 py-1 text-left';
if (!onClick)
return (
<div data-testid={testId} className={className}>
@@ -146,7 +152,7 @@ function FoldRow({ label, open, onClick, indent }: { label: string; open: boolea
aria-expanded={open}
onClick={onClick}
className={cn(
- 'flex min-h-9 w-full items-center gap-1.5 rounded-lg px-2 text-left text-12 text-[var(--text-tertiary)] outline-none',
+ 'flex min-h-8 w-full items-center gap-1.5 rounded-lg px-2 text-left text-12 text-[var(--text-tertiary)] outline-none',
'hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]',
indent && 'pl-10',
)}
@@ -187,6 +193,7 @@ function ComputerRows({ rows }: { rows: ComputerRowModel[] }) {
title={row.name}
muted={!row.current && !row.online}
meta={row.current ? t('bots.glance.runningHere') : row.online ? t('bots.glance.online') : t('bots.glance.offline')}
+ inlineMeta
trailing={
row.current ? (
<Check size={14} className="text-[var(--text-primary)]" aria-label={t('bots.glance.current')} />
@@ -326,25 +333,21 @@ function sourceText(todo: TeammateTodo, t: (key: string) => string): string {
function TodoRow({
todo,
- done,
onOpen,
onMenu,
}: {
todo: TeammateTodo;
- done: boolean;
onOpen: (todo: TeammateTodo) => void;
onMenu: (todo: TeammateTodo, x: number, y: number, origin: HTMLButtonElement) => void;
}) {
const { t, i18n } = useTranslation();
- const due = !done && todoDue(todo);
- const date = done ? '' : todoDateLabel(todo, i18n.language);
- const completion = done ? todo.history[todo.history.length - 1]?.summary : undefined;
+ const due = todoDue(todo);
+ const date = todoDateLabel(todo, i18n.language);
return (
<Row
testId="bot-glance-todo"
title={todo.title}
- muted={done}
- meta={completion ? completion : sourceText(todo, t)}
+ meta={sourceText(todo, t)}
trailing={
date ? (
<>
@@ -386,7 +389,7 @@ function DailyCheckSwitch({ host, todos }: { host: GlanceTodoHost; todos: Return
const { t } = useTranslation();
const [busy, setBusy] = useState(false);
const checked = todos.todos.dailyCheck;
- if (checked === null) return null;
+ if (!checked) return null;
const change = async (next: boolean) => {
setBusy(true);
try {
@@ -398,7 +401,7 @@ function DailyCheckSwitch({ host, todos }: { host: GlanceTodoHost; todos: Return
}
};
return (
- <label
+ <div
data-testid="bot-glance-daily-check"
className="flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-lg px-2 py-1.5 hover:bg-[var(--surface-hover)]"
>
@@ -407,8 +410,10 @@ function DailyCheckSwitch({ host, todos }: { host: GlanceTodoHost; todos: Return
<span className="block truncate text-13 text-[var(--text-primary)]">{t('bots.glance.dailyCheck')}</span>
<span className="block truncate text-12 text-[var(--text-tertiary)]">{t('bots.glance.dailyCheckMeta')}</span>
</span>
- <Switch checked={checked} disabled={busy} onCheckedChange={(next) => void change(next)} />
- </label>
+ <button type="button" disabled={busy} aria-label={t('bots.glance.stopDailyCheck')}
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ onClick={() => void change(false)}><X size={16} /></button>
+ </div>
);
}
@@ -425,10 +430,11 @@ function Todos({
}) {
const { t } = useTranslation();
const [showAll, toggleAll] = useToggle();
- const [showDone, toggleDone] = useToggle();
const [menu, setMenu] = useState<{ todo: TeammateTodo; x: number; y: number } | null>(null);
const menuOrigin = useRef<HTMLButtonElement | null>(null);
- const { open, done, doneTotal, openTotal } = todos.todos;
+ const now = new Date();
+ const open = todos.todos.open.filter(todo => todoDueSoon(todo, now));
+ const openTotal = open.length;
const check = () => {
onClose();
@@ -474,23 +480,21 @@ function Todos({
}
};
+ if (!todos.loaded) return null;
+ if (openTotal === 0) return todos.failed
+ ? <Section label={t('bots.glance.todos')}><Row title={t('bots.glance.loadFailed')} onClick={() => void todos.refresh()} /></Section>
+ : null;
const visible = showAll ? open : open.slice(0, TODO_PREVIEW);
const hiddenCount = Math.max(0, openTotal - TODO_PREVIEW);
return (
- <Section label={t('bots.glance.todos')}>
- <Row
- testId="bot-glance-check"
- icon={<ScanSearch size={16} />}
- title={t('bots.glance.check')}
- meta={t('bots.glance.checkMeta')}
- onClick={check}
- />
+ <Section label={t('bots.glance.todos')} action={<button type="button" data-testid="bot-glance-check"
+ aria-label={t('bots.glance.check')} title={t('bots.glance.check')} onClick={check}
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"><ScanSearch size={16} /></button>}>
<DailyCheckSwitch host={host} todos={todos} />
{visible.map((todo) => (
<TodoRow
key={todo.id}
todo={todo}
- done={false}
onOpen={quote}
onMenu={(target, x, y, origin) => {
menuOrigin.current = origin;
@@ -501,23 +505,6 @@ function Todos({
{hiddenCount > 0 ? (
<FoldRow indent={false} open={showAll} onClick={toggleAll} label={showAll ? t('bots.glance.showLess') : t('bots.glance.showMore')} />
) : null}
- {doneTotal > 0 ? (
- <FoldRow indent={false} open={showDone} onClick={toggleDone} label={t('bots.glance.doneCount', { count: doneTotal })} />
- ) : null}
- {showDone
- ? done.map((todo) => (
- <TodoRow
- key={todo.id}
- todo={todo}
- done
- onOpen={quote}
- onMenu={(target, x, y, origin) => {
- menuOrigin.current = origin;
- setMenu({ todo: target, x, y });
- }}
- />
- ))
- : null}
<DropdownMenu open={menu !== null} onOpenChange={(next) => { if (!next) setMenu(null); }}>
{/* 锚点挂到 body:浮层带入场变换,fixed 元素放在里面会按浮层而不是窗口定位。 */}
{createPortal(
@@ -594,21 +581,17 @@ function useOutputs(sessionId: string, botId: string): OutputFile[] {
}, [botId, delegations]);
}
-function dayLabel(at: number, language: string): string {
- const now = new Date();
- const date = new Date(at);
- const startOf = (value: Date) => new Date(value.getFullYear(), value.getMonth(), value.getDate()).getTime();
- const days = Math.round((startOf(now) - startOf(date)) / 86_400_000);
- if (days >= 0 && days <= 1) return new Intl.RelativeTimeFormat(language, { numeric: 'auto' }).format(-days, 'day');
- return new Intl.DateTimeFormat(language, { month: 'numeric', day: 'numeric' }).format(date);
-}
-function Outputs({ sessionId, botId, onClose }: { sessionId: string; botId: string; onClose: () => void }) {
- const { t, i18n } = useTranslation();
+function Outputs({ sessionId, botId, onClose, prs }: { sessionId: string; botId: string; onClose: () => void; prs: SessionPrRef[] }) {
+ const { t } = useTranslation();
const navigate = useNavigate();
const [showAll, toggleAll] = useToggle();
const files = useOutputs(sessionId, botId);
- if (files.length === 0) return null;
+ const outputs = [
+ ...files.map(file => ({ kind: 'file' as const, key: `file:${file.key}`, at: file.at, file })),
+ ...prs.map(pr => ({ kind: 'pr' as const, key: `pr:${prStatusKey(pr)}`, at: pr.lastSeenAt, pr })),
+ ].sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
+ if (outputs.length === 0) return null;
const open = async (file: OutputFile) => {
// 别的电脑上的伙伴:文件路径属于那台电脑,不在这台打开;改为打开那台上的来源任务。
const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
@@ -628,26 +611,99 @@ function Outputs({ sessionId, botId, onClose }: { sessionId: string; botId: stri
onClose();
navigate(await resolveSessionRoute(childId));
};
- const visible = showAll ? files : files.slice(0, OUTPUT_PREVIEW);
+ const visible = showAll ? outputs : outputs.slice(0, OUTPUT_PREVIEW);
return (
<Section label={t('bots.glance.outputs')}>
- {visible.map((file) => (
+ {visible.map(output => output.kind === 'pr' ? <PrOutput key={output.key} pr={output.pr} /> : (
<Row
- key={file.key}
+ key={output.key}
testId="bot-glance-output"
- icon={<FileTypeIcon name={file.name} />}
- title={file.name}
- meta={t('bots.glance.outputMeta', { time: dayLabel(file.at, i18n.language), task: file.taskTitle })}
- onClick={() => void open(file)}
+ icon={<FileTypeIcon name={output.file.name} />}
+ title={output.file.name}
+ onClick={() => void open(output.file)}
/>
))}
- {files.length > OUTPUT_PREVIEW ? (
+ {outputs.length > OUTPUT_PREVIEW ? (
<FoldRow indent={false} open={showAll} onClick={toggleAll} label={showAll ? t('bots.glance.showLess') : t('bots.glance.showMore')} />
) : null}
</Section>
);
}
+// ---------------------------------------------------------------- 近期任务与 PR:只投影已有任务、归属及未读缓存。
+function Activity({ bot, onClose }: { bot: BotChatIdentity; onClose(): void }) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { sessions: local } = useCCSessions({ includeArchived: 'all' });
+ const remote = useRemoteProjectSessions();
+ const creators = useTaskCreatorIndex();
+ const cloud = useCompanionCloud();
+ const cindyIds = useRemoteCindyIds();
+ const key = taskCreatorFilterKey(cindyIds.has(bot.id) ? { ...bot, templateId: 'cindy' } : bot, cloud);
+ const remoteBots = useRemoteBots();
+ const hostsKey = JSON.stringify([...new Map(remoteBots.filter(row => row.online &&
+ taskCreatorFilterKey(cindyIds.has(row.id) ? { ...row, templateId: 'cindy' } : row, cloud) === key)
+ .map(row => [row.deviceId, row.deviceName])).entries()]);
+ useEffect(() => {
+ // Archived remote tasks are lazily loaded by the sidebar; glance needs both buckets.
+ for (const [id, name] of JSON.parse(hostsKey) as Array<[string, string]>) {
+ for (const status of ['active', 'archived'] as const)
+ void refreshRemoteDeviceSessions(id, name, { status, coalescingMode: 'weak' });
+ }
+ }, [hostsKey]);
+ const tasks = useMemo(() => [...local, ...remote]
+ .filter(task => task.id !== bot.sessionId && task.orcaRole !== 'worker'
+ && (task.status === 'active' || task.status === 'archived')
+ && matchesTaskCreators(task, [key], creators))
+ .sort((a, b) => sessionActivityMs(b) - sessionActivityMs(a)).slice(0, OUTPUT_LIMIT), [local, remote, creators, key, bot.sessionId]);
+ const ids = useMemo(() => tasks.map(task => task.id), [tasks]);
+ const { registerPrConsumer } = usePrActions();
+ useEffect(() => {
+ const stops = tasks.map(task => registerPrConsumer(task.id, task.deviceLinkDeviceId));
+ return () => stops.forEach(stop => stop());
+ }, [tasks, registerPrConsumer]);
+ const refs = usePrRefsForSessions(ids);
+ const prs = useMemo(() => {
+ const unique = new Map<string, SessionPrRef>();
+ for (const ref of [...refs].sort((a, b) => b.lastSeenAt - a.lastSeenAt)) {
+ if (!unique.has(prStatusKey(ref))) unique.set(prStatusKey(ref), ref);
+ }
+ return [...unique.values()];
+ }, [refs]);
+ const [allTasks, toggleTasks] = useToggle();
+ const openTask = async (task: Session) => {
+ if (task.deviceLinkDeviceId) remoteProjectsStore.pinSessionOrigin(task.deviceLinkDeviceId, task.id);
+ onClose();
+ navigate(await resolveSessionRoute(task.id));
+ };
+ return <>
+ {tasks.length > 0 ? <Section label={t('bots.glance.recentTasks')}>
+ {(allTasks ? tasks : tasks.slice(0, TASK_PREVIEW)).map(task => <RecentTask key={task.id} task={task} onOpen={() => void openTask(task)} />)}
+ {tasks.length > TASK_PREVIEW ? <FoldRow indent open={allTasks} onClick={toggleTasks} label={t(allTasks ? 'bots.glance.showLess' : 'bots.glance.showMore')} /> : null}
+ </Section> : null}
+ <Outputs sessionId={bot.sessionId ?? ''} botId={bot.id} onClose={onClose} prs={prs} />
+ </>;
+}
+
+function RecentTask({ task, onOpen }: { task: Session; onOpen(): void }) {
+ const attention = useSessionAttentionKind(task.id);
+ const { t } = useTranslation();
+ return <Row testId="bot-glance-task" icon={<MessageCircle size={16} />} title={task.title}
+ onClick={onOpen}
+ trailing={attention === 'done' ? <span className="flex items-center" role="img" aria-label={t('bots.glance.unread')}><AttentionDot tone="done" /></span> : undefined} />;
+}
+
+function PrOutput({ pr }: { pr: SessionPrRef }) {
+ const { statuses, successfulStatuses } = usePrStatuses(pr.sessionId);
+ const result = statuses.get(prStatusKey(pr));
+ const status = result?.ok ? result : successfulStatuses.get(prStatusKey(pr));
+ const kind = status?.ok ? status.status : null;
+ const Icon = kind ? PR_STATUS_ICON[kind] : GitPullRequest;
+ return <Row testId="bot-glance-pr" title={(status?.ok ? status.title?.trim() : undefined) || `${pr.owner}/${pr.repo}`}
+ icon={<Icon size={16} style={{ color: kind ? PR_STATUS_COLOR[kind] : 'var(--text-tertiary)' }} />}
+ onClick={() => void window.electronAPI.openExternal(sessionPrUrl(pr))} />;
+}
+
// ---------------------------------------------------------------- 入口
export function BotGlanceButton({ bot, cloudHome }: { bot: BotChatIdentity; cloudHome: boolean }) {
@@ -697,12 +753,13 @@ export function BotGlanceButton({ bot, cloudHome }: { bot: BotChatIdentity; clou
<PopoverContent
align="end"
sideOffset={6}
+ collisionPadding={12}
data-testid="bot-glance-popover"
aria-label={t('bots.glance.open', { name: bot.name })}
className="w-[360px] max-w-[calc(100vw-24px)] overflow-y-auto p-0"
- style={{ maxHeight: 'min(640px, calc(100vh - 96px))', ...WINDOW_NO_DRAG_STYLE }}
+ style={{ maxHeight: 'var(--radix-popover-content-available-height, calc(100dvh - 24px))', ...WINDOW_NO_DRAG_STYLE }}
>
- <div className="flex items-center gap-3 px-4 pb-2 pt-4">
+ <div className="flex items-center gap-3 px-4 pb-1 pt-3">
<BotAvatar bot={bot} size="md" />
<span className="min-w-0 truncate text-15 font-medium text-[var(--text-primary)]">{bot.name}</span>
</div>
@@ -716,7 +773,7 @@ export function BotGlanceButton({ bot, cloudHome }: { bot: BotChatIdentity; clou
/>
</Section>
<Todos host={host} sessionId={sessionId} todos={todos} onClose={() => setOpen(false)} />
- <Outputs sessionId={sessionId} botId={bot.id} onClose={() => setOpen(false)} />
+ <Activity bot={bot} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
{cloudHome ? <HomeSwitchConfirm bot={{ id: bot.id, name: bot.name }} state={homeSwitch} /> : null}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGlancePopover.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botGlancePopover.test.tsx
index 91278961a2..051d79214e 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGlancePopover.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGlancePopover.test.tsx
@@ -7,7 +7,7 @@
* - Bug/规则依据:docs/product-rules/cindy-bots-runtime.md「伙伴近况」;近况取代右侧栏工作台后,待办不再有
* 行内按钮(点一条只交给对话),切电脑并进这里。
* - 现有覆盖缺口:这是新入口;头部测试只验证按钮存在,不覆盖浮层内的行为。
- * - 「帮我查查」与「每天帮我查一次」:没有待办时也在;前者以主人的一句话走普通发送,后者经宿主开关内置例行任务。
+ * - 「帮我查查」与「每天帮我查一次」:空待办收起;有待办时紧凑检查动作走普通发送,关闭每天检查经原宿主入口停用。
* - 最小失败输入:一条今天到期的待办 + 一份带成品文件的委派 + Cindy 在另一台在线、一台离线的电脑上。
* - tier:unit(jsdom 渲染真实组件,宿主 API 用内存 fake)。
* - 实测耗时:见 PR(pnpm --dir apps/desktop exec vitest run 本文件)。
@@ -26,6 +26,14 @@ const h = vi.hoisted(() => ({
remote: [] as Array<Record<string, unknown>>,
delegations: [] as Array<Record<string, unknown>>,
send: vi.fn(async () => true),
+ sessions: [] as Array<Record<string, unknown>>,
+ remoteSessions: [] as Array<Record<string, unknown>>,
+ refs: [] as Array<Record<string, unknown>>,
+ statuses: new Map(),
+ attention: new Map(),
+ scopes: [] as Array<Record<string, unknown>>,
+ pin: vi.fn(),
+ openExternal: vi.fn(),
}));
vi.mock('react-i18next', () => ({
@@ -45,7 +53,25 @@ vi.mock('@/lib/sessionService', () => ({
}));
vi.mock('../BotAvatar', () => ({ BotAvatar: () => <span data-testid="bot-avatar" /> }));
vi.mock('../botStore', () => ({ useBotProfiles: () => h.local, useBotUnreadCounts: () => ({}) }));
-vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => h.remote }));
+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => h.remote, useRemoteCindyIds: () => new Set<string>() }));
+vi.mock('@/features/device-link/refreshRemoteSessions', () => ({ refreshRemoteDeviceSessions: async () => 'done' }));
+vi.mock('@/hooks/useCCSessions', () => ({ useCCSessions: () => ({ sessions: h.sessions }) }));
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ useRemoteProjectSessions: () => h.remoteSessions,
+ remoteProjectsStore: { getSessionDeviceId: (id: string) => h.remoteSessions.find(task => task.id === id)?.deviceLinkDeviceId,
+ getDeviceSessions: () => h.remoteSessions, pinSessionOrigin: h.pin },
+}));
+vi.mock('../botFollowScopes', async importOriginal => {
+ const actual = await importOriginal<typeof import('../botFollowScopes')>();
+ return { ...actual, useTaskCreatorIndex: () => new Map(h.scopes.map(scope =>
+ [JSON.stringify([scope.deviceId ?? null, scope.sessionId]), new Set([JSON.stringify([null, 'bot-1'])])])) };
+});
+vi.mock('@/lib/sessionAttentionStore', () => ({ useSessionAttentionKind: (id: string) => h.attention.get(id) }));
+vi.mock('@/contexts/PrRefsContext', () => ({
+ usePrActions: () => ({ registerPrConsumer: () => () => undefined }),
+ usePrRefsForSessions: (ids: string[]) => h.refs.filter(ref => ids.includes(ref.sessionId as string)),
+ usePrStatuses: () => ({ statuses: h.statuses, successfulStatuses: new Map() }),
+}));
vi.mock('../botDelegationLive', () => ({ useBotDelegations: () => h.delegations }));
vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({
useDeviceLinkDeviceList: () => [{ deviceId: 'self', name: 'Mac-Studio', isSelf: true }],
@@ -69,7 +95,7 @@ function todo(id: string, patch: Partial<TeammateTodo> = {}): TeammateTodo {
status: 'open',
createdAt: '2026-10-20T01:00:00Z',
updatedAt: '2026-10-20T01:00:00Z',
- sourceDeadline: null,
+ sourceDeadline: { kind: 'date', date: todoLocalDate(new Date(), 'UTC'), timeZone: 'UTC' },
deadlineCandidate: null,
suggestedDate: null,
decision: null,
@@ -90,6 +116,7 @@ const dailyCheck = vi.fn(async (_botId: string, enabled?: boolean) => (dailyOn =
beforeEach(() => {
items = [];
+ h.sessions = []; h.remoteSessions = []; h.refs = []; h.scopes = []; h.statuses.clear(); h.attention.clear();
dailyOn = false;
dailyCheck.mockImplementation(async (_botId: string, enabled?: boolean) => (dailyOn = enabled ?? dailyOn));
h.local = [];
@@ -97,11 +124,12 @@ beforeEach(() => {
h.delegations = [];
window.localStorage.clear();
(window as unknown as { electronAPI: unknown }).electronAPI = {
- localDb: { bots: { todos: { list, update, dailyCheck } } },
+ localDb: { bots: { todos: { list, update, dailyCheck }, workbench: { followScopes: async () => h.scopes } } },
maker: { onBotWorkbenchChanged: () => () => undefined },
routines: { onChanged: (listener: () => void) => { routinesChanged = listener; return () => { routinesChanged = null; }; } },
deviceLink: { invoke: vi.fn(), onRemotePush: () => () => undefined },
openPath,
+ openExternal: h.openExternal,
};
});
afterEach(() => {
@@ -143,49 +171,63 @@ describe('BotGlanceButton', () => {
expect(update).toHaveBeenLastCalledWith('bot-1', { id: 't1', expectedRevision: 4, operation: 'restore' });
});
- it('asks the teammate to check for todos as the owner, and switches the weekday check on', async () => {
+ it('hides an empty todo section without stopping an enabled daily routine', async () => {
+ dailyOn = true;
+ await openGlance();
+ expect(screen.queryByText('bots.glance.todos')).toBeNull();
+ expect(dailyCheck.mock.calls.every(call => call[1] === undefined)).toBe(true);
+ });
+
+ it('checks from the compact action and stops the daily routine persistently with its close button', async () => {
+ items = [todo('t1')]; dailyOn = true;
await openGlance();
- // No todos yet: the section still offers 「帮我查查」 and the daily switch.
fireEvent.click(await screen.findByTestId('bot-glance-check'));
await waitFor(() => expect(h.send).toHaveBeenCalledWith('s1', 'bots.glance.checkPrompt', 'm', 'high', 'auto', '/w'));
-
fireEvent.click(screen.getByTestId('bot-glance-button'));
- const toggle = (await screen.findByTestId('bot-glance-daily-check')).querySelector('[role="switch"]')!;
- expect(toggle.getAttribute('aria-checked')).toBe('false');
- fireEvent.click(toggle);
- await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('true'));
- expect(dailyCheck).toHaveBeenLastCalledWith('bot-1', true);
-
- // Paused from the routines list while 近况 is open: the switch follows.
- dailyOn = false;
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.glance.stopDailyCheck' }));
+ await waitFor(() => expect(screen.queryByTestId('bot-glance-daily-check')).toBeNull());
+ expect(dailyCheck).toHaveBeenLastCalledWith('bot-1', false);
await act(async () => routinesChanged?.());
- await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('false'));
+ expect(screen.queryByTestId('bot-glance-daily-check')).toBeNull();
});
- it('keeps the switch when the host refuses it, and hides it for a teammate on an older desktop', async () => {
+ it('keeps the daily row and reports failure when stopping is refused', async () => {
+ items = [todo('t1')];
dailyCheck.mockImplementation(async (_botId: string, enabled?: boolean) => {
if (enabled !== undefined) throw new Error('The teammate is paused');
- return false;
+ return true;
});
await openGlance();
- const toggle = (await screen.findByTestId('bot-glance-daily-check')).querySelector('[role="switch"]')!;
- fireEvent.click(toggle);
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.glance.stopDailyCheck' }));
await waitFor(() => expect(h.toastError).toHaveBeenCalledWith('bots.glance.dailyCheckFailed'));
- expect(toggle.getAttribute('aria-checked')).toBe('false');
- cleanup();
+ expect(screen.getByTestId('bot-glance-daily-check')).toBeTruthy();
+ });
- // Another computer whose host predates the switch: its todo page has no dailyCheck field.
- const invoke = window.electronAPI.deviceLink.invoke as ReturnType<typeof vi.fn>;
- invoke.mockResolvedValue({ blocks: [{ primitive: 'teammate-todos', data: { items: [], total: 0 } }] });
- render(<BotGlanceButton bot={{ ...bot, deviceId: 'mini', deviceName: 'Mac-mini' }} cloudHome={false} />);
- await waitFor(() => expect(invoke).toHaveBeenCalled());
- fireEvent.click(screen.getByTestId('bot-glance-button'));
- expect(await screen.findByTestId('bot-glance-check')).toBeTruthy();
- expect(screen.queryByTestId('bot-glance-daily-check')).toBeNull();
+ // User-approved #7546 projection: two devices, existing unread, real PR title, one output per PR.
+ it('opens the correct task host, reads existing attention and deduplicates true PR outputs', async () => {
+ const a = { id: 'task-a', title: 'Session title A', status: 'active', updatedAt: '2026-10-28T10:00:00Z' };
+ const b = { id: 'task-b', title: 'Session title B', status: 'active', updatedAt: '2026-10-28T09:00:00Z', deviceLinkDeviceId: 'mini', deviceLinkDeviceName: 'Mac mini' };
+ h.sessions = [a, { ...a, id: 'unrelated', title: 'Unrelated' }]; h.remoteSessions = [b];
+ h.scopes = [{ sessionId: a.id }, { sessionId: b.id, deviceId: 'mini' }];
+ h.attention.set(a.id, 'done'); h.attention.set(b.id, 'error');
+ h.refs = [a,b].map((task, i) => ({ id: String(i), sessionId: task.id, owner: 'makecindy', repo: 'cindy', prNumber: 123, lastSeenAt: 2-i }));
+ h.statuses.set('makecindy/cindy#123', { ok: true, status: 'merged', title: 'Actual PR title' });
+ await openGlance();
+ expect(screen.getAllByTestId('bot-glance-task')).toHaveLength(2);
+ expect(screen.queryByText('Unrelated')).toBeNull();
+ expect(screen.getAllByLabelText('bots.glance.unread')).toHaveLength(1);
+ expect(screen.getAllByTestId('bot-glance-pr')).toHaveLength(1);
+ expect(screen.getByText('Actual PR title')).toBeTruthy();
+ fireEvent.click(screen.getByTestId('bot-glance-pr'));
+ expect(h.openExternal).toHaveBeenCalledWith('https://github.com/makecindy/cindy/pull/123');
+ fireEvent.click(screen.getByText('Session title B'));
+ await waitFor(() => expect(h.navigate).toHaveBeenCalledWith('/cc-agent/task-b'));
+ expect(h.pin).toHaveBeenCalledWith('mini', 'task-b');
});
it('lights the entry dot for a due todo until 近况 is opened, and marks the row itself', async () => {
- items = [todo('due', { sourceDeadline: { kind: 'date', date: today, timeZone: 'UTC' } }), todo('later')];
+ items = [todo('due', { sourceDeadline: { kind: 'date', date: today, timeZone: 'UTC' } }),
+ todo('later', { sourceDeadline: { kind: 'date', date: todoLocalDate(new Date(Date.now() + 3 * 86_400_000), 'UTC'), timeZone: 'UTC' } })];
render(<BotGlanceButton bot={bot} cloudHome={false} />);
const button = screen.getByTestId('bot-glance-button');
await waitFor(() => expect(button.getAttribute('aria-label')).toContain('bots.glance.dueUnseen'));
@@ -203,17 +245,19 @@ describe('BotGlanceButton', () => {
expect(screen.getByTestId('bot-glance-button').getAttribute('aria-label')).not.toContain('bots.glance.dueUnseen');
});
- it('reaches todos past the first host page, and keeps finished ones after the last open todo is done', async () => {
+ it('reaches due todos past the first host page and hides the section when only old ideas or completed items remain', async () => {
items = Array.from({ length: 30 }, (_, i) => todo(`o${String(i).padStart(2, '0')}`));
await openGlance();
fireEvent.click(screen.getByText('bots.glance.showMore'));
expect(screen.getAllByTestId('bot-glance-todo')).toHaveLength(30);
cleanup();
- items = [todo('finished', { status: 'done' })];
+ items = [todo('finished', { status: 'done' }),
+ ...Array.from({ length: 51 }, (_, i) => todo(`old-${i}`, { sourceDeadline: null }))];
await openGlance();
- fireEvent.click(await screen.findByText('bots.glance.doneCount:1'));
- expect(screen.getByText('Todo finished')).toBeTruthy();
+ expect(screen.queryByText('bots.glance.todos')).toBeNull();
+ expect(screen.queryByTestId('bot-glance-check')).toBeNull();
+ expect(update).not.toHaveBeenCalled();
});
it('lists Cindy on each computer: this one first, online ones selectable, offline ones folded', async () => {
@@ -255,4 +299,24 @@ describe('BotGlanceButton', () => {
fireEvent.click(outputs[0]);
await waitFor(() => expect(openPath).toHaveBeenCalledWith('/w/out/report.docx'));
});
+
+ // PR + file entries share one chronology and one fold; separate lists hid newer files below older PRs.
+ it('mixes PRs and files by time with one shared show-more control', async () => {
+ h.sessions = [{ id: 'task', title: 'Task', status: 'active' }];
+ h.scopes = [{ sessionId: 'task' }];
+ h.refs = [4, 2].map(at => ({ sessionId: 'task', owner: 'example', repo: 'app', prNumber: at, lastSeenAt: at }));
+ for (const at of [4, 2]) h.statuses.set(`example/app#${at}`, { ok: true, status: 'merged', title: `PR title ${at}` });
+ h.delegations = [3, 1].map(at => ({ id: `d${at}`, requestingBotId: 'bot-1', status: 'completed',
+ title: 'Task', childSessionId: 'task', completedAt: at, updatedAt: at,
+ artifacts: [{ path: `file-${at}.pdf`, absolutePath: `/w/file-${at}.pdf`, status: 'added' }] }));
+ const popover = await openGlance();
+ const rows = () => [...popover.querySelectorAll('[data-testid="bot-glance-pr"], [data-testid="bot-glance-output"]')]
+ .map(row => row.querySelector('[title]')?.getAttribute('title'));
+ expect(rows()).toEqual(['PR title 4', 'file-3.pdf', 'PR title 2']);
+ expect(screen.getAllByText('bots.glance.showMore')).toHaveLength(1);
+ fireEvent.click(screen.getByText('bots.glance.showMore'));
+ expect(rows()).toEqual(['PR title 4', 'file-3.pdf', 'PR title 2', 'file-1.pdf']);
+ fireEvent.click(screen.getByText('bots.glance.showLess'));
+ expect(rows()).toHaveLength(3);
+ });
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index bb33eed48e..c5b19001bd 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9614,6 +9614,10 @@
"checkFailed": "Couldn't send. Try again.",
"dailyCheck": "Check every day",
"dailyCheckMeta": "Weekdays at 9:00, quiet when nothing is new",
+ "recentTasks": "Recent tasks",
+ "unread": "Unread result",
+ "stopDailyCheck": "Stop daily checking",
+ "loadFailed": "Couldn’t load to-dos. Try again.",
"dailyCheckFailed": "Couldn't save. Try again.",
"outputs": "Outputs",
"outputMeta": "{{time}} · {{task}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3b905bdf74..9fcdfa2f38 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9580,6 +9580,10 @@
"checkFailed": "送信できませんでした。もう一度お試しください",
"dailyCheck": "毎日確認する",
"dailyCheckMeta": "平日 9:00、新しい Todo がなければ通知しません",
+ "recentTasks": "最近のセッション",
+ "unread": "未読の結果",
+ "stopDailyCheck": "毎日の確認を停止",
+ "loadFailed": "To-do を読み込めませんでした。再試行してください。",
"dailyCheckFailed": "保存できませんでした。もう一度お試しください",
"outputs": "成果物",
"outputMeta": "{{time}} · {{task}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e16b8a1f61..efc2f6d836 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9580,6 +9580,10 @@
"checkFailed": "보내지 못했습니다. 다시 시도하세요",
"dailyCheck": "매일 확인",
"dailyCheckMeta": "평일 9:00, 새 할 일이 없으면 알리지 않습니다",
+ "recentTasks": "최근 세션",
+ "unread": "읽지 않은 결과",
+ "stopDailyCheck": "매일 확인 중지",
+ "loadFailed": "할 일을 불러오지 못했습니다. 다시 시도하세요.",
"dailyCheckFailed": "저장하지 못했습니다. 다시 시도하세요",
"outputs": "결과물",
"outputMeta": "{{time}} · {{task}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 393315dc2e..705666b28d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9580,6 +9580,10 @@
"checkFailed": "没能发送,请重试",
"dailyCheck": "每天帮我查一次",
"dailyCheckMeta": "工作日 9:00,没有新待办不打扰",
+ "recentTasks": "近期任务",
+ "unread": "未读结果",
+ "stopDailyCheck": "停止每天检查",
+ "loadFailed": "待办加载失败,点击重试",
"dailyCheckFailed": "没能保存,请重试",
"outputs": "输出内容",
"outputMeta": "{{time}} · {{task}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 61ac89f055..3d18277480 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9580,6 +9580,10 @@
"checkFailed": "沒能傳送,請重試",
"dailyCheck": "每天幫我查一次",
"dailyCheckMeta": "工作日 9:00,沒有新待辦不打擾",
+ "recentTasks": "近期任務",
+ "unread": "未讀結果",
+ "stopDailyCheck": "停止每天檢查",
+ "loadFailed": "待辦載入失敗,點擊重試",
"dailyCheckFailed": "沒能儲存,請重試",
"outputs": "輸出內容",
"outputMeta": "{{time}} · {{task}}",
diff --git a/apps/mobile/src/__tests__/companionGlance.test.tsx b/apps/mobile/src/__tests__/companionGlance.test.tsx
index 58a99dc5d7..c8fb028ae0 100644
--- a/apps/mobile/src/__tests__/companionGlance.test.tsx
+++ b/apps/mobile/src/__tests__/companionGlance.test.tsx
@@ -15,8 +15,33 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { todoDateLabel, todoLocalDate, type TeammateTodo } from '@cindy/maker-shared/teammate-todo';
-const h = vi.hoisted(() => ({ items: [] as unknown[], reads: [] as Array<Record<string, unknown>> }));
-vi.mock('react-native', () => ({ AppState: { addEventListener: () => ({ remove: () => undefined }) } }));
+const h = vi.hoisted(() => ({ items: [] as unknown[], reads: [] as Array<Record<string, unknown>>,
+ sessions: [] as any[], queried: [] as any[], delegations: [] as any[], prs: new Map(), activity: new Map(), closed: null as (() => void) | null, openURL: vi.fn(),
+}));
+vi.mock('react-native', () => ({
+ AppState: { addEventListener: () => ({ remove: () => undefined }) },
+ Linking: { openURL: h.openURL },
+ StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
+ View: ({ children, testID, accessibilityLabel }: any) => createElement('div', { 'data-testid': testID, 'aria-label': accessibilityLabel }, children),
+ ScrollView: ({ children }: any) => createElement('div', null, children),
+ Pressable: ({ children, testID, accessibilityLabel, onPress, disabled }: any) => createElement('button',
+ { 'data-testid': testID, 'aria-label': accessibilityLabel, onClick: onPress, disabled }, children),
+}));
+vi.mock('@/components/AppText', () => ({ Text: ({ children }: any) => createElement('span', null, children) }));
+vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: () => null }));
+vi.mock('@/components/FileTypeIcon', () => ({ FileTypeIcon: () => null }));
+vi.mock('lucide-react-native', () => Object.fromEntries(['Check','ChevronDown','ChevronUp','Monitor','ScanSearch','MessageCircle','X','GitMerge','GitPullRequest','GitPullRequestClosed','GitPullRequestDraft'].map(name => [name, () => createElement('i', { 'data-icon': name })])));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ return { ...tokens, useTheme: () => ({ colors: tokens.lightColors }), useThemedStyles: (fn: any) => fn(tokens.lightColors) };
+});
+vi.mock('@/platform/chrome/NativePullDownMenu', () => ({ NativePullDownMenu: ({ children }: any) => children }));
+vi.mock('@/session/CompanionSheet', () => ({ CompanionSheet: ({ children, onClosed }: any) => { h.closed = onClosed; return children; } }));
+vi.mock('@/chat/useCloudCompanion', () => ({ useCloudCompanionHome: () => ({ actors: [], cindyIds: [] }) }));
+vi.mock('@/session/remoteSessionStore', () => ({ useRemoteHomeSessions: () => h.sessions,
+ remoteSessionStore: { getHomeSessions: () => h.sessions, subscribeHomeStatus: () => () => undefined, getSessionLiveActivity: (id: string) => h.activity.get(id) } }));
+vi.mock('@/session/HomeSessionInfoMeta', () => ({ useHomeSessionPr: (_device: string, id: string) => h.prs.get(id) ?? null }));
+vi.mock('@/device-link/remoteResourceAvailability', () => ({ readRemoteCollectionCache: () => [], remoteResourceConnectionState: () => 'online' }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: 'en' } }) }));
vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: async () => null, setItem: async () => undefined } }));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'u' }, accountGeneration: 1 }) }));
@@ -32,14 +57,15 @@ vi.mock('@/device-link/remoteResources', () => ({
return { blocks: [{ primitive: 'teammate-todos', data: { items: matching.slice(q.offset, q.offset + q.limit), total: matching.length } }] };
},
}));
-vi.mock('@/session/useRemoteCompanionQuery', () => ({ useRemoteCompanionQuery: () => ({ value: null }) }));
+vi.mock('@/session/useRemoteCompanionQuery', () => ({ useRemoteCompanionQuery: (device: string, channel: string) => ({ value: channel === 'local-db:sessions:list' ? h.queried : { ok: true, delegations: h.delegations } }) }));
+vi.mock('@/session/readTeammateTasks', () => ({ readTeammateTasks: async ({ sessions }: any) => sessions }));
const { useCompanionGlanceTodos } = await import('@/session/useCompanionGlanceTodos');
const { companionGlanceOutputs } = await import('@/session/companionProfileData');
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root;
-beforeEach(() => { h.items = []; h.reads = []; root = createRoot(document.createElement('div')); });
+beforeEach(() => { h.items = []; h.reads = []; h.sessions = []; h.queried = []; h.delegations = []; h.prs.clear(); h.activity.clear(); h.openURL.mockResolvedValue(undefined); root = createRoot(document.createElement('div')); });
afterEach(() => act(() => root.unmount()));
const todo = (id: string, status = 'open') => ({ id, status, title: id, revision: 1, sources: [], history: [] }) as unknown as TeammateTodo;
@@ -97,3 +123,83 @@ it('labels a todo due today with its date where the engine has no relative-time
(Intl as { RelativeTimeFormat?: unknown }).RelativeTimeFormat = original;
}
});
+
+
+// Real sheet rendering covers the new empty state and cross-device task/PR projection;
+// the existing hook-only cases cannot catch incorrect labels or navigation targets.
+import { CompanionGlanceSheet } from '@/session/CompanionGlanceSheet';
+
+it('hides empty todos and opens attributed tasks on their own host, with existing unread and true PR titles', async () => {
+ const host = document.createElement('div');
+ await act(async () => root.unmount()); root = createRoot(host);
+ const onOpenTask = vi.fn();
+ h.sessions = [
+ { id: 'remote', title: 'Task B', deviceLinkDeviceId: 'other-pc', status: 'active', updatedAt: '2026-10-28T11:00:00Z', taskTeammate: { id: 'cindy-default' } },
+ { id: 'unrelated', title: 'Unrelated task', deviceLinkDeviceId: 'pc', status: 'active', taskTeammate: { id: 'other-bot' } },
+ ];
+ // The Home snapshot has no local tasks (e.g. its archived filter); glance reads all statuses.
+ h.queried = [{ id: 'local', title: 'Task A', status: 'active', updatedAt: '2026-10-28T12:00:00Z', taskTeammate: { id: 'cindy-default' } }];
+ h.activity.set('local', { phase: 'completed', attention: true });
+ h.activity.set('remote', { phase: 'error', attention: true });
+ for (const id of ['local', 'remote']) h.prs.set(id, { ref: { owner: 'example', repo: 'app', prNumber: 7, sessionId: id, lastSeenAt: 1 },
+ status: { ok: true, status: 'merged', title: 'Real PR title' } });
+ await act(async () => root.render(<CompanionGlanceSheet visible onClose={() => {}} name="Cindy" avatar={undefined} botId="cindy-default"
+ deviceId="pc" deviceName="PC" sessionId="chat" online cloudHome={false} onQuoteTodo={() => {}} onOpenTask={onOpenTask}
+ onOpenCindy={() => {}} onSwitchHome={() => {}}
+ todos={{ loaded: true, failed: false, todos: {
+ open: Array.from({ length: 51 }, (_, index) => todo(`old idea ${index}`)),
+ done: [todo('completed', 'done')], openTotal: 51, doneTotal: 1, dailyCheck: true,
+ } } as any} />));
+ expect(host.textContent).not.toContain('devices.glance.todos');
+ expect(host.textContent).not.toContain('Unrelated task');
+ expect(host.querySelectorAll('[aria-label="devices.glance.unread"]')).toHaveLength(1);
+ expect(host.querySelectorAll('[data-testid="companion.glance.pr"]')).toHaveLength(1);
+ expect(host.textContent).toContain('Real PR title');
+ await act(async () => (host.querySelector('[data-testid="companion.glance.pr"]') as HTMLButtonElement).click());
+ expect(h.openURL).toHaveBeenCalledWith('https://github.com/example/app/pull/7');
+ await act(async () => (host.querySelectorAll('[data-testid="companion.glance.task"]')[1] as HTMLButtonElement).click());
+ expect(onOpenTask).not.toHaveBeenCalled();
+ await act(async () => h.closed?.());
+ expect(onOpenTask).toHaveBeenCalledWith('remote', 'other-pc');
+});
+
+it('shows only approaching deadlines in the real mobile sheet', async () => {
+ const host = document.createElement('div');
+ await act(async () => root.unmount()); root = createRoot(host);
+ const due = { ...todo('Due today'), sourceDeadline: { kind: 'date', date: todoLocalDate(new Date(), 'UTC'), timeZone: 'UTC' } };
+ const far = { ...todo('Next month'), sourceDeadline: { kind: 'date', date: todoLocalDate(new Date(Date.now() + 30 * 86_400_000), 'UTC'), timeZone: 'UTC' } };
+ await act(async () => root.render(<CompanionGlanceSheet visible onClose={() => {}} name="Cindy" avatar={undefined} botId="cindy-default"
+ deviceId="pc" deviceName="PC" sessionId="chat" online cloudHome={false} onQuoteTodo={() => {}} onOpenTask={() => {}}
+ onOpenCindy={() => {}} onSwitchHome={() => {}}
+ todos={{ loaded: true, failed: false, todos: { open: [due, far, todo('Old idea')], done: [], openTotal: 3, doneTotal: 0, dailyCheck: false } } as any} />));
+ expect(host.querySelectorAll('[data-testid="companion.glance.todo"]')).toHaveLength(1);
+ expect(host.textContent).toContain('Due today');
+ expect(host.textContent).not.toContain('Old idea');
+ expect(host.textContent).not.toContain('Next month');
+});
+
+// Regression: mixed output types must share the same preview budget and expand/collapse action.
+it('mixes PRs and files by time and expands all outputs together', async () => {
+ const host = document.createElement('div');
+ await act(async () => root.unmount()); root = createRoot(host);
+ h.queried = [{ id: 'task', title: 'Task', status: 'active', taskTeammate: { id: 'cindy-default' } }];
+ const pr = (at: number) => ({ ref: { sessionId: 'task', owner: 'example', repo: 'app', prNumber: at, lastSeenAt: at }, status: { ok: true, status: 'merged', title: `PR title ${at}` } });
+ h.prs.set('task', { ...pr(4), additional: [pr(2)] });
+ h.delegations = [3, 1].map(at => ({ id: `d${at}`, requestingBotId: 'cindy-default', status: 'completed',
+ title: 'Task', childSessionId: 'task', completedAt: at, updatedAt: at,
+ artifacts: [{ path: `file-${at}.pdf`, status: 'added' }] }));
+ await act(async () => root.render(<CompanionGlanceSheet visible onClose={() => {}} name="Cindy" avatar={undefined} botId="cindy-default"
+ deviceId="pc" deviceName="PC" sessionId="chat" online cloudHome={false} onQuoteTodo={() => {}} onOpenTask={() => {}}
+ onOpenCindy={() => {}} onSwitchHome={() => {}}
+ todos={{ loaded: true, failed: false, todos: { open: [], done: [], openTotal: 0, doneTotal: 0, dailyCheck: false } } as any} />));
+ const rows = () => [...host.querySelectorAll('[data-testid="companion.glance.pr"], [data-testid="companion.glance.output"]')]
+ .map(row => row.querySelector('span')?.textContent);
+ expect(rows()).toEqual(['PR title 4', 'file-3.pdf', 'PR title 2']);
+ expect(host.querySelectorAll('[data-testid="companion.glance.output.more"]')).toHaveLength(1);
+ expect(host.querySelector('[data-testid="companion.glance.pr.more"]')).toBeNull();
+ const more = () => host.querySelector('[data-testid="companion.glance.output.more"]') as HTMLButtonElement;
+ await act(async () => more().click());
+ expect(rows()).toEqual(['PR title 4', 'file-3.pdf', 'PR title 2', 'file-1.pdf']);
+ await act(async () => more().click());
+ expect(rows()).toHaveLength(3);
+});
diff --git a/apps/mobile/src/__tests__/homeDisplaySettings.test.ts b/apps/mobile/src/__tests__/homeDisplaySettings.test.ts
index 455190207d..7b80e10034 100644
--- a/apps/mobile/src/__tests__/homeDisplaySettings.test.ts
+++ b/apps/mobile/src/__tests__/homeDisplaySettings.test.ts
@@ -278,7 +278,7 @@ describe('task info and retained Home behavior', () => {
const remove = vi.fn(), stopResume = vi.fn(), clearInterval = vi.fn();
const refreshHomeSessionPr = vi.fn((_key: string, _load: () => unknown, _options: unknown) => 0);
const AppState = { currentState: 'active', addEventListener: (_event: string, callback: typeof foreground) => { foreground = callback; return { remove }; } };
- const effect = evaluate(callback, file, { key: 'cache', deviceId: 'd', sessionId: 's', online: true,
+ const effect = evaluate(callback, file, { key: 'cache', deviceId: 'd', sessionId: 's', online: true, foreground: false, includeRelated: false,
isActive: () => visible, AppState, refreshHomeSessionPr, loadHomeSessionPr: vi.fn(), link: {}, refreshKey: 'updated',
PR_STATUS_REFRESH_INTERVAL_MS: 90_000, Date, clearInterval, clearTimeout: vi.fn(),
setInterval: (fn: () => void) => { poll = fn; return 1; }, setTimeout: vi.fn(),
@@ -396,3 +396,16 @@ describe('home PR cache', () => {
await expect(loadHomeSessionPr(invoke, 'd', 's', other)).resolves.toEqual({ ref, status: null });
});
});
+
+
+// Glance needs multiple associated PRs; the existing Home row keeps its one-PR contract.
+it('loads the bounded PR list for glance and retains each known title through lookup failure', async () => {
+ const refs = [1, 2, 3, 4].map(n => ({ id: String(n), sessionId: 's', owner: 'example', repo: 'app', prNumber: n, lastSeenAt: n }));
+ const invoke = vi.fn(async (_device: string, channel: string) => channel.endsWith('list') ? refs :
+ refs.map(ref => ({ ...ref, ok: true, status: 'merged', title: `Actual PR ${ref.prNumber}` }))) as any;
+ const result = await loadHomeSessionPr(invoke, 'd', 's', null, true);
+ expect([result, ...result!.additional!].map(row => row!.ref.prNumber)).toEqual([4, 3, 2]);
+ expect(result!.status).toMatchObject({ title: 'Actual PR 4' });
+ invoke.mockImplementation(async (_device: string, channel: string) => { if (channel.endsWith('list')) return refs; throw new Error('offline'); });
+ expect(await loadHomeSessionPr(invoke, 'd', 's', result, true)).toEqual(result);
+});
diff --git a/apps/mobile/src/debug/teammateVisualFixture.ts b/apps/mobile/src/debug/teammateVisualFixture.ts
index ef905e4ef4..50aa07020b 100644
--- a/apps/mobile/src/debug/teammateVisualFixture.ts
+++ b/apps/mobile/src/debug/teammateVisualFixture.ts
@@ -38,8 +38,22 @@ const teammates: ReadonlyArray<{ id: string; name: string; preview: string; minu
// Fixed per process: a moving clock would make every row look unread again on each read.
const FIXTURE_NOW = Date.now();
+// In-memory mock state only: exercises the real glance actions without a host or automation.
+let dailyTodoCheck = true;
+let todoDeleted = false;
+const glanceTodo = {
+ id: 'visual-glance-todo', revision: 1, key: 'visual-review', origin: 'assigned',
+ title: '确认登录页的验收截图', progress: '', outcome: '', value: '', next: null,
+ sources: [], associations: [], status: 'open', createdAt: new Date(FIXTURE_NOW).toISOString(),
+ updatedAt: new Date(FIXTURE_NOW).toISOString(), sourceDeadline: null, deadlineCandidate: null,
+ suggestedDate: null, decision: null, history: [], action: null,
+};
export function teammateVisualFixture(channel: string, args: unknown[], now = FIXTURE_NOW): unknown {
+ if (channel === 'git-context:pr-refs:list') return args[0] === `${UI_MOCK_ID_PREFIX}rich-answer`
+ ? [{ id: 'visual-pr', sessionId: args[0], owner: 'example', repo: 'demo', prNumber: 7, lastSeenAt: now }] : [];
+ if (channel === 'git-context:pr-status') return [{ owner: 'example', repo: 'demo', prNumber: 7, ok: true,
+ status: 'merged', title: '修复登录页在窄窗口下的布局' }];
if (channel === 'maker:bot-delegations:list') {
const bot = teammates.find(item => args[0] === `${VISUAL_TEAMMATE_SESSION_ID}:${item.id}`);
const ids = bot?.id === 'cindy-default' ? ['visual-running', `${UI_MOCK_ID_PREFIX}rich-answer`]
@@ -51,7 +65,23 @@ export function teammateVisualFixture(channel: string, args: unknown[], now = FI
collections: [{ id: TEAMMATES, resourceKind: 'bot', title: 'Teammates', placement: 'home-scope',
actions: [{ id: 'open-create', label: 'New teammate' }] }],
} satisfies RemoteResourceManifestResponse;
- const request = args[0] as { collectionId?: string; ref?: { collectionId?: string; id?: string }; resourceRef?: { id?: string }; input?: { op?: string; args?: { id?: string } } } | undefined;
+ const request = args[0] as { collectionId?: string; ref?: { collectionId?: string; id?: string }; resourceRef?: { id?: string }; actionId?: string; query?: string; input?: { enabled?: boolean; operation?: string; op?: string; args?: { id?: string } } } | undefined;
+ if (channel === REMOTE_RESOURCE_GET_CHANNEL && request?.ref?.id === 'todos:cindy-default') {
+ const query = JSON.parse(request.query ?? '{}');
+ const items = query.view === 'done' || todoDeleted ? [] : [glanceTodo];
+ return { ref: { collectionId: TEAMMATES, kind: 'bot', id: request.ref.id }, revision: 'visual-1',
+ display: { title: 'Todos' }, actions: [], links: [],
+ blocks: [{ id: 'todos', primitive: 'teammate-todos', fallbackMarkdown: glanceTodo.title, data: { items, total: items.length, dailyCheck: dailyTodoCheck } }] };
+ }
+ if (channel === REMOTE_RESOURCE_INVOKE_CHANNEL && request?.resourceRef?.id === 'todos:cindy-default' && request.actionId === 'todo-daily-check') {
+ dailyTodoCheck = request.input?.enabled === true;
+ return { effects: [], dailyCheck: dailyTodoCheck };
+ }
+ if (channel === REMOTE_RESOURCE_INVOKE_CHANNEL && request?.resourceRef?.id === 'todos:cindy-default' && request.actionId === 'todo-update') {
+ if (request.input?.operation === 'delete') todoDeleted = true;
+ if (request.input?.operation === 'restore') todoDeleted = false;
+ return { effects: [], todo: glanceTodo };
+ }
// Nine members from three accounts: the header shows a member count, not every name.
if (channel === REMOTE_RESOURCE_GET_CHANNEL && request?.ref?.collectionId === BOT_GROUP_REMOTE_COLLECTION_ID
&& request.ref.id === 'visual-crowded-group') return {
@@ -93,7 +123,8 @@ export function teammateVisualFixture(channel: string, args: unknown[], now = FI
if (bot) return {
ref: { collectionId: TEAMMATES, kind: 'bot', id: request.ref.id }, revision: 'visual-1',
display: { title: bot.name, avatar: bot.avatar },
- links: [{ rel: 'conversation', target: { kind: 'session', sessionId: VISUAL_TEAMMATE_SESSION_ID } }],
+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: VISUAL_TEAMMATE_SESSION_ID } },
+ ...(id === 'cindy-default' ? [{ rel: 'todos', target: { kind: 'resource', ref: { collectionId: TEAMMATES, kind: 'bot', id: 'todos:cindy-default' } } }] : [])],
actions: [], blocks: [{ id: 'profile', primitive: 'markdown', fallbackMarkdown: bot.preview }],
};
}
diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.json
index f75d1536c0..d4d92d17b0 100644
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@ -872,6 +872,10 @@
"checkPrompt": "Check my connected sources, like mail and messages, for anything new I need to handle, and add it to my todos.",
"dailyCheck": "Check every day",
"dailyCheckMeta": "Weekdays at 9:00, quiet when nothing is new",
+ "recentTasks": "Recent tasks",
+ "unread": "Unread result",
+ "stopDailyCheck": "Stop daily checking",
+ "openFailed": "Couldn’t open this link",
"dailyCheckFailed": "Couldn't save. Try again.",
"loadFailed": "Couldn't load todos",
"outputs": "Outputs",
diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.json
index 12797e9a6f..bc8d452675 100644
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@ -872,6 +872,10 @@
"checkPrompt": "接続済みのメールやメッセージなどに、私が対応すべき新しい用件がないか確認して、あれば Todo に追加して。",
"dailyCheck": "毎日確認する",
"dailyCheckMeta": "平日 9:00、新しい Todo がなければ通知しません",
+ "recentTasks": "最近のセッション",
+ "unread": "未読の結果",
+ "stopDailyCheck": "毎日の確認を停止",
+ "openFailed": "リンクを開けませんでした",
"dailyCheckFailed": "保存できませんでした。もう一度お試しください",
"loadFailed": "Todo を読み込めませんでした",
"outputs": "成果物",
diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.json
index 0249e683af..428b115837 100644
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@ -872,6 +872,10 @@
"checkPrompt": "연결된 메일, 메시지 등에서 내가 처리해야 할 새 일이 있는지 확인하고, 있으면 할 일에 추가해 줘.",
"dailyCheck": "매일 확인",
"dailyCheckMeta": "평일 9:00, 새 할 일이 없으면 알리지 않습니다",
+ "recentTasks": "최근 세션",
+ "unread": "읽지 않은 결과",
+ "stopDailyCheck": "매일 확인 중지",
+ "openFailed": "링크를 열 수 없습니다",
"dailyCheckFailed": "저장하지 못했습니다. 다시 시도하세요",
"loadFailed": "할 일을 불러오지 못했습니다",
"outputs": "결과물",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.json
index a08fd2cc05..3e99f884a2 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@ -872,6 +872,10 @@
"checkPrompt": "帮我查查已连接的邮箱、消息等来源里,有没有需要我处理的新事项,有就记成待办。",
"dailyCheck": "每天帮我查一次",
"dailyCheckMeta": "工作日 9:00,没有新待办不打扰",
+ "recentTasks": "近期任务",
+ "unread": "未读结果",
+ "stopDailyCheck": "停止每天检查",
+ "openFailed": "无法打开链接",
"dailyCheckFailed": "没能保存,请重试",
"loadFailed": "没能读取待办",
"outputs": "输出内容",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.json
index 38739dab84..57d27bd803 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@ -872,6 +872,10 @@
"checkPrompt": "幫我查查已連接的信箱、訊息等來源裡,有沒有需要我處理的新事項,有就記成待辦。",
"dailyCheck": "每天幫我查一次",
"dailyCheckMeta": "工作日 9:00,沒有新待辦不打擾",
+ "recentTasks": "近期任務",
+ "unread": "未讀結果",
+ "stopDailyCheck": "停止每天檢查",
+ "openFailed": "無法開啟連結",
"dailyCheckFailed": "沒能儲存,請重試",
"loadFailed": "無法讀取待辦",
"outputs": "輸出內容",
diff --git a/apps/mobile/src/session/CompanionGlanceSheet.tsx b/apps/mobile/src/session/CompanionGlanceSheet.tsx
index f8cbb5c1c0..e717ee3842 100644
--- a/apps/mobile/src/session/CompanionGlanceSheet.tsx
+++ b/apps/mobile/src/session/CompanionGlanceSheet.tsx
@@ -1,16 +1,15 @@
-/**
- * 伙伴近况(手机):点伙伴聊天顶栏的头像打开,与桌面 BotGlancePopover 同三块——电脑 / 待办 / 输出内容;
- * 没内容的块整块不出现。规则见 docs/product-rules/cindy-bots-runtime.md「伙伴近况」,版式按原型
- * Designs/cindy/teammate-glance(手机 r1.1):系统 sheet 外壳,内容是 inset grouped 卡片。
- * 待办块第一行「帮我查查」让伙伴现在去已连接的来源里找新待办(作为主人的一句话发进对话),下面的开关让它
- * 每个工作日早上自己查一次。待办行没有按钮:点一条交给对话(作为待办引用放进输入框),长按系统菜单只有「删除」,可撤销。
+/** Mobile partner glance keeps the native sheet: computers, nonempty todos, tasks and outputs.
+ * Task navigation/read state and PR status reuse the existing Home contracts.
*/
-import { useMemo, useRef, useState, type ReactNode } from 'react';
-import { Pressable, ScrollView, StyleSheet, Switch, View } from 'react-native';
-import { Check, ChevronDown, ChevronUp, Monitor, ScanSearch } from 'lucide-react-native';
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
+import { Pressable, ScrollView, StyleSheet, Linking, View } from 'react-native';
+import { Check, ChevronDown, ChevronUp, Monitor, ScanSearch, MessageCircle, X } from 'lucide-react-native';
import { useTranslation } from 'react-i18next';
import type { BotDelegationListResult } from '@cindy/maker-shared/botDelegation';
-import { todoDateLabel, todoDue, type TeammateTodo } from '@cindy/maker-shared/teammate-todo';
+import { todoDateLabel, todoDue, todoDueSoon, type TeammateTodo } from '@cindy/maker-shared/teammate-todo';
+import { prStatusKey, sessionPrUrl } from '@cindy/maker-shared';
+import { isAccessRevokedRemoteError } from '@cindy/maker-shared/device-link-contract';
+import { getSessionListActivityAt } from '@cindy/maker-shared/session-activity';
import type { RemoteResource } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
import { Text } from '@/components/AppText';
@@ -26,7 +25,17 @@ import { companionGlanceOutputs } from './companionProfileData';
import { useRemoteCompanionQuery } from './useRemoteCompanionQuery';
import type { useCompanionGlanceTodos } from './useCompanionGlanceTodos';
-const TODO_PREVIEW = 5;
+import { useCloudCompanionHome } from '@/chat/useCloudCompanion';
+import { remoteSessionStore, useRemoteHomeSessions } from './remoteSessionStore';
+import { taskTeammateKey, isTeammateTask } from './teammateTaskSource';
+import type { RemoteSession } from './types';
+import { useHomeSessionPr } from './HomeSessionInfoMeta';
+import type { HomeSessionPrInfo } from './homeSessionPrStore';
+import { prStatusVisual } from './prStatusVisual';
+import { readTeammateTasks } from './readTeammateTasks';
+
+const TODO_PREVIEW = 2;
+const TASK_PREVIEW = 5;
const OUTPUT_PREVIEW = 3;
const CINDY_BOT_ID = 'cindy-default';
/** Header avatar (原型 56pt). */
@@ -40,15 +49,6 @@ const PRESENCE_DOT = 8;
type GlanceTodoState = ReturnType<typeof useCompanionGlanceTodos>;
-function dayLabel(at: number, language: string): string {
- const now = new Date();
- const date = new Date(at);
- const startOf = (value: Date) => new Date(value.getFullYear(), value.getMonth(), value.getDate()).getTime();
- const days = Math.round((startOf(now) - startOf(date)) / 86_400_000);
- // Hermes has no Intl.RelativeTimeFormat; there recent days show as dates too.
- if (days >= 0 && days <= 1 && typeof Intl.RelativeTimeFormat === 'function') return new Intl.RelativeTimeFormat(language, { numeric: 'auto' }).format(-days, 'day');
- return new Intl.DateTimeFormat(language, { month: 'numeric', day: 'numeric' }).format(date);
-}
export function CompanionGlanceSheet({
visible, onClose, name, avatar, botId, deviceId, deviceName, sessionId, online, cloudHome, todos,
@@ -70,11 +70,12 @@ export function CompanionGlanceSheet({
onQuoteTodo(todo: TeammateTodo): void;
/** 「帮我查查」: ask the teammate, as the owner, to look for new todos now; absent while this chat cannot send. */
onCheckTodos?(): void;
- onOpenTask(sessionId: string): void;
+ onOpenTask(sessionId: string, deviceId?: string): void;
onOpenCindy(hosted: HostedRemoteCollectionItem): void;
onSwitchHome(): void;
}) {
const styles = useThemedStyles(makeStyles);
+ const { accountGeneration } = useAuth();
// Row actions that leave the sheet run once it has closed, so nothing is presented over it.
const pending = useRef<(() => void) | null>(null);
const afterClose = (action: () => void) => { pending.current = action; onClose(); };
@@ -88,18 +89,18 @@ export function CompanionGlanceSheet({
<Computers botId={botId} deviceId={deviceId} deviceName={deviceName} online={online} cloudHome={cloudHome}
onOpenCindy={hosted => afterClose(() => onOpenCindy(hosted))} onSwitchHome={() => afterClose(onSwitchHome)} />
<Todos todos={todos} online={online} onQuote={todo => afterClose(() => onQuoteTodo(todo))} onCheck={onCheckTodos ? () => afterClose(onCheckTodos) : undefined} />
- <Outputs botId={botId} deviceId={deviceId} sessionId={sessionId} online={online}
- onOpenTask={taskId => afterClose(() => onOpenTask(taskId))} />
+ {visible ? <Activity key={`${accountGeneration}:${deviceId}:${botId}`} botId={botId} deviceId={deviceId} deviceName={deviceName} sessionId={sessionId} online={online}
+ onOpenTask={(taskId, taskDeviceId) => afterClose(() => onOpenTask(taskId, taskDeviceId))} /> : null}
</ScrollView>
</CompanionSheet>;
}
// ---------------------------------------------------------------- 分组与行(原型 inset grouped 卡片)
-function Section({ label, children }: { label: string; children: ReactNode }) {
+function Section({ label, children, action }: { label: string; children: ReactNode; action?: ReactNode }) {
const styles = useThemedStyles(makeStyles);
return <View style={styles.section}>
- <Text style={styles.sectionLabel}>{label}</Text>
+ <View style={styles.sectionHeading}><Text style={styles.sectionLabel}>{label}</Text>{action}</View>
<View style={styles.card}>{children}</View>
</View>;
}
@@ -110,21 +111,21 @@ function joinRows(rows: ReactNode[], inset: boolean, styles: ReturnType<typeof m
: [<View key={`divider-${index}`} style={[styles.divider, inset && styles.dividerInset]} />, row]);
}
-function Row({ icon, title, meta, trailing, muted = false, onPress, testID }: {
- icon?: ReactNode; title: string; meta?: string; trailing?: ReactNode; muted?: boolean; onPress?(): void; testID?: string;
+function Row({ icon, title, meta, inlineMeta = false, trailing, muted = false, onPress, testID }: {
+ icon?: ReactNode; title: string; meta?: string; inlineMeta?: boolean; trailing?: ReactNode; muted?: boolean; onPress?(): void; testID?: string;
}) {
const styles = useThemedStyles(makeStyles);
const body = <>
{icon ? <View style={styles.icon}>{icon}</View> : null}
- <View style={styles.rowText}>
- <Text numberOfLines={1} style={[styles.rowTitle, muted && styles.rowTitleMuted]}>{title}</Text>
- {meta ? <Text numberOfLines={1} style={styles.rowMeta}>{meta}</Text> : null}
+ <View style={[styles.rowText, inlineMeta && styles.inlineText]}>
+ <Text numberOfLines={1} style={[styles.rowTitle, inlineMeta && styles.inlineTitle, muted && styles.rowTitleMuted]}>{title}</Text>
+ {meta ? <Text numberOfLines={1} style={[styles.rowMeta, inlineMeta && styles.inlineMeta]}>{meta}</Text> : null}
</View>
{trailing ? <View style={styles.trailing}>{trailing}</View> : null}
</>;
- if (!onPress) return <View style={styles.row} testID={testID}>{body}</View>;
+ if (!onPress) return <View style={[styles.row, inlineMeta && styles.compactRow]} testID={testID}>{body}</View>;
return <Pressable accessibilityRole="button" accessibilityLabel={meta ? `${title}, ${meta}` : title} onPress={onPress}
- style={({ pressed }) => [styles.row, pressed && styles.rowPressed]} testID={testID}>{body}</Pressable>;
+ style={({ pressed }) => [styles.row, inlineMeta && styles.compactRow, pressed && styles.rowPressed]} testID={testID}>{body}</Pressable>;
}
function FoldRow({ label, open, inset, onPress, testID }: { label: string; open: boolean; inset: boolean; onPress(): void; testID?: string }) {
@@ -166,15 +167,15 @@ function Computers({ botId, deviceId, deviceName, online, cloudHome, onOpenCindy
{state === 'here' && online ? <View style={styles.presence} /> : null}
</View>;
const rows: ReactNode[] = [
- <Row key="current" icon={monitor('here')} title={deviceName} meta={online ? t('devices.glance.runningHere') : t('devices.glance.offline')}
+ <Row key="current" icon={monitor('here')} title={deviceName} meta={online ? t('devices.glance.runningHere') : t('devices.glance.offline')} inlineMeta
trailing={<Check size={iconSize.lg} strokeWidth={iconStroke.medium} color={colors.textPrimary} />} testID="companion.glance.computer.current" />,
- ...onlineCopies.map(copy => <Row key={copy.row.key} icon={monitor('online')} title={copy.row.host.deviceName} meta={t('devices.glance.online')}
+ ...onlineCopies.map(copy => <Row key={copy.row.key} icon={monitor('online')} title={copy.row.host.deviceName} meta={t('devices.glance.online')} inlineMeta
onPress={() => onOpenCindy(copy.row)} testID={`companion.glance.computer.${copy.row.host.deviceId}`} />),
];
if (offlineCopies.length > 0) rows.push(<FoldRow key="offline" inset label={t('devices.glance.offlineCount', { count: offlineCopies.length })}
open={showOffline} onPress={() => setShowOffline(value => !value)} testID="companion.glance.computer.offline" />);
if (showOffline) rows.push(...offlineCopies.map(copy => <Row key={copy.row.key} icon={monitor('offline')} title={copy.row.host.deviceName}
- meta={t('devices.glance.offline')} muted />));
+ meta={t('devices.glance.offline')} inlineMeta muted />));
if (cloudHome && online) rows.push(<FoldRow key="switch" inset label={t('devices.cloudCompanion.switchAction')} open={false}
onPress={onSwitchHome} testID="companion.glance.computer.switch" />);
return <Section label={t('devices.glance.computers')}>{joinRows(rows, true, styles)}</Section>;
@@ -199,28 +200,30 @@ function Todos({ todos, online, onQuote, onCheck }: {
const styles = useThemedStyles(makeStyles);
const [dailyBusy, setDailyBusy] = useState(false);
const [showAll, setShowAll] = useState(false);
- const [showDone, setShowDone] = useState(false);
const [deleted, setDeleted] = useState<TeammateTodo | null>(null);
const [error, setError] = useState<string | null>(null);
- const { open, done, doneTotal, openTotal, dailyCheck } = todos.todos;
+ const { dailyCheck } = todos.todos;
+ const now = new Date();
+ const open = todos.todos.open.filter(todo => todoDueSoon(todo, now));
+ const openTotal = open.length;
// Not offered by this desktop, or not read yet while offline: no section at all.
if (!todos.loaded) return null;
- const checkRow = <Row key="check" icon={<ScanSearch size={ICON_GLYPH} strokeWidth={iconStroke.regular} color={colors.textSecondary} />}
- title={t('devices.glance.check')} meta={t('devices.glance.checkMeta')} muted={!online || !onCheck} onPress={online ? onCheck : undefined} testID="companion.glance.todo.check" />;
+ const checkAction = <Pressable accessibilityRole="button" accessibilityLabel={t('devices.glance.check')}
+ disabled={!online || !onCheck} onPress={onCheck} style={styles.headerAction} testID="companion.glance.todo.check">
+ <ScanSearch size={iconSize.sm} strokeWidth={iconStroke.regular} color={colors.textSecondary} />
+ </Pressable>;
const changeDaily = async (next: boolean) => {
setError(null);
setDailyBusy(true);
try { await todos.setDailyCheck(next); } catch { setError(t('devices.glance.dailyCheckFailed')); } finally { setDailyBusy(false); }
};
- // Older desktops do not report the switch; then only 「帮我查查」 shows.
- const dailyRow = dailyCheck === null ? null : <Row key="daily" icon={<View />} title={t('devices.glance.dailyCheck')} meta={t('devices.glance.dailyCheckMeta')}
- trailing={<Switch accessibilityLabel={t('devices.glance.dailyCheck')} value={dailyCheck} disabled={!online || dailyBusy}
- onValueChange={value => void changeDaily(value)} testID="companion.glance.todo.daily" />} />;
- const head = [checkRow, ...(dailyRow ? [dailyRow] : [])];
+ const dailyRow = !dailyCheck ? null : <Row key="daily" title={t('devices.glance.dailyCheck')} meta={t('devices.glance.dailyCheckMeta')}
+ trailing={<Pressable accessibilityRole="button" accessibilityLabel={t('devices.glance.stopDailyCheck')}
+ disabled={!online || dailyBusy} style={styles.headerAction} onPress={() => void changeDaily(false)} testID="companion.glance.todo.daily">
+ <X size={iconSize.sm} strokeWidth={iconStroke.regular} color={colors.textSecondary} /></Pressable>} />;
+ const head = dailyRow ? [dailyRow] : [];
// A failed first read is not "no todos": keep the section with a retry instead of hiding it.
- if (todos.failed && open.length === 0 && doneTotal === 0) return <Section label={t('devices.glance.todos')}>
- {joinRows(head, true, styles)}
- <View style={styles.divider} />
+ if (todos.failed && open.length === 0) return <Section label={t('devices.glance.todos')}>
<Pressable accessibilityRole="button" onPress={() => void todos.refresh()} disabled={!online}
style={({ pressed }) => [styles.row, pressed && styles.rowPressed]} testID="companion.glance.todo.retry">
<Text numberOfLines={1} style={styles.undoNote}>{t('devices.glance.loadFailed')}</Text>
@@ -228,6 +231,8 @@ function Todos({ todos, online, onQuote, onCheck }: {
</Pressable>
</Section>;
+ if (openTotal === 0 && !deleted) return null;
+
const remove = async (todo: TeammateTodo) => {
setError(null);
try {
@@ -250,16 +255,15 @@ function Todos({ todos, online, onQuote, onCheck }: {
setError(t('devices.glance.undoFailed'));
}
};
- const row = (todo: TeammateTodo, isDone: boolean) => {
- const due = !isDone && todoDue(todo);
- const date = isDone ? '' : todoDateLabel(todo, i18n.language);
- const completion = isDone ? todo.history[todo.history.length - 1]?.summary : undefined;
- const content = <Row title={todo.title} meta={completion || sourceText(todo, t)} muted={isDone}
+ const row = (todo: TeammateTodo) => {
+ const due = todoDue(todo);
+ const date = todoDateLabel(todo, i18n.language);
+ const content = <Row title={todo.title} meta={sourceText(todo, t)}
trailing={date ? <View style={styles.date}>
{due ? <View style={styles.dueDot} accessibilityLabel={t('devices.glance.dueUnseen')} /> : null}
<Text style={[styles.dateText, due && styles.dateDue]}>{date}</Text>
</View> : undefined}
- onPress={() => onQuote(todo)} testID={isDone ? 'companion.glance.todo.done' : 'companion.glance.todo'} />;
+ onPress={() => onQuote(todo)} testID="companion.glance.todo" />;
// 长按:系统上下文菜单(行浮起、背景模糊),只有「删除」。
return <NativePullDownMenu key={todo.id} longPress disabled={!online} accessibilityLabel={todo.title}
actions={[{ id: 'delete', title: t('devices.glance.delete'), destructive: true, image: 'trash' }]}
@@ -271,16 +275,13 @@ function Todos({ todos, online, onQuote, onCheck }: {
<Text numberOfLines={1} style={styles.undoNote}>{t('devices.glance.deleted')}</Text>
<Text style={styles.undoAction}>{t('devices.glance.undo')}</Text>
</Pressable>);
- rows.push(...(showAll ? open : open.slice(0, TODO_PREVIEW)).map(todo => row(todo, false)));
+ rows.push(...(showAll ? open : open.slice(0, TODO_PREVIEW)).map(row));
if (openTotal > TODO_PREVIEW) rows.push(<FoldRow key="more" inset={false} label={showAll ? t('devices.glance.showLess') : t('devices.glance.showMore')}
open={showAll} onPress={() => setShowAll(value => !value)} testID="companion.glance.todo.more" />);
- if (doneTotal > 0) rows.push(<FoldRow key="done" inset={false} label={t('devices.glance.doneCount', { count: doneTotal })}
- open={showDone} onPress={() => setShowDone(value => !value)} testID="companion.glance.todo.doneToggle" />);
- if (showDone) rows.push(...done.map(todo => row(todo, true)));
return <View>
- <Section label={t('devices.glance.todos')}>
+ <Section label={t('devices.glance.todos')} action={checkAction}>
{joinRows(head, true, styles)}
- {rows.length > 0 ? <><View style={styles.divider} />{joinRows(rows, false, styles)}</> : null}
+ {rows.length > 0 ? <>{head.length ? <View style={styles.divider} /> : null}{joinRows(rows, false, styles)}</> : null}
</Section>
{error ? <Text accessibilityRole="alert" style={styles.error}>{error}</Text> : null}
</View>;
@@ -288,31 +289,160 @@ function Todos({ todos, online, onQuote, onCheck }: {
// ---------------------------------------------------------------- 输出内容
-function Outputs({ botId, deviceId, sessionId, online, onOpenTask }: {
- botId: string; deviceId: string; sessionId: string; online: boolean; onOpenTask(sessionId: string): void;
+function Outputs({ botId, deviceId, sessionId, online, onOpenTask, prs }: {
+ botId: string; deviceId: string; sessionId: string; online: boolean; onOpenTask(sessionId: string): void; prs: HomeSessionPrInfo[];
}) {
- const { t, i18n } = useTranslation();
+ const { t } = useTranslation();
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const [showAll, setShowAll] = useState(false);
const { value } = useRemoteCompanionQuery<BotDelegationListResult>(deviceId, 'maker:bot-delegations:list', [sessionId], { enabled: online && !!sessionId });
const files = useMemo(() => companionGlanceOutputs(value, botId), [botId, value]);
- if (files.length === 0) return null;
- const rows: ReactNode[] = (showAll ? files : files.slice(0, OUTPUT_PREVIEW)).map(file => <Row key={file.key}
- icon={<FileTypeIcon name={file.name} size={ICON_GLYPH} color={colors.textSecondary} />} title={file.name}
- meta={t('devices.glance.outputMeta', { time: dayLabel(file.at, i18n.language), task: file.taskTitle })}
- onPress={() => onOpenTask(file.childSessionId)} testID="companion.glance.output" />);
- if (files.length > OUTPUT_PREVIEW) rows.push(<FoldRow key="more" inset label={showAll ? t('devices.glance.showLess') : t('devices.glance.showMore')}
+ const outputs = [
+ ...files.map(file => ({ kind: 'file' as const, key: `file:${file.key}`, at: file.at, file })),
+ ...prs.map(pr => ({ kind: 'pr' as const, key: `pr:${prStatusKey(pr.ref)}`, at: pr.ref.lastSeenAt, pr })),
+ ].sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
+ if (outputs.length === 0) return null;
+ const rows: ReactNode[] = (showAll ? outputs : outputs.slice(0, OUTPUT_PREVIEW)).map(output => output.kind === 'pr'
+ ? <PrOutput key={output.key} pr={output.pr} /> : <Row key={output.key}
+ icon={<FileTypeIcon name={output.file.name} size={ICON_GLYPH} color={colors.textSecondary} />} title={output.file.name} inlineMeta
+ onPress={() => onOpenTask(output.file.childSessionId)} testID="companion.glance.output" />);
+ if (outputs.length > OUTPUT_PREVIEW) rows.push(<FoldRow key="more" inset label={showAll ? t('devices.glance.showLess') : t('devices.glance.showMore')}
open={showAll} onPress={() => setShowAll(value => !value)} testID="companion.glance.output.more" />);
return <Section label={t('devices.glance.outputs')}>{joinRows(rows, true, styles)}</Section>;
}
+/** Uses Home's existing teammate attribution, PR cache and live attention; owns no read state. */
+function Activity({ botId, deviceId, deviceName, sessionId, online, onOpenTask }: {
+ botId: string; deviceId: string; deviceName: string; sessionId: string; online: boolean;
+ onOpenTask(id: string, deviceId?: string): void;
+}) {
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const cached = useRemoteHomeSessions();
+ const { user, accountGeneration } = useAuth();
+ const cloud = useCloudCompanionHome(false);
+ const hosts = new Map([[deviceId, deviceName]]);
+ // The same teammate identity rules as Home determine which known computers contribute.
+ const cloudIds = new Set(cloud.actors.filter(actor => actor.kind === 'bot').map(actor => actor.externalId));
+ const cindyIds = new Set(cloud.cindyIds);
+ const target = taskTeammateKey(botId, deviceId, cloudIds, cindyIds);
+ for (const row of readRemoteCollectionCache(`${user?.id ?? ''}:${accountGeneration}`, 'teammates')) {
+ if (row.item.ref.kind === 'bot' && taskTeammateKey(row.item.ref.id, row.host.deviceId, cloudIds, cindyIds) === target)
+ hosts.set(row.host.deviceId, row.host.deviceName);
+ }
+ const [snapshots, setSnapshots] = useState<Record<string, RemoteSession[]>>({});
+ const receiveTasks = useCallback((host: string, rows: RemoteSession[]) =>
+ setSnapshots(previous => ({ ...previous, [host]: rows })), []);
+ const hostIdsKey = JSON.stringify([...hosts.keys()]);
+ const sessions = useMemo(() => {
+ const visibleHosts = new Set(JSON.parse(hostIdsKey) as string[]);
+ return [...cached.filter(row => !snapshots[row.deviceLinkDeviceId ?? '']),
+ ...Object.entries(snapshots).filter(([host]) => visibleHosts.has(host)).flatMap(([, rows]) => rows)];
+ }, [cached, snapshots, hostIdsKey]);
+ const tasks = useMemo(() => {
+ const cloudIds = new Set(cloud.actors.filter(actor => actor.kind === 'bot').map(actor => actor.externalId));
+ const cindyIds = new Set(cloud.cindyIds);
+ const target = taskTeammateKey(botId, deviceId, cloudIds, cindyIds);
+ return sessions.filter(task => {
+ const creator = task.taskTeammate?.id ?? (isTeammateTask(task) ? task.companion?.id : undefined);
+ return task.id !== sessionId && task.orcaRole !== 'worker' && creator
+ && (task.status === 'active' || task.status === 'archived')
+ && taskTeammateKey(creator, task.deviceLinkDeviceId ?? '', cloudIds, cindyIds) === target;
+ }).sort((a, b) => Date.parse(getSessionListActivityAt(b) ?? '') - Date.parse(getSessionListActivityAt(a) ?? '')).slice(0, 30);
+ }, [sessions, cloud.actors, cloud.cindyIds, botId, deviceId, sessionId]);
+ const [allTasks, setAllTasks] = useState(false);
+ const [results, setResults] = useState<Record<string, HomeSessionPrInfo | null>>({});
+ const receive = useCallback((id: string, value: HomeSessionPrInfo | null) =>
+ setResults(previous => previous[id] === value ? previous : { ...previous, [id]: value }), []);
+ const prs = useMemo(() => {
+ const unique = new Map<string, HomeSessionPrInfo>();
+ const values = tasks.flatMap(task => { const value = results[taskKey(task)]; return value ? [value, ...(value.additional ?? [])] : []; }).filter((value): value is HomeSessionPrInfo => !!value)
+ .sort((a, b) => b.ref.lastSeenAt - a.ref.lastSeenAt);
+ for (const value of values) if (!unique.has(prStatusKey(value.ref))) unique.set(prStatusKey(value.ref), value);
+ return [...unique.values()];
+ }, [results, tasks]);
+ const rows = (allTasks ? tasks : tasks.slice(0, TASK_PREVIEW)).map(task =>
+ <RecentTask key={taskKey(task)} task={task} onOpen={() => onOpenTask(task.id, task.deviceLinkDeviceId)} />);
+ return <>
+ {[...hosts].map(([id, name]) => <TaskReader key={id} deviceId={id} deviceName={name} receive={receiveTasks} />)}
+ {tasks.map(task => <PrReader key={taskKey(task)} task={task} receive={receive} />)}
+ {tasks.length ? <Section label={t('devices.glance.recentTasks')}>
+ {joinRows(rows, true, styles)}
+ {tasks.length > TASK_PREVIEW ? <FoldRow inset label={t(allTasks ? 'devices.glance.showLess' : 'devices.glance.showMore')}
+ open={allTasks} onPress={() => setAllTasks(value => !value)} testID="companion.glance.tasks.more" /> : null}
+ </Section> : null}
+ <Outputs botId={botId} deviceId={deviceId} sessionId={sessionId} online={online} onOpenTask={id => onOpenTask(id, deviceId)} prs={prs} />
+ </>;
+}
+
+const taskKey = (task: RemoteSession) => JSON.stringify([task.deviceLinkDeviceId, task.id]);
+
+/** Read all statuses while this sheet is open; never replace Home's filtered snapshot. */
+function TaskReader({ deviceId, deviceName, receive }: {
+ deviceId: string; deviceName: string; receive(host: string, rows: RemoteSession[]): void;
+}) {
+ const { invoke, connectionEpoch } = useDeviceLink();
+ const { accountGeneration } = useAuth();
+ const { value, cause } = useRemoteCompanionQuery<RemoteSession[]>(deviceId, 'local-db:sessions:list', [200, 'all', { fresh: true }]);
+ useEffect(() => {
+ if (isAccessRevokedRemoteError(cause)) { receive(deviceId, []); return; }
+ if (!Array.isArray(value)) return;
+ let disposed = false;
+ void readTeammateTasks({ invoke, deviceId, deviceName, sessions: value, previous: remoteSessionStore.getHomeSessions(),
+ scope: JSON.stringify([accountGeneration, connectionEpoch, deviceId]), status: 'all', limit: 200, current: () => !disposed,
+ }).then(rows => {
+ if (!disposed) receive(deviceId, rows.map(row => ({ ...row, deviceLinkDeviceId: deviceId, deviceLinkDeviceName: deviceName })));
+ }).catch(error => {
+ if (!disposed && isAccessRevokedRemoteError(error)) receive(deviceId, []);
+ // Other failures keep the last known same-account snapshot.
+ });
+ return () => { disposed = true; };
+ }, [value, cause, invoke, accountGeneration, connectionEpoch, deviceId, deviceName, receive]);
+ return null;
+}
+
+function PrReader({ task, receive }: { task: RemoteSession; receive(id: string, value: HomeSessionPrInfo | null): void }) {
+ const value = useHomeSessionPr(task.deviceLinkDeviceId, task.id, true, task.updatedAt, true, true);
+ const key = taskKey(task);
+ useEffect(() => receive(key, value), [receive, key, value]);
+ return null;
+}
+
+function RecentTask({ task, onOpen }: { task: RemoteSession; onOpen(): void }) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const unread = useSyncExternalStore(remoteSessionStore.subscribeHomeStatus, () => {
+ const activity = remoteSessionStore.getSessionLiveActivity(task.id, task.deviceLinkDeviceId);
+ return activity?.phase === 'completed' && activity.attention === true;
+ });
+ return <Row icon={<MessageCircle size={ICON_GLYPH} color={colors.textSecondary} strokeWidth={iconStroke.regular} />}
+ title={task.title} inlineMeta onPress={onOpen} testID="companion.glance.task"
+ trailing={unread ? <View accessibilityLabel={t('devices.glance.unread')} style={styles.unreadDot} /> : undefined} />;
+}
+
+function PrOutput({ pr }: { pr: HomeSessionPrInfo }) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const [failed, setFailed] = useState(false);
+ const visual = prStatusVisual(pr.status?.ok ? pr.status.status : null, colors);
+ return <><Row icon={<visual.Icon size={ICON_GLYPH} color={visual.color} strokeWidth={iconStroke.regular} />}
+ title={(pr.status?.ok ? pr.status.title?.trim() : undefined) || `${pr.ref.owner}/${pr.ref.repo}`} inlineMeta
+ onPress={() => { setFailed(false); void Linking.openURL(sessionPrUrl(pr.ref)).catch(() => setFailed(true)); }} testID="companion.glance.pr" />
+ {failed ? <Text accessibilityRole="alert" style={styles.error}>{t('devices.glance.openFailed')}</Text> : null}</>;
+}
+
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ sectionHeading: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
+ headerAction: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' },
+ unreadDot: { width: 6, height: 6, borderRadius: radius.pill, backgroundColor: colors.statusDone },
// The sheet host already insets content by 16 (原型 .shbody 0 16).
content: { paddingBottom: spacing.xxl },
- header: { flexDirection: 'row', alignItems: 'center', gap: ROW_GAP, paddingTop: spacing.sm, paddingBottom: spacing.xl - 2, paddingHorizontal: spacing.xs },
+ header: { flexDirection: 'row', alignItems: 'center', gap: ROW_GAP, paddingTop: spacing.sm, paddingBottom: spacing.lg, paddingHorizontal: spacing.xs },
headerName: { flex: 1, color: colors.textPrimary, fontSize: typeScale.title, lineHeight: lineHeight.title, fontWeight: fontWeight.semibold },
- section: { marginBottom: spacing.xl - 2 },
+ section: { marginBottom: spacing.lg },
sectionLabel: {
color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.semibold,
paddingHorizontal: spacing.lg, paddingBottom: spacing.sm - 1,
@@ -329,6 +459,10 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
backgroundColor: colors.statusReady, borderWidth: 2, borderColor: colors.sheetActionSurface,
},
rowText: { flex: 1, minWidth: 0 },
+ compactRow: { paddingVertical: spacing.sm },
+ inlineText: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm },
+ inlineTitle: { flex: 1, minWidth: 0 },
+ inlineMeta: { maxWidth: '40%', flexShrink: 0 },
rowTitle: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },
rowTitleMuted: { color: colors.textSecondary, fontWeight: fontWeight.regular },
rowMeta: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
diff --git a/apps/mobile/src/session/CompanionHeader.tsx b/apps/mobile/src/session/CompanionHeader.tsx
index 92e8ee577a..c2a73447c1 100644
--- a/apps/mobile/src/session/CompanionHeader.tsx
+++ b/apps/mobile/src/session/CompanionHeader.tsx
@@ -93,7 +93,7 @@ function CompanionHeaderContent({ nativeHeader, resource, deviceId, deviceName,
deviceId={deviceId} deviceName={deviceName} sessionId={sessionId} online={online} cloudHome={homed} todos={todos}
onQuoteTodo={onQuoteTodo}
onCheckTodos={askCompanionReady ? () => onAskCompanion(t('devices.glance.checkPrompt')) : undefined}
- onOpenTask={taskId => router.push({ pathname: '/sessions/[sessionId]', params: { sessionId: taskId, deviceId } })}
+ onOpenTask={(taskId, taskDeviceId) => router.push({ pathname: '/sessions/[sessionId]', params: { sessionId: taskId, deviceId: taskDeviceId ?? deviceId } })}
onOpenCindy={hosted => void navigation.openTeammate(hosted, { replace: true })}
onSwitchHome={() => setHomeSheet(true)} />
<CompanionProfileSheet initialPage={initialPage} visible={profile} onClose={() => setProfile(false)} onClosed={() => { const action = pending.current; pending.current = null; action?.(); }}
diff --git a/apps/mobile/src/session/HomeSessionInfoMeta.tsx b/apps/mobile/src/session/HomeSessionInfoMeta.tsx
index 8717221d0d..4573339b39 100644
--- a/apps/mobile/src/session/HomeSessionInfoMeta.tsx
+++ b/apps/mobile/src/session/HomeSessionInfoMeta.tsx
@@ -156,16 +156,18 @@ function pickDefinedUsage(usage: RemoteSessionUsage): RemoteSessionUsage {
* 行内 PR 信息。enabled=false(未勾选 PR / 非远程任务)时不订阅、不查询。
* refreshKey 传任务的 updatedAt:任务有新动静时(可能刚提了 PR)提前重查。
*/
-function useHomeSessionPr(
+export function useHomeSessionPr(
deviceId: string | undefined,
sessionId: string,
enabled: boolean,
refreshKey?: string,
+ foreground = false,
+ includeRelated = false,
): HomeSessionPrInfo | null {
const link = useDeviceLink();
const { accountGeneration } = useAuth();
const key = enabled && deviceId
- ? homeSessionPrCacheKey(String(accountGeneration), deviceId, sessionId)
+ ? homeSessionPrCacheKey(String(accountGeneration), deviceId, sessionId) + (includeRelated ? ':related' : '')
: null;
const subscribe = useCallback(
(listener: () => void) => (key ? subscribeHomeSessionPr(key, listener) : () => undefined),
@@ -182,8 +184,8 @@ function useHomeSessionPr(
let retry: ReturnType<typeof setTimeout> | undefined;
// eventful = 回到首页 / 回到前台:期间的轮询被跳过,PR 可能已合并或关闭,不沿用 90 秒缓存。
const refresh = (eventful = false) => {
- if (AppState.currentState !== 'active' || !isActive()) return;
- const retryIn = refreshHomeSessionPr(key, (previous) => loadHomeSessionPr(link.invoke, deviceId, sessionId, previous), {
+ if (AppState.currentState !== 'active' || (!foreground && !isActive())) return;
+ const retryIn = refreshHomeSessionPr(key, (previous) => loadHomeSessionPr(link.invoke, deviceId, sessionId, previous, includeRelated), {
eventful,
now: Date.now(),
refreshKey,
@@ -208,7 +210,7 @@ function useHomeSessionPr(
stopResume();
appState.remove();
};
- }, [deviceId, isActive, key, link.connectionEpoch, link.invoke, onResume, online, refreshKey, sessionId]);
+ }, [deviceId, foreground, includeRelated, isActive, key, link.connectionEpoch, link.invoke, onResume, online, refreshKey, sessionId]);
return value;
}
diff --git a/apps/mobile/src/session/homeSessionPrStore.ts b/apps/mobile/src/session/homeSessionPrStore.ts
index 66db4df0e3..a015a9b242 100644
--- a/apps/mobile/src/session/homeSessionPrStore.ts
+++ b/apps/mobile/src/session/homeSessionPrStore.ts
@@ -1,5 +1,6 @@
import {
PR_STATUS_REFRESH_INTERVAL_MS,
+ MAX_STATUS_QUERIES,
prStatusKey,
type PrStatusResult,
type SessionPrRef,
@@ -19,6 +20,8 @@ import {
export interface HomeSessionPrInfo {
ref: SessionPrRef;
status: PrStatusResult | null;
+ /** Glance includes the same bounded association list as the desktop PR menu. */
+ additional?: HomeSessionPrInfo[];
}
type Invoke = <T>(deviceId: string, channel: string, args: unknown[]) => Promise<T>;
@@ -107,26 +110,35 @@ export async function loadHomeSessionPr(
deviceId: string,
sessionId: string,
previous: HomeSessionPrInfo | null = null,
+ includeRelated = false,
): Promise<HomeSessionPrInfo | null> {
const refs = await invoke<unknown>(deviceId, 'git-context:pr-refs:list', [sessionId]);
const ref = latestPrRef(refs);
if (!ref) return null;
// 状态查询失败只是这一轮没拿到,不是「状态未知」:同一 PR 沿用上次已知状态
// (已合并 / 已关闭不该退回中性图标);换了 PR 才没有可沿用的状态。
- const carried = previous && prStatusKey(previous.ref) === prStatusKey(ref) ? previous.status : null;
+ const previousRows = previous ? [previous, ...(previous.additional ?? [])] : [];
+ const selected = includeRelated && Array.isArray(refs)
+ ? (refs as SessionPrRef[]).filter(item => latestPrRef([item]) !== null).sort((a, b) => b.lastSeenAt - a.lastSeenAt).slice(0, MAX_STATUS_QUERIES)
+ : [ref];
+ const build = (statuses: unknown): HomeSessionPrInfo => {
+ const rows = selected.map(item => {
+ const carried = previousRows.find(row => prStatusKey(row.ref) === prStatusKey(item))?.status ?? null;
+ const next = Array.isArray(statuses) ? (statuses as PrStatusResult[]).find(status => status && prStatusKey(status) === prStatusKey(item)) : null;
+ return { ref: item, status: includeRelated ? (next?.ok ? next : carried ?? next ?? null) : next ?? carried };
+ });
+ return { ...rows[0], ...(includeRelated ? { additional: rows.slice(1) } : {}) };
+ };
let statuses: unknown;
try {
statuses = await invoke<unknown>(deviceId, 'git-context:pr-status', [{
sessionId,
- queries: [{ owner: ref.owner, repo: ref.repo, prNumber: ref.prNumber }],
+ queries: selected.map(item => ({ owner: item.owner, repo: item.repo, prNumber: item.prNumber })),
}]);
} catch {
- return { ref, status: carried };
+ return build(null);
}
- const status = Array.isArray(statuses)
- ? (statuses as PrStatusResult[]).find((item) => item && prStatusKey(item) === prStatusKey(ref)) ?? null
- : null;
- return { ref, status: status ?? carried };
+ return build(statuses);
}
/** 与桌面信息槽一致:只显示最近一次出现的 PR(lastSeenAt 最大)。 */
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 4a1deef570..d26a585fed 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -907,33 +907,43 @@ Session 任务遵守同一套机制与呈现契约:
其它伙伴只看自己开的或明确接手的任务。「自动跟进所有任务」设置的原始 IPC 通道不开放给远程;桌面远程控制经伙伴设置主机(`management:settings`,由伙伴所在电脑执行)读写,与手机的「跟进我的任务」页同一份宿主设置。
**伙伴近况**(2026-10-21 Chris 定稿,取代右侧栏「工作台」标签;原型 `Designs/cindy/teammate-glance`):伙伴聊天头部的
-网格按钮打开一个浮层,参考 Dots 只放三块,没有内容的块整块不出现(新伙伴只有「电脑」)。不再有「等你 / 在做」分组、
+网格按钮打开一个浮层,沿用原浮层外壳,依次放电脑、待办、近期任务、输出内容,没有内容的块整块不出现(新伙伴只有「电脑」)。不再有「等你 / 在做」分组、
「允许」按钮和扫描时间页脚;等你处理的任务照常走任务列表、通知与任务内的确认卡。实现见
`apps/desktop/src/renderer/features/bots/BotGlancePopover.tsx`、`botGlanceTodos.ts`。
+桌面设备状态放在同行,近期任务只显示任务标题与未读点,移除来源电脑副文案;单行最低 32px。
+浮层随内容自然长高,以锚点到窗口边缘的可用空间为上限、保留 12px 边距,超出后滚动,不设固定 640px 高度上限。
+手机同样减少设备与任务副信息的重复行,但保留至少 44pt 点击区域和原生 sheet 的半屏/展开交互。
+
- **电脑**:当前运行的电脑在最前(打勾),其余在线的可点;离线的收进「离线 N 台」。云端伙伴点另一台走主力电脑的
原确认流程(cloud-companions.md §3.1),Cindy 的多台副本直接打开那台上的她;其它伙伴只显示它所在的那台。状态词用
「在线 / 离线」。
-- **待办**:只列未完成的(到期在前),「显示更多」「已完成 N」原地展开。行内没有按钮:点一条就作为 Todo 引用放进
+- **待办**(2026-10-28 修订):只列明确期限已过或未来 7 天内到期的未完成事项(到期在前),默认 2 条,更多原地展开。
+ 无期限旧想法、建议日期、待确认日期和已完成事项不在近况展示;没有符合项时整块收起,不保留「已完成 N」。
+ 这是桌面和手机共用的只读展示规则,不删除源记录、不补造期限,主人覆盖或清除期限仍优先。
+ 行内没有按钮:点一条就作为 Todo 引用放进
输入框(`kind: 'todo'` 的 Composer 引用,带稳定 Todo ID),主人写一句话再发,由伙伴按话更新;右键只有「删除」,
删除即同一问题不再记,可在提示里撤销。期限是今天或已过期的那条在期限前带红点;入口按钮在主人还没打开过近况时
亮同样的红点,打开即灭,期限变化算一次新的到期(本机按伙伴记住看过的到期项)。别的电脑上的伙伴经该电脑的
`todos:<botId>` 远程资源读写,与手机同一路径。
-- **帮我查查 / 每天帮我查一次**(2026-10-22 Chris 定):待办块第一行固定是「帮我查查」,没有待办时整块也在。
- 点它把一句固定的话(让伙伴去已连接的邮箱、消息等来源找需要主人处理的新事项并记成待办)作为主人的消息发进伙伴对话:
- 桌面走普通发送(`makerChatStore.sendMessage`,用伙伴对话当前的模型与权限);手机输入框空着时直接发出,已有草稿或附件时
- 只把这句话放进输入框、不替主人连同草稿一起发。两端都带正常的来源设备标记,不由宿主代发。下一行开关「每天帮我查一次」
- 打开伙伴的内置例行任务 `builtin: 'todo-check'`(工作日 9:00、没有新待办不提醒,见 bot-routines.md「内置查待办例行任务」),
- 默认关;这是伙伴主动在来源里找待办的唯一入口,且只由主人在这里开启。桌面经 `local-db:bots:todos:daily-check`,
- 别的电脑与手机经 `todos:<botId>` 远程资源的 `dailyCheck` 字段与 `todo-daily-check` 动作;旧宿主不带该字段时开关不出现。
- 这是手机唯一的例行任务开关,不恢复手机的例行任务管理。
-- **输出内容**:伙伴开的任务做完时留下的成品文件(委派回执里未删除、属于成品类型的文件),最近在前,先列 3 条;
- 点开本机文件,别的电脑上的打开来源任务。
+- **帮我查查 / 每天帮我查一次**(2026-10-28 修订):成功读到空待办时整块收起;有待办时「帮我查查」
+ 只保留标题旁的小按钮,仍把原固定请求以主人消息交给伙伴。已开启的每天检查显示一行,× 调用原宿主入口停用,
+ 停用成功即移除;不常驻推荐开关。空块隐藏不影响已启用的例行任务;读取失败保留重试,不当成空结果。
+ 引用、删除及撤销原行为不变;已完成记录仍由现有待办工具读取。
+- **近期任务**(2026-10-28):复用任务列表的伙伴创建者归属(#7546),Cindy 跨电脑合并身份,
+ 其它伙伴保留既有本地或云端身份边界。只列独立任务,不把主对话、私聊、群主对话或单纯跟进的任务混进来。
+ 最近活动在前,先列 5 条、展开最多 30 条;点击走任务原路由并保留所属电脑。绿色未读点直接读取已有任务
+ attention(Desktop done / Mobile completed + attention),不新增已读存储或同步、不从完成状态推断未读。
+- **输出内容**:保留完成委派里未删除的成品文件,加入近期任务关联的 PR。PR 按仓库和编号去重;
+ 单行显示可点击的真实 PR 标题,不常驻仓库编号或灰色副标题;标题尚未取得时以仓库名占位,不以任务标题兜底。状态图标与颜色沿用任务列表,未知时中性显示。
+ PR 与文件混排为同一份产物列表,按现有记录时间倒序(PR 的 lastSeenAt,文件委派的 completedAt/updatedAt),
+ 合计预览 3 条,共用一个「显示更多」展开已读取的产物,不按类型分组或分别折叠。
+ 文件同样只显示图标与文件名,不常驻日期和来源任务副文案。PR 点击打开 GitHub,文件仍在本机打开,远程文件打开来源任务。
- **手机**(2026-10-22):点伙伴聊天顶栏的头像(身份区)打开同内容的近况,设置按钮仍进伙伴资料。iOS 用系统 sheet
(中等高度起、可上拉、下拉关闭),Android 用现有面板;内容按原型 r1.1 的 inset grouped 卡片绘制(头部 56 头像与名字,
- 行 11/16 内边距、两行文字、分隔线从文字列起)。电脑:Cindy 的其它副本取自手机已读到的伙伴列表,
+ 紧凑单行保留至少 44pt 点击区、分隔线从文字列起)。电脑:Cindy 的其它副本取自手机已读到的伙伴列表,
云端伙伴用「换一台电脑继续」进入原有的更换主力电脑流程;待办长按弹系统上下文菜单,只有「删除」,删除后该块顶部出现「撤销」
- 一行直到关闭;输出内容一律打开来源任务。到期红点在顶栏头像右上,看过的到期项按账号、电脑与伙伴记在手机本地。
+ 一行直到关闭;文件打开来源任务,PR 打开对应 GitHub 页面。到期红点在顶栏头像右上,看过的到期项按账号、电脑与伙伴记在手机本地。
「成品类型」判断与桌面共用 `@cindy/maker-shared/bot-deliverable`。实现见 Mobile `CompanionGlanceSheet.tsx`、
`useCompanionGlanceTodos.ts`。
- 右侧栏历史里遗留的 `bot-workbench` 页签在打开时静默关闭;设置里的待办列表一并移除,待办只在近况里看、在对话里改。
diff --git a/packages/maker-shared/src/teammateTodo.test.ts b/packages/maker-shared/src/teammateTodo.test.ts
index c2a30d7efb..7657d5cef2 100644
--- a/packages/maker-shared/src/teammateTodo.test.ts
+++ b/packages/maker-shared/src/teammateTodo.test.ts
@@ -8,6 +8,7 @@ import {
scheduleTodoDeferralRefresh,
createTodoDueComparator,
todoOverdue,
+ todoDueSoon,
todoVisible,
validateTodoDeadline,
type TodoPatch,
@@ -25,6 +26,33 @@ const patch: TodoPatch = {
instruction: '按已授权范围排查并准备修复',
},
};
+// Glance's deadline-only rule: old ideas, completed items and tentative dates must not
+// reappear as urgent owner affairs. Both clients consume this production selector (unit).
+it('shows only visible open affairs with a confirmed deadline, respecting cleared overrides', () => {
+ const state = emptyTodoState();
+ const item = applyTodoPatch(state, { ...patch, sourceDeadline: { kind: 'date', date: '2026-10-10', timeZone: 'UTC' } }, 'due', now);
+ expect(todoDueSoon(item, now)).toBe(true);
+ expect(todoDueSoon({ ...item, status: 'done' }, now)).toBe(false);
+ expect(todoDueSoon({ ...item, decision: { kind: 'deleted' } }, now)).toBe(false);
+ expect(todoDueSoon({ ...item, decision: { kind: 'muted' } }, now)).toBe(false);
+ expect(todoDueSoon({ ...item, decision: { kind: 'later', until: '2026-10-11T12:00:00Z' } }, now)).toBe(false);
+ expect(todoDueSoon({ ...item, deadlineOverride: { value: null } }, now)).toBe(false);
+ expect(todoDueSoon({ ...item, sourceDeadline: null, suggestedDate: '2026-10-10',
+ deadlineCandidate: { value: item.sourceDeadline!, reason: 'Unconfirmed' } }, now)).toBe(false);
+ expect(state.items[0]).toEqual(item);
+});
+
+it('includes overdue and the seven-day boundary using the source calendar or exact timestamp', () => {
+ const item = applyTodoPatch(emptyTodoState(), patch, 'one', now);
+ const at = new Date('2026-10-10T23:30:00Z');
+ const dateItem = (date: string) => ({ ...item, sourceDeadline: { kind: 'date' as const, date, timeZone: 'Asia/Shanghai' } });
+ expect(todoDueSoon(dateItem('2026-10-01'), at)).toBe(true);
+ expect(todoDueSoon(dateItem('2026-10-18'), at)).toBe(true);
+ expect(todoDueSoon(dateItem('2026-10-19'), at)).toBe(false);
+ const exact = { ...item, sourceDeadline: { kind: 'instant' as const, date: '2026-10-17', timeZone: 'UTC', at: '2026-10-17T23:30:00Z' } };
+ expect(todoDueSoon(exact, at)).toBe(true);
+ expect(todoDueSoon(exact, new Date(at.getTime() - 1))).toBe(false);
+});
describe('teammate affairs contract', () => {
it('works without projects and merges source evidence into the same affair', () => {
const s = emptyTodoState(),
diff --git a/packages/maker-shared/src/teammateTodo.ts b/packages/maker-shared/src/teammateTodo.ts
index daa7fe7b1c..9b591472b2 100644
--- a/packages/maker-shared/src/teammateTodo.ts
+++ b/packages/maker-shared/src/teammateTodo.ts
@@ -223,6 +223,18 @@ export function todoDue(t: TeammateTodo, now = new Date()): boolean {
? todoLocalDate(new Date(d.at!), d.timeZone) === todoLocalDate(now, d.timeZone)
: d.date === todoLocalDate(now, d.timeZone);
}
+/** Glance shows only open, visible affairs with a real deadline within seven days (including overdue).
+ * Suggestions and unconfirmed candidates never manufacture urgency. Clearing a deadline hides it.
+ */
+export function todoDueSoon(t: TeammateTodo, now = new Date()): boolean {
+ if (t.status !== 'open' || !todoVisible(t, now)) return false;
+ const deadline = effectiveTodoDeadline(t);
+ if (!deadline) return false;
+ if (deadline.kind === 'instant') return Date.parse(deadline.at!) <= now.getTime() + 7 * 86_400_000;
+ const horizon = new Date(todoLocalDate(now, deadline.timeZone) + 'T00:00:00Z');
+ horizon.setUTCDate(horizon.getUTCDate() + 7);
+ return deadline.date <= horizon.toISOString().slice(0, 10);
+}
export function todoDateLabel(t: TeammateTodo, locale: string, now = new Date()): string {
const d = effectiveTodoDeadline(t);
const dateString = d?.date ?? t.deadlineCandidate?.value.date ?? t.suggestedDate;