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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/sdk-typescript/src/daemon/ui/transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,10 @@ function applyDaemonTranscriptEvent(
break;
case 'status':
case 'debug':
appendStatusBlock(next, event.type, event.text, event, {
clearActiveText: event.clearActiveText,
});
break;
case 'error':
appendStatusBlock(next, event.type, event.text, event);
break;
Expand Down
7 changes: 7 additions & 0 deletions packages/sdk-typescript/src/daemon/ui/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,13 @@ export interface DaemonUiStatusEvent extends DaemonUiEventBase {
text: string;
source?: string;
data?: unknown;
/**
* Client-dispatch opt-out: `false` inserts the status block without
* finalizing the active assistant/thought block, so read-only command
* output dispatched mid-turn does not split a streaming answer or orphan
* its usage frames. Daemon-emitted events leave this unset.
*/
clearActiveText?: boolean;
}

export interface DaemonUiErrorEvent extends DaemonUiEventBase {
Expand Down
55 changes: 55 additions & 0 deletions packages/sdk-typescript/test/daemon-ui-transcript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,58 @@ describe('daemon transcript rewind', () => {
expect(state.activeAssistantBlockId).toBeUndefined();
});
});

describe('status event while an assistant block is streaming', () => {
it('finalizes the active assistant block by default', () => {
const state = reduceDaemonTranscriptEvents(
createDaemonTranscriptState({ now: 1 }),
[
{ type: 'user.text.delta', text: 'question' },
{ type: 'assistant.text.delta', text: 'answering' },
{ type: 'status', text: 'mid-stream status' },
{ type: 'assistant.text.delta', text: ' more' },
{ type: 'assistant.done' },
],
{ now: 1 },
);

expect(state.blocks.map((block) => block.kind)).toEqual([
'user',
'assistant',
'status',
'assistant',
]);
});

it('keeps the assistant block active when clearActiveText is false', () => {
const state = reduceDaemonTranscriptEvents(
createDaemonTranscriptState({ now: 1 }),
[
{ type: 'user.text.delta', text: 'question' },
{ type: 'assistant.text.delta', text: 'answering' },
{ type: 'status', text: 'mid-stream status', clearActiveText: false },
{ type: 'assistant.text.delta', text: ' more' },
{
type: 'assistant.usage',
usage: { inputTokens: 3, outputTokens: 5 },
},
{ type: 'assistant.done' },
],
{ now: 1 },
);

expect(state.blocks.map((block) => block.kind)).toEqual([
'user',
'assistant',
'status',
]);
const assistant = state.blocks[1];
if (assistant.kind !== 'assistant') throw new Error('expected assistant');
expect(assistant.text).toBe('answering more');
expect(assistant.usage).toEqual({
inputTokens: 3,
outputTokens: 5,
cachedTokens: 0,
});
});
});
80 changes: 80 additions & 0 deletions packages/web-shell/client/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3821,6 +3821,86 @@ describe('App shell command queueing', () => {
});
});

describe('App read-only local commands mid-turn', () => {
it('runs /stats immediately while streaming and skips the echo', async () => {
const { rerender } = renderApp({});
await flush();

act(() => {
testState.streamingState = 'responding';
rerender({});
});

let accepted: boolean | void;
await act(async () => {
accepted = testState.latestChatEditorProps?.onSubmit('/stats');
await vi.waitFor(() => {
expect(mockSessionActions.getStats).toHaveBeenCalled();
});
});

expect(accepted).toBe(true);
expect(mockStore.appendLocalUserMessage).not.toHaveBeenCalled();
expect(mockStore.dispatch).toHaveBeenCalledWith([
expect.objectContaining({ type: 'status', clearActiveText: false }),
]);
});

it('echoes /stats when idle', async () => {
renderApp({});
await flush();

let accepted: boolean | void;
await act(async () => {
accepted = testState.latestChatEditorProps?.onSubmit('/stats');
await vi.waitFor(() => {
expect(mockSessionActions.getStats).toHaveBeenCalled();
});
});

expect(accepted).toBe(true);
expect(mockStore.appendLocalUserMessage).toHaveBeenCalledWith('/stats');
});

it('runs /about immediately while streaming and skips the echo', async () => {
const { rerender } = renderApp({});
await flush();

act(() => {
testState.streamingState = 'responding';
rerender({});
});

let accepted: boolean | void;
await act(async () => {
accepted = testState.latestChatEditorProps?.onSubmit('/about');
await vi.waitFor(() => {
expect(mockWorkspaceActions.loadPreflight).toHaveBeenCalled();
});
});

expect(accepted).toBe(true);
expect(mockStore.appendLocalUserMessage).not.toHaveBeenCalled();
expect(mockStore.dispatch).toHaveBeenCalledWith([
expect.objectContaining({ type: 'status', clearActiveText: false }),
]);
});

it('echoes /about when idle', async () => {
renderApp({});
await flush();

await act(async () => {
testState.latestChatEditorProps?.onSubmit('/about');
await vi.waitFor(() => {
expect(mockWorkspaceActions.loadPreflight).toHaveBeenCalled();
});
});

expect(mockStore.appendLocalUserMessage).toHaveBeenCalledWith('/about');
});
});

