ui (subagent): Show subagent session link and make subagent sessions view-only (#12998)

This commit is contained in:
Lifei Zhou
2026-10-19 23:17:47 +00:00
committed by GitHub
parent 0742c80deb
commit 75e13d7ba8
32 changed files with 551 additions and 138 deletions
+2 -2
View File
@@ -92,7 +92,7 @@ use self::message_meta::{
use self::tool_calls::chain::{breaks_consecutive_tool_calls, ReadyToolChain, ToolChainTracker};
use self::tool_calls::conversion::{
build_initial_tool_call_with_message_meta, build_permission_tool_call_update,
tool_call_update_fields_from_response, trusted_update_meta,
tool_call_update_fields_from_response, tool_response_meta,
};
use self::tool_calls::enrichment::{spawn_chain_summary_enrichment, spawn_tool_title_enrichment};
@@ -1540,7 +1540,7 @@ impl GooseAcpAgent {
let fields = tool_call_update_fields_from_response(tool_response, tool_request, false);
let update = ToolCallUpdate::new(ToolCallId::new(tool_response.id.clone()), fields)
.meta(trusted_update_meta(tool_response));
.meta(tool_response_meta(tool_response));
let tool_call_notifier = ToolCallNotifier::new(cx, session_id);
tool_call_notifier.send_update(update)?;
+15 -21
View File
@@ -3,7 +3,7 @@ use super::message_meta::{
};
use super::tool_calls::conversion::{
build_initial_tool_call_with_message_meta, tool_call_update_fields_from_response,
trusted_update_meta,
tool_response_meta,
};
use super::tool_calls::enrichment::tool_chain_summary;
use super::*;
@@ -172,7 +172,7 @@ fn replay_conversation_to_client(
replay_tool_requests.get(&tool_response.id),
true,
);
let meta = trusted_update_meta(tool_response).unwrap_or_default();
let meta = tool_response_meta(tool_response).unwrap_or_default();
let update =
ToolCallUpdate::new(ToolCallId::new(tool_response.id.clone()), fields)
@@ -411,6 +411,16 @@ impl GooseAcpAgent {
self.requests_tool_call_label_enrichment(),
replay_tail_from_meta(args.meta.as_ref()),
)?;
let pending_confirmations = session
.conversation
.as_ref()
.map(pending_tool_confirmations)
.unwrap_or_default();
let awaiting_confirmation = !pending_confirmations.is_empty()
|| session
.conversation
.as_ref()
.is_some_and(has_unapplied_tool_confirmation_response);
let (agent, extension_results) = self.prepare_acp_session_agent(cx, &session).await?;
self.register_acp_session(session_id_str.clone(), agent.clone())
.await;
@@ -446,17 +456,9 @@ impl GooseAcpAgent {
}
response = response.meta(meta);
let pending_confirmations = session
.conversation
.as_ref()
.map(pending_tool_confirmations)
.unwrap_or_default();
let should_resume_state_machine = !pending_confirmations.is_empty()
|| session
.conversation
.as_ref()
.is_some_and(has_unapplied_tool_confirmation_response);
if should_resume_state_machine {
let is_subagent = session.session_type == SessionType::SubAgent;
let already_running = self.active_runs.agent_run(&session_id_str).is_some();
if awaiting_confirmation && !is_subagent && !already_running {
self.start_resumed_state_machine_turn(
cx,
&agent,
@@ -464,14 +466,6 @@ impl GooseAcpAgent {
&pending_confirmations,
)
.await?;
} else {
self.resend_pending_tool_permissions(
cx,
&agent,
&session_id_str,
&pending_confirmations,
None,
)?;
}
self.closed_session_ids.lock().await.remove(&session_id_str);
@@ -213,16 +213,29 @@ fn extract_tool_locations_from_request(tool_request: &ToolRequest) -> Vec<ToolCa
vec![ToolCallLocation::new(path).line(line)]
}
pub(crate) fn trusted_update_meta(tool_response: &ToolResponse) -> Option<Meta> {
pub(crate) fn tool_response_meta(tool_response: &ToolResponse) -> Option<Meta> {
let tool_result = tool_response.tool_result.as_ref().ok()?;
let goose_meta = tool_result
.meta
.as_ref()?
let result_meta = tool_result.meta.as_ref()?;
let mut goose_meta = result_meta
.0
.get(TRUSTED_TOOL_UPDATE_META_KEY)?
.clone();
.get(TRUSTED_TOOL_UPDATE_META_KEY)
.and_then(serde_json::Value::as_object)
.cloned()
.unwrap_or_default();
if let Some(subagent_id) = result_meta
.0
.get("subagent_session_id")
.and_then(serde_json::Value::as_str)
{
goose_meta.insert("subagentSessionId".to_string(), subagent_id.into());
}
if goose_meta.is_empty() {
return None;
}
let mut meta_map = serde_json::Map::new();
meta_map.insert("goose".to_string(), goose_meta);
meta_map.insert("goose".to_string(), serde_json::Value::Object(goose_meta));
Some(meta_map)
}
@@ -720,9 +733,24 @@ mod tests {
.map(|locs| locs.into_iter().map(|loc| (loc.path, loc.line)).collect())
}
mod trusted_update_meta {
mod tool_response_meta {
use super::*;
#[test]
fn forwards_subagent_session_id() {
let response = response_with_meta(Some(serde_json::json!({
"subagent_session_id": "child-session",
"foreground_subagent": true,
"unrelated": "not forwarded",
})));
let meta = tool_response_meta(&response).expect("expected subagent metadata");
assert_eq!(
serde_json::Value::Object(meta),
serde_json::json!({"goose": {"subagentSessionId": "child-session"}}),
);
}
#[test]
fn ignores_untrusted_goose_meta() {
let response = response_with_meta(Some(serde_json::json!({
@@ -733,12 +761,13 @@ mod tests {
},
})));
assert_eq!(trusted_update_meta(&response), None);
assert_eq!(tool_response_meta(&response), None);
}
#[test]
fn uses_trusted_meta_only() {
fn preserves_trusted_app_meta_alongside_subagent_session() {
let response = response_with_meta(Some(serde_json::json!({
"subagent_session_id": "child-session",
"goose": {
"mcpApp": {
"resourceUri": "ui://spoofed/app",
@@ -753,10 +782,11 @@ mod tests {
},
})));
let extracted = trusted_update_meta(&response).expect("expected trusted meta");
let extracted = tool_response_meta(&response).expect("expected trusted meta");
assert_eq!(
extracted.get("goose"),
Some(&serde_json::json!({
"subagentSessionId": "child-session",
"mcpApp": {
"resourceUri": "ui://trusted/app",
"extensionName": "weather",
@@ -23,9 +23,9 @@ use tracing::warn;
use super::{
get_tool_meta_value, get_tool_owner, get_tool_resource_uri, insert_trusted_tool_update_meta,
recover_mangled_tool_name, remove_untrusted_mcp_app_meta, ActionRequiredStream, Extension,
ExtensionLoadResult, ExtensionMutation, ExtensionSlot, GooseMcpAppToolAttachment,
TOOL_CALL_NOTIFICATION_CHANNEL_CAPACITY,
recover_mangled_tool_name, remove_subagent_session_meta, remove_untrusted_mcp_app_meta,
ActionRequiredStream, Extension, ExtensionLoadResult, ExtensionMutation, ExtensionSlot,
GooseMcpAppToolAttachment, TOOL_CALL_NOTIFICATION_CHANNEL_CAPACITY,
};
use crate::action_required_manager::ActionRequiredManager;
use crate::agents::container::Container;
@@ -712,6 +712,7 @@ impl ExtensionLease {
remove_untrusted_mcp_app_meta(&mut result);
if !is_platform_extension {
ExtensionMutation::take(&mut result);
remove_subagent_session_meta(&mut result);
}
if let Some(mcp_app_call) = mcp_app_call {
mcp_app_call
@@ -522,6 +522,18 @@ fn remove_untrusted_mcp_app_meta(result: &mut CallToolResult) {
}
}
fn remove_subagent_session_meta(result: &mut CallToolResult) {
let Some(meta) = result.meta.as_mut() else {
return;
};
meta.0.remove("subagent_session_id");
if meta.0.is_empty() {
result.meta = None;
}
}
fn insert_trusted_tool_update_meta(
result: &mut CallToolResult,
attachment: &GooseMcpAppToolAttachment,
@@ -1531,6 +1543,89 @@ mod tests {
}
}
struct SubagentMetaClient;
#[async_trait::async_trait]
impl McpClientTrait for SubagentMetaClient {
async fn list_tools(
&self,
_session_id: &str,
_next_cursor: Option<String>,
_cancellation_token: CancellationToken,
) -> Result<ListToolsResult, Error> {
Ok(ListToolsResult {
tools: vec![Tool::new(
"delegate".to_string(),
"test tool".to_string(),
Arc::new(serde_json::Map::new()),
)],
..Default::default()
})
}
async fn call_tool(
&self,
_ctx: &ToolCallContext,
_name: &str,
_arguments: Option<JsonObject>,
_cancellation_token: CancellationToken,
) -> Result<CallToolResult, Error> {
let meta = serde_json::json!({
"subagent_session_id": "other-session",
"unrelated": "kept",
});
Ok(CallToolResult::success(vec![])
.with_meta(Some(MetaObject(meta.as_object().unwrap().clone()))))
}
fn get_info(&self) -> Option<&InitializeResult> {
None
}
}
async fn dispatch_subagent_meta_tool(extension: &str, tool: &str) -> Option<MetaObject> {
let temp_dir = tempfile::tempdir().unwrap();
let extension_manager = Arc::new(ExtensionManager::with_data_dir(
temp_dir.path().to_path_buf(),
));
extension_manager
.add_mock_extension(extension.to_string(), Arc::new(SubagentMetaClient))
.await;
let dispatched = extension_manager
.scope_lease("session")
.await
.call(
CallToolRequestParams::new(tool.to_string()).with_arguments(object!({})),
CallRequest::from(&ToolCallContext::new("session".to_string(), None, None)),
CancellationToken::default(),
)
.await
.expect("tool call should dispatch");
dispatched.result.await.unwrap().meta
}
#[tokio::test]
async fn dispatch_strips_subagent_session_id_from_external_extensions() {
let meta = dispatch_subagent_meta_tool("external", "external__delegate").await;
assert_eq!(
meta.map(|meta| serde_json::Value::Object(meta.0)),
Some(serde_json::json!({"unrelated": "kept"})),
);
}
#[tokio::test]
async fn dispatch_keeps_subagent_session_id_from_platform_extensions() {
let meta = dispatch_subagent_meta_tool("summon", "delegate").await;
assert_eq!(
meta.and_then(|meta| meta.0.get("subagent_session_id").cloned()),
Some(serde_json::json!("other-session")),
);
}
fn app_tool(name: &str) -> Tool {
let mut tool = Tool::new(
name.to_string(),
+59
View File
@@ -836,6 +836,65 @@ fn test_load_session_replays_image_attachment() {
run_test(async { run_load_session_replays_image_attachment::<AcpServerConnection>().await });
}
async fn seed_session_awaiting_approval(data_root: &Path, session_type: SessionType) -> String {
let session_manager = SessionManager::new(data_root.to_path_buf());
let session = session_manager
.create_session(
data_root.to_path_buf(),
"Awaiting approval".to_string(),
session_type,
GooseMode::default(),
)
.await
.unwrap();
for message in [
Message::user().with_text("run the tool"),
Message::assistant().with_action_required(
"approval",
"tool".to_string(),
Default::default(),
None,
),
] {
session_manager
.add_message(&session.id, &message)
.await
.unwrap();
}
session.id
}
fn starts_a_run(updates: &[SessionUpdate]) -> bool {
updates.iter().any(|update| match update {
SessionUpdate::SessionInfoUpdate(info) => info
.meta
.as_ref()
.and_then(|meta| meta.get("goose"))
.and_then(|goose| goose.get("activeRunId"))
.is_some_and(serde_json::Value::is_string),
_ => false,
})
}
#[test]
fn test_load_session_resumes_pending_approval_except_for_subagents() {
run_test(async {
for (session_type, resumes) in [(SessionType::Acp, true), (SessionType::SubAgent, false)] {
let data_root = tempfile::tempdir().unwrap();
let session_id = seed_session_awaiting_approval(data_root.path(), session_type).await;
let mut conn = new_connection(data_root.path()).await;
let SessionData { session, .. } = conn.load_session(&session_id, vec![]).await.unwrap();
assert_eq!(
starts_a_run(&session.session_updates()),
resumes,
"{session_type:?}"
);
}
});
}
#[test]
fn test_mode_set() {
run_test(async { run_mode_set::<AcpServerConnection>().await });
@@ -411,7 +411,25 @@ describe('createAcpSessionNotificationAdapter', () => {
});
describe('tools', () => {
it('maps tool calls and successful responses, including MCP app metadata', () => {
it('preserves the subagent session ID without MCP app metadata', () => {
const adapter = createAcpSessionNotificationAdapter();
const messages = expectOnlyMessagesChange(
adapter.apply(
acpUpdate({
...DEFAULT_TOOL_CALL_UPDATE,
status: 'completed',
_meta: { goose: { subagentSessionId: 'child-session' } },
})
)
);
expect(getToolResponses(messages[0])[0].toolResult).toMatchObject({
status: 'success',
value: { _meta: { subagent_session_id: 'child-session' } },
});
});
it('maps tool calls and successful responses, preserving app and subagent metadata', () => {
const adapter = createAcpSessionNotificationAdapter();
const toolCallStateChanges = adapter.apply(
@@ -470,6 +488,7 @@ describe('createAcpSessionNotificationAdapter', () => {
],
_meta: {
goose: {
subagentSessionId: 'child-session',
mcpApp: {
resourceUri: 'ui://app/resource',
extensionName: 'developer',
@@ -493,6 +512,7 @@ describe('createAcpSessionNotificationAdapter', () => {
content: [{ type: 'text', text: 'rendered result' }],
isError: false,
_meta: {
subagent_session_id: 'child-session',
ui: { resourceUri: 'ui://app/resource' },
extensionName: 'developer',
toolName: 'read_file',
+22 -21
View File
@@ -84,7 +84,7 @@ export function applyToolCallUpdate(
status: 'success',
value: toolResultValue(
toolCallState,
mcpAppMetadata(update),
toolResultMetadata(update),
toolCallState.status === 'failed'
),
},
@@ -211,7 +211,7 @@ function baseToolMetadata(
function toolResultValue(
update: ToolCallUpdate,
mcpAppMeta: DesktopMcpAppMeta | undefined,
meta: DesktopToolResultMeta | undefined,
isError: boolean
): ToolResultValue {
const content = toolResultContent(update);
@@ -226,7 +226,7 @@ function toolResultValue(
const toolResult: ToolResultValue = {
content,
isError,
...(mcpAppMeta ? { _meta: mcpAppMeta } : {}),
...(meta ? { _meta: meta } : {}),
};
if (update.rawOutput !== undefined) {
@@ -326,47 +326,48 @@ function apiResourceContentsFromAcpResource(
};
}
interface DesktopMcpAppMeta extends Record<string, unknown> {
ui: {
interface DesktopToolResultMeta extends Record<string, unknown> {
ui?: {
resourceUri: string;
};
extensionName?: string;
toolName?: string;
toolNameIsActual?: boolean;
subagent_session_id?: string;
}
type ToolResultValue = {
content: GooseContentBlock[];
structuredContent?: unknown;
isError: boolean;
_meta?: DesktopMcpAppMeta;
_meta?: DesktopToolResultMeta;
};
function mcpAppMetadata(update: ToolCallUpdate): DesktopMcpAppMeta | undefined {
function toolResultMetadata(update: ToolCallUpdate): DesktopToolResultMeta | undefined {
if (!isRecord(update._meta)) {
return undefined;
}
const goose = update._meta.goose;
if (!isRecord(goose) || !isRecord(goose.mcpApp)) {
if (!isRecord(goose)) {
return undefined;
}
const resourceUri = goose.mcpApp.resourceUri;
if (typeof resourceUri !== 'string') {
return undefined;
const meta: DesktopToolResultMeta = {};
if (typeof goose.subagentSessionId === 'string') {
meta.subagent_session_id = goose.subagentSessionId;
}
return {
ui: {
resourceUri,
},
extensionName:
typeof goose.mcpApp.extensionName === 'string' ? goose.mcpApp.extensionName : undefined,
toolName: typeof goose.mcpApp.toolName === 'string' ? goose.mcpApp.toolName : undefined,
toolNameIsActual:
if (isRecord(goose.mcpApp) && typeof goose.mcpApp.resourceUri === 'string') {
meta.ui = { resourceUri: goose.mcpApp.resourceUri };
meta.extensionName =
typeof goose.mcpApp.extensionName === 'string' ? goose.mcpApp.extensionName : undefined;
meta.toolName = typeof goose.mcpApp.toolName === 'string' ? goose.mcpApp.toolName : undefined;
meta.toolNameIsActual =
typeof goose.mcpApp.toolNameIsActual === 'boolean'
? goose.mcpApp.toolNameIsActual
: undefined,
};
: undefined;
}
return Object.keys(meta).length > 0 ? meta : undefined;
}
+72 -60
View File
@@ -8,6 +8,7 @@ import MessageList from './MessageList';
import { MainPanelLayout } from './Layout/MainPanelLayout';
import ChatInput from './ChatInput';
import { ChatInputCard } from './ChatInputCard';
import { SubagentSessionNotice } from './SubagentSessionNotice';
import { Button } from './ui/button';
import { ScrollArea, ScrollAreaHandle } from './ui/scroll-area';
import { useFileDrop } from '../hooks/useFileDrop';
@@ -152,6 +153,7 @@ export default function BaseChat({
submitElicitationResponse,
stopStreaming,
retrySessionLoad,
refreshSession,
sessionLoadError,
tokenState,
notifications: toolCallNotifications,
@@ -169,6 +171,7 @@ export default function BaseChat({
);
const sessionLoaded = session !== undefined;
const isSubagentSession = session?.session_type === 'sub_agent';
const liveVoiceChatBusy = chatState !== ChatState.Idle;
useEffect(() => {
@@ -492,7 +495,7 @@ export default function BaseChat({
</div>
)}
{recipe && (
{recipe && !isSubagentSession && (
<div className={hasStartedUsingRecipe ? 'mb-6' : ''}>
<RecipeActivities
append={appendToChat}
@@ -509,11 +512,11 @@ export default function BaseChat({
messages={messages}
sessionId={sessionId}
toolCallNotifications={toolCallNotifications}
append={appendToChat}
append={isSubagentSession ? undefined : appendToChat}
isUserMessage={isUserMessage}
isStreamingMessage={chatState !== ChatState.Idle}
onRenderingComplete={handleRenderingComplete}
onMessageUpdate={onMessageUpdate}
onMessageUpdate={isSubagentSession ? undefined : onMessageUpdate}
submitElicitationResponse={submitElicitationResponse}
/>
</div>
@@ -537,7 +540,7 @@ export default function BaseChat({
</div>
)}
{quoteButtonPos && (
{quoteButtonPos && !isSubagentSession && (
<button
className="fixed z-50 -translate-x-1/2 -translate-y-full rounded-md bg-background-inverse px-2 py-1 text-xs font-medium text-text-inverse shadow-md hover:opacity-90"
style={{ left: quoteButtonPos.x, top: quoteButtonPos.y }}
@@ -556,63 +559,72 @@ export default function BaseChat({
</button>
)}
<ChatInputCard
className={cn(
'relative z-30 mx-4 mb-4',
!disableAnimation && 'animate-[fadein_400ms_ease-in_forwards]'
)}
>
<ChatInput
inputRef={chatInputRef}
sessionId={sessionId}
handleSubmit={chatInputSubmit}
chatState={chatState}
hasActiveRun={hasActiveRun}
onStop={stopStreaming}
onSteerQueuedMessage={onSteerQueuedMessage}
pauseQueueOnStop={pauseQueueOnStop}
queueProcessingBlocked={queueProcessingBlocked || acpRecovering}
commandHistory={commandHistory}
initialValue={initialPrompt}
setView={setView}
totalTokens={tokenState?.totalTokens ?? session?.usage?.total_tokens ?? undefined}
contextLimit={tokenState?.contextLimit}
accumulatedInputTokens={
tokenState?.accumulatedInputTokens ??
session?.accumulated_usage?.input_tokens ??
undefined
}
accumulatedOutputTokens={
tokenState?.accumulatedOutputTokens ??
session?.accumulated_usage?.output_tokens ??
undefined
}
accumulatedCost={tokenState?.accumulatedCost ?? session?.accumulated_cost ?? undefined}
droppedFiles={droppedFiles}
onFilesProcessed={() => setDroppedFiles([])} // Clear dropped files after processing
messages={messages}
disableAnimation={disableAnimation}
recipe={recipe}
initialPrompt={initialPrompt}
sessionModel={sessionModel}
sessionProvider={sessionProvider}
sessionLoaded={sessionLoaded}
workingDir={session?.working_dir}
onWorkingDirChange={handleWorkingDirChange}
latestInference={latestInference}
liveVoice={{
availability: liveVoiceAvailability,
phase: ownsLiveVoice ? liveVoice.phase : 'idle',
muted: ownsLiveVoice ? liveVoice.muted : false,
activeInAnotherSession: liveVoiceActiveInAnotherSession,
start: () => startLiveVoice(),
stop: liveVoice.stop,
toggleMute: liveVoice.toggleMute,
}}
appendQuote={pendingQuote}
onAppendQuoteConsumed={() => setPendingQuote(null)}
{isSubagentSession ? (
<SubagentSessionNotice
refreshing={chatState === ChatState.LoadingConversation}
onRefresh={() => void refreshSession()}
/>
</ChatInputCard>
) : (
<ChatInputCard
className={cn(
'relative z-30 mx-4 mb-4',
!disableAnimation && 'animate-[fadein_400ms_ease-in_forwards]'
)}
>
<ChatInput
inputRef={chatInputRef}
sessionId={sessionId}
handleSubmit={chatInputSubmit}
chatState={chatState}
hasActiveRun={hasActiveRun}
onStop={stopStreaming}
onSteerQueuedMessage={onSteerQueuedMessage}
pauseQueueOnStop={pauseQueueOnStop}
queueProcessingBlocked={queueProcessingBlocked || acpRecovering}
commandHistory={commandHistory}
initialValue={initialPrompt}
setView={setView}
totalTokens={tokenState?.totalTokens ?? session?.usage?.total_tokens ?? undefined}
contextLimit={tokenState?.contextLimit}
accumulatedInputTokens={
tokenState?.accumulatedInputTokens ??
session?.accumulated_usage?.input_tokens ??
undefined
}
accumulatedOutputTokens={
tokenState?.accumulatedOutputTokens ??
session?.accumulated_usage?.output_tokens ??
undefined
}
accumulatedCost={
tokenState?.accumulatedCost ?? session?.accumulated_cost ?? undefined
}
droppedFiles={droppedFiles}
onFilesProcessed={() => setDroppedFiles([])} // Clear dropped files after processing
messages={messages}
disableAnimation={disableAnimation}
recipe={recipe}
initialPrompt={initialPrompt}
sessionModel={sessionModel}
sessionProvider={sessionProvider}
sessionLoaded={sessionLoaded}
workingDir={session?.working_dir}
onWorkingDirChange={handleWorkingDirChange}
latestInference={latestInference}
liveVoice={{
availability: liveVoiceAvailability,
phase: ownsLiveVoice ? liveVoice.phase : 'idle',
muted: ownsLiveVoice ? liveVoice.muted : false,
activeInAnotherSession: liveVoiceActiveInAnotherSession,
start: () => startLiveVoice(),
stop: liveVoice.stop,
toggleMute: liveVoice.toggleMute,
}}
appendQuote={pendingQuote}
onAppendQuoteConsumed={() => setPendingQuote(null)}
/>
</ChatInputCard>
)}
</MainPanelLayout>
</div>
);
@@ -0,0 +1,27 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { IntlTestWrapper } from '../i18n/test-utils';
import { SubagentSessionNotice } from './SubagentSessionNotice';
describe('SubagentSessionNotice', () => {
it('explains the view is not live and loads the latest progress on click', () => {
const onRefresh = vi.fn();
render(<SubagentSessionNotice refreshing={false} onRefresh={onRefresh} />, {
wrapper: IntlTestWrapper,
});
expect(screen.getByRole('status')).toHaveTextContent(
"Subagent progress isn't shown live here."
);
fireEvent.click(screen.getByRole('button', { name: 'Load latest progress' }));
expect(onRefresh).toHaveBeenCalledOnce();
});
it('disables loading while a load is in progress', () => {
render(<SubagentSessionNotice refreshing onRefresh={vi.fn()} />, {
wrapper: IntlTestWrapper,
});
expect(screen.getByRole('button', { name: 'Load latest progress' })).toBeDisabled();
});
});
@@ -0,0 +1,40 @@
import { Info, RefreshCw } from 'lucide-react';
import { defineMessages, useIntl } from '../i18n';
import { Button } from './ui/button';
import { cn } from '../utils';
const i18n = defineMessages({
notice: {
id: 'subagentSessionNotice.notice',
defaultMessage: "Subagent progress isn't shown live here.",
},
loadLatestProgress: {
id: 'subagentSessionNotice.loadLatestProgress',
defaultMessage: 'Load latest progress',
},
});
interface SubagentSessionNoticeProps {
refreshing: boolean;
onRefresh: () => void;
}
export function SubagentSessionNotice({ refreshing, onRefresh }: SubagentSessionNoticeProps) {
const intl = useIntl();
return (
<div
role="status"
className="relative z-30 mx-4 mb-4 flex items-center justify-between gap-4 rounded-2xl border border-border-primary bg-background-secondary px-4 py-3"
>
<span className="flex items-center gap-2 text-sm text-text-primary">
<Info className="size-4 shrink-0 text-text-secondary" />
{intl.formatMessage(i18n.notice)}
</span>
<Button variant="default" size="sm" onClick={onRefresh} disabled={refreshing}>
<RefreshCw className={cn(refreshing && 'animate-spin')} />
{intl.formatMessage(i18n.loadLatestProgress)}
</Button>
</div>
);
}
@@ -0,0 +1,29 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { IntlTestWrapper } from '../i18n/test-utils';
import type { Message } from '../types/message';
import UserMessage from './UserMessage';
const message: Message = {
content: [{ type: 'text', text: 'Find all callers of load_session' }],
created: Date.now(),
id: 'msg-1',
metadata: { agentVisible: true, userVisible: true },
role: 'user',
};
describe('UserMessage', () => {
it('offers editing when the message can be updated', () => {
render(<UserMessage message={message} onMessageUpdate={vi.fn()} />, {
wrapper: IntlTestWrapper,
});
expect(screen.getByRole('button', { name: /Edit message/ })).toBeInTheDocument();
});
it('hides editing when the message cannot be updated', () => {
render(<UserMessage message={message} />, { wrapper: IntlTestWrapper });
expect(screen.queryByRole('button', { name: /Edit message/ })).not.toBeInTheDocument();
});
});
+20 -18
View File
@@ -353,24 +353,26 @@ function UserMessage({ message, onMessageUpdate }: UserMessageProps) {
{timestamp}
</div>
<div className="absolute right-0 pt-1 flex items-center gap-2">
<button
onClick={handleEditClick}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleEditClick();
}
}}
className="flex items-center gap-1 text-xs text-text-secondary hover:cursor-pointer hover:text-text-primary transition-all duration-200 opacity-0 group-hover:opacity-100 -translate-y-4 group-hover:translate-y-0 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-50 rounded"
aria-label={intl.formatMessage(i18n.editMessageAriaLabel, {
preview: `${textContent.substring(0, 50)}${textContent.length > 50 ? '...' : ''}`,
})}
aria-expanded={isEditing}
title={intl.formatMessage(i18n.editMessageTitle)}
>
<Edit className="h-3 w-3" />
<span>{intl.formatMessage(i18n.editButton)}</span>
</button>
{onMessageUpdate && (
<button
onClick={handleEditClick}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleEditClick();
}
}}
className="flex items-center gap-1 text-xs text-text-secondary hover:cursor-pointer hover:text-text-primary transition-all duration-200 opacity-0 group-hover:opacity-100 -translate-y-4 group-hover:translate-y-0 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-50 rounded"
aria-label={intl.formatMessage(i18n.editMessageAriaLabel, {
preview: `${textContent.substring(0, 50)}${textContent.length > 50 ? '...' : ''}`,
})}
aria-expanded={isEditing}
title={intl.formatMessage(i18n.editMessageTitle)}
>
<Edit className="h-3 w-3" />
<span>{intl.formatMessage(i18n.editButton)}</span>
</button>
)}
<MessageCopyLink text={textContent} contentRef={contentRef} />
</div>
</div>
@@ -153,7 +153,7 @@ describe('RTL chat direction', () => {
});
it('updates the edit textarea direction as the content changes', () => {
renderWithIntl(<UserMessage message={makeUserMessage('hello')} />);
renderWithIntl(<UserMessage message={makeUserMessage('hello')} onMessageUpdate={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: /Edit message/ }));
const textarea = screen.getByRole('textbox') as HTMLTextAreaElement;
+6
View File
@@ -152,6 +152,11 @@ export function useChatSession({
[sessionId, onSessionLoaded]
);
const refreshSession = useCallback(
() => acpChatSessionController.restoreSession(sessionId),
[sessionId]
);
// Load session on mount or sessionId change
useEffect(() => {
void retrySessionLoad();
@@ -351,6 +356,7 @@ export function useChatSession({
submitElicitationResponse,
stopStreaming,
retrySessionLoad,
refreshSession,
tokenState,
notifications: notificationsMap,
pauseQueueOnStop: false,
@@ -23,6 +23,7 @@ export interface UseChatSessionResult {
) => Promise<boolean>;
stopStreaming: () => void;
retrySessionLoad: () => Promise<void>;
refreshSession: () => Promise<void>;
sessionLoadError?: string;
tokenState: TokenState;
notifications: Map<string, NotificationEvent[]>;
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Konfigurieren Sie ein Subrezept, das während der Rezeptausführung als Tool aufgerufen werden kann"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Neuesten Fortschritt laden"
},
"subagentSessionNotice.notice": {
"defaultMessage": "Der Fortschritt des Subagenten wird hier nicht live angezeigt."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Zurück zur Modellliste"
},
+6
View File
@@ -4394,6 +4394,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Configure a subrecipe that can be called as a tool during recipe execution"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Load latest progress"
},
"subagentSessionNotice.notice": {
"defaultMessage": "Subagent progress isn't shown live here."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Back to model list"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Configura una subreceta que se pueda invocar como herramienta durante la ejecución de la receta"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Cargar el progreso más reciente"
},
"subagentSessionNotice.notice": {
"defaultMessage": "El progreso del subagente no se muestra en directo aquí."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Volver a la lista de modelos"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Configurez une sous-recette qui peut être appelée en tant qu'outil lors de l'exécution de la recette"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Charger la progression la plus récente"
},
"subagentSessionNotice.notice": {
"defaultMessage": "La progression du sous-agent n'est pas affichée en direct ici."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Retour à la liste des modèles"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "ऐसी सबरेसिपी कॉन्फ़िगर करें जिसे रेसिपी निष्पादन के दौरान टूल की तरह कॉल किया जा सके"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "नवीनतम प्रगति लोड करें"
},
"subagentSessionNotice.notice": {
"defaultMessage": "सबएजेंट की प्रगति यहाँ लाइव नहीं दिखाई जाती।"
},
"switchModelModal.backToModelList": {
"defaultMessage": "मॉडल सूची पर वापस जाएँ"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Konfigurasikan subresep yang dapat dipanggil sebagai alat selama eksekusi resep"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Muat progres terbaru"
},
"subagentSessionNotice.notice": {
"defaultMessage": "Progres subagen tidak ditampilkan secara langsung di sini."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Kembali ke daftar model"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Configura una sottoricetta che può essere richiamata come strumento durante l'esecuzione della ricetta"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Carica gli ultimi progressi"
},
"subagentSessionNotice.notice": {
"defaultMessage": "I progressi del subagente non vengono mostrati in tempo reale qui."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Torna all'elenco dei modelli"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "レシピ実行中にツールとして呼び出せるサブレシピを設定します"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "最新の進捗を読み込む"
},
"subagentSessionNotice.notice": {
"defaultMessage": "サブエージェントの進捗はここではリアルタイムに表示されません。"
},
"switchModelModal.backToModelList": {
"defaultMessage": "モデル一覧に戻る"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "레시피 실행 시 도구로 호출할 수 있는 서브레시피를 구성합니다."
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "최신 진행 상황 불러오기"
},
"subagentSessionNotice.notice": {
"defaultMessage": "하위 에이전트 진행 상황은 여기에 실시간으로 표시되지 않습니다."
},
"switchModelModal.backToModelList": {
"defaultMessage": "모델 목록으로 돌아가기"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Konfigurasikan subresipi yang boleh dipanggil sebagai alat semasa pelaksanaan resipi"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Muatkan kemajuan terkini"
},
"subagentSessionNotice.notice": {
"defaultMessage": "Kemajuan subagen tidak dipaparkan secara langsung di sini."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Kembali ke senarai model"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Configure uma subrreceita que pode ser invocada como ferramenta durante a execução da receita"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Carregar o progresso mais recente"
},
"subagentSessionNotice.notice": {
"defaultMessage": "O progresso do subagente não é mostrado ao vivo aqui."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Voltar à lista de modelos"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Настройте подрецепт, который можно вызывать как инструмент при выполнении рецепта"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Загрузить последний прогресс"
},
"subagentSessionNotice.notice": {
"defaultMessage": "Прогресс субагента здесь не отображается в реальном времени."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Назад к списку моделей"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Tarif yürütme sırasında araç olarak çağrılabilecek bir alt tarif yapılandırın"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "En son ilerlemeyi yükle"
},
"subagentSessionNotice.notice": {
"defaultMessage": "Alt ajan ilerlemesi burada canlı olarak gösterilmez."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Model listesine geri dön"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "Định cấu hình một công thức con có thể được gọi như công cụ trong quá trình thực thi công thức"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "Tải tiến trình mới nhất"
},
"subagentSessionNotice.notice": {
"defaultMessage": "Tiến trình của tác tử con không được hiển thị trực tiếp tại đây."
},
"switchModelModal.backToModelList": {
"defaultMessage": "Quay lại danh sách mô hình"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "配置一个可在配方执行过程中作为工具调用的子配方"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "加载最新进度"
},
"subagentSessionNotice.notice": {
"defaultMessage": "子代理的进度不会在此实时显示。"
},
"switchModelModal.backToModelList": {
"defaultMessage": "返回模型列表"
},
+6
View File
@@ -4277,6 +4277,12 @@
"subRecipeModal.subtitle": {
"defaultMessage": "設定可在配方執行期間作為工具呼叫的子配方"
},
"subagentSessionNotice.loadLatestProgress": {
"defaultMessage": "載入最新進度"
},
"subagentSessionNotice.notice": {
"defaultMessage": "子代理的進度不會在此即時顯示。"
},
"switchModelModal.backToModelList": {
"defaultMessage": "返回模型清單"
},