From d489e6bbeab5ab053afe2f6d0bbece2fca0dd324 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Fri, 13 Nov 2026 22:38:36 -0500 Subject: [PATCH] inputs: hold a waiting message while it is edited, and put the edit in its place --- cli/internal/daemon/protocol/api.gen.go | 303 ++++++++++++++++++ cli/internal/daemon/protocol/digest.gen.go | 2 +- docs/openapi.yaml | 162 ++++++++++ src/albedo/daemon/api_digest.gleam | 2 +- src/albedo/daemon/http_api.gleam | 8 + src/albedo/daemon/http_sessions.gleam | 110 ++++++- src/albedo/daemon/inbox.gleam | 24 ++ src/albedo/daemon/mail.gleam | 27 ++ src/albedo/daemon/server.gleam | 12 +- src/albedo/daemon/session.gleam | 128 ++++++++ src/albedo/daemon/session_state.gleam | 5 + .../bedrock_replay_preflight_test.gleam | 2 + test/e2e/queue_test.py | 91 +++++- web/src/lib/api.gen.d.ts | 155 +++++++++ 14 files changed, 1025 insertions(+), 6 deletions(-) diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 2d0759eda..b7e8f782f 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -1700,6 +1700,18 @@ type InputDecision struct { Kind string `json:"kind"` } +// InputEdit defines model for InputEdit. +type InputEdit struct { + // Input Examples: {"acceptance_order":1,"accepted_at":"2026-10-02T14:00:00Z","admission":"accepted","blocking_reason":null,"client_id":"draft-1","delivery":"pending","http_status":202,"id":"01a0fcea-2b00-7000-8000-000000000002","kind":"message","problem":null,"session_id":"01a0fcea-2b00-7000-8000-000000000001","transcript_position":null,"turn":null} + Input Input `json:"input"` +} + +// InputHold defines model for InputHold. +type InputHold struct { + // LeaseMs How long the hold lasts unless the message is held again. + LeaseMs int64 `json:"lease_ms"` +} + // InputRequest defines model for InputRequest. type InputRequest = json.RawMessage @@ -5223,6 +5235,12 @@ type PutInputJSONRequestBody = InputRequest // CancelInputJSONRequestBody defines body for CancelInput for application/json ContentType. type CancelInputJSONRequestBody = EmptyRequest +// EditInputJSONRequestBody defines body for EditInput for application/json ContentType. +type EditInputJSONRequestBody = MessageInputRequest + +// HoldInputJSONRequestBody defines body for HoldInput for application/json ContentType. +type HoldInputJSONRequestBody = EmptyRequest + // InterruptSessionJSONRequestBody defines body for InterruptSession for application/json ContentType. type InterruptSessionJSONRequestBody = InterruptRequest @@ -6507,6 +6525,49 @@ type ClientInterface interface { // Corresponds with POST /sessions/{session_id}/inputs/{input_id}/cancel (the `CancelInput` operationId). CancelInput(ctx context.Context, sessionID ID, inputID ID, params *CancelInputParams, body CancelInputJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // EditInputWithBody Put an edited message in place of a waiting one + // + // Replaces a person's typed message that still waits, keeping its id and its place in the queue, and releases any hold on it. 409 input_not_waiting once the session read it or it was cancelled. + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /sessions/{session_id}/inputs/{input_id}/edit (the `EditInput` operationId). + EditInputWithBody(ctx context.Context, sessionID ID, inputID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // EditInput Put an edited message in place of a waiting one + // + // Replaces a person's typed message that still waits, keeping its id and its place in the queue, and releases any hold on it. 409 input_not_waiting once the session read it or it was cancelled. + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /sessions/{session_id}/inputs/{input_id}/edit (the `EditInput` operationId). + EditInput(ctx context.Context, sessionID ID, inputID ID, body EditInputJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ReleaseInput Let a held message be read as it is + // + // Idempotent. A message that was never held is unaffected. + // + // Corresponds with DELETE /sessions/{session_id}/inputs/{input_id}/hold (the `ReleaseInput` operationId). + ReleaseInput(ctx context.Context, sessionID ID, inputID ID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // HoldInputWithBody Hold a waiting message while it is edited + // + // Holds a person's typed message that still waits in the session's queue, or renews the hold. Neither it nor anything queued after it is read until the edit is saved, the hold is released, or lease_ms pass without another hold. 409 input_not_waiting once the session read the message or it was cancelled; 409 input_not_editable for any other input. + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /sessions/{session_id}/inputs/{input_id}/hold (the `HoldInput` operationId). + HoldInputWithBody(ctx context.Context, sessionID ID, inputID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // HoldInput Hold a waiting message while it is edited + // + // Holds a person's typed message that still waits in the session's queue, or renews the hold. Neither it nor anything queued after it is read until the edit is saved, the hold is released, or lease_ms pass without another hold. 409 input_not_waiting once the session read the message or it was cancelled; 409 input_not_editable for any other input. + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /sessions/{session_id}/inputs/{input_id}/hold (the `HoldInput` operationId). + HoldInput(ctx context.Context, sessionID ID, inputID ID, body HoldInputJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // InterruptSessionWithBody Interrupt a captured run and waiting prefix // // Capture run_id and through_input_order from the installed session. Retry cannot interrupt a later run or cancel newer inputs. @@ -9530,6 +9591,99 @@ func (c *Client) CancelInput(ctx context.Context, sessionID ID, inputID ID, para return c.Client.Do(req) } +// EditInputWithBody Put an edited message in place of a waiting one +// +// Replaces a person's typed message that still waits, keeping its id and its place in the queue, and releases any hold on it. 409 input_not_waiting once the session read it or it was cancelled. +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /sessions/{session_id}/inputs/{input_id}/edit (the `EditInput` operationId). +func (c *Client) EditInputWithBody(ctx context.Context, sessionID ID, inputID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewEditInputRequestWithBody(c.Server, sessionID, inputID, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// EditInput Put an edited message in place of a waiting one +// +// Replaces a person's typed message that still waits, keeping its id and its place in the queue, and releases any hold on it. 409 input_not_waiting once the session read it or it was cancelled. +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /sessions/{session_id}/inputs/{input_id}/edit (the `EditInput` operationId). +func (c *Client) EditInput(ctx context.Context, sessionID ID, inputID ID, body EditInputJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewEditInputRequest(c.Server, sessionID, inputID, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ReleaseInput Let a held message be read as it is +// +// Idempotent. A message that was never held is unaffected. +// +// Corresponds with DELETE /sessions/{session_id}/inputs/{input_id}/hold (the `ReleaseInput` operationId). +func (c *Client) ReleaseInput(ctx context.Context, sessionID ID, inputID ID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewReleaseInputRequest(c.Server, sessionID, inputID) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// HoldInputWithBody Hold a waiting message while it is edited +// +// Holds a person's typed message that still waits in the session's queue, or renews the hold. Neither it nor anything queued after it is read until the edit is saved, the hold is released, or lease_ms pass without another hold. 409 input_not_waiting once the session read the message or it was cancelled; 409 input_not_editable for any other input. +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /sessions/{session_id}/inputs/{input_id}/hold (the `HoldInput` operationId). +func (c *Client) HoldInputWithBody(ctx context.Context, sessionID ID, inputID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewHoldInputRequestWithBody(c.Server, sessionID, inputID, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// HoldInput Hold a waiting message while it is edited +// +// Holds a person's typed message that still waits in the session's queue, or renews the hold. Neither it nor anything queued after it is read until the edit is saved, the hold is released, or lease_ms pass without another hold. 409 input_not_waiting once the session read the message or it was cancelled; 409 input_not_editable for any other input. +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /sessions/{session_id}/inputs/{input_id}/hold (the `HoldInput` operationId). +func (c *Client) HoldInput(ctx context.Context, sessionID ID, inputID ID, body HoldInputJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewHoldInputRequest(c.Server, sessionID, inputID, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + // InterruptSessionWithBody Interrupt a captured run and waiting prefix // // Capture run_id and through_input_order from the installed session. Retry cannot interrupt a later run or cancel newer inputs. @@ -16507,6 +16661,155 @@ func NewCancelInputRequestWithBody(server string, sessionID ID, inputID ID, para return req, nil } +// NewEditInputRequest calls the generic EditInput builder with application/json body +func NewEditInputRequest(server string, sessionID ID, inputID ID, body EditInputJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewEditInputRequestWithBody(server, sessionID, inputID, "application/json", bodyReader) +} + +// NewEditInputRequestWithBody constructs an http.Request for the EditInput method, with any body, and a specified content type +func NewEditInputRequestWithBody(server string, sessionID ID, inputID ID, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "session_id", sessionID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "input_id", inputID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/sessions/%s/inputs/%s/edit", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewReleaseInputRequest constructs an http.Request for the ReleaseInput method +func NewReleaseInputRequest(server string, sessionID ID, inputID ID) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "session_id", sessionID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "input_id", inputID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/sessions/%s/inputs/%s/hold", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewHoldInputRequest calls the generic HoldInput builder with application/json body +func NewHoldInputRequest(server string, sessionID ID, inputID ID, body HoldInputJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewHoldInputRequestWithBody(server, sessionID, inputID, "application/json", bodyReader) +} + +// NewHoldInputRequestWithBody constructs an http.Request for the HoldInput method, with any body, and a specified content type +func NewHoldInputRequestWithBody(server string, sessionID ID, inputID ID, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "session_id", sessionID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "input_id", inputID, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/sessions/%s/inputs/%s/hold", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + // NewInterruptSessionRequest calls the generic InterruptSession builder with application/json body func NewInterruptSessionRequest(server string, sessionID ID, body InterruptSessionJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader diff --git a/cli/internal/daemon/protocol/digest.gen.go b/cli/internal/daemon/protocol/digest.gen.go index d59ca755a..2375c6aa7 100644 --- a/cli/internal/daemon/protocol/digest.gen.go +++ b/cli/internal/daemon/protocol/digest.gen.go @@ -5,4 +5,4 @@ package protocol // APIDigest identifies the wire contract these types were generated from. // The daemon reports its own in GET /server; a different value means this // client's decoders may reject what the daemon sends. -const APIDigest = "bb75d16aa845e1786d12ee7da326fe514727d2a8817e66f8b8712c14e5dfb24b" +const APIDigest = "e3ed17301dd286eceaedbac6bc8d8ba01341323d79e02a987d12d88a28c20984" diff --git a/docs/openapi.yaml b/docs/openapi.yaml index e23e4f5d2..98b1daf7b 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -2818,6 +2818,152 @@ paths: schema: $ref: '#/components/schemas/EmptyRequest' description: UTF-8 JSON; duplicate keys and unknown fields are rejected. + /sessions/{session_id}/inputs/{input_id}/hold: + post: + operationId: holdInput + summary: Hold a waiting message while it is edited + tags: + - sessions + responses: + '200': + description: Held until the lease runs out, unless asked again. + content: + application/json: + schema: + $ref: '#/components/schemas/InputHold' + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '403': + $ref: '#/components/responses/Problem403' + '404': + $ref: '#/components/responses/Problem404' + '405': + $ref: '#/components/responses/Problem405' + '406': + $ref: '#/components/responses/Problem406' + '409': + $ref: '#/components/responses/Problem409' + '413': + $ref: '#/components/responses/Problem413' + '415': + $ref: '#/components/responses/Problem415' + '503': + $ref: '#/components/responses/Problem503' + description: + Holds a person's typed message that still waits in the session's queue, + or renews the hold. Neither it nor anything queued after it is read + until the edit is saved, the hold is released, or lease_ms pass without + another hold. 409 input_not_waiting once the session read the message or + it was cancelled; 409 input_not_editable for any other input. + parameters: + - name: input_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EmptyRequest' + description: UTF-8 JSON; duplicate keys and unknown fields are rejected. + delete: + operationId: releaseInput + summary: Let a held message be read as it is + tags: + - sessions + responses: + '204': + description: Released; the message keeps its place in the queue. + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '403': + $ref: '#/components/responses/Problem403' + '404': + $ref: '#/components/responses/Problem404' + '405': + $ref: '#/components/responses/Problem405' + '409': + $ref: '#/components/responses/Problem409' + '503': + $ref: '#/components/responses/Problem503' + description: Idempotent. A message that was never held is unaffected. + parameters: + - name: input_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + /sessions/{session_id}/inputs/{input_id}/edit: + post: + operationId: editInput + summary: Put an edited message in place of a waiting one + tags: + - sessions + responses: + '200': + description: The message as it now waits. + content: + application/json: + schema: + $ref: '#/components/schemas/InputEdit' + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '403': + $ref: '#/components/responses/Problem403' + '404': + $ref: '#/components/responses/Problem404' + '405': + $ref: '#/components/responses/Problem405' + '406': + $ref: '#/components/responses/Problem406' + '409': + $ref: '#/components/responses/Problem409' + '413': + $ref: '#/components/responses/Problem413' + '415': + $ref: '#/components/responses/Problem415' + '503': + $ref: '#/components/responses/Problem503' + description: + Replaces a person's typed message that still waits, keeping its id and + its place in the queue, and releases any hold on it. 409 + input_not_waiting once the session read it or it was cancelled. + parameters: + - name: input_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MessageInputRequest' + description: UTF-8 JSON; duplicate keys and unknown fields are rejected. /sessions/{session_id}/interrupt: post: operationId: interruptSession @@ -12118,6 +12264,22 @@ components: maxLength: 512 required: [kind, command_id, arguments] additionalProperties: false + InputHold: + type: object + properties: + lease_ms: + type: integer + minimum: 1 + description: How long the hold lasts unless the message is held again. + required: [lease_ms] + additionalProperties: false + InputEdit: + type: object + properties: + input: + $ref: '#/components/schemas/Input' + required: [input] + additionalProperties: false InputRequest: oneOf: - $ref: '#/components/schemas/MessageInputRequest' diff --git a/src/albedo/daemon/api_digest.gleam b/src/albedo/daemon/api_digest.gleam index e48d135c4..e1a1b4198 100644 --- a/src/albedo/daemon/api_digest.gleam +++ b/src/albedo/daemon/api_digest.gleam @@ -2,4 +2,4 @@ //// GET /server reports it so a client built from another contract can tell. pub const digest = - "bb75d16aa845e1786d12ee7da326fe514727d2a8817e66f8b8712c14e5dfb24b" + "e3ed17301dd286eceaedbac6bc8d8ba01341323d79e02a987d12d88a28c20984" diff --git a/src/albedo/daemon/http_api.gleam b/src/albedo/daemon/http_api.gleam index e288b8c86..8e4653aba 100644 --- a/src/albedo/daemon/http_api.gleam +++ b/src/albedo/daemon/http_api.gleam @@ -1133,6 +1133,14 @@ pub fn failure(code: String) -> Failure { "file attachments require a local workspace" -> Failure(400, "attachment_workspace_unsupported", code) "message is empty" -> Failure(400, "message_empty", code) + "input_not_waiting" -> + Failure( + 409, + code, + "the session already read this input, or it was cancelled", + ) + "input_not_editable" -> + Failure(409, code, "only a person's typed message can be held or edited") "configuration_changed" | "family_changed" -> Failure(412, code, "observed configuration or family changed") "daemon is shutting down" -> diff --git a/src/albedo/daemon/http_sessions.gleam b/src/albedo/daemon/http_sessions.gleam index e3e3355fc..180d7a087 100644 --- a/src/albedo/daemon/http_sessions.gleam +++ b/src/albedo/daemon/http_sessions.gleam @@ -43,6 +43,7 @@ import albedo/harness/sdk/image import albedo/harness/sdk/profiles as configuration import albedo/openai_api/types import gleam/bit_array +import gleam/bytes_tree import gleam/dynamic/decode import gleam/erlang/process.{type Subject} import gleam/http.{Get, Patch} @@ -802,6 +803,7 @@ pub fn input( input, id, input_id, + input_id, )) case input, token { // The lease is checked again inside the session actor, at the @@ -840,6 +842,9 @@ pub fn input( http_api.answer(outcome) } +/// The submission `input` makes. Pasted text and attached files are saved +/// under `files_key`: the input's id, or a fresh key for an edit, so an edit +/// never rewrites a file the version already read points to. fn prepare_input( config: Config, host: runtime.Runtime, @@ -847,6 +852,7 @@ fn prepare_input( input: http_api.Input, session_id: String, input_id: String, + files_key: String, ) -> Result(turn.Submission, String) { let client = case input { http_api.MessageInput(client_id: client, ..) @@ -890,7 +896,7 @@ fn prepare_input( pasted, config.home, session_id, - input_id, + files_key, )) use expanded <- result.try(expand_skill_mentions( worker, @@ -902,7 +908,7 @@ fn prepare_input( checked, config.home, session_id, - input_id, + files_key, )) Ok(turn.Submission( text, @@ -1199,6 +1205,106 @@ pub fn cancel( http_api.answer(outcome) } +/// `POST /sessions/{id}/inputs/{input_id}/hold`: hold a person's waiting +/// message while they edit it, or renew the hold. Nothing queued from it on is +/// read until the edit is saved or released, or the lease runs out unrenewed. +pub fn hold( + registry: Subject(Message), + id: String, + input_id: String, + req: request.Request(BitArray), +) -> response.Response(mist.ResponseData) { + let outcome = { + use _ <- result.try(http_api.empty_body(req)) + use worker <- result.try(waiting_input(registry, id, input_id, req)) + use _ <- result.try( + session.hold_input(worker, input_id) |> result.map_error(http_api.failure), + ) + Ok(http_api.reply( + 200, + json.object([#("lease_ms", json.int(session.hold_ms))]), + )) + } + http_api.answer(outcome) +} + +/// `DELETE /sessions/{id}/inputs/{input_id}/hold`: the message is read as it +/// is, in its place in the queue. +pub fn release( + registry: Subject(Message), + id: String, + input_id: String, + req: request.Request(BitArray), +) -> response.Response(mist.ResponseData) { + let outcome = { + use worker <- result.try(waiting_input(registry, id, input_id, req)) + use _ <- result.try( + session.release_input(worker, input_id) + |> result.map_error(http_api.failure), + ) + Ok(response.new(204) |> response.set_body(mist.Bytes(bytes_tree.new()))) + } + http_api.answer(outcome) +} + +/// `POST /sessions/{id}/inputs/{input_id}/edit`: a message body put in place +/// of the person's message still waiting under `input_id`, which keeps its id +/// and its place in the queue and is no longer held. +pub fn edit( + config: Config, + registry: Subject(Message), + id: String, + input_id: String, + req: request.Request(BitArray), +) -> response.Response(mist.ResponseData) { + let outcome = { + use input <- result.try(http_api.input(req)) + use _ <- result.try(case input { + http_api.MessageInput(..) -> Ok(Nil) + _ -> Error(http_api.failure("input_not_editable")) + }) + use worker <- result.try(waiting_input(registry, id, input_id, req)) + use host <- result.try( + registry.host(registry) |> result.map_error(http_api.failure), + ) + use submission <- result.try( + prepare_input( + config, + host, + worker, + input, + id, + input_id, + input_id <> "-" <> mail.new_id(), + ) + |> result.map_error(http_api.failure), + ) + use _ <- result.try( + session.edit_input(worker, submission) + |> result.map_error(http_api.failure), + ) + use edited <- result.try(input_outcome(runtime.ledger(host), id, input_id)) + Ok(http_api.reply(200, json.object([#("input", http_wire.input(edited))]))) + } + http_api.answer(outcome) +} + +/// The session holding `input_id`, an input it accepted; whether the input +/// still waits is the session's to say. +fn waiting_input( + registry: Subject(Message), + id: String, + input_id: String, + req: request.Request(BitArray), +) -> Result(session.Session, http_api.Failure) { + use _ <- result.try(http_api.json_parameters(req, [])) + use host <- result.try( + registry.host(registry) |> result.map_error(http_api.failure), + ) + use _ <- result.try(input_outcome(runtime.ledger(host), id, input_id)) + registry.lookup(registry, id) |> result.map_error(http_api.failure) +} + pub fn interrupt( registry: Subject(Message), id: String, diff --git a/src/albedo/daemon/inbox.gleam b/src/albedo/daemon/inbox.gleam index c834f5793..ea150fd5e 100644 --- a/src/albedo/daemon/inbox.gleam +++ b/src/albedo/daemon/inbox.gleam @@ -159,6 +159,30 @@ fn insert_at( ) } +/// Put `submission`, a person's edited message, in place of the one waiting +/// under its id; False when that one was read or dropped meanwhile. +pub fn replace( + db: store.Store, + session: String, + submission: Submission, +) -> Result(Bool, String) { + use <- bool.guard( + !turn.bounded(submission), + Error("prompt or activation exceeds its bounded size"), + ) + use id <- result.try(option.to_result( + submission.submission_id, + "the input has no inbox id", + )) + store.query(db, mail.replace_in( + _, + session, + id, + submission.display, + turn.encode(submission), + )) +} + /// `session`'s waiting rows as the queue's rules see them, leaving out /// `taken`, the rows its running turn holds. A closed session's letters and /// job notices are left out: it reads none of them. diff --git a/src/albedo/daemon/mail.gleam b/src/albedo/daemon/mail.gleam index 98467409b..eef7f0bcb 100644 --- a/src/albedo/daemon/mail.gleam +++ b/src/albedo/daemon/mail.gleam @@ -747,6 +747,33 @@ pub fn drop_in( |> result.map(list.flatten) } +/// Put a person's edited message in place of the one still waiting for +/// `recipient` under `id`, in the caller's transaction; False when it was read +/// or dropped meanwhile. +pub fn replace_in( + connection: sqlight.Connection, + recipient: String, + id: String, + display: String, + payload: BitArray, +) -> Result(Bool, String) { + store.rows( + connection, + "UPDATE mail SET body=?,display=?,payload=? WHERE id=? AND recipient=? AND kind='chat' AND " + <> waits + <> " RETURNING id", + [ + sqlight.text(display), + sqlight.text(display), + sqlight.blob(payload), + sqlight.text(id), + sqlight.text(recipient), + ], + decode.field(0, decode.string, decode.success), + ) + |> result.map(fn(rows) { rows != [] }) +} + /// Number `recipient`'s waiting rows in the order of `ids`, in the caller's /// transaction; waiting rows it leaves out keep their order after them. pub fn arrange_in( diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index f53365b98..55d030891 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -469,7 +469,9 @@ fn routed( req: request.Request(mist.Connection), ) -> response.Response(mist.ResponseData) { let limit = case req.method, request.path_segments(req) { - Put, ["sessions", _, "inputs", _] -> http_api.input_body_limit + Put, ["sessions", _, "inputs", _] + | Post, ["sessions", _, "inputs", _, "edit"] + -> http_api.input_body_limit Put, ["transfers", _, "import"] -> http_transfers.manifest_limit Put, ["transfers", _, "import", "segments", _] -> http_transfers.chunk_limit _, _ -> http_api.ordinary_body_limit @@ -789,6 +791,12 @@ fn daemon_route( http_sessions.input_read(registry, id, input_id, req) Post, ["sessions", id, "inputs", input_id, "cancel"] -> http_sessions.cancel(registry, id, input_id, req) + Post, ["sessions", id, "inputs", input_id, "hold"] -> + http_sessions.hold(registry, id, input_id, req) + Delete, ["sessions", id, "inputs", input_id, "hold"] -> + http_sessions.release(registry, id, input_id, req) + Post, ["sessions", id, "inputs", input_id, "edit"] -> + http_sessions.edit(config, registry, id, input_id, req) Post, ["sessions", id, "interrupt"] -> http_sessions.interrupt(registry, id, req) Put, ["sessions", id, "acp-attachment"] -> @@ -1045,6 +1053,7 @@ fn protocol_method(path: List(String)) -> response.Response(mist.ResponseData) { ["sessions", _, "shell-commands", _, "output"] -> Some("GET") ["sessions", _, "shell-commands", _, "stop"] -> Some("POST") ["sessions", _, "inputs", _] -> Some("GET, PUT") + ["sessions", _, "inputs", _, "hold"] -> Some("POST, DELETE") ["sessions", _, "visits", _] -> Some("PUT") ["sessions", _, "history"] | ["sessions", _, "history", _] @@ -1059,6 +1068,7 @@ fn protocol_method(path: List(String)) -> response.Response(mist.ResponseData) { | ["hosts", _, "probe"] | ["sessions", _, "interrupt"] | ["sessions", _, "inputs", _, "cancel"] + | ["sessions", _, "inputs", _, "edit"] | ["sessions", _, "reload"] | ["sessions", _, "kernel", "upgrade"] | ["sessions", _, "kernel", "restart"] diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index ffec06cbc..cfe15ba72 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -66,6 +66,7 @@ import albedo/harness/sdk/transcript import albedo/harness/ssh import albedo/openai_api/types import gleam/bool +import gleam/dict import gleam/erlang/process.{type Subject} import gleam/int import gleam/io @@ -279,6 +280,13 @@ pub type Message { Abort(String) DropQueued(List(String), Subject(Result(List(String), String))) ArrangeQueue(List(String), Subject(Result(Nil, String))) + /// Hold a person's waiting message while they edit it, or renew the hold. + HoldInput(String, Subject(Result(Nil, String))) + /// The hold on this input reached this deadline without a renewal. + HoldLapsed(String, Int) + ReleaseInput(String, Subject(Nil)) + /// Put an edited message in place of the waiting one under its id. + EditInput(Submission, Subject(Result(Nil, String))) CancelInput( String, Option(acp.Digest), @@ -667,6 +675,7 @@ pub fn start( blocked_until: 0, blocking: None, holding_failure: False, + held: dict.new(), generation: generation, tool_progress: tool_progress_state.new(), progress_timer_token: 0, @@ -750,6 +759,36 @@ pub fn arrange_queue( |> result.flatten } +/// Hold `input_id`, a person's message still waiting, while they edit it: +/// neither it nor what waits behind it is read until the edit is saved, the +/// hold is released, or `hold_ms` pass without asking again. +pub fn hold_input(session: Session, input_id: String) -> Result(Nil, String) { + actor_call.try_call(session, 15_000, HoldInput(input_id, _)) + |> result.replace_error("the session did not answer") + |> result.flatten +} + +/// Let a held input be read again as it is. +pub fn release_input( + session: Session, + input_id: String, +) -> Result(Nil, String) { + actor_call.try_call(session, 15_000, ReleaseInput(input_id, _)) + |> result.replace_error("the session did not answer") +} + +/// Put `submission` in place of the person's message still waiting under its +/// id, and release any hold on it. Errors with `input_not_waiting` once the +/// session read it or it was cancelled. +pub fn edit_input( + session: Session, + submission: Submission, +) -> Result(Nil, String) { + actor_call.try_call(session, 15_000, EditInput(submission, _)) + |> result.replace_error("the session did not answer") + |> result.flatten +} + pub fn cancel_input( session: Session, input_id: String, @@ -1720,6 +1759,9 @@ fn handle( | ReadCommands(..) | Interrupt(..) | CancelInput(..) + | HoldInput(..) + | ReleaseInput(..) + | EditInput(..) | Read(..) | ReadContext(..) | ChangeModel(..) @@ -2024,6 +2066,21 @@ fn handle( let #(state, arranged) = arrange_queue_in(state, ids) answer(state, reply, arranged) } + HoldInput(id, reply) -> { + let #(state, held) = hold_input_in(state, id) + answer(state, reply, held) + } + HoldLapsed(id, deadline) -> + case dict.get(state.held, id) { + Ok(held) if held == deadline -> + actor.continue(release_input_in(state, id)) + _ -> actor.continue(state) + } + ReleaseInput(id, reply) -> answer(release_input_in(state, id), reply, Nil) + EditInput(submission, reply) -> { + let #(state, edited) = edit_input_in(state, submission) + answer(state, reply, edited) + } ReadCommands(reply) -> { let host = state.host let id = state.info.id @@ -6225,6 +6282,9 @@ fn queued(state: State) -> Result(List(turn.Queued), String) { turn.letters(state.active_submissions), family_closed(state) == Ok(True), ) + |> result.map( + list.take_while(_, fn(row) { !dict.has_key(state.held, row.id) }), + ) } /// Someone stored or withdrew a row in this session's inbox: clients read the @@ -6327,6 +6387,74 @@ fn drop_queued_in( } } +/// How long a hold on a person's waiting message lasts unless they ask again. +pub const hold_ms = 30_000 + +fn hold_input_in(state: State, id: String) -> #(State, Result(Nil, String)) { + case waiting_message(state, id) { + Error(reason) -> #(state, Error(reason)) + Ok(Nil) -> { + let deadline = clock.monotonic_ms() + hold_ms + let _ = clock.send_after(state.self, hold_ms, HoldLapsed(id, deadline)) + #( + session_state.State( + ..state, + held: dict.insert(state.held, id, deadline), + ) + |> session_state.queue_changed, + Ok(Nil), + ) + } + } +} + +fn release_input_in(state: State, id: String) -> State { + session_state.State(..state, held: dict.delete(state.held, id)) + |> inbox_changed +} + +fn edit_input_in( + state: State, + submission: Submission, +) -> #(State, Result(Nil, String)) { + let id = option.unwrap(submission.submission_id, "") + let edited = { + use _ <- result.try(waiting_message(state, id)) + use replaced <- result.try(inbox.replace( + runtime.ledger(state.host), + state.info.id, + submission, + )) + case replaced { + True -> Ok(Nil) + False -> Error("input_not_waiting") + } + } + case edited { + // A hold the edit could not use stays until it is released or lapses. + Error(reason) + if reason != "input_not_waiting" && reason != "input_not_editable" + -> #(state, edited) + _ -> #(release_input_in(state, id), edited) + } +} + +/// Whether `id` is a person's typed message still waiting in this session's +/// inbox, one its running turn has not taken. +fn waiting_message(state: State, id: String) -> Result(Nil, String) { + use rows <- result.try(inbox.waiting( + runtime.ledger(state.host), + state.info.id, + turn.letters(state.active_submissions), + False, + )) + case list.find(rows, fn(row) { row.id == id }) { + Ok(turn.Queued(kind: mail_value.Input(mail_value.Typed), ..)) -> Ok(Nil) + Ok(_) -> Error("input_not_editable") + Error(_) -> Error("input_not_waiting") + } +} + /// The inbox orders the queue; the session reads it in that order. fn arrange_queue_in( state: State, diff --git a/src/albedo/daemon/session_state.gleam b/src/albedo/daemon/session_state.gleam index eb9936823..71f7b5b1e 100644 --- a/src/albedo/daemon/session_state.gleam +++ b/src/albedo/daemon/session_state.gleam @@ -22,6 +22,7 @@ import albedo/harness/runtime/admission import albedo/harness/sdk/queue import albedo/harness/sdk/transcript import albedo/openai_api/types +import gleam/dict import gleam/erlang/process.{type Subject} import gleam/int import gleam/json @@ -129,6 +130,10 @@ pub type State(message) { /// A child's failure letter waits briefly for its siblings' before its /// turn starts; the session reports itself preparing meanwhile. holding_failure: Bool, + /// People's waiting inputs held while they edit them, by input id, with + /// the monotonic deadline of each hold. The queue stops at the first held + /// row, so neither it nor what waits behind it is read until the hold ends. + held: dict.Dict(String, Int), generation: String, tool_progress: tool_progress.Projection, progress_timer_token: Int, diff --git a/test/daemon/bedrock_replay_preflight_test.gleam b/test/daemon/bedrock_replay_preflight_test.gleam index f84220178..6c310de2c 100644 --- a/test/daemon/bedrock_replay_preflight_test.gleam +++ b/test/daemon/bedrock_replay_preflight_test.gleam @@ -24,6 +24,7 @@ import albedo/harness/runtime import albedo/harness/sdk/extension import albedo/harness/sdk/transcript import albedo/openai_api/types +import gleam/dict import gleam/erlang/process import gleam/json import gleam/list @@ -196,6 +197,7 @@ fn state(home: String, host: runtime.Runtime) -> session_state.State(Nil) { blocked_until: 0, blocking: None, holding_failure: False, + held: dict.new(), generation: "fixture", tool_progress: tool_progress.new(), progress_timer_token: 0, diff --git a/test/e2e/queue_test.py b/test/e2e/queue_test.py index 15836393a..a8d8a244f 100644 --- a/test/e2e/queue_test.py +++ b/test/e2e/queue_test.py @@ -4,10 +4,11 @@ reorder and drop it before the session takes it.""" import base64 import json import threading +import time import unittest import urllib.error -from harness import Albedo, Provider, operation_id, text +from harness import Albedo, Provider, operation_id, python, text, wait_until from image_limits_test import png @@ -45,6 +46,22 @@ class QueueTests(unittest.TestCase): ) as response: return json.load(response) + def input_action(self, session, input_id, action, body=None, method="POST"): + with self.app.api( + f"/sessions/{session}/inputs/{input_id}/{action}", body, method=method + ) as response: + raw = response.read() + return json.loads(raw) if raw else None + + def phase(self, session): + with self.app.api(f"/sessions/{session}?tail=0") as response: + return json.load(response)["status"]["phase"] + + def said(self): + return [ + json.dumps(record["request"]["input"]) for record in self.provider.requests + ] + def test_waiting_inputs_are_listed_reordered_and_dropped(self): session = self.app.session() self.app.prompt(session, "hold the turn").close() @@ -141,6 +158,78 @@ class QueueTests(unittest.TestCase): self.assertEqual(present, sorted(present)) self.assertEqual(seen, list(range(70))) + def test_a_held_message_waits_for_its_edit_and_keeps_its_place(self): + def script(request): + if len(self.provider.requests) == 1: + self.started.set() + self.gate.wait(40) + return python("print('one more step')") + return text("done") + + self.provider.script = script + session = self.app.session() + self.app.prompt(session, "hold the turn").close() + self.assertTrue(self.started.wait(10)) + typo = self.put_input( + session, {"kind": "message", "text": "use the wrnog branch"} + ) + behind = self.put_input(session, {"kind": "message", "text": "then push it"}) + held = self.input_action(session, typo, "hold", {}) + self.assertGreater(held["lease_ms"], 0) + + # The next step and the end of the turn go without the held message, + # and without what waits behind it. + self.gate.set() + wait_until( + lambda: len(self.provider.requests) >= 2 and self.phase(session) == "idle", + 20, + "the turn did not end", + ) + time.sleep(0.5) + self.assertEqual(len(self.provider.requests), 2) + self.assertFalse( + any("wrnog" in said or "then push it" in said for said in self.said()) + ) + self.assertEqual( + [item["id"] for item in self.queue(session)["items"]], [typo, behind] + ) + + edited = self.input_action( + session, typo, "edit", {"kind": "message", "text": "use the right branch"} + ) + self.assertEqual(edited["input"]["id"], typo) + self.app.idle(session) + said = self.said() + self.assertFalse(any("wrnog" in request for request in said)) + later = next(request for request in said if "use the right branch" in request) + self.assertLess( + later.index("use the right branch"), later.index("then push it") + ) + with self.app.api(f"/sessions/{session}/inputs/{typo}") as response: + self.assertEqual(json.load(response)["delivery"], "committed") + + with self.assertRaises(urllib.error.HTTPError) as read: + self.input_action( + session, typo, "edit", {"kind": "message", "text": "too late"} + ) + self.assertEqual(read.exception.code, 409) + self.assertEqual(json.load(read.exception)["code"], "input_not_waiting") + + def test_a_released_hold_reads_the_message_as_it_was(self): + session = self.app.session() + self.app.prompt(session, "hold the turn").close() + self.assertTrue(self.started.wait(10)) + waiting = self.put_input(session, {"kind": "message", "text": "as it was"}) + self.input_action(session, waiting, "hold", {}) + self.gate.set() + wait_until(lambda: self.phase(session) == "idle", 20, "the turn did not end") + time.sleep(0.5) + self.assertFalse(any("as it was" in said for said in self.said())) + + self.assertIsNone(self.input_action(session, waiting, "hold", method="DELETE")) + self.app.idle(session) + self.assertTrue(any("as it was" in said for said in self.said())) + if __name__ == "__main__": unittest.main() diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index f1a0d6fd2..52e77e6da 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -773,6 +773,50 @@ export interface paths { patch?: never; trace?: never; }; + "/sessions/{session_id}/inputs/{input_id}/hold": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Hold a waiting message while it is edited + * @description Holds a person's typed message that still waits in the session's queue, or renews the hold. Neither it nor anything queued after it is read until the edit is saved, the hold is released, or lease_ms pass without another hold. 409 input_not_waiting once the session read the message or it was cancelled; 409 input_not_editable for any other input. + */ + post: operations["holdInput"]; + /** + * Let a held message be read as it is + * @description Idempotent. A message that was never held is unaffected. + */ + delete: operations["releaseInput"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/sessions/{session_id}/inputs/{input_id}/edit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Put an edited message in place of a waiting one + * @description Replaces a person's typed message that still waits, keeping its id and its place in the queue, and releases any hold on it. 409 input_not_waiting once the session read it or it was cancelled. + */ + post: operations["editInput"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/sessions/{session_id}/interrupt": { parameters: { query?: never; @@ -4065,6 +4109,13 @@ export interface components { arguments: components["schemas"]["DynamicJSON"]; client_id?: string; }; + InputHold: { + /** @description How long the hold lasts unless the message is held again. */ + lease_ms: number; + }; + InputEdit: { + input: components["schemas"]["Input"]; + }; InputRequest: components["schemas"]["MessageInputRequest"] | components["schemas"]["ContinueInputRequest"] | components["schemas"]["SkillInputRequest"] | components["schemas"]["CommandInputRequest"] | components["schemas"]["ACPPromptInputRequest"]; Turn: { id: components["schemas"]["ID"]; @@ -8173,6 +8224,110 @@ export interface operations { 503: components["responses"]["Problem503"]; }; }; + holdInput: { + parameters: { + query?: never; + header?: never; + path: { + input_id: components["schemas"]["ID"]; + session_id: components["schemas"]["ID"]; + }; + cookie?: never; + }; + /** @description UTF-8 JSON; duplicate keys and unknown fields are rejected. */ + requestBody: { + content: { + "application/json": components["schemas"]["EmptyRequest"]; + }; + }; + responses: { + /** @description Held until the lease runs out, unless asked again. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["InputHold"]; + }; + }; + 400: components["responses"]["Problem400"]; + 401: components["responses"]["Problem401"]; + 403: components["responses"]["Problem403"]; + 404: components["responses"]["Problem404"]; + 405: components["responses"]["Problem405"]; + 406: components["responses"]["Problem406"]; + 409: components["responses"]["Problem409"]; + 413: components["responses"]["Problem413"]; + 415: components["responses"]["Problem415"]; + 503: components["responses"]["Problem503"]; + }; + }; + releaseInput: { + parameters: { + query?: never; + header?: never; + path: { + input_id: components["schemas"]["ID"]; + session_id: components["schemas"]["ID"]; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Released; the message keeps its place in the queue. */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 400: components["responses"]["Problem400"]; + 401: components["responses"]["Problem401"]; + 403: components["responses"]["Problem403"]; + 404: components["responses"]["Problem404"]; + 405: components["responses"]["Problem405"]; + 409: components["responses"]["Problem409"]; + 503: components["responses"]["Problem503"]; + }; + }; + editInput: { + parameters: { + query?: never; + header?: never; + path: { + input_id: components["schemas"]["ID"]; + session_id: components["schemas"]["ID"]; + }; + cookie?: never; + }; + /** @description UTF-8 JSON; duplicate keys and unknown fields are rejected. */ + requestBody: { + content: { + "application/json": components["schemas"]["MessageInputRequest"]; + }; + }; + responses: { + /** @description The message as it now waits. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["InputEdit"]; + }; + }; + 400: components["responses"]["Problem400"]; + 401: components["responses"]["Problem401"]; + 403: components["responses"]["Problem403"]; + 404: components["responses"]["Problem404"]; + 405: components["responses"]["Problem405"]; + 406: components["responses"]["Problem406"]; + 409: components["responses"]["Problem409"]; + 413: components["responses"]["Problem413"]; + 415: components["responses"]["Problem415"]; + 503: components["responses"]["Problem503"]; + }; + }; interruptSession: { parameters: { query?: never; -- knotmirror 0.0.1