mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Stream provisional text from thread/sample (#65167)
## Why Clients had to wait for the entire sample before they could display any assistant text. ## What changed Set `stream: true` to receive `thread/sample/textDelta` notifications while a sample is in progress. Each notification goes to the requesting connection and carries the original JSON-RPC `requestId` and a text `delta`. The stream excludes commentary and reasoning. The final RPC response still provides the complete sample and token usage. Discard provisional text if the request fails or the final `text` is null. Omitting `stream` or setting it to `false` returns only the final response. ## Testing Integration tests cover deltas arriving before completion, text supplied only when an output item completes, and custom tool calls producing a null sample even after provisional text has been streamed. GitOrigin-RevId: b2ad960420ce7789722e03f9f283781030cf61fb
This commit is contained in:
@@ -6653,6 +6653,27 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ThreadSampleTextDeltaNotification": {
|
||||
"properties": {
|
||||
"delta": {
|
||||
"description": "Provisional text. The final RPC response determines whether the sample is usable.",
|
||||
"type": "string"
|
||||
},
|
||||
"requestId": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/RequestId"
|
||||
}
|
||||
],
|
||||
"description": "The ID of the `thread/sample` request on this connection."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"delta",
|
||||
"requestId"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ThreadSearchPartialNotification": {
|
||||
"description": "A best-effort incremental batch for `thread/search/stream`. Match `requestId` to the request on this connection. Only a small subset of verified matches may be emitted; rows are unique and arrive in discovery order, but may be dropped under load or fall outside the final sorted page. Thread fields use stored metadata and the current watched status; live thread settings are enriched in the final response. Replace provisional rows with the authoritative final response. No partials follow it or an error.",
|
||||
"properties": {
|
||||
@@ -8231,6 +8252,26 @@
|
||||
"title": "Thread/tokenUsage/updatedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
"enum": [
|
||||
"thread/sample/textDelta"
|
||||
],
|
||||
"title": "Thread/sample/textDeltaNotificationMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/ThreadSampleTextDeltaNotification"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "Thread/sample/textDeltaNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
|
||||
+43
@@ -5312,6 +5312,26 @@
|
||||
"title": "Thread/tokenUsage/updatedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
"enum": [
|
||||
"thread/sample/textDelta"
|
||||
],
|
||||
"title": "Thread/sample/textDeltaNotificationMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/v2/ThreadSampleTextDeltaNotification"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "Thread/sample/textDeltaNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
@@ -26793,6 +26813,29 @@
|
||||
"title": "ThreadRevertedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ThreadSampleTextDeltaNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"delta": {
|
||||
"description": "Provisional text. The final RPC response determines whether the sample is usable.",
|
||||
"type": "string"
|
||||
},
|
||||
"requestId": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/v2/RequestId"
|
||||
}
|
||||
],
|
||||
"description": "The ID of the `thread/sample` request on this connection."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"delta",
|
||||
"requestId"
|
||||
],
|
||||
"title": "ThreadSampleTextDeltaNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ThreadSearchPartialNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "A best-effort incremental batch for `thread/search/stream`. Match `requestId` to the request on this connection. Only a small subset of verified matches may be emitted; rows are unique and arrive in discovery order, but may be dropped under load or fall outside the final sorted page. Thread fields use stored metadata and the current watched status; live thread settings are enriched in the final response. Replace provisional rows with the authoritative final response. No partials follow it or an error.",
|
||||
|
||||
+43
@@ -18617,6 +18617,26 @@
|
||||
"title": "Thread/tokenUsage/updatedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
"enum": [
|
||||
"thread/sample/textDelta"
|
||||
],
|
||||
"title": "Thread/sample/textDeltaNotificationMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/ThreadSampleTextDeltaNotification"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "Thread/sample/textDeltaNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
@@ -24415,6 +24435,29 @@
|
||||
"title": "ThreadRevertedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ThreadSampleTextDeltaNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"delta": {
|
||||
"description": "Provisional text. The final RPC response determines whether the sample is usable.",
|
||||
"type": "string"
|
||||
},
|
||||
"requestId": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/RequestId"
|
||||
}
|
||||
],
|
||||
"description": "The ID of the `thread/sample` request on this connection."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"delta",
|
||||
"requestId"
|
||||
],
|
||||
"title": "ThreadSampleTextDeltaNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ThreadSearchPartialNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "A best-effort incremental batch for `thread/search/stream`. Match `requestId` to the request on this connection. Only a small subset of verified matches may be emitted; rows are unique and arrive in discovery order, but may be dropped under load or fall outside the final sorted page. Thread fields use stored metadata and the current watched status; live thread settings are enriched in the final response. Replace provisional rows with the authoritative final response. No partials follow it or an error.",
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"definitions": {
|
||||
"RequestId": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"delta": {
|
||||
"description": "Provisional text. The final RPC response determines whether the sample is usable.",
|
||||
"type": "string"
|
||||
},
|
||||
"requestId": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/RequestId"
|
||||
}
|
||||
],
|
||||
"description": "The ID of the `thread/sample` request on this connection."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"delta",
|
||||
"requestId"
|
||||
],
|
||||
"title": "ThreadSampleTextDeltaNotification",
|
||||
"type": "object"
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
File diff suppressed because one or more lines are too long
+2
-1
File diff suppressed because one or more lines are too long
+14
@@ -0,0 +1,14 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { RequestId } from "../RequestId";
|
||||
|
||||
export type ThreadSampleTextDeltaNotification = {
|
||||
/**
|
||||
* The ID of the `thread/sample` request on this connection.
|
||||
*/
|
||||
requestId: RequestId,
|
||||
/**
|
||||
* Provisional text. The final RPC response determines whether the sample is usable.
|
||||
*/
|
||||
delta: string, };
|
||||
@@ -621,6 +621,7 @@ export type { ThreadResumeResponse } from "./ThreadResumeResponse";
|
||||
export type { ThreadRevertParams } from "./ThreadRevertParams";
|
||||
export type { ThreadRevertResponse } from "./ThreadRevertResponse";
|
||||
export type { ThreadRevertedNotification } from "./ThreadRevertedNotification";
|
||||
export type { ThreadSampleTextDeltaNotification } from "./ThreadSampleTextDeltaNotification";
|
||||
export type { ThreadSearchPartialNotification } from "./ThreadSearchPartialNotification";
|
||||
export type { ThreadSearchResult } from "./ThreadSearchResult";
|
||||
export type { ThreadSearchSortKey } from "./ThreadSearchSortKey";
|
||||
|
||||
@@ -2130,6 +2130,8 @@ server_notification_definitions! {
|
||||
#[experimental("thread/settings/updated")]
|
||||
ThreadSettingsUpdated => "thread/settings/updated" (v2::ThreadSettingsUpdatedNotification),
|
||||
ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification),
|
||||
#[experimental("thread/sample/textDelta")]
|
||||
ThreadSampleTextDelta => "thread/sample/textDelta" (v2::ThreadSampleTextDeltaNotification),
|
||||
TurnStarted => "turn/started" (v2::TurnStartedNotification),
|
||||
HookStarted => "hook/started" (v2::HookStartedNotification),
|
||||
TurnCompleted => "turn/completed" (v2::TurnCompletedNotification),
|
||||
|
||||
@@ -20,6 +20,9 @@ pub struct ThreadSampleParams {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub allow_in_progress_turn: bool,
|
||||
pub prompt: String,
|
||||
/// Send provisional assistant text via `thread/sample/textDelta` before the RPC completes.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub stream: bool,
|
||||
/// Override the model for this sample.
|
||||
/// Omit or pass `null` to inherit the source thread's model.
|
||||
#[ts(optional = nullable)]
|
||||
@@ -55,6 +58,16 @@ pub struct ThreadSampleResponse {
|
||||
pub output_tokens: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ThreadSampleTextDeltaNotification {
|
||||
/// The ID of the `thread/sample` request on this connection.
|
||||
pub request_id: RequestId,
|
||||
/// Provisional text. The final RPC response determines whether the sample is usable.
|
||||
pub delta: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(export_to = "v2/")]
|
||||
|
||||
@@ -325,6 +325,18 @@ The result measures the supplied recording under the thread's current policy,
|
||||
tool catalog and environment. It grants no permission to execute the call.
|
||||
Direct client input to V2 workers remains restricted.
|
||||
|
||||
## Thread sampling
|
||||
|
||||
`thread/sample` requires the `experimentalApi` opt-in. Set `stream: true` to
|
||||
receive `thread/sample/textDelta` notifications on the requesting connection.
|
||||
Each notification contains the original JSON-RPC `requestId` and a text
|
||||
`delta`. Commentary and reasoning are excluded.
|
||||
|
||||
The final RPC response still contains the complete sample and token usage.
|
||||
Treat deltas as provisional and discard them if the request fails or the final
|
||||
`text` is null. Omit `stream` or set it to `false` to receive just the final
|
||||
response.
|
||||
|
||||
# Thread removal
|
||||
|
||||
`thread/archive` and `thread/delete` reject attempts to remove a live internal
|
||||
|
||||
@@ -121,6 +121,7 @@ fn server_notification_requires_delivery(notification: &ServerNotification) -> b
|
||||
notification,
|
||||
ServerNotification::ProcessOutputDelta(_)
|
||||
| ServerNotification::ProcessExited(_)
|
||||
| ServerNotification::ThreadSampleTextDelta(_)
|
||||
| ServerNotification::TurnCompleted(_)
|
||||
| ServerNotification::ThreadQueueChanged(_)
|
||||
| ServerNotification::ThreadSettingsUpdated(_)
|
||||
|
||||
@@ -1487,7 +1487,12 @@ impl MessageProcessor {
|
||||
}
|
||||
ClientRequest::ThreadSample { params, .. } => self
|
||||
.thread_processor
|
||||
.thread_sample(params, Arc::clone(&session.rpc_gate), request_context)
|
||||
.thread_sample(
|
||||
&request_id,
|
||||
params,
|
||||
Arc::clone(&session.rpc_gate),
|
||||
request_context,
|
||||
)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::ThreadSampleCancel { params, .. } => {
|
||||
|
||||
@@ -78,6 +78,7 @@ pub(crate) fn without_notification_media(notification: ServerNotification) -> Se
|
||||
| ServerNotification::EnvironmentDisconnected(_)
|
||||
| ServerNotification::ThreadSettingsUpdated(_)
|
||||
| ServerNotification::ThreadTokenUsageUpdated(_)
|
||||
| ServerNotification::ThreadSampleTextDelta(_)
|
||||
| ServerNotification::TurnStarted(_)
|
||||
| ServerNotification::HookStarted(_)
|
||||
| ServerNotification::TurnCompleted(_)
|
||||
|
||||
@@ -716,6 +716,7 @@ impl ThreadRequestProcessor {
|
||||
|
||||
pub(crate) async fn thread_sample(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: ThreadSampleParams,
|
||||
rpc_gate: Arc<ConnectionRpcGate>,
|
||||
context: RequestContext,
|
||||
@@ -743,6 +744,8 @@ impl ThreadRequestProcessor {
|
||||
},
|
||||
&self.background_tasks,
|
||||
rpc_gate,
|
||||
&self.outgoing,
|
||||
request_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
//! Captures one model response on an inherited ephemeral fork before Core can act on it.
|
||||
//! Tool calls produce a null sample; an owned task retains startup and cleanup.
|
||||
//! Opt-in text deltas are provisional. An owned task retains startup and cleanup.
|
||||
|
||||
use crate::connection_rpc_gate::ConnectionRpcGate;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::request_processors::build_legacy_api_turns_from_rollout_items;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadSampleParams;
|
||||
use codex_app_server_protocol::ThreadSampleResponse;
|
||||
use codex_app_server_protocol::ThreadSampleTextDeltaNotification;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::ForkSnapshot;
|
||||
@@ -49,6 +53,7 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::Instant;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -62,7 +67,6 @@ const THREAD_SNAPSHOT_NOTE: &str = concat!(
|
||||
"A tool call that was pending at capture may appear as \"aborted\" in this copy.\n",
|
||||
);
|
||||
type SampleResult = Result<ThreadSampleResponse, JSONRPCErrorError>;
|
||||
type SampleSender = Arc<Mutex<Option<oneshot::Sender<SampleResult>>>>;
|
||||
|
||||
/// Marks private sample children from startup through cleanup.
|
||||
pub(crate) struct SampleThread;
|
||||
@@ -81,6 +85,8 @@ pub(crate) async fn generate_sample(
|
||||
task: SampleTask,
|
||||
tasks: &TaskTracker,
|
||||
rpc_gate: Arc<ConnectionRpcGate>,
|
||||
outgoing: &OutgoingMessageSender,
|
||||
request_id: &ConnectionRequestId,
|
||||
) -> SampleResult {
|
||||
let deadline = Instant::now() + SAMPLE_TIMEOUT;
|
||||
if task.params.expected_turn_id.trim().is_empty() || task.params.prompt.trim().is_empty() {
|
||||
@@ -89,23 +95,56 @@ pub(crate) async fn generate_sample(
|
||||
));
|
||||
}
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
let (delta_sender, deltas) = task
|
||||
.params
|
||||
.stream
|
||||
.then(|| mpsc::channel(/*buffer*/ 16))
|
||||
.unzip();
|
||||
let cancellation = task.cancellation.clone();
|
||||
let originator = AuthStorageOriginator::current();
|
||||
tasks.spawn(async move {
|
||||
rpc_gate
|
||||
.run(originator.scope(async move {
|
||||
let result = Box::pin(task.run(deadline)).await;
|
||||
let result = Box::pin(task.run(deadline, delta_sender)).await;
|
||||
let _ = sender.send(result);
|
||||
}))
|
||||
.await;
|
||||
});
|
||||
tokio::time::timeout_at(deadline, receiver)
|
||||
.await
|
||||
.map_err(|_| internal_error("sample timed out"))?
|
||||
.map_err(|_| internal_error("sample task stopped"))?
|
||||
// The request owns delivery so deltas are queued before its final reply and stop on timeout.
|
||||
tokio::time::timeout_at(deadline, async {
|
||||
if let Some(mut deltas) = deltas {
|
||||
cancellation
|
||||
.run_until_cancelled(async {
|
||||
while let Some(delta) = deltas.recv().await {
|
||||
outgoing
|
||||
.send_server_notification_to_connections(
|
||||
&[request_id.connection_id],
|
||||
ServerNotification::ThreadSampleTextDelta(
|
||||
ThreadSampleTextDeltaNotification {
|
||||
request_id: request_id.request_id.clone(),
|
||||
delta,
|
||||
},
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
receiver
|
||||
.await
|
||||
.map_err(|_| internal_error("sample task stopped"))?
|
||||
})
|
||||
.await
|
||||
.map_err(|_| internal_error("sample timed out"))?
|
||||
}
|
||||
|
||||
impl SampleTask {
|
||||
async fn run(self, deadline: Instant) -> SampleResult {
|
||||
async fn run(
|
||||
self,
|
||||
deadline: Instant,
|
||||
delta_sender: Option<mpsc::Sender<String>>,
|
||||
) -> SampleResult {
|
||||
let Self {
|
||||
manager,
|
||||
store,
|
||||
@@ -256,7 +295,10 @@ impl SampleTask {
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.insert(
|
||||
fork.thread_id.to_string(),
|
||||
Arc::new(Mutex::new(Some(sender))),
|
||||
Arc::new(SampleCapture {
|
||||
result: Mutex::new(Some(sender)),
|
||||
deltas: delta_sender,
|
||||
}),
|
||||
);
|
||||
let sample = async {
|
||||
Box::pin(fork.thread.restore_thread_settings(*settings))
|
||||
@@ -360,7 +402,13 @@ impl SampleTask {
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct SampleResponseRegistry {
|
||||
captures: Mutex<HashMap<String, SampleSender>>,
|
||||
captures: Mutex<HashMap<String, Arc<SampleCapture>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SampleCapture {
|
||||
result: Mutex<Option<oneshot::Sender<SampleResult>>>,
|
||||
deltas: Option<mpsc::Sender<String>>,
|
||||
}
|
||||
|
||||
impl ModelRequestContributor for SampleResponseRegistry {
|
||||
@@ -373,22 +421,23 @@ impl ModelRequestContributor for SampleResponseRegistry {
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(input.thread_id)
|
||||
.cloned()
|
||||
.map(|sender| {
|
||||
Box::new(SampleInterceptor { sender }) as Box<dyn ModelResponseInterceptor>
|
||||
.map(|capture| {
|
||||
Box::new(SampleInterceptor { capture }) as Box<dyn ModelResponseInterceptor>
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SampleInterceptor {
|
||||
sender: SampleSender,
|
||||
capture: Arc<SampleCapture>,
|
||||
}
|
||||
|
||||
impl ModelResponseInterceptor for SampleInterceptor {
|
||||
fn intercept(self: Box<Self>, upstream: ModelResponseStream) -> ModelResponseStream {
|
||||
Box::pin(futures::stream::once(async move {
|
||||
let result = collect_response(upstream).await;
|
||||
let result = collect_response(upstream, self.capture.deltas.as_ref()).await;
|
||||
if let Some(sender) = self
|
||||
.sender
|
||||
.capture
|
||||
.result
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.take()
|
||||
@@ -401,11 +450,46 @@ impl ModelResponseInterceptor for SampleInterceptor {
|
||||
}
|
||||
}
|
||||
|
||||
async fn collect_response(mut upstream: ModelResponseStream) -> SampleResult {
|
||||
async fn collect_response(
|
||||
mut upstream: ModelResponseStream,
|
||||
deltas: Option<&mpsc::Sender<String>>,
|
||||
) -> SampleResult {
|
||||
let mut text = String::new();
|
||||
let mut text_only = true;
|
||||
let mut streamed_item = None::<String>;
|
||||
let mut streamed_bytes = 0usize;
|
||||
while let Some(event) = upstream.next().await {
|
||||
match event.map_err(|error| internal_error(format!("sample failed: {error}")))? {
|
||||
let event = event.map_err(|error| internal_error(format!("sample failed: {error}")))?;
|
||||
let prefix = match &event {
|
||||
ResponseEvent::OutputItemAdded(_) => {
|
||||
streamed_item = None;
|
||||
None
|
||||
}
|
||||
ResponseEvent::OutputItemDone(_) => streamed_item.take(),
|
||||
_ => None,
|
||||
};
|
||||
let mut delta = String::new();
|
||||
match event {
|
||||
ResponseEvent::OutputItemAdded(ResponseItem::Message {
|
||||
role,
|
||||
phase,
|
||||
content,
|
||||
..
|
||||
}) if deltas.is_some()
|
||||
&& text_only
|
||||
&& role == "assistant"
|
||||
&& phase != Some(MessagePhase::Commentary) =>
|
||||
{
|
||||
streamed_item = Some(String::new());
|
||||
delta = content
|
||||
.into_iter()
|
||||
.filter_map(|item| match item {
|
||||
ContentItem::OutputText { text, .. } => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
ResponseEvent::OutputTextDelta(part) if streamed_item.is_some() => delta = part,
|
||||
ResponseEvent::OutputItemDone(ResponseItem::Message {
|
||||
phase: Some(MessagePhase::Commentary),
|
||||
..
|
||||
@@ -413,6 +497,7 @@ async fn collect_response(mut upstream: ModelResponseStream) -> SampleResult {
|
||||
ResponseEvent::OutputItemDone(ResponseItem::Message { role, content, .. })
|
||||
if role == "assistant" =>
|
||||
{
|
||||
let start = text.len();
|
||||
for item in content {
|
||||
match item {
|
||||
ContentItem::OutputText { text: part, .. } => {
|
||||
@@ -424,6 +509,14 @@ async fn collect_response(mut upstream: ModelResponseStream) -> SampleResult {
|
||||
_ => text_only = false,
|
||||
}
|
||||
}
|
||||
// A provider can supply the whole message only when its item finishes.
|
||||
if text_only
|
||||
&& deltas.is_some()
|
||||
&& let Some(tail) =
|
||||
text[start..].strip_prefix(prefix.as_deref().unwrap_or_default())
|
||||
{
|
||||
delta = tail.to_owned();
|
||||
}
|
||||
}
|
||||
ResponseEvent::OutputItemDone(ResponseItem::Reasoning { .. }) => {}
|
||||
ResponseEvent::OutputItemDone(_)
|
||||
@@ -451,6 +544,18 @@ async fn collect_response(mut upstream: ModelResponseStream) -> SampleResult {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(deltas) = deltas
|
||||
&& !delta.is_empty()
|
||||
{
|
||||
streamed_bytes = streamed_bytes.saturating_add(delta.len());
|
||||
if streamed_bytes > MAX_OUTPUT_BYTES {
|
||||
return Err(internal_error("sample output exceeds limit"));
|
||||
}
|
||||
if let Some(item) = &mut streamed_item {
|
||||
item.push_str(&delta);
|
||||
}
|
||||
let _ = deltas.send(delta).await;
|
||||
}
|
||||
}
|
||||
Err(internal_error("sample stream ended before completion"))
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ use codex_app_server_protocol::ThreadLoadedListResponse;
|
||||
use codex_app_server_protocol::ThreadSampleCancelResponse;
|
||||
use codex_app_server_protocol::ThreadSampleParams;
|
||||
use codex_app_server_protocol::ThreadSampleResponse;
|
||||
use codex_app_server_protocol::ThreadSampleTextDeltaNotification;
|
||||
use codex_app_server_protocol::ThreadSource;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::TurnCompletedNotification;
|
||||
@@ -146,6 +147,19 @@ async fn sample(
|
||||
timeout(WAIT, client.read_response(id)).await?
|
||||
}
|
||||
|
||||
async fn assert_sample_delta(client: &mut TestAppServer, id: i64, delta: &str) -> Result<()> {
|
||||
let notification: ThreadSampleTextDeltaNotification =
|
||||
timeout(WAIT, client.read_notification("thread/sample/textDelta")).await??;
|
||||
assert_eq!(
|
||||
notification,
|
||||
ThreadSampleTextDeltaNotification {
|
||||
request_id: RequestId::Integer(id),
|
||||
delta: delta.to_string(),
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ready_parent(
|
||||
client: &mut TestAppServer,
|
||||
params: ThreadStartParams,
|
||||
@@ -583,6 +597,10 @@ async fn sample_in_progress_turn_uses_captured_history(
|
||||
}]);
|
||||
}
|
||||
let child_request_index = streams.len() + 1;
|
||||
let mut commentary = responses::ev_message_item_added("commentary", "");
|
||||
commentary["item"]["phase"] = json!("commentary");
|
||||
let mut commentary_done = responses::ev_assistant_message("commentary", "Progress");
|
||||
commentary_done["item"]["phase"] = json!("commentary");
|
||||
streams.extend([
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
@@ -591,13 +609,28 @@ async fn sample_in_progress_turn_uses_captured_history(
|
||||
responses::ev_completed("parent"),
|
||||
]),
|
||||
}],
|
||||
vec![StreamingSseChunk {
|
||||
gate: Some(sample_gate),
|
||||
body: responses::sse(vec![
|
||||
responses::ev_assistant_message("prediction", "Continue"),
|
||||
responses::ev_completed("sample"),
|
||||
]),
|
||||
}],
|
||||
vec![
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: responses::sse(vec![
|
||||
commentary,
|
||||
responses::ev_output_text_delta("Progress"),
|
||||
commentary_done,
|
||||
responses::ev_reasoning_summary_text_delta("Summary"),
|
||||
responses::ev_message_item_added("prediction", "Con"),
|
||||
responses::ev_output_text_delta("tinu"),
|
||||
]),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: Some(sample_gate),
|
||||
body: responses::sse(vec![
|
||||
responses::ev_output_text_delta("e"),
|
||||
responses::ev_assistant_message("prediction", "Continue"),
|
||||
responses::ev_assistant_message("suffix", "!"),
|
||||
responses::ev_completed("sample"),
|
||||
]),
|
||||
},
|
||||
],
|
||||
vec![StreamingSseChunk {
|
||||
gate: None,
|
||||
body: responses::sse(vec![responses::ev_completed("parent-done")]),
|
||||
@@ -646,11 +679,12 @@ async fn sample_in_progress_turn_uses_captured_history(
|
||||
"thread/sample",
|
||||
Some(json!({
|
||||
"threadId": parent, "expectedTurnId": started.turn.id,
|
||||
"allowInProgressTurn": true, "prompt": "Predict"
|
||||
"allowInProgressTurn": true, "prompt": "Predict", "stream": true
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
timeout(WAIT, server.wait_for_request_count(child_request_index + 1)).await?;
|
||||
assert_sample_delta(&mut client, sample_id, "Con").await?;
|
||||
assert_sample_delta(&mut client, sample_id, "tinu").await?;
|
||||
// Finish the parent after the child has captured the pending call.
|
||||
client
|
||||
.send_response(
|
||||
@@ -727,7 +761,17 @@ async fn sample_in_progress_turn_uses_captured_history(
|
||||
release_sample.send(()).expect("sample stream waiting");
|
||||
let response: ThreadSampleResponse = timeout(WAIT, client.read_response(sample_id)).await??;
|
||||
assert_eq!(response.source_turn_id, started.turn.id);
|
||||
assert_eq!(response.text.as_deref(), Some("Continue"));
|
||||
assert_eq!(response.text.as_deref(), Some("Continue!"));
|
||||
assert_eq!(
|
||||
client
|
||||
.pending_notification_methods()
|
||||
.iter()
|
||||
.filter(|method| *method == "thread/sample/textDelta")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
assert_sample_delta(&mut client, sample_id, "e").await?;
|
||||
assert_sample_delta(&mut client, sample_id, "!").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1028,8 +1072,10 @@ async fn sample_skips_inherited_stop_hooks() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(false; "buffered")]
|
||||
#[test_case(true; "streaming")]
|
||||
#[tokio::test]
|
||||
async fn sample_returns_null_for_custom_tool_calls() -> Result<()> {
|
||||
async fn sample_returns_null_for_custom_tool_calls(stream: bool) -> Result<()> {
|
||||
let server = responses::start_mock_server().await;
|
||||
let mut tool = responses::ev_custom_tool_call(
|
||||
"call",
|
||||
@@ -1053,16 +1099,19 @@ async fn sample_returns_null_for_custom_tool_calls() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let mut client = client(&home, &server, /*overrides*/ true).await?;
|
||||
let (parent_id, turn_id) = ready_parent(&mut client, ThreadStartParams::default()).await?;
|
||||
let response = sample(
|
||||
&mut client,
|
||||
ThreadSampleParams {
|
||||
thread_id: parent_id.clone(),
|
||||
expected_turn_id: turn_id.clone(),
|
||||
prompt: "Call the tool".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let id = client
|
||||
.send_raw_request(
|
||||
"thread/sample",
|
||||
Some(serde_json::to_value(ThreadSampleParams {
|
||||
thread_id: parent_id.clone(),
|
||||
expected_turn_id: turn_id.clone(),
|
||||
prompt: "Call the tool".to_string(),
|
||||
stream,
|
||||
..Default::default()
|
||||
})?),
|
||||
)
|
||||
.await?;
|
||||
let response: ThreadSampleResponse = timeout(WAIT, client.read_response(id)).await??;
|
||||
assert_eq!(
|
||||
response,
|
||||
ThreadSampleResponse {
|
||||
@@ -1074,6 +1123,18 @@ async fn sample_returns_null_for_custom_tool_calls() -> Result<()> {
|
||||
output_tokens: Some(5),
|
||||
}
|
||||
);
|
||||
let method = "thread/sample/textDelta";
|
||||
assert_eq!(
|
||||
client
|
||||
.pending_notification_methods()
|
||||
.iter()
|
||||
.filter(|name| *name == method)
|
||||
.count(),
|
||||
usize::from(stream)
|
||||
);
|
||||
if stream {
|
||||
assert_sample_delta(&mut client, id, "Discard this partial answer").await?;
|
||||
}
|
||||
assert_eq!(mock.requests().len(), 2);
|
||||
let id = client
|
||||
.send_raw_request("thread/loaded/list", Some(json!({})))
|
||||
@@ -1295,6 +1356,7 @@ async fn sample_wait_keeps_parent_responsive_and_reclaims_child(stop: SampleStop
|
||||
thread_id: parent_id.clone(),
|
||||
expected_turn_id: turn_id,
|
||||
prompt: "Predict".to_string(),
|
||||
stream: true,
|
||||
..Default::default()
|
||||
};
|
||||
let sample_id = client
|
||||
|
||||
@@ -219,6 +219,7 @@ pub(super) fn server_notification_thread_target(
|
||||
| ServerNotification::CommandExecOutputDelta(_)
|
||||
| ServerNotification::ProcessOutputDelta(_)
|
||||
| ServerNotification::ProcessExited(_)
|
||||
| ServerNotification::ThreadSampleTextDelta(_)
|
||||
| ServerNotification::McpServerEventStream(_)
|
||||
| ServerNotification::FsChanged(_)
|
||||
| ServerNotification::WindowsWorldWritableWarning(_)
|
||||
|
||||
@@ -360,6 +360,7 @@ impl ThreadEventStore {
|
||||
| ServerNotification::CommandExecOutputDelta(_)
|
||||
| ServerNotification::ProcessOutputDelta(_)
|
||||
| ServerNotification::ProcessExited(_)
|
||||
| ServerNotification::ThreadSampleTextDelta(_)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -439,6 +439,7 @@ impl ChatWidget {
|
||||
| ServerNotification::CommandExecOutputDelta(_)
|
||||
| ServerNotification::ProcessOutputDelta(_)
|
||||
| ServerNotification::ProcessExited(_)
|
||||
| ServerNotification::ThreadSampleTextDelta(_)
|
||||
| ServerNotification::McpServerEventStream(_)
|
||||
| ServerNotification::FileChangePatchUpdated(_)
|
||||
| ServerNotification::McpToolCallProgress(_)
|
||||
|
||||
@@ -77,6 +77,7 @@ from .v2_all import ThreadRealtimeStartedNotification
|
||||
from .v2_all import ThreadRealtimeTranscriptDeltaNotification
|
||||
from .v2_all import ThreadRealtimeTranscriptDoneNotification
|
||||
from .v2_all import ThreadRevertedNotification
|
||||
from .v2_all import ThreadSampleTextDeltaNotification
|
||||
from .v2_all import ThreadSearchPartialNotification
|
||||
from .v2_all import ThreadSectionChangedNotification
|
||||
from .v2_all import ThreadSettingsUpdatedNotification
|
||||
@@ -164,6 +165,7 @@ KnownNotificationPayload: TypeAlias = (
|
||||
| ThreadRealtimeTranscriptDeltaNotification
|
||||
| ThreadRealtimeTranscriptDoneNotification
|
||||
| ThreadRevertedNotification
|
||||
| ThreadSampleTextDeltaNotification
|
||||
| ThreadSearchPartialNotification
|
||||
| ThreadSectionChangedNotification
|
||||
| ThreadSettingsUpdatedNotification
|
||||
@@ -254,6 +256,7 @@ NOTIFICATION_MODELS: dict[str, type[KnownNotificationPayload]] = {
|
||||
"thread/realtime/transcript/delta": ThreadRealtimeTranscriptDeltaNotification,
|
||||
"thread/realtime/transcript/done": ThreadRealtimeTranscriptDoneNotification,
|
||||
"thread/reverted": ThreadRevertedNotification,
|
||||
"thread/sample/textDelta": ThreadSampleTextDeltaNotification,
|
||||
"thread/search/partial": ThreadSearchPartialNotification,
|
||||
"thread/section/changed": ThreadSectionChangedNotification,
|
||||
"thread/settings/updated": ThreadSettingsUpdatedNotification,
|
||||
|
||||
@@ -6802,6 +6802,25 @@ class ThreadRevertedNotification(BaseModel):
|
||||
thread_id: Annotated[str, Field(alias="threadId")]
|
||||
|
||||
|
||||
class ThreadSampleTextDeltaNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
delta: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Provisional text. The final RPC response determines whether the sample is usable."
|
||||
),
|
||||
]
|
||||
request_id: Annotated[
|
||||
RequestId,
|
||||
Field(
|
||||
alias="requestId",
|
||||
description="The ID of the `thread/sample` request on this connection.",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class ThreadSearchSortKey(Enum):
|
||||
created_at = "created_at"
|
||||
updated_at = "updated_at"
|
||||
@@ -10535,6 +10554,23 @@ class ThreadProjectUpdatedServerNotification(BaseModel):
|
||||
params: ThreadProjectUpdatedNotification
|
||||
|
||||
|
||||
class ThreadSampleTextDeltaServerNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
)
|
||||
emitted_at_ms: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
alias="emittedAtMs",
|
||||
description="Unix timestamp (in milliseconds) when app-server emitted this notification.",
|
||||
),
|
||||
] = None
|
||||
method: Annotated[
|
||||
Literal["thread/sample/textDelta"], Field(title="Thread/sample/textDeltaNotificationMethod")
|
||||
]
|
||||
params: ThreadSampleTextDeltaNotification
|
||||
|
||||
|
||||
class HookStartedServerNotification(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
@@ -14608,6 +14644,7 @@ class ServerNotification(
|
||||
| ThreadEnvironmentDisconnectedServerNotification
|
||||
| ThreadSettingsUpdatedServerNotification
|
||||
| ThreadTokenUsageUpdatedServerNotification
|
||||
| ThreadSampleTextDeltaServerNotification
|
||||
| TurnStartedServerNotification
|
||||
| HookStartedServerNotification
|
||||
| TurnCompletedServerNotification
|
||||
@@ -14698,6 +14735,7 @@ class ServerNotification(
|
||||
| ThreadEnvironmentDisconnectedServerNotification
|
||||
| ThreadSettingsUpdatedServerNotification
|
||||
| ThreadTokenUsageUpdatedServerNotification
|
||||
| ThreadSampleTextDeltaServerNotification
|
||||
| TurnStartedServerNotification
|
||||
| HookStartedServerNotification
|
||||
| TurnCompletedServerNotification
|
||||
|
||||
Reference in New Issue
Block a user