diff --git a/cli/internal/daemon/boundary_regression_test.go b/cli/internal/daemon/boundary_regression_test.go index ef38cade5..59ed83490 100644 --- a/cli/internal/daemon/boundary_regression_test.go +++ b/cli/internal/daemon/boundary_regression_test.go @@ -82,6 +82,18 @@ func TestSessionReadValidatesRequiredAndNullableMembers(t *testing.T) { {"nested nullable retained", func(session map[string]any) { session["kernel"].(map[string]any)["live_job_count"] = nil }, true}, + {"job list omitted", func(session map[string]any) { + delete(session["kernel"].(map[string]any), "running_jobs") + }, false}, + {"unknown job list", func(session map[string]any) { + session["kernel"].(map[string]any)["running_jobs"] = nil + }, true}, + {"job pid omitted", func(session map[string]any) { + session["kernel"].(map[string]any)["running_jobs"] = []any{map[string]any{"id": "j", "command": "sleep 10"}} + }, false}, + {"nullable job pid", func(session map[string]any) { + session["kernel"].(map[string]any)["running_jobs"] = []any{map[string]any{"id": "j", "pid": nil, "command": "sleep 10"}} + }, true}, {"null scalar", func(session map[string]any) { session["status"].(map[string]any)["interrupt_requested"] = nil }, false}, diff --git a/cli/internal/daemon/commands.go b/cli/internal/daemon/commands.go index a8fe0a94a..a69a612a1 100644 --- a/cli/internal/daemon/commands.go +++ b/cli/internal/daemon/commands.go @@ -5,6 +5,8 @@ import ( "encoding/json" "errors" "maps" + "strings" + "unicode" ) type CommandResult struct { @@ -57,23 +59,49 @@ func InvokeDeclaredCommand(ctx context.Context, conn *Connection, snapshot Sessi return extensionResult(data), nil } +// ParseCommandArguments reads the text typed after a command name. Words fill +// the declared arguments in order and the last argument takes the rest of the +// line; a JSON object names them instead. func ParseCommandArguments(command SessionCommand, text string) (map[string]json.RawMessage, error) { + text = strings.TrimSpace(text) + if len(command.Arguments) > 1 && strings.HasPrefix(text, "{") { + return namedCommandArguments(command, text) + } result := map[string]json.RawMessage{} - if len(command.Arguments) == 1 { - argument := command.Arguments[0] - if text != "" || argument.Required { - value, err := actionFieldValue(argument.field, text) - if err != nil { - return nil, err - } - result[argument.Name] = value + for index, argument := range command.Arguments { + word := text + if index < len(command.Arguments)-1 { + word, text = cutWord(text) + } else { + text = "" + } + if word == "" && !argument.Required { + continue } - return result, nil + value, err := actionFieldValue(argument.field, word) + if err != nil { + return nil, err + } + result[argument.Name] = value } if text != "" { - if err := json.Unmarshal([]byte(text), &result); err != nil { - return nil, errors.New("this command accepts a JSON object with its declared argument names") - } + return nil, errors.New(command.Name + " takes no arguments") + } + return result, nil +} + +func cutWord(text string) (string, string) { + end := strings.IndexFunc(text, unicode.IsSpace) + if end < 0 { + return text, "" + } + return text[:end], strings.TrimSpace(text[end:]) +} + +func namedCommandArguments(command SessionCommand, text string) (map[string]json.RawMessage, error) { + result := map[string]json.RawMessage{} + if err := json.Unmarshal([]byte(text), &result); err != nil { + return nil, errors.New("this command accepts words in argument order or a JSON object with its declared argument names") } for _, field := range command.Arguments { raw, ok := result[field.Name] diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index f8e65f150..d755503de 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -1068,19 +1068,44 @@ type JSONContent struct { Value DynamicJSON `json:"value"` } +// JobCollection Examples: {"items":[],"live_job_count":0,"page":{"actions":[],"empty_state":"no background jobs running","glance":null,"rows":[],"summary":"0 background jobs running","title":"jobs"}} +type JobCollection struct { + Items []KernelJob `json:"items"` + LiveJobCount Counter `json:"live_job_count"` + Page PageDescriptor `json:"page"` +} + +// JobStop Examples: {"stopped":"job-1"} +type JobStop struct { + // Stopped Opaque identity. Never infer a resource type or route from its contents. + Stopped ID `json:"stopped"` +} + // Kernel defines model for Kernel. type Kernel struct { Build *string `json:"build" nullable:"true"` InstanceID *ID `json:"instance_id" nullable:"true"` // LiveJobCount Observed owned jobs. Null while booting or when the kernel owner is lost. - LiveJobCount *Counter `json:"live_job_count" nullable:"true"` + LiveJobCount *Counter `json:"live_job_count" nullable:"true"` + + // RunningJobs Up to 100 observed live jobs, ordered by ID. Null when the kernel owner is unavailable. The count may exceed this list. + RunningJobs []KernelJob `json:"running_jobs" nullable:"true"` Stage *string `json:"stage" nullable:"true"` Stale bool `json:"stale"` StalenessReasons []SafeReason `json:"staleness_reasons"` State string `json:"state"` } +// KernelJob defines model for KernelJob. +type KernelJob struct { + Command string `json:"command"` + + // ID Opaque identity. Never infer a resource type or route from its contents. + ID ID `json:"id"` + Pid *Counter `json:"pid" nullable:"true"` +} + // KernelUpgradeResult defines model for KernelUpgradeResult. type KernelUpgradeResult struct { Failure *SafeReason `json:"failure" nullable:"true"` @@ -1926,7 +1951,7 @@ type RequestRecordPage struct { // ResetBatch Leading reset and complete snapshot. Later events, if any, follow the snapshot cursor. Envelope cursor advances through every delivered event. // -// Examples: {"cursor":0,"events":[{"data":{"reason":"initial"},"type":"reset"}],"generation":"J6kYj6IGcXyP3eMIp-WL3A","snapshot":{"activity":{"latest_answer":null,"latest_input":null,"lines":[],"observed_at":"2026-10-02T14:00:00Z","output_scalars":0,"output_utf8_bytes":0},"activity_at":"2026-10-02T14:00:00Z","address":null,"automatic_name":"New session","closed":false,"composition":{"availability":{},"dependencies":{},"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"quarantine":[]},"configuration_resource":{"etag":"\"session-config-1\"","url":"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration","value":{"effort":null,"family_revision":"family-1","id":"01a0fcea-2b00-7000-8000-000000000001","model":"example-model","name":"New session","preferences":{"archived":false,"pin_order":null,"pinned":false},"provider_profile":"personal","revision":"config-1","selection":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"workspace":"/workspace/project"}},"created_at":"2026-10-02T14:00:00Z","creation":{"resolved":{"effort":null,"model":"example-model","provider_profile":"personal","workspace":"/workspace/project"},"submitted":{"effort":null,"kind":"new","model":null,"name":null,"provider_profile":null,"workspace":"/workspace/project"}},"current_progress":[],"cursor":{"generation":"J6kYj6IGcXyP3eMIp-WL3A","sequence":0},"depth":0,"effort":null,"family_revision":"family-1","glances":[],"history":{"high_water":0,"items":[],"newer":null,"older":null},"id":"01a0fcea-2b00-7000-8000-000000000001","input_order":0,"kernel":{"build":null,"instance_id":null,"live_job_count":0,"stage":null,"stale":false,"staleness_reasons":[],"state":"none"},"location":{"host":null,"label":null,"path":"/workspace/project","user":null},"model":"example-model","name":"New session","parent_id":null,"pending_inputs":[],"preferences":{"archived":false,"opens":0,"pin_order":null,"pinned":false},"preview":{"text":"","transcript_count":0,"truncated":false},"provider_profile":"personal","revision":"config-1","root_id":"01a0fcea-2b00-7000-8000-000000000001","selection":{"effective":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"overrides":{"extensions":{},"instructions":{},"mcp":{},"skills":{}}},"status":{"blocking_reason":null,"interrupt_requested":false,"phase":"idle","run_id":null},"usage":{"cache_fade":[],"cache_ttl_seconds":null,"cache_write_tokens":null,"cached_prompt_tokens":null,"completion_tokens":null,"context_window_tokens":null,"elapsed_ms":null,"model":null,"observed_at":null,"prompt_tokens":null,"tokens_per_second":null,"total_tokens":null},"workspace":"/workspace/project","workspace_change":null}} +// Examples: {"cursor":0,"events":[{"data":{"reason":"initial"},"type":"reset"}],"generation":"J6kYj6IGcXyP3eMIp-WL3A","snapshot":{"activity":{"latest_answer":null,"latest_input":null,"lines":[],"observed_at":"2026-10-02T14:00:00Z","output_scalars":0,"output_utf8_bytes":0},"activity_at":"2026-10-02T14:00:00Z","address":null,"automatic_name":"New session","closed":false,"composition":{"availability":{},"dependencies":{},"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"quarantine":[]},"configuration_resource":{"etag":"\"session-config-1\"","url":"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration","value":{"effort":null,"family_revision":"family-1","id":"01a0fcea-2b00-7000-8000-000000000001","model":"example-model","name":"New session","preferences":{"archived":false,"pin_order":null,"pinned":false},"provider_profile":"personal","revision":"config-1","selection":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"workspace":"/workspace/project"}},"created_at":"2026-10-02T14:00:00Z","creation":{"resolved":{"effort":null,"model":"example-model","provider_profile":"personal","workspace":"/workspace/project"},"submitted":{"effort":null,"kind":"new","model":null,"name":null,"provider_profile":null,"workspace":"/workspace/project"}},"current_progress":[],"cursor":{"generation":"J6kYj6IGcXyP3eMIp-WL3A","sequence":0},"depth":0,"effort":null,"family_revision":"family-1","glances":[],"history":{"high_water":0,"items":[],"newer":null,"older":null},"id":"01a0fcea-2b00-7000-8000-000000000001","input_order":0,"kernel":{"build":null,"instance_id":null,"live_job_count":0,"running_jobs":[],"stage":null,"stale":false,"staleness_reasons":[],"state":"none"},"location":{"host":null,"label":null,"path":"/workspace/project","user":null},"model":"example-model","name":"New session","parent_id":null,"pending_inputs":[],"preferences":{"archived":false,"opens":0,"pin_order":null,"pinned":false},"preview":{"text":"","transcript_count":0,"truncated":false},"provider_profile":"personal","revision":"config-1","root_id":"01a0fcea-2b00-7000-8000-000000000001","selection":{"effective":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"overrides":{"extensions":{},"instructions":{},"mcp":{},"skills":{}}},"status":{"blocking_reason":null,"interrupt_requested":false,"phase":"idle","run_id":null},"usage":{"cache_fade":[],"cache_ttl_seconds":null,"cache_write_tokens":null,"cached_prompt_tokens":null,"completion_tokens":null,"context_window_tokens":null,"elapsed_ms":null,"model":null,"observed_at":null,"prompt_tokens":null,"tokens_per_second":null,"total_tokens":null},"workspace":"/workspace/project","workspace_change":null}} type ResetBatch struct { Cursor Counter `json:"cursor"` Events []SessionEvent `json:"events"` @@ -1934,7 +1959,7 @@ type ResetBatch struct { // Generation 128 random bits encoded as unpadded base64url; new for each session actor lifetime. Generation Generation `json:"generation"` - // Snapshot Examples: {"activity":{"latest_answer":null,"latest_input":null,"lines":[],"observed_at":"2026-10-02T14:00:00Z","output_scalars":0,"output_utf8_bytes":0},"activity_at":"2026-10-02T14:00:00Z","address":null,"automatic_name":"New session","closed":false,"composition":{"availability":{},"dependencies":{},"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"quarantine":[]},"configuration_resource":{"etag":"\"session-config-1\"","url":"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration","value":{"effort":null,"family_revision":"family-1","id":"01a0fcea-2b00-7000-8000-000000000001","model":"example-model","name":"New session","preferences":{"archived":false,"pin_order":null,"pinned":false},"provider_profile":"personal","revision":"config-1","selection":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"workspace":"/workspace/project"}},"created_at":"2026-10-02T14:00:00Z","creation":{"resolved":{"effort":null,"model":"example-model","provider_profile":"personal","workspace":"/workspace/project"},"submitted":{"effort":null,"kind":"new","model":null,"name":null,"provider_profile":null,"workspace":"/workspace/project"}},"current_progress":[],"cursor":{"generation":"J6kYj6IGcXyP3eMIp-WL3A","sequence":0},"depth":0,"effort":null,"family_revision":"family-1","glances":[],"history":{"high_water":0,"items":[],"newer":null,"older":null},"id":"01a0fcea-2b00-7000-8000-000000000001","input_order":0,"kernel":{"build":null,"instance_id":null,"live_job_count":0,"stage":null,"stale":false,"staleness_reasons":[],"state":"none"},"location":{"host":null,"label":null,"path":"/workspace/project","user":null},"model":"example-model","name":"New session","parent_id":null,"pending_inputs":[],"preferences":{"archived":false,"opens":0,"pin_order":null,"pinned":false},"preview":{"text":"","transcript_count":0,"truncated":false},"provider_profile":"personal","revision":"config-1","root_id":"01a0fcea-2b00-7000-8000-000000000001","selection":{"effective":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"overrides":{"extensions":{},"instructions":{},"mcp":{},"skills":{}}},"status":{"blocking_reason":null,"interrupt_requested":false,"phase":"idle","run_id":null},"usage":{"cache_fade":[],"cache_ttl_seconds":null,"cache_write_tokens":null,"cached_prompt_tokens":null,"completion_tokens":null,"context_window_tokens":null,"elapsed_ms":null,"model":null,"observed_at":null,"prompt_tokens":null,"tokens_per_second":null,"total_tokens":null},"workspace":"/workspace/project","workspace_change":null} + // Snapshot Examples: {"activity":{"latest_answer":null,"latest_input":null,"lines":[],"observed_at":"2026-10-02T14:00:00Z","output_scalars":0,"output_utf8_bytes":0},"activity_at":"2026-10-02T14:00:00Z","address":null,"automatic_name":"New session","closed":false,"composition":{"availability":{},"dependencies":{},"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"quarantine":[]},"configuration_resource":{"etag":"\"session-config-1\"","url":"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration","value":{"effort":null,"family_revision":"family-1","id":"01a0fcea-2b00-7000-8000-000000000001","model":"example-model","name":"New session","preferences":{"archived":false,"pin_order":null,"pinned":false},"provider_profile":"personal","revision":"config-1","selection":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"workspace":"/workspace/project"}},"created_at":"2026-10-02T14:00:00Z","creation":{"resolved":{"effort":null,"model":"example-model","provider_profile":"personal","workspace":"/workspace/project"},"submitted":{"effort":null,"kind":"new","model":null,"name":null,"provider_profile":null,"workspace":"/workspace/project"}},"current_progress":[],"cursor":{"generation":"J6kYj6IGcXyP3eMIp-WL3A","sequence":0},"depth":0,"effort":null,"family_revision":"family-1","glances":[],"history":{"high_water":0,"items":[],"newer":null,"older":null},"id":"01a0fcea-2b00-7000-8000-000000000001","input_order":0,"kernel":{"build":null,"instance_id":null,"live_job_count":0,"running_jobs":[],"stage":null,"stale":false,"staleness_reasons":[],"state":"none"},"location":{"host":null,"label":null,"path":"/workspace/project","user":null},"model":"example-model","name":"New session","parent_id":null,"pending_inputs":[],"preferences":{"archived":false,"opens":0,"pin_order":null,"pinned":false},"preview":{"text":"","transcript_count":0,"truncated":false},"provider_profile":"personal","revision":"config-1","root_id":"01a0fcea-2b00-7000-8000-000000000001","selection":{"effective":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"overrides":{"extensions":{},"instructions":{},"mcp":{},"skills":{}}},"status":{"blocking_reason":null,"interrupt_requested":false,"phase":"idle","run_id":null},"usage":{"cache_fade":[],"cache_ttl_seconds":null,"cache_write_tokens":null,"cached_prompt_tokens":null,"completion_tokens":null,"context_window_tokens":null,"elapsed_ms":null,"model":null,"observed_at":null,"prompt_tokens":null,"tokens_per_second":null,"total_tokens":null},"workspace":"/workspace/project","workspace_change":null} Snapshot Session `json:"snapshot"` } @@ -2150,7 +2175,7 @@ type SessionChange struct { } `json:"move" nullable:"true"` Resource SessionConfigurationResource `json:"resource"` - // Session Examples: {"activity":{"latest_answer":null,"latest_input":null,"lines":[],"observed_at":"2026-10-02T14:00:00Z","output_scalars":0,"output_utf8_bytes":0},"activity_at":"2026-10-02T14:00:00Z","address":null,"automatic_name":"New session","closed":false,"composition":{"availability":{},"dependencies":{},"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"quarantine":[]},"configuration_resource":{"etag":"\"session-config-1\"","url":"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration","value":{"effort":null,"family_revision":"family-1","id":"01a0fcea-2b00-7000-8000-000000000001","model":"example-model","name":"New session","preferences":{"archived":false,"pin_order":null,"pinned":false},"provider_profile":"personal","revision":"config-1","selection":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"workspace":"/workspace/project"}},"created_at":"2026-10-02T14:00:00Z","creation":{"resolved":{"effort":null,"model":"example-model","provider_profile":"personal","workspace":"/workspace/project"},"submitted":{"effort":null,"kind":"new","model":null,"name":null,"provider_profile":null,"workspace":"/workspace/project"}},"current_progress":[],"cursor":{"generation":"J6kYj6IGcXyP3eMIp-WL3A","sequence":0},"depth":0,"effort":null,"family_revision":"family-1","glances":[],"history":{"high_water":0,"items":[],"newer":null,"older":null},"id":"01a0fcea-2b00-7000-8000-000000000001","input_order":0,"kernel":{"build":null,"instance_id":null,"live_job_count":0,"stage":null,"stale":false,"staleness_reasons":[],"state":"none"},"location":{"host":null,"label":null,"path":"/workspace/project","user":null},"model":"example-model","name":"New session","parent_id":null,"pending_inputs":[],"preferences":{"archived":false,"opens":0,"pin_order":null,"pinned":false},"preview":{"text":"","transcript_count":0,"truncated":false},"provider_profile":"personal","revision":"config-1","root_id":"01a0fcea-2b00-7000-8000-000000000001","selection":{"effective":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"overrides":{"extensions":{},"instructions":{},"mcp":{},"skills":{}}},"status":{"blocking_reason":null,"interrupt_requested":false,"phase":"idle","run_id":null},"usage":{"cache_fade":[],"cache_ttl_seconds":null,"cache_write_tokens":null,"cached_prompt_tokens":null,"completion_tokens":null,"context_window_tokens":null,"elapsed_ms":null,"model":null,"observed_at":null,"prompt_tokens":null,"tokens_per_second":null,"total_tokens":null},"workspace":"/workspace/project","workspace_change":null} + // Session Examples: {"activity":{"latest_answer":null,"latest_input":null,"lines":[],"observed_at":"2026-10-02T14:00:00Z","output_scalars":0,"output_utf8_bytes":0},"activity_at":"2026-10-02T14:00:00Z","address":null,"automatic_name":"New session","closed":false,"composition":{"availability":{},"dependencies":{},"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"quarantine":[]},"configuration_resource":{"etag":"\"session-config-1\"","url":"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration","value":{"effort":null,"family_revision":"family-1","id":"01a0fcea-2b00-7000-8000-000000000001","model":"example-model","name":"New session","preferences":{"archived":false,"pin_order":null,"pinned":false},"provider_profile":"personal","revision":"config-1","selection":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"workspace":"/workspace/project"}},"created_at":"2026-10-02T14:00:00Z","creation":{"resolved":{"effort":null,"model":"example-model","provider_profile":"personal","workspace":"/workspace/project"},"submitted":{"effort":null,"kind":"new","model":null,"name":null,"provider_profile":null,"workspace":"/workspace/project"}},"current_progress":[],"cursor":{"generation":"J6kYj6IGcXyP3eMIp-WL3A","sequence":0},"depth":0,"effort":null,"family_revision":"family-1","glances":[],"history":{"high_water":0,"items":[],"newer":null,"older":null},"id":"01a0fcea-2b00-7000-8000-000000000001","input_order":0,"kernel":{"build":null,"instance_id":null,"live_job_count":0,"running_jobs":[],"stage":null,"stale":false,"staleness_reasons":[],"state":"none"},"location":{"host":null,"label":null,"path":"/workspace/project","user":null},"model":"example-model","name":"New session","parent_id":null,"pending_inputs":[],"preferences":{"archived":false,"opens":0,"pin_order":null,"pinned":false},"preview":{"text":"","transcript_count":0,"truncated":false},"provider_profile":"personal","revision":"config-1","root_id":"01a0fcea-2b00-7000-8000-000000000001","selection":{"effective":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"overrides":{"extensions":{},"instructions":{},"mcp":{},"skills":{}}},"status":{"blocking_reason":null,"interrupt_requested":false,"phase":"idle","run_id":null},"usage":{"cache_fade":[],"cache_ttl_seconds":null,"cache_write_tokens":null,"cached_prompt_tokens":null,"completion_tokens":null,"context_window_tokens":null,"elapsed_ms":null,"model":null,"observed_at":null,"prompt_tokens":null,"tokens_per_second":null,"total_tokens":null},"workspace":"/workspace/project","workspace_change":null} Session Session `json:"session"` } @@ -2363,7 +2388,7 @@ type SessionRetryEvent struct { // SessionSSE One parsed SSE event. Decode data as JSON and validate SessionBatch separately; contentSchema is not asserted by ordinary JSON Schema validation. No event, id or retry fields are emitted. // -// Examples: {"data":"{\"generation\":\"J6kYj6IGcXyP3eMIp-WL3A\",\"cursor\":0,\"events\":[{\"type\":\"reset\",\"data\":{\"reason\":\"initial\"}}],\"snapshot\":{\"id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"name\":\"New session\",\"automatic_name\":\"New session\",\"workspace\":\"/workspace/project\",\"location\":{\"host\":null,\"user\":null,\"path\":\"/workspace/project\",\"label\":null},\"parent_id\":null,\"root_id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"address\":null,\"depth\":0,\"closed\":false,\"created_at\":\"2026-10-02T14:00:00Z\",\"activity_at\":\"2026-10-02T14:00:00Z\",\"provider_profile\":\"personal\",\"model\":\"example-model\",\"effort\":null,\"status\":{\"phase\":\"idle\",\"run_id\":null,\"interrupt_requested\":false,\"blocking_reason\":null},\"preview\":{\"text\":\"\",\"transcript_count\":0,\"truncated\":false},\"preferences\":{\"pinned\":false,\"pin_order\":null,\"archived\":false,\"opens\":0},\"current_progress\":[],\"activity\":{\"lines\":[],\"output_scalars\":0,\"output_utf8_bytes\":0,\"observed_at\":\"2026-10-02T14:00:00Z\",\"latest_input\":null,\"latest_answer\":null},\"cursor\":{\"generation\":\"J6kYj6IGcXyP3eMIp-WL3A\",\"sequence\":0},\"creation\":{\"submitted\":{\"kind\":\"new\",\"workspace\":\"/workspace/project\",\"name\":null,\"provider_profile\":null,\"model\":null,\"effort\":null},\"resolved\":{\"workspace\":\"/workspace/project\",\"provider_profile\":\"personal\",\"model\":\"example-model\",\"effort\":null}},\"revision\":\"config-1\",\"family_revision\":\"family-1\",\"configuration_resource\":{\"url\":\"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration\",\"etag\":\"\\\"session-config-1\\\"\",\"value\":{\"id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"name\":\"New session\",\"workspace\":\"/workspace/project\",\"provider_profile\":\"personal\",\"model\":\"example-model\",\"effort\":null,\"preferences\":{\"pinned\":false,\"pin_order\":null,\"archived\":false},\"selection\":{\"extensions\":{},\"skills\":{},\"instructions\":{},\"mcp\":{}},\"revision\":\"config-1\",\"family_revision\":\"family-1\"}},\"workspace_change\":null,\"selection\":{\"overrides\":{\"extensions\":{},\"skills\":{},\"instructions\":{},\"mcp\":{}},\"effective\":{\"extensions\":{},\"skills\":{},\"instructions\":{},\"mcp\":{}}},\"composition\":{\"desired_revision\":\"composition-1\",\"loaded_revision\":null,\"needs_reload\":true,\"dependencies\":{},\"quarantine\":[],\"availability\":{}},\"kernel\":{\"instance_id\":null,\"state\":\"none\",\"stage\":null,\"build\":null,\"stale\":false,\"staleness_reasons\":[],\"live_job_count\":0},\"pending_inputs\":[],\"input_order\":0,\"usage\":{\"model\":null,\"observed_at\":null,\"prompt_tokens\":null,\"cached_prompt_tokens\":null,\"cache_write_tokens\":null,\"completion_tokens\":null,\"total_tokens\":null,\"elapsed_ms\":null,\"tokens_per_second\":null,\"context_window_tokens\":null,\"cache_ttl_seconds\":null,\"cache_fade\":[]},\"history\":{\"items\":[],\"older\":null,\"newer\":null,\"high_water\":0},\"glances\":[]}}"}, {"data":"{\"generation\":\"J6kYj6IGcXyP3eMIp-WL3A\",\"cursor\":1,\"events\":[{\"type\":\"input\",\"sequence\":1,\"data\":{\"input\":{\"id\":\"01a0fcea-2b00-7000-8000-000000000002\",\"session_id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"kind\":\"message\",\"admission\":\"accepted\",\"http_status\":202,\"problem\":null,\"accepted_at\":\"2026-10-02T14:00:00Z\",\"acceptance_order\":1,\"delivery\":\"pending\",\"blocking_reason\":null,\"transcript_position\":null,\"turn\":null,\"client_id\":\"draft-1\"}}}]}"} +// Examples: {"data":"{\"generation\":\"J6kYj6IGcXyP3eMIp-WL3A\",\"cursor\":0,\"events\":[{\"type\":\"reset\",\"data\":{\"reason\":\"initial\"}}],\"snapshot\":{\"id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"name\":\"New session\",\"automatic_name\":\"New session\",\"workspace\":\"/workspace/project\",\"location\":{\"host\":null,\"user\":null,\"path\":\"/workspace/project\",\"label\":null},\"parent_id\":null,\"root_id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"address\":null,\"depth\":0,\"closed\":false,\"created_at\":\"2026-10-02T14:00:00Z\",\"activity_at\":\"2026-10-02T14:00:00Z\",\"provider_profile\":\"personal\",\"model\":\"example-model\",\"effort\":null,\"status\":{\"phase\":\"idle\",\"run_id\":null,\"interrupt_requested\":false,\"blocking_reason\":null},\"preview\":{\"text\":\"\",\"transcript_count\":0,\"truncated\":false},\"preferences\":{\"pinned\":false,\"pin_order\":null,\"archived\":false,\"opens\":0},\"current_progress\":[],\"activity\":{\"lines\":[],\"output_scalars\":0,\"output_utf8_bytes\":0,\"observed_at\":\"2026-10-02T14:00:00Z\",\"latest_input\":null,\"latest_answer\":null},\"cursor\":{\"generation\":\"J6kYj6IGcXyP3eMIp-WL3A\",\"sequence\":0},\"creation\":{\"submitted\":{\"kind\":\"new\",\"workspace\":\"/workspace/project\",\"name\":null,\"provider_profile\":null,\"model\":null,\"effort\":null},\"resolved\":{\"workspace\":\"/workspace/project\",\"provider_profile\":\"personal\",\"model\":\"example-model\",\"effort\":null}},\"revision\":\"config-1\",\"family_revision\":\"family-1\",\"configuration_resource\":{\"url\":\"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration\",\"etag\":\"\\\"session-config-1\\\"\",\"value\":{\"id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"name\":\"New session\",\"workspace\":\"/workspace/project\",\"provider_profile\":\"personal\",\"model\":\"example-model\",\"effort\":null,\"preferences\":{\"pinned\":false,\"pin_order\":null,\"archived\":false},\"selection\":{\"extensions\":{},\"skills\":{},\"instructions\":{},\"mcp\":{}},\"revision\":\"config-1\",\"family_revision\":\"family-1\"}},\"workspace_change\":null,\"selection\":{\"overrides\":{\"extensions\":{},\"skills\":{},\"instructions\":{},\"mcp\":{}},\"effective\":{\"extensions\":{},\"skills\":{},\"instructions\":{},\"mcp\":{}}},\"composition\":{\"desired_revision\":\"composition-1\",\"loaded_revision\":null,\"needs_reload\":true,\"dependencies\":{},\"quarantine\":[],\"availability\":{}},\"kernel\":{\"instance_id\":null,\"state\":\"none\",\"stage\":null,\"build\":null,\"stale\":false,\"staleness_reasons\":[],\"live_job_count\":0,\"running_jobs\":[]},\"pending_inputs\":[],\"input_order\":0,\"usage\":{\"model\":null,\"observed_at\":null,\"prompt_tokens\":null,\"cached_prompt_tokens\":null,\"cache_write_tokens\":null,\"completion_tokens\":null,\"total_tokens\":null,\"elapsed_ms\":null,\"tokens_per_second\":null,\"context_window_tokens\":null,\"cache_ttl_seconds\":null,\"cache_fade\":[]},\"history\":{\"items\":[],\"older\":null,\"newer\":null,\"high_water\":0},\"glances\":[]}}"}, {"data":"{\"generation\":\"J6kYj6IGcXyP3eMIp-WL3A\",\"cursor\":1,\"events\":[{\"type\":\"input\",\"sequence\":1,\"data\":{\"input\":{\"id\":\"01a0fcea-2b00-7000-8000-000000000002\",\"session_id\":\"01a0fcea-2b00-7000-8000-000000000001\",\"kind\":\"message\",\"admission\":\"accepted\",\"http_status\":202,\"problem\":null,\"accepted_at\":\"2026-10-02T14:00:00Z\",\"acceptance_order\":1,\"delivery\":\"pending\",\"blocking_reason\":null,\"transcript_position\":null,\"turn\":null,\"client_id\":\"draft-1\"}}}]}"} type SessionSSE struct { Data string `json:"data"` } @@ -3049,6 +3074,9 @@ type PatchPaperclipsParams struct { IfMatch IfMatch `json:"If-Match"` } +// StopJobJSONBody defines parameters for StopJob. +type StopJobJSONBody = map[string]interface{} + // ListScheduleParams defines parameters for ListSchedule. type ListScheduleParams struct { SessionID ID `form:"session_id" json:"session_id"` @@ -3312,6 +3340,9 @@ type PatchPaperclipsApplicationMergePatchPlusJSONRequestBody = PaperclipPatch // CreateProxyCompletionJSONRequestBody defines body for CreateProxyCompletion for application/json ContentType. type CreateProxyCompletionJSONRequestBody = ProxyCompletionRequest +// StopJobJSONRequestBody defines body for StopJob for application/json ContentType. +type StopJobJSONRequestBody = StopJobJSONBody + // CreateScheduleJSONRequestBody defines body for CreateSchedule for application/json ContentType. type CreateScheduleJSONRequestBody = ScheduleCreate @@ -3622,6 +3653,29 @@ type ClientInterface interface { // Corresponds with GET /extensions/proxy/v1/models (the `ListProxyModels` operationId). ListProxyModels(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListJobs Read bounded live job observations and the jobs page + // + // Corresponds with GET /extensions/run/sessions/{session_id}/jobs (the `ListJobs` operationId). + ListJobs(ctx context.Context, sessionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) + + // StopJobWithBody Explicitly stop one observed process group + // + // No automatic retry after response loss. Read the job collection before confirming another attempt. A successful response confirms the supervisor verdict, not just signal delivery. + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /extensions/run/sessions/{session_id}/jobs/{job_id}/stop (the `StopJob` operationId). + StopJobWithBody(ctx context.Context, sessionID ID, jobID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // StopJob Explicitly stop one observed process group + // + // No automatic retry after response loss. Read the job collection before confirming another attempt. A successful response confirms the supervisor verdict, not just signal delivery. + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /extensions/run/sessions/{session_id}/jobs/{job_id}/stop (the `StopJob` operationId). + StopJob(ctx context.Context, sessionID ID, jobID ID, body StopJobJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListSchedule List schedule resources // // Requires enabled extension schedule. Lists may include bounded page descriptors and glances. @@ -4560,6 +4614,59 @@ func (c *Client) ListProxyModels(ctx context.Context, reqEditors ...RequestEdito return c.Client.Do(req) } +// ListJobs Read bounded live job observations and the jobs page +// +// Corresponds with GET /extensions/run/sessions/{session_id}/jobs (the `ListJobs` operationId). +func (c *Client) ListJobs(ctx context.Context, sessionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListJobsRequest(c.Server, sessionID) + 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) +} + +// StopJobWithBody Explicitly stop one observed process group +// +// No automatic retry after response loss. Read the job collection before confirming another attempt. A successful response confirms the supervisor verdict, not just signal delivery. +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /extensions/run/sessions/{session_id}/jobs/{job_id}/stop (the `StopJob` operationId). +func (c *Client) StopJobWithBody(ctx context.Context, sessionID ID, jobID ID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewStopJobRequestWithBody(c.Server, sessionID, jobID, 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) +} + +// StopJob Explicitly stop one observed process group +// +// No automatic retry after response loss. Read the job collection before confirming another attempt. A successful response confirms the supervisor verdict, not just signal delivery. +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /extensions/run/sessions/{session_id}/jobs/{job_id}/stop (the `StopJob` operationId). +func (c *Client) StopJob(ctx context.Context, sessionID ID, jobID ID, body StopJobJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewStopJobRequest(c.Server, sessionID, jobID, 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) +} + // ListSchedule List schedule resources // // Requires enabled extension schedule. Lists may include bounded page descriptors and glances. @@ -6570,6 +6677,94 @@ func NewListProxyModelsRequest(server string) (*http.Request, error) { return req, nil } +// NewListJobsRequest constructs an http.Request for the ListJobs method +func NewListJobsRequest(server string, sessionID 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 + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/extensions/run/sessions/%s/jobs", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewStopJobRequest calls the generic StopJob builder with application/json body +func NewStopJobRequest(server string, sessionID ID, jobID ID, body StopJobJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewStopJobRequestWithBody(server, sessionID, jobID, "application/json", bodyReader) +} + +// NewStopJobRequestWithBody constructs an http.Request for the StopJob method, with any body, and a specified content type +func NewStopJobRequestWithBody(server string, sessionID ID, jobID 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, "job_id", jobID, 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("/extensions/run/sessions/%s/jobs/%s/stop", 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 +} + // NewListScheduleRequest constructs an http.Request for the ListSchedule method func NewListScheduleRequest(server string, params *ListScheduleParams) (*http.Request, error) { var err error diff --git a/cli/internal/daemon/sessions.go b/cli/internal/daemon/sessions.go index bb16b76a1..8fccc7cca 100644 --- a/cli/internal/daemon/sessions.go +++ b/cli/internal/daemon/sessions.go @@ -260,7 +260,12 @@ func GetSessionPreview(ctx context.Context, conn *Connection, id string, limit i } session := sessionValue(wire) result := SessionPreview{Total: int(wire.Preview.TranscriptCount), Items: []PreviewItem{}, Session: &session} - events, err := historyEvents(wire.History.Items) + // Long tool results arrive as references, read in full like the chat's. + items, err := hydrateHistory(ctx, conn, id, wire.History.Items) + if err != nil { + return SessionPreview{}, err + } + events, err := historyEvents(items) if err != nil { return SessionPreview{}, err } diff --git a/cli/internal/daemon/settings.go b/cli/internal/daemon/settings.go index 8281a8076..4eaf5ef19 100644 --- a/cli/internal/daemon/settings.go +++ b/cli/internal/daemon/settings.go @@ -266,10 +266,20 @@ func PatchUI(ctx context.Context, conn *Connection, patch UIPreferencesPatch) (U err := patchSettingsGroup(ctx, conn, "ui", patch.ETag, patch, &change) return UIPreferences{Thinking: change.Resource.Value.Thinking, Tools: change.Resource.Value.Tools, ETag: change.Resource.ETag}, err } + +// PatchSessionUI pins or archives one session. Session lists carry no ETag, +// so a caller without one has the session's current ETag read first. func PatchSessionUI(ctx context.Context, conn *Connection, session string, patch UIPreferencesPatch) (UIPreferences, error) { if patch.Thinking != nil || patch.Tools != nil { return UIPreferences{}, errors.New("thinking and tools are shared preferences") } + if patch.ETag == "" { + current, err := GetSessionConfiguration(ctx, conn, session) + if err != nil { + return UIPreferences{}, err + } + patch.ETag = current.ETag + } body := protocol.SessionPatch{Preferences: &protocol.PreferencePatch{Pinned: patch.Pinned, Archived: patch.Archived}} updated, err := patchSession(ctx, conn, session, patch.ETag, body) prefs := UIPreferences{SessionETags: map[string]string{session: updated.ETag}} diff --git a/cli/internal/daemon/status.go b/cli/internal/daemon/status.go index d45bc2b83..ebba509c6 100644 --- a/cli/internal/daemon/status.go +++ b/cli/internal/daemon/status.go @@ -21,12 +21,13 @@ const ( type AgentStatus struct { Phase *AgentPhase - Running, Idle, KernelStale bool - KernelLink, KernelStep string RunID *string - InputOrder int64 KernelJobs *int64 KernelBuild, KernelInstanceID *string + KernelLink, KernelStep string + RunningJobs []protocol.KernelJob + InputOrder int64 + Running, Idle, KernelStale bool } func validateSessionStatus(status protocol.SessionStatus) error { @@ -50,7 +51,12 @@ func statusValue(status protocol.SessionStatus, kernel protocol.Kernel) AgentSta case "compacting": phase = PhaseCompacting } - return AgentStatus{Phase: &phase, Running: status.Phase != "idle", Idle: status.Phase == "idle", KernelStale: kernel.Stale, KernelLink: kernel.State, KernelStep: value(kernel.Stage), RunID: status.RunID, KernelJobs: kernel.LiveJobCount, KernelBuild: kernel.Build, KernelInstanceID: kernel.InstanceID} + return AgentStatus{ + Phase: &phase, Running: status.Phase != "idle", Idle: status.Phase == "idle", + KernelStale: kernel.Stale, KernelLink: kernel.State, KernelStep: value(kernel.Stage), + RunID: status.RunID, KernelJobs: kernel.LiveJobCount, RunningJobs: kernel.RunningJobs, + KernelBuild: kernel.Build, KernelInstanceID: kernel.InstanceID, + } } func (c *ChatClient) GetStatus(ctx context.Context) (*AgentStatus, error) { session, err := c.GetSession(ctx) diff --git a/cli/internal/testwire/fixtures.go b/cli/internal/testwire/fixtures.go index deac0f387..11c579d61 100644 --- a/cli/internal/testwire/fixtures.go +++ b/cli/internal/testwire/fixtures.go @@ -20,7 +20,7 @@ func Session(id, generation string, sequence int64) map[string]any { "activity": map[string]any{"lines": []any{}, "output_scalars": 0, "output_utf8_bytes": 0, "observed_at": "2026-10-03T00:00:00Z", "latest_input": nil, "latest_answer": nil}, "cursor": map[string]any{"generation": generation, "sequence": sequence}, "creation": nil, "revision": "revision-a", "family_revision": "family-a", "configuration_resource": map[string]any{"url": "/sessions/" + id + "?view=configuration", "etag": "\"revision-a\"", "value": config}, "workspace_change": nil, "selection": map[string]any{"overrides": selection, "effective": selection}, "composition": map[string]any{"desired_revision": "composition-a", "loaded_revision": nil, "needs_reload": false, "dependencies": map[string]any{}, "quarantine": []any{}, "availability": map[string]bool{}}, - "kernel": map[string]any{"state": "none", "stage": nil, "build": nil, "stale": false, "staleness_reasons": []any{}, "live_job_count": 0, "instance_id": nil}, "pending_inputs": []any{}, "input_order": 0, + "kernel": map[string]any{"state": "none", "stage": nil, "build": nil, "stale": false, "staleness_reasons": []any{}, "live_job_count": 0, "running_jobs": []any{}, "instance_id": nil}, "pending_inputs": []any{}, "input_order": 0, "usage": map[string]any{"model": nil, "observed_at": nil, "prompt_tokens": nil, "cached_prompt_tokens": nil, "cache_write_tokens": nil, "completion_tokens": nil, "total_tokens": nil, "elapsed_ms": nil, "tokens_per_second": nil, "context_window_tokens": nil, "cache_ttl_seconds": nil, "cache_fade": []any{}}, "history": map[string]any{"items": []any{}, "older": nil, "newer": nil, "high_water": 0}, "glances": []any{}, } diff --git a/cli/internal/tui/action_preview_test.go b/cli/internal/tui/action_preview_test.go index 8e5e6871c..6a4f78626 100644 --- a/cli/internal/tui/action_preview_test.go +++ b/cli/internal/tui/action_preview_test.go @@ -6,6 +6,7 @@ import ( "testing" "albedo/cli/internal/daemon" + "albedo/cli/internal/daemon/protocol" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) @@ -191,3 +192,28 @@ func TestProseTakesActionSlotWithoutForgettingOtherLiveCalls(t *testing.T) { t.Fatalf("prose forgot call A before call B's result: %q", got) } } +func TestPythonActionShowsCellSourceAndRunningJobCommand(t *testing.T) { + progress := &daemon.ToolProgress{CallID: "cell", Name: "python", Phase: "running", Code: &daemon.ToolCodePreview{Text: "# setup\n\nprint(\"hello\")"}} + if got := actionLabel(progress, nil); got != `running print("hello")` { + t.Fatalf("cell source was not summarized: %q", got) + } + if got := pythonSourceLine(&daemon.ToolCodePreview{Text: "# only comments\n \n"}); got != "" { + t.Fatalf("comment-only cell should have no summary: %q", got) + } +} + +func TestRunningPythonJobCommandAppearsInActionAndFooter(t *testing.T) { + m := newTestChatModel(t, &daemon.Session{ID: "s"}) + m.SetSize(100, 30) + m.Status.RunningJobs = []protocol.KernelJob{{ID: "j", Command: "./test.sh"}} + m.handleStreamEvent(daemon.StreamEvent{Type: daemon.EventToolProgress, + Progress: &daemon.ToolProgress{CallID: "cell", Name: "python", Phase: "running", + Code: &daemon.ToolCodePreview{Text: "job = run(\"./test.sh\")\nawait job"}}}) + m.refreshViewportContent() + if got := ansi.Strip(m.Viewport.View()); !strings.Contains(got, "running ./test.sh") { + t.Fatalf("running command missing from action: %q", got) + } + if got := m.statusLine(); got != "running" { + t.Fatalf("the status line repeats the action row: %q", got) + } +} diff --git a/cli/internal/tui/app_commands.go b/cli/internal/tui/app_commands.go index c8cfe87cc..dabef57d0 100644 --- a/cli/internal/tui/app_commands.go +++ b/cli/internal/tui/app_commands.go @@ -274,17 +274,19 @@ func (m *AppModel) executeCommandCmd(name, args string, gen int) tea.Cmd { compacted, err = daemon.CompactSession(context.Background(), conn, sessionID, strings.TrimSpace(args)) res.Message = compacted.Message() default: - command, found := daemon.SessionCommand{}, false - for _, item := range catalog { - if item.Name == name { - command, found = item, true - break - } + // A name can carry a read and a change; typed text picks the one + // that takes arguments. + index := slices.IndexFunc(catalog, func(item daemon.SessionCommand) bool { + return item.Name == name && args != "" && len(item.Arguments) > 0 + }) + if index < 0 { + index = slices.IndexFunc(catalog, func(item daemon.SessionCommand) bool { return item.Name == name }) } - if !found { + if index < 0 { err = fmt.Errorf("command %s is not in the loaded catalog", name) break } + command := catalog[index] arguments, parseErr := daemon.ParseCommandArguments(command, args) if parseErr != nil { err = parseErr diff --git a/cli/internal/tui/app_commands_test.go b/cli/internal/tui/app_commands_test.go index dfbc38d8f..20912941f 100644 --- a/cli/internal/tui/app_commands_test.go +++ b/cli/internal/tui/app_commands_test.go @@ -170,7 +170,7 @@ func TestStatusAndGlancesUseOneCapturedSessionSnapshot(t *testing.T) { t.Errorf("state polling repeated history reads: %s", r.URL) } session := protocolSession("original", generationA, 0) - session["kernel"] = map[string]any{"state": "attached", "build": "observed-build", "stale": true, "staleness_reasons": []any{map[string]any{"code": "build_changed", "detail": "A newer kernel is available."}}, "live_job_count": 3, "stage": nil, "instance_id": "observed-kernel"} + session["kernel"] = map[string]any{"state": "attached", "build": "observed-build", "stale": true, "staleness_reasons": []any{map[string]any{"code": "build_changed", "detail": "A newer kernel is available."}}, "live_job_count": 3, "running_jobs": []any{map[string]any{"id": "job1", "pid": 123, "command": "sleep 10"}}, "stage": nil, "instance_id": "observed-kernel"} session["glances"] = []any{map[string]any{"extension": "first", "title": "First", "rows": []any{}, "url": "/extensions/first/items"}, map[string]any{"extension": "second", "title": "Second", "rows": []any{}, "url": "/extensions/second/items"}} _ = json.NewEncoder(w).Encode(session) }) @@ -202,7 +202,7 @@ func TestStatusAndGlancesUseOneCapturedSessionSnapshot(t *testing.T) { phase := daemon.PhaseModel app.Chat.handleStreamEvent(daemon.StreamEvent{Type: "status", Status: &daemon.AgentStatus{Phase: &phase, Running: true}}) status := app.Chat.Status - if status.Phase == nil || *status.Phase != phase || !status.Running || status.KernelLink != "attached" || !status.KernelStale || status.KernelJobs == nil || *status.KernelJobs != 3 || status.KernelBuild == nil || *status.KernelBuild != "observed-build" || status.KernelInstanceID == nil || *status.KernelInstanceID != "observed-kernel" { + if status.Phase == nil || *status.Phase != phase || !status.Running || status.KernelLink != "attached" || !status.KernelStale || status.KernelJobs == nil || *status.KernelJobs != 3 || len(status.RunningJobs) != 1 || status.RunningJobs[0].Command != "sleep 10" || status.KernelBuild == nil || *status.KernelBuild != "observed-build" || status.KernelInstanceID == nil || *status.KernelInstanceID != "observed-kernel" { t.Fatalf("lightweight live status lost the last captured kernel observation: %+v", status) } } diff --git a/cli/internal/tui/chat.go b/cli/internal/tui/chat.go index 26d4246db..f325f4c0f 100644 --- a/cli/internal/tui/chat.go +++ b/cli/internal/tui/chat.go @@ -316,8 +316,8 @@ func (m ChatModel) update(msg tea.Msg) (ChatModel, tea.Cmd) { return m, nil } if msg.Err == nil && msg.Status != nil && msg.Revision == m.statusRevision { - m.Status = *msg.Status previousChrome := m.chromeRows() + m.Status = *msg.Status m.Glances = msg.Glances if m.chromeRows() != previousChrome { m.syncViewportHeight() diff --git a/cli/internal/tui/chat_footer.go b/cli/internal/tui/chat_footer.go index ccf0193a4..c0a0545b6 100644 --- a/cli/internal/tui/chat_footer.go +++ b/cli/internal/tui/chat_footer.go @@ -12,17 +12,46 @@ import ( "github.com/charmbracelet/x/ansi" ) -// glanceCounts counts each glance with rows that the sidebar leaves out: all -// of them without a sidebar, the ones after its first with one. -func (m ChatModel) glanceCounts() []string { - var counts []string +func (m ChatModel) backgroundJobCount() int64 { + if m.Status.KernelJobs == nil { + return 0 + } + return *m.Status.KernelJobs +} + +// activeGlances lists the sidebar's sections in order, leaving out empty ones: +// the extensions' glances (active work), then background jobs. +func (m ChatModel) activeGlances() []PageGlance { + var glances []PageGlance for _, g := range m.Glances { if len(g.Rows) > 0 { - counts = append(counts, fmt.Sprintf("%s %d", g.Title, len(g.Rows))) + glances = append(glances, g) } } - if len(counts) > 0 && m.sidebarWidth() > 0 { - counts = counts[1:] + if len(m.Status.RunningJobs) == 0 { + return glances + } + rows := make([]PageRow, 0, len(m.Status.RunningJobs)) + for _, job := range m.Status.RunningJobs { + command := oneLine(job.Command) + if command == "" { + command = "job " + job.ID + } + rows = append(rows, PageRow{Text: command, Tone: ToneActive}) + } + return append(glances, PageGlance{Title: "background jobs", Rows: rows}) +} + +// glanceCounts counts each glance the sidebar leaves out: all of them without +// a sidebar, the ones that did not fit its height with one. +func (m ChatModel) glanceCounts() []string { + omitted := m.activeGlances() + if m.sidebarWidth() > 0 { + _, omitted = m.sidebarRows() + } + var counts []string + for _, g := range omitted { + counts = append(counts, fmt.Sprintf("%s %d", g.Title, len(g.Rows))) } if m.Status.KernelStale { counts = append([]string{"kernel older"}, counts...) @@ -31,38 +60,60 @@ func (m ChatModel) glanceCounts() []string { } func (m ChatModel) renderGlances() string { - for _, g := range m.Glances { - if len(g.Rows) == 0 { + rows, _ := m.sidebarRows() + return lipgloss.NewStyle().Width(m.sidebarWidth()).Render(strings.Join(rows, "\n")) +} + +// sidebarRows stacks the glances, a blank row apart and at most 12 rows each, +// within the viewport's height. A glance with no room for its title and one +// row is returned as omitted. +func (m ChatModel) sidebarRows() ([]string, []PageGlance) { + var rows []string + var omitted []PageGlance + room := m.Viewport.Height() + for _, g := range m.activeGlances() { + gap := min(1, len(rows)) + limit := min(room-gap, 12) + if limit < 2 { + omitted = append(omitted, g) continue } - room := max(0, min(m.Viewport.Height(), 12)-1) - shown := min(room, len(g.Rows)) - if len(g.Rows) > room { - shown = max(0, room-1) - } - rows := []string{m.Styles.Faint.Render(fmt.Sprintf("%s · %d", g.Title, len(g.Rows)))} - for _, item := range g.Rows[:shown] { - mark, style := "○", m.Styles.Faint - switch item.Tone { - case ToneActive: - mark, style = "●", m.Styles.Success - case ToneWarning: - mark, style = "!", m.Styles.Warning - case ToneMuted: - mark = "✓" - } - label := item.Text - if item.ID != "" { - label = "#" + item.ID + " " + item.Text - } - rows = append(rows, style.Render(mark)+" "+label) + section := m.glanceRows(g, limit) + rows = append(rows, make([]string, gap)...) + rows = append(rows, section...) + room -= gap + len(section) + } + return rows, omitted +} + +// glanceRows renders a glance's title and rows in at most limit rows, one +// line per row. +func (m ChatModel) glanceRows(g PageGlance, limit int) []string { + shown := min(limit-1, len(g.Rows)) + if len(g.Rows) > shown { + shown = limit - 2 + } + rows := []string{m.Styles.Faint.Render(fmt.Sprintf("%s · %d", g.Title, len(g.Rows)))} + for _, item := range g.Rows[:shown] { + mark, style := "○", m.Styles.Faint + switch item.Tone { + case ToneActive: + mark, style = "●", m.Styles.Success + case ToneWarning: + mark, style = "!", m.Styles.Warning + case ToneMuted: + mark = "✓" } - if shown < len(g.Rows) { - rows = append(rows, m.Styles.Faint.Render(fmt.Sprintf("+%d more", len(g.Rows)-shown))) + label := item.Text + if item.ID != "" { + label = "#" + item.ID + " " + item.Text } - return lipgloss.NewStyle().Width(m.sidebarWidth()).Render(strings.Join(rows, "\n")) + rows = append(rows, style.Render(mark)+" "+ansi.Truncate(label, max(1, m.sidebarWidth()-2), "…")) + } + if shown < len(g.Rows) { + rows = append(rows, m.Styles.Faint.Render(fmt.Sprintf("+%d more", len(g.Rows)-shown))) } - return "" + return rows } func (m ChatModel) renderFooter() string { diff --git a/cli/internal/tui/chat_input.go b/cli/internal/tui/chat_input.go index 069d09469..61201168e 100644 --- a/cli/internal/tui/chat_input.go +++ b/cli/internal/tui/chat_input.go @@ -267,15 +267,19 @@ func (m *ChatModel) isRecognizedCommand(input string) bool { if !strings.HasPrefix(trimmed, "/") { return false } - token := strings.Fields(trimmed)[0] + fields := strings.Fields(trimmed) + token, typed := fields[0], len(fields) > 1 switch token { case "/a", "/agents", "/sessions", "/q", "/quit", "/exit", "/new", "/model", "/extensions", "/plugins", "/tree", "/context", "/t", "/thinking", "/v", "/verbose", - "/status", "/login", "/mouse", "/skills", "/instructions", "/mcp", "/cd", "/effort", "/compact", "/kernel", "/reload": + "/status", "/login", "/mouse", "/skills", "/instructions", "/mcp", "/cd", "/effort", "/compact", "/kernel", "/reload", + "/work", "/paperclips": return true } + // Text after a command that declares no arguments is a prompt that + // happens to start with the command's name. return slices.ContainsFunc(m.CommandMenu.Catalog, func(cmd daemon.SessionCommand) bool { - return cmd.Name == token + return cmd.Name == token && (!typed || len(cmd.Arguments) > 0) }) } diff --git a/cli/internal/tui/chat_stream.go b/cli/internal/tui/chat_stream.go index 7056dcdee..098268e24 100644 --- a/cli/internal/tui/chat_stream.go +++ b/cli/internal/tui/chat_stream.go @@ -28,11 +28,30 @@ func (m ChatModel) toolLabel() string { return "" } if progress := m.latestProgress(); progress != nil { - return actionLabel(progress, nil) + return m.liveActionLabel(progress) } return m.settledToolLabel } +func (m ChatModel) liveActionLabel(progress *daemon.ToolProgress) string { + if progress.Name == "python" && progress.Phase == "running" { + if command := m.runningJobCommand(); command != "" { + return "running " + command + } + } + return actionLabel(progress, nil) +} + +// runningJobCommand is the first live job's command, folded onto one row. +func (m ChatModel) runningJobCommand() string { + for _, job := range m.Status.RunningJobs { + if command := oneLine(job.Command); command != "" { + return command + } + } + return "" +} + func (m *ChatModel) rememberProgress(progress *daemon.ToolProgress) { if m.progressByCallID == nil { m.progressByCallID = make(map[string]*daemon.ToolProgress) diff --git a/cli/internal/tui/chat_subscription.go b/cli/internal/tui/chat_subscription.go index 160d14ecb..04004e85a 100644 --- a/cli/internal/tui/chat_subscription.go +++ b/cli/internal/tui/chat_subscription.go @@ -9,7 +9,7 @@ import ( ) func (m ChatModel) animating() bool { - return m.isSending || m.pendingSendCount() > 0 || m.Stopping || m.latestProgress() != nil || m.Status.Running && !m.Status.Idle || m.reaching() != "" + return m.isSending || m.pendingSendCount() > 0 || m.Stopping || m.latestProgress() != nil || m.Status.Running && !m.Status.Idle || m.reaching() != "" || m.backgroundJobCount() > 0 } func (m *ChatModel) startAnimation() tea.Cmd { diff --git a/cli/internal/tui/chat_view.go b/cli/internal/tui/chat_view.go index 650f485a2..67eaeaffb 100644 --- a/cli/internal/tui/chat_view.go +++ b/cli/internal/tui/chat_view.go @@ -48,16 +48,11 @@ func (m ChatModel) padding() int { func (m ChatModel) chatWidth() int { return max(1, m.Width-2*m.padding()) } func (m ChatModel) sidebarWidth() int { - for _, glance := range m.Glances { - if len(glance.Rows) > 0 { - margin := m.chatWidth() - min(100, m.chatWidth()) - 2 - if margin >= 16 { - return min(32, margin) - } - break - } + margin := m.chatWidth() - min(100, m.chatWidth()) - 2 + if margin < 16 || len(m.activeGlances()) == 0 { + return 0 } - return 0 + return min(32, margin) } // actionLabel is the action row for a call, live from its progress and then @@ -69,10 +64,28 @@ func actionLabel(progress *daemon.ToolProgress, result *HistoryEntry) string { return head + tail case progress.Phase == "generating": return "generating " + progress.Name + case progress.Name == "python": + if line := pythonSourceLine(progress.Code); line != "" { + return "running " + line + } } return "running " + progress.Name } +// pythonSourceLine returns the first useful source line from a cell preview. +func pythonSourceLine(preview *daemon.ToolCodePreview) string { + if preview == nil { + return "" + } + for _, line := range strings.Split(preview.Text, "\n") { + line = strings.TrimSpace(line) + if line != "" && !strings.HasPrefix(line, "#") { + return line + } + } + return "" +} + // renderProgress holds the last tool action in one row; a call still being // generated also shows the newest end of its code. func (m ChatModel) renderProgress() string { @@ -127,7 +140,8 @@ func (m ChatModel) statusLine() string { if progress.Phase == "generating" { return "generating call" } - return "running " + progress.Name + // the action row above already names what runs + return "running" } if m.Status.Running && !m.Status.Idle { if m.transcript.activeKind == StreamKindText { @@ -148,6 +162,16 @@ func (m ChatModel) statusLine() string { if m.connecting() { return "connecting…" } + if count := m.backgroundJobCount(); count > 0 { + label := "1 background job running" + if count > 1 { + label = fmt.Sprintf("%d background jobs running", count) + } + if command := m.runningJobCommand(); command != "" { + label += " · " + command + } + return label + } if m.Flags.Tools { return "ready" } @@ -168,7 +192,7 @@ func (m ChatModel) phaseMood() mood { return moodConnecting case m.isSending || m.pendingSendCount() > 0 && !m.Status.Running: return moodPreparing - case m.latestProgress() != nil: + case m.latestProgress() != nil || m.Status.Idle && m.backgroundJobCount() > 0: return moodWorking case m.transcript.activeKind == StreamKindText: return moodResponding @@ -302,13 +326,17 @@ func (m ChatModel) View() string { content = HighlightSelection(content, Selection{Anchor: anchor, Head: head, Gutter: railWidth}) } rows = append(rows, content...) - status := m.statusLine() + // one row: a job's command may span lines + status := oneLine(m.statusLine()) // the face trails the text, so its frames never move anything if m.animating() && !m.TurnFailed && !m.Notices.HasError() { face := m.phaseMood().frame(m.moodSeed, m.ProgressFrame) if host := m.reaching(); host != "" { face = connectingFace(host, m.ProgressFrame) // the picker's face for this host } + if m.Width > 0 { + status = ansi.Truncate(status, max(1, m.chatWidth()-ansi.StringWidth(face)-1), "…") + } status = m.Styles.Faint.Render(status) + " " + m.Styles.Agent.Render(face) } if !m.Follow { diff --git a/cli/internal/tui/glance_test.go b/cli/internal/tui/glance_test.go index ea8203f9b..99d1232a4 100644 --- a/cli/internal/tui/glance_test.go +++ b/cli/internal/tui/glance_test.go @@ -1,12 +1,18 @@ // Transcript re-rendering on width changes, not height changes, prevents // expensive UI refreshes. The cost is invisible outside the process: the // rendered text is identical either way, so no e2e can catch a regression. +// The sidebar's stacking is checked here too: a daemon run would need a live +// job and an active work item at once to show both sections. package tui import ( + "strings" "testing" "albedo/cli/internal/daemon" + "albedo/cli/internal/daemon/protocol" + + "github.com/charmbracelet/x/ansi" ) func TestResizeRendersTranscriptOnlyForNewBodyWidth(t *testing.T) { @@ -26,3 +32,35 @@ func TestResizeRendersTranscriptOnlyForNewBodyWidth(t *testing.T) { t.Fatal("a narrower body should render the transcript again") } } + +func TestSidebarStacksActiveWorkAboveBackgroundJobs(t *testing.T) { + m := newTestChatModel(t, &daemon.Session{ID: "s"}) + m.Glances = []PageGlance{{Title: "active work", Rows: []PageRow{{ID: "7", Text: "fix the parser", Tone: ToneActive}}}} + m.Status.RunningJobs = []protocol.KernelJob{{ID: "job1", Command: "go test ./..."}, {ID: "job2", Command: "python3 -c '\nimport os\nprint(1)\n'"}} + m.SetSize(160, 30) + view := ansi.Strip(m.View()) + work, jobs := strings.Index(view, "active work"), strings.Index(view, "background jobs") + if work < 0 || jobs < work || !strings.Contains(view, "fix the parser") || !strings.Contains(view, "go test ./...") { + t.Fatalf("the sidebar must show active work, then background jobs:\n%s", view) + } + if strings.Contains(view, "job1") { + t.Fatalf("a background job shows its command, not its id:\n%s", view) + } + if counts := m.glanceCounts(); len(counts) != 0 { + t.Fatalf("the footer repeats sections the sidebar shows: %v", counts) + } + if !strings.Contains(view, "python3 -c ' import os") { + t.Fatalf("a multi-line command must fold onto its row:\n%s", view) + } + m.Glances, m.Status.RunningJobs = nil, m.Status.RunningJobs[1:] + m.Status.KernelJobs = new(int64(1)) + m.SetSize(60, 20) + for line := range strings.SplitSeq(ansi.Strip(m.View()), "\n") { + if strings.Contains(line, "import os") && !strings.Contains(line, "background job running") { + t.Fatalf("the status line wrapped a job's command:\n%s", ansi.Strip(m.View())) + } + if ansi.StringWidth(line) > 60 { + t.Fatalf("a %d-cell line at width 60: %q", ansi.StringWidth(line), line) + } + } +} diff --git a/cli/internal/tui/header_test.go b/cli/internal/tui/header_test.go index 049278075..323799c25 100644 --- a/cli/internal/tui/header_test.go +++ b/cli/internal/tui/header_test.go @@ -9,6 +9,7 @@ import ( "testing" "albedo/cli/internal/daemon" + "albedo/cli/internal/daemon/protocol" "github.com/charmbracelet/x/ansi" ) @@ -100,3 +101,83 @@ func TestRemoteHeaderFoldsUnderTheHostsHomeAndSaysWhileConnecting(t *testing.T) t.Fatalf("a lost kernel reads %q", got) } } + +func TestBackgroundJobsRenderInHeaderStatusAndSidebar(t *testing.T) { + m := newTestChatModel(t, &daemon.Session{ID: "s"}) + m.AgentName, m.Workspace, m.Model = "albedo", "/src/proj/albedo", "claude-opus-4-6" + m.Status = daemon.AgentStatus{ + Idle: true, + KernelJobs: new(int64(1)), + RunningJobs: []protocol.KernelJob{ + {ID: "job1", Command: "go test ./..."}, + }, + } + + if got := m.statusLine(); got != "1 background job running · go test ./..." { + t.Fatalf("expected statusLine to show 1 running job, got %q", got) + } + if !m.animating() { + t.Fatalf("expected model to animate when background jobs are running") + } + + header := ansi.Strip(m.header(120)) + if !strings.Contains(header, "background jobs 1") { + t.Fatalf("expected header to count running jobs glance, got %q", header) + } + + m.Glances = []PageGlance{{Title: "open vents", Rows: []PageRow{{ID: "v1", Text: "a vent"}}}} + m.SetSize(140, 30) + view := ansi.Strip(m.View()) + if !strings.Contains(view, "background jobs") || !strings.Contains(view, "go test ./...") { + t.Fatalf("expected sidebar to show running background job, got:\n%s", view) + } + + if len(m.Glances) != 1 || m.Glances[0].Title != "open vents" { + t.Fatal("rendering jobs changed extension glances") + } + for width := 1; width <= 140; width++ { + m.SetSize(width, 30) + if got := ansi.StringWidth(m.header(width)); got > width { + t.Fatalf("job header at width %d exceeds its bounds: %d", width, got) + } + } + m.Glances = nil + m.Status.KernelJobs = nil + m.Status.RunningJobs = nil + if m.animating() || m.statusLine() != "" || len(m.activeGlances()) != 0 { + t.Fatal("unknown jobs must not claim that background work is running") + } + + m.Status.KernelJobs = new(int64(2)) + m.Status.RunningJobs = []protocol.KernelJob{ + {ID: "job1", Command: "sleep 10"}, + {ID: "job2", Command: "cargo build"}, + } + if got := m.statusLine(); got != "2 background jobs running · sleep 10" { + t.Fatalf("expected statusLine to show 2 running jobs, got %q", got) + } + + m.Status.KernelJobs = new(int64(0)) + m.Status.RunningJobs = nil + if got := m.statusLine(); got != "" { + t.Fatalf("expected empty statusLine when idle with no jobs, got %q", got) + } +} + +func TestBackgroundJobsRefreshWithoutStartingATurn(t *testing.T) { + m := newTestChatModel(t, &daemon.Session{ID: "s"}) + m.SetSize(80, 30) + status := daemon.AgentStatus{Idle: true, KernelJobs: new(int64(1)), + RunningJobs: []protocol.KernelJob{{ID: "j", Command: "sleep 10"}}} + m, cmd := m.Update(ChatStatusMsg{SessionID: m.SessionID, Generation: m.Generation, + Revision: m.statusRevision, Status: &status}) + if !m.animating() || cmd == nil || !strings.Contains(m.statusLine(), "sleep 10") { + t.Fatal("idle background job did not start its status animation") + } + status.KernelJobs, status.RunningJobs = new(int64(0)), nil + m, _ = m.Update(ChatStatusMsg{SessionID: m.SessionID, Generation: m.Generation, + Revision: m.statusRevision, Status: &status}) + if m.animating() || m.statusLine() != "" || len(m.activeGlances()) != 0 { + t.Fatal("finished jobs left idle job chrome behind") + } +} diff --git a/cli/internal/tui/session_viewer.go b/cli/internal/tui/session_viewer.go index 1f8a17ef1..fa2ef67fb 100644 --- a/cli/internal/tui/session_viewer.go +++ b/cli/internal/tui/session_viewer.go @@ -223,7 +223,9 @@ func (m *SessionViewer) rebuild() { slices.SortStableFunc(frequent, func(a, b daemon.Session) int { return cmp.Compare(m.prefs.Opens[b.ID], m.prefs.Opens[a.ID]) }) - for _, s := range frequent[:min(len(frequent), frequentLimit)] { + frequent = frequent[:min(len(frequent), frequentLimit)] + slices.SortStableFunc(frequent, byLoaded) + for _, s := range frequent { m.section[s.ID] = secFrequent ordered = append(ordered, s) } @@ -255,8 +257,11 @@ func (m *SessionViewer) rebuild() { } rest = append(rest, s) } - // Navigation follows the grouping; the daemon's order holds within a day group. - slices.SortStableFunc(rest, func(a, b daemon.Session) int { return cmp.Compare(m.section[a.ID], m.section[b.ID]) }) + // Navigation follows the grouping. Within a group loaded sessions lead the + // reaped ones, and the daemon's order holds otherwise. + slices.SortStableFunc(rest, func(a, b daemon.Session) int { + return cmp.Or(cmp.Compare(m.section[a.ID], m.section[b.ID]), byLoaded(a, b)) + }) m.Sessions = slices.Concat(ordered, active, rest) var items []PickerItem @@ -296,6 +301,21 @@ func (m *SessionViewer) rebuildGroups() { } } +// loaded reports whether the daemon holds the session live, not yet reaped +// for idleness; only a live session has a stream cursor. +func loaded(s daemon.Session) bool { return s.Cursor != nil } + +// byLoaded orders loaded sessions before reaped ones. +func byLoaded(a, b daemon.Session) int { + switch { + case loaded(a) == loaded(b): + return 0 + case loaded(a): + return -1 + } + return 1 +} + const untitled = "Untitled session" func sessionTitle(s daemon.Session) string { diff --git a/cli/internal/tui/session_viewer_test.go b/cli/internal/tui/session_viewer_test.go index dc7f30395..92cb9abb3 100644 --- a/cli/internal/tui/session_viewer_test.go +++ b/cli/internal/tui/session_viewer_test.go @@ -7,7 +7,9 @@ // - preview timing: a debounce, a stale tick for a row no longer // highlighted, and the cache stamp that decides when a new reply // invalidates a preview are race-dependent state a scripted scenario -// reaches only flakily. +// reaches only flakily; +// - grouping: within a group, sessions the daemon still holds lead the +// reaped ones. package tui import ( @@ -47,6 +49,22 @@ func TestSessionViewerResponsiveViewport(t *testing.T) { } } +func TestSessionViewerPutsLoadedSessionsAboveReapedOnes(t *testing.T) { + now := time.Date(2026, 9, 23, 12, 0, 0, 0, time.Local) + newer, older := now.Add(-time.Minute).Unix(), now.Add(-time.Hour).Unix() + m := viewerAt(now) + m.SetSize(120, 30) + // the daemon lists by activity; the reaped session replied last + m.SetSessions([]daemon.Session{ + {ID: "reaped", Title: "Reaped session", LastAssistantAt: &newer}, + {ID: "live", Title: "Loaded session", LastAssistantAt: &older, Cursor: &daemon.Cursor{}}, + }, nil) + view := ansi.Strip(m.View()) + if live, reaped := strings.Index(view, "Loaded session"), strings.Index(view, "Reaped session"); live < 0 || reaped < live { + t.Fatalf("a loaded session must lead the reaped ones in its group:\n%s", view) + } +} + func viewerAt(now time.Time) SessionViewer { m := NewSessionViewer("/work/current") m.now = func() time.Time { return now } diff --git a/cli/internal/tui/session_viewer_view.go b/cli/internal/tui/session_viewer_view.go index a3af8b995..37f87c517 100644 --- a/cli/internal/tui/session_viewer_view.go +++ b/cli/internal/tui/session_viewer_view.go @@ -393,7 +393,6 @@ func (m SessionViewer) row(item PickerItem, s daemon.Session, sec int, selected st(DefaultStyles.Faint).Render(svCell(" "+hint, max(0, width-4-titleWidth), false))) } - recent := s.LastAssistantAt != nil && now.Sub(time.Unix(*s.LastAssistantAt, 0)) < time.Hour glyph, iconStyle := "· ", DefaultStyles.Faint switch { case editing: @@ -402,7 +401,7 @@ func (m SessionViewer) row(item PickerItem, s daemon.Session, sec int, selected glyph, iconStyle = "◆ ", DefaultStyles.Agent case sec == secPinned: glyph, iconStyle = "★ ", DefaultStyles.Agent - case recent: + case loaded(s): glyph, iconStyle = "● ", DefaultStyles.Success } gap := st(lipgloss.NewStyle()).Render(" ") @@ -427,7 +426,7 @@ func (m SessionViewer) row(item PickerItem, s daemon.Session, sec int, selected } if cols.age > 0 { as := DefaultStyles.Faint - if recent { + if loaded(s) { as = DefaultStyles.Success } line += gap + st(as).Render(svCell(svCompactAge(s.LastAssistantAt, now), cols.age, true)) diff --git a/cli/test/e2e/tui_flow_test.go b/cli/test/e2e/tui_flow_test.go index c7aeea616..73296c513 100644 --- a/cli/test/e2e/tui_flow_test.go +++ b/cli/test/e2e/tui_flow_test.go @@ -5,6 +5,7 @@ package e2e import ( + "slices" "strings" "testing" @@ -96,6 +97,42 @@ func TestTUIEffortSelectorCommitsThroughTheDaemon(t *testing.T) { } } +// Text after a command that declares no arguments is a prompt that starts with +// the command's name; the command would only reject it. +func TestTUISendsTextAfterAnArgumentlessCommandAsAPrompt(t *testing.T) { + profile := providerRoute(t, echoReply) + session := daemonSession(t, newSession(t, t.TempDir())) + // A session lists its commands once its first turn has loaded them. + if _, err := daemon.NewChatClient(conn(t), session.ID).Send(t.Context(), "hello", nil); err != nil { + t.Fatal(err) + } + waitIdle(t, session.ID, profile, 1) + d := driveTUI(t, &session) + defer d.App.Chat.Close() + d.Dispatch(tui.CapabilityPageChangedMsg{}) + jobs := slices.IndexFunc(d.App.Chat.CommandMenu.Catalog, func(command daemon.SessionCommand) bool { return command.Name == "/jobs" }) + if jobs < 0 || len(d.App.Chat.CommandMenu.Catalog[jobs].Arguments) != 0 { + t.Fatalf("the daemon's catalog has no argumentless /jobs: %+v", d.App.Chat.CommandMenu.Catalog) + } + d.connected() + + d.App.Chat.TextArea.SetValue("/jobs is broken") + var admitted tui.ChatTurnSentMsg + for _, message := range d.results(d.Update(tea.KeyPressMsg{Code: tea.KeyEnter})) { + if sent, ok := message.(tui.ChatTurnSentMsg); ok { + admitted = sent + d.Update(sent) + } + } + if admitted.Err != nil || !admitted.OK { + t.Fatalf("enter did not send the prompt: %+v\n%s", admitted, d.View()) + } + waitIdle(t, session.ID, profile, 2) + if reply := strings.Join(eventText(durableHistorySnapshot(t, session.ID), "message"), "\n"); !strings.Contains(reply, "echo: /jobs is broken") { + t.Fatalf("the model did not receive the whole prompt; got:\n%s", reply) + } +} + func TestTUIExtensionPickerSwitchesCompactionStrategies(t *testing.T) { profile := providerRoute(t, echoReply) session := daemonSession(t, newSession(t, t.TempDir())) diff --git a/cli/test/e2e/tui_sessions_test.go b/cli/test/e2e/tui_sessions_test.go index 89e8c3113..4b934143b 100644 --- a/cli/test/e2e/tui_sessions_test.go +++ b/cli/test/e2e/tui_sessions_test.go @@ -65,6 +65,45 @@ func TestTUISessionPickerPinsRenamesArchivesAndDeletes(t *testing.T) { } } +// The session list carries no validators, so archiving a row whose preview +// never loaded still has to reach the daemon. +func TestTUIArchivesASessionStraightFromTheList(t *testing.T) { + t.Parallel() + providerRoute(t, echoReply) + d := newTUIDriver(t) + target := newSession(t, t.TempDir()) + d.Dispatch(tui.ChatBackToSessionsMsg{}) + i := slices.IndexFunc(d.App.SessionPicker.Filtered, func(it tui.PickerItem) bool { return it.ID == target }) + if i < 0 { + t.Fatalf("the picker does not list %s:\n%s", target, d.View()) + } + d.App.SessionPicker.Cursor = i + d.Dispatch(tea.KeyPressMsg{Code: 'a', Mod: tea.ModCtrl}) + if saved := daemonSession(t, target); !saved.Archived { + t.Fatalf("ctrl+a did not archive the listed session:\n%s", d.View()) + } +} + +// A long message reaches a preview as a content reference; the session list +// and agents view read it in full instead of failing the preview. +func TestSessionPreviewReadsLongMessagesInFull(t *testing.T) { + t.Parallel() + profile := providerRoute(t, echoReply) + id := newSession(t, t.TempDir()) + long := strings.Repeat("long preview line ", 12000) + if _, err := daemon.NewChatClient(conn(t), id).Send(t.Context(), long, nil); err != nil { + t.Fatal(err) + } + waitIdle(t, id, profile, 1) + preview, err := daemon.GetSessionPreview(t.Context(), conn(t), id, 16) + if err != nil { + t.Fatalf("the preview failed: %v", err) + } + if !slices.ContainsFunc(preview.Items, func(item daemon.PreviewItem) bool { return item.Preview == "echo: "+long }) { + t.Fatalf("the long reply is missing from the preview: %d items", len(preview.Items)) + } +} + func TestTUINavigationRetainsPendingTurnsAndContinuation(t *testing.T) { entered, release := make(chan struct{}), make(chan struct{}) released := false diff --git a/docs/http-api-design.md b/docs/http-api-design.md index b1f639a30..6982ff2fa 100644 --- a/docs/http-api-design.md +++ b/docs/http-api-design.md @@ -512,8 +512,12 @@ bounded activity once, before subscriber fan-out. Full content stays in history. - `selection`, containing session overrides and effective selections. - `composition`, containing desired and loaded revisions, `needs_reload`, dependencies, quarantine diagnostics, and capability availability. -- `kernel`, containing state, build identity, staleness reasons, and live-job - count. No Python variables or process handles leave the daemon. +- `kernel`, containing state, build identity, staleness reasons, live-job + count, and up to 100 running-job summaries ordered by ID. Each summary names + the job, its observed PID (nullable), and its command (at most 4096 scalars). + Unknown counts and lists are null; known empty lists are `[]`. The count can + exceed the bounded list. Reads observe the kernel without preparing it. + No Python variables or executable process handles leave the daemon. - `pending_inputs`, at most 32 bounded input summaries with acceptance order, and `input_order`, the greatest order ever accepted into this session. - `usage`, including token and cache counters, elapsed time, model limits, diff --git a/docs/openapi.yaml b/docs/openapi.yaml index ff43d0c78..10e57dab2 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -559,6 +559,7 @@ paths: stale: false staleness_reasons: [] live_job_count: 0 + running_jobs: [] pending_inputs: [] input_order: 0 usage: @@ -760,6 +761,7 @@ paths: stale: false staleness_reasons: [] live_job_count: 0 + running_jobs: [] pending_inputs: [] input_order: 0 usage: @@ -3617,6 +3619,81 @@ paths: content: Hello stream: true description: UTF-8 JSON; duplicate keys and unknown fields are rejected. + /extensions/run/sessions/{session_id}/jobs: + get: + operationId: listJobs + summary: Read bounded live job observations and the jobs page + parameters: + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + responses: + '200': + description: Known live jobs, with up to 100 summaries ordered by ID. + content: + application/json: + schema: + $ref: '#/components/schemas/JobCollection' + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '404': + $ref: '#/components/responses/Problem404' + '405': + $ref: '#/components/responses/Problem405' + '406': + $ref: '#/components/responses/Problem406' + '503': + $ref: '#/components/responses/Problem503' + /extensions/run/sessions/{session_id}/jobs/{job_id}/stop: + post: + operationId: stopJob + summary: Explicitly stop one observed process group + description: No automatic retry after response loss. Read the job collection before confirming another attempt. A successful response confirms the supervisor verdict, not just signal delivery. + parameters: + - name: session_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + - name: job_id + in: path + required: true + schema: + $ref: '#/components/schemas/ID' + responses: + '200': + description: The observed job's process group was stopped. + content: + application/json: + schema: + $ref: '#/components/schemas/JobStop' + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '404': + $ref: '#/components/responses/Problem404' + '405': + $ref: '#/components/responses/Problem405' + '406': + $ref: '#/components/responses/Problem406' + '413': + $ref: '#/components/responses/Problem413' + '415': + $ref: '#/components/responses/Problem415' + '503': + $ref: '#/components/responses/Problem503' + requestBody: + required: false + content: + application/json: + schema: + type: object + additionalProperties: false components: securitySchemes: DaemonBearer: @@ -5830,6 +5907,53 @@ components: type: boolean required: [desired_revision, loaded_revision, needs_reload, dependencies, quarantine, availability] additionalProperties: false + JobCollection: + type: object + properties: + items: + type: array + items: + $ref: '#/components/schemas/KernelJob' + maxItems: 100 + live_job_count: + $ref: '#/components/schemas/Counter' + page: + $ref: '#/components/schemas/PageDescriptor' + required: [items, live_job_count, page] + additionalProperties: false + examples: + - items: [] + live_job_count: 0 + page: + title: jobs + empty_state: no background jobs running + rows: [] + glance: null + actions: [] + summary: 0 background jobs running + JobStop: + type: object + properties: + stopped: + $ref: '#/components/schemas/ID' + required: [stopped] + additionalProperties: false + examples: + - stopped: job-1 + KernelJob: + type: object + properties: + id: + $ref: '#/components/schemas/ID' + pid: + anyOf: + - $ref: '#/components/schemas/Counter' + - type: 'null' + command: + type: string + maxLength: 4096 + required: [id, pid, command] + additionalProperties: false Kernel: type: object properties: @@ -5853,6 +5977,14 @@ components: items: $ref: '#/components/schemas/SafeReason' maxItems: 100 + running_jobs: + description: Up to 100 observed live jobs, ordered by ID. Null when the kernel owner is unavailable. The count may exceed this list. + anyOf: + - type: array + items: + $ref: '#/components/schemas/KernelJob' + maxItems: 100 + - type: 'null' live_job_count: description: Observed owned jobs. Null while booting or when the kernel owner is lost. anyOf: @@ -5862,7 +5994,7 @@ components: anyOf: - $ref: '#/components/schemas/ID' - type: 'null' - required: [state, stage, build, stale, staleness_reasons, live_job_count, instance_id] + required: [state, stage, build, stale, staleness_reasons, live_job_count, running_jobs, instance_id] additionalProperties: false Usage: type: object @@ -6126,6 +6258,7 @@ components: stale: false staleness_reasons: [] live_job_count: 0 + running_jobs: [] pending_inputs: [] input_order: 0 usage: @@ -8959,6 +9092,7 @@ components: stale: false staleness_reasons: [] live_job_count: 0 + running_jobs: [] pending_inputs: [] input_order: 0 usage: @@ -9182,7 +9316,7 @@ components: examples: - data: '{"generation":"J6kYj6IGcXyP3eMIp-WL3A","cursor":0,"events":[{"type":"reset","data":{"reason":"initial"}}],"snapshot":{"id":"01a0fcea-2b00-7000-8000-000000000001","name":"New session","automatic_name":"New session","workspace":"/workspace/project","location":{"host":null,"user":null,"path":"/workspace/project","label":null},"parent_id":null,"root_id":"01a0fcea-2b00-7000-8000-000000000001","address":null,"depth":0,"closed":false,"created_at":"2026-10-02T14:00:00Z","activity_at":"2026-10-02T14:00:00Z","provider_profile":"personal","model":"example-model","effort":null,"status":{"phase":"idle","run_id":null,"interrupt_requested":false,"blocking_reason":null},"preview":{"text":"","transcript_count":0,"truncated":false},"preferences":{"pinned":false,"pin_order":null,"archived":false,"opens":0},"current_progress":[],"activity":{"lines":[],"output_scalars":0,"output_utf8_bytes":0,"observed_at":"2026-10-02T14:00:00Z","latest_input":null,"latest_answer":null},"cursor":{"generation":"J6kYj6IGcXyP3eMIp-WL3A","sequence":0},"creation":{"submitted":{"kind":"new","workspace":"/workspace/project","name":null,"provider_profile":null,"model":null,"effort":null},"resolved":{"workspace":"/workspace/project","provider_profile":"personal","model":"example-model","effort":null}},"revision":"config-1","family_revision":"family-1","configuration_resource":{"url":"/sessions/01a0fcea-2b00-7000-8000-000000000001?view=configuration","etag":"\"session-config-1\"","value":{"id":"01a0fcea-2b00-7000-8000-000000000001","name":"New - session","workspace":"/workspace/project","provider_profile":"personal","model":"example-model","effort":null,"preferences":{"pinned":false,"pin_order":null,"archived":false},"selection":{"extensions":{},"skills":{},"instructions":{},"mcp":{}},"revision":"config-1","family_revision":"family-1"}},"workspace_change":null,"selection":{"overrides":{"extensions":{},"skills":{},"instructions":{},"mcp":{}},"effective":{"extensions":{},"skills":{},"instructions":{},"mcp":{}}},"composition":{"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"dependencies":{},"quarantine":[],"availability":{}},"kernel":{"instance_id":null,"state":"none","stage":null,"build":null,"stale":false,"staleness_reasons":[],"live_job_count":0},"pending_inputs":[],"input_order":0,"usage":{"model":null,"observed_at":null,"prompt_tokens":null,"cached_prompt_tokens":null,"cache_write_tokens":null,"completion_tokens":null,"total_tokens":null,"elapsed_ms":null,"tokens_per_second":null,"context_window_tokens":null,"cache_ttl_seconds":null,"cache_fade":[]},"history":{"items":[],"older":null,"newer":null,"high_water":0},"glances":[]}}' + session","workspace":"/workspace/project","provider_profile":"personal","model":"example-model","effort":null,"preferences":{"pinned":false,"pin_order":null,"archived":false},"selection":{"extensions":{},"skills":{},"instructions":{},"mcp":{}},"revision":"config-1","family_revision":"family-1"}},"workspace_change":null,"selection":{"overrides":{"extensions":{},"skills":{},"instructions":{},"mcp":{}},"effective":{"extensions":{},"skills":{},"instructions":{},"mcp":{}}},"composition":{"desired_revision":"composition-1","loaded_revision":null,"needs_reload":true,"dependencies":{},"quarantine":[],"availability":{}},"kernel":{"instance_id":null,"state":"none","stage":null,"build":null,"stale":false,"staleness_reasons":[],"live_job_count":0,"running_jobs":[]},"pending_inputs":[],"input_order":0,"usage":{"model":null,"observed_at":null,"prompt_tokens":null,"cached_prompt_tokens":null,"cache_write_tokens":null,"completion_tokens":null,"total_tokens":null,"elapsed_ms":null,"tokens_per_second":null,"context_window_tokens":null,"cache_ttl_seconds":null,"cache_fade":[]},"history":{"items":[],"older":null,"newer":null,"high_water":0},"glances":[]}}' - data: '{"generation":"J6kYj6IGcXyP3eMIp-WL3A","cursor":1,"events":[{"type":"input","sequence":1,"data":{"input":{"id":"01a0fcea-2b00-7000-8000-000000000002","session_id":"01a0fcea-2b00-7000-8000-000000000001","kind":"message","admission":"accepted","http_status":202,"problem":null,"accepted_at":"2026-10-02T14:00:00Z","acceptance_order":1,"delivery":"pending","blocking_reason":null,"transcript_position":null,"turn":null,"client_id":"draft-1"}}}]}' CollectionSSE: type: object diff --git a/priv/python/albedo_api.py b/priv/python/albedo_api.py index e69e4167c..47f23a7ab 100644 --- a/priv/python/albedo_api.py +++ b/priv/python/albedo_api.py @@ -18,7 +18,6 @@ from albedo_protocol import ( Reply as Reply, Interrupt as Interrupt, Shutdown as Shutdown, - JobSlot as JobSlot, Invoke as Invoke, Introspect as Introspect, Release as Release, @@ -133,9 +132,6 @@ class PythonApi: # model sees the image; returns a short description, raises ValueError # past the per-cell limits. Absent when the host pre-dates images. attach_image: Callable[[bytes], str] | None = None - # Local shell admission, shared across the daemon's kernels. Completion - # releases it through the existing verified `job` cleanup frame. - job_slot: Callable[[str, Callable[[], None]], Awaitable[None]] | None = None # A host call that blocks until its answer, for synchronous APIs over # routes that answer at once. Absent when the host pre-dates it. host_now: Callable[[str, dict[str, object]], object] | None = None diff --git a/priv/python/albedo_kernel.py b/priv/python/albedo_kernel.py index b3adbbb17..52bbba68a 100644 --- a/priv/python/albedo_kernel.py +++ b/priv/python/albedo_kernel.py @@ -15,6 +15,7 @@ from typing import cast from types import CodeType, FrameType import albedo_trace import asyncio +import builtins import codecs import collections import contextvars @@ -55,7 +56,6 @@ PENDING: dict[str, asyncio.Future[albedo_api.HostReply]] = {} # over directly, since the loop it would go through is the one waiting. WAITING: dict[str, tuple[threading.Event, list[albedo_api.HostReply]]] = {} HOST_NOW_TIMEOUT = 30.0 -JOB_SLOTS: dict[str, tuple[asyncio.Future[None], Callable[[], None]]] = {} HOST_SLOTS = asyncio.Semaphore(32) OWNER_CALLS = asyncio.Semaphore(32) # concurrent tool calls from the connection owner OWNER_TASKS: dict[str, asyncio.Task[object]] = {} # interruptable by invoke id @@ -68,8 +68,14 @@ PENDING_OBJECTS: collections.OrderedDict[str, asyncio.Future[tuple[bool, object] ) MIRROR_INTERVAL = 0.15 # seconds between output-tail mirror frames while data flows MIRROR_TAIL = 16 * 1024 # bytes of tail a mirror frame carries -active: asyncio.Task[object] | None = None -active_capture: Capture | None = None +BACKGROUND_SECONDS = max( + 0.01, float(os.environ.get("ALBEDO_CELL_BACKGROUND_SECONDS", "60")) +) +CELL_TASKS: dict[str, asyncio.Task[dict[str, object]]] = {} +CELL_CAPTURES: dict[str, Capture] = {} +BACKGROUND_RESULTS: dict[str, dict[str, object]] = {} +READ_CELLS: set[str] = set() +CELL_ANNOUNCER: asyncio.Task[None] | None = None interrupt_capture: Capture | None = None ARCHIVES: collections.OrderedDict[str, Capture] = collections.OrderedDict() # Finished executions by cell id: a replayed execute answers with its result @@ -168,11 +174,12 @@ def receive(frame: object) -> None: if message["type"] == "shutdown": die() elif message["type"] == "interrupt": - capture = active_capture - if capture is not None and capture.id == message["id"]: + capture = CELL_CAPTURES.get(message["id"]) + if capture is not None: interrupt_capture = capture capture.interruption = message.get("reason", "cancelled") os.kill(os.getpid(), signal.SIGINT) + _ = LOOP.call_soon_threadsafe(interrupt_queued, message) else: # The loop takes it after the execute it may name, not started yet. _ = LOOP.call_soon_threadsafe(deliver, message) @@ -201,7 +208,7 @@ def watch() -> None: time.sleep(WATCH_INTERVAL) if not os.path.isdir(RUN_DIR): die() - busy = active is not None or not QUEUE.empty() or LINK.jobs.live() > 0 + busy = bool(CELL_TASKS) or not QUEUE.empty() or LINK.jobs.live() > 0 if not busy and LINK.idle_for() > LINK.grace: die() @@ -214,25 +221,12 @@ def hello() -> dict[str, object]: "pgid": pgid if pgid == os.getpid() else None, "leader": albedo_proc.leader_token(os.getpid()), "ready": READY.is_set(), - "slots": [id for id, (slot, _) in JOB_SLOTS.items() if not slot.done()], + "cells": len(CELL_TASKS), } def deliver(message: albedo_api.Incoming) -> None: - if message["type"] == "job_slot": - entry = JOB_SLOTS.get(message["id"]) - if entry is not None and not entry[0].done(): - slot, on_queued = entry - if message.get("ok") is True: - LINK.jobs.hold(message["id"]) - slot.set_result(None) - elif message.get("queued") is True: - on_queued() - else: - slot.set_exception( - RuntimeError(str(message.get("message", "job admission failed"))) - ) - elif message["type"] == "interrupt": + if message["type"] == "interrupt": interrupt_queued(message) elif message["type"] == "reply": future = PENDING.pop(message["id"], None) @@ -257,7 +251,7 @@ def deliver(message: albedo_api.Incoming) -> None: ) elif message["type"] == "release": LIVE.pop(message["handle"], None) - elif message["type"] == "snapshot" and (active is not None or not QUEUE.empty()): + elif message["type"] == "snapshot" and (bool(CELL_TASKS) or not QUEUE.empty()): # A namespace mid-cell is no state to carry: the owner tries again later. send(state_reply(message, {"error": "a cell is still running"})) elif message["type"] == "execute" and message["id"] in FINISHED: @@ -276,12 +270,12 @@ def interrupt_queued(message: albedo_api.Interrupt) -> None: at an await, where cancelling reaches it.""" reason = message.get("reason", "cancelled") task = OWNER_TASKS.get(message["id"]) - capture = active_capture + capture = CELL_CAPTURES.get(message["id"]) if task is not None: _ = task.cancel() - elif active is not None and capture is not None and capture.id == message["id"]: + elif capture is not None: capture.interruption = reason - _ = active.cancel() + _ = CELL_TASKS[message["id"]].cancel() elif message["id"] in EXECUTING: INTERRUPTS[message["id"]] = reason @@ -292,21 +286,6 @@ class WorkError(Exception): self.code: str = code -async def job_slot(id: str, on_queued: Callable[[], None]) -> None: - """Wait for a heavy-job slot; `on_queued` runs at once if none is free, so - the caller can pause the job. Independent of host RPC slots.""" - future: asyncio.Future[None] = LOOP.create_future() - JOB_SLOTS[id] = (future, on_queued) - send({"type": "job_acquire", "id": id}) - try: - await future - except BaseException: - send({"type": "job_cancel", "id": id}) - raise - finally: - JOB_SLOTS.pop(id, None) - - async def host(method: str, args: dict[str, object]) -> object: async with HOST_SLOTS: return await _host(method, args) @@ -351,9 +330,8 @@ def host_now(method: str, args: dict[str, object]) -> object: def attach_image(data: bytes) -> str: """Attach image bytes to the running cell; plugins reach this as api.attach_image.""" capture = CELL.get() - # A task spawned by a finished cell still carries that cell's context; only - # the capture currently receiving output belongs to a result not yet sent. - if capture is None or capture.kind != "cell" or capture is not sink: + # Spawned tasks inherit context even after their creating cell finishes. + if capture is None or capture.kind != "cell" or capture.id not in ACTIVE_CAPTURES: raise RuntimeError( "images attach to a running cell; background work has no result to carry them" ) @@ -383,7 +361,8 @@ NATIVE = Capture("native", "native") NATIVE_LOCK = threading.RLock() NATIVE_FD = -1 DECODER = codecs.getincrementaldecoder("utf-8")("replace") -sink: Capture | None = None # the cell whose code is running; native bytes join it +NATIVE_SINKS: dict[asyncio.Task[object], Capture] = {} +ACTIVE_CAPTURES: set[str] = set() def retained(id: str) -> Capture: @@ -478,7 +457,8 @@ def drain() -> bool: return False text = DECODER.decode(data) if text: - (sink or NATIVE).write(text) + sinks = list(NATIVE_SINKS.values()) + (sinks[0] if len(sinks) == 1 else NATIVE).write(text) def native_output(fd: int) -> None: @@ -491,7 +471,7 @@ def native_output(fd: int) -> None: def interrupt(_signal: int, _frame: FrameType | None) -> None: - if active_capture is not None and active_capture is interrupt_capture: + if CELL.get() is not None and CELL.get() is interrupt_capture: raise KeyboardInterrupt() @@ -626,6 +606,7 @@ def capture_definitions( async def evaluate(source: str, cell_id: str, durable: bool = False) -> object: started = False + ACTIVE_CAPTURES.add(cell_id) try: prefix, suffix, tree = compile_cell(source, "") if durable: @@ -657,6 +638,8 @@ async def evaluate(source: str, cell_id: str, durable: bool = False) -> object: setattr(error, "_albedo_cell_id", cell_id) setattr(error, "_albedo_started", started) raise + finally: + ACTIVE_CAPTURES.discard(cell_id) class Cells: @@ -684,6 +667,7 @@ class Cells: raise ValueError("expected positive inclusive line numbers") if not isinstance(limit, int) or limit < 1: raise ValueError("limit must be a positive byte count") + cell_read(id) cell = cast(albedo_api.SavedCell, await host("cells.read", {"id": id})) lines = cell["source"].splitlines(keepends=True) data = "".join(lines[start_line - 1 : end_line]).encode( @@ -700,11 +684,22 @@ class Cells: """Status (ok, error, interrupted, started, saved, lost, unavailable), parentage, whether the cell started, and how long a finished cell ran, without its source.""" + cell_read(id) cell = cast(albedo_api.SavedCell, await host("cells.read", {"id": id})) return albedo_api.Record( (key, value) for key, value in cell.items() if key != "source" ) + async def cancel(self, id: str) -> bool: + """Request cancellation of a running cell and suppress its completion wake.""" + task = CELL_TASKS.get(id) + if task is None or task.done(): + cell_read(id) + return False + READ_CELLS.add(id) + CELL_CAPTURES[id].interruption = "cancelled" + return task.cancel() + async def list(self, limit: int = 20) -> albedo_api.ReadyList: """This session's cells, newest first: id, status, parent, and first line. Unlike output.list(), it reaches cells whose output has rolled out.""" @@ -718,6 +713,7 @@ class Cells: Diffs can be large; inspect the fields rather than printing the whole trace. """ + cell_read(id) return cast(dict[str, object], await host("cells.trace", {"id": id})) async def run( @@ -818,9 +814,12 @@ INJECTED: set[str] = {"__name__", "__builtins__", "_"} def swap_sink(capture: Capture | None) -> Capture | None: - global sink - previous, sink = sink, capture - return previous + task = cast(asyncio.Task[object], asyncio.current_task()) + with NATIVE_LOCK: + previous = NATIVE_SINKS.pop(task, None) + if capture is not None: + NATIVE_SINKS[task] = capture + return previous def background_capture(id: str) -> Capture: @@ -836,7 +835,7 @@ def remember(capture: Capture) -> None: ARCHIVES.move_to_end(capture.id) counts = collections.Counter(held.kind for held in ARCHIVES.values()) for key, held in list(ARCHIVES.items()): - if counts[held.kind] > LIMITS[held.kind]: + if counts[held.kind] > LIMITS[held.kind] and key not in EXECUTING: forget_output(key) counts[held.kind] -= 1 @@ -895,7 +894,6 @@ def _mirror_state(obj: object) -> dict[str, object]: "exit_code": getattr(obj, "exit_code", None), "timed_out": getattr(obj, "timed_out", False), "duration": getattr(obj, "duration", None), - "waited": getattr(obj, "waited", 0.0), } @@ -1144,71 +1142,245 @@ def deliver_trace(capture: Capture) -> None: capture.trace.release() +def cell_read(id: str) -> None: + task = CELL_TASKS.get(id) + if id in BACKGROUND_RESULTS or (task is not None and task.done()): + READ_CELLS.add(id) + BACKGROUND_RESULTS.pop(id, None) + + +def first_line(code: str) -> str: + """The cell's first line that is not blank or a comment, for one-line displays.""" + for line in code.splitlines(): + line = line.strip() + if line and not line.startswith("#"): + return line[:200] + return "python cell" + + +async def announce_cells() -> None: + while BACKGROUND_RESULTS: + batch = dict(BACKGROUND_RESULTS) + display = "\n".join( + f"cell finished (status={result['status']}, ran {result['duration']}s): {result['summary']}" + for result in batch.values() + ) + listed = "; ".join( + f"{id}: status={result['status']}, ran {result['duration']}s" + for id, result in batch.items() + ) + text = ( + "background python cells finished with results unread: " + + listed + + ". output.read(id) reads retained output; await cells.info(id) reads " + "the final status. no user sent this message; use the results if needed, " + "otherwise acknowledge briefly and stay idle." + ) + try: + await host("cells.completed", {"display": display, "text": text}) + except Exception as error: + if getattr(error, "code", "") == "busy": + await asyncio.sleep(2) + continue + for id in batch: + capture = ARCHIVES.get(id) + if capture is not None: + capture.write(f"\n[completion notice not delivered: {error}]\n") + for id in batch: + BACKGROUND_RESULTS.pop(id, None) + + +async def execute_cell( + message: albedo_api.Execute, capture: Capture +) -> dict[str, object]: + token = CELL.set(capture) + status, value = "ok", "" + began = LOOP.time() + _ = swap_sink(capture) + try: + if capture.interruption: + raise asyncio.CancelledError() + result = await evaluate( + message["code"], capture.id, message.get("durable", False) + ) + if result is not None: + value = show(result) + except (KeyboardInterrupt, asyncio.CancelledError): + status = "interrupted" + if capture.interruption == "deadline": + capture.write("\n[cell deadline exceeded; execution interrupted]\n") + except BaseException as error: + status = "error" + failed_id = cast(str, getattr(error, "_albedo_cell_id", capture.id)) + capture.write(traceback.format_exc()) + if message.get("durable", False): + capture.write( + f"\n[cell {failed_id} retained; inspect with await cells.read({failed_id!r}); repair with await cells.run({failed_id!r}, replacements=[(old, new)])]\n" + ) + finally: + _ = drain() + _ = swap_sink(None) + CELL.reset(token) + deliver_trace(capture) + return { + "type": "done", + "id": capture.id, + "status": status, + "duration": round(LOOP.time() - began, 3), + "output": capture.preview(status), + "value": value, + "truncated": capture.seen > PREVIEW, + "images": capture.encoded_images(), + } + + +async def finish_background( + message: albedo_api.Execute, task: asyncio.Task[dict[str, object]] +) -> None: + global CELL_ANNOUNCER + done = await task + capture = ARCHIVES[message["id"]] + if done["value"]: + capture.write("\n[result]\n" + str(done["value"]) + "\n") + done["output"] = capture.preview(str(done["status"])) + done["truncated"] = capture.seen > PREVIEW + # Commit before the wake, so cells.info/read see the terminal outcome. + if message.get("durable", False): + try: + await host("cells.finish", {"id": message["id"], "outcome": done}) + except Exception as error: + ARCHIVES[message["id"]].write( + f"\n[cell result could not be journaled: {error}]\n" + ) + else: + send(done) + retain_cell_result(message["id"], done) + if message["id"] in READ_CELLS: + READ_CELLS.discard(message["id"]) + return + BACKGROUND_RESULTS[message["id"]] = {**done, "summary": first_line(message["code"])} + if CELL_ANNOUNCER is None or CELL_ANNOUNCER.done(): + CELL_ANNOUNCER = LOOP.create_task(announce_cells()) + + +def retain_cell_result(id: str, done: dict[str, object]) -> None: + FINISHED[id] = done + while len(FINISHED) > FINISHED_LIMIT: + old, _ = FINISHED.popitem(last=False) + BACKGROUND_RESULTS.pop(old, None) + READ_CELLS.discard(old) + EXECUTING.discard(id) + CELL_TASKS.pop(id, None) + CELL_CAPTURES.pop(id, None) + capture = ARCHIVES.get(id) + if capture is not None: + capture.images.clear() + remember(capture) + send({"type": "cells", "live": len(CELL_TASKS)}) + + +def cell_timers( + capture: Capture, task: asyncio.Task[dict[str, object]], timeout_ms: int +) -> tuple[ + threading.Event, + threading.Event, + threading.Lock, + asyncio.Future[None], + threading.Timer, +]: + detached = threading.Event() + settled = threading.Event() + response_lock = threading.Lock() + released: asyncio.Future[None] = LOOP.create_future() + + def background() -> None: + with response_lock: + if settled.is_set() or task.done(): + return + detached.set() + send(background_reply(capture)) + LOOP.call_soon_threadsafe(released.set_result, None) + + # Threads also fire while synchronous cell code occupies the asyncio loop. + background_timer = threading.Timer(BACKGROUND_SECONDS, background) + deadline_timer = threading.Timer( + timeout_ms / 1000, + receive, + args=({"type": "interrupt", "id": capture.id, "reason": "deadline"},), + ) + background_timer.daemon = deadline_timer.daemon = True + background_timer.start() + deadline_timer.start() + task.add_done_callback(lambda _: deadline_timer.cancel()) + return detached, settled, response_lock, released, background_timer + + async def serve(): - global active, active_capture while True: message = await QUEUE.get() if message["type"] != "execute": send(state_reply(message)) continue capture = Capture(message["id"], max_edge=message.get("max_edge")) + capture.interruption = "" remember(capture) - token = CELL.set(capture) - _ = swap_sink(capture) - status, value = "ok", "" - began = LOOP.time() - task = active = LOOP.create_task( - evaluate(message["code"], capture.id, message.get("durable", False)) - ) + if len(CELL_TASKS) >= LIMITS["cell"]: + done: dict[str, object] = { + "type": "done", + "id": capture.id, + "status": "error", + "duration": 0, + "output": "16 cells are still running; cancel an unused cell with await cells.cancel(id), or end your turn and wait for completion.", + "value": "", + "truncated": False, + "images": [], + } + retain_cell_result(capture.id, done) + send(done) + continue + task = LOOP.create_task(execute_cell(message, capture)) + CELL_TASKS[capture.id] = task + CELL_CAPTURES[capture.id] = capture + send({"type": "cells", "live": len(CELL_TASKS)}) interrupted = INTERRUPTS.pop(capture.id, None) if interrupted is not None: capture.interruption = interrupted - _ = task.cancel() - try: - active_capture = capture - result = await task - if result is not None: - value = show(result) - except (KeyboardInterrupt, asyncio.CancelledError): - status = "interrupted" - if capture.interruption == "deadline": - capture.write("\n[cell deadline exceeded; execution interrupted]\n") - if not task.done(): - _ = task.cancel() - except BaseException as error: - status = "error" - failed_id = cast(str, getattr(error, "_albedo_cell_id", capture.id)) - capture.write(traceback.format_exc()) - if message.get("durable", False): - capture.write( - f"\n[cell {failed_id} retained; inspect with await cells.read({failed_id!r}); repair with await cells.run({failed_id!r}, replacements=[(old, new)])]\n" - ) - finally: - _ = ( - drain() - ) # a subprocess that already wrote belongs to this cell, not the next - _ = swap_sink(None) - active = None - active_capture = None - CELL.reset(token) - duration = round(LOOP.time() - began, 3) - deliver_trace(capture) - done: dict[str, object] = { - "type": "done", - "id": capture.id, - "status": status, - "duration": duration, - "output": capture.preview(status), - "value": value, - "truncated": capture.seen > PREVIEW, - "images": capture.encoded_images(), - } - FINISHED[capture.id] = done - while len(FINISHED) > FINISHED_LIMIT: - FINISHED.popitem(last=False) - EXECUTING.discard(capture.id) - send(done) - capture.images.clear() + detached, settled, response_lock, released, background_timer = cell_timers( + capture, task, message.get("timeout_ms", 300_000) + ) + _ = await asyncio.wait({task, released}, return_when=asyncio.FIRST_COMPLETED) + with response_lock: + settled.set() + background_timer.cancel() + is_background = detached.is_set() + if is_background: + watch_output(capture.id, lambda id=capture.id: cell_read(id)) + _ = LOOP.create_task(finish_background(message, task)) + else: + done = task.result() + retain_cell_result(capture.id, done) + READ_CELLS.discard(capture.id) + send(done) + + +def background_reply(capture: Capture) -> dict[str, object]: + return { + "type": "done", + "id": capture.id, + "status": "backgrounded", + "duration": BACKGROUND_SECONDS, + "output": capture.preview("ok") + + ( + f"\n[cell {capture.id} is still running in the background. " + "the session will wake automatically when it finishes; do NOT poll " + "or sleep. meanwhile do other useful work, or give the user a short " + "status report and end your turn. the original timeout_ms deadline " + "still applies. avoid changing variables this cell is using.]\n" + ), + "value": "", + "truncated": capture.seen > PREVIEW, + "images": capture.encoded_images(), + } def flush(timeout: float) -> None: @@ -1278,10 +1450,6 @@ def main(): modules=modules, watch_output=watch_output, attach_image=attach_image, - job_slot=job_slot - if os.environ.get("ALBEDO_JOB_ADMISSION") == "1" - and not os.environ.get("ALBEDO_REMOTE_TARGET") - else None, ) NAMESPACE.update(cells=Cells(), output=Output(), show_image=show_image) try: @@ -1295,6 +1463,10 @@ def main(): sys.path[0] = "" # Plugin bindings and session objects are rebuilt on every start, never saved. INJECTED.update(NAMESPACE) + # Cell globals may shadow tools; deletion reveals the original session binding. + NAMESPACE["__builtins__"] = vars(builtins) | { + name: value for name, value in NAMESPACE.items() if not name.startswith("_") + } # Declare our own process group; a group we do not lead is never the supervisor's target. pgid = os.getpgid(0) send( @@ -1311,8 +1483,10 @@ def main(): try: LOOP.run_until_complete(task) except KeyboardInterrupt: - if active is not None: - _ = active.cancel() + if interrupt_capture is not None: + running = CELL_TASKS.get(interrupt_capture.id) + if running is not None: + _ = running.cancel() die() diff --git a/priv/python/albedo_link.py b/priv/python/albedo_link.py index fc92dbec4..747f9072f 100644 --- a/priv/python/albedo_link.py +++ b/priv/python/albedo_link.py @@ -24,7 +24,7 @@ import time from collections.abc import Callable from typing import Any, BinaryIO -PROTOCOL = 1 # hello, snapshot and shutdown frames never change shape +PROTOCOL = 1 # framing version; hello fields describe the current bundle MAX_FRAME = 8 * 1024 * 1024 SOCKET = "kernel.sock" ATTACH_TIMEOUT = 10.0 # seconds a fresh connection has to present its token @@ -32,7 +32,7 @@ OUTBOX_FRAMES = 4096 OUTBOX_BYTES = 64 * 1024 * 1024 # Frames whose newest copy supersedes every older unacknowledged one, by the # field naming what they describe. Everything else must be delivered. -COALESCE = {"mirror": "handle", "trace": "id", "jobs": None} +COALESCE = {"mirror": "handle", "trace": "id", "jobs": None, "cells": None} def encode(value: object) -> bytes: @@ -160,20 +160,14 @@ class JobBook: """Job groups this kernel still owns, read from the frames it sends. The same bookkeeping the daemon keeps: a started job's group is owned - until a job frame proves it gone, and so is the heavy-job slot it was - granted. A reattaching daemon learns both from the hello, and the kernel - stays alive past its grace while any job is live. + until a job frame proves it gone. A reattaching daemon learns the groups + from the hello. The kernel stays alive past its grace while a job is live. """ def __init__(self) -> None: self.started: dict[str, dict[str, object]] = {} - self.held: set[str] = set() self.external = 0 - def hold(self, id: str) -> None: - """The daemon granted this job a slot.""" - self.held.add(id) - def observe(self, frame: dict[str, object]) -> None: kind, id = frame.get("type"), frame.get("id") if kind == "job_start" and isinstance(id, str): @@ -184,7 +178,6 @@ class JobBook: cleanup = frame.get("cleanup") if isinstance(cleanup, dict) and cleanup.get("gone") is True: self.started.pop(id, None) - self.held.discard(id) elif kind == "jobs": live = frame.get("live") if isinstance(live, int) and not isinstance(live, bool) and live >= 0: @@ -331,7 +324,6 @@ class SocketLink: "epoch": self.epoch, "ack": self.inbound.last, "jobs": list(self.jobs.started.values()), - "held": sorted(self.jobs.held), "external": self.jobs.external, "dropped": self.outbox.dropped, } diff --git a/priv/python/albedo_plugins/remote.py b/priv/python/albedo_plugins/remote.py index 3f434f2a0..25498fa4d 100644 --- a/priv/python/albedo_plugins/remote.py +++ b/priv/python/albedo_plugins/remote.py @@ -307,12 +307,6 @@ class RemoteRef: state = self._mirror() return state.get("duration") if state else None - @property - def waited(self) -> float: - """The seconds the remote job sat paused for a heavy slot.""" - state = self._mirror() - return state.get("waited", 0.0) if state else 0.0 - @property def id(self) -> str | None: """The remote job's id, for output.read on the remote side.""" diff --git a/priv/python/albedo_plugins/run.py b/priv/python/albedo_plugins/run.py index 73586bffb..92a6e60ec 100644 --- a/priv/python/albedo_plugins/run.py +++ b/priv/python/albedo_plugins/run.py @@ -4,7 +4,7 @@ run(program, *args) starts one program without a shell. A job runs in its own session, so its program leads a process group and one signal reaches it plus every descendant that stayed in that group. The group is ended when the command ends, when its deadline passes, and at kernel -shutdown. What survives is reported, and unfinished work keeps its running slot. +shutdown. What survives is reported, and unfinished work stays owned. When the command ends on its own, members a process that left the group still parents stay with it: ssh's ControlPersist master daemonizes out of the job but leaves its ProxyCommand in the group, and ending that ends the master. @@ -20,7 +20,7 @@ still owed when the retry lands share one notice, and so one turn. from __future__ import annotations from collections import OrderedDict -from collections.abc import Awaitable, Callable, Generator +from collections.abc import Callable, Generator from typing import cast from albedo_api import RAW_RETAIN, Host, PythonApi, OutputCapture, Send, excerpt import albedo_proc @@ -30,7 +30,6 @@ import asyncio import os import shlex import shutil -import signal import sys import uuid @@ -44,18 +43,14 @@ owed: dict[str, Job] = {} # finished with results unread, in completion order announcer: asyncio.Task[None] | None = None send: Send host: Host | None = None -job_slot: Callable[[str, Callable[[], None]], Awaitable[None]] | None = None watch_output: Callable[[str, Callable[[], None]], None] | None = None forget_output: Callable[[str], None] | None = None -ACTIVE_LIMIT = 64 # queued or running jobs in one kernel +ACTIVE_LIMIT = 64 # active jobs in one kernel RETAINED_LIMIT = 64 # finished handles still addressable through `jobs` COMPLETION_GRACE = 0.1 # seconds to keep reading after the command exits SHUTDOWN_TERM = 0.25 # shared by every live group at shutdown SHUTDOWN_KILL = 1.0 -# A job still running after this long is heavy: it needs a daemon-wide slot, and -# waits for one paused. Quick commands finish first and never wait. -GRACE = float(os.environ.get("ALBEDO_JOB_GRACE_SECONDS", "5") or 5) NICENESS = 10 # macOS runs utility-QoS work below the interface, so a busy swarm yields. TASKPOLICY = shutil.which("taskpolicy") if sys.platform == "darwin" else None @@ -280,8 +275,6 @@ class Job: self.timed_out: bool = False self.started: float = loop.time() self.duration: float | None = None # seconds it ran, once it ended - self.waited: float = 0.0 # seconds it sat paused for a heavy slot - self._paused_at: float | None = None self.termination: albedo_proc.Termination | None = None self.capture: OutputCapture = capture_factory(self.id) self.ending: asyncio.Task[albedo_proc.Termination] | None = None @@ -291,10 +284,6 @@ class Job: self._starting = ( False # the OS spawn began; from then on it must finish, not be cancelled ) - self._paused = False # stopped, waiting for a heavy slot - self._resumed = asyncio.Event() - self._resumed.set() - self._pausing = asyncio.Event() if watch_output is not None: watch_output(self.id, self._mark_read) if traced: @@ -307,12 +296,6 @@ class Job: active[self.id] = self jobs[self.id] = self - @property - def queued(self) -> bool: - """Paused, waiting for a heavy slot: it ran past the grace window while - the machine's slots were taken.""" - return self._paused - async def _launch( self, cwd: str | None, @@ -360,50 +343,6 @@ class Job: else self.command ) - async def _heavy(self) -> None: - """Past the grace window, hold a daemon-wide slot; pause until one frees.""" - await asyncio.sleep(GRACE) - if ( - job_slot is None - or self.process is None - or self.process.returncode is not None - ): - return - try: - await job_slot(self.id, self._pause) - finally: - self._resume() - - def _signal(self, signum: int) -> None: - group = self.claim() - if group is not None: - try: - os.killpg(group.pgid, signum) - except (ProcessLookupError, PermissionError): - pass - - def _pause(self) -> None: - if ( - not self._paused - and self.process is not None - and self.process.returncode is None - ): - self._signal(signal.SIGSTOP) - self._paused = True - self._paused_at = loop.time() - self._resumed.clear() - self._pausing.set() - - def _resume(self) -> None: - if self._paused: - self._signal(signal.SIGCONT) - self._paused = False - if self._paused_at is not None: - self.waited += loop.time() - self._paused_at - self._paused_at = None - self._pausing.clear() - self._resumed.set() - def claim(self) -> albedo_proc.Group | None: """The group this job owns, derived again when a late spawn beat the assignment.""" if self.group is None and self.process is not None: @@ -414,8 +353,10 @@ class Job: { "type": "job_start", "id": self.id, + "pid": self.process.pid, "pgid": self.group.pgid, "leader": self.group.leader, + "command": self.pipeline[:4096], } ) return self.group @@ -434,11 +375,8 @@ class Job: async def _run(self, timeout: float) -> Job: try: process = self.process = await self._spawn() - heavy = loop.create_task(self._heavy()) - try: - self.exit_code = await self._wait(process, timeout) - finally: - heavy.cancel() + await asyncio.wait_for(asyncio.shield(process.exited), timeout) + self.exit_code = await self._drain(process) except asyncio.TimeoutError: self.timed_out = True except asyncio.CancelledError: @@ -454,7 +392,7 @@ class Job: self.exit_code = await self._status(self.process) if self.process is not None and ending.gone: self.process.transport.close() - self.duration = loop.time() - self.started - self.waited + self.duration = loop.time() - self.started if self.timed_out: self.capture.write( f"\n[deadline exceeded after {timeout:g}s; {ending.report()}]\n" @@ -475,28 +413,6 @@ class Job: owe(self) return self - async def _wait(self, process: Command, timeout: float) -> int: - """The exit code, with `timeout` counting only time the job ran: a pause - for a heavy slot does not spend it.""" - remaining = timeout - while True: - if self._paused: - await self._resumed.wait() - continue - began = loop.time() - pausing = loop.create_task(self._pausing.wait()) - done, _ = await asyncio.wait( - {process.exited, pausing}, - timeout=remaining, - return_when=asyncio.FIRST_COMPLETED, - ) - pausing.cancel() - if process.exited in done: - return await self._drain(process) - remaining -= loop.time() - began - if remaining <= 0: - raise asyncio.TimeoutError - async def _drain(self, process: Command) -> int: """Read output while the command runs; a descendant holding the pipe does not extend it.""" code = await asyncio.shield(process.exited) @@ -566,8 +482,6 @@ class Job: if self.duration is not None else "unknown duration" ) - if self.waited: - seconds += f", queued {self.waited:.1f}s" return { "id": self.id, "command": command, @@ -576,7 +490,6 @@ class Job: "exit_code": self.exit_code, "timed_out": self.timed_out, "duration": self.duration, - "waited": self.waited, "host": self._remote, } @@ -590,8 +503,6 @@ class Job: that left the group still parents stays with that process.""" if self.termination is not None and self.termination.gone: return self.termination - # A stopped group cannot act on TERM; let it run to hear it. - self._resume() process = self.process if process is None: if not self._starting: @@ -636,9 +547,9 @@ class Job: def __repr__(self) -> str: return ( - f"Job(id={self.id!r}, queued={self.queued!r}, exit_code={self.exit_code!r}, " + f"Job(id={self.id!r}, exit_code={self.exit_code!r}, " f"timed_out={self.timed_out!r}, duration={self.duration!r}, " - f"waited={self.waited!r}, bytes={self.capture.seen})" + f"bytes={self.capture.seen})" ) @@ -647,7 +558,7 @@ async def _unstarted() -> albedo_proc.Termination: def release(job: Job) -> None: - """Free the running slot only when the group is gone; a leaked group keeps it.""" + """Retire active work only when its group is gone.""" if ( job.termination is None or not job.termination.gone @@ -750,9 +661,8 @@ def run( timeout: float = 300, ) -> Job: """Start one program, without a shell, and return its handle immediately: - run("go", "test", "./...", cwd="cli"). It starts at once, at low priority; - one still running after the grace window (5 s) needs a daemon-wide heavy - slot, and pauses until one frees; `job.queued` is True while it waits. + run("go", "test", "./...", cwd="cli"). It starts at once, at low priority. + The timeout counts wall time after the program starts. `env` adds to the kernel's environment. `stdin` is text or bytes to feed the program, a path to read, or another job, whose output streams in like @@ -807,16 +717,14 @@ def start( ) -> Job: """A job for argv as given, for run() and for plugins' own supervised work.""" if len(active) >= ACTIVE_LIMIT: - raise RuntimeError( - f"{ACTIVE_LIMIT} jobs are queued or running; await or stop one first" - ) + raise RuntimeError(f"{ACTIVE_LIMIT} jobs are active; await or stop one first") return Job(argv, timeout, cwd=cwd, env=env, stdin=stdin, traced=traced) async def close() -> None: """Kernel shutdown: end every live group inside one shared deadline.""" owned = list(active.values()) - # Never spawn a queued command just to shut it down. In-flight OS spawns, + # Never spawn a pending command just to shut it down. In-flight OS spawns, # however, must finish transferring ownership before the shared ladder. for job in owned: if not job._starting: @@ -840,7 +748,7 @@ async def close() -> None: def setup(api: PythonApi) -> dict[str, object]: global loop, capture_factory, preview_limit, jobs, active, retained, send - global host, job_slot, watch_output, forget_output + global host, watch_output, forget_output loop, capture_factory, preview_limit, send = ( api.loop, api.capture, @@ -848,7 +756,6 @@ def setup(api: PythonApi) -> dict[str, object]: api.send, ) host, watch_output, forget_output = api.host, api.watch_output, api.forget_output - job_slot = api.job_slot jobs, active, retained = {}, {}, OrderedDict() api.background_handle(Job) api.on_shutdown(close) diff --git a/priv/python/albedo_proc.py b/priv/python/albedo_proc.py index acd92e8db..114c5c400 100644 --- a/priv/python/albedo_proc.py +++ b/priv/python/albedo_proc.py @@ -30,7 +30,7 @@ def reap_stopped_safely(loop: asyncio.AbstractEventLoop) -> None: Python 3.14's threaded child watcher waits with waitid(WEXITED | WNOWAIT), which macOS also answers for a stopped child, and then reaps with a blocking - waitpid on the event loop: a job paused for a heavy slot froze the kernel. + waitpid on the event loop, which can freeze the kernel on a stopped child. The replacement reaps in its thread with a waitpid that ignores stops, as 3.13 did. Linux uses pidfds, which only wake on exit, and needs nothing. """ diff --git a/priv/python/albedo_protocol.py b/priv/python/albedo_protocol.py index b456465ad..6bc03ba4e 100644 --- a/priv/python/albedo_protocol.py +++ b/priv/python/albedo_protocol.py @@ -9,6 +9,7 @@ class Execute(TypedDict): code: str durable: NotRequired[bool] max_edge: NotRequired[int] + timeout_ms: NotRequired[int] class HostSuccess(TypedDict): @@ -41,14 +42,6 @@ class Shutdown(TypedDict): type: Literal["shutdown"] -class JobSlot(TypedDict): - type: Literal["job_slot"] - id: str - ok: bool - queued: NotRequired[bool] - message: NotRequired[str] - - Invoke = TypedDict( "Invoke", { @@ -82,15 +75,7 @@ class State(TypedDict): Incoming = ( - Execute - | Reply - | Interrupt - | Shutdown - | Invoke - | Introspect - | Release - | State - | JobSlot + Execute | Reply | Interrupt | Shutdown | Invoke | Introspect | Release | State ) @@ -134,7 +119,6 @@ class MirrorState(TypedDict, total=False): exit_code: int | None timed_out: bool duration: float | None - waited: float class Invoked(TypedDict): @@ -228,7 +212,6 @@ def parse_incoming(value: object) -> Incoming: "reply", "interrupt", "shutdown", - "job_slot", "invoke", "introspect", "release", @@ -242,6 +225,7 @@ def parse_incoming(value: object) -> Incoming: _field(message, "code", str, kind) _field(message, "durable", bool, kind, optional=True) _field(message, "max_edge", int, kind, optional=True) + _field(message, "timeout_ms", int, kind, optional=True) elif kind == "reply": reply = _object(message.get("value"), "reply.value") _field(reply, "ok", bool, "reply.value") @@ -254,10 +238,6 @@ def parse_incoming(value: object) -> Incoming: _field(message, "reason", str, kind, optional=True) if "reason" in message and message["reason"] not in ("deadline", "cancelled"): raise ValueError("interrupt.reason: expected deadline or cancelled") - elif kind == "job_slot": - _field(message, "ok", bool, kind) - _field(message, "queued", bool, kind, optional=True) - _field(message, "message", str, kind, optional=True) elif kind == "invoke": for field, expected in ( ("name", str), @@ -291,7 +271,6 @@ def _mirror(value: object, context: str) -> None: ("exit_code", (int, type(None))), ("timed_out", bool), ("duration", (int, float, type(None))), - ("waited", (int, float)), ): _field(state, field, expected, context, optional=True) diff --git a/priv/python/albedo_ssh.py b/priv/python/albedo_ssh.py index 205a2b8d8..e197071a5 100644 --- a/priv/python/albedo_ssh.py +++ b/priv/python/albedo_ssh.py @@ -181,10 +181,7 @@ def commands(target: str, home: str) -> dict[str, object]: "control": control, "bundle": bundle, "bridge": in_login_shell( - "ALBEDO_JOB_ADMISSION=1 " - + python - + shlex.quote(f"{bundle}/albedo_bridge.py") - + " --frame" + python + shlex.quote(f"{bundle}/albedo_bridge.py") + " --frame" ), "signal": in_login_shell( python + shlex.quote(f"{bundle}/albedo_signal.py") + " -" diff --git a/robot-docs/agents.md b/robot-docs/agents.md index a45863871..0e72e11be 100644 --- a/robot-docs/agents.md +++ b/robot-docs/agents.md @@ -77,22 +77,8 @@ the orchestrator feed batches every 100 ms and skips activity serialization when nobody is watching. run jobs start at once, at low priority (`nice`, and utility QoS on macOS), so a -busy swarm yields to the person at the machine. a job still running after the grace -window (5 s) is heavy and needs one of a few daemon-wide slots; without one it is -paused (`SIGSTOP`, `job.queued` is true) and resumed when one frees, so waiting -costs no cpu and loses no work. quick commands never wait. the timeout counts only -time the command ran. `await job.stop()` resumes a paused job so it can exit. - -slots default to the machine's cores and shrink while the one-minute load average -runs past 1.25× the cores, which catches heavy jobs that fan out workers of their -own. a freed slot goes to the kernel holding the fewest, oldest request first, so -one busy agent cannot starve the rest. a slot is released only after process-group -cleanup is confirmed; failed cleanup keeps it held. - -settings, read when the daemon starts: `ALBEDO_MAX_LOCAL_JOBS` fixes the slot count -(1–256), `ALBEDO_JOB_GRACE_SECONDS` sets the grace window, `ALBEDO_JOB_LOAD=0` -turns off the load adjustment. this bounds sustained shell work, not agent/model -concurrency, remote kernels, or python computed directly in a cell. +busy swarm yields to the person at the machine. jobs never pause for admission, +and their deadlines count wall time after the program starts. ## deletion failures diff --git a/robot-docs/commands.md b/robot-docs/commands.md index 6d452db7c..60c872ef7 100644 --- a/robot-docs/commands.md +++ b/robot-docs/commands.md @@ -38,7 +38,7 @@ a run executes **outside** the session actor — on the kernel's host-call proce the `commands` extension exposes the async `commands` object. at kernel boot the catalog mints one typed method per model-callable command: `commands.model("gpt-5")`, `commands.demo("the args")`. each method's docstring and signature come from the declaration, so `help(commands.)` is the command's help text. `commands.catalog()` returns the current catalog, so a session `/reload` reaches it without a kernel restart; `commands.invoke(name, arguments)` runs any model-callable command by slash name with raw text or a dict. a command whose method name is reserved (`catalog`, `invoke`, `help`), invalid, taken, or added after the kernel booted stays callable through `invoke()`. -argument parsing is shared: leading arguments take one whitespace token each, the last declared argument takes the rest with outer whitespace trimmed and inner spacing exact, so `/fix-lint one two` arrives as `"one two"`. +argument parsing is shared: leading arguments take one whitespace token each, the last declared argument takes the rest with outer whitespace trimmed and inner spacing exact, so `/fix-lint one two` arrives as `"one two"`. the TUI also accepts a JSON object naming the arguments. text after a command that declares no arguments is not a command at all: the TUI sends `/jobs is broken` to the model as a prompt. ## v1 commands diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index dbe94e78c..13a7522bb 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -152,6 +152,9 @@ The kernel runs detached behind a bridge, with a durable session layer under the ## run +Jobs start immediately at the existing nice level and macOS utility QoS. There is +no heavy-job admission or process pausing; deadlines count wall time after spawn. + Output read watchers use weak references to bound job methods. They remain registered across early reads, so a read after completion still retires the notice. Forgetting or evicting an output channel removes its watcher. Job handles and output channels keep their separate retention order and existing limits. A retained output watcher does not keep an evicted job alive, and an explicitly held job keeps its own output after archive eviction. `run(program, *args, cwd=, env=, stdin=)` starts one program, without a shell, as a supervised job that owns its process group: a deadline, a stop or kernel shutdown ends the whole group, and so does the command's own exit, except for members a process that moved out of the group still parents (`albedo_proc.adopted`). that keeps ssh's ControlPersist masters working from jobs: the master daemonizes out of the group but leaves its ProxyCommand in it, and ending the proxy ends the master, so every later ssh (and every hardware-key touch) would start over. a parent started after the job's leader came from the job; orphans, adopted by init or a subreaper that was running before, still go. `run` is synchronous and returns the handle; awaiting the handle waits for the program, so the instructions teach `job = run(...)` then `await job` — `job = await run(...)` would leave nothing bound when a cell deadline interrupts the wait, and the model would recover the running job through `jobs` or start it twice; output stays on the handle (`job.tail()`, `output.read(job.id)`) and finished handles stay addressable in `jobs`. a job that finishes with its result unread wakes the session: the kernel reports the completion through the `jobs` host route, and the session submits a user turn naming the job, its exit, and how to read it, so the model never polls or awaits a handle just to learn it finished. awaiting the job, reading its result, or stopping it retires the wake. a busy session is retried, not queued in gleam: the kernel retries the notice until the run ends or the result is read. live jobs pin the kernel against the idle sweep — a detached session is not released while background work still runs, local or remote, because releasing it would kill the job and the wake it owes. remote `run` jobs wake the same way — the remote kernel's host calls relay over the ssh connection into this session's route, and the notice names the host — and a mirror read (`rem_job.tail()`) tells the remote job it was read through one `poll` round trip. @@ -198,7 +201,7 @@ the model's instructions are short on purpose: `remote.connect(host)` is ssh for the ssh options, control path, agent socket discovery, login-shell wrapper and bundle staging live in `priv/python/albedo_ssh.py`, which the daemon's own remote kernels use too (kernel.md, "remote kernels"), so both ride the same control sockets and the same staged bundle under `~/.albedo-remote/`. a session whose workspace is itself on another host needs no `remote.connect()`: its kernel already runs there. -machine tools run on the remote kernel: `rem.run(program, *args)` starts a supervised job on the host immediately and synchronously, like local run — the handle exists right away, `job.tail()`, `job.id`, `job.exit_code`, `job.duration`, `job.waited`, and `job.timed_out` answer synchronously from the mirrored output stream, `await job` waits for completion, and `await job.stop()` stops it. pipes run entirely on the host, chained before the one await: `job = rem.run("journalctl", "-u", "nginx", "--no-pager").pipe("rg", "error")`, `await job`, then `job.tail(lines=40)`. `tail(lines=)` and `exit_code` answer from the mirror; other job methods, like `head(lines=)`, are remote calls to await, and properties such as `job.pipeline` do not cross. session tools run where the daemon runs: `await rem.work.*` and `await rem.skills.*` relay over the connection to the local daemon's ledger and catalog. both kernels load the same content-hashed bundle, so a tool's remote shape matches its local one. every other call returns a reference that settles on its first await: values cross as real objects — dataclasses and list subclasses are rebuilt, so remote output prints exactly like local output — and a result that cannot cross comes back as a live reference whose methods are further remote calls. references passed back into remote calls stay references, not copies, including ones still in flight. one rule remains: a call whose local counterpart is synchronous (`rem.files.read`) still needs `await`, because the value itself crosses the network; handles and their state never do. +machine tools run on the remote kernel: `rem.run(program, *args)` starts a supervised job on the host immediately and synchronously, like local run — the handle exists right away, `job.tail()`, `job.id`, `job.exit_code`, `job.duration`, and `job.timed_out` answer synchronously from the mirrored output stream, `await job` waits for completion, and `await job.stop()` stops it. pipes run entirely on the host, chained before the one await: `job = rem.run("journalctl", "-u", "nginx", "--no-pager").pipe("rg", "error")`, `await job`, then `job.tail(lines=40)`. `tail(lines=)` and `exit_code` answer from the mirror; other job methods, like `head(lines=)`, are remote calls to await, and properties such as `job.pipeline` do not cross. session tools run where the daemon runs: `await rem.work.*` and `await rem.skills.*` relay over the connection to the local daemon's ledger and catalog. both kernels load the same content-hashed bundle, so a tool's remote shape matches its local one. every other call returns a reference that settles on its first await: values cross as real objects — dataclasses and list subclasses are rebuilt, so remote output prints exactly like local output — and a result that cannot cross comes back as a live reference whose methods are further remote calls. references passed back into remote calls stay references, not copies, including ones still in flight. one rule remains: a call whose local counterpart is synchronous (`rem.files.read`) still needs `await`, because the value itself crosses the network; handles and their state never do. images are the exception to "every harness tool runs remotely": a remote call is not a cell, so the remote kernel has no result to carry one. `await rem.show_image(path_or_bytes)` runs locally instead: it reads a remote path over the control connection (at most one byte past the 5 MiB a cell may carry) and attaches the bytes to the local cell through `api.attach_image`, so the image meets the same format, count, size and edge checks as `show_image`. it works in degraded mode too. diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 07fd30867..1d81807fd 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -6,6 +6,69 @@ restart, keeping its namespace and its background jobs. the daemon reaches it through a bridge, and every message between the two travels through a small session layer that neither loses nor repeats a message across a reconnect. +## tool bindings + +The kernel keeps injected helpers in cell globals and in a session-private copy +of Python's builtins. An assignment such as `files = [...]` shadows the helper; +`del files` reveals the original binding again, including inside functions and +later cells. The process-wide `builtins` module is unchanged. Plugin instances +are owned by this kernel's API, not module-level singletons. This fallback is +built once after plugins load and is not serialized with user state. + +## background job observations + +`GET /sessions/{id}` exposes `kernel.live_job_count` and `kernel.running_jobs` +without starting a kernel. Unknown observations are null. The list contains up +to 100 live jobs ordered by ID, with `id`, nullable `pid`, and `command` (up to +4096 scalars); the count can exceed the list when remote jobs have no summaries. +The TUI uses these observations for its idle-job status, animation, and sidebar. + +`/jobs` reads `GET /extensions/run/sessions/{id}/jobs`, whose page declares the +stop action. `POST /extensions/run/sessions/{id}/jobs/{job_id}/stop` supervises +that job's recorded process group and reports failure if its stop is unconfirmed. +A missing job returns 404. After response loss, read the collection before +confirming another attempt; stopping is never automatically retried. Job rows +carry no resource; the stop action binds the row id. + +A job that finishes with its result unread wakes the session. The model reads +the full notice with the job's handle; the transcript keeps the wake's one-line +display (`job finished (exit_code=0, ran 1.2s): …`) as a note from `job`. + +## background cells + +The kernel returns a python tool result with `status=backgrounded` after 60 +seconds (`ALBEDO_CELL_BACKGROUND_SECONDS` overrides the threshold, in seconds). +The result includes output so far, the cell id, and instructions to do useful +work or report status and end the turn, without polling or sleeping. This is not +a final outcome: the journal stays `started` until `cells.finish` records it. +`cells.info/read/trace` remain available; traces appear when execution finishes. +The original `timeout_ms` is carried to the kernel and still interrupts the cell +at its deadline, even after the daemon's original execute wait has ended. + +New cells can run while a detached cell awaits. They share the namespace, so +avoid modifying variables the detached cell uses. Python output, images, and +activity traces use the task's context; native fd output goes to `native` when +multiple cells run, since it cannot be attributed safely. A synchronous cell +can return its tool result early, but other cells must wait until it yields or +finishes. Background and deadline timers run outside the asyncio loop so a +synchronous cell cannot prevent its deadline from firing. + +At most 16 cells run concurrently. Running captures are protected from eviction; completed output rolls out +under the existing 16-capture limit. `await cells.cancel(id)` requests cancellation and +suppresses that cell's wake. Explicit kernel reset/replacement ends its cells; +a daemon restart merely reattaches. Internal `cells` count frames, replayed in +the hello, keep idle reaping and automatic stale-kernel replacement from ending +a running cell without pretending the cells are process jobs in the public API. + +Completion is committed before `cells.completed` sends a wake. The transcript +gets a one-line `cell finished (status=ok, ran 90.0s): ` from +`cell`, while the model gets the full notice with the cell id separately. Unread completions share a wake and retry +every two seconds while the session is busy; there is no model polling. The final expression is appended to retained output under `[result]`, so +`output.read(id)` can read it after a background completion. Reading finished +output, source, status, or trace retires a pending wake. +Reading partial output while the cell still runs does not retire its eventual +completion. A read racing with the completion journal also retires the wake. + ## processes - **kernel**: started in its own session and process group, stdio not tied to @@ -38,15 +101,12 @@ the daemon writes `{"attach": {"kernel", "token", "ack", "grace"}}` first. the kernel checks the token (kept in the daemon's sqlite), bumps its epoch, cuts off any older connection (newest attach wins), and answers `{"hello": {protocol, bundle, epoch, ack, pid, pgid, leader, ready, jobs, -held, external, slots, dropped}}`, or `{"refused": reason}`. `protocol` (1) and the -hello/snapshot/shutdown frames never change shape. `bundle` is +external, dropped}}`, or `{"refused": reason}`. `protocol` (1) and the +hello reports the running `cells` count. `bundle` is `albedo_bundle.digest()`, the same content hash the remote plugin stages under; a hello whose bundle or protocol differs from the bridge's makes the -kernel stale (see version skew). `jobs` (live `job_start` frames), `external`, -`held` (jobs granted a heavy slot whose end isn't proven yet) and `slots` (job -slots still waited for) let a fresh port owner take over job ownership and -admission: held slots count in its pool at once (`albedo_job_slots:claim`, -even past the limit), waited-for ones are asked for again. +kernel stale (see version skew). `jobs` (live `job_start` frames) and `external` +let a fresh port owner take over job ownership and live-job observations. ## session layer @@ -84,8 +144,7 @@ dedupe: one for a cell the kernel no longer holds is dropped. - what the kernel resends after a restart: job wakes are host calls (`jobs.completed`), so the call ledger covers them; `job_start`, `job`, - `job_cancel` and `jobs` only update ownership and slot bookkeeping, which - converges; `job_acquire` asks the new pool, which never saw it; a `done` + and `jobs` only update ownership and observations, which converge; a `done` nobody waits for rewrites the same outcome; traces save by cell id. ## drops @@ -256,12 +315,6 @@ with backoff and `resume_kernels` treat an ssh drop as a bridge that exited. only the bridge (a local ssh client) is ever signalled here. the run directory goes with `rm -rf` over ssh. `os_pid` answers nothing for a remote kernel, so the reaper's `ps` never reads an unrelated local pid. -- **heavy slots**: a remote kernel's jobs queue in that host's own pool - (`albedo_job_slots:ensure(Host, Cpus)`, started and watched by the local - pool), sized to the cores the probe found (`ALBEDO_MAX_REMOTE_JOBS` - overrides; two while a host attached without a probe is still unknown, - corrected by the next probe) with no load adjustment; admission is the - same protocol. - **turns**: a session that holds a kernel (attached, or reattaching through its outbox) never probes on a turn. one that must boot probes for up to 3 s: still warming is left to the boot, which waits for the diff --git a/robot-docs/paperclips.md b/robot-docs/paperclips.md index 7df3d1ae2..998ce25b7 100644 --- a/robot-docs/paperclips.md +++ b/robot-docs/paperclips.md @@ -48,10 +48,10 @@ not be told and the reply stays saved on the vent. the detail pane shows the suggestion, the answer, a model's resolution note with the session that closed it, and the filing session and workspace; a session shows by the name someone gave it — a child by its family name, a root by its -title — else by a short id, the same precedence the agents view uses. open vents -also appear in the page's glance beside the conversation, globally: every -session's glance counts the open vents in the review window, which keeps -open vents ahead of newer finished ones. +title — else by a short id, the same precedence the agents view uses. the +page's glance lists the open vents in the review window, which keeps open vents +ahead of newer finished ones. vents stay out of the chat sidebar, which shows +only the work ledger's active items and the session's background jobs. ## storage diff --git a/src/albedo/daemon/albedo_wakes.erl b/src/albedo/daemon/albedo_wakes.erl index 2cf2beca5..18646454a 100644 --- a/src/albedo/daemon/albedo_wakes.erl +++ b/src/albedo/daemon/albedo_wakes.erl @@ -6,7 +6,7 @@ %% `run.Wake` type: delivered, busy (the kernel retries), or %% {unavailable, Reason}. -module(albedo_wakes). --export([register/2, forget/1, deliver/3]). +-export([register/2, forget/1, deliver/3, deliver/4]). -define(TABLE, albedo_wakes). @@ -15,7 +15,9 @@ register(Id, Fun) -> albedo_registry:register(?TABLE, Id, Fun). forget(Id) -> albedo_registry:forget(?TABLE, Id). %% The session's answer to one wake; a missing or crashed session is unavailable. -deliver(Id, Display, Text) -> - albedo_registry:call(?TABLE, Id, 2, [Display, Text], +deliver(Id, Display, Text) -> deliver(Id, <<"job">>, Display, Text). + +deliver(Id, Origin, Display, Text) -> + albedo_registry:call(?TABLE, Id, 3, [Origin, Display, Text], {unavailable, <<"session unavailable">>}, {unavailable, <<"session unavailable">>}). diff --git a/src/albedo/daemon/http_history.gleam b/src/albedo/daemon/http_history.gleam index 4e727f581..be795eb05 100644 --- a/src/albedo/daemon/http_history.gleam +++ b/src/albedo/daemon/http_history.gleam @@ -132,7 +132,7 @@ fn project_row( let #(kind, text, origin) = case ownership.display { Some(display) -> case display.source { - "chat" | "mail" | "job" | "webhook" | "continue" -> #( + "chat" | "mail" | "webhook" | "continue" -> #( "user", case ownership.letter { Some(letter) if letter.kind != mail.Webhook -> letter.body diff --git a/src/albedo/daemon/http_transcript.gleam b/src/albedo/daemon/http_transcript.gleam index 109c337c9..7e6bd8a65 100644 --- a/src/albedo/daemon/http_transcript.gleam +++ b/src/albedo/daemon/http_transcript.gleam @@ -110,16 +110,24 @@ pub fn project( list.filter(entries, fn(entry) { entry.checkpoint != None }) _ -> entries } - let shown = list.drop(projected, cursor.entry_offset) |> list.take(limit) - let first_position = - list.first(source.entries) - |> result.map(fn(entry) { entry.source.seq }) - |> result.unwrap(cursor.position) + let #(skipped, shown) = case cursor.direction, cursor.entry_offset { + "before", 0 -> newest(projected, limit) + _, offset -> #(offset, list.drop(projected, offset) |> list.take(limit)) + } + let first_position = case cursor.direction, shown { + "before", [first, ..] -> first.position + _, _ -> + list.first(source.entries) + |> result.map(fn(entry) { entry.source.seq }) + |> result.unwrap(cursor.position) + } let last_position = list.last(source.entries) |> result.map(fn(entry) { entry.source.seq }) |> result.unwrap(cursor.position) - let older = case source.has_older { + let older = case + source.has_older || skipped > 0 && cursor.direction == "before" + { True -> token( secret, @@ -139,16 +147,14 @@ pub fn project( ) False -> json.null() } - let newer = case - cursor.entry_offset + list.length(shown) < list.length(projected) - { + let newer = case skipped + list.length(shown) < list.length(projected) { True -> token( secret, id, view, limit, - Cursor(..cursor, entry_offset: cursor.entry_offset + list.length(shown)), + Cursor(..cursor, entry_offset: skipped + list.length(shown)), ) False -> case source.more_continuations { @@ -220,6 +226,36 @@ pub fn project( ) } +/// The newest `limit` entries of a backwards page and how many come before +/// them. A position cut in two is dropped whole, so the older page, which +/// starts before the first shown position, repeats nothing and skips nothing. +fn newest( + projected: List(http_history.Entry), + limit: Int, +) -> #(Int, List(http_history.Entry)) { + let skipped = int.max(0, list.length(projected) - limit) + let tail = list.drop(projected, skipped) + case skipped, tail { + 0, _ | _, [] -> #(skipped, tail) + _, [first, ..] -> { + let cut = + list.drop(projected, skipped - 1) + |> list.first + |> result.map(fn(before) { before.position == first.position }) + |> result.unwrap(False) + let whole = case cut { + True -> + list.drop_while(tail, fn(entry) { entry.position == first.position }) + False -> tail + } + case whole { + [] -> #(skipped, tail) + _ -> #(list.length(projected) - list.length(whole), whole) + } + } + } +} + pub fn history( secret: String, storage: Result(store.Store, String), diff --git a/src/albedo/daemon/http_wire.gleam b/src/albedo/daemon/http_wire.gleam index de39c27fa..9bba98146 100644 --- a/src/albedo/daemon/http_wire.gleam +++ b/src/albedo/daemon/http_wire.gleam @@ -255,6 +255,12 @@ pub fn kernel(observed: session_namespace.KernelObservation) -> json.Json { #("stale", json.bool(observed.stale != None)), #("staleness_reasons", json.preprocessed_array(reasons)), #("live_job_count", json.nullable(observed.live_job_count, json.int)), + #( + "running_jobs", + json.nullable(observed.running_jobs, fn(jobs) { + json.array(jobs, python.job_json) + }), + ), ]) } diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 8e584865d..67265c9a4 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -198,6 +198,7 @@ pub type Message { ) ReadEffort(Subject(Result(json.Json, String))) ChangeEffort(String, Subject(Result(json.Json, String))) + StopJob(String, Subject(Result(Nil, String))) /// Report on the kernel's staleness, or (True) force its swap now. UpgradeKernel(Subject(Result(runtime.KernelUpgrade, String))) UpgradeCompletion( @@ -351,13 +352,22 @@ pub fn start( ), announced_status: None, ) - // Background jobs wake this session through the kernel's jobs route; the + // Background jobs and cells wake through their kernel host routes; the // registered closure lands a completion notice as an ordinary submit, so - // the wake reuses the whole turn pipeline and busy answers itself. - wakes_register(info.id, fn(display, text) { + // the wake reuses the whole turn pipeline and busy answers itself. Its own + // input id keeps the one-line display beside the model's longer notice. + wakes_register(info.id, fn(origin, display, text) { wake( self, - Submission(display, text, "job", turn.JobWake, None, None, None), + Submission( + display, + text, + origin, + turn.JobWake, + None, + Some(mail.new_id()), + None, + ), ) }) commands_register(info.id, fn(op) { command_op(self, host, info.id, op) }) @@ -1229,6 +1239,12 @@ fn handle( Ok(state) -> compact(state, strategy, reply) } } + StopJob(id, reply) -> + case state.kernel { + Some(kernel) -> answer(state, reply, runtime.stop_job(kernel, id)) + None -> + answer(state, reply, Error("no kernel attached to this session")) + } Watch(owner, notify) -> { let watchers = case list.any(state.watchers, fn(watcher) { watcher.owner == owner }) @@ -1826,6 +1842,26 @@ fn command_op( #("failure", json.nullable(report.failure, json.string)), ]) }) + command.KernelJobs -> + capture(session) + |> result.try(fn(captured) { + case captured.kernel.running_jobs { + Some(jobs) -> + Ok( + json.object([ + #("items", json.array(jobs, python.job_json)), + #( + "live_job_count", + json.nullable(captured.kernel.live_job_count, json.int), + ), + ]), + ) + None -> Error("kernel job observation unavailable") + } + }) + command.KernelStopJob(id) -> + actor.call(session, 5000, StopJob(id, _)) + |> result.map(fn(_) { json.object([#("stopped", json.bool(True))]) }) } } @@ -1922,7 +1958,7 @@ fn collect() -> Nil @external(erlang, "albedo_wakes", "register") fn wakes_register( session: String, - submit: fn(String, String) -> run.Wake, + submit: fn(String, String, String) -> run.Wake, ) -> Nil @external(erlang, "albedo_wakes", "forget") diff --git a/src/albedo/daemon/session_namespace.gleam b/src/albedo/daemon/session_namespace.gleam index 44c118e0b..12b6abac6 100644 --- a/src/albedo/daemon/session_namespace.gleam +++ b/src/albedo/daemon/session_namespace.gleam @@ -22,6 +22,7 @@ pub type KernelObservation { stage: Option(String), stale: Option(python.Stale), live_job_count: Option(Int), + running_jobs: Option(List(python.Job)), ) } @@ -49,6 +50,11 @@ pub fn observe_kernel( None, "none" -> Some(0) _, _ -> None }, + case loaded.kernel, phase { + Some(observed), _ -> Some(observed.running_jobs) + None, "none" -> Some([]) + _, _ -> None + }, ), ) } @@ -67,12 +73,13 @@ pub fn observe_kernel( stage, observed.stale, Some(observed.live_job_count), + Some(observed.running_jobs), )) Error(_) -> case runtime.alive(kernel) { True -> Error("kernel observation unavailable") False -> - Ok(KernelObservation(None, None, "lost", stage, None, None)) + Ok(KernelObservation(None, None, "lost", stage, None, None, None)) } } } diff --git a/src/albedo/daemon/session_submission.gleam b/src/albedo/daemon/session_submission.gleam index 19b8c950b..02e17c95f 100644 --- a/src/albedo/daemon/session_submission.gleam +++ b/src/albedo/daemon/session_submission.gleam @@ -93,12 +93,12 @@ pub fn commits( } #(next, case submission.operation_id { None -> - case submission.source { - turn.Mail(id, _) -> [ + case submission.source, submission.submission_id { + turn.Mail(id, _), _ | turn.JobWake, Some(id) -> [ operations.Commit(id, position, display(submission)), ..acc.1 ] - _ -> acc.1 + _, _ -> acc.1 } Some(id) -> [ operations.Commit(id, position, display(submission)), diff --git a/src/albedo/harness/command.gleam b/src/albedo/harness/command.gleam index caff7a72c..500a7bf97 100644 --- a/src/albedo/harness/command.gleam +++ b/src/albedo/harness/command.gleam @@ -66,6 +66,10 @@ pub type StateOp { KernelReport /// Swap a stale kernel now, ending its live jobs as a restart would. KernelUpgrade + /// Active background jobs supervised by the session's kernel. + KernelJobs + /// Terminate one background job by id. + KernelStopJob(id: String) } /// The dispatch context: `state` is the session's registered command bridge. diff --git a/src/albedo/harness/extensions/files/extension.gleam b/src/albedo/harness/extensions/files/extension.gleam index 109dbc8c3..7065c3497 100644 --- a/src/albedo/harness/extensions/files/extension.gleam +++ b/src/albedo/harness/extensions/files/extension.gleam @@ -5,7 +5,7 @@ pub fn extension() -> extension.Extension { "files", "Read, search, and exactly edit workspace files from Python.", "files", - "files.read(path, start_line=, end_line=, limit=) returns complete numbered lines; limit counts lines, and a separate max_chars= budget (default 16000 characters) stops very large windows and says where to resume, files.ls(path, pattern=) lists one directory, files.write(path, content) creates or replaces a whole file, and files.edit(path, old, new) replaces one exact unique string, reporting every occurrence with line ranges when it is not unique; retry it with line_hint=. These return immediately, and awaiting them also works. await files.find(pattern, path_or_paths, glob=, context=N, literal=, case_sensitive=, max_results=50, hidden=, ignored=) searches contents (a regex unless literal=True) with N surrounding lines; a missing root raises, hidden and ignored files are skipped unless hidden=True / ignored=True, and an empty result reports the searched root, file count, what was skipped, and skipped files that would match; and await files.paths(pattern) searches names; both run a background search and must be awaited. Prefer these over rg, grep, find, ls, cat, and sed through run().", + "files.read(path, start_line=, end_line=, limit=) returns complete numbered lines; limit counts lines, and a separate max_chars= budget (default 16000 characters) stops very large windows and says where to resume, files.ls(path, pattern=) lists one directory, files.write(path, content) creates or replaces a whole file, and files.edit(path, old, new) replaces one exact unique string, reporting every occurrence with line ranges when it is not unique; retry it with line_hint=. These return immediately, and awaiting them also works. await files.find(pattern, path_or_paths, glob=, context=N, literal=, case_sensitive=, max_results=50, hidden=, ignored=) searches contents (a regex unless literal=True) with N surrounding lines. A missing root raises, hidden and ignored files are skipped unless hidden=True / ignored=True, and an empty result reports the searched root, file count, what was skipped, and skipped files that would match. await files.paths(pattern) searches names. Both run a background search and must be awaited. Prefer these over rg, grep, find, ls, cat, and sed through run().", ["python", "run"], ) } diff --git a/src/albedo/harness/extensions/paperclips/extension.gleam b/src/albedo/harness/extensions/paperclips/extension.gleam index c161a8e4d..9ae7de182 100644 --- a/src/albedo/harness/extensions/paperclips/extension.gleam +++ b/src/albedo/harness/extensions/paperclips/extension.gleam @@ -55,7 +55,6 @@ pub fn extension() -> harness_extension.Extension { ), ), ]), - harness_extension.GlancePlugin(service.sidebar, service.resource_url), harness_extension.ServicePlugin(harness_extension.Service( fn(_, _) { harness_extension.Admission(harness_extension.DaemonToken, 65_536) diff --git a/src/albedo/harness/extensions/paperclips/ledger.gleam b/src/albedo/harness/extensions/paperclips/ledger.gleam index 187bc5f91..02ead4d6a 100644 --- a/src/albedo/harness/extensions/paperclips/ledger.gleam +++ b/src/albedo/harness/extensions/paperclips/ledger.gleam @@ -483,16 +483,3 @@ pub fn delete_observed( } }) } - -/// A sidebar remains small even when finished records fill the global ledger. -pub fn open(store: Store) -> Result(List(Vent), Error) { - storage.query(store, fn(db) { - rows( - db, - "SELECT " - <> columns - <> " FROM paperclips WHERE status='open' ORDER BY id DESC LIMIT 12", - [], - ) - }) -} diff --git a/src/albedo/harness/extensions/paperclips/service.gleam b/src/albedo/harness/extensions/paperclips/service.gleam index 1d324a1e1..4c3da75c4 100644 --- a/src/albedo/harness/extensions/paperclips/service.gleam +++ b/src/albedo/harness/extensions/paperclips/service.gleam @@ -5,7 +5,6 @@ import albedo/harness/extension import albedo/harness/extensions/paperclips/ledger import albedo/harness/extensions/paperclips/notifications import albedo/harness/extensions/paperclips/presentation -import albedo/harness/page import gleam/dict import gleam/dynamic/decode import gleam/http.{Delete, Get, Patch, Post} @@ -561,32 +560,3 @@ fn glance(items: List(ledger.Vent)) -> json.Json { #("url", json.string("/extensions/paperclips/items")), ]) } - -/// Native composition uses this typed bounded read without executing a command. -pub fn sidebar( - storage: ledger.Store, - _session: String, - _workspace: String, -) -> Result(page.Glance, String) { - use items <- result.try( - ledger.open(storage) - |> result.map_error(fn(error) { failure(error).detail }), - ) - Ok(page.Glance( - "open vents", - list.map(items, fn(item) { - page.detail_row( - int.to_string(item.id), - api.content_preview(presentation.title(item), 64), - ledger.status_name(item.status), - page.Warning, - "", - ) - }), - )) -} - -/// Canonical resource addressed by this extension sidebar. -pub fn resource_url(_session: String, _workspace: String) -> String { - "/extensions/paperclips/items" -} diff --git a/src/albedo/harness/extensions/python/albedo_job_slots.erl b/src/albedo/harness/extensions/python/albedo_job_slots.erl deleted file mode 100644 index 0c664e790..000000000 --- a/src/albedo/harness/extensions/python/albedo_job_slots.erl +++ /dev/null @@ -1,189 +0,0 @@ -%% Heavy-job slots for the whole daemon. Every shell job starts at once; only a -%% job still running after the grace window asks for a slot, so quick commands -%% never wait. A job that cannot get one is paused by its kernel (SIGSTOP) and -%% resumed when a slot frees, so waiting costs no CPU and loses no work. -%% -%% Slots default to the machine's cores and shrink while the load average runs -%% well past them: a heavy job that fans out its own workers leaves less room. -%% A freed slot goes to the kernel holding the fewest, oldest request first, so -%% one busy agent cannot starve the rest. -%% -%% Only confirmed cleanup releases a running lease. If its bridge dies without -%% that proof, keep the slot reserved rather than oversubscribing leaked work. -%% -%% Kernels on another host share that host's own pool instead: sized to the -%% cores its probe reported (ALBEDO_MAX_REMOTE_JOBS overrides), with no load -%% adjustment, since this machine's load average says nothing about it. The -%% local pool starts and watches the host pools; the admission protocol is the -%% same. --module(albedo_job_slots). --behaviour(gen_server). --export([ensure/0, ensure/2, acquire/2, claim/2, release/2, release_owner/1, limit/0]). --export([init/1, handle_call/3, handle_cast/2, handle_info/2]). - --record(state, {base, running = 0, entries = #{}, waiting = [], load = false, ticking = false, hosts = #{}}). --define(MAX_WAITING, 1024). --define(TICK_MS, 2000). -%% Load above this multiple of the cores counts as overload. --define(OVERLOAD, 1.25). - -ensure() -> - case gen_server:start({local, ?MODULE}, ?MODULE, [], []) of - {ok, Pid} -> Pid; - {error, {already_started, Pid}} -> Pid - end. - -%% The pool for kernels on Host, which has Cpus cores. -ensure(Host, Cpus) -> gen_server:call(ensure(), {host, Host, Cpus}). - -acquire(Pool, Id) -> gen_server:cast(Pool, {acquire, self(), Id}). -%% A slot a running job already holds, granted by an earlier daemon: it counts -%% at once, even past the limit, and nothing is sent back. -claim(Pool, Id) -> gen_server:cast(Pool, {claim, self(), Id}). -release(Pool, Id) -> gen_server:cast(Pool, {release, {self(), Id}}). -release_owner(Pool) -> gen_server:cast(Pool, {release_owner, self()}). - -%% The slot count right now, for tests and status. -limit() -> gen_server:call(ensure(), limit). - -init([{host, Cpus}]) -> {ok, #state{base = remote_base(Cpus)}}; -init([]) -> - Cores = case erlang:system_info(logical_processors_available) of - N when is_integer(N), N > 0 -> N; - _ -> erlang:system_info(schedulers_online) - end, - Base = try list_to_integer(os:getenv("ALBEDO_MAX_LOCAL_JOBS", "")) of - N2 when N2 > 0 -> min(256, N2); - _ -> Cores - catch _:_ -> Cores end, - %% The load average comes from os_mon; without it the base stands alone. - %% ALBEDO_JOB_LOAD=0 turns the adjustment off, for a fixed count. - %% Only the load average is wanted: no disk or memory monitors and their alarms. - Load = os:getenv("ALBEDO_JOB_LOAD") =/= "0" andalso - try - _ = application:load(os_mon), - [application:set_env(os_mon, K, false) - || K <- [start_disksup, start_memsup, start_os_sup]], - {ok, _} = application:ensure_all_started(os_mon, temporary), - true - catch _:_ -> false - end, - {ok, #state{base = Base, load = Load}}. - -handle_call(limit, _, S) -> {reply, effective(S), S}; -handle_call({host, Host, Cpus}, _, S = #state{hosts = Hosts}) -> - case maps:find(Host, Hosts) of - {ok, Pool} -> - %% A pool opened while the host was out of reach learns its cores - %% from the first kernel that probed it. - Cpus > 0 andalso gen_server:cast(Pool, {base, Cpus}), - {reply, Pool, S}; - error -> - {ok, Pool} = gen_server:start(?MODULE, [{host, Cpus}], []), - monitor(process, Pool), - {reply, Pool, S#state{hosts = Hosts#{Host => Pool}}} - end; -handle_call(_, _, S) -> {reply, {error, unsupported}, S}. - -handle_cast({acquire, Owner, Id}, S = #state{entries = Entries}) -> - Key = {Owner, Id}, - case {maps:is_key(Key, Entries), length(S#state.waiting) >= ?MAX_WAITING} of - {true, _} -> {noreply, S}; - {false, true} -> - Owner ! {job_slot, Id, {error, <<"heavy job queue is full">>}}, - {noreply, S}; - {false, false} -> - Mon = monitor(process, Owner), - S1 = drain(S#state{entries = Entries#{Key => {waiting, Mon}}, - waiting = S#state.waiting ++ [Key]}), - %% Not granted on the spot: say so, so the kernel pauses the job. - case maps:get(Key, S1#state.entries) of - {waiting, _} -> Owner ! {job_slot, Id, queued}; - _ -> ok - end, - {noreply, tick(S1)} - end; -handle_cast({claim, Owner, Id}, S = #state{entries = Entries, running = Running}) -> - Key = {Owner, Id}, - case maps:is_key(Key, Entries) of - true -> {noreply, S}; - false -> - Mon = monitor(process, Owner), - {noreply, S#state{entries = Entries#{Key => {active, Mon}}, running = Running + 1}} - end; -handle_cast({release, Key}, S) -> {noreply, drain(drop(Key, S))}; -handle_cast({base, Cpus}, S) -> {noreply, drain(S#state{base = remote_base(Cpus)})}; -handle_cast({release_owner, Owner}, S) -> - {noreply, drop_keys([K || {P, _} = K := _ <- S#state.entries, P =:= Owner], S)}. - -handle_info(tick, S) -> - {noreply, tick(drain(S#state{ticking = false}))}; -handle_info({'DOWN', Mon, process, Pid, _}, S = #state{hosts = Hosts}) -> - case [Host || Host := Pool <- Hosts, Pool =:= Pid] of - [Host | _] -> {noreply, S#state{hosts = maps:remove(Host, Hosts)}}; - %% A waiting request owns no running work; active ones need cleanup proof. - [] -> {noreply, drop_keys([K || {P, _} = K := {waiting, Ref} <- S#state.entries, - P =:= Pid, Ref =:= Mon], S)} - end; -handle_info(_, S) -> {noreply, S}. - -%% A host pool's size: ALBEDO_MAX_REMOTE_JOBS, else the host's cores, else -%% (cores still unknown) two. -remote_base(Cpus) -> - Default = case Cpus > 0 of true -> Cpus; false -> 2 end, - try list_to_integer(os:getenv("ALBEDO_MAX_REMOTE_JOBS", "")) of - N when N > 0 -> min(256, N); - _ -> Default - catch _:_ -> Default - end. - -drop_keys(Keys, S) -> drain(lists:foldl(fun drop/2, S, Keys)). - -%% While anything waits, look again now and then: the load may have fallen. -tick(S = #state{waiting = [_ | _], ticking = false}) -> - erlang:send_after(?TICK_MS, self(), tick), - S#state{ticking = true}; -tick(S) -> S. - -effective(#state{base = Base, load = false}) -> Base; -effective(#state{base = Base}) -> - Load = try cpu_sup:avg1() / 256 catch _:_ -> 0.0 end, - Excess = Load - Base * ?OVERLOAD, - if Excess > 0 -> max(1, Base - ceil(Excess)); true -> Base end. - -drop(Key, S = #state{entries = Entries, running = Running, waiting = Waiting}) -> - case maps:take(Key, Entries) of - error -> S; - {{State, Mon}, Rest} -> - demonitor(Mon, [flush]), - case State of - active -> S#state{entries = Rest, running = Running - 1}; - waiting -> S#state{entries = Rest, waiting = lists:delete(Key, Waiting)} - end - end. - -drain(S = #state{waiting = []}) -> S; -drain(S = #state{running = N}) -> - case N >= effective(S) of - true -> S; - false -> - Key = {Owner, Id} = fairest(S), - {waiting, Mon} = maps:get(Key, S#state.entries), - Waiting = lists:delete(Key, S#state.waiting), - case is_process_alive(Owner) of - false -> drain(drop(Key, S)); - true -> - Owner ! {job_slot, Id, ok}, - drain(S#state{waiting = Waiting, running = N + 1, - entries = (S#state.entries)#{Key => {active, Mon}}}) - end - end. - -%% The oldest request from the kernel that holds the fewest slots. -fairest(#state{waiting = Waiting, entries = Entries}) -> - Held = maps:fold(fun({Owner, _}, {active, _}, Acc) -> maps:update_with(Owner, fun(C) -> C + 1 end, 1, Acc); - (_, _, Acc) -> Acc - end, #{}, Entries), - {_, Key} = lists:min([{{maps:get(Owner, Held, 0), Index}, Key} - || {Index, Key = {Owner, _}} <- lists:enumerate(Waiting)]), - Key. diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 94f86b03c..426457f74 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -16,7 +16,7 @@ %% and it returns a structured verdict instead of kill(1) exit statuses the %% supervisor would have to guess at. -module(albedo_python). --export([start/1, execute/3, interrupt/1, stop/1, detach/1, events/1, alive/1, os_pid/1, job_count/1, local_paths/0, paths/0, grace/0, rebind/2, clean_environment/0]). +-export([start/1, execute/3, interrupt/1, stop/1, detach/1, events/1, alive/1, os_pid/1, job_count/1, stop_job/2, local_paths/0, paths/0, grace/0, rebind/2, clean_environment/0]). -export([stale/1, mark_stale/2]). -export([observation/1, stop_recorded/2, stop_jobs/1]). @@ -45,16 +45,11 @@ start({boot, Owner, Python, Bridge, Cwd, Host, Modules, Link, RunDir, Kernel, To {Pid, Mon} = spawn_monitor(fun() -> process_flag(trap_exit, true), monitor(process, Owner), - Pool = case Remote of - {some, {remote, _, Machine, Cpus}} -> albedo_job_slots:ensure(Machine, Cpus); - none -> albedo_job_slots:ensure() - end, - monitor(process, Pool), %% What the record says the kernel owned, so a kernel found dead at %% this attach still has its groups ended. {Target, Groups} = owned(Owned), S = #{port => none, host => Host, link => Link, owner => Owner, active => none, events => [], - groups => Groups, external => 0, pool => Pool, slots => #{}, target => Target, + groups => Groups, external => 0, cells => 0, target => Target, python => Python, bridge => Bridge, cwd => Cwd, remote => Remote, modules => Modules, run_dir => RunDir, kernel => Kernel, token => Token, grace => Grace, in => 0, acked => 0, kack => 0, out => OutSeq, @@ -85,8 +80,8 @@ open_bridge(S = #{python := Python, bridge := Bridge, run_dir := RunDir}, Mode) {Exe, Argv, Dir, Env, First} = case maps:get(remote, S) of none -> {Python, [<<"-u">>, Bridge | Args], Cd, - [{"ALBEDO_JOB_ADMISSION", "1"} | lists:keydelete("ALBEDO_JOB_ADMISSION", 1, clean_environment())], []}; - {some, {remote, {commands, _, Command, _, _, _, _}, _, _}} -> + clean_environment(), []}; + {some, {remote, {commands, _, Command, _, _, _, _}, _}} -> Spec = case Mode of start -> #{argv => Args, cwd => Cd}; attach -> #{argv => Args} @@ -138,7 +133,6 @@ startup(S = #{port := Port}, Mode, Parent, Ref, Deadline) -> invalid -> startup_fail(S, Parent, Ref, {unavailable, <<"invalid kernel handshake">>}) end; {host_reply, Id, Reply} -> startup(host_reply(Id, Reply, S), Mode, Parent, Ref, Deadline); - {job_slot, Id, Result} -> startup(slot_reply(Id, Result, S), Mode, Parent, Ref, Deadline); flush_ack -> startup(flush_ack(S), Mode, Parent, Ref, Deadline); {Port, {data, _}} -> startup_fail(S, Parent, Ref, {unavailable, <<"invalid kernel handshake">>}); {Port, {exit_status, ?GONE}} when Mode =:= attach -> startup_fail(S#{port => none}, Parent, Ref, lost); @@ -182,13 +176,20 @@ startup_fail(S, Parent, Ref, Error) -> execute(Pid, Data, Timeout) -> call(Pid, {execute, Data, Timeout}). %% Background jobs whose groups are still owned: local job groups plus the -%% remote jobs the remote plugin reported through "jobs" frames. A released -%% kernel would kill them, so the idle sweep keeps such kernels alive. +%% remote jobs the remote plugin reported through "jobs" frames, plus running +%% cells. A released kernel would end them, so the idle sweep keeps it alive. job_count(Pid) -> case call(Pid, job_count) of {ok, Count} when is_integer(Count), Count >= 0 -> Count; _ -> 0 end. +stop_job(Pid, Id) -> + case call(Pid, {stop_job, Id}) of + ok -> {ok, nil}; + {error, not_found} -> {error, <<"job not found">>}; + {error, Reason} -> {error, detail(Reason)}; + _ -> {error, <<"could not stop job">>} + end. events(Pid) -> case call(Pid, events) of {ok, Events} -> Events; _ -> [] end. interrupt(Pid) -> Pid ! interrupt, nil. @@ -288,7 +289,7 @@ loop(S = #{port := Port, active := Active}) -> end, From ! {Ref, Reply}, loop(S); {call, From, Ref, job_count} -> - Count = maps:size(maps:merge(maps:get(groups, S), maps:get(slots, S))) + maps:get(external, S, 0), + Count = maps:size(maps:get(groups, S)) + maps:get(external, S, 0) + maps:get(cells, S, 0), From ! {Ref, {ok, Count}}, loop(S); {call, From, Ref, observation} -> Build = case maps:get(kernel_bundle, S) of @@ -296,11 +297,18 @@ loop(S = #{port := Port, active := Active}) -> _ -> none end, Stale = case maps:get(stale, S) of none -> none; Reason -> {some, Reason} end, - Jobs = maps:merge(maps:get(groups, S), maps:get(slots, S)), + Jobs = maps:get(groups, S), Count = maps:size(Jobs) + maps:get(external, S, 0), JobIds = lists:sublist(lists:sort(maps:keys(Jobs)), 200), - From ! {Ref, {observation, maps:get(kernel, S), Build, Port =/= none, Stale, Count, JobIds}}, + From ! {Ref, {observation, maps:get(kernel, S), Build, Port =/= none, Stale, Count, JobIds, job_summaries(maps:get(groups, S))}}, loop(S); + {call, From, Ref, {stop_job, Id}} -> + Reply = case maps:get(Id, maps:get(groups, S), none) of + none -> {error, not_found}; + Group -> + verdict(supervise(S, [target_spec(<<"job ", Id/binary>>, Group)], ?TERM_MS, ?KILL_MS)) + end, + From ! {Ref, Reply}, loop(S); {call, From, Ref, {rebind, Host}} when is_function(Host, 1) -> From ! {Ref, {ok, nil}}, loop(S#{host => Host}); {call, From, Ref, events} -> @@ -366,7 +374,6 @@ loop(S = #{port := Port, active := Active}) -> reattach when Port =:= none -> reattach(S); flush_ack -> loop(flush_ack(S)); {host_reply, Id, Reply} -> loop(host_reply(Id, Reply, S)); - {job_slot, Id, Result} -> loop(slot_reply(Id, Result, S)); {'DOWN', Caller, process, _, _} -> case Active of {_, _, _, Caller, _} -> loop(interrupt_active(S, <<"cancelled">>)); @@ -405,7 +412,7 @@ reattach(S) -> attach_again(S). %% A remote kernel unreachable for longer than its grace has exited by itself %% and reaped its own jobs: forget it without reaching for the host again. -expire(S = #{pool := Pool}) -> +expire(S) -> case maps:get(active, S) of {From, Ref, Timer, Caller, _} -> erlang:cancel_timer(Timer), demonitor(Caller, [flush]), @@ -413,7 +420,6 @@ expire(S = #{pool := Pool}) -> none -> ok end, link_forget(S), - albedo_job_slots:release_owner(Pool), nil. attach_again(S = #{retries := Tries}) -> @@ -473,16 +479,14 @@ hello(Hello, S0) -> leader => maps:get(leader, Target), epoch => maps:get(<<"epoch">>, Hello, 0)}), Jobs = [Job || Job <- maps:get(<<"jobs">>, Hello, []), is_map(Job)], S1 = lists:foldl(fun track/2, S#{target => Target}, Jobs), - S2 = case maps:get(<<"external">>, Hello, 0) of - Live when is_integer(Live), Live >= 0 -> S1#{external => Live}; - _ -> S1 + Cells = case maps:get(<<"cells">>, Hello, 0) of + N when is_integer(N), N >= 0 -> N; + _ -> 0 end, - %% Slots its running jobs hold count again in this daemon's pool; the - %% ones still waited for are asked for again. - Untracked = fun(Field) -> [Id || Id <- maps:get(Field, Hello, []), is_binary(Id), - not maps:is_key(Id, maps:get(slots, S2))] end, - S3 = lists:foldl(fun claim_slot/2, S2, Untracked(<<"held">>)), - lists:foldl(fun acquire_slot/2, S3, Untracked(<<"slots">>)). + case maps:get(<<"external">>, Hello, 0) of + Live when is_integer(Live), Live >= 0 -> S1#{external => Live, cells => Cells}; + _ -> S1#{cells => Cells} + end. %% A kernel speaking another protocol, or running another bundle than the %% bridge that reached it, is stale: the session swaps it at its next idle @@ -529,10 +533,11 @@ handle_frame(#{<<"type">> := <<"call">>, <<"id">> := Id} = Message, S = #{host : spawn(fun() -> Parent ! {host_reply, Id, host_call(Host, Message)} end), S#{calls => Calls#{Id => true}} end; -handle_frame(#{<<"type">> := <<"job_acquire">>, <<"id">> := Id}, S) when is_binary(Id) -> - acquire_slot(Id, S); handle_frame(#{<<"type">> := <<"job">>} = Message, S) -> journal(Message, track(Message, S)); +handle_frame(#{<<"type">> := <<"cells">>, <<"live">> := Live}, S) + when is_integer(Live), Live >= 0 -> + S#{cells => Live}; handle_frame(#{<<"type">> := <<"jobs">>, <<"live">> := Live}, S) when is_integer(Live), Live >= 0 -> S#{external => Live}; @@ -547,32 +552,6 @@ host_reply(Id, Reply, S = #{calls := Calls, out := Out}) -> write_envelope(S, Seq, Frame), S#{calls => maps:remove(Id, Calls), out => Seq, acked => maps:get(in, S)}. -acquire_slot(Id, S = #{pool := Pool, slots := Slots}) -> - albedo_job_slots:acquire(Pool, Id), - S#{slots => Slots#{Id => true}}. - -claim_slot(Id, S = #{pool := Pool, slots := Slots}) -> - albedo_job_slots:claim(Pool, Id), - S#{slots => Slots#{Id => true}}. - -slot_reply(Id, Result, S = #{slots := Slots}) -> - case maps:is_key(Id, Slots) of - false -> S; %% cancelled before the grant reached us - true -> - Reply = case Result of - ok -> #{ok => true}; - %% No slot yet: the kernel pauses the job until one frees. - queued -> #{ok => false, queued => true}; - {error, Why} -> #{ok => false, message => Why} - end, - S1 = send(Reply#{type => <<"job_slot">>, id => Id}, S), - case Result of {error, _} -> release_slot(Id, S1); _ -> S1 end - end. - -release_slot(Id, S = #{pool := Pool, slots := Slots}) -> - albedo_job_slots:release(Pool, Id), - S#{slots => maps:remove(Id, Slots)}. - %% One host call's decoded reply, with the fixed fallback when the host itself %% fails to answer. host_call(Host, Message) -> @@ -581,12 +560,12 @@ host_call(Host, Message) -> %% Job ownership bookkeeping shared by the main loop and the startup and %% shutdown drains: a started job's group is recorded; a job proven gone -%% releases its slot and its group. +%% releases its group. start_job(Message, Id, S = #{groups := Groups}) -> owns(S, Groups#{Id => group_of(Message)}). gone(Id, S = #{groups := Groups}) -> - owns(release_slot(Id, S), maps:remove(Id, Groups)). + owns(S, maps:remove(Id, Groups)). %% The groups are recorded as they change, so a daemon that finds the kernel %% dead after a restart can still end them. @@ -603,7 +582,7 @@ nil_null(_, V) -> V. owned(Owned) -> M = try json:decode(Owned) catch _:_ -> #{} end, Spec = fun(Fields) -> maps:map(fun(_, null) -> nil; (_, V) -> V end, - maps:with([<<"pid">>, <<"pgid">>, <<"leader">>], Fields)) end, + maps:with([<<"pid">>, <<"pgid">>, <<"leader">>, <<"command">>], Fields)) end, Target = case maps:get(<<"pid">>, M, null) of Pid when is_integer(Pid), Pid > 1 -> target_of(Spec(M)); _ -> none @@ -680,7 +659,7 @@ shutdown_state(S = #{target := Target}, TermMs, KillMs) -> #{port := none} -> S; _ -> send(#{type => <<"shutdown">>}, S) end, - Jobs = maps:merge(maps:get(groups, S1), maps:get(slots, S1)), + Jobs = maps:get(groups, S1), {Settled, ShutdownJobs} = case maps:get(exited, S1, false) orelse maps:get(port, S1) =:= none of true -> {S1, Jobs}; false -> await_exit(S1, erlang:monotonic_time(millisecond) + ?SHUTDOWN_GRACE, Jobs) @@ -697,7 +676,7 @@ abandon(S) -> report(owner_lost, shutdown(S, ?TERM_MS, ?KILL_MS)). %% Keep accepting ownership transfers while shutdown is in flight. A job may %% finish spawning after the shutdown request was sent. await_exit(S = #{port := Port}, Deadline, Jobs) -> - Known = maps:merge(Jobs, maps:merge(maps:get(groups, S), maps:get(slots, S))), + Known = maps:merge(Jobs, maps:get(groups, S)), Now = erlang:monotonic_time(millisecond), case Now >= Deadline of true -> {S, Known}; @@ -725,7 +704,6 @@ track(#{<<"type">> := <<"job">>, <<"id">> := Id} = Message, S) -> none -> S; %% unverified: keep owning the group Cleanup -> log({job_cleanup_failed, Id, Cleanup}), S end; -track(#{<<"type">> := <<"job_cancel">>, <<"id">> := Id}, S) -> release_slot(Id, S); track(#{<<"type">> := <<"cleanup">>, <<"failures">> := Failures}, S) -> log({kernel_cleanup_failed, Failures}), S; track(_, S) -> S. @@ -739,7 +717,7 @@ supervise(_, [], _, _) -> {ok, []}; supervise(S, Targets, TermMs, KillMs) -> Request = iolist_to_binary(json:encode(#{targets => Targets, term_ms => TermMs, kill_ms => KillMs})), case S of - #{remote := {some, {remote, {commands, _, _, Signal, _, _, _}, Host, _}}} -> + #{remote := {some, {remote, {commands, _, _, Signal, _, _, _}, Host}}} -> {Ssh, Argv, _, Env} = ssh_command(S, Signal), case run_helper(Ssh, Argv, Env, ?REMOTE_HELPER_WAIT, [Request, $\n]) of {error, Reason} -> {error, iolist_to_binary([<<"ending the kernel on ">>, Host, <<" over ssh failed, so its own grace exit is left to end it: ">>, Reason])}; @@ -768,7 +746,7 @@ run_helper(Exe, Args, Env, Wait, Input) -> %% ssh to a remote kernel's host, running one of the commands albedo_ssh.py %% built for it: the executable, its arguments, the local directory and the %% environment. Nothing is quoted here. -ssh_command(#{remote := {some, {remote, {commands, [Ssh | Options], _, _, _, _, AuthSock}, _, _}}}, Command) -> +ssh_command(#{remote := {some, {remote, {commands, [Ssh | Options], _, _, _, _, AuthSock}, _}}}, Command) -> Exe = case os:find_executable(binary_to_list(Ssh)) of false -> Ssh; Found -> unicode:characters_to_binary(Found) @@ -781,7 +759,7 @@ ssh_command(#{remote := {some, {remote, {commands, [Ssh | Options], _, _, _, _, %% A remote kernel's run directory goes with a short ssh command; the kernel %% exits within a second of it disappearing, as a local one does. -remove_run_dir(S = #{remote := {some, {remote, {commands, _, _, _, Remove, _, _}, _, _}}, run_dir := RunDir}) -> +remove_run_dir(S = #{remote := {some, {remote, {commands, _, _, _, Remove, _, _}, _}}, run_dir := RunDir}) -> {Ssh, Argv, _, Env} = ssh_command(S, Remove), _ = run_helper(Ssh, Argv, Env, ?REMOTE_HELPER_WAIT, [RunDir, $\n]), ok; @@ -839,9 +817,17 @@ detail_text(Detail) -> io_lib:format(" (~ts)", [Detail]). %% Identity the kernel declared for itself; a port's os_pid is trustworthy only %% while that port is alive. target_of(M) -> proc_spec(maps:get(<<"pid">>, M, nil), M). -group_of(M) -> proc_spec(maps:get(<<"pgid">>, M, nil), M). +group_of(M) -> + Pid = case maps:get(<<"pid">>, M, nil) of + nil -> maps:get(<<"pgid">>, M, nil); + P -> P + end, + proc_spec(Pid, M). proc_spec(Pid, M) -> - #{pid => Pid, pgid => maps:get(<<"pgid">>, M, nil), leader => maps:get(<<"leader">>, M, nil)}. + #{pid => Pid, + pgid => maps:get(<<"pgid">>, M, nil), + leader => maps:get(<<"leader">>, M, nil), + command => maps:get(<<"command">>, M, <<>>)}. target_spec(Label, #{pid := Pid, pgid := Pgid, leader := Leader}) -> Base = #{label => iolist_to_binary(Label), pid => Pid, pgid => Pgid}, @@ -870,14 +856,13 @@ reap_start(S = #{port := Port}) -> report(startup_reaped, reap_finish(S, Result)). %% The kernel is gone for good: its durable link and run directory go too. -reap_finish(S = #{pool := Pool, port := Port}, Result) -> +reap_finish(S = #{port := Port}, Result) -> close_port(Port), case Result of ok -> case link_forget(S) of {ok, nil} -> remove_run_dir(S), - albedo_job_slots:release_owner(Pool), ok; {error, Reason} -> {error, <<"kernel ownership cleanup failed: ", Reason/binary>>}; _ -> {error, <<"kernel ownership cleanup was not confirmed">>} @@ -925,7 +910,7 @@ grace() -> clean_environment() -> %% Strip daemon internal tokens (e.g. ALBEDO_TOKEN, ALBEDO_API_KEY) and %% provider keys, keeping the user's shell/tool environment intact. - SafeAlbedo = ["ALBEDO_HOME", "ALBEDO_SSH", "ALBEDO_JOB_GRACE_SECONDS", "ALBEDO_JOB_ADMISSION"], + SafeAlbedo = ["ALBEDO_HOME", "ALBEDO_SSH", "ALBEDO_CELL_BACKGROUND_SECONDS"], SecretSuffixes = ["_API_KEY", "_TOKEN"], IsBlocked = fun(Name) -> case lists:prefix("ALBEDO_", Name) of @@ -934,3 +919,12 @@ clean_environment() -> end end, [{Name, false} || Entry <- os:getenv(), Name <- [hd(string:split(Entry, "="))], IsBlocked(Name)]. + +job_summaries(Jobs) -> + [{job, Id, + case maps:get(pid, Group, nil) of + P when is_integer(P), P > 0 -> {some, P}; + _ -> none + end, + unicode:characters_to_binary(lists:sublist(unicode:characters_to_list(maps:get(command, Group, <<>>)), 4096))} + || {Id, Group} <- lists:sublist(lists:sort(maps:to_list(Jobs)), 100)]. diff --git a/src/albedo/harness/extensions/python/cells.gleam b/src/albedo/harness/extensions/python/cells.gleam index 7a2eb58b0..690146724 100644 --- a/src/albedo/harness/extensions/python/cells.gleam +++ b/src/albedo/harness/extensions/python/cells.gleam @@ -139,8 +139,8 @@ pub fn finish( } /// Record how an execution ended, unless it has not: a cell that outlived -/// its deadline while the kernel was out of reach stays started, and the -/// kernel's own result finishes it when it arrives. +/// its deadline while out of reach, or returns early as backgrounded, stays +/// started until the kernel records its final result. pub fn settle( storage: store.Store, id: String, @@ -148,6 +148,7 @@ pub fn settle( ) -> Result(Nil, String) { case outcome { Error(python.Detached) -> Ok(Nil) + Ok(python.Outcome(status: python.Backgrounded, ..)) -> Ok(Nil) _ -> finish(storage, id, outcome) } } diff --git a/src/albedo/harness/extensions/python/extension.gleam b/src/albedo/harness/extensions/python/extension.gleam index 6a5a5162e..f0d8b0636 100644 --- a/src/albedo/harness/extensions/python/extension.gleam +++ b/src/albedo/harness/extensions/python/extension.gleam @@ -24,7 +24,7 @@ const default_timeout_ms = 300_000 fn definition() -> types.Tool { types.Tool( "python", - "Execute Python in your persistent session. Provide code (string); timeout_ms (integer, 1–3600000) is optional and defaults to 300000. Top-level await works. Variables stay alive. Only printed output and the final expression return; duration is the cell's wall seconds; truncated=true means the output passed the 64 KiB preview, and the rest (up to 1 MiB) is readable with output.read(cell_id, offset=65536) while the cell is among the 16 most recent; read it before running many more cells, or print less. Failed cells are retained: await cells.read(id) for bounded source, await cells.info(id) for its status (ok, error, interrupted, started, saved) without source, await cells.trace(id) for what the cell read, ran and changed. Repair exact unique text without resending the source with await cells.run(id, replacements=[(old,new)]), or pass check=True first to compile the rewrite and get the syntax error back without running anything. A cell that started requires allow_partial=True after checking side effects; never retry blindly.", + "Execute Python in your persistent session. Provide code (string); timeout_ms (integer, 1–3600000) is optional and defaults to 300000. Cells still running after 60 seconds return status=backgrounded and keep running under their cell id, with the original timeout_ms deadline. The session wakes automatically when they finish: do not poll or sleep. Do other useful work without changing variables the running cell uses, or give the user a short status report and end your turn. await cells.cancel(id) cancels a running cell and suppresses its wake. Read finished results with output.read(id) and await cells.info(id); reading output, source, status, or trace after completion suppresses its wake. Top-level await works. Variables stay alive. If you shadow an injected helper (files, run, cells, etc.), delete that variable with del files to recover the original binding. Only printed output and the final expression return; duration is the cell's wall seconds; truncated=true means the output passed the 64 KiB preview, and the rest (up to 1 MiB) is readable with output.read(cell_id, offset=65536) while the cell is among the 16 most recent; read it before running many more cells, or print less. Failed cells are retained: await cells.read(id) for bounded source, await cells.info(id) for its status (ok, error, interrupted, started, saved) without source, await cells.trace(id) for what the cell read, ran and changed. Repair exact unique text without resending the source with await cells.run(id, replacements=[(old,new)]), or pass check=True first to compile the rewrite and get the syntax error back without running anything. A cell that started requires allow_partial=True after checking side effects; never retry blindly.", json.object([ #("type", json.string("object")), #("additionalProperties", json.bool(False)), @@ -181,7 +181,7 @@ pub fn extension() -> extension.Extension { ]), extension.ContextPlugin(place.context), extension.ToolPlugin( - "Python has a persistent namespace, top-level await, cells.read/info/trace and cells.run for saved-source repair (all async), and output.read/output.list for bounded retained output (synchronous; awaiting them also works). cells.last_id is the id of the latest cell, and await cells.list(limit=20) lists this session's cells newest first with their status and first line, even after their output has rolled out. output.read(id, offset=0, limit=4000) returns up to limit characters. output.list() names every retained channel, which is also how to find earlier cells: cells, background jobs, and 'native' for bytes written to fd 1/2 while no cell was running. show_image(source) returns a PNG, JPEG, or WebP (bytes or a file path) to you with this cell's result, so you see it after the cell ends; at most 4 images and 5 MiB per cell.", + "Python cells automatically background after 60 seconds; the session wakes when they finish, so do not poll or sleep. Python has a persistent namespace, top-level await, cells.read/info/trace and cells.run for saved-source repair (all async), and output.read/output.list for bounded retained output (synchronous; awaiting them also works). cells.last_id is the id of the latest cell, and await cells.list(limit=20) lists this session's cells newest first with their status and first line, even after their output has rolled out. output.read(id, offset=0, limit=4000) returns up to limit characters. output.list() names every retained channel, which is also how to find earlier cells: cells, background jobs, and 'native' for bytes written to fd 1/2 while no cell was running. show_image(source) returns a PNG, JPEG, or WebP (bytes or a file path) to you with this cell's result, so you see it after the cell ends; at most 4 images and 5 MiB per cell.", [extension.Tool(definition(), invoke, recover)], [], [#("cells", cells.handle)], diff --git a/src/albedo/harness/extensions/python/kernel.gleam b/src/albedo/harness/extensions/python/kernel.gleam index 4d31ea31c..fc211dfac 100644 --- a/src/albedo/harness/extensions/python/kernel.gleam +++ b/src/albedo/harness/extensions/python/kernel.gleam @@ -28,6 +28,7 @@ pub type Observation { stale: Option(Stale), live_job_count: Int, job_ids: List(String), + running_jobs: List(Job), ) } @@ -48,14 +49,16 @@ pub type Status { Succeeded Failed Interrupted + Backgrounded } -/// The wire name of a cell's end state. +/// The wire name of a cell result's status. pub fn status_name(status: Status) -> String { case status { Succeeded -> "ok" Failed -> "error" Interrupted -> "interrupted" + Backgrounded -> "backgrounded" } } @@ -98,10 +101,9 @@ type Boot { } /// How the port owner reaches a kernel on another host: the commands it -/// runs there over ssh, and the host's cores for its own heavy-job pool (0 -/// while unknown). +/// runs there over ssh. type Remote { - Remote(commands: ssh.Commands, host: String, cpus: Int) + Remote(commands: ssh.Commands, host: String) } /// A remote workspace's host as a boot finds it: probed now, or out of reach @@ -157,6 +159,7 @@ fn run( #("code", json.string(code)), #("durable", json.bool(durable)), #("max_edge", json.int(max_edge)), + #("timeout_ms", json.int(timeout_ms)), ]) |> json.to_string use response <- result.try(execute_native(kernel, command, timeout_ms)) @@ -263,11 +266,27 @@ fn saved_decoder() -> decode.Decoder(Result(Saved, Error)) { @external(erlang, "albedo_python", "os_pid") pub fn os_pid(kernel: Kernel) -> Result(Int, Nil) +pub type Job { + Job(id: String, pid: Option(Int), command: String) +} + +pub fn job_json(job: Job) -> json.Json { + json.object([ + #("id", json.string(job.id)), + #("pid", json.nullable(job.pid, json.int)), + #("command", json.string(job.command)), + ]) +} + /// Live background jobs the kernel still supervises, local groups plus remote /// jobs its remote plugin reported. Zero when the kernel cannot answer. @external(erlang, "albedo_python", "job_count") pub fn job_count(kernel: Kernel) -> Int +/// Stop one background job's process group. +@external(erlang, "albedo_python", "stop_job") +pub fn stop_job(kernel: Kernel, id: String) -> Result(Nil, String) + @external(erlang, "albedo_python", "interrupt") pub fn interrupt(kernel: Kernel) -> Nil @@ -314,7 +333,7 @@ pub fn stop_recorded_instance( |> result.replace_error("invalid recorded remote run directory"), ) ssh.offline(target, home) - |> result.map(fn(commands) { Some(Remote(commands, target, 0)) }) + |> result.map(fn(commands) { Some(Remote(commands, target)) }) } Ok(location.Local(_)) -> Ok(None) Error(_) -> Error("invalid recorded kernel location") @@ -371,6 +390,7 @@ pub fn outcome_decoder() -> decode.Decoder(Outcome) { "ok" -> decode.success(outcome(Succeeded)) "error" -> decode.success(outcome(Failed)) "interrupted" -> decode.success(outcome(Interrupted)) + "backgrounded" -> decode.success(outcome(Backgrounded)) _ -> decode.failure(outcome(Failed), "cell status") } } @@ -617,7 +637,7 @@ fn place( ) case ssh.ready(target, ssh.boot_wait_ms) { Ok(host) -> { - let remote = Remote(host.commands, target, host.cpus) + let remote = Remote(host.commands, target) Ok(#(path, Ok(host.home <> remote_runs), Some(Probed(remote)))) } Error(ssh.Unsupported(_) as failure) -> @@ -651,7 +671,7 @@ fn reached( |> result.replace_error(Unavailable("can't reach " <> target)), ) ssh.offline(target, home) - |> result.map(fn(commands) { Some(Remote(commands, target, 0)) }) + |> result.map(fn(commands) { Some(Remote(commands, target)) }) |> result.map_error(Unavailable) } } diff --git a/src/albedo/harness/extensions/python/rpc.gleam b/src/albedo/harness/extensions/python/rpc.gleam index bec8190b0..c51a25a8e 100644 --- a/src/albedo/harness/extensions/python/rpc.gleam +++ b/src/albedo/harness/extensions/python/rpc.gleam @@ -32,6 +32,19 @@ pub fn handle(store: work.Store, session: String, request: String) -> String { "unknown cells operation", fn(method, args) { case method { + "cells.completed" -> { + let decoder = { + use display <- decode.field("display", decode.string) + use text <- decode.field("text", decode.string) + decode.success(#(display, text)) + } + use #(display, text) <- result.try(parse(args, decoder)) + case deliver(session, "cell", display, text) { + Delivered -> Ok(json.string("delivered")) + Busy -> Error("session is busy") + Unavailable(reason) -> Error(reason) + } + } "cells.list" -> { let limit = decode.run( @@ -55,7 +68,12 @@ pub fn handle(store: work.Store, session: String, request: String) -> String { _ -> Error("unknown cells operation") } }, - fn(message) { #("cell", message) }, + fn(message) { + case message { + "session is busy" -> #("busy", message) + _ -> #("cell", message) + } + }, ) } @@ -149,7 +167,7 @@ fn cells( )) case outcome.id == id { True -> - journal.finish(store, id, Ok(outcome)) + journal.settle(store, id, Ok(outcome)) |> result.replace(json.null()) False -> Error("cell result id differs") } @@ -182,3 +200,17 @@ fn to_json(cell: journal.Cell) -> json.Json { #("duration", json.nullable(duration(cell), json.float)), ]) } + +type Wake { + Delivered + Busy + Unavailable(String) +} + +@external(erlang, "albedo_wakes", "deliver") +fn deliver( + session: String, + origin: String, + display: String, + text: String, +) -> Wake diff --git a/src/albedo/harness/extensions/run/extension.gleam b/src/albedo/harness/extensions/run/extension.gleam index 86114eef9..6d55b237a 100644 --- a/src/albedo/harness/extensions/run/extension.gleam +++ b/src/albedo/harness/extensions/run/extension.gleam @@ -1,12 +1,17 @@ //// Start supervised programs from Python, without a shell. import albedo/daemon/store +import albedo/harness/client_api +import albedo/harness/command.{Data} import albedo/harness/extension as harness_extension +import albedo/harness/extensions/run/service import albedo/harness/rpc import gleam/dynamic/decode import gleam/json +import gleam/option.{None} +import gleam/result -const instructions = "run(program, *args, cwd=None, env=None, stdin=None, timeout=300) starts one program without a shell and returns its job handle right away; run is not async, and awaiting the handle waits for the program: job = run(\"go\", \"test\", \"./...\", cwd=\"cli\"), then await job, then job.exit_code and job.tail(lines=20). Bind the handle before awaiting it: job = await run(...) blocks before the assignment, so a cell interrupted mid-wait leaves the running job only in jobs. There is no shell, so shell syntax has Python spellings: cd dir && ... is cwd=, NAME=value is env= (added to the kernel's environment), | tail -n 20 is job.tail(lines=20), | head -n 20 is job.head(lines=20), a | b is .pipe(): run() and job.pipe(program, *args) return handles at once, so chain first and await once, as in job = run(\"git\", \"log\", \"--oneline\").pipe(\"rg\", \"fix\").pipe(\"sort\", \"-u\"); await job; the stages stream like a shell pipe, the await waits for the last one, and job.pipeline is the whole line, 2>&1 is implied (stderr joins stdout), stdin= takes text, bytes, a path, or another job, and &&, loops, and globs are Python over job.exit_code and the output. `sh -c` and subprocess/os.system from a cell are refused with the run() call they mean. Programs start at once at low priority; one still running after 5 seconds needs one of a few daemon-wide heavy slots and is paused while it waits (job.queued is True then), so keep long computations few and let quick commands be quick. The timeout (seconds) counts only time the program ran, not time paused. Await the handle for completion, or keep it in a variable. jobs is a dict of job id to handle for this session. A job's output lives on its handle (job.tail(n=4000) for the last n characters, lines= for lines; job.command is what ran, job.argv as a list) and stays readable in full with output.read(job.id, offset=0, limit=4000); await job.stop() ends it. job.exit_code, job.duration, and job.timed_out report the exit status, the seconds it ran, and deadline state once the program ends (job.poll() and job.returncode are subprocess-style spellings of job.exit_code); job.waited is the seconds it sat paused for a heavy slot, which job.duration leaves out. A job that finishes with its result unread wakes the session by itself, so polling a handle is optional: leave it in a variable, end the cell, and a notice naming the job arrives once the session is idle. A job that finishes while you are still working is reported after your turn ends, unless you read it first. Awaiting the job, reading its result, or stopping it first means no wake." +const instructions = "run(program, *args, cwd=None, env=None, stdin=None, timeout=300) starts one program without a shell and returns its job handle right away; run is not async, and awaiting the handle waits for the program: job = run(\"go\", \"test\", \"./...\", cwd=\"cli\"), then await job, then job.exit_code and job.tail(lines=20). Bind the handle before awaiting it: job = await run(...) blocks before the assignment, so a cell interrupted mid-wait leaves the running job only in jobs. There is no shell, so shell syntax has Python spellings: cd dir && ... is cwd=, NAME=value is env= (added to the kernel's environment), | tail -n 20 is job.tail(lines=20), | head -n 20 is job.head(lines=20), a | b is .pipe(): run() and job.pipe(program, *args) return handles at once, so chain first and await once, as in job = run(\"git\", \"log\", \"--oneline\").pipe(\"rg\", \"fix\").pipe(\"sort\", \"-u\"); await job; the stages stream like a shell pipe, the await waits for the last one, and job.pipeline is the whole line, 2>&1 is implied (stderr joins stdout), stdin= takes text, bytes, a path, or another job, and &&, loops, and globs are Python over job.exit_code and the output. `sh -c` and subprocess/os.system from a cell are refused with the run() call they mean. Programs start at once at low priority and are never paused for admission. The timeout (seconds) counts wall time after the program starts. Await the handle for completion, or keep it in a variable. jobs is a dict of job id to handle for this session. A job's output lives on its handle (job.tail(n=4000) for the last n characters, lines= for lines; job.command is what ran, job.argv as a list) and stays readable in full with output.read(job.id, offset=0, limit=4000); await job.stop() ends it. job.exit_code, job.duration, and job.timed_out report the exit status, the seconds it ran, and deadline state once the program ends (job.poll() and job.returncode are subprocess-style spellings of job.exit_code). A job that finishes with its result unread wakes the session by itself, so polling a handle is optional: leave it in a variable, end the cell, and a notice naming the job arrives once the session is idle. A job that finishes while you are still working is reported after your turn ends, unless you read it first. Awaiting the job, reading its result, or stopping it first means no wake." pub fn extension() -> harness_extension.Extension { harness_extension.Extension( @@ -14,14 +19,40 @@ pub fn extension() -> harness_extension.Extension { "Start supervised programs from Python, without a shell.", ["python"], [ + harness_extension.ClientPlugin([ + client_api.Command("/jobs", client_api.Read, [], service.operation()), + ]), + harness_extension.ServicePlugin(harness_extension.Service( + fn(_, _) { + harness_extension.Admission(harness_extension.DaemonToken, 1024) + }, + service.handle, + )), harness_extension.ToolPlugin(instructions, [], ["run"], [ #("jobs", route), ]), + harness_extension.CommandPlugin([command()]), ], harness_extension.no_initialise, ) } +/// `/jobs`: inspect and manage background jobs running in the session. +fn command() -> command.Command { + command.Command( + "/jobs", + "Show background jobs running in this session.", + [], + False, + False, + True, + None, + fn(ctx, _caller, _args) { + ctx.state(command.KernelJobs) |> result.map(Data) + }, + ) +} + /// A session's answer to a job wake. `Busy` is the kernel's retry signal. pub type Wake { Delivered diff --git a/src/albedo/harness/extensions/run/service.gleam b/src/albedo/harness/extensions/run/service.gleam new file mode 100644 index 000000000..c2e2219b6 --- /dev/null +++ b/src/albedo/harness/extensions/run/service.gleam @@ -0,0 +1,162 @@ +//// Session-owned job observations and explicit process-group stops. + +import albedo/daemon/http_api as api +import albedo/harness/client_api +import albedo/harness/command +import albedo/harness/extension +import albedo/harness/extensions/python/kernel +import gleam/dynamic/decode +import gleam/http.{Get, Post} +import gleam/http/request +import gleam/http/response +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{None, Some} +import gleam/result +import mist + +pub fn operation() -> client_api.Operation { + client_api.Operation( + "listJobs", + Get, + "/extensions/run/sessions/{session_id}/jobs", + [#("session_id", client_api.Session("/id"))], + [], + [], + [], + json.object([]), + Some(200), + ) +} + +pub fn handle( + _daemon: extension.Daemon, + path: List(String), + req: request.Request(BitArray), + _live: request.Request(mist.Connection), +) -> response.Response(mist.ResponseData) { + case dispatch(path, req) { + Ok(value) -> value + Error(error) -> api.fail(error) + } +} + +fn failure(detail: String) -> api.Failure { + case detail { + "session unavailable" -> api.failure("session not found") + "job not found" -> api.Failure(404, "job_not_found", detail) + _ -> api.Failure(503, "job_operation_failed", detail) + } +} + +fn dispatch( + path: List(String), + req: request.Request(BitArray), +) -> Result(response.Response(mist.ResponseData), api.Failure) { + use events <- result.try(api.wants_events(req)) + use _ <- result.try(case events { + True -> Error(api.Failure(406, "not_acceptable", "jobs use JSON")) + False -> Ok(Nil) + }) + use _ <- result.try(api.parameters(req, [])) + case req.method, path { + Get, ["sessions", id, "jobs"] -> { + use observed <- result.try( + command.context(id).state(command.KernelJobs) + |> result.map_error(failure), + ) + use jobs <- result.try( + json.parse(json.to_string(observed), { + use jobs <- decode.field("items", decode.list(job_decoder())) + decode.success(jobs) + }) + |> result.replace_error(api.Failure( + 503, + "kernel_unavailable", + "invalid kernel job observation", + )), + ) + use fields <- result.try(api.fields(json.to_string(observed))) + Ok(api.reply( + 200, + json.object([#("page", descriptor(id, jobs)), ..fields]), + )) + } + Post, ["sessions", id, "jobs", job, "stop"] -> { + use _ <- result.try(api.empty_body(req)) + use _ <- result.try( + command.context(id).state(command.KernelStopJob(job)) + |> result.map_error(failure), + ) + let _ = + command.context(id).state(command.Note( + "jobs", + "stopped background job " <> job, + "background job " <> job <> " was stopped", + )) + Ok(api.reply(200, json.object([#("stopped", json.string(job))]))) + } + _, ["sessions", _, "jobs"] | _, ["sessions", _, "jobs", _, "stop"] -> + Error(api.Failure(405, "method_not_allowed", "unsupported job method")) + _, _ -> Error(api.Failure(404, "not_found", "job resource not found")) + } +} + +fn job_decoder() -> decode.Decoder(kernel.Job) { + use id <- decode.field("id", decode.string) + use pid <- decode.field("pid", decode.optional(decode.int)) + use command <- decode.field("command", decode.string) + decode.success(kernel.Job(id, pid, command)) +} + +fn descriptor(id: String, jobs: List(kernel.Job)) -> json.Json { + client_api.page(client_api.Page( + title: "jobs", + summary: case list.length(jobs) { + 1 -> "1 background job running" + count -> int.to_string(count) <> " background jobs running" + }, + empty_state: "no background jobs running", + glance: None, + actions: [ + client_api.Action( + id: "stop", + label: "stop", + keyboard_hint: "x", + confirmation: Some("stop this background job?"), + fields: [], + operation: client_api.Operation( + "stopJob", + Post, + "/extensions/run/sessions/{session_id}/jobs/{job_id}/stop", + [ + #("session_id", client_api.Literal(json.string(id))), + #("job_id", client_api.Row("/id")), + ], + [], + [], + [], + json.object([]), + Some(200), + ), + ), + ], + rows: list.map(jobs, fn(job) { + client_api.PageRow( + id: job.id, + text: case job.command { + "" -> "job " <> job.id + cmd -> cmd + }, + badge: Some(case job.pid { + Some(pid) -> "pid " <> int.to_string(pid) + None -> "running" + }), + tone: "active", + detail: None, + resource: json.null(), + ) + }), + )) +} diff --git a/src/albedo/harness/extensions/work/ledger.gleam b/src/albedo/harness/extensions/work/ledger.gleam index 190d93234..24ab8000b 100644 --- a/src/albedo/harness/extensions/work/ledger.gleam +++ b/src/albedo/harness/extensions/work/ledger.gleam @@ -391,8 +391,8 @@ pub fn initialise(store: Store) -> Result(Nil, String) { storage.query(store, storage.exec(_, schema)) } -/// The pending sidebar reads only the twelve records it can display. -pub fn pending(store: Store, cwd: String) -> Result(List(Item), Error) { +/// The sidebar reads only the twelve active records it can display. +pub fn active(store: Store, cwd: String) -> Result(List(Item), Error) { use _ <- result.try(valid_cwd(cwd)) storage.query(store, fn(db) { use #(within, group) <- result.try(scope(db, cwd)) @@ -402,7 +402,7 @@ pub fn pending(store: Store, cwd: String) -> Result(List(Item), Error) { <> columns <> " FROM work WHERE " <> within - <> " AND status IN ('active','blocked','open') ORDER BY CASE status WHEN 'active' THEN 0 WHEN 'blocked' THEN 1 ELSE 2 END,id LIMIT 12", + <> " AND status='active' ORDER BY id LIMIT 12", group, ) }) diff --git a/src/albedo/harness/extensions/work/service.gleam b/src/albedo/harness/extensions/work/service.gleam index f918f84b0..ec9741539 100644 --- a/src/albedo/harness/extensions/work/service.gleam +++ b/src/albedo/harness/extensions/work/service.gleam @@ -593,21 +593,17 @@ pub fn sidebar( workspace: String, ) -> Result(page.Glance, String) { use items <- result.try( - work.pending(storage, workspace) + work.active(storage, workspace) |> result.map_error(fn(error) { failure(error).detail }), ) Ok(page.Glance( - "pending work", + "active work", list.map(items, fn(item) { page.detail_row( int.to_string(item.id), api.content_preview(item.title, 64), work.status_name(item.status), - case item.status { - work.Active -> page.Active - work.Blocked -> page.Warning - _ -> page.Plain - }, + page.Active, "", ) }), diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 0af79446d..28a23ade2 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -915,6 +915,11 @@ pub fn job_count(session: Session) -> Int { python.job_count(session.kernel) } +/// Stop one background job by id. +pub fn stop_job(session: Session, id: String) -> Result(Nil, String) { + python.stop_job(session.kernel, id) +} + pub fn save_state( session: Session, path: String, diff --git a/test/e2e/cell_background_test.py b/test/e2e/cell_background_test.py new file mode 100644 index 000000000..4df1d60f6 --- /dev/null +++ b/test/e2e/cell_background_test.py @@ -0,0 +1,191 @@ +"""Long cells detach without losing output, deadlines, or completion wakes.""" + +import json +import time +import unittest + +from harness import Albedo, Provider, Reply, exclusive, python, text + + +def user_text(request): + return next( + ( + item.get("content", "") + for item in reversed(request["messages"]) + if item.get("role") == "user" + ), + "", + ) + + +def wait_for(predicate, timeout=40): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if result := predicate(): + return result + time.sleep(0.1) + raise AssertionError("background cell did not wake session") + + +@exclusive +class CellBackgroundTests(unittest.TestCase): + def setUp(self): + self.results = [] + self.read_before_idle = False + self.deadline = False + self.synchronous = False + self.cell_id = None + + def script(request): + last = request["messages"][-1] + user = user_text(request) + if last.get("role") == "tool": + result = json.loads(last["content"]) + self.results.append(result) + if result.get("status") == "backgrounded": + self.cell_id = result["cell_id"] + return text("waiting for the background cell") + if "background python cells finished" in user: + return text("completion received") + if "start cell" in user: + code = ( + "import asyncio\n" + "cell_gate = asyncio.Event()\n" + "cell_done = asyncio.Event()\n" + "print('before detach')\n" + "await cell_gate.wait()\n" + "print('after detach')\n" + "cell_done.set()\n" + "{'answer': 42}" + ) + if self.synchronous: + code = "import time\nprint('before detach')\ntime.sleep(10)\nprint('after detach')" + if self.deadline: + return Reply( + "python", tool_arguments={"code": code, "timeout_ms": 1800} + ) + return python(code) + if "release cell" in user: + code = "print('other cell output')\ncell_gate.set()" + if self.read_before_idle: + code += f"\nawait cell_done.wait()\nprint(output.read({self.cell_id!r}))" + return python(code) + if "cancel cell" in user: + return python(f"print(await cells.cancel({self.cell_id!r}))") + if "inspect cell" in user: + return python( + f"print(await cells.info({self.cell_id!r}))\nprint(output.read({self.cell_id!r}))" + ) + return text("done") + + def prepare(app): + app.env["ALBEDO_CELL_BACKGROUND_SECONDS"] = "0.5" + app.env["ALBEDO_IDLE_SECONDS"] = "2" + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + self.app = Albedo(self.provider, prepare=prepare) + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + + def prompt(self, session, message): + self.app.prompt(session, message).close() + self.app.idle(session) + + def wakes(self): + return [ + record + for record in self.provider.requests + if "background python cells finished" in user_text(record["request"]) + ] + + def start(self): + session = self.app.session() + self.prompt(session, "start cell") + result = self.results[0] + self.assertEqual(result["status"], "backgrounded") + self.assertIn("before detach", result["output"]) + self.assertIn("do NOT poll or sleep", result["output"]) + self.assertIn("wake automatically", result["output"]) + return session + + def test_cell_wakes_once_and_keeps_its_capture_separate(self): + session = self.start() + self.prompt(session, "inspect cell") + self.assertIn("'status': 'started'", self.results[-1]["output"]) + self.assertIn("before detach", self.results[-1]["output"]) + self.prompt(session, "release cell") + self.assertEqual(self.results[-1]["output"].strip(), "other cell output") + wait_for(lambda: self.wakes()) + self.app.idle(session) + self.assertEqual(len(self.wakes()), 1) + notes = [ + entry + for entry in self.app.history(session)["items"] + if entry["kind"] == "note" + and any( + part["kind"] == "text" and "cell finished" in part["text"] + for part in entry["content"] + ) + ] + self.assertEqual(len(notes), 1) + shown = next( + part["text"] for part in notes[0]["content"] if part["kind"] == "text" + ) + self.assertTrue(shown.startswith("cell finished (status=ok"), shown) + # the transcript names the code, the model's notice the cell id + self.assertTrue(shown.endswith("import asyncio"), shown) + self.assertNotIn("", shown) + self.assertIn(self.cell_id, user_text(self.wakes()[0]["request"])) + self.prompt(session, "inspect cell") + self.assertIn("'status': 'ok'", self.results[-1]["output"]) + self.assertIn("after detach", self.results[-1]["output"]) + self.assertIn("{'answer': 42}", self.results[-1]["output"]) + self.assertNotIn("other cell output", self.results[-1]["output"]) + time.sleep(2.5) + self.assertEqual(len(self.wakes()), 1) + + def test_reading_finished_output_suppresses_the_wake(self): + self.read_before_idle = True + session = self.start() + self.prompt(session, "release cell") + self.assertIn("after detach", self.results[1]["output"]) + time.sleep(2.5) + self.assertEqual(self.wakes(), []) + + def test_original_deadline_interrupts_the_background_cell(self): + self.deadline = True + session = self.start() + wait_for(lambda: self.wakes()) + self.app.idle(session) + self.assertIn("status=interrupted", user_text(self.wakes()[0]["request"])) + self.prompt(session, "inspect cell") + self.assertIn("'status': 'interrupted'", self.results[-1]["output"]) + + def test_background_cell_survives_idle_reaping_and_daemon_restart(self): + session = self.start() + time.sleep(4) + self.app.restart() + self.prompt(session, "release cell") + wait_for(lambda: self.wakes()) + self.app.idle(session) + self.assertEqual(len(self.wakes()), 1) + self.assertIn("status=ok", user_text(self.wakes()[0]["request"])) + + def test_cancelled_background_cell_does_not_wake(self): + session = self.start() + self.prompt(session, "cancel cell") + self.assertEqual(self.results[1]["output"].strip(), "True") + time.sleep(2.5) + self.prompt(session, "inspect cell") + self.assertIn("'status': 'interrupted'", self.results[-1]["output"]) + self.assertEqual(self.wakes(), []) + + def test_synchronous_cell_returns_early_and_keeps_its_deadline(self): + self.synchronous = True + self.deadline = True + session = self.start() + wait_for(lambda: self.wakes()) + self.app.idle(session) + self.assertEqual(len(self.wakes()), 1) + self.assertIn("status=interrupted", user_text(self.wakes()[0]["request"])) diff --git a/test/e2e/job_wake_test.py b/test/e2e/job_wake_test.py index 88b3986c7..0f5e7a55a 100644 --- a/test/e2e/job_wake_test.py +++ b/test/e2e/job_wake_test.py @@ -1,9 +1,11 @@ """Unread background job results wake idle sessions once, even across idle reaping.""" import errno +import json import os import time import unittest +import urllib.error from harness import Albedo, Provider, exclusive, python, text @@ -33,6 +35,20 @@ def wait_for(predicate, timeout=40): raise AssertionError("background job did not wake session") +def release_fifo(gate): + try: + descriptor = os.open(gate, os.O_WRONLY | os.O_NONBLOCK) + except OSError as error: + if error.errno == errno.ENXIO: + return False + raise + try: + os.write(descriptor, b"x") + finally: + os.close(descriptor) + return True + + class JobWakeCase(unittest.TestCase): idle_seconds = None @@ -80,20 +96,7 @@ class JobWakeTests(JobWakeCase): self.assertEqual(len(self.users()), 2) before = self.app.stream_page(session) - def release_job(): - try: - descriptor = os.open(gate, os.O_WRONLY | os.O_NONBLOCK) - except OSError as error: - if error.errno == errno.ENXIO: - return False - raise - try: - os.write(descriptor, b"x") - finally: - os.close(descriptor) - return True - - wait_for(release_job) + wait_for(lambda: release_fifo(gate)) wait_for(lambda: len(self.users()) >= 3) self.app.idle(session) self.assertEqual(len(self.users()), 3) @@ -117,12 +120,14 @@ class JobWakeTests(JobWakeCase): 1, {"live": live, "history": self.app.history(session)}, ) - self.assertIn( - "exit_code=0", - "".join( - part["text"] for part in notices[0]["content"] if part["kind"] == "text" - ), + # The transcript shows the one-line display; the model's notice with the + # handle and advice stays in the request above. + shown = "".join( + part["text"] for part in notices[0]["content"] if part["kind"] == "text" ) + self.assertTrue(shown.startswith("job finished (exit_code=0"), shown) + self.assertNotIn("\n", shown) + self.assertNotIn("jobs[", shown) durable = [ entry for entry in self.app.history(session)["items"] @@ -136,7 +141,7 @@ class JobWakeTests(JobWakeCase): self.assertEqual(durable[0]["id"], notices[0]["id"]) self.assertEqual(durable[0]["turn_id"], notices[0]["turn_id"]) self.assertIsNotNone(durable[0]["turn_id"]) - self.assertIsNone(durable[0]["input_id"]) + self.assertEqual(durable[0]["input_id"], notices[0]["input_id"]) for entry in [notices[0], durable[0]]: self.assertEqual( [ @@ -144,11 +149,96 @@ class JobWakeTests(JobWakeCase): for part in entry["content"] if part["kind"] == "json" and part["field"] == "origin" ], - ["note"], + ["job"], ) time.sleep(2.5) self.assertEqual(len(self.users()), 3) + def start_blocked_job(self): + session = self.app.session() + self.job_gate = self.app.workspace / "job-release" + os.mkfifo(self.job_gate) + self.app.prompt(session, "start a slow job").close() + self.app.idle(session) + self.assertEqual(len(self.users()), 2) + return session + + def jobs_resource(self, session): + return json.loads( + self.app.api(f"/extensions/run/sessions/{session}/jobs").read() + ) + + def test_running_job_observation_and_page_clear_after_completion(self): + session = self.start_blocked_job() + kernel = json.loads(self.app.api(f"/sessions/{session}?tail=0").read())[ + "kernel" + ] + self.assertEqual(kernel["live_job_count"], 1) + running = kernel["running_jobs"] + self.assertEqual(len(running), 1) + self.assertIsInstance(running[0]["pid"], int) + self.assertIn(str(self.job_gate), running[0]["command"]) + + resource = self.jobs_resource(session) + self.assertEqual(resource["items"], running) + self.assertEqual(resource["live_job_count"], 1) + page = resource["page"] + self.assertEqual(page["title"], "jobs") + self.assertEqual(page["summary"], "1 background job running") + self.assertEqual(len(page["rows"]), 1) + self.assertIn(str(self.job_gate), page["rows"][0]["text"]) + # A row resource is a validated representation or nothing; clients + # reject one without an etag. + row_resource = page["rows"][0]["resource"] + self.assertTrue( + row_resource is None or isinstance(row_resource.get("etag"), str), + row_resource, + ) + stop = page["actions"][0]["operation"] + self.assertEqual(stop["method"], "POST") + self.assertEqual( + stop["path_template"], + "/extensions/run/sessions/{session_id}/jobs/{job_id}/stop", + ) + self.assertEqual( + stop["path"], + { + "session_id": {"source": "literal", "value": session}, + "job_id": {"source": "row", "pointer": "/id"}, + }, + ) + + gate = self.job_gate + assert gate is not None + + wait_for(lambda: release_fifo(gate)) + wait_for(lambda: len(self.users()) >= 3) + self.app.idle(session) + after = json.loads(self.app.api(f"/sessions/{session}?tail=0").read())["kernel"] + self.assertEqual(after["live_job_count"], 0) + self.assertEqual(after["running_jobs"], []) + self.assertEqual(self.jobs_resource(session)["items"], []) + + def test_stopping_one_job_and_rejecting_unknown_job(self): + session = self.start_blocked_job() + resource = self.jobs_resource(session) + job_id = resource["items"][0]["id"] + stopped = json.loads( + self.app.api( + f"/extensions/run/sessions/{session}/jobs/{job_id}/stop", + method="POST", + ).read() + ) + self.assertEqual(stopped, {"stopped": job_id}) + wait_for(lambda: self.jobs_resource(session)["live_job_count"] == 0) + self.assertEqual(self.jobs_resource(session)["items"], []) + with self.assertRaises(urllib.error.HTTPError) as missing: + self.app.api( + f"/extensions/run/sessions/{session}/jobs/missing/stop", + method="POST", + ) + self.assertEqual(missing.exception.code, 404) + # exclusive: changes daemon idle sweep timing @exclusive diff --git a/test/e2e/kernel_detach_test.py b/test/e2e/kernel_detach_test.py index 4aead58b4..57b34e32f 100644 --- a/test/e2e/kernel_detach_test.py +++ b/test/e2e/kernel_detach_test.py @@ -3,10 +3,10 @@ The kernel runs detached behind a bridge process; the daemon reattaches to it after a restart (graceful or crash) and after the bridge dies mid-cell, so the namespace, the kernel process, and an in-flight cell's result all survive. -What the kernel owns survives with it: a reattached kernel's running job keeps -its heavy-job slot, and one found dead after a restart has its jobs ended. +A kernel found dead after a restart has its jobs ended. """ +import ast import json import os import signal @@ -30,7 +30,7 @@ def bridges(home): ] -# exclusive: changes daemon-wide heavy-job timing and restarts the daemon +# exclusive: restarts the daemon @exclusive class KernelDetachTests(unittest.TestCase): def setUp(self): @@ -44,15 +44,7 @@ class KernelDetachTests(unittest.TestCase): self.provider = Provider(script) self.addCleanup(self.provider.close) - def prepare(app): - # One heavy slot, granted to a job half a second in. - app.daemon.env.update( - ALBEDO_MAX_LOCAL_JOBS="1", - ALBEDO_JOB_LOAD="0", - ALBEDO_JOB_GRACE_SECONDS="0.5", - ) - - self.app = Albedo(self.provider, protocol="responses", prepare=prepare) + self.app = Albedo(self.provider, protocol="responses") self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.session = self.app.session() @@ -108,20 +100,27 @@ class KernelDetachTests(unittest.TestCase): (replacement,) = bridges(self.app.home) self.assertNotEqual(replacement, bridge) - def test_a_reattached_kernels_running_job_keeps_its_slot(self): - held = self.cell( - "import asyncio\na = run('sleep', '60')\nawait asyncio.sleep(1.5)\na.queued" + def test_concurrent_jobs_keep_running_and_deadlines_count_wall_time(self): + # Legacy admission settings must not throttle new kernels. + self.app.daemon.env.update( + ALBEDO_MAX_LOCAL_JOBS="1", ALBEDO_JOB_GRACE_SECONDS="0.2" ) - self.assertEqual(held["value"], "False") self.app.restart() - # The new daemon's pool counts the slot a's job already holds. - waiting = self.cell( - "b = run('sleep', '60')\nawait asyncio.sleep(1.5)\n(a.queued, b.queued)" + program = "import time; time.sleep(5.5); print('progress', flush=True); time.sleep(60)" + result = self.cell( + "import sys\n" + f"workers = [run(sys.executable, '-c', {program!r}, timeout=7) for _ in range(3)]\n" + "for worker in workers:\n await worker\n" + "[(worker.timed_out, worker.duration, worker.tail().startswith('progress')) for worker in workers]" ) - self.assertEqual(waiting["value"], "(False, True)") - freed = self.cell("await a.stop()\nawait asyncio.sleep(1)\nb.queued") - self.assertEqual(freed["value"], "False") - self.cell("await b.stop()") + self.assertEqual(result["status"], "ok", result) + outcomes = ast.literal_eval(result["value"]) + self.assertEqual(len(outcomes), 3) + for timed_out, duration, progressed in outcomes: + self.assertTrue(timed_out) + self.assertTrue(progressed) + self.assertGreaterEqual(duration, 7) + self.assertLess(duration, 10) def test_a_kernel_killed_while_the_daemon_was_down_has_its_jobs_ended(self): started = self.cell( diff --git a/test/e2e/paperclips_test.py b/test/e2e/paperclips_test.py index 3f22279fb..4cbbd1bf3 100644 --- a/test/e2e/paperclips_test.py +++ b/test/e2e/paperclips_test.py @@ -102,15 +102,10 @@ def vent_row(page, vent_id): ) -def glance_ids(app, session): +def sidebar_extensions(app, session): with app.api(f"/sessions/{session}?tail=0") as response: glances = json.load(response)["glances"] - return { - row["id"] - for glance in glances - if glance["extension"] == "paperclips" - for row in glance["rows"] - } + return {glance["extension"] for glance in glances} def paperclips_page(app): @@ -180,9 +175,8 @@ class PaperclipsTests(unittest.TestCase): page = paperclips_page(app) rows = {item["value"]["id"] for item in page["items"]} self.assertTrue({str(vent_id) for vent_id in ids} <= rows) - self.assertTrue( - {str(vent_id) for vent_id in ids} <= glance_ids(app, sessions[0]) - ) + # open vents stay out of the chat sidebar + self.assertNotIn("paperclips", sidebar_extensions(app, sessions[0])) finally: if ids: self.remove_vents(app, sessions[0], ids) @@ -211,7 +205,6 @@ class PaperclipsTests(unittest.TestCase): self.assertEqual(row["message"], "a background job stopped responding") self.assertEqual(row["suggestion"], "report the blocked job") self.assertEqual(row["session_id"], session) - self.assertIn(str(vent_id), glance_ids(app, session)) replied = reply_to_vent(app, vent_id, "the blocked job is now visible") self.assertEqual(replied["notification"]["state"], "queued") @@ -227,7 +220,6 @@ class PaperclipsTests(unittest.TestCase): "the blocked job is now visible", vent_row(page, vent_id)["reply"], ) - self.assertNotIn(str(vent_id), glance_ids(app, session)) # the note reaches the model with its next turn; the ledger agrees app.prompt(session, "check your vents").close() @@ -369,10 +361,6 @@ class PaperclipsTests(unittest.TestCase): "for nobody", vent_row(page, ids["sessionless vent"])["reply"], ) - self.assertFalse( - {str(vent_id) for vent_id in ids.values()} - & glance_ids(app, session) - ) finally: self.remove_vents(app, session, list(ids.values())) @@ -407,7 +395,6 @@ class PaperclipsTests(unittest.TestCase): self.assertEqual( row["resolution"], "the blocked job now reports its state" ) - self.assertNotIn(str(vent_id), glance_ids(app, session)) finally: if vent_id is not None: self.remove_vents(app, session, [vent_id]) diff --git a/test/e2e/python_test.py b/test/e2e/python_test.py index 70fc45eeb..bc122a18c 100644 --- a/test/e2e/python_test.py +++ b/test/e2e/python_test.py @@ -41,6 +41,28 @@ class PythonToolsTests(unittest.TestCase): def execute(self, code): return self.run_cell(code, self.app.session())["output"] + def test_deleting_shadowed_tools_recovers_the_original_bindings(self): + (self.app.workspace / "note.txt").write_text("recovered\n") + session = self.app.session() + output = self.run_cell( + "original_tools = (files, run, jobs, cells, output, show_image)\n" + "files, run, jobs, cells, output, show_image = range(6)\n" + "assert (files, run, jobs, cells, output, show_image) == tuple(range(6))\n" + "del files, run, jobs, cells, output, show_image\n" + "assert (files, run, jobs, cells, output, show_image) == original_tools\n" + "def recovered_read():\n return files.read('note.txt')\n" + "print(recovered_read())", + session, + )["output"] + self.assertIn("recovered", output) + output = self.run_cell( + "assert (files, run, jobs, cells, output, show_image) == original_tools\n" + "print(recovered_read())\n" + "import builtins\nassert not hasattr(builtins, 'files')", + session, + )["output"] + self.assertIn("recovered", output) + def test_ambiguous_edit_requires_a_hint_and_preserves_other_matches(self): note = self.app.workspace / "note.txt" note.write_text("same\nother\nsame\n") diff --git a/test/e2e/transcript_tail_test.py b/test/e2e/transcript_tail_test.py new file mode 100644 index 000000000..a0142e084 --- /dev/null +++ b/test/e2e/transcript_tail_test.py @@ -0,0 +1,55 @@ +"""The newest end of a long transcript is what a client sees first.""" + +import json +import unittest + +from harness import Albedo, Provider, python, text + +ROUNDS = 8 + + +class TranscriptTailTests(unittest.TestCase): + def setUp(self): + def script(request): + results = [m for m in request["messages"] if m.get("role") == "tool"] + if len(results) < ROUNDS: + return python(f"{len(results)}", reasoning=f"step {len(results)}") + return text("all rounds done") + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + self.app = Albedo(self.provider) + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + + def read(self, path): + return json.loads(self.app.api(path).read()) + + def test_a_short_tail_ends_at_the_newest_entry_and_pages_back_whole(self): + session = self.app.session() + self.app.prompt(session, "run the rounds").close() + self.app.idle(session) + everything = self.read(f"/sessions/{session}/history?limit=200") + self.assertIsNone(everything["older"]) + full = [entry["id"] for entry in everything["items"]] + + # a thought and its tool call share a row, so ten rows hold more + # than ten entries; the page keeps the newest ones + tail = self.read(f"/sessions/{session}?tail=10")["history"] + shown = [entry["id"] for entry in tail["items"]] + self.assertTrue(shown and len(shown) <= 10, shown) + self.assertEqual(shown, full[-len(shown) :]) + self.assertIsNone(tail["newer"]) + + # older pages continue from there without gaps or repeats + seen = shown + older = tail["older"] + while older is not None: + page = self.read(f"/sessions/{session}/history?limit=10&next={older}") + seen = [entry["id"] for entry in page["items"]] + seen + older = page["older"] + self.assertEqual(seen, full) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/harness/albedo_job_slots_test_support.erl b/test/harness/albedo_job_slots_test_support.erl deleted file mode 100644 index 192ce791c..000000000 --- a/test/harness/albedo_job_slots_test_support.erl +++ /dev/null @@ -1,148 +0,0 @@ --module(albedo_job_slots_test_support). --export([check/0, run/0]). - -%% A separate VM makes the daemon-wide budget/config independent of other tests. -check() -> - Port = open_port({spawn_executable, os:find_executable("erl")}, - [binary, exit_status, stderr_to_stdout, - {env, [{"ALBEDO_MAX_LOCAL_JOBS", "2"}, {"ALBEDO_JOB_LOAD", "0"}, - {"ALBEDO_JOB_GRACE_SECONDS", "0.3"}, {"ERL_FLAGS", false}]}, - {args, ["+S", "2:2", "-noshell", "-pa"] ++ - [filename:absname(Path) || Path <- code:get_path()] ++ - ["-eval", "albedo_job_slots_test_support:run(), halt()."]}]), - collect(Port, <<>>). - -collect(Port, Output) -> - receive - {Port, {data, Data}} -> collect(Port, <>); - {Port, {exit_status, 0}} -> true; - {Port, {exit_status, Code}} -> error({job_slots_test, Code, Output}) - after 45000 -> port_close(Port), error({job_slots_timeout, Output}) - end. - -run() -> - Pool = albedo_job_slots:ensure(), - %% One hundred requests, two grants; the rest hear at once that they wait. - [albedo_job_slots:acquire(Pool, N) || N <- lists:seq(1, 100)], - barrier(Pool), - granted(1), granted(2), queued(3), no_grant(), - albedo_job_slots:release(Pool, 3), - albedo_job_slots:release(Pool, 1), granted(4), - albedo_job_slots:release(Pool, 2), granted(5), - albedo_job_slots:release_owner(Pool), barrier(Pool), flush_queued(), no_grant(), - [albedo_job_slots:acquire(Pool, N) || N <- lists:seq(1, 1027)], - barrier(Pool), granted(1), granted(2), - receive {job_slot, 1027, {error, _}} -> ok after 1000 -> error(queue_unbounded) end, - flush_queued(), no_grant(), albedo_job_slots:release_owner(Pool), barrier(Pool), - %% A freed slot goes to the kernel holding the fewest, not the oldest request. - Busy = relay(), Idle = relay(), - ask(Busy, a1), ask(Busy, a2), barrier(Pool), - relayed(Busy, a1, ok), relayed(Busy, a2, ok), - ask(Busy, a3), barrier(Pool), relayed(Busy, a3, queued), - ask(Idle, b1), barrier(Pool), relayed(Idle, b1, queued), - Busy ! {release, a1}, barrier(Pool), relayed(Idle, b1, ok), - Busy ! {release, a2}, barrier(Pool), relayed(Busy, a3, ok), - Busy ! release_all, Idle ! release_all, barrier(Pool), flush_queued(), - %% Unverified owner death must not silently free an active process slot. - Parent = self(), - {Owner, Mon} = spawn_monitor(fun() -> - albedo_job_slots:acquire(Pool, owned), granted(owned), Parent ! owned - end), - receive owned -> ok after 1000 -> error(owner_timeout) end, - receive {'DOWN', Mon, process, Owner, _} -> ok after 1000 -> error(down_timeout) end, - albedo_job_slots:acquire(Pool, other), granted(other), - albedo_job_slots:acquire(Pool, waiting), barrier(Pool), queued(waiting), no_grant(), - gen_server:cast(Pool, {release_owner, Owner}), granted(waiting), - albedo_job_slots:release_owner(Pool), barrier(Pool), - kernels(), - bootstrap(). - -barrier(Pool) -> _ = sys:get_state(Pool), ok. -granted(Id) -> receive {job_slot, Id, ok} -> ok after 5000 -> error({no_grant, Id}) end. -queued(Id) -> receive {job_slot, Id, queued} -> ok after 1000 -> error({not_queued, Id}) end. -no_grant() -> receive {job_slot, Id, ok} -> error({extra_grant, Id}) after 0 -> ok end. -flush_queued() -> receive {job_slot, _, queued} -> flush_queued() after 0 -> ok end. - -%% A stand-in kernel: asks as itself and reports every answer to the test. -relay() -> - Parent = self(), - spawn(fun Loop() -> - receive - {ask, Id} -> albedo_job_slots:acquire(albedo_job_slots:ensure(), Id), Loop(); - {release, Id} -> albedo_job_slots:release(albedo_job_slots:ensure(), Id), Loop(); - release_all -> albedo_job_slots:release_owner(albedo_job_slots:ensure()), Loop(); - {job_slot, Id, Answer} -> Parent ! {relayed, self(), Id, Answer}, Loop() - end - end). -ask(Relay, Id) -> Relay ! {ask, Id}. -relayed(Relay, Id, Answer) -> - receive {relayed, Relay, Id, Answer} -> ok - after 2000 -> error({not_relayed, Id, Answer}) - end. - -kernels() -> - {ok, {Python, Script}} = albedo_python:local_paths(), - Host = fun(_) -> <<"{\"ok\":true,\"value\":null}">> end, - Kernels = [begin {ok, K} = start(Python, Script, Host, [<<"run">>]), K end - || _ <- lists:seq(1, 3)], - [A, B, C] = Kernels, - try - %% Two long jobs pass the grace window and take both heavy slots. - [cell(K, <<"j = run('sleep', '30')\nimport asyncio\nawait asyncio.sleep(0.6)\nj.queued">>) || K <- [A, B]], - %% A third long job is paused, not refused: its handle answers. - <<"True">> = cell(C, <<"j = run('sleep', '30')\nimport asyncio\nawait asyncio.sleep(0.8)\nj.queued">>), - %% Quick commands never wait for a slot, even with none free. - <<"(0, 'quick')">> = cell(C, <<"q = run('printf', 'quick')\nawait q\n(q.exit_code, q.tail())">>), - %% Freeing a slot resumes the paused job. - cell(A, <<"await j.stop()\nNone">>), - <<"False">> = cell(C, <<"await asyncio.sleep(0.3)\nj.queued">>), - %% A paused job still stops cleanly. - cell(B, <<"j2 = run('sleep', '30')\nawait asyncio.sleep(0.8)\nNone">>), - <<"(True, True)">> = cell(B, <<"(await j2.stop()).gone, j2.exit_code is not None or True">>) - after - [albedo_python:stop(K) || K <- Kernels] - end. - -%% A fresh detached kernel in /tmp whose session layer persists nothing: these -%% tests never reattach, so the link only has to answer. -start(Python, Script, Host, Modules) -> - Link = {link, fun(_, _) -> nil end, fun(_) -> nil end, fun() -> [] end, - fun(_) -> fresh end, fun(_, _, _) -> nil end, fun(_) -> nil end, fun() -> {ok, nil} end, fun(_) -> nil end}, - Id = binary:part(albedo_native:new_id(), 0, 16), - RunDir = filename:join(os:getenv("TMPDIR", "/tmp"), <<"albedo-run-", Id/binary>>), - Bridge = filename:join(filename:dirname(Script), <<"albedo_bridge.py">>), - albedo_python:start({boot, self(), Python, Bridge, <<"/tmp">>, Host, - iolist_to_binary(json:encode(Modules)), Link, unicode:characters_to_binary(RunDir), - Id, albedo_native:new_id(), 20, 0, <<"{}">>, true, none}). - -cell(Kernel, Code) -> - %% A kernel answers a cell id it already ran with that run's result. - Request = iolist_to_binary(json:encode(#{type => <<"execute">>, id => albedo_native:new_id(), code => Code})), - {ok, Reply} = albedo_python:execute(Kernel, Request, 5000), - #{<<"status">> := <<"ok">>, <<"value">> := Value} = json:decode(Reply), - Value. - -bootstrap() -> - {ok, {Python, Script}} = albedo_python:local_paths(), - Source = filename:dirname(binary_to_list(Script)), - Dir = filename:join("/tmp", "albedo-boot-job-" ++ binary_to_list(albedo_native:new_id())), - ok = file:make_dir(Dir), - try - {ok, Files} = file:list_dir(Source), - [case filelib:is_dir(filename:join(Source, F)) of - true -> file:make_symlink(filename:join(Source, F), filename:join(Dir, F)); - false -> file:copy(filename:join(Source, F), filename:join(Dir, F)) - end || F <- Files], - ok = file:make_dir(filename:join(Dir, "fixture")), - ok = file:write_file(filename:join([Dir, "fixture", "boot_job.py"]), - <<"from albedo_plugins.run import run\n" - "async def setup(api):\n" - " job = await run('printf', 'booted')\n" - " return {'boot_output': job.tail()}\n">>), - Host = fun(_) -> <<"{\"ok\":true,\"value\":null}">> end, - {ok, K} = start(Python, - unicode:characters_to_binary(filename:join(Dir, "albedo_kernel.py")), Host, - [<<"run">>, <<"fixture.boot_job">>]), - try <<"'booted'">> = cell(K, <<"boot_output">>), 0 = albedo_python:job_count(K) - after {ok, nil} = albedo_python:stop(K) end - after file:del_dir_r(Dir) end. diff --git a/test/harness/api_docs_test.py b/test/harness/api_docs_test.py index 3d3b8bd13..1be55c600 100644 --- a/test/harness/api_docs_test.py +++ b/test/harness/api_docs_test.py @@ -109,7 +109,7 @@ class ApiDocsTest(unittest.TestCase): for name in vars(run.Job) if not name.startswith("_") and f"run.Job.{name}" not in INTERNAL ] - fields = ["id", "command", "exit_code", "duration", "waited", "timed_out"] + fields = ["id", "command", "exit_code", "duration", "timed_out"] missing = [ name for name in public + fields if not re.search(rf"\bjob\.{name}\b", text) ] diff --git a/test/harness/job_slots_test.gleam b/test/harness/job_slots_test.gleam deleted file mode 100644 index d82025cc9..000000000 --- a/test/harness/job_slots_test.gleam +++ /dev/null @@ -1,11 +0,0 @@ -//// Shared admission must cap grants, bound its queue, and retain owned slots. -//// Barriers force grant and owner-death interleavings that E2E cannot order. - -import gleeunit/should - -@external(erlang, "albedo_job_slots_test_support", "check") -fn check() -> Bool - -pub fn shared_local_job_admission_test() -> Nil { - check() |> should.be_true -} diff --git a/test/harness/process_supervision_test.py b/test/harness/process_supervision_test.py index 41b3cec94..2f72637bc 100644 --- a/test/harness/process_supervision_test.py +++ b/test/harness/process_supervision_test.py @@ -1,4 +1,4 @@ -"""OS process-group identity, shutdown races and heavy-slot admission need controlled child processes rather than flaky daemon timing.""" +"""OS process-group identity and shutdown races need controlled child processes rather than flaky daemon timing.""" from __future__ import annotations @@ -24,7 +24,7 @@ albedo_proc.reap_stopped_safely(LOOP) EVENTS: list[dict[str, object]] = [] -def install(job_slot=None) -> None: +def install() -> None: plugin.setup( albedo_api.PythonApi( version=1, @@ -38,7 +38,6 @@ def install(job_slot=None) -> None: send=EVENTS.append, on_shutdown=lambda close: None, background_handle=lambda _: None, - job_slot=job_slot, ) ) @@ -183,8 +182,8 @@ class SupervisionTest(unittest.TestCase): run(job) self.assertIn(job.id, plugin.retained) - def test_surviving_group_keeps_its_slot_and_is_surfaced(self): - """A group that outlives KILL keeps its slot and is reported, not forgotten.""" + def test_surviving_group_stays_owned_and_is_surfaced(self): + """A group that outlives KILL stays owned and is reported, not forgotten.""" real = ( albedo_proc.alive, albedo_proc.current, @@ -203,7 +202,7 @@ class SupervisionTest(unittest.TestCase): job = start("true") wait(job) self.assertFalse(job.termination.gone) - self.assertIn(job.id, plugin.active) # work keeps its slot + self.assertIn(job.id, plugin.active) # surviving work stays owned self.assertNotIn(job.id, plugin.retained) self.assertIn("cleanup failed", job.tail()) run(plugin.close()) @@ -242,56 +241,6 @@ class SupervisionTest(unittest.TestCase): run(albedo_proc.terminate([albedo_proc.Group(leader.pid)])) run(leader.wait()) - def test_long_jobs_pause_for_a_heavy_slot_and_quick_ones_never_ask(self): - import subprocess - - async def check(): - asked: list[str] = [] - grant = LOOP.create_future() - - async def admission(id, on_queued): - asked.append(id) - on_queued() # no slot free: the job is paused - await grant - - install(admission) - grace = plugin.GRACE - plugin.GRACE = 0.2 - try: - quick = start("true") - await quick - self.assertEqual(asked, [], "a quick command must never ask for a slot") - slow = start("sleep 5", timeout=1.0) - await asyncio.sleep(0.5) - self.assertEqual(asked, [slow.id]) - self.assertTrue(slow.queued) - state = subprocess.run( - ["ps", "-o", "stat=", "-p", str(slow.process.pid)], - capture_output=True, - text=True, - ).stdout.strip() - self.assertTrue( - state.startswith("T"), - f"paused job should be stopped, ps says {state!r}", - ) - # Time spent paused does not count against the timeout. - await asyncio.sleep(1.2) - self.assertFalse(slow.task.done()) - grant.set_result(None) - await asyncio.sleep(0.1) - self.assertFalse(slow.queued) - await slow - self.assertTrue(slow.timed_out) - self.assertTrue(slow.termination.gone) - # The pause is reported apart from the time the job ran. - self.assertGreaterEqual(slow.waited, 1.2) - self.assertAlmostEqual(slow.duration, 1.0, delta=0.4) - finally: - plugin.GRACE = grace - await plugin.close() - - run(check()) - def test_stop_before_spawn_and_immediate_cancellation_keep_ownership(self): async def check(): job = start("sleep 30") diff --git a/test/harness/remote_kernel_test.py b/test/harness/remote_kernel_test.py index afc64bfef..4cef3125e 100644 --- a/test/harness/remote_kernel_test.py +++ b/test/harness/remote_kernel_test.py @@ -137,7 +137,6 @@ class KernelInvokeTest(unittest.TestCase): {"type": "reply", "id": "x", "value": {"ok": 1, "value": None}}, {"type": "reply", "id": "x", "value": {"ok": True}}, {"type": "reply", "id": "x", "value": {"ok": False, "code": "bad"}}, - {"type": "job_slot", "id": "x", "ok": "yes"}, {"type": "interrupt", "id": "x", "reason": "other"}, {"type": "restore", "id": "x", "path": None}, {"type": "release", "handle": []},