feat(tui): support goal budgets

This commit is contained in:
Felipe Coury
2026-05-02 15:55:16 -03:00
parent 35aaa5d9fc
commit 06bebefbfc
37 changed files with 2138 additions and 53 deletions
@@ -3521,6 +3521,52 @@
],
"type": "object"
},
"ThreadGoalBudgetParams": {
"oneOf": [
{
"properties": {
"token_budget": {
"format": "int64",
"type": "integer"
},
"type": {
"enum": [
"tokens"
],
"title": "TokensThreadGoalBudgetParamsType",
"type": "string"
}
},
"required": [
"token_budget",
"type"
],
"title": "TokensThreadGoalBudgetParams",
"type": "object"
},
{
"properties": {
"percent": {
"format": "double",
"type": "number"
},
"type": {
"enum": [
"fiveHourLimitPercent"
],
"title": "FiveHourLimitPercentThreadGoalBudgetParamsType",
"type": "string"
}
},
"required": [
"percent",
"type"
],
"title": "FiveHourLimitPercentThreadGoalBudgetParams",
"type": "object"
}
]
},
"ThreadGoalStatus": {
"enum": [
"active",
@@ -3045,6 +3045,16 @@
},
"ThreadGoal": {
"properties": {
"budget": {
"anyOf": [
{
"$ref": "#/definitions/ThreadGoalBudget"
},
{
"type": "null"
}
]
},
"createdAt": {
"format": "int64",
"type": "integer"
@@ -3089,6 +3099,80 @@
],
"type": "object"
},
"ThreadGoalBudget": {
"oneOf": [
{
"properties": {
"token_budget": {
"format": "int64",
"type": "integer"
},
"type": {
"enum": [
"tokens"
],
"title": "TokensThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"token_budget",
"type"
],
"title": "TokensThreadGoalBudget",
"type": "object"
},
{
"properties": {
"baseline_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"baseline_used_percent": {
"format": "double",
"type": "number"
},
"latest_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"latest_used_percent": {
"format": "double",
"type": "number"
},
"limit_id": {
"type": "string"
},
"percent": {
"format": "double",
"type": "number"
},
"type": {
"enum": [
"fiveHourLimitPercent"
],
"title": "FiveHourLimitPercentThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"baseline_used_percent",
"latest_used_percent",
"limit_id",
"percent",
"type"
],
"title": "FiveHourLimitPercentThreadGoalBudget",
"type": "object"
}
]
},
"ThreadGoalClearedNotification": {
"properties": {
"threadId": {
@@ -15265,6 +15265,16 @@
},
"ThreadGoal": {
"properties": {
"budget": {
"anyOf": [
{
"$ref": "#/definitions/v2/ThreadGoalBudget"
},
{
"type": "null"
}
]
},
"createdAt": {
"format": "int64",
"type": "integer"
@@ -15309,6 +15319,126 @@
],
"type": "object"
},
"ThreadGoalBudget": {
"oneOf": [
{
"properties": {
"token_budget": {
"format": "int64",
"type": "integer"
},
"type": {
"enum": [
"tokens"
],
"title": "TokensThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"token_budget",
"type"
],
"title": "TokensThreadGoalBudget",
"type": "object"
},
{
"properties": {
"baseline_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"baseline_used_percent": {
"format": "double",
"type": "number"
},
"latest_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"latest_used_percent": {
"format": "double",
"type": "number"
},
"limit_id": {
"type": "string"
},
"percent": {
"format": "double",
"type": "number"
},
"type": {
"enum": [
"fiveHourLimitPercent"
],
"title": "FiveHourLimitPercentThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"baseline_used_percent",
"latest_used_percent",
"limit_id",
"percent",
"type"
],
"title": "FiveHourLimitPercentThreadGoalBudget",
"type": "object"
}
]
},
"ThreadGoalBudgetParams": {
"oneOf": [
{
"properties": {
"token_budget": {
"format": "int64",
"type": "integer"
},
"type": {
"enum": [
"tokens"
],
"title": "TokensThreadGoalBudgetParamsType",
"type": "string"
}
},
"required": [
"token_budget",
"type"
],
"title": "TokensThreadGoalBudgetParams",
"type": "object"
},
{
"properties": {
"percent": {
"format": "double",
"type": "number"
},
"type": {
"enum": [
"fiveHourLimitPercent"
],
"title": "FiveHourLimitPercentThreadGoalBudgetParamsType",
"type": "string"
}
},
"required": [
"percent",
"type"
],
"title": "FiveHourLimitPercentThreadGoalBudgetParams",
"type": "object"
}
]
},
"ThreadGoalClearedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -13151,6 +13151,16 @@
},
"ThreadGoal": {
"properties": {
"budget": {
"anyOf": [
{
"$ref": "#/definitions/ThreadGoalBudget"
},
{
"type": "null"
}
]
},
"createdAt": {
"format": "int64",
"type": "integer"
@@ -13195,6 +13205,126 @@
],
"type": "object"
},
"ThreadGoalBudget": {
"oneOf": [
{
"properties": {
"token_budget": {
"format": "int64",
"type": "integer"
},
"type": {
"enum": [
"tokens"
],
"title": "TokensThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"token_budget",
"type"
],
"title": "TokensThreadGoalBudget",
"type": "object"
},
{
"properties": {
"baseline_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"baseline_used_percent": {
"format": "double",
"type": "number"
},
"latest_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"latest_used_percent": {
"format": "double",
"type": "number"
},
"limit_id": {
"type": "string"
},
"percent": {
"format": "double",
"type": "number"
},
"type": {
"enum": [
"fiveHourLimitPercent"
],
"title": "FiveHourLimitPercentThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"baseline_used_percent",
"latest_used_percent",
"limit_id",
"percent",
"type"
],
"title": "FiveHourLimitPercentThreadGoalBudget",
"type": "object"
}
]
},
"ThreadGoalBudgetParams": {
"oneOf": [
{
"properties": {
"token_budget": {
"format": "int64",
"type": "integer"
},
"type": {
"enum": [
"tokens"
],
"title": "TokensThreadGoalBudgetParamsType",
"type": "string"
}
},
"required": [
"token_budget",
"type"
],
"title": "TokensThreadGoalBudgetParams",
"type": "object"
},
{
"properties": {
"percent": {
"format": "double",
"type": "number"
},
"type": {
"enum": [
"fiveHourLimitPercent"
],
"title": "FiveHourLimitPercentThreadGoalBudgetParamsType",
"type": "string"
}
},
"required": [
"percent",
"type"
],
"title": "FiveHourLimitPercentThreadGoalBudgetParams",
"type": "object"
}
]
},
"ThreadGoalClearedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -3,6 +3,16 @@
"definitions": {
"ThreadGoal": {
"properties": {
"budget": {
"anyOf": [
{
"$ref": "#/definitions/ThreadGoalBudget"
},
{
"type": "null"
}
]
},
"createdAt": {
"format": "int64",
"type": "integer"
@@ -47,6 +57,80 @@
],
"type": "object"
},
"ThreadGoalBudget": {
"oneOf": [
{
"properties": {
"token_budget": {
"format": "int64",
"type": "integer"
},
"type": {
"enum": [
"tokens"
],
"title": "TokensThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"token_budget",
"type"
],
"title": "TokensThreadGoalBudget",
"type": "object"
},
{
"properties": {
"baseline_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"baseline_used_percent": {
"format": "double",
"type": "number"
},
"latest_resets_at": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"latest_used_percent": {
"format": "double",
"type": "number"
},
"limit_id": {
"type": "string"
},
"percent": {
"format": "double",
"type": "number"
},
"type": {
"enum": [
"fiveHourLimitPercent"
],
"title": "FiveHourLimitPercentThreadGoalBudgetType",
"type": "string"
}
},
"required": [
"baseline_used_percent",
"latest_used_percent",
"limit_id",
"percent",
"type"
],
"title": "FiveHourLimitPercentThreadGoalBudget",
"type": "object"
}
]
},
"ThreadGoalStatus": {
"enum": [
"active",
@@ -3,4 +3,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ThreadGoalStatus } from "./ThreadGoalStatus";
export type ThreadGoal = { threadId: string, objective: string, status: ThreadGoalStatus, tokenBudget: number | null, tokensUsed: number, timeUsedSeconds: number, createdAt: number, updatedAt: number, };
export type ThreadGoal = { threadId: string, objective: string, status: ThreadGoalStatus, budget: ThreadGoalBudget | null, tokenBudget: number | null, tokensUsed: number, timeUsedSeconds: number, createdAt: number, updatedAt: number, };
@@ -1675,6 +1675,7 @@ mod tests {
thread_id: "goal-thread".to_string(),
objective: Some("ship it".to_string()),
status: None,
budget: None,
token_budget: None,
},
};
@@ -2795,6 +2796,7 @@ mod tests {
thread_id: "thr_123".to_string(),
objective: Some("ship goal mode".to_string()),
status: Some(v2::ThreadGoalStatus::Active),
budget: None,
token_budget: Some(Some(10_000)),
},
};
@@ -2831,6 +2833,7 @@ mod tests {
thread_id: "thr_123".to_string(),
objective: "ship goal mode".to_string(),
status: v2::ThreadGoalStatus::Active,
budget: None,
token_budget: Some(10_000),
tokens_used: 123,
time_used_seconds: 45,
@@ -3991,6 +3991,66 @@ v2_enum_from_core! {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum ThreadGoalBudget {
Tokens {
#[ts(type = "number")]
token_budget: i64,
},
FiveHourLimitPercent {
limit_id: String,
percent: f64,
baseline_used_percent: f64,
#[ts(type = "number | null")]
baseline_resets_at: Option<i64>,
latest_used_percent: f64,
#[ts(type = "number | null")]
latest_resets_at: Option<i64>,
},
}
impl From<codex_protocol::protocol::ThreadGoalBudget> for ThreadGoalBudget {
fn from(value: codex_protocol::protocol::ThreadGoalBudget) -> Self {
match value {
codex_protocol::protocol::ThreadGoalBudget::Tokens { token_budget } => {
Self::Tokens { token_budget }
}
codex_protocol::protocol::ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at,
latest_used_percent,
latest_resets_at,
} => Self::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at,
latest_used_percent,
latest_resets_at,
},
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum ThreadGoalBudgetParams {
Tokens {
#[ts(type = "number")]
token_budget: i64,
},
FiveHourLimitPercent {
percent: f64,
},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -3998,6 +4058,8 @@ pub struct ThreadGoal {
pub thread_id: String,
pub objective: String,
pub status: ThreadGoalStatus,
#[ts(type = "ThreadGoalBudget | null")]
pub budget: Option<ThreadGoalBudget>,
#[ts(type = "number | null")]
pub token_budget: Option<i64>,
#[ts(type = "number")]
@@ -4016,6 +4078,7 @@ impl From<codex_protocol::protocol::ThreadGoal> for ThreadGoal {
thread_id: value.thread_id.to_string(),
objective: value.objective,
status: value.status.into(),
budget: value.budget.map(ThreadGoalBudget::from),
token_budget: value.token_budget,
tokens_used: value.tokens_used,
time_used_seconds: value.time_used_seconds,
@@ -4040,6 +4103,14 @@ pub struct ThreadGoalSetParams {
serialize_with = "super::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional = nullable, type = "ThreadGoalBudgetParams | null")]
pub budget: Option<Option<ThreadGoalBudgetParams>>,
#[serde(
default,
deserialize_with = "super::serde_helpers::deserialize_double_option",
serialize_with = "super::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional = nullable, type = "number | null")]
pub token_budget: Option<Option<i64>>,
}
+37 -7
View File
@@ -153,7 +153,7 @@ Example with notification opt-out:
- `thread/metadata/update` — patch stored thread metadata in sqlite; currently supports updating persisted `gitInfo` fields and returns the refreshed `thread`.
- `thread/memoryMode/set` — experimental; set a thread’s persisted memory eligibility to `"enabled"` or `"disabled"` for either a loaded thread or a stored rollout; returns `{}` on success.
- `memory/reset` — experimental; clear the current `CODEX_HOME/memories` directory and reset persisted memory stage data in sqlite while preserving existing thread memory modes; returns `{}` on success.
- `thread/goal/set` — create, replace, or update the single persisted goal for a materialized thread; returns the current goal and emits `thread/goal/updated`. Supplying a new `objective` replaces the goal and resets usage accounting. Supplying the current non-terminal objective or omitting `objective` updates the existing goal’s status and/or token budget while preserving usage.
- `thread/goal/set` — create, replace, or update the single persisted goal for a materialized thread; returns the current goal and emits `thread/goal/updated`. Supplying a new `objective` replaces the goal and resets usage accounting. Supplying the current non-terminal objective or omitting `objective` updates the existing goal’s status and/or budget while preserving usage.
- `thread/goal/get` — fetch the current persisted goal for a materialized thread; returns `goal: null` when no goal exists.
- `thread/goal/clear` — clear the current persisted goal for a materialized thread; returns whether a goal was removed and emits `thread/goal/cleared` when state changes.
- `thread/goal/updated` — notification emitted whenever a thread goal changes; includes the full current goal.
@@ -483,18 +483,19 @@ Experimental: use `memory/reset` to clear local memory artifacts and sqlite-back
### Example: Set and update a thread goal
Use `thread/goal/set` with an `objective` to create or replace the current goal for a materialized thread. Supplying a new objective resets `tokensUsed`, `timeUsedSeconds`, and `createdAt`. Supplying the current non-terminal objective, or omitting `objective`, updates the existing goal’s status or token budget while preserving usage history. Clients can set `budgetLimited` when they stop because a token budget is exhausted or nearly exhausted; the system also sets it when accounting crosses a configured token budget.
Use `thread/goal/set` with an `objective` to create or replace the current goal for a materialized thread. Supplying a new objective resets `tokensUsed`, `timeUsedSeconds`, and `createdAt`. Supplying the current non-terminal objective, or omitting `objective`, updates the existing goal’s status or budget while preserving usage history. Clients can use the legacy `tokenBudget` field or the structured `budget` field. Structured budgets support fixed tokens and 5h limit percentage points, where the server snapshots the current 5h usage as the baseline and stops the goal after usage increases by the requested percent. Clients can set `budgetLimited` when they stop because a budget is exhausted or nearly exhausted; the system also sets it when accounting crosses a configured budget.
```json
{ "method": "thread/goal/set", "id": 27, "params": {
"threadId": "thr_123",
"objective": "Keep improving the benchmark until p95 latency is under 120ms",
"tokenBudget": 200000
"budget": { "type": "tokens", "tokenBudget": 200000 }
} }
{ "id": 27, "result": { "goal": {
"threadId": "thr_123",
"objective": "Keep improving the benchmark until p95 latency is under 120ms",
"status": "active",
"budget": { "type": "tokens", "tokenBudget": 200000 },
"tokenBudget": 200000,
"tokensUsed": 0,
"timeUsedSeconds": 0,
@@ -505,6 +506,7 @@ Use `thread/goal/set` with an `objective` to create or replace the current goal
"threadId": "thr_123",
"objective": "Keep improving the benchmark until p95 latency is under 120ms",
"status": "active",
"budget": { "type": "tokens", "tokenBudget": 200000 },
"tokenBudget": 200000,
"tokensUsed": 0,
"timeUsedSeconds": 0,
@@ -522,6 +524,7 @@ Use `thread/goal/set` with an `objective` to create or replace the current goal
"threadId": "thr_123",
"objective": "Keep improving the benchmark until p95 latency is under 120ms",
"status": "paused",
"budget": { "type": "tokens", "tokenBudget": 200000 },
"tokenBudget": 200000,
"tokensUsed": 10000,
"timeUsedSeconds": 60,
@@ -530,18 +533,45 @@ Use `thread/goal/set` with an `objective` to create or replace the current goal
} } }
```
```json
{ "method": "thread/goal/set", "id": 29, "params": {
"threadId": "thr_456",
"objective": "Complete the migration without using more than ten percent of the 5h limit",
"budget": { "type": "fiveHourLimitPercent", "percent": 10 }
} }
{ "id": 29, "result": { "goal": {
"threadId": "thr_456",
"objective": "Complete the migration without using more than ten percent of the 5h limit",
"status": "active",
"budget": {
"type": "fiveHourLimitPercent",
"limitId": "codex",
"percent": 10,
"baselineUsedPercent": 42,
"baselineResetsAt": 1776800000,
"latestUsedPercent": 42,
"latestResetsAt": 1776800000
},
"tokenBudget": null,
"tokensUsed": 0,
"timeUsedSeconds": 0,
"createdAt": 1776272400,
"updatedAt": 1776272400
} } }
```
Use `thread/goal/get` to read the current goal without changing it.
```json
{ "method": "thread/goal/get", "id": 29, "params": { "threadId": "thr_123" } }
{ "id": 29, "result": { "goal": null } }
{ "method": "thread/goal/get", "id": 30, "params": { "threadId": "thr_123" } }
{ "id": 30, "result": { "goal": null } }
```
Use `thread/goal/clear` to remove the current goal.
```json
{ "method": "thread/goal/clear", "id": 30, "params": { "threadId": "thr_123" } }
{ "id": 30, "result": { "cleared": true } }
{ "method": "thread/goal/clear", "id": 31, "params": { "threadId": "thr_123" } }
{ "id": 31, "result": { "cleared": true } }
{ "method": "thread/goal/cleared", "params": { "threadId": "thr_123" } }
```
@@ -165,6 +165,8 @@ use codex_app_server_protocol::ThreadDecrementElicitationResponse;
use codex_app_server_protocol::ThreadForkParams;
use codex_app_server_protocol::ThreadForkResponse;
use codex_app_server_protocol::ThreadGoal;
use codex_app_server_protocol::ThreadGoalBudget;
use codex_app_server_protocol::ThreadGoalBudgetParams;
use codex_app_server_protocol::ThreadGoalClearParams;
use codex_app_server_protocol::ThreadGoalClearResponse;
use codex_app_server_protocol::ThreadGoalClearedNotification;
@@ -82,18 +82,25 @@ impl CodexMessageProcessor {
};
let status = params.status.map(thread_goal_status_to_state);
let objective = params.objective.as_deref().map(str::trim);
let budget = match self.state_goal_budget_from_params(&params).await {
Ok(budget) => budget,
Err(message) => {
self.send_invalid_request_error(request_id, message).await;
return;
}
};
if let Some(objective) = objective {
if let Err(message) = validate_thread_goal_objective(objective) {
self.send_invalid_request_error(request_id, message).await;
return;
}
if let Err(message) = validate_goal_budget(params.token_budget.flatten()) {
if let Err(message) = validate_goal_budget(budget.as_ref()) {
self.send_invalid_request_error(request_id, message).await;
return;
}
} else if let Some(token_budget) = params.token_budget
&& let Err(message) = validate_goal_budget(token_budget)
} else if (params.budget.is_some() || params.token_budget.is_some())
&& let Err(message) = validate_goal_budget(budget.as_ref())
{
self.send_invalid_request_error(request_id, message).await;
return;
@@ -109,13 +116,14 @@ impl CodexMessageProcessor {
if let Some(goal) = goal.as_ref().filter(|goal| {
goal.objective == objective
&& goal.status != codex_state::ThreadGoalStatus::Complete
&& supports_thread_goal_update_budget(budget.as_ref())
}) {
state_db
.update_thread_goal(
thread_id,
codex_state::ThreadGoalUpdate {
status,
token_budget: params.token_budget,
token_budget: legacy_token_budget_update(budget.as_ref()),
expected_goal_id: Some(goal.goal_id.clone()),
},
)
@@ -129,11 +137,11 @@ impl CodexMessageProcessor {
})
} else {
state_db
.replace_thread_goal(
.replace_thread_goal_with_budget(
thread_id,
objective,
status.unwrap_or(codex_state::ThreadGoalStatus::Active),
params.token_budget.flatten(),
budget.clone().flatten(),
)
.await
}
@@ -146,7 +154,7 @@ impl CodexMessageProcessor {
thread_id,
codex_state::ThreadGoalUpdate {
status,
token_budget: params.token_budget,
token_budget: legacy_token_budget_update(budget.as_ref()),
expected_goal_id: None,
},
)
@@ -219,6 +227,53 @@ impl CodexMessageProcessor {
.await;
}
async fn state_goal_budget_from_params(
&self,
params: &ThreadGoalSetParams,
) -> Result<Option<Option<codex_state::ThreadGoalBudget>>, String> {
if let Some(budget) = params.budget.clone() {
return match budget {
Some(ThreadGoalBudgetParams::Tokens { token_budget }) => {
Ok(Some(Some(codex_state::ThreadGoalBudget::Tokens {
token_budget,
})))
}
Some(ThreadGoalBudgetParams::FiveHourLimitPercent { percent }) => {
let (snapshot, snapshots_by_limit_id) = self
.fetch_account_rate_limits()
.await
.map_err(|err| err.message)?;
let snapshot = snapshots_by_limit_id
.get("codex")
.cloned()
.unwrap_or(snapshot);
let Some(window) = snapshot.primary else {
return Err(
"cannot set a five-hour-limit goal because current Codex usage data is unavailable"
.to_string(),
);
};
let limit_id = snapshot.limit_id.unwrap_or_else(|| "codex".to_string());
Ok(Some(Some(
codex_state::ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent: window.used_percent,
baseline_resets_at: window.resets_at,
latest_used_percent: window.used_percent,
latest_resets_at: window.resets_at,
},
)))
}
None => Ok(Some(None)),
};
}
Ok(params.token_budget.map(|token_budget| {
token_budget.map(|token_budget| codex_state::ThreadGoalBudget::Tokens { token_budget })
}))
}
pub(super) async fn thread_goal_clear(
&self,
request_id: ConnectionRequestId,
@@ -438,13 +493,42 @@ impl CodexMessageProcessor {
}
}
fn validate_goal_budget(value: Option<i64>) -> Result<(), String> {
if let Some(value) = value
&& value <= 0
{
return Err("goal budgets must be positive when provided".to_string());
fn supports_thread_goal_update_budget(
budget: Option<&Option<codex_state::ThreadGoalBudget>>,
) -> bool {
matches!(
budget,
None | Some(None) | Some(Some(codex_state::ThreadGoalBudget::Tokens { .. }))
)
}
fn legacy_token_budget_update(
budget: Option<&Option<codex_state::ThreadGoalBudget>>,
) -> Option<Option<i64>> {
budget.map(|budget| {
budget
.as_ref()
.and_then(codex_state::ThreadGoalBudget::token_budget)
})
}
fn validate_goal_budget(
value: Option<&Option<codex_state::ThreadGoalBudget>>,
) -> Result<(), String> {
let Some(Some(value)) = value else {
return Ok(());
};
match value {
codex_state::ThreadGoalBudget::Tokens { token_budget } if *token_budget <= 0 => {
Err("goal budgets must be positive when provided".to_string())
}
codex_state::ThreadGoalBudget::FiveHourLimitPercent { percent, .. }
if !percent.is_finite() || *percent <= 0.0 || *percent > 100.0 =>
{
Err("five-hour-limit goal budgets must be a percent from 0 to 100".to_string())
}
_ => Ok(()),
}
Ok(())
}
fn thread_goal_status_to_state(status: ThreadGoalStatus) -> codex_state::ThreadGoalStatus {
@@ -470,6 +554,7 @@ pub(super) fn api_thread_goal_from_state(goal: codex_state::ThreadGoal) -> Threa
thread_id: goal.thread_id.to_string(),
objective: goal.objective,
status: thread_goal_status_from_state(goal.status),
budget: goal.budget.map(api_thread_goal_budget_from_state),
token_budget: goal.token_budget,
tokens_used: goal.tokens_used,
time_used_seconds: goal.time_used_seconds,
@@ -477,3 +562,26 @@ pub(super) fn api_thread_goal_from_state(goal: codex_state::ThreadGoal) -> Threa
updated_at: goal.updated_at.timestamp(),
}
}
fn api_thread_goal_budget_from_state(budget: codex_state::ThreadGoalBudget) -> ThreadGoalBudget {
match budget {
codex_state::ThreadGoalBudget::Tokens { token_budget } => {
ThreadGoalBudget::Tokens { token_budget }
}
codex_state::ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at,
latest_used_percent,
latest_resets_at,
} => ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at,
latest_used_percent,
latest_resets_at,
},
}
}
@@ -23,6 +23,7 @@ fn thread_goal_updated_notification() -> ServerNotification {
thread_id: "thread-1".to_string(),
objective: "ship goal mode".to_string(),
status: ThreadGoalStatus::Active,
budget: None,
token_budget: None,
tokens_used: 0,
time_used_seconds: 0,
+161 -3
View File
@@ -18,6 +18,7 @@ use codex_protocol::models::ResponseInputItem;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ThreadGoal;
use codex_protocol::protocol::ThreadGoalBudget;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
use codex_protocol::protocol::TokenUsage;
@@ -44,6 +45,12 @@ pub(crate) struct SetGoalRequest {
pub(crate) struct CreateGoalRequest {
pub(crate) objective: String,
pub(crate) token_budget: Option<i64>,
pub(crate) budget: Option<GoalBudgetRequest>,
}
pub(crate) enum GoalBudgetRequest {
Tokens(i64),
FiveHourLimitPercent(f64),
}
static CONTINUATION_PROMPT_TEMPLATE: LazyLock<Template> =
@@ -494,10 +501,13 @@ impl Session {
let CreateGoalRequest {
objective,
token_budget,
budget,
} = request;
validate_goal_budget(token_budget)?;
let budget = budget.or_else(|| token_budget.map(GoalBudgetRequest::Tokens));
validate_goal_budget_request(budget.as_ref())?;
let objective = objective.trim();
validate_thread_goal_objective(objective).map_err(anyhow::Error::msg)?;
let budget = self.state_budget_from_request(budget).await?;
let state_db = self.require_state_db_for_thread_goals().await?;
self.account_thread_goal_wall_clock_usage(
@@ -506,11 +516,11 @@ impl Session {
)
.await?;
let goal = state_db
.insert_thread_goal(
.insert_thread_goal_with_budget(
self.conversation_id,
objective,
codex_state::ThreadGoalStatus::Active,
token_budget,
budget,
)
.await?
.ok_or_else(|| {
@@ -544,6 +554,43 @@ impl Session {
Ok(goal)
}
async fn state_budget_from_request(
&self,
budget: Option<GoalBudgetRequest>,
) -> anyhow::Result<Option<codex_state::ThreadGoalBudget>> {
let Some(budget) = budget else {
return Ok(None);
};
match budget {
GoalBudgetRequest::Tokens(token_budget) => {
Ok(Some(codex_state::ThreadGoalBudget::Tokens { token_budget }))
}
GoalBudgetRequest::FiveHourLimitPercent(percent) => {
let snapshot = self.latest_rate_limits().await;
let Some(snapshot) = snapshot else {
anyhow::bail!(
"cannot create a five-hour-limit goal because current Codex usage data is unavailable; retry after rate-limit data loads"
);
};
let Some(window) = snapshot.primary else {
anyhow::bail!(
"cannot create a five-hour-limit goal because the current Codex 5h limit is unavailable"
);
};
let limit_id = snapshot.limit_id.unwrap_or_else(|| "codex".to_string());
Ok(Some(codex_state::ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent: window.used_percent,
baseline_resets_at: window.resets_at,
latest_used_percent: window.used_percent,
latest_resets_at: window.resets_at,
}))
}
}
}
async fn apply_external_thread_goal_status(
self: &Arc<Self>,
status: codex_state::ThreadGoalStatus,
@@ -894,6 +941,74 @@ impl Session {
Ok(())
}
pub(crate) async fn account_thread_goal_five_hour_limit_snapshot(
&self,
turn_context: &TurnContext,
snapshot: &codex_protocol::protocol::RateLimitSnapshot,
) -> anyhow::Result<()> {
if !self.enabled(Feature::Goals) {
return Ok(());
}
if should_ignore_goal_for_mode(turn_context.collaboration_mode.mode) {
return Ok(());
}
let Some(window) = snapshot.primary.as_ref() else {
return Ok(());
};
let Some(state_db) = self.state_db_for_thread_goals().await? else {
return Ok(());
};
let limit_id = snapshot.limit_id.as_deref().unwrap_or("codex");
let expected_goal_id = {
let accounting = self.goal_runtime.accounting.lock().await;
accounting.wall_clock.active_goal_id()
};
let outcome = state_db
.account_thread_goal_five_hour_limit(
self.conversation_id,
limit_id,
window.used_percent,
window.resets_at,
expected_goal_id.as_deref(),
)
.await?;
let budget_limit_was_already_reported = {
let reported_goal_id = self.goal_runtime.budget_limit_reported_goal_id.lock().await;
expected_goal_id
.as_deref()
.is_some_and(|goal_id| reported_goal_id.as_deref() == Some(goal_id))
};
let goal = match outcome {
codex_state::ThreadGoalAccountingOutcome::Updated(goal) => goal,
codex_state::ThreadGoalAccountingOutcome::Unchanged(_) => return Ok(()),
};
let should_steer_budget_limit = goal.status == codex_state::ThreadGoalStatus::BudgetLimited
&& !budget_limit_was_already_reported;
let goal_status = goal.status;
let goal_id = goal.goal_id.clone();
if goal_status != codex_state::ThreadGoalStatus::BudgetLimited {
*self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
}
let goal = protocol_goal_from_state(goal);
self.send_event(
turn_context,
EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
thread_id: self.conversation_id,
turn_id: Some(turn_context.sub_id.clone()),
goal: goal.clone(),
}),
)
.await;
if should_steer_budget_limit {
let item = budget_limit_steering_item(&goal);
if self.inject_response_items(vec![item]).await.is_err() {
tracing::debug!("skipping 5h budget-limit goal steering because no turn is active");
}
*self.goal_runtime.budget_limit_reported_goal_id.lock().await = Some(goal_id);
}
Ok(())
}
async fn account_thread_goal_before_external_mutation(&self) -> anyhow::Result<()> {
if let Some(turn_context) = self.active_turn_context().await {
return self
@@ -1414,6 +1529,7 @@ pub(crate) fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadG
thread_id: goal.thread_id,
objective: goal.objective,
status: protocol_goal_status_from_state(goal.status),
budget: goal.budget.map(protocol_goal_budget_from_state),
token_budget: goal.token_budget,
tokens_used: goal.tokens_used,
time_used_seconds: goal.time_used_seconds,
@@ -1422,6 +1538,29 @@ pub(crate) fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadG
}
}
fn protocol_goal_budget_from_state(budget: codex_state::ThreadGoalBudget) -> ThreadGoalBudget {
match budget {
codex_state::ThreadGoalBudget::Tokens { token_budget } => {
ThreadGoalBudget::Tokens { token_budget }
}
codex_state::ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at,
latest_used_percent,
latest_resets_at,
} => ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at,
latest_used_percent,
latest_resets_at,
},
}
}
pub(crate) fn protocol_goal_status_from_state(
status: codex_state::ThreadGoalStatus,
) -> ThreadGoalStatus {
@@ -1453,6 +1592,21 @@ pub(crate) fn validate_goal_budget(value: Option<i64>) -> anyhow::Result<()> {
Ok(())
}
pub(crate) fn validate_goal_budget_request(
value: Option<&GoalBudgetRequest>,
) -> anyhow::Result<()> {
match value {
Some(GoalBudgetRequest::Tokens(token_budget)) => validate_goal_budget(Some(*token_budget)),
Some(GoalBudgetRequest::FiveHourLimitPercent(percent)) => {
if !percent.is_finite() || *percent <= 0.0 || *percent > 100.0 {
anyhow::bail!("five-hour-limit goal budgets must be a percent from 0 to 100");
}
Ok(())
}
None => Ok(()),
}
}
pub(crate) fn goal_token_delta_for_usage(usage: &TokenUsage) -> i64 {
usage
.non_cached_input()
@@ -1518,6 +1672,7 @@ mod tests {
thread_id: ThreadId::new(),
objective: "finish the stack".to_string(),
status: ThreadGoalStatus::Active,
budget: None,
token_budget: Some(10_000),
tokens_used: 1_234,
time_used_seconds: 56,
@@ -1543,6 +1698,7 @@ mod tests {
thread_id: ThreadId::new(),
objective: "finish the stack".to_string(),
status: ThreadGoalStatus::BudgetLimited,
budget: None,
token_budget: Some(10_000),
tokens_used: 10_100,
time_used_seconds: 56,
@@ -1568,6 +1724,7 @@ mod tests {
thread_id: ThreadId::new(),
objective: objective.to_string(),
status: ThreadGoalStatus::Active,
budget: None,
token_budget: None,
tokens_used: 0,
time_used_seconds: 0,
@@ -1578,6 +1735,7 @@ mod tests {
thread_id: ThreadId::new(),
objective: objective.to_string(),
status: ThreadGoalStatus::BudgetLimited,
budget: None,
token_budget: Some(10_000),
tokens_used: 10_100,
time_used_seconds: 56,
+11 -1
View File
@@ -2852,11 +2852,21 @@ impl Session {
) {
{
let mut state = self.state.lock().await;
state.set_rate_limits(new_rate_limits);
state.set_rate_limits(new_rate_limits.clone());
}
if let Err(err) = self
.account_thread_goal_five_hour_limit_snapshot(turn_context, &new_rate_limits)
.await
{
tracing::warn!("failed to account five-hour-limit goal progress: {err}");
}
self.send_token_count_event(turn_context).await;
}
pub(crate) async fn latest_rate_limits(&self) -> Option<RateLimitSnapshot> {
self.state.lock().await.latest_rate_limits.clone()
}
pub(crate) async fn mcp_dependency_prompted(&self) -> HashSet<String> {
let state = self.state.lock().await;
state.mcp_dependency_prompted()
+21
View File
@@ -6,6 +6,7 @@
use crate::function_tool::FunctionCallError;
use crate::goals::CreateGoalRequest;
use crate::goals::GoalBudgetRequest;
use crate::goals::GoalRuntimeEvent;
use crate::goals::SetGoalRequest;
use crate::session::session::Session;
@@ -33,6 +34,14 @@ pub struct GoalHandler;
struct CreateGoalArgs {
objective: String,
token_budget: Option<i64>,
budget: Option<CreateGoalBudgetArgs>,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum CreateGoalBudgetArgs {
Tokens { token_budget: i64 },
FiveHourLimitPercent { percent: f64 },
}
#[derive(Debug, Deserialize)]
@@ -134,6 +143,7 @@ async fn handle_create_goal(
CreateGoalRequest {
objective: args.objective,
token_budget: args.token_budget,
budget: args.budget.map(goal_budget_request_from_args),
},
)
.await
@@ -153,6 +163,15 @@ async fn handle_create_goal(
goal_response(Some(goal), CompletionBudgetReport::Omit)
}
fn goal_budget_request_from_args(args: CreateGoalBudgetArgs) -> GoalBudgetRequest {
match args {
CreateGoalBudgetArgs::Tokens { token_budget } => GoalBudgetRequest::Tokens(token_budget),
CreateGoalBudgetArgs::FiveHourLimitPercent { percent } => {
GoalBudgetRequest::FiveHourLimitPercent(percent)
}
}
}
async fn handle_update_goal(
session: &Arc<Session>,
turn_context: &TurnContext,
@@ -231,6 +250,7 @@ mod tests {
thread_id: ThreadId::new(),
objective: "Keep optimizing".to_string(),
status: ThreadGoalStatus::Complete,
budget: None,
token_budget: Some(10_000),
tokens_used: 3_250,
time_used_seconds: 75,
@@ -259,6 +279,7 @@ mod tests {
thread_id: ThreadId::new(),
objective: "Write a poem".to_string(),
status: ThreadGoalStatus::Complete,
budget: None,
token_budget: None,
tokens_used: 120,
time_used_seconds: 0,
+24 -2
View File
@@ -3613,7 +3613,26 @@ pub fn validate_thread_goal_objective(value: &str) -> Result<(), String> {
Ok(())
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", export_to = "protocol/")]
pub enum ThreadGoalBudget {
Tokens {
token_budget: i64,
},
FiveHourLimitPercent {
limit_id: String,
percent: f64,
baseline_used_percent: f64,
#[ts(type = "number | null")]
baseline_resets_at: Option<i64>,
latest_used_percent: f64,
#[ts(type = "number | null")]
latest_resets_at: Option<i64>,
},
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "protocol/")]
pub struct ThreadGoal {
@@ -3622,6 +3641,9 @@ pub struct ThreadGoal {
pub status: ThreadGoalStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub budget: Option<ThreadGoalBudget>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub token_budget: Option<i64>,
pub tokens_used: i64,
pub time_used_seconds: i64,
@@ -3629,7 +3651,7 @@ pub struct ThreadGoal {
pub updated_at: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "protocol/")]
pub struct ThreadGoalUpdatedEvent {
@@ -0,0 +1,11 @@
ALTER TABLE thread_goals ADD COLUMN budget_kind TEXT CHECK(budget_kind IN ('tokens', 'five_hour_limit_percent'));
ALTER TABLE thread_goals ADD COLUMN budget_limit_id TEXT;
ALTER TABLE thread_goals ADD COLUMN budget_percent REAL;
ALTER TABLE thread_goals ADD COLUMN budget_baseline_used_percent REAL;
ALTER TABLE thread_goals ADD COLUMN budget_baseline_resets_at INTEGER;
ALTER TABLE thread_goals ADD COLUMN budget_latest_used_percent REAL;
ALTER TABLE thread_goals ADD COLUMN budget_latest_resets_at INTEGER;
UPDATE thread_goals
SET budget_kind = 'tokens'
WHERE token_budget IS NOT NULL;
+1
View File
@@ -43,6 +43,7 @@ pub use model::Stage1JobClaimOutcome;
pub use model::Stage1Output;
pub use model::Stage1StartupClaimParams;
pub use model::ThreadGoal;
pub use model::ThreadGoalBudget;
pub use model::ThreadGoalStatus;
pub use model::ThreadMetadata;
pub use model::ThreadMetadataBuilder;
+1
View File
@@ -25,6 +25,7 @@ pub use memories::Stage1JobClaimOutcome;
pub use memories::Stage1Output;
pub use memories::Stage1StartupClaimParams;
pub use thread_goal::ThreadGoal;
pub use thread_goal::ThreadGoalBudget;
pub use thread_goal::ThreadGoalStatus;
pub use thread_metadata::Anchor;
pub use thread_metadata::BackfillStats;
+87 -2
View File
@@ -49,12 +49,37 @@ impl TryFrom<&str> for ThreadGoalStatus {
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq)]
pub enum ThreadGoalBudget {
Tokens {
token_budget: i64,
},
FiveHourLimitPercent {
limit_id: String,
percent: f64,
baseline_used_percent: f64,
baseline_resets_at: Option<i64>,
latest_used_percent: f64,
latest_resets_at: Option<i64>,
},
}
impl ThreadGoalBudget {
pub fn token_budget(&self) -> Option<i64> {
match self {
Self::Tokens { token_budget } => Some(*token_budget),
Self::FiveHourLimitPercent { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ThreadGoal {
pub thread_id: ThreadId,
pub goal_id: String,
pub objective: String,
pub status: ThreadGoalStatus,
pub budget: Option<ThreadGoalBudget>,
pub token_budget: Option<i64>,
pub tokens_used: i64,
pub time_used_seconds: i64,
@@ -67,6 +92,13 @@ pub(crate) struct ThreadGoalRow {
pub goal_id: String,
pub objective: String,
pub status: String,
pub budget_kind: Option<String>,
pub budget_limit_id: Option<String>,
pub budget_percent: Option<f64>,
pub budget_baseline_used_percent: Option<f64>,
pub budget_baseline_resets_at: Option<i64>,
pub budget_latest_used_percent: Option<f64>,
pub budget_latest_resets_at: Option<i64>,
pub token_budget: Option<i64>,
pub tokens_used: i64,
pub time_used_seconds: i64,
@@ -81,6 +113,13 @@ impl ThreadGoalRow {
goal_id: row.try_get("goal_id")?,
objective: row.try_get("objective")?,
status: row.try_get("status")?,
budget_kind: row.try_get("budget_kind")?,
budget_limit_id: row.try_get("budget_limit_id")?,
budget_percent: row.try_get("budget_percent")?,
budget_baseline_used_percent: row.try_get("budget_baseline_used_percent")?,
budget_baseline_resets_at: row.try_get("budget_baseline_resets_at")?,
budget_latest_used_percent: row.try_get("budget_latest_used_percent")?,
budget_latest_resets_at: row.try_get("budget_latest_resets_at")?,
token_budget: row.try_get("token_budget")?,
tokens_used: row.try_get("tokens_used")?,
time_used_seconds: row.try_get("time_used_seconds")?,
@@ -94,12 +133,18 @@ impl TryFrom<ThreadGoalRow> for ThreadGoal {
type Error = anyhow::Error;
fn try_from(row: ThreadGoalRow) -> Result<Self> {
let budget = thread_goal_budget_from_row(&row)?;
let token_budget = budget
.as_ref()
.and_then(ThreadGoalBudget::token_budget)
.or(row.token_budget);
Ok(Self {
thread_id: ThreadId::try_from(row.thread_id)?,
goal_id: row.goal_id,
objective: row.objective,
status: ThreadGoalStatus::try_from(row.status.as_str())?,
token_budget: row.token_budget,
budget,
token_budget,
tokens_used: row.tokens_used,
time_used_seconds: row.time_used_seconds,
created_at: epoch_millis_to_datetime(row.created_at_ms)?,
@@ -107,3 +152,43 @@ impl TryFrom<ThreadGoalRow> for ThreadGoal {
})
}
}
fn thread_goal_budget_from_row(row: &ThreadGoalRow) -> Result<Option<ThreadGoalBudget>> {
match row.budget_kind.as_deref() {
Some("tokens") => {
let token_budget = row
.token_budget
.ok_or_else(|| anyhow!("token goal budget missing token_budget"))?;
Ok(Some(ThreadGoalBudget::Tokens { token_budget }))
}
Some("five_hour_limit_percent") => {
let limit_id = row
.budget_limit_id
.clone()
.ok_or_else(|| anyhow!("5h goal budget missing budget_limit_id"))?;
let percent = row
.budget_percent
.ok_or_else(|| anyhow!("5h goal budget missing budget_percent"))?;
let baseline_used_percent = row
.budget_baseline_used_percent
.ok_or_else(|| anyhow!("5h goal budget missing budget_baseline_used_percent"))?;
let latest_used_percent = row
.budget_latest_used_percent
.unwrap_or(baseline_used_percent);
Ok(Some(ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at: row.budget_baseline_resets_at,
latest_used_percent,
latest_resets_at: row
.budget_latest_resets_at
.or(row.budget_baseline_resets_at),
}))
}
Some(other) => Err(anyhow!("unknown thread goal budget kind `{other}`")),
None => Ok(row
.token_budget
.map(|token_budget| ThreadGoalBudget::Tokens { token_budget })),
}
}
+316 -6
View File
@@ -7,6 +7,17 @@ pub struct ThreadGoalUpdate {
pub expected_goal_id: Option<String>,
}
struct GoalBudgetColumns<'a> {
kind: Option<&'static str>,
limit_id: Option<&'a str>,
percent: Option<f64>,
baseline_used_percent: Option<f64>,
baseline_resets_at: Option<i64>,
latest_used_percent: Option<f64>,
latest_resets_at: Option<i64>,
token_budget: Option<i64>,
}
pub enum ThreadGoalAccountingOutcome {
Unchanged(Option<crate::ThreadGoal>),
Updated(crate::ThreadGoal),
@@ -32,6 +43,13 @@ SELECT
goal_id,
objective,
status,
budget_kind,
budget_limit_id,
budget_percent,
budget_baseline_used_percent,
budget_baseline_resets_at,
budget_latest_used_percent,
budget_latest_resets_at,
token_budget,
tokens_used,
time_used_seconds,
@@ -54,10 +72,28 @@ WHERE thread_id = ?
objective: &str,
status: crate::ThreadGoalStatus,
token_budget: Option<i64>,
) -> anyhow::Result<crate::ThreadGoal> {
self.replace_thread_goal_with_budget(
thread_id,
objective,
status,
token_budget.map(|token_budget| crate::ThreadGoalBudget::Tokens { token_budget }),
)
.await
}
pub async fn replace_thread_goal_with_budget(
&self,
thread_id: ThreadId,
objective: &str,
status: crate::ThreadGoalStatus,
budget: Option<crate::ThreadGoalBudget>,
) -> anyhow::Result<crate::ThreadGoal> {
let goal_id = Uuid::new_v4().to_string();
let now_ms = datetime_to_epoch_millis(Utc::now());
let status = status_after_budget_limit(status, /*tokens_used*/ 0, token_budget);
let budget_columns = budget_columns(budget.as_ref());
let status =
status_after_budget_limit(status, /*tokens_used*/ 0, budget_columns.token_budget);
let row = sqlx::query(
r#"
INSERT INTO thread_goals (
@@ -65,16 +101,30 @@ INSERT INTO thread_goals (
goal_id,
objective,
status,
budget_kind,
budget_limit_id,
budget_percent,
budget_baseline_used_percent,
budget_baseline_resets_at,
budget_latest_used_percent,
budget_latest_resets_at,
token_budget,
tokens_used,
time_used_seconds,
created_at_ms,
updated_at_ms
) VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?)
ON CONFLICT(thread_id) DO UPDATE SET
goal_id = excluded.goal_id,
objective = excluded.objective,
status = excluded.status,
budget_kind = excluded.budget_kind,
budget_limit_id = excluded.budget_limit_id,
budget_percent = excluded.budget_percent,
budget_baseline_used_percent = excluded.budget_baseline_used_percent,
budget_baseline_resets_at = excluded.budget_baseline_resets_at,
budget_latest_used_percent = excluded.budget_latest_used_percent,
budget_latest_resets_at = excluded.budget_latest_resets_at,
token_budget = excluded.token_budget,
tokens_used = 0,
time_used_seconds = 0,
@@ -85,6 +135,13 @@ RETURNING
goal_id,
objective,
status,
budget_kind,
budget_limit_id,
budget_percent,
budget_baseline_used_percent,
budget_baseline_resets_at,
budget_latest_used_percent,
budget_latest_resets_at,
token_budget,
tokens_used,
time_used_seconds,
@@ -96,7 +153,14 @@ RETURNING
.bind(goal_id)
.bind(objective)
.bind(status.as_str())
.bind(token_budget)
.bind(budget_columns.kind)
.bind(budget_columns.limit_id)
.bind(budget_columns.percent)
.bind(budget_columns.baseline_used_percent)
.bind(budget_columns.baseline_resets_at)
.bind(budget_columns.latest_used_percent)
.bind(budget_columns.latest_resets_at)
.bind(budget_columns.token_budget)
.bind(now_ms)
.bind(now_ms)
.fetch_one(self.pool.as_ref())
@@ -111,10 +175,28 @@ RETURNING
objective: &str,
status: crate::ThreadGoalStatus,
token_budget: Option<i64>,
) -> anyhow::Result<Option<crate::ThreadGoal>> {
self.insert_thread_goal_with_budget(
thread_id,
objective,
status,
token_budget.map(|token_budget| crate::ThreadGoalBudget::Tokens { token_budget }),
)
.await
}
pub async fn insert_thread_goal_with_budget(
&self,
thread_id: ThreadId,
objective: &str,
status: crate::ThreadGoalStatus,
budget: Option<crate::ThreadGoalBudget>,
) -> anyhow::Result<Option<crate::ThreadGoal>> {
let goal_id = Uuid::new_v4().to_string();
let now_ms = datetime_to_epoch_millis(Utc::now());
let status = status_after_budget_limit(status, /*tokens_used*/ 0, token_budget);
let budget_columns = budget_columns(budget.as_ref());
let status =
status_after_budget_limit(status, /*tokens_used*/ 0, budget_columns.token_budget);
let row = sqlx::query(
r#"
INSERT INTO thread_goals (
@@ -122,18 +204,32 @@ INSERT INTO thread_goals (
goal_id,
objective,
status,
budget_kind,
budget_limit_id,
budget_percent,
budget_baseline_used_percent,
budget_baseline_resets_at,
budget_latest_used_percent,
budget_latest_resets_at,
token_budget,
tokens_used,
time_used_seconds,
created_at_ms,
updated_at_ms
) VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?)
ON CONFLICT(thread_id) DO NOTHING
RETURNING
thread_id,
goal_id,
objective,
status,
budget_kind,
budget_limit_id,
budget_percent,
budget_baseline_used_percent,
budget_baseline_resets_at,
budget_latest_used_percent,
budget_latest_resets_at,
token_budget,
tokens_used,
time_used_seconds,
@@ -145,7 +241,14 @@ RETURNING
.bind(goal_id)
.bind(objective)
.bind(status.as_str())
.bind(token_budget)
.bind(budget_columns.kind)
.bind(budget_columns.limit_id)
.bind(budget_columns.percent)
.bind(budget_columns.baseline_used_percent)
.bind(budget_columns.baseline_resets_at)
.bind(budget_columns.latest_used_percent)
.bind(budget_columns.latest_resets_at)
.bind(budget_columns.token_budget)
.bind(now_ms)
.bind(now_ms)
.fetch_optional(self.pool.as_ref())
@@ -177,6 +280,13 @@ SET
WHEN ? = 'active' AND ? IS NOT NULL AND tokens_used >= ? THEN ?
ELSE ?
END,
budget_kind = CASE WHEN ? IS NULL THEN NULL ELSE 'tokens' END,
budget_limit_id = NULL,
budget_percent = NULL,
budget_baseline_used_percent = NULL,
budget_baseline_resets_at = NULL,
budget_latest_used_percent = NULL,
budget_latest_resets_at = NULL,
token_budget = ?,
updated_at_ms = ?
WHERE thread_id = ?
@@ -192,6 +302,7 @@ WHERE thread_id = ?
.bind(crate::ThreadGoalStatus::BudgetLimited.as_str())
.bind(status.as_str())
.bind(token_budget)
.bind(token_budget)
.bind(now_ms)
.bind(thread_id.to_string())
.bind(expected_goal_id)
@@ -233,6 +344,13 @@ WHERE thread_id = ?
UPDATE thread_goals
SET
token_budget = ?,
budget_kind = CASE WHEN ? IS NULL THEN NULL ELSE 'tokens' END,
budget_limit_id = NULL,
budget_percent = NULL,
budget_baseline_used_percent = NULL,
budget_baseline_resets_at = NULL,
budget_latest_used_percent = NULL,
budget_latest_resets_at = NULL,
status = CASE
WHEN status = 'active' AND ? IS NOT NULL AND tokens_used >= ? THEN ?
ELSE status
@@ -245,6 +363,7 @@ WHERE thread_id = ?
.bind(token_budget)
.bind(token_budget)
.bind(token_budget)
.bind(token_budget)
.bind(crate::ThreadGoalStatus::BudgetLimited.as_str())
.bind(now_ms)
.bind(thread_id.to_string())
@@ -373,6 +492,13 @@ RETURNING
goal_id,
objective,
status,
budget_kind,
budget_limit_id,
budget_percent,
budget_baseline_used_percent,
budget_baseline_resets_at,
budget_latest_used_percent,
budget_latest_resets_at,
token_budget,
tokens_used,
time_used_seconds,
@@ -403,12 +529,139 @@ RETURNING
let updated = thread_goal_from_row(&row)?;
Ok(ThreadGoalAccountingOutcome::Updated(updated))
}
pub async fn account_thread_goal_five_hour_limit(
&self,
thread_id: ThreadId,
limit_id: &str,
used_percent: f64,
resets_at: Option<i64>,
expected_goal_id: Option<&str>,
) -> anyhow::Result<ThreadGoalAccountingOutcome> {
let now_ms = datetime_to_epoch_millis(Utc::now());
let goal_id_filter = if expected_goal_id.is_some() {
"goal_id = ?"
} else {
"1 = 1"
};
let query = format!(
r#"
UPDATE thread_goals
SET
budget_latest_used_percent = ?,
budget_latest_resets_at = ?,
status = CASE
WHEN status = 'active'
AND (
? - budget_baseline_used_percent >= budget_percent
OR (
budget_baseline_resets_at IS NOT NULL
AND ? IS NOT NULL
AND budget_baseline_resets_at != ?
)
)
THEN ?
ELSE status
END,
updated_at_ms = ?
WHERE thread_id = ?
AND budget_kind = 'five_hour_limit_percent'
AND budget_limit_id = ?
AND status IN ('active', 'budget_limited')
AND {goal_id_filter}
RETURNING
thread_id,
goal_id,
objective,
status,
budget_kind,
budget_limit_id,
budget_percent,
budget_baseline_used_percent,
budget_baseline_resets_at,
budget_latest_used_percent,
budget_latest_resets_at,
token_budget,
tokens_used,
time_used_seconds,
created_at_ms,
updated_at_ms
"#,
);
let mut query = sqlx::query(&query)
.bind(used_percent)
.bind(resets_at)
.bind(used_percent)
.bind(resets_at)
.bind(resets_at)
.bind(crate::ThreadGoalStatus::BudgetLimited.as_str())
.bind(now_ms)
.bind(thread_id.to_string())
.bind(limit_id);
if let Some(expected_goal_id) = expected_goal_id {
query = query.bind(expected_goal_id);
}
let row = query.fetch_optional(self.pool.as_ref()).await?;
let Some(row) = row else {
return Ok(ThreadGoalAccountingOutcome::Unchanged(
self.get_thread_goal(thread_id).await?,
));
};
let updated = thread_goal_from_row(&row)?;
Ok(ThreadGoalAccountingOutcome::Updated(updated))
}
}
fn thread_goal_from_row(row: &sqlx::sqlite::SqliteRow) -> anyhow::Result<crate::ThreadGoal> {
ThreadGoalRow::try_from_row(row).and_then(crate::ThreadGoal::try_from)
}
fn budget_columns(budget: Option<&crate::ThreadGoalBudget>) -> GoalBudgetColumns<'_> {
match budget {
Some(crate::ThreadGoalBudget::Tokens { token_budget }) => GoalBudgetColumns {
kind: Some("tokens"),
limit_id: None,
percent: None,
baseline_used_percent: None,
baseline_resets_at: None,
latest_used_percent: None,
latest_resets_at: None,
token_budget: Some(*token_budget),
},
Some(crate::ThreadGoalBudget::FiveHourLimitPercent {
limit_id,
percent,
baseline_used_percent,
baseline_resets_at,
latest_used_percent,
latest_resets_at,
}) => GoalBudgetColumns {
kind: Some("five_hour_limit_percent"),
limit_id: Some(limit_id.as_str()),
percent: Some(*percent),
baseline_used_percent: Some(*baseline_used_percent),
baseline_resets_at: *baseline_resets_at,
latest_used_percent: Some(*latest_used_percent),
latest_resets_at: *latest_resets_at,
token_budget: None,
},
None => GoalBudgetColumns {
kind: None,
limit_id: None,
percent: None,
baseline_used_percent: None,
baseline_resets_at: None,
latest_used_percent: None,
latest_resets_at: None,
token_budget: None,
},
}
}
fn status_after_budget_limit(
status: crate::ThreadGoalStatus,
tokens_used: i64,
@@ -486,6 +739,9 @@ mod tests {
.expect("goal should exist");
let expected = crate::ThreadGoal {
status: crate::ThreadGoalStatus::Paused,
budget: Some(crate::ThreadGoalBudget::Tokens {
token_budget: 200_000,
}),
token_budget: Some(200_000),
updated_at: updated.updated_at,
..goal.clone()
@@ -591,6 +847,60 @@ mod tests {
assert_eq!(0, inserted.time_used_seconds);
}
#[tokio::test]
async fn five_hour_limit_accounting_budget_limits_at_percent_threshold() {
let runtime = test_runtime().await;
let thread_id = test_thread_id();
upsert_test_thread(&runtime, thread_id).await;
let goal = runtime
.replace_thread_goal_with_budget(
thread_id,
"stay under 5h usage",
crate::ThreadGoalStatus::Active,
Some(crate::ThreadGoalBudget::FiveHourLimitPercent {
limit_id: "codex".to_string(),
percent: 10.0,
baseline_used_percent: 25.0,
baseline_resets_at: Some(1_800_000_000),
latest_used_percent: 25.0,
latest_resets_at: Some(1_800_000_000),
}),
)
.await
.expect("goal replacement should succeed");
let outcome = runtime
.account_thread_goal_five_hour_limit(
thread_id,
"codex",
/*used_percent*/ 34.9,
Some(1_800_000_000),
Some(goal.goal_id.as_str()),
)
.await
.expect("5h limit accounting should succeed");
let ThreadGoalAccountingOutcome::Updated(goal) = outcome else {
panic!("5h limit progress should update the goal");
};
assert_eq!(crate::ThreadGoalStatus::Active, goal.status);
let outcome = runtime
.account_thread_goal_five_hour_limit(
thread_id,
"codex",
/*used_percent*/ 35.0,
Some(1_800_000_000),
Some(goal.goal_id.as_str()),
)
.await
.expect("5h limit accounting should succeed");
let ThreadGoalAccountingOutcome::Updated(goal) = outcome else {
panic!("5h limit threshold should update the goal");
};
assert_eq!(crate::ThreadGoalStatus::BudgetLimited, goal.status);
}
#[tokio::test]
async fn update_thread_goal_ignores_replaced_goal_version() {
let runtime = test_runtime().await;
+45 -1
View File
@@ -26,6 +26,40 @@ pub fn create_get_goal_tool() -> ToolSpec {
}
pub fn create_create_goal_tool() -> ToolSpec {
let token_budget_schema = JsonSchema::object(
BTreeMap::from([
(
"type".to_string(),
JsonSchema::string_enum(vec![json!("tokens")], /*description*/ None),
),
(
"token_budget".to_string(),
JsonSchema::integer(Some("Positive token budget.".to_string())),
),
]),
Some(vec!["type".to_string(), "token_budget".to_string()]),
Some(false.into()),
);
let five_hour_limit_budget_schema = JsonSchema::object(
BTreeMap::from([
(
"type".to_string(),
JsonSchema::string_enum(
vec![json!("five_hour_limit_percent")],
/*description*/ None,
),
),
(
"percent".to_string(),
JsonSchema::number(Some(
"Percentage points of the current Codex 5h limit to spend on this goal."
.to_string(),
)),
),
]),
Some(vec!["type".to_string(), "percent".to_string()]),
Some(false.into()),
);
let properties = BTreeMap::from([
(
"objective".to_string(),
@@ -40,13 +74,23 @@ pub fn create_create_goal_tool() -> ToolSpec {
"Optional positive token budget for the new active goal.".to_string(),
)),
),
(
"budget".to_string(),
JsonSchema::any_of(
vec![token_budget_schema, five_hour_limit_budget_schema],
Some(
"Optional structured budget. Prefer this over token_budget. Use five_hour_limit_percent only when the user explicitly asks to cap the goal by a percentage of their 5h Codex limit."
.to_string(),
),
),
),
]);
ToolSpec::Function(ResponsesApiTool {
name: CREATE_GOAL_TOOL_NAME.to_string(),
description: format!(
r#"Create a goal only when explicitly requested by the user or system/developer instructions; do not infer goals from ordinary tasks.
Set token_budget only when an explicit token budget is requested. Fails if a goal exists; use {UPDATE_GOAL_TOOL_NAME} only for status."#
Set budget only when an explicit budget is requested. Use tokens for explicit token budgets and five_hour_limit_percent for explicit five-hour-limit percentage budgets. Fails if a goal exists; use {UPDATE_GOAL_TOOL_NAME} only for status."#
),
strict: false,
defer_loading: None,
+2 -1
View File
@@ -653,9 +653,10 @@ impl App {
AppEvent::SetThreadGoalObjective {
thread_id,
objective,
budget,
mode,
} => {
self.set_thread_goal_objective(app_server, thread_id, objective, mode)
self.set_thread_goal_objective(app_server, thread_id, objective, budget, mode)
.await;
}
AppEvent::SetThreadGoalStatus { thread_id, status } => {
+14 -6
View File
@@ -8,6 +8,7 @@ use crate::bottom_pane::SelectionViewParams;
use crate::bottom_pane::popup_consts::standard_popup_hint_line;
use crate::goal_display::goal_status_label;
use crate::goal_display::goal_usage_summary;
use codex_app_server_protocol::ThreadGoalBudgetParams;
use codex_app_server_protocol::ThreadGoalStatus;
use codex_protocol::ThreadId;
@@ -32,10 +33,7 @@ impl App {
};
let Some(goal) = response.goal else {
self.chat_widget.add_info_message(
"Usage: /goal <objective>".to_string(),
Some("No goal is currently set.".to_string()),
);
self.chat_widget.show_goal_setup(thread_id);
return;
};
@@ -47,6 +45,7 @@ impl App {
app_server: &mut AppServerSession,
thread_id: ThreadId,
objective: String,
budget: Option<ThreadGoalBudgetParams>,
mode: ThreadGoalSetMode,
) {
if mode == ThreadGoalSetMode::ConfirmIfExists {
@@ -57,7 +56,7 @@ impl App {
match result {
Ok(response) if response.goal.is_some() => {
self.show_replace_thread_goal_confirmation(thread_id, objective);
self.show_replace_thread_goal_confirmation(thread_id, objective, budget);
return;
}
Ok(_) => {}
@@ -74,6 +73,7 @@ impl App {
thread_id,
Some(objective),
Some(ThreadGoalStatus::Active),
budget.map(Some),
/*token_budget*/ None,
)
.await;
@@ -103,6 +103,7 @@ impl App {
thread_id,
/*objective*/ None,
Some(status),
/*budget*/ None,
/*token_budget*/ None,
)
.await;
@@ -149,12 +150,19 @@ impl App {
}
}
fn show_replace_thread_goal_confirmation(&mut self, thread_id: ThreadId, objective: String) {
fn show_replace_thread_goal_confirmation(
&mut self,
thread_id: ThreadId,
objective: String,
budget: Option<ThreadGoalBudgetParams>,
) {
let replace_objective = objective.clone();
let replace_budget = budget;
let replace_actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
tx.send(AppEvent::SetThreadGoalObjective {
thread_id,
objective: replace_objective.clone(),
budget: replace_budget.clone(),
mode: ThreadGoalSetMode::ReplaceExisting,
});
})];
+2
View File
@@ -25,6 +25,7 @@ use codex_app_server_protocol::PluginReadResponse;
use codex_app_server_protocol::PluginUninstallResponse;
use codex_app_server_protocol::RateLimitSnapshot;
use codex_app_server_protocol::SkillsListResponse;
use codex_app_server_protocol::ThreadGoalBudgetParams;
use codex_app_server_protocol::ThreadGoalStatus;
use codex_file_search::FileMatch;
use codex_protocol::ThreadId;
@@ -226,6 +227,7 @@ pub(crate) enum AppEvent {
SetThreadGoalObjective {
thread_id: ThreadId,
objective: String,
budget: Option<ThreadGoalBudgetParams>,
mode: ThreadGoalSetMode,
},
+3
View File
@@ -55,6 +55,7 @@ use codex_app_server_protocol::ThreadCompactStartParams;
use codex_app_server_protocol::ThreadCompactStartResponse;
use codex_app_server_protocol::ThreadForkParams;
use codex_app_server_protocol::ThreadForkResponse;
use codex_app_server_protocol::ThreadGoalBudgetParams;
use codex_app_server_protocol::ThreadGoalClearParams;
use codex_app_server_protocol::ThreadGoalClearResponse;
use codex_app_server_protocol::ThreadGoalGetParams;
@@ -686,6 +687,7 @@ impl AppServerSession {
thread_id: ThreadId,
objective: Option<String>,
status: Option<ThreadGoalStatus>,
budget: Option<Option<ThreadGoalBudgetParams>>,
token_budget: Option<Option<i64>>,
) -> Result<ThreadGoalSetResponse> {
let request_id = self.next_request_id();
@@ -696,6 +698,7 @@ impl AppServerSession {
thread_id: thread_id.to_string(),
objective,
status,
budget,
token_budget,
},
})
@@ -0,0 +1,441 @@
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::Clear;
use ratatui::widgets::Paragraph;
use ratatui::widgets::StatefulWidgetRef;
use ratatui::widgets::Widget;
use std::cell::RefCell;
use codex_app_server_protocol::ThreadGoalBudgetParams;
use crate::render::renderable::Renderable;
use super::CancellationEvent;
use super::bottom_pane_view::BottomPaneView;
use super::bottom_pane_view::ViewCompletion;
use super::popup_consts::standard_popup_hint_line;
use super::textarea::TextArea;
use super::textarea::TextAreaState;
pub(crate) type GoalSetupSubmitted =
Box<dyn Fn(String, Option<ThreadGoalBudgetParams>) + Send + Sync>;
pub(crate) struct GoalSetupView {
objective: TextArea,
objective_state: RefCell<TextAreaState>,
budget_value: TextArea,
budget_value_state: RefCell<TextAreaState>,
budget_kind: GoalBudgetKind,
focus: GoalSetupFocus,
error: Option<String>,
on_submit: GoalSetupSubmitted,
completion: Option<ViewCompletion>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum GoalBudgetKind {
None,
Tokens,
FiveHourLimit,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum GoalSetupFocus {
Objective,
Budget,
Value,
}
impl GoalSetupView {
pub(crate) fn new(on_submit: GoalSetupSubmitted) -> Self {
Self {
objective: TextArea::new(),
objective_state: RefCell::new(TextAreaState::default()),
budget_value: TextArea::new(),
budget_value_state: RefCell::new(TextAreaState::default()),
budget_kind: GoalBudgetKind::None,
focus: GoalSetupFocus::Objective,
error: None,
on_submit,
completion: None,
}
}
fn submit(&mut self) {
let objective = self.objective.text().trim().to_string();
if objective.is_empty() {
self.error = Some("Goal objective must not be empty.".to_string());
return;
}
match self.budget() {
Ok(budget) => {
(self.on_submit)(objective, budget);
self.completion = Some(ViewCompletion::Accepted);
}
Err(err) => self.error = Some(err),
}
}
fn budget(&self) -> Result<Option<ThreadGoalBudgetParams>, String> {
let value = self.budget_value.text().trim();
match self.budget_kind {
GoalBudgetKind::None => Ok(None),
GoalBudgetKind::Tokens => Ok(Some(ThreadGoalBudgetParams::Tokens {
token_budget: parse_token_budget(value)?,
})),
GoalBudgetKind::FiveHourLimit => {
Ok(Some(ThreadGoalBudgetParams::FiveHourLimitPercent {
percent: parse_five_hour_percent(value)?,
}))
}
}
}
fn cycle_budget(&mut self) {
self.budget_kind = match self.budget_kind {
GoalBudgetKind::None => GoalBudgetKind::Tokens,
GoalBudgetKind::Tokens => GoalBudgetKind::FiveHourLimit,
GoalBudgetKind::FiveHourLimit => GoalBudgetKind::None,
};
if self.budget_kind == GoalBudgetKind::None && self.focus == GoalSetupFocus::Value {
self.focus = GoalSetupFocus::Budget;
}
self.error = None;
}
fn cycle_focus(&mut self) {
self.focus = match (self.focus, self.budget_kind) {
(GoalSetupFocus::Objective, _) => GoalSetupFocus::Budget,
(GoalSetupFocus::Budget, GoalBudgetKind::None) => GoalSetupFocus::Objective,
(GoalSetupFocus::Budget, _) => GoalSetupFocus::Value,
(GoalSetupFocus::Value, _) => GoalSetupFocus::Objective,
};
}
fn budget_label(&self) -> &'static str {
match self.budget_kind {
GoalBudgetKind::None => "None",
GoalBudgetKind::Tokens => "Tokens",
GoalBudgetKind::FiveHourLimit => "5h limit",
}
}
fn value_placeholder(&self) -> &'static str {
match self.budget_kind {
GoalBudgetKind::None => "",
GoalBudgetKind::Tokens => "500000 or 500k",
GoalBudgetKind::FiveHourLimit => "10%",
}
}
}
impl BottomPaneView for GoalSetupView {
fn handle_key_event(&mut self, key_event: KeyEvent) {
self.error = None;
match key_event {
KeyEvent {
code: KeyCode::Esc, ..
} => {
self.on_ctrl_c();
}
KeyEvent {
code: KeyCode::Tab, ..
} => self.cycle_focus(),
KeyEvent {
code: KeyCode::Enter,
modifiers: KeyModifiers::NONE,
..
} if self.focus == GoalSetupFocus::Budget => self.cycle_budget(),
KeyEvent {
code: KeyCode::Left | KeyCode::Right | KeyCode::Char(' '),
..
} if self.focus == GoalSetupFocus::Budget => self.cycle_budget(),
KeyEvent {
code: KeyCode::Enter,
modifiers: KeyModifiers::NONE,
..
} => self.submit(),
other => match self.focus {
GoalSetupFocus::Objective => self.objective.input(other),
GoalSetupFocus::Value => self.budget_value.input(other),
GoalSetupFocus::Budget => {}
},
}
}
fn on_ctrl_c(&mut self) -> CancellationEvent {
self.completion = Some(ViewCompletion::Cancelled);
CancellationEvent::Handled
}
fn is_complete(&self) -> bool {
self.completion.is_some()
}
fn completion(&self) -> Option<ViewCompletion> {
self.completion
}
fn handle_paste(&mut self, pasted: String) -> bool {
if pasted.is_empty() {
return false;
}
match self.focus {
GoalSetupFocus::Objective => self.objective.insert_str(&pasted),
GoalSetupFocus::Value => self.budget_value.insert_str(&pasted),
GoalSetupFocus::Budget => return false,
}
true
}
}
impl Renderable for GoalSetupView {
fn desired_height(&self, width: u16) -> u16 {
let value_rows = if self.budget_kind == GoalBudgetKind::None {
0
} else {
2
};
6u16.saturating_add(self.objective_height(width))
.saturating_add(value_rows)
.saturating_add(u16::from(self.error.is_some()))
}
fn render(&self, area: Rect, buf: &mut Buffer) {
if area.height == 0 || area.width == 0 {
return;
}
let mut y = area.y;
Paragraph::new(Line::from(vec![gutter(), "Set goal".bold()])).render(
Rect {
x: area.x,
y,
width: area.width,
height: 1,
},
buf,
);
y = y.saturating_add(1);
let budget_style = if self.focus == GoalSetupFocus::Budget {
self.budget_label().cyan()
} else {
self.budget_label().into()
};
Paragraph::new(Line::from(vec![
gutter(),
"Budget: ".dim(),
budget_style,
" ".into(),
"tab focus, arrows cycle".dim(),
]))
.render(
Rect {
x: area.x,
y,
width: area.width,
height: 1,
},
buf,
);
y = y.saturating_add(1);
if self.budget_kind != GoalBudgetKind::None {
Paragraph::new(Line::from(vec![gutter(), "Value: ".dim()])).render(
Rect {
x: area.x,
y,
width: area.width,
height: 1,
},
buf,
);
y = y.saturating_add(1);
self.render_textarea(
&self.budget_value,
&self.budget_value_state,
self.value_placeholder(),
Rect {
x: area.x,
y,
width: area.width,
height: 1,
},
buf,
);
y = y.saturating_add(1);
}
Paragraph::new(Line::from(vec![gutter(), "Objective: ".dim()])).render(
Rect {
x: area.x,
y,
width: area.width,
height: 1,
},
buf,
);
y = y.saturating_add(1);
let objective_height = self.objective_height(area.width);
self.render_textarea(
&self.objective,
&self.objective_state,
"What should Codex keep working toward?",
Rect {
x: area.x,
y,
width: area.width,
height: objective_height,
},
buf,
);
y = y.saturating_add(objective_height);
if let Some(error) = &self.error {
Paragraph::new(Line::from(vec![gutter(), error.clone().red()])).render(
Rect {
x: area.x,
y,
width: area.width,
height: 1,
},
buf,
);
y = y.saturating_add(1);
}
let hint_y = y.saturating_add(1);
if hint_y < area.y.saturating_add(area.height) {
Paragraph::new(standard_popup_hint_line()).render(
Rect {
x: area.x,
y: hint_y,
width: area.width,
height: 1,
},
buf,
);
}
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
if area.width <= 2 {
return None;
}
match self.focus {
GoalSetupFocus::Objective => {
let y = area.y
+ 3
+ if self.budget_kind == GoalBudgetKind::None {
0
} else {
2
};
let rect = Rect {
x: area.x.saturating_add(2),
y,
width: area.width.saturating_sub(2),
height: self.objective_height(area.width),
};
self.objective
.cursor_pos_with_state(rect, *self.objective_state.borrow())
}
GoalSetupFocus::Value if self.budget_kind != GoalBudgetKind::None => {
let rect = Rect {
x: area.x.saturating_add(2),
y: area.y.saturating_add(3),
width: area.width.saturating_sub(2),
height: 1,
};
self.budget_value
.cursor_pos_with_state(rect, *self.budget_value_state.borrow())
}
_ => None,
}
}
}
impl GoalSetupView {
fn objective_height(&self, width: u16) -> u16 {
self.objective
.desired_height(width.saturating_sub(2))
.clamp(2, 6)
}
fn render_textarea(
&self,
textarea: &TextArea,
state: &RefCell<TextAreaState>,
placeholder: &str,
area: Rect,
buf: &mut Buffer,
) {
for row in 0..area.height {
Paragraph::new(Line::from(vec![gutter()])).render(
Rect {
x: area.x,
y: area.y.saturating_add(row),
width: 2,
height: 1,
},
buf,
);
}
let textarea_rect = Rect {
x: area.x.saturating_add(2),
y: area.y,
width: area.width.saturating_sub(2),
height: area.height,
};
Clear.render(textarea_rect, buf);
StatefulWidgetRef::render_ref(&textarea, textarea_rect, buf, &mut *state.borrow_mut());
if textarea.text().is_empty() {
Paragraph::new(Line::from(placeholder.to_string().dim())).render(textarea_rect, buf);
}
}
}
fn parse_token_budget(value: &str) -> Result<i64, String> {
let value = value.trim();
if value.is_empty() {
return Err("Token budget must not be empty.".to_string());
}
let (number, multiplier) = match value.chars().last() {
Some('k' | 'K') => (&value[..value.len() - 1], 1_000.0),
Some('m' | 'M') => (&value[..value.len() - 1], 1_000_000.0),
_ => (value, 1.0),
};
let parsed = number
.parse::<f64>()
.map_err(|_| "Token budget must be a number like 500000 or 500k.".to_string())?;
let budget = (parsed * multiplier).round();
if !budget.is_finite() || budget <= 0.0 || budget > i64::MAX as f64 {
return Err("Token budget must be positive.".to_string());
}
Ok(budget as i64)
}
fn parse_five_hour_percent(value: &str) -> Result<f64, String> {
let value = value
.trim()
.strip_suffix('%')
.unwrap_or(value.trim())
.trim();
let percent = value
.parse::<f64>()
.map_err(|_| "5h limit must be a percent like 10%.".to_string())?;
if !percent.is_finite() || percent <= 0.0 || percent > 100.0 {
return Err("5h limit must be between 0% and 100%.".to_string());
}
Ok(percent)
}
fn gutter() -> Span<'static> {
"| ".cyan()
}
+2
View File
@@ -91,6 +91,7 @@ pub(crate) mod custom_prompt_view;
mod experimental_features_view;
mod file_search_popup;
mod footer;
mod goal_setup_view;
mod list_selection_view;
mod memories_settings_view;
pub(crate) mod prompt_args;
@@ -101,6 +102,7 @@ pub(crate) use footer::CollaborationModeIndicator;
pub(crate) use footer::GoalStatusIndicator;
#[cfg(test)]
pub(crate) use footer::goal_status_indicator_line;
pub(crate) use goal_setup_view::GoalSetupView;
pub(crate) use list_selection_view::ColumnWidthMode;
#[cfg(test)]
pub(crate) use list_selection_view::ListSelectionView;
+26
View File
@@ -1,14 +1,34 @@
//! Goal summary for the bare `/goal` command.
use super::*;
use crate::app_event::AppEvent;
use crate::app_event::ThreadGoalSetMode;
use crate::bottom_pane::GoalSetupView;
use crate::goal_display::format_five_hour_goal_progress;
use crate::goal_display::format_goal_elapsed_seconds;
use crate::status::format_tokens_compact;
use codex_app_server_protocol::ThreadGoalBudgetParams;
impl ChatWidget {
pub(crate) fn show_goal_summary(&mut self, goal: AppThreadGoal) {
self.add_plain_history_lines(goal_summary_lines(&goal));
}
pub(crate) fn show_goal_setup(&mut self, thread_id: ThreadId) {
let tx = self.app_event_tx.clone();
let view = GoalSetupView::new(Box::new(
move |objective: String, budget: Option<ThreadGoalBudgetParams>| {
tx.send(AppEvent::SetThreadGoalObjective {
thread_id,
objective,
budget,
mode: ThreadGoalSetMode::ConfirmIfExists,
});
},
));
self.bottom_pane.show_view(Box::new(view));
}
pub(crate) fn on_thread_goal_cleared(&mut self, thread_id: &str) {
if self
.thread_id
@@ -42,6 +62,12 @@ fn goal_summary_lines(goal: &AppThreadGoal) -> Vec<Line<'static>> {
"Token budget: ".dim(),
format_tokens_compact(token_budget).into(),
]));
} else if let Some(progress) = goal
.budget
.as_ref()
.and_then(format_five_hour_goal_progress)
{
lines.push(Line::from(vec!["5h limit: ".dim(), progress.into()]));
}
let command_hint = match goal.status {
AppThreadGoalStatus::Active => "Commands: /goal pause, /goal clear",
+42 -7
View File
@@ -5,6 +5,7 @@ use codex_app_server_protocol::ThreadGoalStatus as AppThreadGoalStatus;
use std::time::Instant;
use crate::bottom_pane::GoalStatusIndicator;
use crate::goal_display::format_five_hour_goal_progress;
use crate::goal_display::format_goal_elapsed_seconds;
use crate::status::format_tokens_compact;
@@ -47,14 +48,24 @@ pub(super) fn goal_status_indicator_from_app_goal(
) -> Option<GoalStatusIndicator> {
match goal.status {
AppThreadGoalStatus::Active => Some(GoalStatusIndicator::Active {
usage: active_goal_usage(goal.token_budget, goal.tokens_used, goal.time_used_seconds),
usage: active_goal_usage(
goal.budget.as_ref(),
goal.token_budget,
goal.tokens_used,
goal.time_used_seconds,
),
}),
AppThreadGoalStatus::Paused => Some(GoalStatusIndicator::Paused),
AppThreadGoalStatus::BudgetLimited => Some(GoalStatusIndicator::BudgetLimited {
usage: stopped_goal_budget_usage(goal.token_budget, goal.tokens_used),
usage: stopped_goal_budget_usage(
goal.budget.as_ref(),
goal.token_budget,
goal.tokens_used,
),
}),
AppThreadGoalStatus::Complete => Some(GoalStatusIndicator::Complete {
usage: Some(completed_goal_usage(
goal.budget.as_ref(),
goal.token_budget,
goal.tokens_used,
goal.time_used_seconds,
@@ -64,10 +75,14 @@ pub(super) fn goal_status_indicator_from_app_goal(
}
fn active_goal_usage(
budget: Option<&codex_app_server_protocol::ThreadGoalBudget>,
token_budget: Option<i64>,
tokens_used: i64,
time_used_seconds: i64,
) -> Option<String> {
if let Some(budget) = budget.and_then(format_five_hour_goal_progress) {
return Some(budget);
}
if let Some(token_budget) = token_budget {
return Some(format!(
"{} / {}",
@@ -79,7 +94,14 @@ fn active_goal_usage(
Some(format_goal_elapsed_seconds(time_used_seconds))
}
fn stopped_goal_budget_usage(token_budget: Option<i64>, tokens_used: i64) -> Option<String> {
fn stopped_goal_budget_usage(
budget: Option<&codex_app_server_protocol::ThreadGoalBudget>,
token_budget: Option<i64>,
tokens_used: i64,
) -> Option<String> {
if let Some(budget) = budget.and_then(format_five_hour_goal_progress) {
return Some(format!("{budget} 5h limit"));
}
token_budget.map(|token_budget| {
format!(
"{} / {} tokens",
@@ -90,10 +112,14 @@ fn stopped_goal_budget_usage(token_budget: Option<i64>, tokens_used: i64) -> Opt
}
fn completed_goal_usage(
budget: Option<&codex_app_server_protocol::ThreadGoalBudget>,
token_budget: Option<i64>,
tokens_used: i64,
time_used_seconds: i64,
) -> String {
if let Some(budget) = budget.and_then(format_five_hour_goal_progress) {
return format!("{budget} 5h limit");
}
if token_budget.is_some() {
return format!("{} tokens", format_tokens_compact(tokens_used));
}
@@ -117,6 +143,7 @@ mod tests {
fn active_goal_usage_prefers_token_budget() {
assert_eq!(
active_goal_usage(
/*budget*/ None,
Some(50_000),
/*tokens_used*/ 12_500,
/*time_used_seconds*/ 90
@@ -129,7 +156,7 @@ mod tests {
fn active_goal_usage_reports_time_without_budget() {
assert_eq!(
active_goal_usage(
/*token_budget*/ None, /*tokens_used*/ 12_500,
/*budget*/ None, /*token_budget*/ None, /*tokens_used*/ 12_500,
/*time_used_seconds*/ 120,
),
Some("2m".to_string())
@@ -139,7 +166,11 @@ mod tests {
#[test]
fn stopped_goal_budget_usage_reports_budgeted_tokens() {
assert_eq!(
stopped_goal_budget_usage(Some(50_000), /*tokens_used*/ 63_876),
stopped_goal_budget_usage(
/*budget*/ None,
Some(50_000),
/*tokens_used*/ 63_876
),
Some("63.9K / 50K tokens".to_string())
);
}
@@ -147,7 +178,9 @@ mod tests {
#[test]
fn stopped_goal_budget_usage_omits_unbudgeted_usage() {
assert_eq!(
stopped_goal_budget_usage(/*token_budget*/ None, /*tokens_used*/ 12_500),
stopped_goal_budget_usage(
/*budget*/ None, /*token_budget*/ None, /*tokens_used*/ 12_500
),
None
);
}
@@ -156,6 +189,7 @@ mod tests {
fn completed_goal_usage_reports_tokens_when_budgeted() {
assert_eq!(
completed_goal_usage(
/*budget*/ None,
Some(50_000),
/*tokens_used*/ 40_000,
/*time_used_seconds*/ 120,
@@ -168,7 +202,7 @@ mod tests {
fn completed_goal_usage_reports_time_without_token_budget() {
assert_eq!(
completed_goal_usage(
/*token_budget*/ None, /*tokens_used*/ 40_000,
/*budget*/ None, /*token_budget*/ None, /*tokens_used*/ 40_000,
/*time_used_seconds*/ 36_720,
),
"10h 12m".to_string()
@@ -214,6 +248,7 @@ mod tests {
thread_id: "thread".to_string(),
objective: "do the thing".to_string(),
status: AppThreadGoalStatus::Active,
budget: None,
token_budget: None,
tokens_used: 0,
time_used_seconds,
+92 -2
View File
@@ -9,6 +9,7 @@ use super::*;
use crate::app_event::ThreadGoalSetMode;
use crate::bottom_pane::prompt_args::parse_slash_name;
use crate::bottom_pane::slash_commands;
use codex_app_server_protocol::ThreadGoalBudgetParams;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SlashCommandDispatchSource {
@@ -32,6 +33,84 @@ const SIDE_SLASH_COMMAND_UNAVAILABLE_HINT: &str = "Press Esc to return to the ma
const GOAL_USAGE: &str = "Usage: /goal <objective>";
const GOAL_USAGE_HINT: &str = "Example: /goal improve benchmark coverage";
struct ParsedGoalCommand {
objective: String,
budget: Option<ThreadGoalBudgetParams>,
}
fn parse_goal_objective_and_budget(input: &str) -> Result<ParsedGoalCommand, String> {
let Some(rest) = input.strip_prefix("--tokens ") else {
if let Some(rest) = input.strip_prefix("--5h-limit ") {
return parse_goal_five_hour_limit_budget(rest, "--5h-limit");
}
if let Some(rest) = input.strip_prefix("--five-hour-limit ") {
return parse_goal_five_hour_limit_budget(rest, "--five-hour-limit");
};
return Ok(ParsedGoalCommand {
objective: input.to_string(),
budget: None,
});
};
let (tokens, objective) = split_budget_value(rest, "--tokens")?;
Ok(ParsedGoalCommand {
objective: objective.to_string(),
budget: Some(ThreadGoalBudgetParams::Tokens {
token_budget: parse_goal_token_budget(tokens)?,
}),
})
}
fn parse_goal_five_hour_limit_budget(input: &str, flag: &str) -> Result<ParsedGoalCommand, String> {
let (percent, objective) = split_budget_value(input, flag)?;
Ok(ParsedGoalCommand {
objective: objective.to_string(),
budget: Some(ThreadGoalBudgetParams::FiveHourLimitPercent {
percent: parse_goal_five_hour_percent(percent)?,
}),
})
}
fn split_budget_value<'a>(input: &'a str, flag: &str) -> Result<(&'a str, &'a str), String> {
let mut parts = input.trim().splitn(2, char::is_whitespace);
let value = parts.next().unwrap_or_default();
let objective = parts.next().unwrap_or_default().trim();
if value.is_empty() || objective.is_empty() {
return Err(format!("Usage: /goal {flag} <value> <objective>"));
}
Ok((value, objective))
}
fn parse_goal_token_budget(value: &str) -> Result<i64, String> {
let (number, multiplier) = match value.chars().last() {
Some('k' | 'K') => (&value[..value.len() - 1], 1_000.0),
Some('m' | 'M') => (&value[..value.len() - 1], 1_000_000.0),
_ => (value, 1.0),
};
let parsed = number
.parse::<f64>()
.map_err(|_| "Token budget must be a number like 500000 or 500k.".to_string())?;
let budget = (parsed * multiplier).round();
if !budget.is_finite() || budget <= 0.0 || budget > i64::MAX as f64 {
return Err("Token budget must be positive.".to_string());
}
Ok(budget as i64)
}
fn parse_goal_five_hour_percent(value: &str) -> Result<f64, String> {
let value = value
.trim()
.strip_suffix('%')
.unwrap_or(value.trim())
.trim();
let percent = value
.parse::<f64>()
.map_err(|_| "5h limit must be a percent like 10%.".to_string())?;
if !percent.is_finite() || percent <= 0.0 || percent > 100.0 {
return Err("5h limit must be between 0% and 100%.".to_string());
}
Ok(percent)
}
impl ChatWidget {
/// Dispatch a bare slash command and record its staged local-history entry.
///
@@ -654,7 +733,17 @@ impl ChatWidget {
}
return;
}
let objective = args.trim();
let parsed_goal = match parse_goal_objective_and_budget(args.trim()) {
Ok(parsed_goal) => parsed_goal,
Err(err) => {
self.add_error_message(err);
if source == SlashCommandDispatchSource::Live {
self.bottom_pane.drain_pending_submission_state();
}
return;
}
};
let objective = parsed_goal.objective.as_str();
if objective.is_empty() {
self.add_error_message("Goal objective must not be empty.".to_string());
self.add_info_message(
@@ -689,7 +778,8 @@ impl ChatWidget {
};
self.app_event_tx.send(AppEvent::SetThreadGoalObjective {
thread_id,
objective: objective.to_string(),
objective: parsed_goal.objective,
budget: parsed_goal.budget,
mode: ThreadGoalSetMode::ConfirmIfExists,
});
if source == SlashCommandDispatchSource::Live {
@@ -0,0 +1,11 @@
---
source: tui/src/chatwidget/tests/goal_menu.rs
expression: "render_bottom_popup(&chat, 80)"
---
| Set goal
| Budget: None tab focus, arrows cycle
| Objective:
| What should Codex keep working toward?
|
Press enter to confirm or esc to go back
@@ -42,6 +42,14 @@ async fn goal_menu_budget_limited_snapshot() {
assert_chatwidget_snapshot!("goal_menu_budget_limited", rendered_goal_summary(&mut rx));
}
#[tokio::test]
async fn goal_setup_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.show_goal_setup(ThreadId::new());
assert_chatwidget_snapshot!("goal_setup", render_bottom_popup(&chat, /*width*/ 80));
}
fn test_goal(
thread_id: ThreadId,
status: AppThreadGoalStatus,
@@ -52,6 +60,7 @@ fn test_goal(
objective: "Keep improving the bare goal command until it feels calm and useful."
.to_string(),
status,
budget: None,
token_budget,
tokens_used: 12_500,
time_used_seconds: 90,
@@ -1180,6 +1180,7 @@ async fn interrupted_turn_after_goal_budget_limited_uses_budget_message_snapshot
thread_id: "thread-1".to_string(),
objective: "Run until the token budget is limited".to_string(),
status: codex_app_server_protocol::ThreadGoalStatus::BudgetLimited,
budget: None,
token_budget: Some(10_000),
tokens_used: 10_500,
time_used_seconds: 0,
@@ -571,18 +571,59 @@ async fn goal_slash_command_emits_set_goal_event() {
let AppEvent::SetThreadGoalObjective {
thread_id: actual_thread_id,
objective,
budget,
mode,
} = event
else {
panic!("expected SetThreadGoalObjective, got {event:?}");
};
assert_eq!(actual_thread_id, thread_id);
assert_eq!(objective, "--tokens 98.5K improve benchmark coverage");
assert_eq!(objective, "improve benchmark coverage");
assert_eq!(
budget,
Some(codex_app_server_protocol::ThreadGoalBudgetParams::Tokens {
token_budget: 98_500,
})
);
assert_eq!(mode, crate::app_event::ThreadGoalSetMode::ConfirmIfExists);
assert_no_submit_op(&mut op_rx);
assert_eq!(recall_latest_after_clearing(&mut chat), command);
}
#[tokio::test]
async fn goal_slash_command_accepts_five_hour_limit_budget() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
let thread_id = ThreadId::new();
chat.thread_id = Some(thread_id);
let command = "/goal --5h-limit 7.5% finish the risky migration";
submit_composer_text(&mut chat, command);
let event = rx.try_recv().expect("expected goal objective event");
let AppEvent::SetThreadGoalObjective {
thread_id: actual_thread_id,
objective,
budget,
mode,
} = event
else {
panic!("expected SetThreadGoalObjective, got {event:?}");
};
assert_eq!(actual_thread_id, thread_id);
assert_eq!(objective, "finish the risky migration");
assert_eq!(
budget,
Some(
codex_app_server_protocol::ThreadGoalBudgetParams::FiveHourLimitPercent {
percent: 7.5
}
)
);
assert_eq!(mode, crate::app_event::ThreadGoalSetMode::ConfirmIfExists);
assert_no_submit_op(&mut op_rx);
}
#[tokio::test]
async fn goal_slash_command_uses_plain_text_for_mentions() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -1355,6 +1396,7 @@ async fn active_goal_without_follow_up_suppresses_agent_turn_complete_notificati
thread_id: "thread-1".to_string(),
objective: "finish the benchmark".to_string(),
status: codex_app_server_protocol::ThreadGoalStatus::Active,
budget: None,
token_budget: None,
tokens_used: 0,
time_used_seconds: 0,
@@ -1867,6 +1867,7 @@ fn test_thread_goal(
thread_id: "thread-1".to_string(),
objective: "Keep improving the benchmark".to_string(),
status,
budget: None,
token_budget,
tokens_used,
time_used_seconds: 30 * 60,
+61
View File
@@ -1,5 +1,6 @@
use crate::status::format_tokens_compact;
use codex_app_server_protocol::ThreadGoal;
use codex_app_server_protocol::ThreadGoalBudget;
use codex_app_server_protocol::ThreadGoalStatus;
pub(crate) fn format_goal_elapsed_seconds(seconds: i64) -> String {
@@ -51,10 +52,69 @@ pub(crate) fn goal_usage_summary(goal: &ThreadGoal) -> String {
format_tokens_compact(goal.tokens_used),
format_tokens_compact(token_budget)
));
} else if let Some(ThreadGoalBudget::FiveHourLimitPercent {
percent,
baseline_used_percent,
latest_used_percent,
baseline_resets_at,
..
}) = &goal.budget
{
parts.push(format!(
"5h limit: {} / {}.",
format_percent_points(latest_used_percent - baseline_used_percent),
format_percent_points(*percent)
));
if let Some(resets_at) = baseline_resets_at {
parts.push(format!(
"Started at {}; limit at {}; resets {}.",
format_percent(*baseline_used_percent),
format_percent(baseline_used_percent + percent),
format_unix_date(*resets_at)
));
}
}
parts.join(" ")
}
pub(crate) fn format_five_hour_goal_progress(budget: &ThreadGoalBudget) -> Option<String> {
match budget {
ThreadGoalBudget::FiveHourLimitPercent {
percent,
baseline_used_percent,
latest_used_percent,
..
} => Some(format!(
"{} / {}",
format_percent_points(latest_used_percent - baseline_used_percent),
format_percent_points(*percent)
)),
ThreadGoalBudget::Tokens { .. } => None,
}
}
fn format_percent_points(value: f64) -> String {
format!("+{}pp", format_percent_number(value.max(0.0)))
}
fn format_percent(value: f64) -> String {
format!("{}%", format_percent_number(value))
}
fn format_percent_number(value: f64) -> String {
if (value.fract()).abs() < 0.05 {
format!("{value:.0}")
} else {
format!("{value:.1}")
}
}
fn format_unix_date(value: i64) -> String {
chrono::DateTime::from_timestamp(value, 0)
.map(|date| date.format("%b %-d, %Y").to_string())
.unwrap_or_else(|| "unknown".to_string())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -86,6 +146,7 @@ mod tests {
objective: "Complete the task described in ../gameboy-long-running-prompt5.txt"
.to_string(),
status: ThreadGoalStatus::BudgetLimited,
budget: token_budget.map(|token_budget| ThreadGoalBudget::Tokens { token_budget }),
token_budget,
tokens_used,
time_used_seconds: 120,