WIP: preserve remaining background task output work
This commit is contained in:
@@ -13,6 +13,8 @@ import net.awan.pipelines.data.protocol.ChatPromptRequest
|
|||||||
import net.awan.pipelines.data.protocol.ChatProtocol
|
import net.awan.pipelines.data.protocol.ChatProtocol
|
||||||
import net.awan.pipelines.data.protocol.ChatQuery
|
import net.awan.pipelines.data.protocol.ChatQuery
|
||||||
import net.awan.pipelines.data.protocol.ChatSession
|
import net.awan.pipelines.data.protocol.ChatSession
|
||||||
|
import net.awan.pipelines.data.protocol.ChatShellOutputPage
|
||||||
|
import net.awan.pipelines.data.protocol.ChatShell
|
||||||
import net.awan.pipelines.data.protocol.Message
|
import net.awan.pipelines.data.protocol.Message
|
||||||
import net.awan.pipelines.data.protocol.Graph
|
import net.awan.pipelines.data.protocol.Graph
|
||||||
import net.awan.pipelines.data.protocol.PipelineDetail
|
import net.awan.pipelines.data.protocol.PipelineDetail
|
||||||
@@ -312,6 +314,22 @@ class PipelinesRepository(
|
|||||||
return response.chatHistory ?: ChatHistoryPage(messages = response.chatMessages ?: emptyList())
|
return response.chatHistory ?: ChatHistoryPage(messages = response.chatMessages ?: emptyList())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Reads one bounded page from a verified, currently observable shell. */
|
||||||
|
suspend fun chatShellOutput(sessionId: String, shellId: String, cursor: Long = 0, limit: Int = ChatProtocol.SHELL_OUTPUT_LIMIT): ChatShellOutputPage {
|
||||||
|
if (sessionId.isBlank() || shellId.isBlank()) throw ProtocolException("Select a shell first.")
|
||||||
|
if (cursor < 0 || limit <= 0 || limit > ChatProtocol.SHELL_OUTPUT_LIMIT) {
|
||||||
|
throw ProtocolException("Shell output bounds are invalid.")
|
||||||
|
}
|
||||||
|
return client.call(ChatProtocol.shellOutputRequest(sessionId, shellId, cursor, limit)).chatShellOutput
|
||||||
|
?: throw ProtocolException("The server returned no shell output page.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lists currently observed shells owned by this operator chat session. */
|
||||||
|
suspend fun chatShells(sessionId: String): List<ChatShell> {
|
||||||
|
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
|
||||||
|
return client.call(ChatProtocol.shellsRequest(sessionId)).chatShells ?: emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attaches this connection to [sessionId]'s shared live stream, so it sees
|
* Attaches this connection to [sessionId]'s shared live stream, so it sees
|
||||||
* every frame any client's turn produces — the other devices' prompts and the
|
* every frame any client's turn produces — the other devices' prompts and the
|
||||||
|
|||||||
@@ -201,6 +201,24 @@ data class ChatShell(
|
|||||||
val exit: Int? = null,
|
val exit: Int? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ChatShellOutputQuery(
|
||||||
|
@SerialName("session_id") val sessionId: String = "",
|
||||||
|
@SerialName("shell_id") val shellId: String = "",
|
||||||
|
val cursor: Long = 0,
|
||||||
|
val limit: Int = ChatProtocol.SHELL_OUTPUT_LIMIT,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ChatShellOutputPage(
|
||||||
|
val shell: ChatShell = ChatShell(),
|
||||||
|
val output: String = "",
|
||||||
|
val cursor: Long = 0,
|
||||||
|
val size: Long = 0,
|
||||||
|
val truncated: Boolean = false,
|
||||||
|
val unavailable: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class ChatStep(
|
data class ChatStep(
|
||||||
val status: String = "",
|
val status: String = "",
|
||||||
@@ -282,6 +300,7 @@ object ChatProtocol {
|
|||||||
|
|
||||||
const val SHELL_RUNNING = "running"
|
const val SHELL_RUNNING = "running"
|
||||||
const val SHELL_EXITED = "exited"
|
const val SHELL_EXITED = "exited"
|
||||||
|
const val SHELL_OUTPUT_LIMIT = 64 * 1024
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A prompt another client sent, echoed live to this client so it appears in
|
* A prompt another client sent, echoed live to this client so it appears in
|
||||||
@@ -359,6 +378,15 @@ object ChatProtocol {
|
|||||||
fun interruptRequest(sessionId: String): Message =
|
fun interruptRequest(sessionId: String): Message =
|
||||||
Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))
|
Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))
|
||||||
|
|
||||||
|
fun shellOutputRequest(sessionId: String, shellId: String, cursor: Long = 0, limit: Int = SHELL_OUTPUT_LIMIT): Message =
|
||||||
|
Message(
|
||||||
|
type = Protocol.CHAT_SHELL_OUTPUT,
|
||||||
|
chatShellOutputQuery = ChatShellOutputQuery(sessionId, shellId, cursor, limit),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun shellsRequest(sessionId: String): Message =
|
||||||
|
Message(type = Protocol.CHAT_SHELLS, chatQuery = ChatQuery(sessionId = sessionId))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `chat_close` frame that finishes [sessionId]: the server stops any
|
* The `chat_close` frame that finishes [sessionId]: the server stops any
|
||||||
* running turn (through the same interrupt) and records the session closed on
|
* running turn (through the same interrupt) and records the session closed on
|
||||||
|
|||||||
@@ -79,6 +79,8 @@ object Protocol {
|
|||||||
// The operator's directory choices for a new chat (home first, then the
|
// The operator's directory choices for a new chat (home first, then the
|
||||||
// directories of previous operator sessions, most recently used first).
|
// directories of previous operator sessions, most recently used first).
|
||||||
const val CHAT_DIRECTORIES = "chat_directories"
|
const val CHAT_DIRECTORIES = "chat_directories"
|
||||||
|
const val CHAT_SHELLS = "chat_shells"
|
||||||
|
const val CHAT_SHELL_OUTPUT = "chat_shell_output"
|
||||||
// Server-pushed frames with no matching request.
|
// Server-pushed frames with no matching request.
|
||||||
const val CHAT_EVENT = "chat_event"
|
const val CHAT_EVENT = "chat_event"
|
||||||
const val CHAT_PERMISSION = "chat_permission"
|
const val CHAT_PERMISSION = "chat_permission"
|
||||||
@@ -712,4 +714,7 @@ data class Message(
|
|||||||
// close/reopen requests themselves ride on chat_query like chat_interrupt.
|
// close/reopen requests themselves ride on chat_query like chat_interrupt.
|
||||||
@SerialName("chat_close") val chatClose: ChatCloseResult? = null,
|
@SerialName("chat_close") val chatClose: ChatCloseResult? = null,
|
||||||
@SerialName("chat_directories") val chatDirectories: List<String>? = null,
|
@SerialName("chat_directories") val chatDirectories: List<String>? = null,
|
||||||
|
@SerialName("chat_shell_output_query") val chatShellOutputQuery: ChatShellOutputQuery? = null,
|
||||||
|
@SerialName("chat_shells") val chatShells: List<ChatShell>? = null,
|
||||||
|
@SerialName("chat_shell_output") val chatShellOutput: ChatShellOutputPage? = null,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -405,6 +405,36 @@ class ChatProtocolTest {
|
|||||||
assertEquals(1792112367999L, decodedReply.chatClose!!.closedAt)
|
assertEquals(1792112367999L, decodedReply.chatClose!!.closedAt)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun shellOutputRequestAndPageUseBoundedWireNames() {
|
||||||
|
val request = ChatProtocol.shellOutputRequest("ses_1", "sh_1", 7, 128)
|
||||||
|
val decoded = PipelinesJson.decodeFromString(Message.serializer(), PipelinesJson.encodeToString(Message.serializer(), request))
|
||||||
|
assertEquals(Protocol.CHAT_SHELL_OUTPUT, decoded.type)
|
||||||
|
assertEquals("ses_1", decoded.chatShellOutputQuery!!.sessionId)
|
||||||
|
assertEquals("sh_1", decoded.chatShellOutputQuery!!.shellId)
|
||||||
|
assertEquals(7L, decoded.chatShellOutputQuery!!.cursor)
|
||||||
|
assertEquals(128, decoded.chatShellOutputQuery!!.limit)
|
||||||
|
|
||||||
|
val page = PipelinesJson.decodeFromString(Message.serializer(), """
|
||||||
|
{"type":"chat_shell_output","chat_shell_output":{"shell":{"id":"sh_1","status":"running"},"output":"marker","cursor":13,"size":20,"truncated":true}}
|
||||||
|
""".trimIndent())
|
||||||
|
assertEquals("marker", page.chatShellOutput!!.output)
|
||||||
|
assertTrue(page.chatShellOutput!!.truncated)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun shellsRequestUsesSessionQueryAndPreservesListWireName() {
|
||||||
|
val request = ChatProtocol.shellsRequest("ses_1")
|
||||||
|
val decoded = PipelinesJson.decodeFromString(Message.serializer(), PipelinesJson.encodeToString(Message.serializer(), request))
|
||||||
|
assertEquals(Protocol.CHAT_SHELLS, decoded.type)
|
||||||
|
assertEquals("ses_1", decoded.chatQuery!!.sessionId)
|
||||||
|
val reply = PipelinesJson.decodeFromString(Message.serializer(), """
|
||||||
|
{"type":"chat_shells","chat_shells":[{"id":"sh_1","status":"running","command":"printf marker"}]}
|
||||||
|
""".trimIndent())
|
||||||
|
assertEquals("sh_1", reply.chatShells!!.single().id)
|
||||||
|
assertEquals(ChatProtocol.SHELL_RUNNING, reply.chatShells.single().status)
|
||||||
|
}
|
||||||
|
|
||||||
private fun toolDuration(part: ChatPart): Long? {
|
private fun toolDuration(part: ChatPart): Long? {
|
||||||
val time = part.time ?: return null
|
val time = part.time ?: return null
|
||||||
return time.completed - time.ran
|
return time.completed - time.ran
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import (
|
|||||||
func main() {
|
func main() {
|
||||||
addr := flag.String("addr", "127.0.0.1:0", "Pipelines scratch listen address")
|
addr := flag.String("addr", "127.0.0.1:0", "Pipelines scratch listen address")
|
||||||
scratch := flag.String("scratch-dir", "", "required scratch directory for the database and workspace")
|
scratch := flag.String("scratch-dir", "", "required scratch directory for the database and workspace")
|
||||||
|
exited := flag.Bool("shell-exited", false, "serve the selected fixture shell as observed exited")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
if *scratch == "" {
|
if *scratch == "" {
|
||||||
fatal(fmt.Errorf("-scratch-dir is required"))
|
fatal(fmt.Errorf("-scratch-dir is required"))
|
||||||
@@ -46,7 +47,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
defer upstream.Close()
|
defer upstream.Close()
|
||||||
upstreamURL := "http://" + upstream.Addr().String()
|
upstreamURL := "http://" + upstream.Addr().String()
|
||||||
upstreamServer := &http.Server{Handler: server.LargeChatFixtureHandler(workspace), ReadHeaderTimeout: 5 * time.Second}
|
upstreamServer := &http.Server{Handler: server.LargeChatFixtureHandlerWithShell(workspace, *exited), ReadHeaderTimeout: 5 * time.Second}
|
||||||
go func() { _ = upstreamServer.Serve(upstream) }()
|
go func() { _ = upstreamServer.Serve(upstream) }()
|
||||||
|
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
@@ -76,6 +77,9 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
fatal(err)
|
fatal(err)
|
||||||
}
|
}
|
||||||
|
if err := verifyShellReadback(ctx, endpoint, *exited); err != nil {
|
||||||
|
fatal(err)
|
||||||
|
}
|
||||||
info := buildinfo.Current()
|
info := buildinfo.Current()
|
||||||
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{
|
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{
|
||||||
"endpoint": endpoint, "upstream_endpoint": upstreamURL, "backend": attached.Connection.Backend,
|
"endpoint": endpoint, "upstream_endpoint": upstreamURL, "backend": attached.Connection.Backend,
|
||||||
@@ -89,6 +93,35 @@ func main() {
|
|||||||
_ = upstreamServer.Shutdown(shutdown)
|
_ = upstreamServer.Shutdown(shutdown)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func verifyShellReadback(ctx context.Context, endpoint string, exited bool) error {
|
||||||
|
ws, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(endpoint, "http")+"/connect", nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer ws.Close(websocket.StatusNormalClosure, "fixture complete")
|
||||||
|
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatShells, ID: "fixture-shells", ChatQuery: &protocol.ChatQuery{SessionID: server.LargeChatFixtureSessionID}}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var listed protocol.Message
|
||||||
|
if listed, err = readFixtureResponse(ctx, ws, protocol.ChatShells); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !exited && (len(listed.ChatShells) != 1 || listed.ChatShells[0].ID != server.LargeChatFixtureShellID) {
|
||||||
|
return fmt.Errorf("fixture shell is not listed")
|
||||||
|
}
|
||||||
|
if err := wsjson.Write(ctx, ws, protocol.Message{Type: protocol.ChatShellOutput, ID: "fixture-output", ChatShellOutputQuery: &protocol.ChatShellOutputQuery{SessionID: server.LargeChatFixtureSessionID, ShellID: server.LargeChatFixtureShellID, Limit: 64 << 10}}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
page, err := readFixtureResponse(ctx, ws, protocol.ChatShellOutput)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if page.ChatShellOutput == nil || page.ChatShellOutput.Output != server.LargeChatFixtureShellOutput || page.ChatShellOutput.Shell.Status != map[bool]string{true: "exited", false: "running"}[exited] {
|
||||||
|
return fmt.Errorf("unexpected shell readback: %+v", page.ChatShellOutput)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func verifyBroker(ctx context.Context, endpoint string) ([2]map[string]any, error) {
|
func verifyBroker(ctx context.Context, endpoint string) ([2]map[string]any, error) {
|
||||||
var readbacks [2]map[string]any
|
var readbacks [2]map[string]any
|
||||||
cursor := ""
|
cursor := ""
|
||||||
|
|||||||
@@ -11,3 +11,14 @@ history or restart retention.
|
|||||||
Stale shared documentation: the packaged OpenCode operational references under
|
Stale shared documentation: the packaged OpenCode operational references under
|
||||||
`internal/author/skill/references/` need a later docs-fold update describing the
|
`internal/author/skill/references/` need a later docs-fold update describing the
|
||||||
two additive websocket messages, 64 KiB maximum page, and current-only history.
|
two additive websocket messages, 64 KiB maximum page, and current-only history.
|
||||||
|
|
||||||
|
Fixture evidence (2026-10-18): `go build -o /tmp/pipelines-large-chat-fixture-stage
|
||||||
|
./cmd/pipelines-large-chat-fixture`; then `/tmp/pipelines-large-chat-fixture-stage
|
||||||
|
-scratch-dir /var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/pipelines-shell-fixture-pxnc95h2
|
||||||
|
-shell-exited`, stopped with SIGTERM. The foreground run exercised authenticated
|
||||||
|
`chat_sessions`, three reconnecting history pages, `chat_shells`, and bounded
|
||||||
|
`chat_shell_output` readback against scratch DB/workspace only, and exited 0 after
|
||||||
|
clean shutdown. Recorded revision `fd4c329eafc46d1ce32dc9bc36fd9bd09b34e058`,
|
||||||
|
session `ses_large_chat_fixture`, shell `sh_large_chat_fixture`, and fixed marker
|
||||||
|
`fixture shell output marker\n`. The selected exited shell is read directly by id;
|
||||||
|
the current list remains running-shell discovery.
|
||||||
|
|||||||
+25
-10
@@ -50,6 +50,21 @@ func NewChat(conn *Connection) *Chat { return &Chat{conn: conn} }
|
|||||||
// chat adapter and callers that must reject a request before any OpenCode call.
|
// chat adapter and callers that must reject a request before any OpenCode call.
|
||||||
func ValidSessionID(id string) bool { return sessionID.MatchString(id) }
|
func ValidSessionID(id string) bool { return sessionID.MatchString(id) }
|
||||||
|
|
||||||
|
// ValidShellID accepts only the provider's opaque shell-id alphabet. Keeping
|
||||||
|
// this check shared by the websocket boundary and provider adapter ensures an
|
||||||
|
// invalid id is rejected before either network call or path construction.
|
||||||
|
func ValidShellID(id string) bool {
|
||||||
|
if len(id) <= 3 || len(id) > 128 || !strings.HasPrefix(id, "sh_") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range id[3:] {
|
||||||
|
if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_' && c != '-' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// call serializes the adapter's HTTP calls and forwards them through the shared
|
// call serializes the adapter's HTTP calls and forwards them through the shared
|
||||||
// Connection, so no second transport is introduced and Connection's recorded
|
// Connection, so no second transport is introduced and Connection's recorded
|
||||||
// last operation/status is never written by two goroutines at once.
|
// last operation/status is never written by two goroutines at once.
|
||||||
@@ -392,7 +407,7 @@ func (c *Chat) Shells(ctx context.Context, sessionID string) ([]protocol.ChatShe
|
|||||||
}
|
}
|
||||||
out := make([]protocol.ChatShell, 0, len(response.Data))
|
out := make([]protocol.ChatShell, 0, len(response.Data))
|
||||||
for _, info := range response.Data {
|
for _, info := range response.Data {
|
||||||
if info.ID == "" || info.shellSessionID() != sessionID || (info.Status != "" && info.Status != protocol.ChatShellRunning) {
|
if info.ID == "" || info.shellSessionID() != sessionID || (info.Status != "" && info.Status != protocol.ChatShellRunning && info.Status != protocol.ChatShellExited) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
status := info.Status
|
status := info.Status
|
||||||
@@ -422,7 +437,7 @@ func (c *Chat) Shells(ctx context.Context, sessionID string) ([]protocol.ChatShe
|
|||||||
// record before reading the selected bounded output page. A shared directory is
|
// record before reading the selected bounded output page. A shared directory is
|
||||||
// never ownership evidence.
|
// never ownership evidence.
|
||||||
func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
|
func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
|
||||||
if !ValidSessionID(query.SessionID) || len(query.ShellID) <= 3 || !strings.HasPrefix(query.ShellID, "sh_") || query.Cursor < 0 || query.Limit < 0 || query.Limit > 64<<10 {
|
if !ValidSessionID(query.SessionID) || !ValidShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
|
||||||
return protocol.ChatShellOutputPage{}, fmt.Errorf("invalid shell output query")
|
return protocol.ChatShellOutputPage{}, fmt.Errorf("invalid shell output query")
|
||||||
}
|
}
|
||||||
data, err := c.call(ctx, "get", "/api/shell/"+query.ShellID, nil)
|
data, err := c.call(ctx, "get", "/api/shell/"+query.ShellID, nil)
|
||||||
@@ -435,7 +450,7 @@ func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQu
|
|||||||
var detail struct {
|
var detail struct {
|
||||||
Data chatShellInfo `json:"data"`
|
Data chatShellInfo `json:"data"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(data, &detail); err != nil || detail.Data.ID != query.ShellID || detail.Data.shellSessionID() != query.SessionID {
|
if err := json.Unmarshal(data, &detail); err != nil || detail.Data.ID != query.ShellID || detail.Data.shellSessionID() != query.SessionID || (detail.Data.Status != "" && detail.Data.Status != protocol.ChatShellRunning && detail.Data.Status != protocol.ChatShellExited) {
|
||||||
return protocol.ChatShellOutputPage{}, fmt.Errorf("shell is not available for this session")
|
return protocol.ChatShellOutputPage{}, fmt.Errorf("shell is not available for this session")
|
||||||
}
|
}
|
||||||
shell := protocol.ChatShell{ID: detail.Data.ID, Status: detail.Data.Status, Command: detail.Data.Command, Exit: detail.Data.Exit}
|
shell := protocol.ChatShell{ID: detail.Data.ID, Status: detail.Data.Status, Command: detail.Data.Command, Exit: detail.Data.Exit}
|
||||||
@@ -451,17 +466,17 @@ func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQu
|
|||||||
return protocol.ChatShellOutputPage{}, err
|
return protocol.ChatShellOutputPage{}, err
|
||||||
}
|
}
|
||||||
var response struct {
|
var response struct {
|
||||||
Data struct {
|
Data *struct {
|
||||||
Output string `json:"output"`
|
Output *string `json:"output"`
|
||||||
Cursor int64 `json:"cursor"`
|
Cursor *int64 `json:"cursor"`
|
||||||
Size int64 `json:"size"`
|
Size *int64 `json:"size"`
|
||||||
Truncated bool `json:"truncated"`
|
Truncated *bool `json:"truncated"`
|
||||||
} `json:"data"`
|
} `json:"data"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(data, &response); err != nil || len(response.Data.Output) > 64<<10 || response.Data.Cursor < query.Cursor || response.Data.Size < response.Data.Cursor {
|
if err := json.Unmarshal(data, &response); err != nil || response.Data == nil || response.Data.Output == nil || response.Data.Cursor == nil || response.Data.Size == nil || response.Data.Truncated == nil || len(*response.Data.Output) > query.Limit || *response.Data.Cursor < query.Cursor || *response.Data.Cursor > protocol.ChatShellOutputMaxCursor || *response.Data.Size < *response.Data.Cursor || *response.Data.Size > protocol.ChatShellOutputMaxCursor || *response.Data.Cursor-query.Cursor != int64(len(*response.Data.Output)) {
|
||||||
return protocol.ChatShellOutputPage{}, fmt.Errorf("invalid OpenCode shell output response")
|
return protocol.ChatShellOutputPage{}, fmt.Errorf("invalid OpenCode shell output response")
|
||||||
}
|
}
|
||||||
return protocol.ChatShellOutputPage{Shell: shell, Output: response.Data.Output, Cursor: response.Data.Cursor, Size: response.Data.Size, Truncated: response.Data.Truncated}, nil
|
return protocol.ChatShellOutputPage{Shell: shell, Output: *response.Data.Output, Cursor: *response.Data.Cursor, Size: *response.Data.Size, Truncated: *response.Data.Truncated}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// streamState returns the session's retained, verified shell identities. It is
|
// streamState returns the session's retained, verified shell identities. It is
|
||||||
|
|||||||
@@ -450,6 +450,33 @@ func TestChatShellOutputVerifiesOwnerAndBoundsPage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestChatShellOutputRejectsMissingRequiredPageFields(t *testing.T) {
|
||||||
|
for _, body := range []string{
|
||||||
|
`{"data":{}}`,
|
||||||
|
`{"data":{"output":"","cursor":0,"size":0}}`,
|
||||||
|
`{"data":{"output":"","size":0,"truncated":false}}`,
|
||||||
|
`{"data":{"output":"","cursor":0,"truncated":false}}`,
|
||||||
|
} {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/api/shell/sh_1":
|
||||||
|
_, _ = w.Write([]byte(`{"data":{"id":"sh_1","status":"running","metadata":{"sessionID":"ses_1"}}}`))
|
||||||
|
case "/api/shell/sh_1/output":
|
||||||
|
_, _ = w.Write([]byte(body))
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||||
|
_, err := chat.ShellOutput(context.Background(), protocol.ChatShellOutputQuery{SessionID: "ses_1", ShellID: "sh_1", Limit: 1})
|
||||||
|
srv.Close()
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("response %s was accepted", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestChatReleaseShellsBoundsDisconnectedState(t *testing.T) {
|
func TestChatReleaseShellsBoundsDisconnectedState(t *testing.T) {
|
||||||
chat := NewChat(&Connection{})
|
chat := NewChat(&Connection{})
|
||||||
state := chat.streamState("ses_1")
|
state := chat.streamState("ses_1")
|
||||||
|
|||||||
@@ -93,8 +93,10 @@ const (
|
|||||||
// ChatShell.Status values, mirroring the OpenCode shell events. A running shell
|
// ChatShell.Status values, mirroring the OpenCode shell events. A running shell
|
||||||
// is one whose command has started and not yet exited; exited is final.
|
// is one whose command has started and not yet exited; exited is final.
|
||||||
const (
|
const (
|
||||||
ChatShellRunning = "running"
|
ChatShellRunning = "running"
|
||||||
ChatShellExited = "exited"
|
ChatShellExited = "exited"
|
||||||
|
ChatShellOutputLimit = 64 << 10
|
||||||
|
ChatShellOutputMaxCursor = int64(1 << 62)
|
||||||
)
|
)
|
||||||
|
|
||||||
// ChatStep.Status values, mirroring the OpenCode session.step events.
|
// ChatStep.Status values, mirroring the OpenCode session.step events.
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ import (
|
|||||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||||
)
|
)
|
||||||
|
|
||||||
const chatShellOutputLimit = 64 << 10
|
|
||||||
|
|
||||||
func operatorChatSession(ctx context.Context, registry operatorRegistry, id string) error {
|
func operatorChatSession(ctx context.Context, registry operatorRegistry, id string) error {
|
||||||
if registry == nil {
|
if registry == nil {
|
||||||
return fmt.Errorf("operator session registry is not configured on this server")
|
return fmt.Errorf("operator session registry is not configured on this server")
|
||||||
@@ -52,7 +50,7 @@ func handleChatShellOutput(ctx context.Context, request protocol.Message, broker
|
|||||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if query == nil || !opencode.ValidSessionID(query.SessionID) || !validShellID(query.ShellID) || query.Cursor < 0 || query.Limit < 0 || query.Limit > chatShellOutputLimit {
|
if query == nil || !opencode.ValidSessionID(query.SessionID) || !validShellID(query.ShellID) || query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
|
||||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid bounded shell output query is required"})
|
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid bounded shell output query is required"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -73,4 +71,6 @@ func handleChatShellOutput(ctx context.Context, request protocol.Message, broker
|
|||||||
_ = write(protocol.Message{Type: protocol.ChatShellOutput, ID: request.ID, ChatShellOutput: &output})
|
_ = write(protocol.Message{Type: protocol.ChatShellOutput, ID: request.ID, ChatShellOutput: &output})
|
||||||
}
|
}
|
||||||
|
|
||||||
func validShellID(id string) bool { return len(id) > 3 && len(id) <= 128 && id[:3] == "sh_" }
|
func validShellID(id string) bool {
|
||||||
|
return opencode.ValidShellID(id)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
type shellOutputTestBroker struct {
|
||||||
|
*fakeChat
|
||||||
|
outputCalls int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *shellOutputTestBroker) ShellOutput(context.Context, protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
|
||||||
|
b.outputCalls++
|
||||||
|
return protocol.ChatShellOutputPage{Output: "unexpected"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChatShellOutputRejectsBoundsBeforeRegistryOrProvider(t *testing.T) {
|
||||||
|
store := newOperatorStore(t)
|
||||||
|
broker := &shellOutputTestBroker{fakeChat: scriptedChat()}
|
||||||
|
queries := []protocol.ChatShellOutputQuery{
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_1", Limit: 0},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_1", Limit: -1},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_1", Cursor: protocol.ChatShellOutputMaxCursor + 1, Limit: 1},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_1/../x", Limit: 1},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_1%2f", Limit: 1},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_1?cursor=0", Limit: 1},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_1#fragment", Limit: 1},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_%ZZ", Limit: 1},
|
||||||
|
{SessionID: "ses_1", ShellID: "sh_" + string(make([]byte, 126)), Limit: 1},
|
||||||
|
}
|
||||||
|
for _, query := range queries {
|
||||||
|
var response protocol.Message
|
||||||
|
handleChatShellOutput(context.Background(), protocol.Message{ChatShellOutputQuery: &query}, broker, store, func(m protocol.Message) error {
|
||||||
|
response = m
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if response.Type != protocol.Error {
|
||||||
|
t.Fatalf("query %+v response = %+v", query, response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if broker.outputCalls != 0 {
|
||||||
|
t.Fatalf("invalid queries reached provider %d times", broker.outputCalls)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,8 @@ const LargeChatFixtureSessionID = "ses_large_chat_fixture"
|
|||||||
// LargeChatFixturePassword authenticates the disposable fixture endpoint. It is
|
// LargeChatFixturePassword authenticates the disposable fixture endpoint. It is
|
||||||
// fixed fixture data, not an operator credential.
|
// fixed fixture data, not an operator credential.
|
||||||
const LargeChatFixturePassword = "large-chat-fixture"
|
const LargeChatFixturePassword = "large-chat-fixture"
|
||||||
|
const LargeChatFixtureShellID = "sh_large_chat_fixture"
|
||||||
|
const LargeChatFixtureShellOutput = "fixture shell output marker\n"
|
||||||
|
|
||||||
const (
|
const (
|
||||||
LargeChatFixtureNewestAnswer = "Controlled newest answer: large history fixture"
|
LargeChatFixtureNewestAnswer = "Controlled newest answer: large history fixture"
|
||||||
@@ -24,6 +26,13 @@ const (
|
|||||||
// It deliberately serves fixed, paged data: no model is invoked and no production
|
// It deliberately serves fixed, paged data: no model is invoked and no production
|
||||||
// history is read or written.
|
// history is read or written.
|
||||||
func LargeChatFixtureHandler(workspace string) http.Handler {
|
func LargeChatFixtureHandler(workspace string) http.Handler {
|
||||||
|
return LargeChatFixtureHandlerWithShell(workspace, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LargeChatFixtureHandlerWithShell is the foreground fixture surface used by
|
||||||
|
// the readback check. exited selects the provider's observed terminal state;
|
||||||
|
// the output remains fixed and bounded in either state.
|
||||||
|
func LargeChatFixtureHandlerWithShell(workspace string, exited bool) http.Handler {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("GET /api/info", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("GET /api/info", func(w http.ResponseWriter, r *http.Request) {
|
||||||
if !largeChatFixtureAuthenticated(w, r) {
|
if !largeChatFixtureAuthenticated(w, r) {
|
||||||
@@ -63,6 +72,33 @@ func LargeChatFixtureHandler(workspace string) http.Handler {
|
|||||||
}
|
}
|
||||||
writeLargeChatFixturePage(w, page)
|
writeLargeChatFixturePage(w, page)
|
||||||
})
|
})
|
||||||
|
status := "running"
|
||||||
|
if exited {
|
||||||
|
status = "exited"
|
||||||
|
}
|
||||||
|
mux.HandleFunc("GET /api/shell", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !largeChatFixtureAuthenticated(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":[{"id":%q,"status":%q,"command":"printf fixture","metadata":{"sessionID":%q}}]}`, LargeChatFixtureShellID, status, LargeChatFixtureSessionID))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureShellID, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !largeChatFixtureAuthenticated(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
exit := "null"
|
||||||
|
if exited {
|
||||||
|
exit = "0"
|
||||||
|
}
|
||||||
|
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"id":%q,"status":%q,"command":"printf fixture","exit":%s,"metadata":{"sessionID":%q}}}`, LargeChatFixtureShellID, status, exit, LargeChatFixtureSessionID))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/shell/"+LargeChatFixtureShellID+"/output", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !largeChatFixtureAuthenticated(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cursor := int64(len(LargeChatFixtureShellOutput))
|
||||||
|
writeLargeChatFixtureJSON(w, fmt.Sprintf(`{"data":{"output":%q,"cursor":%d,"size":%d,"truncated":false}}`, LargeChatFixtureShellOutput, cursor, cursor))
|
||||||
|
})
|
||||||
return mux
|
return mux
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user