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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/__tests__/integration/control-plane/session-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,31 @@ describe('control-plane session lifecycle API', () => {
});
});

it('returns selected-session runtime context for commands and status surfaces', async () => {
const { caller } = createControlPlaneCaller();
const session = await caller.sessionCreate({ name: 'Runtime context session', model: 'gpt-5.4' });
await caller.sessionSettingsUpdate({
id: session.id,
reasoningEffort: 'medium',
driftEnabled: true,
});

await expect(caller.sessionRuntimeContext({
sessionId: session.id,
})).resolves.toMatchObject({
workspaceId: DEFAULT_WORKSPACE_ID,
sessionId: session.id,
sessionName: 'Runtime context session',
model: 'gpt-5.4',
reasoningEffort: 'medium',
effectiveReasoningEffort: 'medium',
reasoningSupported: true,
contextWindow: 400000,
driftEnabled: true,
running: false,
});
});

it('returns visible errors for unknown slash commands', async () => {
const { caller } = createControlPlaneCaller();
const session = await caller.sessionCreate({ name: 'Unknown slash command session' });
Expand Down
59 changes: 59 additions & 0 deletions src/__tests__/unit/cli-v2/control-plane-session-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
ControlPlanePendingApproval,
ControlPlaneSessionDetail,
ControlPlaneSessionEventEnvelope,
ControlPlaneSessionRuntimeContext,
ControlPlaneSessionSendPromptAsyncResult,
ControlPlaneSessionView,
ControlPlaneSessionsEventEnvelope,
Expand All @@ -22,19 +23,50 @@ describe('ControlPlaneSessionStore', () => {
expect(fixture.calls.slashCommandCatalogQuery).toHaveBeenCalledWith({ workspaceId: 'workspace-1' });
expect(fixture.calls.sessionsQuery).toHaveBeenCalledWith({ workspaceId: 'workspace-1' });
expect(fixture.calls.sessionQuery).toHaveBeenCalledWith({ id: 'session-1', workspaceId: 'workspace-1' });
expect(fixture.calls.sessionRuntimeContextQuery).toHaveBeenCalledWith({
sessionId: 'session-1',
workspaceId: 'workspace-1',
});
expect(store.getSnapshot()).toMatchObject({
workspaceId: 'workspace-1',
activeSessionId: 'session-1',
loading: false,
running: false,
pendingApproval: null,
runtimeContext: expect.objectContaining({
model: 'gpt-5.4',
effectiveReasoningEffort: 'medium',
}),
});
expect(store.getSnapshot().activeSession?.messages).toEqual([
{ id: 'message-1', role: 'assistant', text: 'Ready.' },
]);
store.dispose();
});

it('refreshes runtime context when selecting a different session', async () => {
const fixture = createClientFixture();
const store = new ControlPlaneSessionStore({ client: fixture.client });
await store.start();
fixture.calls.sessionRuntimeContextQuery.mockResolvedValueOnce(createRuntimeContext({
sessionId: 'session-2',
sessionName: 'Session 2',
model: 'gpt-5.4-mini',
}));

await store.selectSession('session-2');

expect(fixture.calls.sessionRuntimeContextQuery).toHaveBeenLastCalledWith({
workspaceId: 'workspace-1',
sessionId: 'session-2',
});
expect(store.getSnapshot().runtimeContext).toMatchObject({
sessionId: 'session-2',
model: 'gpt-5.4-mini',
});
store.dispose();
});

it('submits prompts through sessionSendPromptAsync without a direct runtime fallback', async () => {
const fixture = createClientFixture();
const store = new ControlPlaneSessionStore({
Expand Down Expand Up @@ -485,6 +517,7 @@ function createClientFixture() {
sessionQuery: vi.fn(async () => sessionDetail),
sessionRunningQuery: vi.fn(async () => ({ running: false })),
sessionRunStateQuery: vi.fn(async () => ({ running: false, pendingApproval })),
sessionRuntimeContextQuery: vi.fn(async () => createRuntimeContext()),
sessionPendingApprovalQuery: vi.fn(async () => pendingApproval),
sessionSendPromptMutate: vi.fn(async () => ({
session: {
Expand Down Expand Up @@ -555,6 +588,7 @@ function createClientFixture() {
},
sessionRunning: { query: calls.sessionRunningQuery },
sessionRunState: { query: calls.sessionRunStateQuery },
sessionRuntimeContext: { query: calls.sessionRuntimeContextQuery },
sessionPendingApproval: { query: calls.sessionPendingApprovalQuery },
sessionSendPrompt: { mutate: calls.sessionSendPromptMutate },
sessionSendPromptAsync: { mutate: calls.sessionSendPromptAsyncMutate },
Expand Down Expand Up @@ -602,6 +636,31 @@ function createSessionDetail(): NonNullable<ControlPlaneSessionDetail> {
};
}

function createRuntimeContext(
overrides: Partial<ControlPlaneSessionRuntimeContext> = {},
): ControlPlaneSessionRuntimeContext {
return {
workspaceId: 'workspace-1',
sessionId: 'session-1',
sessionName: 'Session 1',
model: 'gpt-5.4',
reasoningEffort: 'medium',
effectiveReasoningEffort: 'medium',
reasoningSupported: true,
credentialSource: {
type: 'oauth',
provider: 'openai',
accountId: 'acct-test',
expiresAt: Date.now() + 60_000,
},
contextWindow: 400000,
estimatedInputTokens: undefined,
driftEnabled: false,
running: false,
...overrides,
};
}

function createAcceptedResult(): ControlPlaneSessionSendPromptAsyncResult {
return {
accepted: true,
Expand Down
62 changes: 62 additions & 0 deletions src/__tests__/unit/cli-v2/runtime-status.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest';
import { RuntimeStatusService } from '../../../cli-v2/services/status/index.js';
import type { ControlPlaneSessionStoreSnapshot } from '../../../cli-v2/state/control-plane-session-store.js';

describe('RuntimeStatusService', () => {
it('formats runtime context for the cli-v2 status bar', () => {
expect(RuntimeStatusService.build(createSnapshot())).toBe(
'model=gpt-5.4 • reasoning=medium • auth=openai-oauth:acct-tes • context window ~400,000 tokens • drift=off • session=session-1 (Session 1)',
);
});

it('includes estimated input usage and running status when available', () => {
expect(RuntimeStatusService.build(createSnapshot({
running: true,
runtimeContext: {
...createSnapshot().runtimeContext!,
estimatedInputTokens: 20000,
driftEnabled: true,
driftLevel: 'low',
running: true,
},
}))).toBe(
'model=gpt-5.4 • reasoning=medium • auth=openai-oauth:acct-tes • estimated input 20,000 / 400,000 tokens (5%) • drift=low • session=session-1 (Session 1) • status=running',
);
});
});

function createSnapshot(overrides: Partial<ControlPlaneSessionStoreSnapshot> = {}): ControlPlaneSessionStoreSnapshot {
return {
workspaceId: 'workspace-1',
sessions: [],
activeSessionId: 'session-1',
activeSession: null,
runtimeContext: {
workspaceId: 'workspace-1',
sessionId: 'session-1',
sessionName: 'Session 1',
model: 'gpt-5.4',
reasoningEffort: 'medium',
effectiveReasoningEffort: 'medium',
reasoningSupported: true,
credentialSource: {
type: 'oauth',
provider: 'openai',
accountId: 'acct-test',
expiresAt: Date.now() + 60_000,
},
contextWindow: 400000,
driftEnabled: false,
running: false,
},
pendingApproval: null,
loading: false,
submitting: false,
approvalResolving: false,
running: false,
cancelling: false,
streamConnected: false,
commandResults: [],
...overrides,
};
}
2 changes: 2 additions & 0 deletions src/cli-v2/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { CommandResultPanel } from './components/CommandResultPanel.js';
import { ConversationPanel } from './components/ConversationPanel.js';
import { PromptInput } from './components/PromptInput.js';
import { RunControls } from './components/RunControls.js';
import { RuntimeStatusBar } from './components/RuntimeStatusBar.js';
import { SlashCommandHintPanel } from './components/SlashCommandHintPanel.js';
import { useControlPlaneSessionStore } from './hooks/useControlPlaneSessionStore.js';
import { usePromptDraft } from './hooks/usePromptDraft.js';
Expand Down Expand Up @@ -102,6 +103,7 @@ export function App({
onSubmit={submitPrompt}
onComplete={(value) => store.completeSlashCommandDraft(value)}
/>
<RuntimeStatusBar snapshot={snapshot} />
</Box>
);
}
16 changes: 16 additions & 0 deletions src/cli-v2/components/RuntimeStatusBar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React from 'react';
import { Box, Text } from 'ink';
import type { ControlPlaneSessionStoreSnapshot } from '../state/control-plane-session-store.js';
import { RuntimeStatusService } from '../services/status/index.js';

export function RuntimeStatusBar({
snapshot,
}: {
snapshot: ControlPlaneSessionStoreSnapshot;
}) {
return (
<Box overflow="hidden">
<Text dimColor wrap="truncate-end">{RuntimeStatusService.build(snapshot)}</Text>
</Box>
);
}
1 change: 1 addition & 0 deletions src/cli-v2/services/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ Current domains:
to Ink rendering and cli-v2 store coordination.
- `slash-commands/`: local hint filtering and tab completion over
control-plane-provided slash command metadata.
- `status/`: terminal status-bar formatting over control-plane runtime context.
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ export class ControlPlaneSessionApiService {
return this.client.controlPlane.sessionRunState.query({ id: sessionId, workspaceId });
}

async getRuntimeContext(workspaceId: string, sessionId: string) {
return this.client.controlPlane.sessionRuntimeContext.query({ sessionId, workspaceId });
}

async getPendingApproval(workspaceId: string, sessionId: string) {
return this.client.controlPlane.sessionPendingApproval.query({ id: sessionId, workspaceId });
}
Expand Down
1 change: 1 addition & 0 deletions src/cli-v2/services/status/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { RuntimeStatusService } from './runtime-status-service.js';
58 changes: 58 additions & 0 deletions src/cli-v2/services/status/runtime-status-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { ControlPlaneSessionRuntimeContext } from '@/client-shared/api/types.js';
import type { ControlPlaneSessionStoreSnapshot } from '../../state/control-plane-session-store.js';

export class RuntimeStatusService {
static build(snapshot: ControlPlaneSessionStoreSnapshot): string {
const context = snapshot.runtimeContext;
if (!context) {
return snapshot.workspaceId ? 'runtime context loading...' : 'workspace loading...';
}

return [
`model=${context.model}`,
`reasoning=${RuntimeStatusService.formatReasoning(context)}`,
RuntimeStatusService.formatAuth(context),
RuntimeStatusService.formatContextWindow(context),
`drift=${context.driftEnabled ? context.driftLevel ?? 'unknown' : 'off'}`,
`session=${context.sessionId} (${context.sessionName})`,
snapshot.running ? 'status=running' : undefined,
].filter((item): item is string => Boolean(item)).join(' • ');
}

private static formatReasoning(context: ControlPlaneSessionRuntimeContext): string {
if (!context.reasoningSupported) {
return 'unsupported';
}

return context.effectiveReasoningEffort ?? 'default';
}

private static formatAuth(context: ControlPlaneSessionRuntimeContext): string {
const source = context.credentialSource;
switch (source.type) {
case 'explicit-api-key':
return 'auth=explicit-key';
case 'env-api-key':
return `auth=${source.provider}-key`;
case 'oauth':
return source.accountId ? `auth=${source.provider}-oauth:${source.accountId.slice(0, 8)}` : `auth=${source.provider}-oauth`;
case 'missing':
return `auth=missing-${source.provider}`;
}
}

private static formatContextWindow(context: ControlPlaneSessionRuntimeContext): string {
if (!context.contextWindow) {
return context.estimatedInputTokens
? `estimated input tokens ${context.estimatedInputTokens.toLocaleString()}`
: 'context window unknown';
}

if (!context.estimatedInputTokens) {
return `context window ~${context.contextWindow.toLocaleString()} tokens`;
}

const percent = Math.round(Math.min(1, context.estimatedInputTokens / context.contextWindow) * 100);
return `estimated input ${context.estimatedInputTokens.toLocaleString()} / ${context.contextWindow.toLocaleString()} tokens (${percent}%)`;
}
}
11 changes: 11 additions & 0 deletions src/cli-v2/state/control-plane-session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
ControlPlanePendingApproval,
ControlPlaneSessionDetail,
ControlPlaneSessionEventEnvelope,
ControlPlaneSessionRuntimeContext,
ControlPlaneSessionView,
ControlPlaneSlashCommandCatalog,
ControlPlaneSlashCommandHint,
Expand Down Expand Up @@ -53,6 +54,7 @@ export type ControlPlaneSessionStoreSnapshot = {
sessions: ControlPlaneSessionView[];
activeSessionId?: string;
activeSession: ControlPlaneSessionDetail;
runtimeContext?: ControlPlaneSessionRuntimeContext;
pendingApproval: ControlPlanePendingApproval;
loading: boolean;
submitting: boolean;
Expand All @@ -70,6 +72,7 @@ export type ControlPlaneSessionStoreSnapshot = {
const INITIAL_SNAPSHOT: ControlPlaneSessionStoreSnapshot = {
sessions: [],
activeSession: null,
runtimeContext: undefined,
pendingApproval: null,
loading: false,
submitting: false,
Expand Down Expand Up @@ -182,6 +185,7 @@ export class ControlPlaneSessionStore {
this.setSnapshot({
activeSessionId: sessionId,
activeSession: null,
runtimeContext: undefined,
pendingApproval: null,
liveStatus: undefined,
latestUpdate: undefined,
Expand All @@ -192,9 +196,11 @@ export class ControlPlaneSessionStore {

try {
const session = await this.api.getSession(workspaceId, sessionId);
const runtimeContext = await this.api.getRuntimeContext(workspaceId, sessionId);
const running = await this.api.getRunning(workspaceId, sessionId);
this.setSnapshot({
activeSession: session,
runtimeContext,
running: running.running,
loading: false,
});
Expand Down Expand Up @@ -379,10 +385,12 @@ export class ControlPlaneSessionStore {

try {
const next = await this.api.getSession(workspaceId, sessionId);
const runtimeContext = await this.api.getRuntimeContext(workspaceId, sessionId);
this.setSnapshot((current) => ({
activeSession: options.silent
? ClientSharedSessionMessageService.mergeTransientMessages(current.activeSession, next)
: next,
runtimeContext,
loading: false,
}));
} catch (error) {
Expand Down Expand Up @@ -625,6 +633,9 @@ export class ControlPlaneSessionStore {
this.setSnapshot({
pendingApproval: runState.pendingApproval,
running: runState.running,
runtimeContext: this.snapshotValue.runtimeContext
? { ...this.snapshotValue.runtimeContext, running: runState.running }
: this.snapshotValue.runtimeContext,
cancelling: runState.running ? this.snapshotValue.cancelling : false,
latestUpdate: runState.pendingApproval
? {
Expand Down
1 change: 1 addition & 0 deletions src/client-shared/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type ControlPlaneSessionEventEnvelope = AsyncIterableValue<RouterOutputs[
export type ControlPlaneSessionsEventEnvelope = AsyncIterableValue<RouterOutputs['controlPlane']['sessionsEvents']>;
export type ControlPlaneHeartbeatEventEnvelope = AsyncIterableValue<RouterOutputs['controlPlane']['heartbeatEvents']>;
export type ControlPlaneSessionMessage = NonNullable<ControlPlaneSessionDetail>['messages'][number];
export type ControlPlaneSessionRuntimeContext = RouterOutputs['controlPlane']['sessionRuntimeContext'];
export type ControlPlanePendingApproval = RouterOutputs['controlPlane']['sessionPendingApproval'];
export type ControlPlaneApprovalDecision = RouterInputs['controlPlane']['sessionResolveApproval']['decision'];
export type ControlPlaneSessionSendPromptResult = RouterOutputs['controlPlane']['sessionSendPrompt'];
Expand Down
Loading
Loading