Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Show Assistant provider route start events

rcourtmanad8373eec642
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index a98309912f..3ced7ef128 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -252,24 +252,30 @@ runtime cost control, and shared AI transport surfaces.
when `provider_fallback` names the next route so message labels, cost
context, retry decisions, and model-route recovery do not continue to point
at the failed provider. The referenced OpenCode source at fetched
- `origin/dev` commit `1399323b78a04229d9bfe00c7436d7f41770fda8` renders
- `ModelSwitchedMessage` as a typed transcript message and appends the
- effective provider/model route to completed assistant turns in
+ `origin/dev` commit `4519a1da329c1a4fc384054e7203ba7d06928205` defines
+ `session.next.model.switched` in
+ `packages/core/src/session/event.ts`, appends it as a
+ `SessionMessage.ModelSwitched` transcript message in
+ `packages/core/src/session/message-updater.ts`, and renders it as
+ `ModelSwitchedMessage` in
`packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx`.
- Pulse adapts that by rendering provider fallback route changes as a typed
- `model_switch` stream row on the active assistant turn instead of hiding the
- switch in transient status text or assistant prose. Provider-fallback rows
- must preserve the failed route and next route together, using the backend
- `failed_model` and `next_model` payloads, so the transcript shows the actual
- recovery path rather than only the successful replacement model. A successful
- provider fallback is also a session-model event, not only transcript
- decoration: once the live assistant turn completes with the fallback route as
- its effective model, the drawer must promote that route into the active
- session selection and recent-model list so the next prompt does not retry
- the just-failed direct provider before using the route that worked. This
- promotion may only apply to fallback rows observed during the live stream and
- must not rewrite historical loaded sessions or override an explicit user
- model change made while the fallback turn was still running.
+ Pulse adapts that by rendering model route changes as typed `model_switch`
+ stream rows on the active assistant turn instead of hiding the route in
+ transient status text or assistant prose. The initial `provider_start`
+ workflow state must carry the selected `provider` and concrete `model` route,
+ and the drawer must render that first route as a selected-model row (`Using
+ ...`) before visible content or tool activity when the event arrives.
+ Provider-fallback rows must preserve the failed route and next route
+ together, using the backend `failed_model` and `next_model` payloads, so the
+ transcript shows the actual recovery path rather than only the successful
+ replacement model. A successful provider fallback is also a session-model
+ event, not only transcript decoration: once the live assistant turn completes
+ with the fallback route as its effective model, the drawer must promote that
+ route into the active session selection and recent-model list so the next
+ prompt does not retry the just-failed direct provider before using the route
+ that worked. This promotion may only apply to fallback rows observed during
+ the live stream and must not rewrite historical loaded sessions or override
+ an explicit user model change made while the fallback turn was still running.
Interactive Assistant streams must establish the session ID and emit the
`session` event once as soon as the HTTP SSE writer is ready, before finding
handoff recovery, model resolution, provider fallback planning,
diff --git a/frontend-modern/src/components/AI/Chat/ChatMessages.tsx b/frontend-modern/src/components/AI/Chat/ChatMessages.tsx
index e0b4b8cbdf..7689a6f121 100644
--- a/frontend-modern/src/components/AI/Chat/ChatMessages.tsx
+++ b/frontend-modern/src/components/AI/Chat/ChatMessages.tsx
@@ -83,7 +83,7 @@ export const ChatMessages: Component<ChatMessagesProps> = (props) => {
case 'thinking':
return [...base, textActivityFingerprint(event.thinking)].join(':');
case 'model_switch':
- return [...base, event.model, event.failedModel].join(':');
+ return [...base, event.model, event.failedModel, event.modelEvent].join(':');
case 'approval':
return [
...base,
diff --git a/frontend-modern/src/components/AI/Chat/MessageItem.tsx b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
index f23743cdb3..0e2e3900fa 100644
--- a/frontend-modern/src/components/AI/Chat/MessageItem.tsx
+++ b/frontend-modern/src/components/AI/Chat/MessageItem.tsx
@@ -431,8 +431,10 @@ export const MessageItem: Component<MessageItemProps> = (props) => {
const failed = event.failedModel?.trim();
return !!model && !!failed && failed !== model;
};
+ const isSelectedModelEvent = (event: StreamDisplayEvent) =>
+ event.modelEvent === 'selected' && !!event.model?.trim();
const modelSwitchTitle = (event: StreamDisplayEvent) => {
- if (!isProviderFallbackEvent(event)) return event.model || '';
+ if (!isProviderFallbackEvent(event)) return modelRouteLabel(event.model);
return `${modelRouteLabel(event.failedModel)} -> ${modelRouteLabel(event.model)}`;
};
const messageModelLabel = () => modelRouteLabel(props.message.model);
@@ -731,7 +733,9 @@ export const MessageItem: Component<MessageItemProps> = (props) => {
aria-label={
isProviderFallbackEvent(evt)
? 'Assistant provider fallback route changed'
- : 'Assistant model route changed'
+ : isSelectedModelEvent(evt)
+ ? 'Assistant model route selected'
+ : 'Assistant model route changed'
}
title={modelSwitchTitle(evt)}
>
@@ -740,7 +744,12 @@ export const MessageItem: Component<MessageItemProps> = (props) => {
when={isProviderFallbackEvent(evt)}
fallback={
<>
- <span class="shrink-0">Switched to</span>{' '}
+ <Show when={isSelectedModelEvent(evt)}>
+ <span class="shrink-0">Using</span>{' '}
+ </Show>
+ <Show when={!isSelectedModelEvent(evt)}>
+ <span class="shrink-0">Switched to</span>{' '}
+ </Show>
<span class="truncate font-medium text-base-content">
{modelRouteLabel(evt.model)}
</span>
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
index a5b632d6d9..ec13163b52 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/MessageItem.test.tsx
@@ -821,6 +821,30 @@ describe('MessageItem', () => {
).toHaveTextContent('Switched to DeepSeek V4 Pro via OpenRouter');
});
+ it('renders the initially selected provider model route as active model use', () => {
+ const events: StreamDisplayEvent[] = [
+ {
+ type: 'model_switch',
+ model: 'openrouter:qwen/qwen3.7-plus',
+ modelEvent: 'selected',
+ },
+ ];
+
+ render(() => (
+ <MessageItem
+ message={makeMessage({ role: 'assistant', streamEvents: events })}
+ getModelRouteLabel={(model) =>
+ model === 'openrouter:qwen/qwen3.7-plus' ? 'Qwen 3.7 Plus via OpenRouter' : model
+ }
+ {...makeHandlers()}
+ />
+ ));
+
+ expect(
+ screen.getByRole('status', { name: 'Assistant model route selected' }),
+ ).toHaveTextContent('Using Qwen 3.7 Plus via OpenRouter');
+ });
+
it('renders provider fallback model switches with failed and next routes', () => {
const events: StreamDisplayEvent[] = [
{
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts
index 35ede34f55..df17b36224 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts
@@ -326,6 +326,31 @@ describe('getAssistantActiveTurnStatus', () => {
});
});
+ it('shows the initial selected model route without calling it a fallback', () => {
+ expect(
+ getAssistantActiveTurnStatus(
+ [
+ assistantMessage({
+ streamEvents: [
+ {
+ type: 'model_switch',
+ model: 'openrouter:qwen/qwen3.7-plus',
+ modelEvent: 'selected',
+ startedAt: 2_000,
+ updatedAt: 2_000,
+ },
+ ],
+ }),
+ ],
+ true,
+ ),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Using Qwen: Qwen3.7 Plus via OpenRouter',
+ startedAt: 2_000,
+ });
+ });
+
it('carries approval event timing into the active waiting status', () => {
expect(
getAssistantActiveTurnStatus(
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.test.ts
index b58eaf4f09..b5840d8159 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.test.ts
@@ -151,6 +151,30 @@ describe('Assistant transcript export', () => {
expect(transcript).toContain('No active alerts');
});
+ it('formats initially selected model route events distinctly from fallback switches', () => {
+ const transcript = formatAssistantTranscript({
+ messages: [
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ streamEvents: [
+ {
+ type: 'model_switch',
+ model: 'openrouter:qwen/qwen3.7-plus',
+ modelEvent: 'selected',
+ },
+ ],
+ },
+ ],
+ generatedAt: timestamp,
+ getModelRouteLabel: () => 'Qwen 3.7 Plus via OpenRouter',
+ });
+
+ expect(transcript).toContain('[model] using Qwen 3.7 Plus via OpenRouter');
+ });
+
it('reports whether a transcript has content', () => {
expect(hasAssistantTranscriptContent([])).toBe(false);
expect(
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
index e4d3b8429b..0fcd98f6dc 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -1393,6 +1393,59 @@ describe('useChat', () => {
dispose();
});
+ it('records the initial provider model route as a typed stream event', async () => {
+ const { getFireEvent } = setupWithEventCapture();
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
+
+ await chat.sendMessage('hi');
+ const fire = getFireEvent();
+
+ fire({
+ type: 'workflow_state',
+ data: {
+ phase: 'provider_start',
+ message: 'Sent request to OpenRouter; waiting for the first token.',
+ provider: 'openrouter',
+ model: 'openrouter:qwen/qwen3.7-plus',
+ },
+ });
+ fire({
+ type: 'workflow_state',
+ data: {
+ phase: 'provider_start',
+ message: 'Sent request to OpenRouter; waiting for the first token.',
+ provider: 'openrouter',
+ model: 'openrouter:qwen/qwen3.7-plus',
+ },
+ });
+
+ const assistant = chat.messages().find((m) => m.role === 'assistant')!;
+ expect(assistant.model).toBe('openrouter:qwen/qwen3.7-plus');
+ expect(assistant.streamEvents?.map((event) => event.type)).toEqual([
+ 'model_switch',
+ 'workflow_status',
+ ]);
+ expect(assistant.streamEvents?.[0]).toEqual(
+ expect.objectContaining({
+ type: 'model_switch',
+ model: 'openrouter:qwen/qwen3.7-plus',
+ failedModel: undefined,
+ modelEvent: 'selected',
+ }),
+ );
+ expect(assistant.streamEvents?.[1]).toEqual(
+ expect.objectContaining({
+ type: 'workflow_status',
+ workflowStatus: expect.objectContaining({
+ phase: 'provider_start',
+ message: 'Sent request to OpenRouter; waiting for the first token.',
+ }),
+ }),
+ );
+
+ dispose();
+ });
+
it('keeps the local request-start status when an early idle heartbeat arrives', async () => {
const { getFireEvent } = setupWithEventCapture();
const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
diff --git a/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts b/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts
index 8f2ae0dad5..9dbeeccf74 100644
--- a/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts
+++ b/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts
@@ -322,6 +322,7 @@ const modelSwitchStatusText = (event: StreamDisplayEvent): string => {
if (!model) return '';
const next = formatAIModelRouteLabel(model);
const failed = event.failedModel?.trim();
+ if (event.modelEvent === 'selected') return `Using ${next}`;
if (!failed || failed === model) return `Switched to ${next}`;
return `Provider fallback: ${formatAIModelRouteLabel(failed)} -> ${next}`;
};
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index f4276a6262..91e25297ec 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -424,6 +424,40 @@ export function useChat(options: UseChatOptions = {}) {
};
};
+ const streamModelEventKind = (event: StreamDisplayEvent): StreamDisplayEvent['modelEvent'] => {
+ if (event.modelEvent) return event.modelEvent;
+ const model = event.model?.trim();
+ const failed = event.failedModel?.trim();
+ return model && failed && model !== failed ? 'fallback' : 'switch';
+ };
+
+ const withModelRouteEvent = (
+ msg: ChatMessage,
+ route: string,
+ options: { failedModel?: string; modelEvent: NonNullable<StreamDisplayEvent['modelEvent']> },
+ ): ChatMessage => {
+ const model = route.trim();
+ if (!model) return msg;
+ const failedModel = options.failedModel?.trim();
+ const duplicate = (msg.streamEvents || []).some(
+ (event) =>
+ event.type === 'model_switch' &&
+ event.model?.trim() === model &&
+ (event.failedModel?.trim() || '') === (failedModel || '') &&
+ streamModelEventKind(event) === options.modelEvent,
+ );
+ if (duplicate) {
+ return { ...msg, model };
+ }
+ const updated = addStreamEvent(msg, {
+ type: 'model_switch',
+ model,
+ failedModel: failedModel || undefined,
+ modelEvent: options.modelEvent,
+ });
+ return { ...updated, model };
+ };
+
const normalizePendingToolStatus = (phase?: string): PendingTool['status'] => {
const normalized = (phase || 'running').trim().toLowerCase();
if (normalized === 'pending') return 'pending';
@@ -737,6 +771,8 @@ export function useChat(options: UseChatOptions = {}) {
return typeof modelRoute === 'string' ? modelRoute.trim() : '';
};
+ const extractWorkflowModel = (data: unknown): string => extractCompletedModel(data);
+
const extractWorkflowNextModel = (data: unknown): string => {
if (!data || typeof data !== 'object') return '';
const record = data as Record<string, unknown>;
@@ -997,19 +1033,33 @@ export function useChat(options: UseChatOptions = {}) {
const workflowStatus = extractWorkflowStatus(event.data);
const nextModel = extractWorkflowNextModel(event.data);
const failedModel = extractWorkflowFailedModel(event.data);
- if (!workflowStatus && !nextModel) return;
+ const startedModel =
+ workflowStatus?.phase === 'provider_start' ? extractWorkflowModel(event.data) : '';
+ const routeEvent = nextModel
+ ? {
+ model: nextModel,
+ failedModel,
+ modelEvent: (failedModel ? 'fallback' : 'switch') as NonNullable<
+ StreamDisplayEvent['modelEvent']
+ >,
+ }
+ : startedModel
+ ? {
+ model: startedModel,
+ failedModel: '',
+ modelEvent: 'selected' as const,
+ }
+ : null;
+ if (!workflowStatus && !routeEvent) return;
- if (nextModel) {
+ if (routeEvent) {
setMessages((prev) =>
prev.map((msg) => {
if (msg.id !== assistantId) return msg;
- if ((msg.model || '').trim() === nextModel) return msg;
- const updated = addStreamEvent(msg, {
- type: 'model_switch',
- model: nextModel,
- failedModel: failedModel || undefined,
+ return withModelRouteEvent(msg, routeEvent.model, {
+ failedModel: routeEvent.failedModel || undefined,
+ modelEvent: routeEvent.modelEvent,
});
- return { ...updated, model: nextModel };
}),
);
}
diff --git a/frontend-modern/src/components/AI/Chat/transcriptExport.ts b/frontend-modern/src/components/AI/Chat/transcriptExport.ts
index 94e52ef95e..feaee22f55 100644
--- a/frontend-modern/src/components/AI/Chat/transcriptExport.ts
+++ b/frontend-modern/src/components/AI/Chat/transcriptExport.ts
@@ -129,6 +129,7 @@ const formatModelSwitch = (
const model = formatModelRoute(event.model, getModelRouteLabel);
if (!model) return '';
const failed = formatModelRoute(event.failedModel, getModelRouteLabel);
+ if (event.modelEvent === 'selected') return `[model] using ${model}`;
return failed && failed !== model ? `[model] ${model} after ${failed}` : `[model] ${model}`;
};
diff --git a/frontend-modern/src/components/AI/Chat/types.ts b/frontend-modern/src/components/AI/Chat/types.ts
index 5ef1a57df9..351b7d4379 100644
--- a/frontend-modern/src/components/AI/Chat/types.ts
+++ b/frontend-modern/src/components/AI/Chat/types.ts
@@ -115,6 +115,7 @@ export interface StreamDisplayEvent {
content?: string;
model?: string;
failedModel?: string;
+ modelEvent?: 'selected' | 'switch' | 'fallback';
toolId?: string; // Used to match pending_tool with completed tool
approval?: PendingApproval; // For approval_needed events
question?: PendingQuestion; // For question events
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 97bf72c896..7350462427 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -13,6 +13,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rs/zerolog/log"
)
@@ -81,6 +82,18 @@ func withWorkflowRetry(nextAttempt, maxAttempts int, retryAfter time.Duration) w
}
}
+func withWorkflowModelRoute(modelRoute string) workflowStateOption {
+ return func(data *WorkflowStateData) {
+ route := strings.TrimSpace(modelRoute)
+ if route == "" {
+ return
+ }
+ provider, _ := config.ParseModelString(route)
+ data.Model = route
+ data.Provider = provider
+ }
+}
+
func emitWorkflowState(callback StreamCallback, phase, message, state, tool string, opts ...workflowStateOption) {
if callback == nil {
return
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index b0309f5e32..6207b83c63 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -877,6 +877,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
fmt.Sprintf("Sent request to %s; waiting for the first token.", providerLabelForAttempt(attempt)),
sessionFSMState(sessionFSM),
"",
+ withWorkflowModelRoute(attempt.Model),
)
log.Debug().
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index 776a4bea8c..7ca0067c06 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -616,6 +616,12 @@ func TestService_ExecuteStream_EmitsProviderStartupBeforeProviderCall(t *testing
if data.Message != "Sent request to OpenRouter; waiting for the first token." {
t.Fatalf("provider_start message = %q", data.Message)
}
+ if data.Provider != config.AIProviderOpenRouter {
+ t.Fatalf("provider_start provider = %q, want %q", data.Provider, config.AIProviderOpenRouter)
+ }
+ if data.Model != "openrouter:qwen/qwen3.7-plus" {
+ t.Fatalf("provider_start model = %q, want OpenRouter route", data.Model)
+ }
}
})
if err != nil {
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
index 56aadaae5d..8024328dec 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -276,6 +276,8 @@ type WorkflowStateData struct {
Message string `json:"message"` // Human-readable status text for the UI
State string `json:"state,omitempty"` // Backend workflow state, when available
Tool string `json:"tool,omitempty"` // Tool associated with this transition
+ Provider string `json:"provider,omitempty"` // Provider selected for this workflow step
+ Model string `json:"model,omitempty"` // Model route selected for this workflow step
Attempt int `json:"attempt,omitempty"` // One-based attempt number for transient provider retries
MaxAttempts int `json:"max_attempts,omitempty"` // Maximum attempts available for the current provider request
RetryAfterMS int64 `json:"retry_after_ms,omitempty"` // Milliseconds until the next provider attempt starts