Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(computer): keep UI scripts alive on recoverable runtime errors

jeffrey72c218a150eb
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md
index f2e6f633..a46b8ebf 100644
--- a/apps/computer/local-daemon/README.md
+++ b/apps/computer/local-daemon/README.md
@@ -330,7 +330,10 @@ rejects dynamic code evaluation. The Daemon limits memory, runtime, call count
and output. Only the explicit `state` object is intended to persist between
calls within one Operation. `ui_reset` discards this state and image handles.
Applications and action records survive a reset. An unknown write outcome
-blocks further writes to its driver in this Operation.
+blocks further writes to its driver in this Operation. Every `ui_exec` and
+`ui_reset` result lists the Operation's unknown actions. Retained images share
+a 12 MiB budget; once it is spent, an action returns a text note in place of
+its image until `ui_reset`, so a completed action never reports an error.
Use `await ui.page(url)` for a managed browser and `ui.window(pid, window_id)`
for a macOS window. Use `ui.computer.list_windows({app: appName})` to discover
diff --git a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime.go b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime.go
index 1ac8507c..f051d253 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime.go
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
+ "net"
"net/http"
"path/filepath"
"strconv"
@@ -35,18 +36,21 @@ type uiDispatchReceipt struct {
// uiExecution keeps script state for one Operation and execution lease.
type uiExecution struct {
- cancel context.CancelFunc
- set *mcpproxy.Set
- endpoints map[string]mcpproxy.ToolEndpoint
- catalogs map[string][]tool
- engine *uiruntime.Runtime
- server *toolServer
- slot chan struct{}
- closeOnce sync.Once
- closeErr error
- sequence uint64
- blocked map[string]bool
- receipts []uiDispatchReceipt
+ cancel context.CancelFunc
+ set *mcpproxy.Set
+ endpoints map[string]mcpproxy.ToolEndpoint
+ catalogs map[string][]tool
+ engine *uiruntime.Runtime
+ server *toolServer
+ slot chan struct{}
+ closeOnce sync.Once
+ closeErr error
+ sequence uint64
+ blocked map[string]bool
+ receipts []uiDispatchReceipt
+ // unknown keeps every unknown-outcome receipt for the Operation; a lost
+ // response or a reset must not hide which action may have applied.
+ unknown []uiDispatchReceipt
lastResults map[string]json.RawMessage
images map[string]json.RawMessage
imageBytes int
@@ -117,13 +121,13 @@ func unifiedUITools() []tool {
func (u *uiExecution) call(ctx context.Context, name string, args json.RawMessage) (json.RawMessage, error) {
if !u.set.ToolReviewerReady() {
- return nil, errors.New("UI action reviewer is not ready for this Operation")
+ return nil, fmt.Errorf("UI action reviewer is not ready for this Operation: %w", errNotSent)
}
select {
case u.slot <- struct{}{}:
defer func() { <-u.slot }()
default:
- return nil, errors.New("UI execution is busy; await the current call")
+ return nil, fmt.Errorf("UI execution is busy; await the current call: %w", errNotSent)
}
if err := schedulingError(ctx); err != nil {
return nil, err
@@ -138,7 +142,7 @@ func (u *uiExecution) call(ctx context.Context, name string, args json.RawMessag
}
u.images = map[string]json.RawMessage{}
u.imageBytes = 0
- return uiTextResult(map[string]any{"reset": true, "generation": u.engine.Generation(), "unknown_actions_preserved": true}), nil
+ return uiTextResult(map[string]any{"reset": true, "generation": u.engine.Generation(), "unknown_actions": u.unknown}), nil
}
if name != "ui_exec" {
return nil, errors.New("unknown UI entry")
@@ -170,6 +174,9 @@ func (u *uiExecution) call(ctx context.Context, name string, args json.RawMessag
result, err := u.engine.Exec(ctx, scheduling, input.Code)
defer func() { u.syncImageGeneration(u.engine.Generation()) }()
summary := map[string]any{"generation": result.Generation, "value": result.Value, "receipts": u.receipts}
+ if len(u.unknown) > 0 {
+ summary["unknown_actions"] = u.unknown
+ }
if current := u.engine.Generation(); current != result.Generation {
summary["state_reset"] = true
summary["current_generation"] = current
@@ -283,10 +290,7 @@ func (u *uiExecution) dispatch(ctx context.Context, call uiruntime.Call) (json.R
u.receipts[index].Status = "not_dispatched"
return nil, err
}
- u.receipts[index].Status = "unknown"
- if write {
- u.blocked[endpoint.Name] = true
- }
+ u.markUnknown(index, write)
return nil, fmt.Errorf("UI tool outcome is unknown; do not replay: %w", err)
}
var envelope struct {
@@ -297,10 +301,7 @@ func (u *uiExecution) dispatch(ctx context.Context, call uiruntime.Call) (json.R
Structured json.RawMessage `json:"structuredContent"`
}
if json.Unmarshal(result, &envelope) != nil || envelope.Content == nil {
- u.receipts[index].Status = "unknown"
- if write {
- u.blocked[endpoint.Name] = true
- }
+ u.markUnknown(index, write)
return nil, errors.New("UI tool returned an invalid result; outcome unknown")
}
var structured struct {
@@ -308,10 +309,7 @@ func (u *uiExecution) dispatch(ctx context.Context, call uiruntime.Call) (json.R
}
_ = json.Unmarshal(envelope.Structured, &structured)
if structured.Outcome == "unknown" {
- u.receipts[index].Status = "unknown"
- if write {
- u.blocked[endpoint.Name] = true
- }
+ u.markUnknown(index, write)
return nil, errors.New("UI tool outcome is unknown; inspect the current state")
}
if envelope.IsError {
@@ -339,6 +337,14 @@ func (u *uiExecution) dispatch(ctx context.Context, call uiruntime.Call) (json.R
return retained, err
}
+func (u *uiExecution) markUnknown(index int, write bool) {
+ u.receipts[index].Status = "unknown"
+ u.unknown = append(u.unknown, u.receipts[index])
+ if write {
+ u.blocked[u.receipts[index].Server] = true
+ }
+}
+
func (u *uiExecution) syncImageGeneration(generation uint64) {
if generation == u.generation {
return
@@ -422,6 +428,9 @@ func (u *uiExecution) rpc(ctx context.Context, endpoint mcpproxy.ToolEndpoint, m
}
response, err := http.DefaultClient.Do(request)
if err != nil {
+ if opErr := (*net.OpError)(nil); errors.As(err, &opErr) && opErr.Op == "dial" {
+ return nil, fmt.Errorf("local UI server is unreachable: %w: %w", err, errNotSent)
+ }
return nil, err
}
defer response.Body.Close()
@@ -470,7 +479,9 @@ func (u *uiExecution) retainImages(raw json.RawMessage) (json.RawMessage, error)
continue
}
if u.imageBytes+len(part) > uiImageBudget {
- return nil, errors.New("UI image budget exhausted; emit required images and reset state")
+ // The action already completed, so an error here would invite a replay.
+ content[i], _ = json.Marshal(map[string]string{"type": "text", "text": "Image omitted: the UI image budget is exhausted. Call ui_reset to capture more images."})
+ continue
}
id := rand.Text()
u.images[id] = part
diff --git a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_test.go b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_test.go
index 23b92779..02d93670 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_test.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"io"
+ "net"
"net/http"
"os/exec"
"path/filepath"
@@ -215,9 +216,12 @@ func TestUnifiedUIResetDoesNotClearUnknownWrites(t *testing.T) {
if !strings.Contains(string(first), `"status":"unknown"`) {
t.Fatalf("unknown not retained: %s", first)
}
- f.rpc(t, t.Context(), "tools/call", map[string]any{"name": "ui_reset", "arguments": map[string]any{}})
+ reset := f.rpc(t, t.Context(), "tools/call", map[string]any{"name": "ui_reset", "arguments": map[string]any{}})
+ if !strings.Contains(string(reset), `\"unknown_actions\":[{\"server\":\"browser\",\"method\":\"browser_click\",\"status\":\"unknown\"}]`) {
+ t.Fatalf("reset hid the unknown action: %s", reset)
+ }
second := f.execute(t, `await ui.browser.click({});`)
- if !strings.Contains(string(second), "cannot send further writes") || writes.Load() != 1 {
+ if !strings.Contains(string(second), "cannot send further writes") || !strings.Contains(string(second), `"unknown_actions"`) || writes.Load() != 1 {
t.Fatalf("unknown replayed: %s %d", second, writes.Load())
}
read := f.execute(t, `return await ui.browser.snapshot({});`)
@@ -369,3 +373,25 @@ func TestUnifiedUIExpandedImagesStayBounded(t *testing.T) {
t.Fatal(string(nested))
}
}
+
+func TestUIImageBudgetNeverFailsACompletedAction(t *testing.T) {
+ u := &uiExecution{images: map[string]json.RawMessage{}, imageBytes: uiImageBudget}
+ got, err := u.retainImages(json.RawMessage(`{"content":[{"type":"image","data":"AAAA","mimeType":"image/png"},{"type":"text","text":"clicked"}]}`))
+ if err != nil || len(u.images) != 0 || !strings.Contains(string(got), "Image omitted") || !strings.Contains(string(got), "clicked") {
+ t.Fatalf("got=%s err=%v", got, err)
+ }
+}
+
+func TestUIUnreachableDriverIsNotDispatched(t *testing.T) {
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ address := listener.Addr().String()
+ _ = listener.Close()
+ u := &uiExecution{}
+ _, err = u.rpc(t.Context(), mcpproxy.ToolEndpoint{Name: "browser", URL: "http://" + address + "/mcp"}, "tools/call", map[string]any{})
+ if !errors.Is(err, errNotSent) {
+ t.Fatalf("err=%v", err)
+ }
+}
diff --git a/apps/computer/local-daemon/internal/uiruntime/runtime.go b/apps/computer/local-daemon/internal/uiruntime/runtime.go
index 596ac24e..de36580c 100644
--- a/apps/computer/local-daemon/internal/uiruntime/runtime.go
+++ b/apps/computer/local-daemon/internal/uiruntime/runtime.go
@@ -30,6 +30,7 @@ var (
ErrClosed = errors.New("UI runtime is closed")
// ErrCleanupUnconfirmed prevents replacing a child whose cleanup is unknown.
ErrCleanupUnconfirmed = errors.New("UI runtime child cleanup is unconfirmed")
+ errFrameTooLarge = errors.New("UI protocol frame exceeds byte limit")
)
// Limits bound execution and protocol resources. RSSMiB is a supervised
@@ -253,6 +254,11 @@ func (r *Runtime) Exec(hardCtx, schedulingCtx context.Context, code string) (res
return result, errors.New("UI dispatcher returned invalid JSON")
}
err = c.send(hard, map[string]any{"type": "reply", "execution": execution, "id": msg.ID, "value": value}, r.opts.Limits.MaxProtocolBytes)
+ if errors.Is(err, errFrameTooLarge) {
+ // The action has completed; reject only this call so the
+ // script keeps its state and can read a smaller result.
+ err = c.send(hard, map[string]any{"type": "reply", "execution": execution, "id": msg.ID, "error": "UI call result exceeds byte limit"}, r.opts.Limits.MaxProtocolBytes)
+ }
}
if err != nil {
return result, err
@@ -411,17 +417,22 @@ func (c *child) stop() {
func (r *Runtime) ensureChild(hard, scheduling context.Context) (*child, error) {
r.mu.Lock()
c := r.child
+ // A cancellation can invalidate the child after its last Exec returned.
+ usable := c != nil && !c.invalid
r.mu.Unlock()
if c != nil {
select {
case <-c.exited:
- r.invalidate(c)
- if err := r.reap(c); err != nil {
- return nil, err
- }
+ usable = false
default:
+ }
+ if usable {
return c, nil
}
+ r.invalidate(c)
+ if err := r.reap(c); err != nil {
+ return nil, err
+ }
}
engineDir, err := filepath.EvalSymlinks(r.opts.QuickJSDirectory)
if err != nil {
@@ -496,7 +507,7 @@ func (c *child) send(ctx context.Context, value any, limit int) error {
return err
}
if len(data) >= limit {
- return errors.New("UI protocol frame exceeds byte limit")
+ return errFrameTooLarge
}
done := make(chan error, 1)
go func() { _, err := c.stdin.Write(append(data, '\n')); done <- err }()
diff --git a/apps/computer/local-daemon/internal/uiruntime/runtime.mjs b/apps/computer/local-daemon/internal/uiruntime/runtime.mjs
index 926c15b7..b8c056bf 100644
--- a/apps/computer/local-daemon/internal/uiruntime/runtime.mjs
+++ b/apps/computer/local-daemon/internal/uiruntime/runtime.mjs
@@ -26,13 +26,14 @@ const options = {
interruptHandler: () => performance.now() >= deadline,
};
const compiler = await QuickJS.create(options);
-const unhandled = new Set();
+// QuickJS reports a promise as handled only after reporting it unhandled, and
+// its promise handle is not a stable identity, so a count tracks the balance.
+let unhandled = 0;
const guest = await QuickJS.create({
...options,
intrinsics: Intrinsics.ALL & ~Intrinsics.EVAL,
- onUnhandledRejection(promise, _reason, handled) {
- if (handled) unhandled.delete(promise.ptr);
- else unhandled.add(promise.ptr);
+ onUnhandledRejection(_promise, _reason, handled) {
+ unhandled += handled ? -1 : 1;
},
});
const drain = compiler.compile("__uiBridge.drain()");
@@ -64,7 +65,7 @@ function evaluate(source) {
source === drain ? drain : compiler.compile(source),
);
guest.executePendingJobs();
- if (unhandled.size) throw new Error("UI unhandled asynchronous rejection");
+ if (unhandled > 0) throw new Error("UI unhandled asynchronous rejection");
return value.typeof === "string" ? value.toString() : undefined;
} finally {
deadline = Infinity;
@@ -92,12 +93,15 @@ evaluate(`(() => {
const revisions = {browser:0, computer:0};
const call = (owner, namespace, method, args) => {
if (owner !== epoch || !active || completed) return Promise.reject(new Error('UI execution is not active'));
+ // Serialize before taking an ID: a thrown argument must not leave a gap
+ // in the call sequence that the Daemon validates.
+ const argumentsValue = clone(args === undefined ? {} : args);
if (++next > maxCalls) {
failure = 'UI call limit exceeded';
return Promise.reject(new Error(failure));
}
if (namespace === 'browser' || namespace === 'computer') ++revisions[namespace];
- const argumentsValue = clone(args === undefined ? {} : args), id = next;
+ const id = next;
const promise = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
queue.push({ type: 'call', id, namespace, method, arguments: argumentsValue });
return promise;
@@ -310,8 +314,8 @@ process.stdin.on("data", (chunk) => {
}
if (input.length >= limits.maxProtocolBytes)
throw new Error("UI protocol frame exceeds byte limit");
- } catch {
- fail("UI protocol or execution failed");
+ } catch (error) {
+ fail(`UI protocol or execution failed: ${error?.message ?? error}`);
}
});
process.stdin.on("end", () => {
diff --git a/apps/computer/local-daemon/internal/uiruntime/runtime_test.go b/apps/computer/local-daemon/internal/uiruntime/runtime_test.go
index da70d5f5..42194a09 100644
--- a/apps/computer/local-daemon/internal/uiruntime/runtime_test.go
+++ b/apps/computer/local-daemon/internal/uiruntime/runtime_test.go
@@ -511,3 +511,42 @@ return after.text.includes("Route");`)
t.Fatalf("batch count=%d result=%+v", fills, result)
}
}
+func TestLateHandledRejectionKeepsState(t *testing.T) {
+ r := nodeRuntime(t, noCalls(t), Limits{})
+ first := execute(t, r, `state.kept = 1; const p = Promise.reject(new Error("x")); await null; try { await p } catch {} return "caught";`)
+ second := execute(t, r, `return state.kept;`)
+ if string(first.Value) != `"caught"` || string(second.Value) != "1" || second.Generation != first.Generation {
+ t.Fatalf("first=%+v second=%+v", first, second)
+ }
+}
+func TestUnserializableArgumentsDoNotConsumeCallID(t *testing.T) {
+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) { return c.Arguments, nil }, Limits{})
+ result := execute(t, r, `const cyclic = {}; cyclic.self = cyclic;
+for (const bad of [{n: 1n}, cyclic]) { try { await ui.browser.click(bad); return "sent"; } catch {} }
+return await ui.browser.click({ok: true});`)
+ if string(result.Value) != `{"ok":true}` {
+ t.Fatalf("result=%+v", result)
+ }
+}
+func TestOversizedDispatchResultRejectsOnlyTheCall(t *testing.T) {
+ large := json.RawMessage(`"` + strings.Repeat("a", 4096) + `"`)
+ r := nodeRuntime(t, func(context.Context, Call) (json.RawMessage, error) { return large, nil }, Limits{MaxProtocolBytes: 2048, MaxOutputBytes: 1024})
+ first := execute(t, r, `state.kept = 1; try { await ui.browser.snapshot({}); return "delivered"; } catch (error) { return error.message; }`)
+ second := execute(t, r, `return state.kept;`)
+ if !strings.Contains(string(first.Value), "byte limit") || string(second.Value) != "1" || second.Generation != first.Generation {
+ t.Fatalf("first=%+v second=%+v", first, second)
+ }
+}
+func TestInvalidatedIdleChildIsReplaced(t *testing.T) {
+ r := nodeRuntime(t, noCalls(t), Limits{})
+ first := execute(t, r, `return 1;`)
+ r.mu.Lock()
+ c := r.child
+ r.mu.Unlock()
+ // Models a cancellation that lands after Exec has already returned.
+ r.invalidate(c)
+ second := execute(t, r, `return 2;`)
+ if string(second.Value) != "2" || second.Generation <= first.Generation {
+ t.Fatalf("second=%+v", second)
+ }
+}