feat: session goals - server-driven goal loop with independent small-model audit (#2148)

Arm the target button in the composer and the next prompt becomes a goal:
the server keeps the session working toward it (idle tick -> small-model
audit -> continuation) until the objective is verifiably complete, blocked,
or out of budget — even with the UI closed.

Server (packages/web/server/lib/session-goal):
- event-driven loop on the global SSE hub; goal state lives in
  session.metadata.openchamber.goal (merge-safe patches, stale-write guard
  by goal id), so it survives restarts and syncs to every client for free
- the small-model audit (objective + last assistant turn only, language
  pinned to the objective) is the sole termination authority; blocked needs
  3 consecutive verdicts, audit outages tolerate one unaudited continuation
  then stop the goal as resumable-blocked
- hard stops: optional token budget, auto-continuation cap (Resume grants a
  fresh allowance), turn errors; user abort pauses the goal instead of
  blocking it, and resuming over an aborted tail nudges immediately
- token accounting as a snapshot of the latest turn (input + cache.read +
  output), goal-relative via a creation baseline and segmented across
  compactions; a compaction summary skips the audit and continues
- continuations reuse the session's own provider/model/agent/variant

UI:
- three-mode target button (arm / disarm / manage dialog), informational
  goal strip with inline pause/resume and an Evaluating indicator, sidebar
  state glyph, objective length counter (2000-char server clamp),
  read-only completed goals
- goal entry points: composer (sessions and drafts), start-new-session-
  from-answer dialog, plan implement dialog (plan content becomes the
  objective), scheduled tasks (Run as goal + budget)
- Settings -> Chat -> Goal: feature toggle + default token budget with
  three-layer parity (web server, client persistence, VS Code bridge);
  VS Code renders goal state but hides the entry points (the loop runs in
  the web server only)

Notifications: per-turn "ready" notifications are suppressed while a goal
is active; settling sends one final notification (desktop, web-push, APNs
generic titles with the session name as body) honoring the completion
toggle. Error/question/permission notifications are untouched.

Docs: user guide (session-goals) in all 9 locales + sidebar entry,
scheduled-tasks cross-reference, server module DOCUMENTATION.md.
This commit is contained in:
Bohdan Triapitsyn
2026-07-12 01:23:22 +03:00
committed by GitHub
parent 82c039117a
commit bb45164ae8
73 changed files with 3330 additions and 29 deletions
+49
View File
@@ -57,6 +57,10 @@ import {
fetchMessagesForSession,
} from "./session-actions"
import { useInputStore, type SyntheticContextPart } from "./input-store"
import { useSessionGoalArmStore } from "@/stores/useSessionGoalArmStore"
import { setSessionGoal } from "@/lib/sessionGoalActions"
import { wrapSystemReminder } from "@/lib/systemReminder"
import { useUIStore } from "@/stores/useUIStore"
import { useSelectionStore } from "./selection-store"
import { getViewportSessionMemory, useViewportStore, viewportSessionKey } from "./viewport-store"
import { useSessionWorktreeStore } from "./session-worktree-store"
@@ -177,6 +181,7 @@ type AssistantMessageSessionExecution = {
agent: string
instructions: string
createWorktree?: boolean
runAsGoal?: boolean
}
function notifyMessageSent(sessionId: string): void {
@@ -1003,6 +1008,9 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
// ---------------------------------------------------------------------------
// sendMessage — calls SDK, reads domain data from sync
// ---------------------------------------------------------------------------
// Armed goal (composer target button): the sent prompt becomes the goal
// objective; budget comes from the global default setting. Fire-and-forget —
// a failed metadata patch must not fail the send.
sendMessage: async (
content: string,
providerID: string,
@@ -1026,6 +1034,36 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
const draft = get().newSessionDraft
const trimmedAgent = typeof agent === "string" && agent.trim().length > 0 ? agent.trim() : undefined
const goalArm = inputMode !== "shell" && content.trim().length > 0
? useSessionGoalArmStore.getState().consume()
: { armed: false, objectiveOverride: null }
const goalArmed = goalArm.armed
if (goalArmed) {
// Teach the agent the goal protocol from turn one — without this it
// only learns about goal mode from the first server continuation.
const uiState = useUIStore.getState()
const budgetLine = uiState.sessionGoalDefaultBudgetEnabled
? ` A token budget of ${uiState.sessionGoalDefaultBudget} tokens applies to this goal.`
: ""
const goalIntro = wrapSystemReminder(
"Goal mode is active for this session. The user message above defines the goal objective. "
+ "Work toward it across turns; whenever you stop before the objective is verifiably complete, the system will automatically prompt you to continue. "
+ "Progress is evaluated independently after each turn, so end every turn with a clear, factual statement of what is done, what was verified, and what remains."
+ budgetLine,
)
additionalParts = [...(additionalParts ?? []), { text: goalIntro, synthetic: true }]
}
const applyArmedGoal = (goalSessionId: string, goalDirectory: string | null | undefined) => {
if (!goalArmed) return
const uiState = useUIStore.getState()
const tokenBudget = uiState.sessionGoalDefaultBudgetEnabled ? uiState.sessionGoalDefaultBudget : null
const objective = goalArm.objectiveOverride?.trim() || content
void setSessionGoal(goalSessionId, goalDirectory ?? undefined, { objective, tokenBudget }, null)
.catch((error) => {
console.warn("[session-ui-store] failed to set goal from armed send", error)
})
}
// ---- New session from draft ----
if (!options?.sessionId && draft?.open) {
const createdDraftSession = await materializeOpenDraftSession({
@@ -1074,6 +1112,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
})),
})),
})
applyArmedGoal(createdDraftSession.sessionId, createdDraftSession.directory)
return
}
@@ -1153,6 +1192,9 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
})),
})),
})
if (targetSessionId) {
applyArmedGoal(targetSessionId, currentSessionDirectory)
}
},
// ---------------------------------------------------------------------------
@@ -1437,6 +1479,13 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
useDirectoryStore.getState().setDirectory(createdWorktree.path, { showOverlay: false })
}
// "Run as goal" rides the same arm mechanism as the composer target
// button: sendMessage consumes the flag, stamps the goal (objective =
// the composed fork message) and attaches the goal-mode intro part.
// Set explicitly either way so a stray armed flag cannot leak into a
// non-goal fork.
useSessionGoalArmStore.getState().setArmed(execution.runAsGoal === true)
await get().sendMessage(
composeForkSessionMessage(execution.instructions, assistantPlanText),
pID,