fix(gateway): typed /reasoning and Move to project edit the owner's frozen policy
Mechanism: on main, Desktop's `config.set key=reasoning` (typed /reasoning, the keybind step, the
onboarding kickoff) and `session.workspace.move` (Move to project) changed the live sidecar
session. On the shared owner the next turn runs under the session's frozen LocalSessionPolicy,
and no owner verb could change its reasoning level or cwd: round 11 refused /reasoning by name in
Desktop and Ink, and the interim B21 commit refused Move to project by name (the WS legacy
fallback's sidecar move had rewritten only the row while execution cwd, TERMINAL_CWD and resume
stayed on the old folder).
Fix: two revision- and generation-fenced `session.mutate` operations, prepared off the commit and
published exactly like `model` (one `_POLICY` set in gateway/session_mutations.py):
- `reasoning {effort}`: the level build_policy freezes at create (agent.reasoning_effort,
per-model overrides dropped); validated by parse_reasoning_effort.
- `workspace {cwd}`: policy.cwd and terminal TERMINAL_CWD move together (restore_policy's
invariant), every row of the local conversation gets the new cwd with git branch/root REPLACED
(main's replace_git_meta), the terminal env is dropped like main's _set_session_cwd. The receipt
transaction's existing require_target_advanceable fence refuses it with `session_busy` while a
turn runs; Desktop shows "Stop the running turn, then move the chat".
Both re-bind the launch key / config secrets (policy identity covers config and cwd), bump the
generation, publish the policy, and push a session.info so viewers repaint. Prepare/commit live
in gateway/session_mutation_policy.py and hermes_state_mutation_prepared.py (shared
_commit_policy with model). `--global` reasoning and the display words stay named refusals (no
owner config-write verb). Desktop's canonical adapter maps session-scope config.set reasoning and
session.workspace.move onto the retained mutation (sidebar rows attach first to learn the
revision); Ink's typed /reasoning uses mutateCanonical. session.workspace.move leaves the legacy
fallback allowlist.
Tests (red on r12-integ1):
- tests/gateway/test_session_policy_verbs.py: a real SessionAuthority + state.db: reasoning is the
next turn's policy, session.info and the durable receipt, prompt untouched; Move refuses
session_busy mid-turn, then re-homes policy + row + session.info and the next turn executes in
the new folder.
- apps/desktop canonical-reasoning-config-set.test.ts and canonical-producer-contract.test.ts
sites (moveBusy copy listed as an ar/ja/zh-hant overlay gap beside moveFailed); ui-tui canonicalSlashCommands.test.ts.
Review: JoaoMarcos44 B14
Review: JoaoMarcos44 B21
Review: helix4u C-hx-2
(cherry picked from commit deef795dcb5e9fb98633b844ef5c4571dcb6f08e)
This commit is contained in:
@@ -80,6 +80,13 @@ function answer(frame: { method: string; params: Record<string, unknown> }): Rec
|
||||
return { status: 'settled', delivery_id: p.id, value: 'x' }
|
||||
}
|
||||
|
||||
// The owner edit each mutating site must send (fenced by the attached snapshot's revision/generation).
|
||||
const MUTATIONS: Record<string, Record<string, unknown>> = {
|
||||
rewind: { operation: 'rewind', payload: { target_message_id: 9 } },
|
||||
reasoning: { operation: 'reasoning', payload: { effort: 'high' } },
|
||||
workspace: { operation: 'workspace', payload: { cwd: '/repo' } }
|
||||
}
|
||||
|
||||
// [label, Desktop method, exact producer params, expected: wire methods sent (after attach) or a named refusal]
|
||||
const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]> = [
|
||||
[
|
||||
@@ -102,9 +109,15 @@ const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]>
|
||||
/reasoning .*not available/
|
||||
],
|
||||
[
|
||||
'reasoning-step.ts keybind step',
|
||||
'reasoning-step.ts keybind step (B14)',
|
||||
'config.set',
|
||||
{ key: 'reasoning', session_id: 's', value: 'high' },
|
||||
['session.mutate']
|
||||
],
|
||||
[
|
||||
'reasoning-slash.ts /reasoning show (display word, config.yaml)',
|
||||
'config.set',
|
||||
{ key: 'reasoning', session_id: 's', value: 'show' },
|
||||
/reasoning is not available/
|
||||
],
|
||||
['model-presets.ts fast', 'config.set', { key: 'fast', session_id: 's', value: 'fast' }, /fast is not available/],
|
||||
@@ -169,7 +182,7 @@ const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]>
|
||||
'projects.ts moveSessionToProject (B21 / C-hx-2)',
|
||||
'session.workspace.move',
|
||||
{ cwd: '/repo', session_key: 's' },
|
||||
/Moving a chat to another project is not available/
|
||||
['session.mutate']
|
||||
],
|
||||
[
|
||||
'connector-tool.tsx in-chat connect',
|
||||
@@ -211,6 +224,12 @@ test.each(SITES)('%s: the canonical frame fits the generated contract', async (_
|
||||
try {
|
||||
const address = server.address() as { port: number }
|
||||
await client.connect(`ws://127.0.0.1:${address.port}/api/ws?native_dial=fixture&ticket=one-use`)
|
||||
|
||||
// Typed /reasoning and the keybind act on the open (attached) session, as the model picker does.
|
||||
if (method === 'config.set' && params.key === 'reasoning') {
|
||||
await client.request('session.resume', { session_id: 's' })
|
||||
}
|
||||
|
||||
const call = client.request(method, params)
|
||||
|
||||
if (expected instanceof RegExp) {
|
||||
@@ -231,10 +250,12 @@ test.each(SITES)('%s: the canonical frame fits the generated contract', async (_
|
||||
}
|
||||
|
||||
if (Array.isArray(expected) && expected[0] === 'session.mutate') {
|
||||
const edit =
|
||||
MUTATIONS[method === 'prompt.submit' ? 'rewind' : method === 'config.set' ? 'reasoning' : 'workspace']
|
||||
|
||||
expect(sent.find(frame => frame.method === 'session.mutate').params).toMatchObject({
|
||||
session_id: 's',
|
||||
operation: 'rewind',
|
||||
payload: { target_message_id: 9 },
|
||||
...edit,
|
||||
expected_revision: 4,
|
||||
expected_generation: 2
|
||||
})
|
||||
|
||||
@@ -145,18 +145,12 @@ const CANONICAL_CONFIG_KEYS = new Set(['busy', 'verbose', 'yolo', 'model'])
|
||||
// The one guard between a Desktop producer and the owner's closed contracts: translate a legacy
|
||||
// shape the owner has a canonical form for, refuse by name what it does not serve.
|
||||
function canonicalProducerFrame(method: string, params: Record<string, unknown>): Record<string, unknown> {
|
||||
// No verb for other settings (reasoning, fast, approvals.mode, voice, display.*) nor a global
|
||||
// scope: refuse before the wire, like Ink, instead of a bare invalid_params.
|
||||
// No verb for other settings (reasoning display words, fast, approvals.mode, voice, display.*)
|
||||
// nor a global scope: refuse before the wire, like Ink, instead of a bare invalid_params.
|
||||
if (method === 'config.set' && (!CANONICAL_CONFIG_KEYS.has(String(params.key)) || 'scope' in params)) {
|
||||
throw new Error(`Changing ${params.key}${'scope' in params ? ` (${params.scope})` : ''} is not available on the shared gateway yet`)
|
||||
}
|
||||
|
||||
// The sidecar's move rewrites only the stored row: the owner's frozen policy (execution cwd,
|
||||
// TERMINAL_CWD, resume) would stay on the old folder while the sidebar showed the new one.
|
||||
if (method === 'session.workspace.move') {
|
||||
throw new Error('Moving a chat to another project is not available on the shared gateway yet')
|
||||
}
|
||||
|
||||
if (SIDECAR_SESSION_VERBS.has(method) || (method.startsWith('connect') && (params.owner as { type?: unknown } | undefined)?.type === 'session')) {
|
||||
throw new Error(`${method} is not available on the shared gateway yet`)
|
||||
}
|
||||
@@ -168,9 +162,26 @@ function canonicalProducerFrame(method: string, params: Record<string, unknown>)
|
||||
return method === 'bot_relay.deliver' ? canonicalBotDelivery(params) : params
|
||||
}
|
||||
|
||||
// The levels `hermes_constants.parse_reasoning_effort` accepts: a session `/reasoning <level>` is the
|
||||
// owner's `reasoning` mutation; the display words (show/hide/full/clamp) are config.yaml writes.
|
||||
const REASONING_EFFORTS = new Set(['none', 'false', 'disabled', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])
|
||||
|
||||
// Frozen-policy edits: a session-scope `/reasoning <level>` (`--global` stays the named refusal, no
|
||||
// owner config-write verb) and Move to project, which re-homes the execution cwd and TERMINAL_CWD
|
||||
// with the row (`session_key` names the sidebar row).
|
||||
function policyEdit(method: string, params: Record<string, unknown>): { session: unknown; operation: string; payload: Record<string, unknown> } | null {
|
||||
const effort = String(params.value ?? '').trim().toLowerCase()
|
||||
|
||||
if (method === 'config.set' && params.key === 'reasoning' && params.scope !== 'global' && REASONING_EFFORTS.has(effort)) {
|
||||
return { session: params.session_id, operation: 'reasoning', payload: { effort } }
|
||||
}
|
||||
|
||||
return method === 'session.workspace.move' ? { session: params.session_key, operation: 'workspace', payload: { cwd: params.cwd } } : null
|
||||
}
|
||||
|
||||
const BRANCH_METHODS = new Set(['session.branch', 'session.branch_stored', 'session.branch_whole'])
|
||||
// Value-setting mutations: re-applying one is harmless, so a later acknowledged edit retires it.
|
||||
const VALUE_OPERATIONS = new Set(['rename', 'archive', 'model'])
|
||||
const VALUE_OPERATIONS = new Set(['rename', 'archive', 'model', 'reasoning', 'workspace'])
|
||||
const MUTATION_METHODS = new Set(['session.title', 'session.archive', 'session.compress', 'session.rewind', ...BRANCH_METHODS])
|
||||
|
||||
export class CanonicalDesktopProtocol {
|
||||
@@ -200,8 +211,8 @@ export class CanonicalDesktopProtocol {
|
||||
// failure carries no reason; its outcome is unknown and the token stays for the exact retry.
|
||||
if (typeof reason === 'string') { this.settleModelConfirmation(params) }
|
||||
|
||||
// A typed busy refusal of a rewind wrote nothing either; the caller interrupts and retries at the new revision.
|
||||
if (reason !== 'revision_conflict' && !(reason === 'session_busy' && params.operation === 'rewind')) { return }
|
||||
// A typed busy refusal of a rewind or a move wrote nothing either; the retry is a new request at the new revision.
|
||||
if (reason !== 'revision_conflict' && !(reason === 'session_busy' && ['rewind', 'workspace'].includes(params.operation as string))) { return }
|
||||
|
||||
// A confirmed CAS refusal did not mutate. Ambiguous transport failures keep
|
||||
// the original revision/id so a retry cannot overwrite another user's edit.
|
||||
@@ -219,7 +230,7 @@ export class CanonicalDesktopProtocol {
|
||||
// rebinds the live event transport and returns the same snapshot shape.
|
||||
if (method === 'session.activate') { return 'session.resume' }
|
||||
|
||||
return (method === 'slash.exec' || method === 'config.set') && typeof prepared.operation === 'string' ? 'session.mutate' : method
|
||||
return (method === 'slash.exec' || method === 'config.set' || method === 'session.workspace.move') && typeof prepared.operation === 'string' ? 'session.mutate' : method
|
||||
}
|
||||
|
||||
private retainedMutation(sessionId: unknown, profile: unknown, operation: string, payload: Record<string, unknown>, withGeneration: boolean): Record<string, unknown> {
|
||||
@@ -314,6 +325,10 @@ export class CanonicalDesktopProtocol {
|
||||
return this.retainedMutation(parent, params.profile, 'branch', payload, true)
|
||||
}
|
||||
|
||||
const policy = policyEdit(method, params)
|
||||
|
||||
if (policy) { return this.retainedMutation(policy.session, params.profile, policy.operation, policy.payload, true) }
|
||||
|
||||
if (method === 'config.set' && params.key === 'model') {
|
||||
const pick = pickerModelMutation(params.value)
|
||||
|
||||
@@ -459,7 +474,7 @@ export class CanonicalDesktopProtocol {
|
||||
result(method: string, params: Record<string, unknown>, value: any): any {
|
||||
if (!value || typeof value !== 'object') { return value }
|
||||
|
||||
const mutation = MUTATION_METHODS.has(method) || ((method === 'slash.exec' || method === 'config.set') && typeof params.operation === 'string')
|
||||
const mutation = MUTATION_METHODS.has(method) || ((method === 'slash.exec' || method === 'config.set' || method === 'session.workspace.move') && typeof params.operation === 'string')
|
||||
this.adoptRevision(params, value, mutation)
|
||||
|
||||
if (mutation) { return this.mutationReceipt(method, params, value) }
|
||||
@@ -527,7 +542,8 @@ export class CanonicalDesktopProtocol {
|
||||
|
||||
if (method === 'slash.exec') { return { ...value, type: 'exec', output: mutationSummary(params.operation as string, value) } }
|
||||
|
||||
return { ...value, ok: true }
|
||||
// The legacy config.set answer every reasoning caller reads (`result.value`).
|
||||
return params.operation === 'reasoning' ? { ...value, ok: true, value: value.effort } : { ...value, ok: true }
|
||||
}
|
||||
|
||||
// An acknowledged mutation at revision R settles every older retained value-setting request of
|
||||
|
||||
@@ -3,11 +3,10 @@ import { expect, test } from 'vitest'
|
||||
|
||||
import { HermesGateway } from './client'
|
||||
|
||||
// The canonical config.set key set (tui_gateway/contracts/canonical_projections.py::
|
||||
// CanonicalConfigSetParams); the real owner answers any other key with 4001 invalid_params.
|
||||
const CANONICAL_CONFIG_KEYS = new Set(['busy', 'verbose', 'yolo', 'model'])
|
||||
|
||||
test('typed /reasoning on a canonical dial is refused by name and never sent as a bare invalid_params', async () => {
|
||||
// B14: main's Desktop /reasoning <level> changed the session's reasoning through legacy config.set.
|
||||
// On the shared owner the session scope is the revision-fenced `session.mutate operation=reasoning`;
|
||||
// `--global` (a config.yaml write the owner has no verb for) stays a named refusal.
|
||||
test('typed /reasoning sets the session level through the owner mutation; --global is refused by name', async () => {
|
||||
const wsPackage = 'ws'
|
||||
const { WebSocketServer } = await import(wsPackage)
|
||||
const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
|
||||
@@ -17,17 +16,32 @@ test('typed /reasoning on a canonical dial is refused by name and never sent as
|
||||
socket.on('message', (bytes: Buffer) => {
|
||||
const frame = JSON.parse(bytes.toString())
|
||||
sent.push(frame)
|
||||
const refused = frame.method === 'config.set' && !CANONICAL_CONFIG_KEYS.has(frame.params.key)
|
||||
const p = frame.params
|
||||
|
||||
const result =
|
||||
frame.method === 'session.resume'
|
||||
? { session_id: 's', revision: 4, execution_generation: 2, running: false, messages: [], prompts: [] }
|
||||
: frame.method === 'session.mutate'
|
||||
? {
|
||||
session_id: p.session_id,
|
||||
operation: p.operation,
|
||||
revision: 5,
|
||||
execution_generation: 3,
|
||||
effort: p.payload.effort
|
||||
}
|
||||
: frame.method === 'config.set'
|
||||
? null
|
||||
: { value: 'medium' }
|
||||
|
||||
socket.send(
|
||||
JSON.stringify(
|
||||
refused
|
||||
? {
|
||||
result
|
||||
? { jsonrpc: '2.0', id: frame.id, result }
|
||||
: {
|
||||
jsonrpc: '2.0',
|
||||
id: frame.id,
|
||||
error: { code: 4001, message: 'invalid_params', data: { reason: 'invalid_params', fields: ['key'] } }
|
||||
error: { code: 4001, message: 'invalid_params', data: { reason: 'invalid_params' } }
|
||||
}
|
||||
: { jsonrpc: '2.0', id: frame.id, result: { value: 'medium' } }
|
||||
)
|
||||
)
|
||||
})
|
||||
@@ -37,15 +51,31 @@ test('typed /reasoning on a canonical dial is refused by name and never sent as
|
||||
try {
|
||||
const address = server.address() as { port: number }
|
||||
await client.connect(`ws://127.0.0.1:${address.port}/api/ws?native_dial=fixture&ticket=one-use`)
|
||||
await client.request('session.resume', { session_id: 's' })
|
||||
|
||||
// reasoningSlashParams('high --global', 's') — the Desktop /reasoning write.
|
||||
for (const params of [
|
||||
{ key: 'reasoning', session_id: 's', value: 'high' },
|
||||
{ key: 'reasoning', session_id: 's', value: 'high', scope: 'global' }
|
||||
]) {
|
||||
await expect(client.request('config.set', params)).rejects.toThrow(/not available on the shared gateway yet/)
|
||||
}
|
||||
// reasoningSlashParams('high', 's') and ('high --session', 's'): the result's `value` is what
|
||||
// applyReasoningSlashResult / writeSessionReasoningEffort read.
|
||||
await expect(
|
||||
client.request('config.set', { key: 'reasoning', session_id: 's', value: 'high' })
|
||||
).resolves.toMatchObject({ value: 'high' })
|
||||
await expect(
|
||||
client.request('config.set', { key: 'reasoning', session_id: 's', value: 'low', scope: 'session' })
|
||||
).resolves.toMatchObject({ value: 'low' })
|
||||
await expect(
|
||||
client.request('config.set', { key: 'reasoning', session_id: 's', value: 'high', scope: 'global' })
|
||||
).rejects.toThrow(/reasoning \(global\) is not available on the shared gateway yet/)
|
||||
|
||||
const mutations = sent.filter(frame => frame.method === 'session.mutate').map(frame => frame.params)
|
||||
expect(mutations).toMatchObject([
|
||||
{
|
||||
session_id: 's',
|
||||
operation: 'reasoning',
|
||||
payload: { effort: 'high' },
|
||||
expected_revision: 4,
|
||||
expected_generation: 2
|
||||
},
|
||||
{ session_id: 's', operation: 'reasoning', payload: { effort: 'low' }, expected_revision: 5 }
|
||||
])
|
||||
expect(sent.filter(frame => frame.method === 'config.set')).toEqual([])
|
||||
// The bare form's read still reaches the owner.
|
||||
await expect(client.request('config.get', { key: 'reasoning', session_id: 's' })).resolves.toEqual({
|
||||
|
||||
@@ -45,8 +45,9 @@ const CANONICAL_PROMPT_EVENTS: Record<string, 'approval' | 'clarify'> = { 'appro
|
||||
|
||||
const ATTACH_REQUIRED = new Set(['prompt.submit', 'approval.respond', 'clarify.respond', 'session.interrupt', 'prompt.cancel', 'session.rewind'])
|
||||
// A branch is a CAS mutation on the PARENT: an un-attached parent (right-click on a sidebar row
|
||||
// that was never opened) has no cached revision, so attach it first to learn one.
|
||||
const PARENT_ATTACH_REQUIRED = new Set(['session.branch_stored', 'session.branch_whole'])
|
||||
// that was never opened) has no cached revision, so attach it first to learn one. Move to project
|
||||
// (`session_key`) is the same CAS mutation on a sidebar row.
|
||||
const PARENT_ATTACH_REQUIRED = new Set(['session.branch_stored', 'session.branch_whole', 'session.workspace.move'])
|
||||
|
||||
// Canonical-only identity keys. The legacy `hermes serve` contract refuses an unknown key as
|
||||
// version skew (4000), so they are stripped on a non-canonical dial. `prompt.submit` keeps its
|
||||
@@ -401,7 +402,7 @@ export class HermesGateway extends JsonRpcGatewayClient {
|
||||
await resume(sid)
|
||||
}
|
||||
|
||||
const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id : null
|
||||
const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id ?? params.session_key : null
|
||||
|
||||
if (typeof parent === 'string' && parent && !this.attached.has(canonicalSessionKey(parent, params.profile))) {
|
||||
await resume(parent)
|
||||
|
||||
@@ -33,6 +33,7 @@ export const deProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
|
||||
movedTo: name => `In ${name} verschoben`,
|
||||
moveFailed: 'Session konnte nicht verschoben werden',
|
||||
moveNoFolder: 'Dieses Projekt hat keinen Ordner, in den verschoben werden kann',
|
||||
moveBusy: 'Beende zuerst den laufenden Durchgang und verschiebe dann den Chat',
|
||||
moveNoProjects: 'Keine anderen Projekte',
|
||||
reveal: 'Im Ordner anzeigen',
|
||||
copyPath: 'Pfad kopieren',
|
||||
|
||||
@@ -33,6 +33,7 @@ export const enProjects: Translations['sidebar']['projects'] = {
|
||||
movedTo: name => `Moved to ${name}`,
|
||||
moveFailed: 'Could not move session',
|
||||
moveNoFolder: 'That project has no folder to move into',
|
||||
moveBusy: 'Stop the running turn, then move the chat',
|
||||
moveNoProjects: 'No other projects',
|
||||
reveal: 'Reveal in folder',
|
||||
copyPath: 'Copy path',
|
||||
|
||||
@@ -33,6 +33,7 @@ export const esProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
|
||||
movedTo: name => `Movido a ${name}`,
|
||||
moveFailed: 'No se pudo mover la sesión',
|
||||
moveNoFolder: 'Ese proyecto no tiene carpeta a la que mover',
|
||||
moveBusy: 'Detén el turno en curso y luego mueve el chat',
|
||||
moveNoProjects: 'No hay otros proyectos',
|
||||
reveal: 'Revelar en carpeta',
|
||||
copyPath: 'Copiar ruta',
|
||||
|
||||
@@ -33,6 +33,7 @@ export const frProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
|
||||
movedTo: name => `Déplacée vers ${name}`,
|
||||
moveFailed: 'Impossible de déplacer la session',
|
||||
moveNoFolder: "Ce projet n'a aucun dossier vers lequel effectuer le déplacement",
|
||||
moveBusy: 'Arrêtez le tour en cours, puis déplacez la discussion',
|
||||
moveNoProjects: 'Aucun autre projet',
|
||||
reveal: 'Afficher dans le dossier',
|
||||
copyPath: 'Copier le chemin',
|
||||
|
||||
@@ -1894,6 +1894,7 @@
|
||||
"sidebar.projects.branchOff": ["ar"],
|
||||
"sidebar.projects.moveFailed": ["ar","ja","zh-hant"],
|
||||
"sidebar.projects.moveNoFolder": ["ar","ja","zh-hant"],
|
||||
"sidebar.projects.moveBusy": ["ar","ja","zh-hant"],
|
||||
"sidebar.projects.moveNoProjects": ["ar","ja","zh-hant"],
|
||||
"sidebar.projects.moveToProject": ["ar","ja","zh-hant"],
|
||||
"sidebar.projects.movedTo": ["ar","ja","zh-hant"],
|
||||
|
||||
@@ -32,6 +32,7 @@ export const ruProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
|
||||
movedTo: name => `Перемещено в ${name}`,
|
||||
moveFailed: 'Не удалось переместить сеанс',
|
||||
moveNoFolder: 'У этого проекта нет папки для перемещения',
|
||||
moveBusy: 'Остановите текущий ход, затем переместите чат',
|
||||
moveNoProjects: 'Нет других проектов',
|
||||
reveal: 'Показать в папке',
|
||||
copyPath: 'Копировать путь',
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface SidebarProjectsTranslations {
|
||||
movedTo: (name: string) => string
|
||||
moveFailed: string
|
||||
moveNoFolder: string
|
||||
moveBusy: string
|
||||
moveNoProjects: string
|
||||
reveal: string
|
||||
copyPath: string
|
||||
|
||||
@@ -33,6 +33,7 @@ export const zhProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
|
||||
movedTo: name => `已移动到 ${name}`,
|
||||
moveFailed: '无法移动会话',
|
||||
moveNoFolder: '该项目没有可移入的文件夹',
|
||||
moveBusy: '请先停止正在运行的回合,再移动该聊天',
|
||||
moveNoProjects: '没有其他项目',
|
||||
reveal: '在文件夹中显示',
|
||||
copyPath: '复制路径',
|
||||
|
||||
@@ -799,10 +799,15 @@ export async function moveSessionToProject(
|
||||
throw new Error(translateNow('sidebar.projects.moveNoFolder'))
|
||||
}
|
||||
|
||||
// The shared owner refuses a move while a turn runs (its frozen policy would change under it).
|
||||
const res = await gatewayRequest<WorkspaceMovePayload>('session.workspace.move', {
|
||||
cwd,
|
||||
session_key: sessionId,
|
||||
...(profile ? { profile } : {})
|
||||
}).catch((err: unknown) => {
|
||||
throw (err as { data?: { reason?: string } })?.data?.reason === 'session_busy'
|
||||
? new Error(translateNow('sidebar.projects.moveBusy'))
|
||||
: err
|
||||
})
|
||||
|
||||
const moved = res.cwd || cwd
|
||||
|
||||
@@ -4472,7 +4472,7 @@ export interface PromptResolveUnknownParams {
|
||||
admission_id: string
|
||||
execution_generation: number
|
||||
}
|
||||
/** ``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``; ``expected_generation`` is required for delete/rewind/reset/branch/model/compress. */
|
||||
/** ``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``; ``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace. ``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project. */
|
||||
export interface SessionMutateParams {
|
||||
session_id: string
|
||||
request_id: string
|
||||
@@ -6396,7 +6396,7 @@ export interface CanonicalRpcMethods {
|
||||
'session.info': { params: CanonicalSessionInfoParams; result: CanonicalSessionInfo }
|
||||
'session.interrupt': { params: CanonicalControlParams; result: CanonicalSessionHandle }
|
||||
'session.list': { params: CanonicalListParams; result: CanonicalListResult }
|
||||
/** Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, compress, import). */
|
||||
/** Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, compress, import). */
|
||||
'session.mutate': { params: SessionMutateParams; result: SessionMutateResult }
|
||||
/** Local operator only: the owner deletes the ended sessions `hermes sessions prune` selected, skipping busy sessions and retained reset owners. */
|
||||
'session.prune': { params: SessionPruneParams; result: SessionPruneResult }
|
||||
|
||||
@@ -35123,7 +35123,7 @@
|
||||
},
|
||||
"SessionMutateParams": {
|
||||
"additionalProperties": false,
|
||||
"description": "``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;\n``expected_generation`` is required for delete/rewind/reset/branch/model/compress.",
|
||||
"description": "``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;\n``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace.\n``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite\nthe session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project.",
|
||||
"properties": {
|
||||
"session_id": {
|
||||
"title": "Session Id",
|
||||
@@ -44448,7 +44448,7 @@
|
||||
},
|
||||
{
|
||||
"name": "session.mutate",
|
||||
"summary": "Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, compress, import).",
|
||||
"summary": "Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, compress, import).",
|
||||
"params": [
|
||||
{
|
||||
"name": "params",
|
||||
|
||||
54
gateway/session_mutation_policy.py
Normal file
54
gateway/session_mutation_policy.py
Normal file
@@ -0,0 +1,54 @@
|
||||
"""Prepare the policy-only session edits: session-scope reasoning and the workspace (Move to project).
|
||||
|
||||
Both rewrite the frozen LocalSessionPolicy the next turn runs under, re-bound like a model switch
|
||||
(policy identity covers config/cwd, so its config-secret reference is re-fingerprinted).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import asdict, replace
|
||||
|
||||
from hermes_state_runtime import RuntimeStoreError
|
||||
|
||||
|
||||
def _rebind(authority, prepared, old, policy, **extra):
|
||||
from gateway.session_policy import bind_launch_key, launch_key
|
||||
from gateway.session_policy_credentials import recover_config_secrets
|
||||
secrets = recover_config_secrets(authority, old) if old.config_secret_ref else {}
|
||||
policy = bind_launch_key(authority, prepared['snapshot']['receipt']['session_id'], policy,
|
||||
launch_key(authority, old), config_secrets=secrets)
|
||||
return dict(prepared, policy=asdict(policy), **extra)
|
||||
|
||||
|
||||
async def prepare_reasoning(authority, live, payload, prepared):
|
||||
"""``/reasoning <level>`` for this session: the level ``build_policy`` freezes at creation."""
|
||||
from gateway.session_policy import restore_policy
|
||||
old = restore_policy(prepared['snapshot']['receipt']['policy'])
|
||||
frozen = old.config()
|
||||
frozen.setdefault('agent', {})['reasoning_effort'] = payload['effort']
|
||||
# An explicit session level wins over a per-model default, as at creation.
|
||||
frozen['agent'].pop('reasoning_overrides', None)
|
||||
return _rebind(authority, prepared, old, replace(old, config_json=json.dumps(frozen)))
|
||||
|
||||
|
||||
async def prepare_workspace(authority, live, payload, prepared):
|
||||
"""Move to project: execution cwd and TERMINAL_CWD move together (restore_policy's invariant)."""
|
||||
import os
|
||||
from gateway.session_policy import restore_policy
|
||||
from hermes_constants import translate_cwd_for_wsl_backend
|
||||
from tui_gateway import git_probe
|
||||
old = restore_policy(prepared['snapshot']['receipt']['policy'])
|
||||
|
||||
def probe():
|
||||
# Off-loop: a stat and up to three `git` spawns.
|
||||
cwd = os.path.abspath(os.path.expanduser(translate_cwd_for_wsl_backend(payload['cwd'])))
|
||||
if not os.path.isdir(cwd):
|
||||
raise RuntimeStoreError('invalid_params')
|
||||
return cwd, git_probe.branch(cwd), git_probe.common_repo_root(cwd)
|
||||
cwd, branch, root = await asyncio.to_thread(probe)
|
||||
terminal = json.loads(old.terminal_json)
|
||||
terminal['TERMINAL_CWD'] = cwd
|
||||
policy = replace(old, cwd=cwd, terminal_json=json.dumps(terminal))
|
||||
return _rebind(authority, prepared, old, policy, git={'branch': branch, 'root': root})
|
||||
|
||||
|
||||
PREPARE = {'reasoning': prepare_reasoning, 'workspace': prepare_workspace}
|
||||
@@ -10,6 +10,8 @@ from contextlib import nullcontext
|
||||
from hermes_state_runtime import RuntimeStoreError, mutate_runtime_session
|
||||
|
||||
_METADATA = frozenset({'rename', 'archive', 'sidebar'})
|
||||
# Prepared off the commit like model, then published as a new frozen policy.
|
||||
_POLICY = frozenset({'model', 'reasoning', 'workspace'})
|
||||
_FIELDS = frozenset({'session_id', 'request_id', 'expected_revision', 'operation', 'payload'})
|
||||
|
||||
|
||||
@@ -73,7 +75,7 @@ async def mutate_session(authority, actor, ref, params):
|
||||
|
||||
|
||||
async def _owned_mutation(authority, actor, ref, params):
|
||||
if (params.get('operation') in {'model', 'compress', 'reset', 'rewind'}
|
||||
if (params.get('operation') in {*_POLICY, 'compress', 'reset', 'rewind'}
|
||||
and ref.session_id not in authority.sessions and 'request_id' in params):
|
||||
_authorize_control(authority, actor, ref, params)
|
||||
live = authority.sessions.get(_owner_ref(authority, ref, params).session_id)
|
||||
@@ -90,7 +92,7 @@ async def _owned_mutation(authority, actor, ref, params):
|
||||
else:
|
||||
async with live.mutation_lock:
|
||||
result = await _mutate_session(authority, actor, ref, params)
|
||||
if params.get('operation') in {'model', 'compress', 'reset'}:
|
||||
if params.get('operation') in {*_POLICY, 'compress', 'reset'}:
|
||||
authority._schedule(ref)
|
||||
return result
|
||||
|
||||
@@ -100,7 +102,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
|
||||
or params['session_id'] != ref.session_id):
|
||||
raise RuntimeStoreError('invalid_params')
|
||||
operation = params['operation']
|
||||
if not isinstance(operation, str):
|
||||
if not isinstance(operation, str) or (operation in _POLICY and params.get('expected_generation') is None):
|
||||
raise RuntimeStoreError('invalid_params')
|
||||
cold_history = False
|
||||
imported_ids = None
|
||||
@@ -140,7 +142,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
|
||||
raise RuntimeStoreError('permission_denied')
|
||||
|
||||
prepared = None
|
||||
if operation in {'model', 'compress'}:
|
||||
if operation in {*_POLICY, 'compress'}:
|
||||
# Its own BEGIN IMMEDIATE, so off the loop like the commit below.
|
||||
prepared = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,
|
||||
principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],
|
||||
@@ -149,7 +151,8 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
|
||||
if 'snapshot' in prepared:
|
||||
from gateway.session_mutation_model import prepare_model
|
||||
from gateway.session_mutation_compress import prepare_compress
|
||||
prepare = {'model': prepare_model, 'compress': prepare_compress}[operation]
|
||||
from gateway.session_mutation_policy import PREPARE
|
||||
prepare = {'model': prepare_model, 'compress': prepare_compress, **PREPARE}[operation]
|
||||
prepared = await prepare(authority, live, params['payload'], prepared)
|
||||
applied = False
|
||||
if prepared.get('status') in {'preview', 'confirmation_required'}:
|
||||
@@ -175,7 +178,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
|
||||
current = authority.db.get_session(ref.session_id)
|
||||
owns_projection = current is not None and (
|
||||
current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))
|
||||
if operation not in {'model', 'reset', 'compress', 'rewind'} or owns_projection:
|
||||
if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:
|
||||
_project_committed(authority, ref, operation, result)
|
||||
if live is not None:
|
||||
if operation == 'rewind' and owns_projection:
|
||||
@@ -192,13 +195,25 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
|
||||
|
||||
def _project_committed(authority, ref, operation, result):
|
||||
"""Publish a committed receipt's runtime projections (safe to repeat on exact retry)."""
|
||||
if operation == 'model':
|
||||
if operation in _POLICY:
|
||||
from gateway.session_local import publish_local_policy
|
||||
publish_local_policy(authority, ref.session_id)
|
||||
# A drain that ran while the receipt committed off-loop saw the new stored policy beside
|
||||
# the old live one and paused; with both now equal, queued input must run, not wait for
|
||||
# the next submit or restart.
|
||||
authority._schedule(ref)
|
||||
if operation in {'reasoning', 'workspace'}:
|
||||
# Every viewer repaints its reasoning pill / workspace from the published policy, as main's
|
||||
# _emit_session_info did after the live change.
|
||||
from gateway.session_local import local_session_info
|
||||
authority.sessions[ref.session_id].event_stream.publish(
|
||||
ref.session_id, local_session_info(authority, ref), event_type='session.info')
|
||||
if operation == 'workspace':
|
||||
# Main's move drops the terminal environment so the next command starts in the new folder.
|
||||
from hermes_state_local import local_receipt
|
||||
from tools.terminal_tool_lifecycle import cleanup_vm
|
||||
for sid in {ref.session_id, local_receipt(authority.db, ref.session_id)['entry']['session_id']}:
|
||||
cleanup_vm(sid)
|
||||
if operation == 'branch':
|
||||
from gateway.session_local_recovery import restore_local_session
|
||||
restore_local_session(authority, result['branched_session_id'])
|
||||
|
||||
@@ -26,12 +26,21 @@ def validate_prepared(db, conn, session_id, prepared):
|
||||
return current
|
||||
|
||||
|
||||
def model_in_transaction(db, conn, session_id, payload, prepared):
|
||||
def _commit_policy(db, conn, session_id, prepared):
|
||||
"""Write the prepared policy over the snapshot it was derived from and bump the generation."""
|
||||
from hermes_state_runtime import _json
|
||||
snapshot = validate_prepared(db, conn, session_id, prepared)
|
||||
saved = snapshot['receipt']
|
||||
saved['policy'] = prepared['policy']
|
||||
conn.execute('UPDATE state_meta SET value=? WHERE key=?', (_json(saved), POLICY_PREFIX + session_id))
|
||||
conn.execute('UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', (session_id,))
|
||||
generation = conn.execute('SELECT runtime_generation FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
|
||||
return snapshot, generation
|
||||
|
||||
|
||||
def model_in_transaction(db, conn, session_id, payload, prepared):
|
||||
from hermes_state_runtime import _json
|
||||
snapshot, generation = _commit_policy(db, conn, session_id, prepared)
|
||||
model = prepared['policy']['model']
|
||||
config = json.loads(prepared['policy']['config_json'])['model']
|
||||
target = snapshot['target']
|
||||
@@ -41,6 +50,28 @@ def model_in_transaction(db, conn, session_id, payload, prepared):
|
||||
model_config = json.loads(row[0] or '{}')
|
||||
model_config['provider'] = config['provider']
|
||||
conn.execute('UPDATE sessions SET model=?,model_config=? WHERE id=?', (model, _json(model_config), target))
|
||||
conn.execute('UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', (session_id,))
|
||||
generation = conn.execute('SELECT runtime_generation FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
|
||||
return {session_id, target}, {'model': model, 'provider': config['provider'], 'execution_generation': generation}
|
||||
|
||||
|
||||
def reasoning_in_transaction(db, conn, session_id, payload, prepared):
|
||||
snapshot, generation = _commit_policy(db, conn, session_id, prepared)
|
||||
return {session_id, snapshot['target']}, {'effort': payload['effort'], 'execution_generation': generation}
|
||||
|
||||
|
||||
def workspace_in_transaction(db, conn, session_id, payload, prepared):
|
||||
"""The policy (execution cwd + TERMINAL_CWD) and every row of the conversation move together:
|
||||
the sidebar groups by the row's cwd/git identity, which a move REPLACES (main's update_session_cwd
|
||||
with replace_git_meta), never merges."""
|
||||
from hermes_state_local import local_conversation_ids
|
||||
snapshot, generation = _commit_policy(db, conn, session_id, prepared)
|
||||
cwd, git = prepared['policy']['cwd'], prepared['git']
|
||||
rows = list(dict.fromkeys([*local_conversation_ids(conn, session_id), snapshot['target']]))
|
||||
conn.executemany('UPDATE sessions SET cwd=?, git_branch=?, git_repo_root=?, '
|
||||
'git_metadata_generation=COALESCE(git_metadata_generation, 0)+1 WHERE id=?',
|
||||
[(cwd, git['branch'] or None, git['root'] or None, sid) for sid in rows])
|
||||
return {session_id, snapshot['target']}, {'cwd': cwd, 'branch': git['branch'] or None,
|
||||
'git_repo_root': git['root'] or None, 'execution_generation': generation}
|
||||
|
||||
|
||||
POLICY_HANDLERS = {'model': model_in_transaction, 'reasoning': reasoning_in_transaction,
|
||||
'workspace': workspace_in_transaction}
|
||||
|
||||
@@ -14,6 +14,14 @@ def validate_action(operation, payload):
|
||||
return
|
||||
if operation == 'branch' and _valid_branch_payload(payload):
|
||||
return
|
||||
# Session-scope ``/reasoning <level>`` and Desktop's Move to project: revision-fenced edits of
|
||||
# the frozen policy (gateway/session_mutation_policy.py).
|
||||
if operation == 'reasoning' and set(payload) == {'effort'} and isinstance(payload['effort'], str):
|
||||
from hermes_constants import parse_reasoning_effort
|
||||
if parse_reasoning_effort(payload['effort']) is not None:
|
||||
return
|
||||
if operation == 'workspace' and set(payload) == {'cwd'} and isinstance(payload['cwd'], str) and payload['cwd'].strip():
|
||||
return
|
||||
if operation == 'compress' and _valid_compress_payload(payload):
|
||||
return
|
||||
if operation in {'delete', 'reset'} and not payload:
|
||||
@@ -62,9 +70,9 @@ def apply_action(db, conn, session_id, operation, payload, *, prepared=None):
|
||||
if operation == 'compress':
|
||||
from hermes_state_mutation_compress import compress_in_transaction
|
||||
return compress_in_transaction(db, conn, session_id, payload, prepared)
|
||||
if operation == 'model':
|
||||
from hermes_state_mutation_prepared import model_in_transaction
|
||||
return model_in_transaction(db, conn, session_id, payload, prepared)
|
||||
if operation in {'model', 'reasoning', 'workspace'}:
|
||||
from hermes_state_mutation_prepared import POLICY_HANDLERS
|
||||
return POLICY_HANDLERS[operation](db, conn, session_id, payload, prepared)
|
||||
from hermes_state_mutation_reset import reset_in_transaction
|
||||
from hermes_state_mutation_branch import branch_in_transaction
|
||||
handlers = {'delete': _delete, 'import': _import, 'rewind': _rewind, 'reset': reset_in_transaction,
|
||||
|
||||
119
tests/gateway/test_session_policy_verbs.py
Normal file
119
tests/gateway/test_session_policy_verbs.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Desktop's typed /reasoning and Move to project on the shared owner (B14, B21 / C-hx-2).
|
||||
|
||||
Main applied both to the live sidecar session. On the owner the next turn runs under the frozen
|
||||
LocalSessionPolicy, so each is a revision-fenced ``session.mutate`` that rewrites that policy.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _owner(tmp_path, monkeypatch, handle):
|
||||
from gateway import run
|
||||
from gateway.config import GatewayConfig
|
||||
from gateway.session import SessionStore
|
||||
from gateway.session_authority import SessionAuthority
|
||||
from gateway.session_controls import AuthorityConnection
|
||||
from gateway.session_local import create_local_session
|
||||
import hermes_state_runtime as rt
|
||||
monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {})
|
||||
store = SessionStore(tmp_path / 'sessions', GatewayConfig())
|
||||
db = store._db
|
||||
runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,
|
||||
_evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,
|
||||
_handle_message=handle, _resolve_session_agent_runtime=lambda **k: ('frozen', {}))
|
||||
runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
|
||||
authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,
|
||||
epoch=rt.begin_runtime_epoch(db, instance_id='owner'))
|
||||
owner = AuthorityConnection(authority, object(), {'user_id': 'human'})
|
||||
start = tmp_path / 'project-a'
|
||||
start.mkdir()
|
||||
ref = create_local_session(authority, owner.actor, dict(request_id='m', source='gui', cwd=str(start),
|
||||
model='frozen', toolsets=[], reasoning='low'))
|
||||
return store, db, authority, owner, ref
|
||||
|
||||
|
||||
def _mutation(db, ref, request_id, operation, payload):
|
||||
snap = db.get_session(ref.session_id)
|
||||
return {'id': request_id, 'method': 'session.mutate', 'params': {
|
||||
'session_id': ref.session_id, 'request_id': request_id, 'operation': operation, 'payload': payload,
|
||||
'expected_revision': snap['runtime_revision'], 'expected_generation': snap['runtime_generation']}}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_reasoning_mutation_is_the_next_turns_reasoning(tmp_path, monkeypatch):
|
||||
from gateway.session_policy import policy_for_source
|
||||
store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, None)
|
||||
live = authority.sessions[ref.session_id]
|
||||
try:
|
||||
before = db.get_session(ref.session_id)
|
||||
frozen_prompt = before['system_prompt']
|
||||
response = await owner.dispatch(_mutation(db, ref, 'r1', 'reasoning', {'effort': 'high'}))
|
||||
assert 'result' in response, response
|
||||
assert response['result']['effort'] == 'high'
|
||||
# The policy the next turn executes under, and what every viewer's session.info reports.
|
||||
assert policy_for_source(authority.runner, live.source).reasoning_config == {'enabled': True, 'effort': 'high'}
|
||||
info = await owner.dispatch({'id': 2, 'method': 'session.info', 'params': {'session_id': ref.session_id}})
|
||||
assert info['result']['reasoning_effort'] == 'high'
|
||||
after = db.get_session(ref.session_id)
|
||||
assert after['runtime_revision'] > before['runtime_revision']
|
||||
assert after['runtime_generation'] == before['runtime_generation'] + 1
|
||||
assert after['system_prompt'] == frozen_prompt
|
||||
# Durable: a restarted owner restores the new level from the receipt.
|
||||
from hermes_state_local import local_receipt
|
||||
assert json.loads(local_receipt(db, ref.session_id)['policy']['config_json'])['agent']['reasoning_effort'] == 'high'
|
||||
bad = await owner.dispatch(_mutation(db, ref, 'r2', 'reasoning', {'effort': 'hgih'}))
|
||||
assert bad['error']['data']['reason'] == 'invalid_params'
|
||||
finally:
|
||||
await owner.close()
|
||||
store.close_all_db_handles()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_move_to_project_rehomes_the_policy_and_row_and_refuses_mid_turn(tmp_path, monkeypatch):
|
||||
from gateway.session_contract import Submission
|
||||
from gateway.session_policy import policy_for_source
|
||||
from hermes_state_local import local_receipt
|
||||
import hermes_state_runtime as rt
|
||||
started, release, seen = asyncio.Event(), asyncio.Event(), []
|
||||
|
||||
async def handle(event):
|
||||
seen.append(policy_for_source(authority.runner, event.source).cwd)
|
||||
started.set()
|
||||
await release.wait()
|
||||
return 'ok'
|
||||
store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, handle)
|
||||
target = tmp_path / 'project-b'
|
||||
target.mkdir()
|
||||
try:
|
||||
queued = await authority.submit(owner.actor, Submission('turn-1', ref, {'text': 'one'}, 'queue'))
|
||||
await asyncio.wait_for(started.wait(), 10)
|
||||
busy = await owner.dispatch(_mutation(db, ref, 'mv-busy', 'workspace', {'cwd': str(target)}))
|
||||
assert busy['error']['data']['reason'] == 'session_busy', busy
|
||||
assert db.get_session(ref.session_id)['cwd'] == str(tmp_path / 'project-a')
|
||||
release.set()
|
||||
async with asyncio.timeout(10):
|
||||
while rt.get_session_admission(db, admission_id=queued.admission_id)['status'] != 'terminal':
|
||||
await asyncio.sleep(0.02)
|
||||
moved = await owner.dispatch(_mutation(db, ref, 'mv', 'workspace', {'cwd': str(target)}))
|
||||
assert moved['result']['cwd'] == str(target), moved
|
||||
policy = local_receipt(db, ref.session_id)['policy']
|
||||
assert policy['cwd'] == str(target) and json.loads(policy['terminal_json'])['TERMINAL_CWD'] == str(target)
|
||||
assert db.get_session(ref.session_id)['cwd'] == str(target)
|
||||
info = await owner.dispatch({'id': 3, 'method': 'session.info', 'params': {'session_id': ref.session_id}})
|
||||
assert info['result']['cwd'] == str(target)
|
||||
started.clear()
|
||||
second = await authority.submit(owner.actor, Submission('turn-2', ref, {'text': 'two'}, 'queue'))
|
||||
await asyncio.wait_for(started.wait(), 10)
|
||||
async with asyncio.timeout(10):
|
||||
while rt.get_session_admission(db, admission_id=second.admission_id)['status'] != 'terminal':
|
||||
await asyncio.sleep(0.02)
|
||||
assert seen == [str(tmp_path / 'project-a'), str(target)]
|
||||
missing = await owner.dispatch(_mutation(db, ref, 'mv-missing', 'workspace', {'cwd': str(tmp_path / 'nope')}))
|
||||
assert missing['error']['data']['reason'] == 'invalid_params'
|
||||
finally:
|
||||
release.set()
|
||||
await owner.close()
|
||||
store.close_all_db_handles()
|
||||
@@ -79,7 +79,9 @@ canonical_method("prompt.resolve_unknown", params=PromptResolveUnknownParams, re
|
||||
|
||||
class SessionMutateParams(Params):
|
||||
"""``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;
|
||||
``expected_generation`` is required for delete/rewind/reset/branch/model/compress."""
|
||||
``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace.
|
||||
``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite
|
||||
the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project."""
|
||||
|
||||
session_id: str
|
||||
request_id: str
|
||||
@@ -101,7 +103,7 @@ class SessionMutateResult(OpenModel):
|
||||
|
||||
canonical_method("session.mutate", params=SessionMutateParams, result=SessionMutateResult,
|
||||
doc="Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, "
|
||||
"delete, rewind, reset, model, compress, import).")
|
||||
"delete, rewind, reset, model, reasoning, workspace, compress, import).")
|
||||
|
||||
|
||||
class SessionPruneParams(Params):
|
||||
|
||||
@@ -25,14 +25,13 @@ _connection_profile_home: contextvars.ContextVar[str | None] = contextvars.Conte
|
||||
# The authority owns every session, its transcript and its admissions: a legacy handler in these
|
||||
# namespaces would write the same state.db behind its receipts and revision fence (a legacy
|
||||
# ``session.delete`` dropped a row the authority still held live; ``session.branch_stored`` built a
|
||||
# second, legacy-owned runtime). Kept: store-wide reads, foreign-history import (new rows only), and
|
||||
# Desktop's project move (``session.workspace.move``), which rewrites only the row's cwd/git grouping
|
||||
# and has no authority verb yet.
|
||||
# second, legacy-owned runtime; ``session.workspace.move`` rewrote only the row, never the frozen
|
||||
# policy: Desktop sends ``session.mutate operation=workspace``). Kept: store-wide reads and
|
||||
# foreign-history import (new rows only).
|
||||
_SESSION_NAMESPACES = ("session.", "prompt.", "message.")
|
||||
_SESSION_FALLBACK_ALLOWED = frozenset({
|
||||
"session.most_recent", "session.active_list", "session.events.stats",
|
||||
"session.foreign.list", "session.foreign.preview", "session.foreign.import",
|
||||
"session.workspace.move",
|
||||
})
|
||||
# Sidecar verbs whose handler acts on PROCESS-global state. In a TUI's own sidecar that state was
|
||||
# that TUI's alone; on the shared owner it is every chat's, Desktop window's and served profile's:
|
||||
|
||||
@@ -39,6 +39,10 @@ function harness() {
|
||||
}
|
||||
}
|
||||
|
||||
if (method === 'session.mutate' && params.operation === 'reasoning') {
|
||||
return { session_id: 'owner', operation: 'reasoning', revision: 8, execution_generation: 4, effort: params.payload.effort }
|
||||
}
|
||||
|
||||
if (method === 'prompt.receipt') {
|
||||
return { status: 'terminal', result: { model: 'm', input_tokens: 5, output_tokens: 7, total_tokens: 12, api_calls: 1 } }
|
||||
}
|
||||
@@ -202,7 +206,7 @@ it('setting writes the shared gateway has no verb for say so instead of a bare i
|
||||
const { request, slash, sys } = harness()
|
||||
|
||||
// dokterdok P3: the canonical config.set accepts only busy / verbose / yolo / model.
|
||||
for (const cmd of ['/theme dark', '/skin mono', '/indicator ascii', '/reasoning high', '/fast fast', '/personality pirate', '/skin']) {
|
||||
for (const cmd of ['/theme dark', '/skin mono', '/indicator ascii', '/reasoning high --global', '/fast fast', '/personality pirate', '/skin']) {
|
||||
slash(cmd)
|
||||
}
|
||||
|
||||
@@ -219,3 +223,22 @@ it('setting writes the shared gateway has no verb for say so instead of a bare i
|
||||
|
||||
expect(notices.some(line => /skin: default/.test(line))).toBe(true)
|
||||
})
|
||||
|
||||
it('session /reasoning <level> is the owner\'s fenced reasoning mutation (B14); display words still refuse', async () => {
|
||||
const { request, slash, sys } = harness()
|
||||
|
||||
slash('/reasoning high')
|
||||
await flush()
|
||||
slash('/reasoning show')
|
||||
await flush()
|
||||
|
||||
expect(request).toHaveBeenCalledWith('session.mutate', expect.objectContaining({
|
||||
session_id: 'owner', operation: 'reasoning', payload: { effort: 'high' }, expected_revision: 7, expected_generation: 3
|
||||
}))
|
||||
expect(request.mock.calls.map(([method]) => method)).not.toContain('config.set')
|
||||
|
||||
const notices = sys.mock.calls.map(([text]) => String(text))
|
||||
|
||||
expect(notices.some(line => /high/.test(line))).toBe(true)
|
||||
expect(notices).toContain('/reasoning is not available on the shared gateway yet')
|
||||
})
|
||||
|
||||
@@ -78,6 +78,39 @@ export async function renameCanonicalSession(
|
||||
return mutation?.result ? String(mutation.result.title ?? title).trim() : undefined
|
||||
}
|
||||
|
||||
// The levels `hermes_constants.parse_reasoning_effort` accepts; the display words are config.yaml writes.
|
||||
const REASONING_EFFORTS = new Set([
|
||||
'none',
|
||||
'false',
|
||||
'disabled',
|
||||
'minimal',
|
||||
'low',
|
||||
'medium',
|
||||
'high',
|
||||
'xhigh',
|
||||
'max',
|
||||
'ultra'
|
||||
])
|
||||
|
||||
/** Session-scope `/reasoning <level>`: the owner's revision-fenced `reasoning` mutation of the frozen
|
||||
* policy. False when the shared gateway has no verb for it (`--global`, a display word). */
|
||||
export function canonicalReasoning(payload: { scope?: string; value: string }, ctx: SlashRunCtx): boolean {
|
||||
const effort = payload.value.trim().toLowerCase()
|
||||
|
||||
if (payload.scope === 'global' || !REASONING_EFFORTS.has(effort)) {
|
||||
return false
|
||||
}
|
||||
|
||||
void mutateCanonical(ctx.gateway.gw, ctx.sid!, 'reasoning', { effort }, ctx.stale)
|
||||
.then(
|
||||
mutation =>
|
||||
mutation?.result && !ctx.stale() && ctx.transcript.sys(t('slashCmd.session.reasoning.current', effort))
|
||||
)
|
||||
.catch(ctx.guardedErr)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/** `/undo` and `/retry`: rewind to before the newest user turn; `/retry` then resubmits its text. */
|
||||
export function canonicalRewind(intent: 'retry' | 'undo', ctx: SlashRunCtx) {
|
||||
const sid = ctx.sid!
|
||||
|
||||
@@ -45,7 +45,7 @@ function modelPayload(arg: string) {
|
||||
return payload
|
||||
}
|
||||
|
||||
export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'rename' | 'rewind'
|
||||
export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'rename' | 'rewind' | 'reasoning'
|
||||
|
||||
/** The snapshot a mutation's CAS tuple was read from; `payload` may derive its target from it. */
|
||||
export interface MutationSnapshot {
|
||||
|
||||
@@ -20,7 +20,7 @@ import { applyConfiguredTuiTheme } from '../../createGatewayEventHandler.js'
|
||||
import { DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES, type IndicatorStyle } from '../../interfaces.js'
|
||||
import { patchOverlayState } from '../../overlayStore.js'
|
||||
import { getUiState, patchUiState } from '../../uiStore.js'
|
||||
import { canonicalUsage } from '../canonicalSessionCommands.js'
|
||||
import { canonicalReasoning, canonicalUsage } from '../canonicalSessionCommands.js'
|
||||
import { runCanonicalSessionControl } from '../canonicalSessionControls.js'
|
||||
import type { SlashCommand, SlashRunCtx } from '../types.js'
|
||||
|
||||
@@ -665,13 +665,15 @@ export const sessionCommands: SlashCommand[] = [
|
||||
)
|
||||
}
|
||||
|
||||
// The shared owner serves this setting's read, not its write (a config.yaml / per-session
|
||||
// setting it has no frozen-policy verb for yet): say so instead of a bare invalid_params.
|
||||
const payload = reasoningConfigPayload(arg, ctx.sid ?? '')
|
||||
|
||||
// The shared owner sets a session level through its frozen-policy mutation; it has no verb for
|
||||
// the config.yaml writes (`--global`, the display words): say so instead of a bare invalid_params.
|
||||
if (ctx.gateway.gw?.isCanonical) {
|
||||
return ctx.transcript.sys(t('canonical.controls.notAvailable', 'reasoning'))
|
||||
return canonicalReasoning(payload, ctx) || ctx.transcript.sys(t('canonical.controls.notAvailable', 'reasoning'))
|
||||
}
|
||||
|
||||
ctx.gateway.rpc<ConfigSetResponse>('config.set', reasoningConfigPayload(arg, ctx.sid ?? '')).then(
|
||||
ctx.gateway.rpc<ConfigSetResponse>('config.set', payload).then(
|
||||
ctx.guarded<ConfigSetResponse>(r => {
|
||||
if (!r.value) {
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user