Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(web): magic chip as a fixed-height expandable card; fix duplicate-folded prompts (#6230)

Wolf Mermelstein8766c88f3fb2
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
index fa809667bf..2cdc68c536 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
@@ -2,69 +2,184 @@
* @vitest-environment jsdom
*/
-import { render, screen } from '@solidjs/testing-library';
-import { describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MagicChipView } from './MagicChipView';
vi.mock(
'@core/component/LexicalMarkdown/component/core/StaticMarkdown',
() => ({
StaticMarkdownContext: (props: { children: unknown }) => props.children,
- StaticMarkdown: (props: { markdown: string }) => <p>{props.markdown}</p>,
+ StaticMarkdown: (props: { markdown: string }) => (
+ <div data-testid="chip-markdown">{props.markdown}</div>
+ ),
})
);
-import { MagicChipView } from './MagicChipView';
+vi.mock('@core/component/LexicalMarkdown/theme', () => ({
+ channelTheme: {},
+}));
+
+afterEach(cleanup);
const LONG_PATH =
'/home/ubuntu/.cursor/projects/workspace/terminals/261831.txt'.repeat(8);
+function answerArea(container: HTMLElement) {
+ return container.querySelector('[data-magic-chip-answer]');
+}
+
describe('MagicChipView', () => {
- it('keeps a streaming thought inside the message column', () => {
+ it('reserves the answer height and shows the activity row while working', () => {
+ const onOpen = vi.fn();
const { container } = render(() => (
- <div style={{ width: '320px' }}>
- <MagicChipView
- agentSessionId="session-1"
- presentation={{
- kind: 'working',
- activity: {
- label: 'Thinking',
- detail: LONG_PATH,
- busy: true,
- },
- }}
- />
- </div>
+ <MagicChipView
+ agentSessionId="session"
+ presentation={{
+ kind: 'working',
+ activity: { label: 'Booting agent', busy: true },
+ }}
+ onOpen={onOpen}
+ />
));
- const chip = container.querySelector('[data-magic-chip="session-1"]');
- expect(chip?.className).toContain('min-w-0');
- expect(chip?.className).toContain('max-w-full');
- expect(chip?.className).toContain('overflow-x-hidden');
- expect(screen.getByText('Thinking')).toBeTruthy();
- expect(screen.getByText(LONG_PATH).className).toContain('truncate');
+ const card = container.querySelector('[data-magic-chip-preview]');
+ expect(card?.className).toContain('rounded-lg');
+ expect(card?.className).not.toContain('border-accent');
+
+ expect(answerArea(container)?.className).toContain('h-22');
+ expect(container.querySelector('[data-testid="chip-markdown"]')).toBeNull();
+ expect(container.querySelector('[data-magic-chip-pending]')).toBeTruthy();
+ expect(container.querySelector('.bg-skeleton')).toBeNull();
+
+ const footer = card?.querySelector('button');
+ expect(footer?.textContent).toContain('Booting agent');
+ expect(footer?.getAttribute('data-message-reply-preview')).toBe(
+ 'Booting agent'
+ );
+
+ // Nothing to expand yet, so the answer area leads to the session too.
+ expect(answerArea(container)?.getAttribute('aria-expanded')).toBeNull();
+ fireEvent.click(answerArea(container)!);
+ fireEvent.click(footer!);
+ expect(onOpen).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps the same answer height once the answer streams in', () => {
+ const onOpen = vi.fn();
+ const { container } = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={{
+ kind: 'answering',
+ markdown: 'Hello from the agent',
+ activity: { label: 'Writing response', busy: false },
+ }}
+ onOpen={onOpen}
+ />
+ ));
+
+ expect(answerArea(container)?.className).toContain('h-22');
+ expect(container.querySelector('[data-magic-chip-pending]')).toBeNull();
+
+ const clip = container.querySelector('[data-magic-chip-clip]');
+ expect(clip?.className).toContain('overflow-hidden');
+ const preview = container.querySelector('[data-message-reply-preview]');
+ expect(preview?.textContent).toBe('Hello from the agent');
+
+ const footer = container.querySelector('[data-magic-chip-preview] button');
+ expect(footer?.textContent).toContain('Writing response');
+ expect(footer?.textContent).not.toContain('Open session');
+
+ fireEvent.click(footer!);
+ expect(onOpen).toHaveBeenCalledTimes(1);
+ });
+
+ it('expands the answer in place on click and collapses again', () => {
+ const onOpen = vi.fn();
+ const { container } = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={{ kind: 'settled', markdown: 'All done' }}
+ onOpen={onOpen}
+ />
+ ));
+
+ const area = answerArea(container)!;
+ const clip = () => container.querySelector('[data-magic-chip-clip]');
+ const fade = () => container.querySelector('[data-magic-chip-fade]');
+ expect(area.getAttribute('aria-expanded')).toBe('false');
+ expect(area.className).toContain('h-22');
+ expect(fade()).toBeTruthy();
+ expect(area.textContent).toContain('Show more');
+
+ fireEvent.click(area);
+ expect(area.getAttribute('aria-expanded')).toBe('true');
+ expect(area.className).not.toContain('h-22');
+ expect(clip()?.className).not.toContain('overflow-hidden');
+ expect(fade()).toBeNull();
+ expect(area.textContent).toContain('Show less');
+ expect(onOpen).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(area, { key: 'Enter' });
+ expect(area.getAttribute('aria-expanded')).toBe('false');
+ expect(area.className).toContain('h-22');
+ expect(clip()?.className).toContain('overflow-hidden');
+ expect(fade()).toBeTruthy();
+ expect(area.textContent).toContain('Show more');
+ expect(onOpen).not.toHaveBeenCalled();
});
- it('keeps a streaming answer inside the message column', () => {
+ it('keeps the disclosure hint out of the reply preview text', () => {
+ const { container } = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={{ kind: 'settled', markdown: 'All done' }}
+ />
+ ));
+
+ fireEvent.click(answerArea(container)!);
+ expect(answerArea(container)?.textContent).toContain('Show less');
+ expect(
+ container.querySelector('[data-message-reply-preview]')?.textContent
+ ).toBe('All done');
+ });
+
+ it('labels the settled footer Open session', () => {
+ const onOpen = vi.fn();
+ const { container } = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={{ kind: 'settled', markdown: 'All done' }}
+ onOpen={onOpen}
+ />
+ ));
+
+ expect(answerArea(container)?.className).toContain('h-22');
+ const footer = container.querySelector('[data-magic-chip-preview] button');
+ expect(footer?.textContent).toContain('Open session');
+ fireEvent.click(footer!);
+ expect(onOpen).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a long activity detail inside the message column', () => {
const { container } = render(() => (
<div style={{ width: '320px' }}>
<MagicChipView
- agentSessionId="session-2"
+ agentSessionId="session-1"
presentation={{
- kind: 'answering',
- markdown: `Inspecting \`${LONG_PATH}\``,
- activity: {
- label: 'Reading files',
- detail: LONG_PATH,
- busy: true,
- },
+ kind: 'working',
+ activity: { label: 'Thinking', detail: LONG_PATH, busy: true },
}}
/>
</div>
));
- const chip = container.querySelector('[data-magic-chip="session-2"]');
- expect(chip?.className).toContain('grid-cols-[minmax(0,1fr)]');
- expect(chip?.className).toContain('overflow-x-hidden');
- expect(screen.getByText('Reading files')).toBeTruthy();
+ const card = container.querySelector('[data-magic-chip="session-1"]');
+ expect(card?.className).toContain('min-w-0');
+ expect(card?.className).toContain('max-w-full');
+ expect(card?.className).toContain('overflow-hidden');
+ expect(screen.getByText('Thinking')).toBeTruthy();
+ expect(screen.getByText(LONG_PATH).className).toContain('truncate');
});
});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
index fc6f36612e..238a0e4f60 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
@@ -3,49 +3,31 @@ import {
StaticMarkdownContext,
} from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { channelTheme } from '@core/component/LexicalMarkdown/theme';
-import { type Component, Match, Show, Switch } from 'solid-js';
+import { PulsingStar } from '@entity/components/PulsingStar';
+import ArrowUpRight from '@phosphor/arrow-up-right.svg';
+import CaretRight from '@phosphor/caret-right.svg';
+import { Layer } from '@ui';
+import { type Component, createSignal, Show } from 'solid-js';
import type { MagicChipActivity, MagicChipPresentation } from './presentation';
-/**
- * Keep the chip inside the message column. A default grid track sizes to
- * min-content, so a streaming thought, path, or unbreakable token can grow
- * the chip past the chat edge — the reply is still in the DOM, just off
- * screen, which looks like the agent never answered.
- */
-const CHIP_BOUNDS = 'w-full min-w-0 max-w-full overflow-x-hidden';
-const CHIP_STACK = `grid ${CHIP_BOUNDS} grid-cols-[minmax(0,1fr)] gap-1`;
-
-function working(presentation: MagicChipPresentation) {
- return presentation.kind === 'working' ? presentation : undefined;
+function answerMarkdown(presentation: MagicChipPresentation) {
+ return presentation.kind === 'working' ? undefined : presentation.markdown;
}
-function answering(presentation: MagicChipPresentation) {
- return presentation.kind === 'answering' ? presentation : undefined;
+function currentActivity(presentation: MagicChipPresentation) {
+ return presentation.kind === 'settled' ? undefined : presentation.activity;
}
-function settled(presentation: MagicChipPresentation) {
- return presentation.kind === 'settled' ? presentation : undefined;
+function replyPreview(activity: MagicChipActivity | undefined) {
+ if (!activity) return 'Open session';
+ return `${activity.label}${activity.detail ? ` ${activity.detail}` : ''}`;
}
-/** Fixed-height activity line — no box, just a shimmering label in the flow. */
-const ActivityLine: Component<{
- agentSessionId: string;
- activity: MagicChipActivity;
- onOpen?: () => void;
-}> = (props) => (
- <button
- type="button"
- class={`flex h-6 ${CHIP_BOUNDS} items-center gap-2 text-left`}
- data-magic-chip={props.agentSessionId}
- data-message-reply-preview={`${props.activity.label}${
- props.activity.detail ? ` ${props.activity.detail}` : ''
- }`}
- disabled={!props.onOpen}
- onMouseDown={(event) => event.preventDefault()}
- onClick={props.onOpen}
- >
+/** The shimmering label plus its muted detail. */
+const ActivityText: Component<{ activity: MagicChipActivity }> = (props) => (
+ <>
<span
- class="shrink-0 text-xs font-semibold"
+ class="shrink-0"
classList={{
'magic-chip-shimmer': props.activity.busy,
'text-ink-muted': !props.activity.busy,
@@ -56,105 +38,171 @@ const ActivityLine: Component<{
</span>
<Show when={props.activity.detail}>
{(detail) => (
- <span class="min-w-0 flex-1 truncate text-xs text-ink-extra-muted">
- {detail()}
- </span>
+ <>
+ <span aria-hidden="true" class="shrink-0 text-ink-placeholder">
+ ·
+ </span>
+ <span
+ class="min-w-0 flex-1 truncate text-ink-extra-muted"
+ title={detail()}
+ >
+ {detail()}
+ </span>
+ </>
)}
</Show>
- </button>
+ </>
);
-/** The response, quoted as if the agent had answered inline. */
-const AnswerBody: Component<{ markdown: string }> = (props) => (
+/**
+ * Holds the answer's space until the agent writes: the chat's own waiting
+ * glyph, pulsing while the agent is busy and still while it is not (a
+ * disconnected session, a turn that ended without prose).
+ */
+const AnswerPending: Component<{ busy: boolean }> = (props) => (
<div
- class={`${CHIP_BOUNDS} wrap-break-word border-l-2 border-accent pl-3 text-left text-sm leading-6`}
- data-message-reply-preview
+ class="flex h-full items-center justify-center"
+ data-magic-chip-pending
+ aria-hidden="true"
>
- <StaticMarkdownContext theme={channelTheme}>
- <StaticMarkdown markdown={props.markdown} target="external" />
- </StaticMarkdownContext>
+ <PulsingStar kind="streamIndicator" animate={props.busy} />
</div>
);
/**
- * The answer as it is being written, with the activity line beneath it.
- *
- * The same quoted body the settled state uses, so the turn ending changes
- * only what is under the answer, not the answer itself — no reflow at the
- * moment the agent stops.
+ * The answer: clipped to the fixed answer area with a fade while collapsed,
+ * whole once expanded.
*/
-const StreamingAnswer: Component<{
- agentSessionId: string;
- markdown: string;
- activity: MagicChipActivity;
- onOpen?: () => void;
-}> = (props) => (
- <div class={CHIP_STACK} data-magic-chip={props.agentSessionId}>
- <AnswerBody markdown={props.markdown} />
- <div class={`${CHIP_BOUNDS} pl-3`}>
- <ActivityLine
- agentSessionId={props.agentSessionId}
- activity={props.activity}
- onOpen={props.onOpen}
- />
+const AnswerBody: Component<{ markdown: string; expanded: boolean }> = (
+ props
+) => (
+ <div
+ class="relative"
+ classList={{ 'h-full overflow-hidden': !props.expanded }}
+ data-magic-chip-clip
+ >
+ <div
+ class="pointer-events-none min-w-0 max-w-full wrap-break-word"
+ data-message-reply-preview
+ >
+ <StaticMarkdownContext theme={channelTheme}>
+ <StaticMarkdown markdown={props.markdown} target="external" />
+ </StaticMarkdownContext>
</div>
+ <Show
+ when={props.expanded}
+ fallback={
+ <>
+ <div
+ class="pointer-events-none absolute inset-x-0 top-1/2 bottom-0 bg-linear-to-b from-transparent via-surface/80 to-surface group-hover/answer:via-hover/80 group-hover/answer:to-hover"
+ data-magic-chip-fade
+ />
+ <ExpandHint expanded={false} />
+ </>
+ }
+ >
+ <ExpandHint expanded />
+ </Show>
</div>
);
-/** The settled response, quoted as if the agent had answered inline. */
-const SettledAnswer: Component<{
- agentSessionId: string;
- markdown: string;
- onOpen?: () => void;
-}> = (props) => (
- <div class={CHIP_STACK} data-magic-chip={props.agentSessionId}>
- <AnswerBody markdown={props.markdown} />
- <button
- type="button"
- class="pl-3.5 mb-2 text-xs text-ink-extra-muted hover:text-ink"
- onMouseDown={(event) => event.preventDefault()}
- onClick={props.onOpen}
- disabled={!props.onOpen}
- >
- Open session
- </button>
- </div>
+/**
+ * The disclosure cue: `Show more` over the fade, `Show less` under the text.
+ * The collapsed cue steps aside while the area is hovered so it never sits
+ * on top of the text the hover is inviting you to read.
+ */
+const ExpandHint: Component<{ expanded: boolean }> = (props) => (
+ <span
+ class="pointer-events-none flex items-center gap-1 text-xs text-ink-extra-muted transition-opacity motion-reduce:transition-none"
+ classList={{
+ 'absolute right-0 bottom-0 pb-0.5 group-hover/answer:opacity-0':
+ !props.expanded,
+ 'pt-1 pb-0.5': props.expanded,
+ }}
+ aria-hidden="true"
+ >
+ <CaretRight
+ class="size-3 shrink-0 transition-transform motion-reduce:transition-none"
+ classList={{ 'rotate-90': props.expanded }}
+ />
+ {props.expanded ? 'Show less' : 'Show more'}
+ </span>
);
-/** Render an already-derived Magic Chip presentation. */
+/**
+ * One card for the whole turn: the answer area is reserved from the first
+ * moment (a pulsing star while the agent works, the opening of the answer
+ * once it writes) so the thread never jumps, and the bottom row reads the
+ * current activity or `Open session`. Clicking the answer expands it in
+ * place; clicking the row opens the session.
+ */
export const MagicChipView: Component<{
agentSessionId: string;
presentation: MagicChipPresentation;
onOpen?: () => void;
-}> = (props) => (
- <Switch>
- <Match when={working(props.presentation)}>
- {(presentation) => (
- <ActivityLine
- agentSessionId={props.agentSessionId}
- activity={presentation().activity}
- onOpen={props.onOpen}
- />
- )}
- </Match>
- <Match when={answering(props.presentation)}>
- {(presentation) => (
- <StreamingAnswer
- agentSessionId={props.agentSessionId}
- markdown={presentation().markdown}
- activity={presentation().activity}
- onOpen={props.onOpen}
- />
- )}
- </Match>
- <Match when={settled(props.presentation)}>
- {(presentation) => (
- <SettledAnswer
- agentSessionId={props.agentSessionId}
- markdown={presentation().markdown}
- onOpen={props.onOpen}
- />
- )}
- </Match>
- </Switch>
-);
+}> = (props) => {
+ const markdown = () => answerMarkdown(props.presentation);
+ const activity = () => currentActivity(props.presentation);
+ const [expanded, setExpanded] = createSignal(false);
+
+ // Before there is an answer there is nothing to expand, so the whole card
+ // leads to the session.
+ const onAnswerClick = () => {
+ if (markdown()) setExpanded((open) => !open);
+ else props.onOpen?.();
+ };
+
+ return (
+ <Layer depth={2}>
+ <div
+ class="my-2 w-full min-w-0 max-w-full overflow-hidden rounded-lg border border-edge-muted bg-surface"
+ data-magic-chip={props.agentSessionId}
+ data-magic-chip-preview
+ onMouseDown={(event) => event.preventDefault()}
+ >
+ <div
+ role="button"
+ tabIndex={0}
+ aria-expanded={markdown() ? expanded() : undefined}
+ class="group/answer px-3 py-1 text-left hover:bg-hover"
+ classList={{ 'h-22': !expanded() }}
+ data-magic-chip-answer
+ onClick={onAnswerClick}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ onAnswerClick();
+ }}
+ >
+ <Show
+ when={markdown()}
+ fallback={<AnswerPending busy={activity()?.busy ?? false} />}
+ >
+ {(answer) => (
+ <AnswerBody markdown={answer()} expanded={expanded()} />
+ )}
+ </Show>
+ </div>
+ <button
+ type="button"
+ class="flex min-h-9 w-full items-center gap-1.5 border-t border-edge-muted px-3 py-2 text-left text-xs leading-5 text-ink-extra-muted hover:bg-hover"
+ data-message-reply-preview={
+ markdown() ? undefined : replyPreview(activity())
+ }
+ disabled={!props.onOpen}
+ onClick={props.onOpen}
+ >
+ <span class="flex min-w-0 flex-1 items-center gap-1.5">
+ <Show
+ when={activity()}
+ fallback={<span class="text-ink-muted">Open session</span>}
+ >
+ {(current) => <ActivityText activity={current()} />}
+ </Show>
+ </span>
+ <ArrowUpRight aria-hidden="true" class="size-3 shrink-0" />
+ </button>
+ </div>
+ </Layer>
+ );
+};
diff --git a/apps/web/src/lib/queries/agent-session/session-fold.test.ts b/apps/web/src/lib/queries/agent-session/session-fold.test.ts
index 7095301038..7dced3738c 100644
--- a/apps/web/src/lib/queries/agent-session/session-fold.test.ts
+++ b/apps/web/src/lib/queries/agent-session/session-fold.test.ts
@@ -78,6 +78,36 @@ describe('buffer overlap', () => {
).toEqual([]);
expect(dropOverlap([frame(1)], [frame(1), frame(1)])).toEqual([frame(1)]);
});
+
+ it('matches one entry whose object keys came back in another order', () => {
+ // The persisted log is read from jsonb, which reorders keys; the
+ // realtime frame for the same row keeps the runtime's order.
+ const stored = {
+ createdAt: '2026-08-13T00:00:05Z',
+ direction: 'to_server',
+ content: {
+ type: 'acp',
+ jsonrpc: '2.0',
+ id: 5,
+ method: 'session/prompt',
+ params: { prompt: [{ text: 'hi', type: 'text' }], sessionId: 's' },
+ },
+ } as unknown as AgentSessionLogEntryDto;
+ const live = {
+ content: {
+ jsonrpc: '2.0',
+ id: 5,
+ method: 'session/prompt',
+ params: { sessionId: 's', prompt: [{ type: 'text', text: 'hi' }] },
+ type: 'acp',
+ },
+ direction: 'to_server',
+ createdAt: '2026-08-13T00:00:05Z',
+ } as unknown as AgentSessionLogEntryDto;
+
+ expect(JSON.stringify(stored)).not.toBe(JSON.stringify(live));
+ expect(dropOverlap([stored], [live])).toEqual([]);
+ });
});
describe('shared session folds', () => {
@@ -110,6 +140,26 @@ describe('shared session folds', () => {
(await acquired).release();
});
+ it('skips a late realtime frame the fetched log already held', async () => {
+ harness.getLog.mockResolvedValue(
+ ok({ bot, entries: [frame(1), frame(2)] })
+ );
+ const acquired = await acquireAgentSessionFold({
+ agentSessionId: 'session-a',
+ });
+
+ // The gateway delivers the second row after the HTTP fetch returned it.
+ handleAgentSessionLog(event('session-a', 2));
+ handleAgentSessionLog(event('session-a', 3));
+ await Promise.resolve();
+
+ expect(fold.pushSessionEntries).toHaveBeenCalledTimes(1);
+ expect(fold.pushSessionEntries).toHaveBeenCalledWith('session-a', [
+ frame(3),
+ ]);
+ acquired.release();
+ });
+
it('isolates raw and folded events by session', async () => {
const raw: string[] = [];
const changed: FoldedMessage[][] = [];
diff --git a/apps/web/src/lib/queries/agent-session/session-fold.ts b/apps/web/src/lib/queries/agent-session/session-fold.ts
index 8b872797be..8241a3ec84 100644
--- a/apps/web/src/lib/queries/agent-session/session-fold.ts
+++ b/apps/web/src/lib/queries/agent-session/session-fold.ts
@@ -31,6 +31,8 @@ type SessionState = {
foldedSinks: Set<FoldedMessageSink>;
metadataSinks: Set<SessionMetadataSink>;
opening?: Promise<void>;
+ /** Drops realtime frames the fetched log already contained. */
+ overlap?: OverlapFilter;
ready: boolean;
references: number;
};
@@ -127,17 +129,16 @@ async function open(state: SessionState): Promise<void> {
}
state.bot = result.value.bot;
+ state.overlap = createOverlapFilter(result.value.entries);
await openSession(state.agentSessionId, result.value.entries);
machineOpen = true;
// Frames can continue arriving while each worker request is in flight.
// Drain until an empty check and `ready` assignment can happen together.
- let fetched = result.value.entries;
while (state.buffered.length > 0) {
const buffered = state.buffered;
state.buffered = [];
- const replay = dropOverlap(fetched, buffered);
- fetched = [];
+ const replay = state.overlap(buffered);
if (replay.length > 0) await push(state, replay);
}
state.ready = true;
@@ -172,7 +173,11 @@ export function handleAgentSessionLog(event: AgentSessionLogEvent): void {
state.buffered.push(entry);
return;
}
- void push(state, [entry]).catch((error: unknown) => {
+ // The gateway can deliver a frame after the HTTP log that already held it
+ // was fetched; folding it again would open a second turn for one prompt.
+ const fresh = state.overlap?.([entry]) ?? [entry];
+ if (fresh.length === 0) return;
+ void push(state, fresh).catch((error: unknown) => {
console.error('[agent-fold] live frame could not be folded', error);
});
}
@@ -195,24 +200,62 @@ async function push(
for (const sink of state.foldedSinks) sink(messages);
}
+type OverlapFilter = (
+ entries: AgentSessionLogEntryDto[]
+) => AgentSessionLogEntryDto[];
+
+/**
+ * A key under which the same log row compares equal however it travelled.
+ *
+ * The fetched log comes out of a jsonb column, which stores object keys in
+ * its own order; realtime frames are serialized from memory in insertion
+ * order. `JSON.stringify` therefore differs for one and the same entry, so
+ * keys are sorted before comparing.
+ */
+function canonical(value: unknown): string {
+ return JSON.stringify(value, (_key, inner: unknown) => {
+ if (!inner || typeof inner !== 'object' || Array.isArray(inner)) {
+ return inner;
+ }
+ return Object.fromEntries(
+ Object.entries(inner as Record<string, unknown>).sort(([a], [b]) =>
+ a < b ? -1 : a > b ? 1 : 0
+ )
+ );
+ });
+}
+
+/**
+ * Build a filter that drops each fetched occurrence once, so realtime frames
+ * that duplicate the snapshot are skipped whenever they arrive, while a
+ * genuinely new frame with the same content later still passes.
+ */
+export function createOverlapFilter(
+ fetched: AgentSessionLogEntryDto[]
+): OverlapFilter {
+ const remaining = new Map<string, number>();
+ for (const entry of fetched) {
+ const key = canonical(entry);
+ remaining.set(key, (remaining.get(key) ?? 0) + 1);
+ }
+
+ return (entries) => {
+ if (remaining.size === 0) return entries;
+ return entries.filter((entry) => {
+ const key = canonical(entry);
+ const count = remaining.get(key);
+ if (!count) return true;
+ if (count === 1) remaining.delete(key);
+ else remaining.set(key, count - 1);
+ return false;
+ });
+ };
+}
+
/** Return buffered frame occurrences not already present in the snapshot. */
export function dropOverlap(
fetched: AgentSessionLogEntryDto[],
buffered: AgentSessionLogEntryDto[]
): AgentSessionLogEntryDto[] {
- if (buffered.length === 0 || fetched.length === 0) return buffered;
-
- const fetchedCounts = new Map<string, number>();
- for (const entry of fetched) {
- const key = JSON.stringify(entry);
- fetchedCounts.set(key, (fetchedCounts.get(key) ?? 0) + 1);
- }
-
- return buffered.filter((entry) => {
- const key = JSON.stringify(entry);
- const remaining = fetchedCounts.get(key) ?? 0;
- if (remaining === 0) return true;
- fetchedCounts.set(key, remaining - 1);
- return false;
- });
+ return createOverlapFilter(fetched)(buffered);
}
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 7d8e39e024..458e0b8156 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -43,6 +43,14 @@ own time zone (their primary calendar's), so it resolves relative times ("tomorr
bot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cursor` open
an agent session; follow-up
`@` mentions of that bot in the same thread route to it.
+The reply renders a Magic Chip: a rounded card of constant height that is present
+from the moment the session boots. Its answer area shows a pulsing star while the
+agent works, then the opening of the answer clipped to four lines and faded out; its
+bottom row reads the current activity (`Booting agent`, `Writing response`, ...) and
+`Open session` once the turn ends. A `Show more` cue sits over the fade: click the
+answer text to expand it in place (`Show less` collapses it again); click the
+bottom row to open the agent session. Before an
+answer exists, clicking the answer area also opens the session.
Agent replies may contain mention chips (`<m-document-mention>`) that render like any
other channel mention.
The Magic Chip that streams the agent's reply stays inside the message column: long