describe('App session callbacks', () => {
it('binds the main composer Voice target to its active secondary session', async () => {
mockConnection.workspaceCwd = '/work/secondary';
Expand Down
49 changes: 40 additions & 9 deletions packages/web-shell/client/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,10 @@ import {
encodeVisionModelForSetting,
extractBareModelId,
} from './utils/modelEncoding';
import { appendOrDeferLocalUserMessage } from './utils/localCommandQueue';
import {
appendLocalUserEchoIfIdle,
appendOrDeferLocalUserMessage,
} from './utils/localCommandQueue';
import { QueuedPromptDisplay } from './components/QueuedPromptDisplay';
import { useQueuedPrompts } from './hooks/useQueuedPrompts';
import { useNewSessionSuggestion } from './hooks/useNewSessionSuggestion';
Expand Down Expand Up @@ -5003,6 +5006,21 @@ export function App({
[store],
);

// Echo a local command when idle, but never block it. Read-only display
// commands (/stats, /about, /context) render their result as a status
// block, which does not split the active turn, so they run immediately
// mid-turn with only the echo skipped (see appendLocalUserEchoIfIdle).
// Their result dispatch must pass `clearActiveText: false`, otherwise the
// status block would finalize the in-flight assistant block mid-stream.
const echoLocalCommandIfIdle = useCallback(
(text: string): void => {
appendLocalUserEchoIfIdle(streamingStateRef.current !== 'idle', text, {
append: (value: string) => store.appendLocalUserMessage(value),
});
Comment thread
wenshao marked this conversation as resolved.
Resolved
},
[store],
);

const blockLocalCommandDuringTurn = useCallback((): false => {
pushToast('error', t('queue.commandBlocked'));
return false;
Expand Down Expand Up @@ -5865,17 +5883,20 @@ export function App({
// is revealed even when the click comes while scrolled up.
const showContextUsage = useCallback(
(commandText: string, detail: boolean) => {
// Self-guard so every entry point (keyboard, status-bar button, in-chat
// "context detail" click) defers mid-turn instead of splitting the turn.
// Read-only: every entry point (keyboard, status-bar button, in-chat
// "context detail" click) runs immediately, even mid-turn — only the
// echo is skipped while streaming so the active turn is not split.
if (!requireActiveSessionForLocalCommand()) return;
if (echoOrDeferLocalCommand(commandText)) return;
echoLocalCommandIfIdle(commandText);
sessionActions
.getContextUsage({ detail })
.then((result) => {
store.dispatch([
{
type: 'status',
text: serializeContextUsageMessage(result),
// Mid-turn runs must not finalize the streaming block.
clearActiveText: false,
},
]);
resumeChatBottomFollow('smooth');
Expand All @@ -5885,7 +5906,7 @@ export function App({
});
},
[
echoOrDeferLocalCommand,
echoLocalCommandIfIdle,
store,
requireActiveSessionForLocalCommand,
sessionActions,
Expand Down Expand Up @@ -7561,23 +7582,27 @@ export function App({
if (statsArg === 'model') statsView = 'model';
else if (statsArg === 'tools') statsView = 'tools';
if (!requireActiveSessionForLocalCommand()) return false;
if (echoOrDeferLocalCommand(text, images)) return true;
echoLocalCommandIfIdle(text);
sessionActions
Comment thread
wenshao marked this conversation as resolved.
Resolved
.getStats()
.then((result) => {
store.dispatch([
{
type: 'status',
text: serializeStatsMessage(result, statsView),
// Mid-turn runs must not finalize the streaming block.
clearActiveText: false,
},
]);
resumeChatBottomFollow('smooth');
})
.catch(() => {});
.catch((error: unknown) => {
reportError(error, 'Failed to load stats');
});
return true;
}
if (cmd === 'status' || cmd === 'about') {
if (echoOrDeferLocalCommand(text, images)) return true;
echoLocalCommandIfIdle(text);
Promise.all([
workspaceActions.loadPreflight().catch(() => null),
Comment on lines +7624 to 7626

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The /about handler's Promise.all(...).then(...) chain has no .catch(), while the adjacent /stats handler was explicitly updated in this same diff to use reportError. — Concrete cost: if serializeStatusMessage, store.dispatch, or resumeChatBottomFollow throws synchronously inside the .then() callback, the rejection is unhandled — no error toast, no console diagnostic, silent failure. The /about path is the lone outlier among the three read-only display commands after this diff.

Append .catch((error: unknown) => { reportError(error, 'Failed to load status info'); }) to the Promise chain, matching /stats and /context.

中文说明

/about 处理器的 Promise.all(...).then(...) 链缺少 .catch(),而相邻的 /stats 处理器在本 diff 中已显式更新为使用 reportError。— 具体代价:如果 .then() 回调内的 serializeStatusMessage、store.dispatch 或 resumeChatBottomFollow 同步抛出异常,该 rejection 将无人处理——没有错误 toast、没有控制台诊断信息,静默失败。本 diff 后 /about 是三个只读显示命令中唯一的遗漏。

在 Promise 链末尾追加 .catch((error: unknown) => { reportError(error, 'Failed to load status info'); }),与 /stats 和 /context 保持一致。

— claude-opus-4-6 via Qwen Code /review (v0.21.5)

workspaceActions.loadProviders().catch(() => null),
Expand Down Expand Up @@ -7635,7 +7660,12 @@ export function App({
};

store.dispatch([
{ type: 'status', text: serializeStatusMessage(info) },
{
type: 'status',
text: serializeStatusMessage(info),
// Mid-turn runs must not finalize the streaming block.
clearActiveText: false,
},
]);
resumeChatBottomFollow('smooth');
});
Expand Down Expand Up @@ -7780,6 +7810,7 @@ export function App({
store,
enqueuePrompt,
echoOrDeferLocalCommand,
echoLocalCommandIfIdle,
branchCurrentSession,
closeMobileDrawer,
closePanel,
Expand Down
21 changes: 21 additions & 0 deletions packages/web-shell/client/utils/localCommandQueue.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import {
appendLocalUserEchoIfIdle,
appendOrDeferLocalUserMessage,
isCommandPrompt,
} from './localCommandQueue';
Expand Down Expand Up @@ -53,6 +54,26 @@ describe('appendOrDeferLocalUserMessage', () => {
});
});

describe('appendLocalUserEchoIfIdle', () => {
it('appends and returns true when no turn is streaming', () => {
const append = vi.fn();

const appended = appendLocalUserEchoIfIdle(false, '/stats', { append });

expect(appended).toBe(true);
expect(append).toHaveBeenCalledExactlyOnceWith('/stats');
});

it('skips the echo but returns false without blocking while streaming', () => {
const append = vi.fn();

const appended = appendLocalUserEchoIfIdle(true, '/about', { append });

expect(appended).toBe(false);
expect(append).not.toHaveBeenCalled();
});
});

describe('isCommandPrompt', () => {
it('treats slash and shell prefixes as commands', () => {
expect(isCommandPrompt('/context detail')).toBe(true);
Expand Down
28 changes: 27 additions & 1 deletion packages/web-shell/client/utils/localCommandQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ import type { PromptImage } from '../adapters/promptTypes';
*
* The only call sites that should bypass this and append mid-stream are the
* deliberate "busy acknowledgement" paths (e.g. clearing a goal while a turn
* runs), which opt in by calling `append` directly.
* runs), which opt in by calling `append` directly. Read-only display
* commands (/stats, /about, /context) use `appendLocalUserEchoIfIdle`
* instead: they skip the echo mid-turn and still run immediately.
*/
export interface LocalEchoSink {
/** Append the command as a local user message (renders inline immediately). */
Expand All @@ -44,6 +46,30 @@ export function appendOrDeferLocalUserMessage(
return false;
}

/**
* Append a local command's echo when idle, skipping it while a turn is
* streaming — without ever blocking the command itself.
*
* Read-only display commands render their result as a status block, which is
* not a turn boundary in `applyTurnCollapse`, so they can run mid-turn; only
* the user echo row would split the active turn. Skipping the echo also
* avoids `appendLocalUserTranscriptMessage` finalizing the in-flight
* assistant block mid-stream — and the command's result dispatch must pass
* `clearActiveText: false` for the same reason.
*
* Delegates to `appendOrDeferLocalUserMessage` so the idle gate lives in one
* place; note the inverted polarity — here `true` means "echo appended".
*
* @returns `true` if the echo was appended, `false` if it was skipped.
*/
export function appendLocalUserEchoIfIdle(
isStreaming: boolean,
text: string,
sink: LocalEchoSink,
): boolean {
Comment thread
wenshao marked this conversation as resolved.
Resolved
return !appendOrDeferLocalUserMessage(isStreaming, text, undefined, sink);
}

/**
* Whether a queued prompt is a slash (`/…`) or shell (`!…`) command rather than
* model-facing prose.
Expand Down
Loading