Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: keep sandbox images a box still uses

ogsamrat8d9c61de64cc
diff --git a/apps/desktop/box/go/cmd/boxrun/imageuse.go b/apps/desktop/box/go/cmd/boxrun/imageuse.go
new file mode 100644
index 00000000..5e8ba807
--- /dev/null
+++ b/apps/desktop/box/go/cmd/boxrun/imageuse.go
@@ -0,0 +1,99 @@
+//go:build linux
+
+package main
+
+// Which boxes use which unpacked image, so `rmimage` never deletes the lower
+// layer of a box that still exists (running or stopped). `up` records the
+// image in <box>/image.id and registers the box in <store>/refs/<id>/; both
+// happen under the image's store lock, the same lock `rmimage` holds while it
+// checks and deletes.
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+)
+
+const boxImageFile = "image.id"
+
+func refsDir(store, id string) string { return filepath.Join(store, "refs", id) }
+
+func boxRefName(box string) string {
+ sum := sha256.Sum256([]byte(box))
+ return hex.EncodeToString(sum[:12])
+}
+
+// boxImage is the image id a box records, or "".
+func boxImage(box string) string {
+ data, err := os.ReadFile(filepath.Join(box, boxImageFile))
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(data))
+}
+
+// recordImageUse marks `box` as a user of image `id` (and no longer of the one it ran on before).
+func recordImageUse(store, box, id string) error {
+ if old := boxImage(box); old != "" && old != id && !strings.ContainsAny(old, "/\\.") {
+ _ = os.Remove(filepath.Join(refsDir(store, old), boxRefName(box)))
+ }
+ if err := os.MkdirAll(box, 0o755); err != nil {
+ return err
+ }
+ if err := os.WriteFile(filepath.Join(box, boxImageFile), []byte(id+"\n"), 0o644); err != nil {
+ return err
+ }
+ if err := os.MkdirAll(refsDir(store, id), 0o700); err != nil {
+ return err
+ }
+ return os.WriteFile(filepath.Join(refsDir(store, id), boxRefName(box)), []byte(box+"\n"), 0o600)
+}
+
+// imageUsers lists the boxes that still use image `id`: the ones registered
+// in the store (a registration whose box is gone or now runs another image is
+// dropped) and any box folder directly under one of `roots` recording it.
+func imageUsers(store, id string, roots []string) []string {
+ seen := map[string]bool{}
+ var users []string
+ add := func(box string) {
+ if !seen[box] {
+ seen[box] = true
+ users = append(users, box)
+ }
+ }
+ dir := refsDir(store, id)
+ entries, _ := os.ReadDir(dir)
+ for _, e := range entries {
+ file := filepath.Join(dir, e.Name())
+ data, err := os.ReadFile(file)
+ if err != nil {
+ continue
+ }
+ box := strings.TrimSpace(string(data))
+ if info, err := os.Stat(box); err == nil && info.IsDir() && boxImage(box) == id {
+ add(box)
+ continue
+ }
+ _ = os.Remove(file)
+ }
+ for _, root := range roots {
+ if root == "" {
+ continue
+ }
+ subs, _ := os.ReadDir(root)
+ for _, s := range subs {
+ if !s.IsDir() {
+ continue
+ }
+ box := filepath.Join(root, s.Name())
+ if boxImage(box) == id {
+ add(box)
+ }
+ }
+ }
+ sort.Strings(users)
+ return users
+}
diff --git a/apps/desktop/box/go/cmd/boxrun/imageuse_test.go b/apps/desktop/box/go/cmd/boxrun/imageuse_test.go
new file mode 100644
index 00000000..876db2e6
--- /dev/null
+++ b/apps/desktop/box/go/cmd/boxrun/imageuse_test.go
@@ -0,0 +1,75 @@
+//go:build linux
+
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func unpacked(t *testing.T, store, id string) string {
+ t.Helper()
+ dir := filepath.Join(store, "images", id)
+ if err := os.MkdirAll(filepath.Join(dir, "rootfs", "usr"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ os.WriteFile(filepath.Join(dir, "image.json"), []byte(`{"ref":"ghcr.io/omnirush-ai/box-base@sha256:x"}`), 0o644)
+ return dir
+}
+
+func TestRmImageRefusesWhileABoxUsesIt(t *testing.T) {
+ root := t.TempDir()
+ store, boxes := filepath.Join(root, "store"), filepath.Join(root, "boxes")
+ img1, img2 := unpacked(t, store, "img1-amd64"), unpacked(t, store, "img2-amd64")
+ boxA := filepath.Join(boxes, "a")
+ // A stopped box (no state.json): only its folder and its record of the image.
+ if err := recordImageUse(store, boxA, "img1-amd64"); err != nil {
+ t.Fatal(err)
+ }
+ if err := cmdRmImage([]string{"--store", store, "--id", "img1-amd64"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(img1); err != nil {
+ t.Fatal("deleted the image a stopped box still runs on")
+ }
+ if got := imageUsers(store, "img1-amd64", nil); len(got) != 1 || got[0] != boxA {
+ t.Fatalf("users %v", got)
+ }
+
+ // A box found only under --boxes (no registration in the store) also keeps its image.
+ boxB := filepath.Join(boxes, "b")
+ os.MkdirAll(boxB, 0o755)
+ os.WriteFile(filepath.Join(boxB, boxImageFile), []byte("img2-amd64\n"), 0o644)
+ cmdRmImage([]string{"--store", store, "--id", "img2-amd64", "--boxes", boxes})
+ if _, err := os.Stat(img2); err != nil {
+ t.Fatal("deleted the image of a box under --boxes")
+ }
+
+ // The box moves to another image: the old one is free again.
+ unpacked(t, store, "img3-amd64")
+ if err := recordImageUse(store, boxA, "img3-amd64"); err != nil {
+ t.Fatal(err)
+ }
+ if err := cmdRmImage([]string{"--store", store, "--id", "img1-amd64"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(img1); !os.IsNotExist(err) {
+ t.Fatal("an image no box uses was kept")
+ }
+
+ // The box is removed (`boxrun rm`): its registration is stale and the image goes.
+ os.RemoveAll(boxA)
+ if err := cmdRmImage([]string{"--store", store, "--id", "img3-amd64"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(store, "images", "img3-amd64")); !os.IsNotExist(err) {
+ t.Fatal("the image of a removed box was kept")
+ }
+ if _, err := os.Stat(refsDir(store, "img3-amd64")); !os.IsNotExist(err) {
+ t.Fatal("refs left behind")
+ }
+ if err := cmdRmImage([]string{"--store", store, "--id", "../x"}); err == nil {
+ t.Fatal("a path as an id was accepted")
+ }
+}
diff --git a/apps/desktop/box/go/cmd/boxrun/main.go b/apps/desktop/box/go/cmd/boxrun/main.go
index f499204e..b00db49d 100644
--- a/apps/desktop/box/go/cmd/boxrun/main.go
+++ b/apps/desktop/box/go/cmd/boxrun/main.go
@@ -13,7 +13,7 @@
// boxrun pull --store DIR --ref REF [--arch A] download + unpack an image
// boxrun import --store DIR --file TAR [--ref REF] [--arch A] unpack `docker save` / a rootfs tar
// boxrun image --store DIR --ref REF [--arch A] the unpacked image, if any
-// boxrun rmimage --store DIR --id ID delete an unpacked image
+// boxrun rmimage --store DIR --id ID [--boxes DIR]... delete an unpacked image no box uses
// boxrun up --box DIR --store DIR --image ID --boxd FILE ... start (or reuse) a project's box
// boxrun stop --box DIR stop it (the upper layer stays)
// boxrun rm --box DIR stop it and delete its layer
@@ -234,15 +234,29 @@ func cmdRmImage(args []string) error {
fs := newFlags("rmimage")
store := fs.String("store", "", "image store folder")
id := fs.String("id", "", "image id")
+ var roots multi
+ fs.Var(&roots, "boxes", "a folder whose subfolders are boxes (repeat): one recording this image keeps it")
if err := fs.Parse(args); err != nil {
return err
}
if *store == "" || *id == "" || strings.ContainsAny(*id, "/\\.") {
return errors.New("--store and a plain --id are needed")
}
+ st := oci.Store{Dir: *store}
+ unlock, err := st.Lock(*id)
+ if err != nil {
+ return err
+ }
+ defer unlock()
+ // Never the lower layer of a box that still exists, running or stopped.
+ if users := imageUsers(*store, *id, roots); len(users) > 0 {
+ emit(map[string]any{"ok": false, "in_use": true, "id": *id, "boxes": users})
+ return nil
+ }
if err := removeTree(filepath.Join(*store, "images", *id)); err != nil {
return err
}
+ _ = os.RemoveAll(refsDir(*store, *id))
emit(map[string]any{"ok": true, "removed": *id})
return nil
}
@@ -707,6 +721,13 @@ func cmdUp(args []string) error {
start := time.Now()
if s := readState(*box); alive(s) {
if port := readPort(*portFile); port > 0 && portOpen(port) {
+ // A box started by an older boxrun is registered now (best effort).
+ if boxImage(*box) != *image && !strings.ContainsAny(*image, "/\\.") {
+ if unlock, err := (oci.Store{Dir: *store}).Lock(*image); err == nil {
+ _ = recordImageUse(*store, *box, *image)
+ unlock()
+ }
+ }
emit(map[string]any{"ok": true, "reused": true, "pid": s.Pid, "port": port, "launcher": s.Launcher, "idmap": s.IDMap, "overlay": s.Overlay, "ms": time.Since(start).Milliseconds()})
if *foreground {
keep(nil)
@@ -716,10 +737,21 @@ func cmdUp(args []string) error {
killTree(s.Pid)
}
st := oci.Store{Dir: *store}
+ unlockImage, err := st.Lock(*image)
+ if err != nil {
+ return err
+ }
img := st.Lookup(*image)
if img == nil {
+ unlockImage()
return fmt.Errorf("image %s is not unpacked", *image)
}
+ // Registered before the box uses it, under the lock rmimage holds: it is never deleted under the box.
+ err = recordImageUse(*store, *box, *image)
+ unlockImage()
+ if err != nil {
+ return err
+ }
for _, d := range []string{"upper", "work"} {
if err := os.MkdirAll(filepath.Join(*box, d), 0o755); err != nil {
return err
diff --git a/apps/desktop/box/go/oci/store.go b/apps/desktop/box/go/oci/store.go
index 51a13106..1dcfad59 100644
--- a/apps/desktop/box/go/oci/store.go
+++ b/apps/desktop/box/go/oci/store.go
@@ -82,6 +82,9 @@ func (s Store) tagFile(ref Ref, arch string) string {
return filepath.Join(s.Dir, "tags", hex.EncodeToString(sum[:12]))
}
+// Lock is lock for callers outside the package (rmimage and up: one image-use change at a time).
+func (s Store) Lock(id string) (func(), error) { return s.lock(id) }
+
// lock takes an exclusive lock for an image id (one unpack at a time).
func (s Store) lock(id string) (func(), error) {
dir := filepath.Join(s.Dir, "locks")
diff --git a/apps/server/src/box/backends/bwrap.ts b/apps/server/src/box/backends/bwrap.ts
index 3383d572..93d33247 100644
--- a/apps/server/src/box/backends/bwrap.ts
+++ b/apps/server/src/box/backends/bwrap.ts
@@ -259,7 +259,8 @@ export const bwrapDriver: BoxDriver = {
if (!img || !removableImage({ ref: img.ref, digest: img.digest, id }, { keep, used: usedIds })) continue;
try { if (now - statSync(path.join(dir, id, "image.json")).mtimeMs < YOUNG_IMAGE_MS) continue; } catch { continue; }
if (dryRun) { removed.push({ kind: "image", name: String(img.ref), reason: "not current", path: path.join(dir, id), dryRun: true }); continue; }
- const res = await run(runtime.bin, ["rmimage", ...storeArgs(home), "--id", id], { timeoutMs: 120_000 });
+ // boxrun itself also refuses while any box (running or stopped) records this image.
+ const res = await run(runtime.bin, ["rmimage", ...storeArgs(home), "--id", id, "--boxes", path.join(bwrapHome(home), "boxes")], { timeoutMs: 120_000 });
if (parseOut(res.stdout)?.ok) removed.push({ kind: "image", name: String(img.ref), reason: "not current" });
}
return removed;
diff --git a/apps/server/src/box/backends/wsl.ts b/apps/server/src/box/backends/wsl.ts
index a5fa956d..9a804a60 100644
--- a/apps/server/src/box/backends/wsl.ts
+++ b/apps/server/src/box/backends/wsl.ts
@@ -463,7 +463,7 @@ export const wslDriver: BoxDriver = {
if (!Number.isFinite(unpackedAt) || unpackedAt <= 0 || now - unpackedAt < YOUNG_IMAGE_MS) continue;
if (!/^[0-9a-zA-Z._-]+$/.test(id) || !removableImage({ ref: img?.ref, digest: img?.digest, id }, { keep, used: usedIds })) continue;
if (dryRun) { removed.push({ kind: "image", name: String(img?.ref), reason: "not current", dryRun: true }); continue; }
- const { out } = await boxrun(wsl, ["rmimage", "--store", STORE, "--id", id], { run, env, timeoutMs: 120_000 });
+ const { out } = await boxrun(wsl, ["rmimage", "--store", STORE, "--id", id, "--boxes", BOXES], { run, env, timeoutMs: 120_000 });
if (out?.ok) removed.push({ kind: "image", name: String(img?.ref), reason: "not current" });
}
return removed;