Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): add Agent activity display shortcuts (#1697)

Call White66e02fdd9248
diff --git a/core/internal_server.py b/core/internal_server.py
index af5f0cf42..4154a18a9 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -946,6 +946,18 @@ def create_app(
logger.exception("internal platform reconcile failed")
return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+ @app.post("/internal/invalidate-activity-streaming")
+ async def _invalidate_activity_streaming() -> Any:
+ """Drop the controller process's cached Agent Activity display flag."""
+ try:
+ from core.message_mirror import reset_activity_flag_cache
+
+ reset_activity_flag_cache()
+ return JSONResponse(status_code=200, content={"ok": True})
+ except Exception as exc:
+ logger.exception("internal Agent Activity cache invalidation failed")
+ return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+
@app.post("/internal/reconcile-agent-backends")
async def _reconcile_agent_backends(request: Request) -> Any:
"""Hot-apply persisted Agent backend config on the controller loop."""
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 8404b1f9a..96c46f134 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -258,6 +258,26 @@ def test_reconcile_platforms_missing_socket_raises_unavailable(tmp_path):
asyncio.run(internal_client.reconcile_platforms(socket_path=sock))
+def test_invalidate_activity_streaming_round_trip(socket_path):
+ app = FastAPI()
+ calls: list[bool] = []
+
+ @app.post("/internal/invalidate-activity-streaming")
+ async def _invalidate():
+ calls.append(True)
+ return {"ok": True}
+
+ async def _go():
+ fake_transport = httpx.ASGITransport(app=app)
+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):
+ return await internal_client.invalidate_activity_streaming(socket_path=socket_path)
+
+ result = asyncio.run(_go())
+
+ assert calls == [True]
+ assert result == {"status_code": 200, "body": {"ok": True}}
+
+
def test_reconcile_agent_backends_round_trip(tmp_path, socket_path):
app = FastAPI()
captured: dict = {}
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 45cd42806..6437a004e 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -1915,6 +1915,27 @@ def test_reconcile_platforms_endpoint_reports_controller_failure(monkeypatch):
assert resp.json() == {"ok": False, "error": "IM thread for discord did not stop within timeout"}
+def test_invalidate_activity_streaming_endpoint_clears_controller_cache(monkeypatch):
+ controller = _build_controller_double()
+ calls: list[bool] = []
+ monkeypatch.setattr(
+ "core.message_mirror.reset_activity_flag_cache",
+ lambda: calls.append(True),
+ )
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post("/internal/invalidate-activity-streaming")
+
+ resp = asyncio.run(_go())
+
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True}
+ assert calls == [True]
+
+
def test_reconcile_agent_backends_endpoint_calls_controller():
controller = _build_controller_double()
calls = []
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index c9a5c913b..47e2cbf4e 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -2017,6 +2017,37 @@ def test_config_post_hot_reconciles_platform_runtime_credential_change(monkeypat
assert reconcile_calls == [True]
+def test_config_post_invalidates_controller_activity_flag_cache(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+
+ api.save_config(_full_config_payload())
+ invalidate_calls: list[bool] = []
+
+ async def _invalidate_activity_streaming():
+ invalidate_calls.append(True)
+ return {"status_code": 200, "body": {"ok": True}}
+
+ monkeypatch.setattr(
+ internal_client,
+ "invalidate_activity_streaming",
+ _invalidate_activity_streaming,
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"ui": {"show_agent_activity": True}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ runtime = response.get_json()["activity_streaming_runtime"]
+ assert runtime == {"ok": True, "hot_reconciled": True, "body": {"ok": True}}
+ assert invalidate_calls == [True]
+
+
def test_platform_runtime_fields_changed_detects_primary_only_change():
from config.v2_config import V2Config
@@ -2257,8 +2288,16 @@ def test_config_post_non_platform_change_does_not_reconcile_platforms(monkeypatc
async def _reconcile_agent_backends(_backends):
raise AssertionError("Agent backend reconcile should not run")
+ async def _invalidate_activity_streaming():
+ raise AssertionError("Agent Activity cache invalidation should not run")
+
monkeypatch.setattr(internal_client, "reconcile_platforms", _reconcile_platforms)
monkeypatch.setattr(internal_client, "reconcile_agent_backends", _reconcile_agent_backends)
+ monkeypatch.setattr(
+ internal_client,
+ "invalidate_activity_streaming",
+ _invalidate_activity_streaming,
+ )
client = app.test_client()
response = client.post("/api/config", json={"show_duration": False}, headers=csrf_headers(client))
@@ -2266,6 +2305,7 @@ def test_config_post_non_platform_change_does_not_reconcile_platforms(monkeypatc
assert response.status_code == 200
assert "platform_runtime" not in response.get_json()
assert "agent_backend_runtime" not in response.get_json()
+ assert "activity_streaming_runtime" not in response.get_json()
def test_config_post_schedules_service_restart_when_hot_reconcile_unavailable(monkeypatch, tmp_path):
diff --git a/ui/src/components/workbench/AgentActivityGroup.test.tsx b/ui/src/components/workbench/AgentActivityGroup.test.tsx
new file mode 100644
index 000000000..f4cc33c2b
--- /dev/null
+++ b/ui/src/components/workbench/AgentActivityGroup.test.tsx
@@ -0,0 +1,44 @@
+/** @vitest-environment jsdom */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { ActivityCard } from './AgentActivityGroup';
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('ActivityCard display shortcut', () => {
+ it('renders a compact neutral close control beside the existing header controls', () => {
+ const onDisableActivity = vi.fn();
+ render(
+ <ActivityCard
+ rows={[]}
+ startedAtMs={Date.now()}
+ expanded
+ onToggleExpanded={vi.fn()}
+ showToolCalls
+ onToggleTools={vi.fn()}
+ onDisableActivity={onDisableActivity}
+ />,
+ );
+
+ const tools = screen.getByTitle('chat.agentActivity.hideTools');
+ const close = screen.getByRole('button', { name: 'chat.agentActivity.disable' });
+ const collapse = screen.getByRole('button', { name: 'chat.agentActivity.collapse' });
+ expect(close.className).toContain('size-6');
+ for (const sharedClass of ['border-border', 'bg-foreground/[0.04]', 'text-foreground/80']) {
+ expect(tools.className).toContain(sharedClass);
+ expect(close.className).toContain(sharedClass);
+ }
+ expect(close.nextElementSibling).toBe(collapse);
+
+ fireEvent.click(close);
+ expect(onDisableActivity).toHaveBeenCalledOnce();
+ });
+});
diff --git a/ui/src/components/workbench/AgentActivityGroup.tsx b/ui/src/components/workbench/AgentActivityGroup.tsx
index 0e8c88701..00fb78570 100644
--- a/ui/src/components/workbench/AgentActivityGroup.tsx
+++ b/ui/src/components/workbench/AgentActivityGroup.tsx
@@ -19,6 +19,7 @@ import {
Sparkles,
Terminal,
Wrench,
+ X,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import clsx from 'clsx';
@@ -396,7 +397,16 @@ export const ActivityCard: React.FC<{
onToggleExpanded: () => void;
showToolCalls: boolean;
onToggleTools: () => void;
-}> = ({ rows, startedAtMs, expanded, onToggleExpanded, showToolCalls, onToggleTools }) => {
+ onDisableActivity?: () => void;
+}> = ({
+ rows,
+ startedAtMs,
+ expanded,
+ onToggleExpanded,
+ showToolCalls,
+ onToggleTools,
+ onDisableActivity,
+}) => {
const { t } = useTranslation();
const [nowMs, setNowMs] = useState(() => Date.now());
// Fallback start if the turn's start time is unknown (defensive — the card only
@@ -463,6 +473,17 @@ export const ActivityCard: React.FC<{
<span className="ml-auto shrink-0 font-mono text-[11px] text-muted">{clock}</span>
</button>
<ToolsEyePill shown={showToolCalls} onToggle={onToggleTools} />
+ {onDisableActivity && (
+ <button
+ type="button"
+ onClick={onDisableActivity}
+ aria-label={t('chat.agentActivity.disable')}
+ title={t('chat.agentActivity.disable')}
+ className="inline-flex size-6 shrink-0 items-center justify-center rounded-full border border-border bg-foreground/[0.04] text-foreground/80 transition-colors hover:bg-foreground/[0.08]"
+ >
+ <X className="size-3.5" aria-hidden="true" />
+ </button>
+ )}
<button type="button" onClick={onToggleExpanded} aria-label={t('chat.agentActivity.collapse')}>
<ChevronDown
className={clsx('size-3.5 shrink-0 text-muted transition-transform', expanded && 'rotate-180')}
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index 683930ee7..75043ad29 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -16,15 +16,27 @@ const mocks = vi.hoisted(() => ({
getWorkbenchPrefs: vi.fn(),
listSessionMessages: vi.fn(),
listSessionQueue: vi.fn(),
+ mutateConfig: vi.fn(),
+ waitForAgentActivityConfigMutations: vi.fn(),
onSessionArchived: vi.fn(),
},
events: null as null | {
onConnected: () => void;
- onAuthorizationChanged: (data: { resource_kinds?: string[] }) => void;
+ onAuthorizationChanged: (data: {
+ resource_kinds?: string[];
+ instance_authorization_revision?: number;
+ }) => void;
onMessageNew: (message: ReturnType<typeof projectedMessage>) => void;
onTurnStart: (data: { session_id: string }) => void;
onTurnEnd: (data: { session_id: string }) => void;
},
+ authorizationCapabilities: {
+ can_chat: true,
+ can_manage_instance: false,
+ can_use_show_pages: false,
+ can_use_system: false,
+ can_use_vault_secrets: false,
+ },
}));
vi.mock('react-i18next', () => ({
@@ -45,12 +57,7 @@ vi.mock('../../context/WorkbenchInboxContext', () => ({
vi.mock('../../context/InstanceAuthorizationContext', () => ({
useInstanceAuthorization: () => ({
- capabilities: {
- can_chat: true,
- can_manage_instance: false,
- can_use_show_pages: false,
- can_use_vault_secrets: false,
- },
+ capabilities: mocks.authorizationCapabilities,
}),
}));
@@ -192,6 +199,13 @@ describe('ChatPage transcript hydration', () => {
bootstrap = deferred();
mocks.events = null;
vi.clearAllMocks();
+ Object.assign(mocks.authorizationCapabilities, {
+ can_chat: true,
+ can_manage_instance: false,
+ can_use_show_pages: false,
+ can_use_system: false,
+ can_use_vault_secrets: false,
+ });
mocks.api.connectWorkbenchEvents.mockImplementation((events) => {
mocks.events = events;
@@ -206,6 +220,8 @@ describe('ChatPage transcript hydration', () => {
mocks.api.getWorkbenchPrefs.mockResolvedValue({});
mocks.api.listSessionMessages.mockResolvedValue({ messages: [] });
mocks.api.listSessionQueue.mockResolvedValue([]);
+ mocks.api.mutateConfig.mockResolvedValue({ ui: {} });
+ mocks.api.waitForAgentActivityConfigMutations.mockResolvedValue(undefined);
mocks.api.onSessionArchived.mockReturnValue(() => {});
});
@@ -491,4 +507,269 @@ describe('ChatPage transcript hydration', () => {
await waitFor(() => expect(screen.getByText('chat.agentActivity.running')).toBeTruthy());
expect(screen.queryByText('chat.agentActivity.interrupted')).toBeNull();
});
+
+ it('uses the thinking dots and the Activity header as shortcuts for the global display setting', async () => {
+ const openGroup = {
+ id: 'current-turn',
+ anchor_message_id: null,
+ anchor_position: 'after' as const,
+ open: true,
+ status: 'running' as const,
+ steps: 1,
+ duration_ms: null,
+ };
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ });
+ mocks.api.getSessionActivity.mockResolvedValue({ groups: [openGroup] });
+ mocks.api.getSessionActivityGroup.mockResolvedValue({
+ ...openGroup,
+ rows: [{
+ id: 'current-step',
+ kind: 'assistant',
+ text: 'current work step',
+ created_at: '2026-08-25T00:00:00Z',
+ }],
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const enable = await screen.findByRole('button', { name: 'chat.agentActivity.enable' });
+ expect(enable.className).toContain('cursor-pointer');
+ act(() => enable.click());
+
+ await waitFor(() => expect(mocks.api.mutateConfig).toHaveBeenCalledWith([
+ { kind: 'set', path: ['ui', 'show_agent_activity'], value: true },
+ ]));
+ await waitFor(() => expect(screen.getByText('current work step')).toBeTruthy());
+
+ const disable = screen.getByRole('button', { name: 'chat.agentActivity.disable' });
+ expect(disable.className).toContain('size-6');
+ expect(disable.className).toContain('border-border');
+ act(() => disable.click());
+
+ await waitFor(() => expect(mocks.api.mutateConfig).toHaveBeenCalledWith([
+ { kind: 'set', path: ['ui', 'show_agent_activity'], value: false },
+ ]));
+ await waitFor(() => expect(screen.queryByText('current work step')).toBeNull());
+ expect(screen.getByRole('button', { name: 'chat.agentActivity.enable' })).toBeTruthy();
+ });
+
+ it('waits for a visibility write before bootstrapping a switched chat', async () => {
+ const activityWrite = deferred<{ ui: { show_agent_activity: boolean } }>();
+ mocks.api.getSession.mockImplementation((id: string) => Promise.resolve({ id }));
+ mocks.api.getSessionBootstrap
+ .mockResolvedValueOnce({
+ ...bootstrapPayload('session-new'),
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ })
+ .mockResolvedValueOnce({
+ ...bootstrapPayload('session-running'),
+ config: { ui: { show_agent_activity: true } },
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ });
+ mocks.api.mutateConfig.mockImplementationOnce(() => activityWrite.promise);
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <SessionSwitcher />
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const enable = await screen.findByRole('button', { name: 'chat.agentActivity.enable' });
+ mocks.api.waitForAgentActivityConfigMutations.mockImplementationOnce(
+ () => activityWrite.promise.then(() => undefined),
+ );
+ act(() => enable.click());
+ await waitFor(() => expect(mocks.api.mutateConfig).toHaveBeenCalledTimes(1));
+ act(() => screen.getByRole('button', { name: 'switch chat' }).click());
+ await act(async () => Promise.resolve());
+ expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(1);
+
+ await act(async () => activityWrite.resolve({ ui: { show_agent_activity: true } }));
+ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(2));
+ expect(mocks.api.getSessionBootstrap).toHaveBeenLastCalledWith('session-running');
+ await waitFor(() => expect(screen.queryByRole('button', {
+ name: 'chat.agentActivity.enable',
+ })).toBeNull());
+ });
+
+ it('does not let an in-flight authorization bootstrap overwrite a newer visibility click', async () => {
+ const authorizationBootstrap = deferred<ReturnType<typeof bootstrapPayload>>();
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap
+ .mockResolvedValueOnce({
+ ...bootstrapPayload('session-new'),
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ })
+ .mockImplementationOnce(() => authorizationBootstrap.promise);
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const enable = await screen.findByRole('button', { name: 'chat.agentActivity.enable' });
+ act(() => mocks.events?.onAuthorizationChanged({ instance_authorization_revision: 2 }));
+ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(2));
+ act(() => enable.click());
+ await waitFor(() => expect(mocks.api.mutateConfig).toHaveBeenCalledTimes(1));
+
+ await act(async () => authorizationBootstrap.resolve({
+ ...bootstrapPayload('session-new'),
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ }));
+ await waitFor(() => expect(screen.queryByRole('button', {
+ name: 'chat.agentActivity.enable',
+ })).toBeNull());
+ });
+
+ it('restores the enable shortcut when the visibility write fails', async () => {
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ });
+ mocks.api.mutateConfig.mockRejectedValueOnce(new Error('save failed'));
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const enable = await screen.findByRole('button', { name: 'chat.agentActivity.enable' });
+ act(() => enable.click());
+ await waitFor(() => expect(mocks.api.mutateConfig).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(screen.getByRole('button', {
+ name: 'chat.agentActivity.enable',
+ })).toBeTruthy());
+ });
+
+ it('restores the last confirmed visibility when the latest write fails', async () => {
+ const openGroup = {
+ id: 'current-turn',
+ anchor_message_id: null,
+ anchor_position: 'after' as const,
+ open: true,
+ status: 'running' as const,
+ steps: 1,
+ duration_ms: null,
+ };
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ });
+ mocks.api.getSessionActivity.mockResolvedValue({ groups: [openGroup] });
+ mocks.api.getSessionActivityGroup.mockResolvedValue({
+ ...openGroup,
+ rows: [{
+ id: 'current-step',
+ kind: 'assistant',
+ text: 'current work step',
+ created_at: '2026-08-25T00:00:00Z',
+ }],
+ });
+ mocks.api.mutateConfig
+ .mockResolvedValueOnce({ ui: { show_agent_activity: true } })
+ .mockRejectedValueOnce(new Error('save failed'));
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const enable = await screen.findByRole('button', { name: 'chat.agentActivity.enable' });
+ act(() => enable.click());
+ await screen.findByText('current work step');
+ const disable = screen.getByRole('button', { name: 'chat.agentActivity.disable' });
+ act(() => disable.click());
+ await waitFor(() => expect(mocks.api.mutateConfig).toHaveBeenCalledTimes(2));
+ await screen.findByText('current work step');
+ await waitFor(() => expect(screen.getByRole('button', {
+ name: 'chat.agentActivity.disable',
+ })).toBeTruthy());
+ });
+
+ it('does not offer the global enable shortcut to a Viewer', async () => {
+ mocks.authorizationCapabilities.can_chat = false;
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await screen.findByText('chat.thinking');
+ expect(screen.queryByRole('button', { name: 'chat.agentActivity.enable' })).toBeNull();
+ expect(mocks.api.mutateConfig).not.toHaveBeenCalled();
+ });
+
+ it('does not offer the global disable shortcut to a Viewer', async () => {
+ mocks.authorizationCapabilities.can_chat = false;
+ const openGroup = {
+ id: 'current-turn',
+ anchor_message_id: null,
+ anchor_position: 'after' as const,
+ open: true,
+ status: 'running' as const,
+ steps: 1,
+ duration_ms: null,
+ };
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ config: { ui: { show_agent_activity: true } },
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ });
+ mocks.api.getSessionActivity.mockResolvedValue({ groups: [openGroup] });
+ mocks.api.getSessionActivityGroup.mockResolvedValue({
+ ...openGroup,
+ rows: [{
+ id: 'current-step',
+ kind: 'assistant',
+ text: 'viewer-visible work step',
+ created_at: '2026-08-25T00:00:00Z',
+ }],
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await screen.findByText('viewer-visible work step');
+ expect(screen.queryByRole('button', { name: 'chat.agentActivity.disable' })).toBeNull();
+ expect(mocks.api.mutateConfig).not.toHaveBeenCalled();
+ });
});
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 3e33a27be..7cfd0c2b3 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -303,6 +303,9 @@ export const ChatPage: React.FC = () => {
const readOnly = isSessionReadOnly(session);
const writable = canChat && !readOnly;
const metadataWritable = sessionCanChat && !readOnly;
+ // The shared Messaging settings use this same capability boundary: Editors
+ // can persist display preferences, while Viewers can only observe them.
+ const canEditAgentActivityVisibility = capabilities.can_chat || capabilities.can_use_system;
// Chat-page-wide drag-and-drop: dropping files anywhere over the chat surface
// (not just the input row) stages them on the composer via its imperative
@@ -627,6 +630,8 @@ export const ChatPage: React.FC = () => {
const [showAgentActivity, setShowAgentActivity] = useState(false);
const showAgentActivityRef = useRef(false);
showAgentActivityRef.current = showAgentActivity;
+ const confirmedAgentActivityVisibilityRef = useRef(false);
+ const agentActivityVisibilityRequestRef = useRef(0);
const [activityGroups, setActivityGroups] = useState<ActivityGroup[]>([]);
const liveStateRef = useRef<LiveActivityState>(initialLiveActivity());
const [liveRows, setLiveRows] = useState<ActivityRow[]>([]);
@@ -721,7 +726,7 @@ export const ChatPage: React.FC = () => {
} catch {
return false; // transient failure → caller retries; a stale card is hidden by the working gate
}
- if (sid !== sessionIdRef.current) return true;
+ if (sid !== sessionIdRef.current || !showAgentActivityRef.current) return true;
const fetched = (res.groups ?? []).map(groupFromWire);
// Interpret an open group against the LATEST controller state, not the state
// from when this request started. A chat switch can hydrate ``running`` while
@@ -741,7 +746,7 @@ export const ChatPage: React.FC = () => {
if (liveStateRef.current.rows.length === 0) {
try {
const wire = await api.getSessionActivityGroup(sid, inflight.id);
- if (sid !== sessionIdRef.current) return true;
+ if (sid !== sessionIdRef.current || !showAgentActivityRef.current) return true;
if (activityForegroundRef.current !== 'running') return true;
const rows = groupFromWire(wire).rows ?? [];
if (rows.length > 0) {
@@ -795,6 +800,59 @@ export const ChatPage: React.FC = () => {
[refreshActivity],
);
scheduleActivityRefreshRef.current = scheduleActivityRefresh;
+ const applyAgentActivityVisibility = useCallback(
+ (enabled: boolean) => {
+ showAgentActivityRef.current = enabled;
+ setShowAgentActivity(enabled);
+
+ if (enabled) {
+ // The shortcut means "show me this execution now", not merely "remember
+ // the preference for the next turn". Expand first, then hydrate the open
+ // durable group while the config write enables subsequent live events.
+ setActivityCardExpanded(true);
+ scheduleActivityRefresh();
+ } else {
+ // Bump the generation so detail reads already in flight cannot repopulate
+ // the card after it was globally hidden. The next enable hydrates afresh.
+ dispatchLive({ type: 'reset' });
+ setActivityGroups([]);
+ setActivityCardExpanded(false);
+ setExpandedActivity({});
+ setLoadingActivity({});
+ setActivityError({});
+ activityRefreshPendingRef.current = false;
+ if (activityRetryTimerRef.current !== null) {
+ window.clearTimeout(activityRetryTimerRef.current);
+ activityRetryTimerRef.current = null;
+ }
+ }
+ },
+ [dispatchLive, scheduleActivityRefresh],
+ );
+ const setAgentActivityVisibility = useCallback(
+ (enabled: boolean) => {
+ if (!canEditAgentActivityVisibility) return;
+ applyAgentActivityVisibility(enabled);
+ const request = ++agentActivityVisibilityRequestRef.current;
+
+ const pendingWrite = api.mutateConfig([
+ setConfigField(['ui', 'show_agent_activity'], enabled),
+ ]);
+ void pendingWrite
+ .then(() => {
+ confirmedAgentActivityVisibilityRef.current = enabled;
+ if (request !== agentActivityVisibilityRequestRef.current) return;
+ // Close the small save/streaming gap: rows persisted while the config
+ // mutation was in flight are recovered from the durable group.
+ if (enabled && showAgentActivityRef.current) scheduleActivityRefresh();
+ })
+ .catch(() => {
+ if (request !== agentActivityVisibilityRequestRef.current) return;
+ applyAgentActivityVisibility(confirmedAgentActivityVisibilityRef.current);
+ });
+ },
+ [api, applyAgentActivityVisibility, canEditAgentActivityVisibility, scheduleActivityRefresh],
+ );
// Send-while-busy queue (messages sent while a turn runs, shown above the
// composer) + the loaded draft to seed the composer with.
const [queue, setQueue] = useState<WorkbenchMessage[]>([]);
@@ -1358,6 +1416,12 @@ export const ChatPage: React.FC = () => {
setError(null);
setFailedBootstrapSessionId((current) => current === sessionId ? null : current);
try {
+ // This component is reused across chat routes. A visibility click from the
+ // previous route must settle before the next bootstrap reads global config,
+ // otherwise the new chat can reinstall the pre-click value.
+ await api.waitForAgentActivityConfigMutations();
+ if (!requestIsCurrent()) return;
+ const activityVisibilityRequest = agentActivityVisibilityRequestRef.current;
// Initial chat open needs the same recent tail window, queue, draft,
// route/config state, and current turn state. Fetch them as one bootstrap
// payload so remote links don't pay a tunnel round-trip per widget.
@@ -1390,9 +1454,18 @@ export const ChatPage: React.FC = () => {
setAgents(bootstrap.agents);
setDefaultAgentName(bootstrap.default_agent_name);
setMessageFontSize(normalizeChatMessageFontSize(bootstrap.config?.ui?.chat_message_font_size));
- const activityEnabled = Boolean(bootstrap.config?.ui?.show_agent_activity);
- setShowAgentActivity(activityEnabled);
- showAgentActivityRef.current = activityEnabled;
+ const bootstrapActivityEnabled = Boolean(bootstrap.config?.ui?.show_agent_activity);
+ const activityPreferenceIsCurrent = (
+ activityVisibilityRequest === agentActivityVisibilityRequestRef.current
+ );
+ if (activityPreferenceIsCurrent) {
+ setShowAgentActivity(bootstrapActivityEnabled);
+ showAgentActivityRef.current = bootstrapActivityEnabled;
+ confirmedAgentActivityVisibilityRef.current = bootstrapActivityEnabled;
+ }
+ const activityEnabled = activityPreferenceIsCurrent
+ ? bootstrapActivityEnabled
+ : showAgentActivityRef.current;
// Default on: only an explicit ``false`` hides tool rows.
setShowToolCalls(bootstrap.config?.ui?.show_tool_calls !== false);
// Merge (not replace) so a row that arrived over the stream during the
@@ -2719,6 +2792,12 @@ export const ChatPage: React.FC = () => {
liveStartedAt,
cardExpanded: activityCardExpanded,
onToggleCard: () => setActivityCardExpanded((v) => !v),
+ onEnable: canEditAgentActivityVisibility
+ ? () => setAgentActivityVisibility(true)
+ : undefined,
+ onDisable: canEditAgentActivityVisibility
+ ? () => setAgentActivityVisibility(false)
+ : undefined,
expanded: expandedActivity,
loading: loadingActivity,
error: activityError,
@@ -3552,6 +3631,8 @@ interface TranscriptProps {
liveStartedAt: number | null;
cardExpanded: boolean;
onToggleCard: () => void;
+ onEnable?: () => void;
+ onDisable?: () => void;
expanded: Record<string, boolean>;
loading: Record<string, boolean>;
error: Record<string, boolean>;
@@ -4180,9 +4261,14 @@ export const Transcript: React.FC<TranscriptProps> = ({
onToggleExpanded={activity.onToggleCard}
showToolCalls={activity.showToolCalls}
onToggleTools={activity.onToggleTools}
+ onDisableActivity={activity.onDisable}
/>
) : showThinking ? (
- <ThinkingBubble session={session} agentDisplayName={agentDisplayName} />
+ <ThinkingBubble
+ session={session}
+ agentDisplayName={agentDisplayName}
+ onShowActivity={!activity?.enabled ? activity?.onEnable : undefined}
+ />
) : null}
{footer}
</div>
@@ -4238,8 +4324,16 @@ const ForkSourceBanner: React.FC<{ sourceSessionId: string; sourceTitle: string
export const ThinkingBubble: React.FC<{
session: WorkbenchSession;
agentDisplayName: string | null;
-}> = ({ session, agentDisplayName }) => {
+ onShowActivity?: () => void;
+}> = ({ session, agentDisplayName, onShowActivity }) => {
const { t } = useTranslation();
+ const dots = (
+ <div className="flex items-center gap-1 py-0.5">
+ <span className="vr-typing-dot size-1.5 rounded-full bg-mint" />
+ <span className="vr-typing-dot size-1.5 rounded-full bg-mint [animation-delay:0.2s]" />
+ <span className="vr-typing-dot size-1.5 rounded-full bg-mint [animation-delay:0.4s]" />
+ </div>
+ );
return (
<div className="flex w-full justify-start">
<div className="group/message flex max-w-[min(92%,860px)] flex-col items-start gap-1">
@@ -4249,13 +4343,21 @@ export const ThinkingBubble: React.FC<{
{agentDisplayName || session.agent_name || t('chat.thinking')}
</span>
</div>
- <div className="w-fit rounded-2xl rounded-tl-md border border-mint/25 bg-mint/[0.09] px-3.5 py-2.5">
- <div className="flex items-center gap-1 py-0.5">
- <span className="vr-typing-dot size-1.5 rounded-full bg-mint" />
- <span className="vr-typing-dot size-1.5 rounded-full bg-mint [animation-delay:0.2s]" />
- <span className="vr-typing-dot size-1.5 rounded-full bg-mint [animation-delay:0.4s]" />
+ {onShowActivity ? (
+ <button
+ type="button"
+ onClick={onShowActivity}
+ aria-label={t('chat.agentActivity.enable')}
+ title={t('chat.agentActivity.enable')}
+ className="w-fit cursor-pointer rounded-2xl rounded-tl-md border border-mint/25 bg-mint/[0.09] px-3.5 py-2.5 transition-colors hover:border-mint/45 hover:bg-mint/[0.14]"
+ >
+ {dots}
+ </button>
+ ) : (
+ <div className="w-fit rounded-2xl rounded-tl-md border border-mint/25 bg-mint/[0.09] px-3.5 py-2.5">
+ {dots}
</div>
- </div>
+ )}
</div>
</div>
);
diff --git a/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx b/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
index de32a7d11..8ec5be7b2 100644
--- a/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
+++ b/ui/src/components/workbench/ChatRowOptimisticWrites.test.tsx
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
getWorkbenchPrefs: vi.fn(),
listSessionMessages: vi.fn(),
listSessionQueue: vi.fn(),
+ waitForAgentActivityConfigMutations: vi.fn(),
onSessionArchived: vi.fn(),
updateSession: vi.fn(),
cancelSession: vi.fn(),
@@ -316,6 +317,7 @@ describe('the chat row under an optimistic write', () => {
mocks.api.getWorkbenchPrefs.mockResolvedValue({});
mocks.api.listSessionMessages.mockResolvedValue({ messages: [] });
mocks.api.listSessionQueue.mockResolvedValue([]);
+ mocks.api.waitForAgentActivityConfigMutations.mockResolvedValue(undefined);
mocks.api.onSessionArchived.mockReturnValue(() => {});
// A turn started; no transcript row to graft in this harness.
mocks.apiFetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });
diff --git a/ui/src/context/ApiContext.configChanges.test.tsx b/ui/src/context/ApiContext.configChanges.test.tsx
index e36458cdb..03eaeb537 100644
--- a/ui/src/context/ApiContext.configChanges.test.tsx
+++ b/ui/src/context/ApiContext.configChanges.test.tsx
@@ -30,6 +30,16 @@ const response = (payload: unknown, status = 200) => new Response(JSON.stringify
headers: { 'Content-Type': 'application/json' },
});
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+};
+
beforeEach(() => {
capturedApi = null;
apiFetch.mockReset();
@@ -79,4 +89,71 @@ describe('ApiProvider config convergence', () => {
await capturedApi!.mutateConfig([setConfigField(['language'], 'en')]);
expect(changed).toHaveBeenCalledOnce();
});
+
+ it('serializes mutations and preserves the fence across consumer remounts', async () => {
+ const firstResponse = deferred<Response>();
+ const view = render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+ apiFetch
+ .mockImplementationOnce(() => firstResponse.promise)
+ .mockResolvedValueOnce(response({ language: 'en' }));
+
+ const first = capturedApi!.mutateConfig([
+ setConfigField(['ui', 'show_agent_activity'], true),
+ ]);
+ const second = capturedApi!.mutateConfig([
+ setConfigField(['ui', 'show_agent_activity'], false),
+ ]);
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(1));
+
+ view.rerender(<ApiProvider><div /></ApiProvider>);
+ capturedApi = null;
+ view.rerender(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+ let fenceSettled = false;
+ const fence = capturedApi!.waitForAgentActivityConfigMutations().then(() => {
+ fenceSettled = true;
+ });
+ await Promise.resolve();
+ expect(fenceSettled).toBe(false);
+
+ firstResponse.resolve(response({ ui: { show_agent_activity: true } }));
+ await first;
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2));
+ await second;
+ await fence;
+ expect(fenceSettled).toBe(true);
+ });
+
+ it('continues the mutation queue after a failed save', async () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+ apiFetch
+ .mockResolvedValueOnce(response({ detail: 'save failed' }, 500))
+ .mockResolvedValueOnce(response({ language: 'en' }));
+
+ const failed = capturedApi!.mutateConfig([
+ setConfigField(['ui', 'show_agent_activity'], true),
+ ]);
+ const recovered = capturedApi!.mutateConfig([
+ setConfigField(['ui', 'show_agent_activity'], false),
+ ]);
+ await expect(failed).rejects.toThrow();
+ await expect(recovered).resolves.toEqual({ language: 'en' });
+ expect(apiFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not hold the Agent Activity fence behind an unrelated config save', async () => {
+ const unrelatedResponse = deferred<Response>();
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+ apiFetch.mockImplementationOnce(() => unrelatedResponse.promise);
+
+ const unrelated = capturedApi!.mutateConfig([setConfigField(['language'], 'zh')]);
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(1));
+ await expect(capturedApi!.waitForAgentActivityConfigMutations()).resolves.toBeUndefined();
+
+ unrelatedResponse.resolve(response({ language: 'zh' }));
+ await unrelated;
+ });
});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index aee5d3fee..4cb038da1 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -510,6 +510,7 @@ export type ApiContextType = {
getConfig: () => Promise<any>;
getPlatformCatalog: () => Promise<any>;
mutateConfig: (mutations: readonly ConfigMutation[]) => Promise<any>;
+ waitForAgentActivityConfigMutations: () => Promise<void>;
onConfigChanged: (handler: (config: unknown) => void) => () => void;
getSettings: (platform?: string) => Promise<any>;
saveSettings: (payload: any, platform?: string) => Promise<any>;
@@ -2586,6 +2587,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const { t } = useTranslation();
const readCacheRef = useRef(new Map<string, { expiresAt: number; promise: Promise<any> }>());
const configChangedHandlersRef = useRef(new Set<(config: unknown) => void>());
+ // Agent Activity is global across chat routes. Keep its writes ordered for the
+ // provider lifetime without making unrelated runtime-backed config saves block chat.
+ const agentActivityConfigMutationTailRef = useRef<Promise<unknown>>(Promise.resolve());
const eventSourceRef = useRef<EventSource | null>(null);
const eventHandlersRef = useRef(new Set<WorkbenchEventHandlers>());
const eventConnectionRef = useRef<{ sub_id: number; source?: 'browser' | 'controller' } | null>(null);
@@ -3550,10 +3554,32 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const value: ApiContextType = useMemo(() => ({
getConfig: () => getCachedJson('/api/config', CONFIG_CACHE_TTL_MS),
getPlatformCatalog: () => getJson('/api/platforms'),
- mutateConfig: async (mutations) => {
- const config = await postJson('/api/config', configMutationsToPayload(mutations));
- convergeConfig(config);
- return config;
+ mutateConfig: (mutations) => {
+ const save = async () => {
+ const config = await postJson('/api/config', configMutationsToPayload(mutations));
+ convergeConfig(config);
+ return config;
+ };
+ const touchesAgentActivity = mutations.some((mutation) => (
+ mutation.kind === 'set'
+ && mutation.path.length <= 2
+ && mutation.path.every((part, index) => part === ['ui', 'show_agent_activity'][index])
+ ));
+ if (!touchesAgentActivity) return save();
+ const mutation = agentActivityConfigMutationTailRef.current
+ .catch(() => undefined)
+ .then(save);
+ agentActivityConfigMutationTailRef.current = mutation;
+ return mutation;
+ },
+ waitForAgentActivityConfigMutations: async () => {
+ // Include writes appended while the current tail is settling; return only
+ // when the provider's Agent Activity queue is actually idle.
+ while (true) {
+ const pending = agentActivityConfigMutationTailRef.current;
+ await pending.catch(() => undefined);
+ if (pending === agentActivityConfigMutationTailRef.current) return;
+ }
},
onConfigChanged,
getSettings: (platform) => getJson(platform ? `/api/settings?platform=${encodeURIComponent(platform)}` : '/api/settings'),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b24b95b25..37ab0dbbf 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3874,6 +3874,8 @@
"interrupted": "Interrupted · stopped at step {{count}}",
"expand": "Show activity",
"collapse": "Hide activity",
+ "enable": "Turn on Agent activity",
+ "disable": "Turn off Agent activity",
"showCall": "Show details",
"hideCall": "Hide details",
"jumpToLatest": "Jump to latest",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 95efe939d..d17296768 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3874,6 +3874,8 @@
"interrupted": "已中断 · 第 {{count}} 步停止",
"expand": "展开执行过程",
"collapse": "收起执行过程",
+ "enable": "开启 Agent 执行过程显示",
+ "disable": "关闭 Agent 执行过程显示",
"showCall": "展开详情",
"hideCall": "收起详情",
"jumpToLatest": "跳到最新",
diff --git a/ui/src/lib/agentActivity.test.ts b/ui/src/lib/agentActivity.test.ts
index 2963337cc..5c61a0909 100644
--- a/ui/src/lib/agentActivity.test.ts
+++ b/ui/src/lib/agentActivity.test.ts
@@ -358,6 +358,22 @@ describe('liveActivityReducer (generation invariant)', () => {
expect(s.startedAt).toBeNull();
});
+ it('reset invalidates the visible generation and clears every live field', () => {
+ let s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
+ s = liveActivityReducer(s, { type: 'row', row: row('a'), now: 1 });
+ const visibleGen = s.gen;
+ s = liveActivityReducer(s, { type: 'reset' });
+ expect(s).toEqual({ gen: visibleGen + 1, settled: false, rows: [], startedAt: null });
+
+ const stale = liveActivityReducer(s, {
+ type: 'rehydrate_for_gen',
+ gen: visibleGen,
+ rows: [row('stale')],
+ startedAt: 1,
+ });
+ expect(stale.rows).toEqual([]);
+ });
+
it('rows append within a generation; the first stamps startedAt', () => {
let s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
s = liveActivityReducer(s, { type: 'row', row: row('a'), now: 100 });
diff --git a/ui/src/lib/agentActivity.ts b/ui/src/lib/agentActivity.ts
index 6d636361e..19695b702 100644
--- a/ui/src/lib/agentActivity.ts
+++ b/ui/src/lib/agentActivity.ts
@@ -120,6 +120,7 @@ export const initialLiveActivity = (): LiveActivityState => ({
export type LiveActivityEvent =
| { type: 'turn_start' }
+ | { type: 'reset' }
| { type: 'row'; row: ActivityRow; now: number }
| { type: 'settle' }
| { type: 'clear_for_gen'; gen: number }
@@ -146,6 +147,10 @@ export const liveActivityReducer = (
// New turn → new generation with a fresh empty buffer (any stale rows from the
// previous generation are dropped by construction).
return { gen: state.gen + 1, settled: false, rows: [], startedAt: null };
+ case 'reset':
+ // Turning Activity off invalidates every in-flight refresh from the visible
+ // generation. Re-enabling may then hydrate only the current durable turn.
+ return { gen: state.gen + 1, settled: false, rows: [], startedAt: null };
case 'row':
if (state.settled) {
// First row after a settle with no turn.start = an agent-initiated new turn.
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index d42131789..280f932f7 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -354,6 +354,27 @@ async def reconcile_platforms(
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def invalidate_activity_streaming(
+ *,
+ socket_path: Optional[Path] = None,
+ timeout: float = 5.0,
+) -> dict[str, Any]:
+ """Make the controller re-read the persisted Agent Activity display flag."""
+
+ target = await _verified_socket_path_async(socket_path)
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(timeout, connect=2.0),
+ ) as client:
+ resp = await client.post("/internal/invalidate-activity-streaming")
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+
+
async def reconcile_agent_backends(
backends: list[str],
*,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 908829467..f06b7e8e9 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1547,6 +1547,11 @@ def _should_rotate_remote_session_secret(previous: V2Config | None, current: V2C
return bool(previous_cloud.enabled and not current_cloud.enabled and current_cloud.session_secret)
+def _activity_streaming_flag_touched(payload: dict) -> bool:
+ ui_payload = payload.get("ui")
+ return isinstance(ui_payload, dict) and "show_agent_activity" in ui_payload
+
+
def _platform_runtime_signature(config: V2Config) -> dict[str, tuple[Any, ...]]:
from config.platform_registry import get_platform_descriptor
@@ -6474,7 +6479,7 @@ def _schedule_service_restart_for_config_fallback() -> dict[str, Any]:
return {"ok": True, "restart": restart}
-def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, bool, list[str]]:
+def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, bool, bool, list[str]]:
from vibe import api
from vibe import remote_access
@@ -6504,8 +6509,15 @@ def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, b
config = V2Config.load()
should_reconcile_remote_access = True
should_reconcile_platforms = _platform_runtime_fields_changed(previous_config, config, payload)
+ should_reconcile_activity_streaming = _activity_streaming_flag_touched(payload)
changed_agent_backends = _changed_agent_backend_runtimes(previous_config, config, payload)
- return config, should_reconcile_remote_access, should_reconcile_platforms, changed_agent_backends
+ return (
+ config,
+ should_reconcile_remote_access,
+ should_reconcile_platforms,
+ should_reconcile_activity_streaming,
+ changed_agent_backends,
+ )
_UI_RUNTIME_ACTIVE = False
@@ -6619,6 +6631,7 @@ async def config_post():
config,
should_reconcile_remote_access,
should_reconcile_platforms,
+ should_reconcile_activity_streaming,
changed_agent_backends,
) = await asyncio.to_thread(
_save_config_and_runtime_decisions,
@@ -6637,6 +6650,25 @@ async def config_post():
if should_reconcile_remote_access:
remote_access_runtime = await asyncio.to_thread(remote_access.reconcile)
await asyncio.to_thread(_ensure_remote_access_monitoring, config)
+ activity_streaming_runtime = None
+ if should_reconcile_activity_streaming:
+ try:
+ result = await internal_client.invalidate_activity_streaming()
+ body = result.get("body") or {}
+ hot_reconciled = result.get("status_code") == 200 and bool(body.get("ok"))
+ activity_streaming_runtime = {
+ "ok": hot_reconciled,
+ "hot_reconciled": hot_reconciled,
+ "body": body,
+ }
+ except internal_client.InternalServerUnavailable as exc:
+ # The controller's bounded cache remains the degradation path; the
+ # persisted setting is still authoritative and self-heals within its TTL.
+ activity_streaming_runtime = {
+ "ok": False,
+ "hot_reconciled": False,
+ "error": str(exc),
+ }
platform_runtime = None
if should_reconcile_platforms:
try:
@@ -6701,6 +6733,8 @@ async def config_post():
response_payload["remote_access_runtime"] = remote_access_runtime
if platform_runtime is not None:
response_payload["platform_runtime"] = platform_runtime
+ if activity_streaming_runtime is not None:
+ response_payload["activity_streaming_runtime"] = activity_streaming_runtime
if agent_backend_runtime is not None:
response_payload["agent_backend_runtime"] = agent_backend_runtime
return jsonify(response_payload)