Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(execenv): expose shared bundled marketplaces in per-task codex-home (#10881)

苗大5f74c8ec80dc
diff --git a/server/internal/daemon/execenv/codex_bundled_marketplaces.go b/server/internal/daemon/execenv/codex_bundled_marketplaces.go
new file mode 100644
index 0000000000..27b5204899
--- /dev/null
+++ b/server/internal/daemon/execenv/codex_bundled_marketplaces.go
@@ -0,0 +1,327 @@
+package execenv
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/pelletier/go-toml/v2/unstable"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// codexBundledMarketplacesRelPath is the directory under a CODEX_HOME where
+// the Codex CLI resolves bundled plugin marketplaces (openai-bundled:
+// browser, chrome, computer-use, ...). The same relative location inside the
+// shared home is where ChatGPT Desktop materializes them from the app bundle.
+const codexBundledMarketplacesRelPath = ".tmp" + string(filepath.Separator) + "bundled-marketplaces"
+
+// exposeSharedCodexBundledMarketplaces links the shared home's bundled
+// marketplaces into the per-task CODEX_HOME and repoints the task config's
+// local marketplace sources at the linked copy.
+//
+// Why this exists: the user's shared ~/.codex/config.toml registers the
+// bundled plugin marketplaces with an absolute local source inside the shared
+// home, because ChatGPT Desktop materializes them there (for example
+// `~/.codex/.tmp/bundled-marketplaces/openai-bundled`). The Codex CLI resolves
+// bundled-marketplace sources against the ACTIVE CODEX_HOME and silently
+// drops any whose source is not inside it — a config copied verbatim into the
+// per-task home therefore loses the whole openai-bundled marketplace, even
+// though the shared directory exists and is readable.
+//
+// The browser plugin in that marketplace owns the Stop / Interrupt /
+// SubagentStop hooks that notify the node_repl MCP server (`turn_ended`) when
+// a turn finishes. Without the marketplace the hooks never load, and a task
+// that drove the browser through node_repl leaves its tabs behind: unmarked
+// tabs stay open after completion, and a markDeliverable tab keeps the
+// finished session's browser-session lock so a later session's claimTab fails.
+//
+// The link mirrors exposeSharedCodexPluginCache: one directory link, shared
+// contents stay shared, task reclamation only ever removes the link. A shared
+// home without bundled marketplaces (a CLI-only machine) is a no-op — the
+// daemon never creates the shared directory, it only surfaces what the
+// desktop app already materialized.
+func exposeSharedCodexBundledMarketplaces(codexHome, sharedHome string) error {
+ src := filepath.Join(sharedHome, filepath.FromSlash(codexBundledMarketplacesRelPath))
+ fi, err := os.Stat(src)
+ if err != nil {
+ if os.IsNotExist(err) {
+ // Nothing materialized in the shared home — nothing to expose. Do
+ // not create the shared directory: bundled marketplaces belong to
+ // the desktop app, not to the daemon.
+ return nil
+ }
+ // A read failure is not "absent": swallowing it would leave the task
+ // silently without its marketplaces and the operator without a clue
+ // (the caller warns on every error this function returns).
+ return fmt.Errorf("stat shared bundled marketplaces %s: %w", src, err)
+ }
+ if !fi.IsDir() {
+ return nil
+ }
+ dst := filepath.Join(codexHome, filepath.FromSlash(codexBundledMarketplacesRelPath))
+ if err := verifyTaskHomeComponentsForLink(codexHome, filepath.Dir(dst)); err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
+ return fmt.Errorf("create codex .tmp dir: %w", err)
+ }
+
+ if fi, err := os.Lstat(dst); err == nil {
+ isLink := fi.Mode()&os.ModeSymlink != 0
+ if isLink {
+ if target, readlinkErr := os.Readlink(dst); readlinkErr == nil && target == src {
+ return rewriteSharedBundledMarketplaceSources(filepath.Join(codexHome, "config.toml"), src, dst)
+ }
+ if err := os.Remove(dst); err != nil {
+ return fmt.Errorf("remove stale bundled marketplaces link: %w", err)
+ }
+ } else {
+ if err := os.RemoveAll(dst); err != nil {
+ return fmt.Errorf("remove stale bundled marketplaces path: %w", err)
+ }
+ }
+ }
+
+ if err := createDirLink(src, dst); err != nil {
+ return fmt.Errorf("expose shared bundled marketplaces: %w", err)
+ }
+ return rewriteSharedBundledMarketplaceSources(filepath.Join(codexHome, "config.toml"), src, dst)
+}
+
+// verifyTaskHomeComponentsForLink refuses to touch the link destination when
+// a path component the daemon is about to create into, delete through, or
+// place a link under is itself a link out of the task home. Reuse hands the
+// daemon a home a previous task (and its descendants, unconfirmed on
+// Windows) could write; if `.tmp` had been swapped for a symlink, MkdirAll
+// and RemoveAll here would follow it outside the home. The leaf itself is
+// safe either way — os.Remove/RemoveAll only ever unlink a symlinked leaf —
+// so the check is about the interior, not the destination.
+func verifyTaskHomeComponentsForLink(codexHome, tmpDir string) error {
+ if fi, err := os.Lstat(codexHome); err != nil {
+ return fmt.Errorf("stat codex home %s: %w", codexHome, err)
+ } else if fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() {
+ return fmt.Errorf("codex home %s is not a real directory; refusing to place bundled marketplaces link", codexHome)
+ }
+ fi, err := os.Lstat(tmpDir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return fmt.Errorf("stat codex home .tmp %s: %w", tmpDir, err)
+ }
+ if fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() {
+ return fmt.Errorf("codex home .tmp %s is not a real directory; refusing to place bundled marketplaces link", tmpDir)
+ }
+ return nil
+}
+
+// rewriteSharedBundledMarketplaceSources rewrites the per-task config.toml's
+// local marketplace sources that point into the shared home's bundled
+// marketplaces directory so they point at the same location inside the task
+// home instead.
+//
+// The rewrite works on the TOML AST, not on lines: go-toml's unstable parser
+// reports every key/value's exact byte range, so whichever of the many valid
+// spellings a config uses — plain tables, trailing comments, bare or quoted
+// keys, dotted keys at the top level, inline tables, single- or multi-line
+// strings — the same logical field is found and nothing else can be touched.
+// That last part is the safety property: a string VALUE that happens to
+// contain text like `source = "..."` (an MCP env entry, say) is one AST node
+// whose bytes are replaced only if its key path is a marketplace source, and
+// its interior is never scanned. A config the parser rejects is left
+// untouched (and reported): the CLI would reject it too, so there is nothing
+// for this step to fix.
+//
+// A source is repointed only when it resolves inside sharedBundledRoot,
+// which is precise enough on its own: Git marketplace sources are URLs, and
+// other local marketplaces (e.g. openai-primary-runtime under ~/.cache)
+// resolve elsewhere and keep their absolute paths — the CLI only requires
+// bundled ones to live inside the active CODEX_HOME. A source already spelled
+// as its task-home destination maps back to itself through the link and is
+// reported as "nothing to change", so prepare and reuse can both run it
+// without ever rewriting the same bytes twice.
+func rewriteSharedBundledMarketplaceSources(configPath, sharedBundledRoot, codexBundledRoot string) error {
+ data, err := os.ReadFile(configPath)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("read config.toml: %w", err)
+ }
+
+ replacements, err := locateMarketplaceSourceRewrites(data, sharedBundledRoot, codexBundledRoot)
+ if err != nil {
+ return fmt.Errorf("parse config.toml marketplaces: %w", err)
+ }
+ if len(replacements) == 0 {
+ return nil
+ }
+
+ out := data
+ // Apply back-to-front so the offsets of the untouched replacements stay
+ // valid while earlier ones splice the buffer down.
+ for i := len(replacements) - 1; i >= 0; i-- {
+ r := replacements[i]
+ spliced := make([]byte, 0, len(out)-(r.end-r.start)+len(r.quoted))
+ spliced = append(spliced, out[:r.start]...)
+ spliced = append(spliced, r.quoted...)
+ spliced = append(spliced, out[r.end:]...)
+ out = spliced
+ }
+ if bytes.Equal(out, data) {
+ return nil
+ }
+ if err := os.WriteFile(configPath, out, 0o644); err != nil {
+ return fmt.Errorf("write config.toml: %w", err)
+ }
+ return nil
+}
+
+// sourceReplacement replaces the byte range [start,end) of a config (a
+// marketplace source string literal) with the quoted text of the new path.
+type sourceReplacement struct {
+ start, end int
+ quoted string
+}
+
+// locateMarketplaceSourceRewrites parses config content and returns the byte
+// ranges of every marketplace source value that must move from
+// sharedBundledRoot into codexBundledRoot. A parse failure returns an error
+// rather than a guess: the daemon must not rewrite a config it cannot read.
+func locateMarketplaceSourceRewrites(data []byte, sharedBundledRoot, codexBundledRoot string) ([]sourceReplacement, error) {
+ var parser unstable.Parser
+ parser.Reset(data)
+
+ var currentPath []string
+ var replacements []sourceReplacement
+ for parser.NextExpression() {
+ expr := parser.Expression()
+ switch expr.Kind {
+ case unstable.Table, unstable.ArrayTable:
+ currentPath = unstableKeyPath(expr)
+ case unstable.KeyValue:
+ value := expr.Child()
+ keys := unstableKeyPath(expr)
+ path := append(append([]string{}, currentPath...), keys...)
+ walkMarketplaceValues(value, path, sharedBundledRoot, codexBundledRoot, &replacements)
+ }
+ }
+ if err := parser.Error(); err != nil {
+ return nil, err
+ }
+ return replacements, nil
+}
+
+// unstableKeyPath decodes the dotted key of a Table / ArrayTable node, or the
+// key part of a KeyValue node (its children after the first), into logical
+// segments with quoting already resolved by the parser.
+func unstableKeyPath(keyOwner *unstable.Node) []string {
+ var path []string
+ for it := keyOwner.Key(); it.Next(); {
+ path = append(path, string(it.Node().Data))
+ }
+ return path
+}
+
+// walkMarketplaceValues descends a key/value's value node collecting
+// replacements for string values whose key path names a marketplace source
+// (`marketplaces.<name>.source`, including deeper sub-tables and inline or
+// dotted spellings). Arrays and inline tables are recursed into so every
+// container form of the same logical field is covered; scalar non-strings
+// cannot be a marketplace source and are skipped.
+func walkMarketplaceValues(value *unstable.Node, path []string, sharedBundledRoot, codexBundledRoot string, replacements *[]sourceReplacement) {
+ switch value.Kind {
+ case unstable.String:
+ if isMarketplaceSourcePath(path) {
+ recordMarketplaceSource(value, string(value.Data), sharedBundledRoot, codexBundledRoot, replacements)
+ }
+ case unstable.InlineTable:
+ for child := value.Child(); child.Valid(); child = child.Next() {
+ if child.Kind != unstable.KeyValue {
+ continue // comments and other meta nodes
+ }
+ childValue := child.Child()
+ childPath := append(append([]string{}, path...), unstableKeyPath(child)...)
+ walkMarketplaceValues(childValue, childPath, sharedBundledRoot, codexBundledRoot, replacements)
+ }
+ case unstable.Array:
+ for element := value.Child(); element.Valid(); element = element.Next() {
+ walkMarketplaceValues(element, path, sharedBundledRoot, codexBundledRoot, replacements)
+ }
+ }
+}
+
+// isMarketplaceSourcePath reports whether a decoded key path names the source
+// of one marketplace inside the [marketplaces] collection: exactly
+// `marketplaces.<name>.source`. That three-segment shape is the marketplace
+// definition field the CLI reads; anything deeper nested under a marketplace
+// (metadata sub-tables and the like) is unrelated content that merely shares
+// the root and must keep its own value, and a bare `marketplaces.source` is
+// not a marketplace entry at all. Both are left alone.
+func isMarketplaceSourcePath(path []string) bool {
+ return len(path) == 3 && path[0] == "marketplaces" && path[2] == "source"
+}
+
+// recordMarketplaceSource appends a replacement for one source value when it
+// resolves inside the shared bundled root. Surrounding whitespace the value
+// spelling carried (a multi-line literal's leading/trailing newlines, say) is
+// trimmed before the path checks — the CLI trims it too — and the replacement
+// is always the canonical quoted form of the relocated path.
+func recordMarketplaceSource(value *unstable.Node, src string, sharedBundledRoot, codexBundledRoot string, replacements *[]sourceReplacement) {
+ relocated, ok := repointSharedBundledSource(strings.TrimSpace(src), sharedBundledRoot, codexBundledRoot)
+ if !ok {
+ return
+ }
+ *replacements = append(*replacements, sourceReplacement{
+ start: int(value.Raw.Offset),
+ end: int(value.Raw.Offset + value.Raw.Length),
+ quoted: strconv.Quote(relocated),
+ })
+}
+
+// repointSharedBundledSource maps src into codexBundledRoot when src resolves
+// inside sharedBundledRoot, preserving the relative layout. It reports false
+// for anything else: a source that resolves outside the shared bundled root
+// (URLs, other local marketplaces, sources already inside the task home) and
+// a shared source that no longer exists.
+//
+// A source already spelled as a codexBundledRoot path decodes — through the
+// link — back into sharedBundledRoot and would map to itself; that mapping is
+// detected and reported as "nothing to change", so prepare and reuse re-runs
+// do not rewrite the config with the same bytes over and over. The comparison
+// happens on the mapped result, not the input spelling, so an unusual but
+// equivalent spelling of the task-home path still converges to the canonical
+// one exactly once.
+//
+// Both roots are resolved the way the OS opens them (util.ResolveSymlinks,
+// which on Windows follows directory junctions that filepath.EvalSymlinks
+// refuses to traverse) so a shared home reached via a link — the $CODEX_HOME
+// fallback in resolveSharedCodexHome, or a home moved across drives on
+// Windows — still matches the literal paths the copied config carries.
+func repointSharedBundledSource(src, sharedBundledRoot, codexBundledRoot string) (string, bool) {
+ if !filepath.IsAbs(src) {
+ return "", false
+ }
+ evalRoot, err := util.ResolveSymlinks(sharedBundledRoot)
+ if err != nil {
+ return "", false
+ }
+ evalSrc, err := util.ResolveSymlinks(src)
+ if err != nil {
+ return "", false
+ }
+ rel, err := filepath.Rel(evalRoot, evalSrc)
+ if err != nil || rel == ".." || filepath.IsAbs(rel) || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return "", false
+ }
+ relocated := filepath.Join(codexBundledRoot, rel)
+ if relocated == src {
+ // Already pointed at the task-home copy (idempotent re-prepare).
+ return "", false
+ }
+ return relocated, true
+}
diff --git a/server/internal/daemon/execenv/codex_bundled_marketplaces_realcli_test.go b/server/internal/daemon/execenv/codex_bundled_marketplaces_realcli_test.go
new file mode 100644
index 0000000000..3ad71da4b4
--- /dev/null
+++ b/server/internal/daemon/execenv/codex_bundled_marketplaces_realcli_test.go
@@ -0,0 +1,149 @@
+//go:build agentintegration
+
+package execenv
+
+import (
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// Regression: the marketplace-source rewrite must handle every TOML spelling
+// Codex itself accepts — trailing comments on the header and on the source
+// line, quoted keys, top-level dotted keys, inline tables, multi-line string
+// values, and nested/unrelated `source` fields that must survive untouched.
+// This
+// drives the REAL Codex CLI (executes a user-installed agent binary), so it
+// stays behind the agentintegration tag and the real-agent smoke gate:
+//
+// (cd server && MULTICA_RUN_REAL_AGENT_SMOKE=1 go test -tags=agentintegration ./internal/daemon/execenv -run TestCodexBundledMarketplaceSourceRewriteRealCLI -count=1 -v)
+//
+// The default-test assertions for the same spellings live in
+// codex_bundled_marketplaces_test.go (TestExposeSharedCodexBundledMarketplacesQASpellingVariants).
+
+func TestCodexBundledMarketplaceSourceRewriteRealCLI(t *testing.T) {
+ if os.Getenv("MULTICA_RUN_REAL_AGENT_SMOKE") != "1" {
+ t.Skip("real-agent smoke test; set MULTICA_RUN_REAL_AGENT_SMOKE=1 to run against the installed Codex CLI")
+ }
+ codex, err := exec.LookPath("codex")
+ if err != nil {
+ t.Fatal(err)
+ }
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ for _, tc := range []struct {
+ name, configFmt, preservedFmt string
+ }{
+ {"canonical", "[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = %q\n", ""},
+ {"source_comment", "[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = %q # Desktop bundle\n", ""},
+ {"header_comment", "[marketplaces.openai-bundled] # Desktop bundle\nsource_type = \"local\"\nsource = %q\n", ""},
+ {"quoted_source_key", "[marketplaces.openai-bundled]\nsource_type = \"local\"\n\"source\" = %q\n", ""},
+ {"dotted_keys", "marketplaces.openai-bundled.source_type = \"local\"\nmarketplaces.openai-bundled.source = %q\n", ""},
+ {"inline_table", "[marketplaces]\nopenai-bundled = { source_type = \"local\", source = %q }\n", ""},
+ {"multiline_literal", "[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = '''\n%s'''\n", ""},
+ {"unrelated_multiline_value", "[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = %q\n", "[mcp_servers.rewrite_probe_fixture]\ncommand = \"/usr/bin/true\"\n[mcp_servers.rewrite_probe_fixture.env]\nREWRITE_PROBE_SENTINEL = '''\nsource = %q\n'''\n"},
+ {"nested_source_preserved", "[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = %q\n", "[marketplaces.openai-bundled.metadata]\nsource = %q\n"},
+ {"external_local_marketplace", "[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = %q\n", "[marketplaces.rewrite-independent]\nsource_type = \"local\"\nsource = %q\n"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ root, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ shared := filepath.Join(root, "shared")
+ bundled := filepath.Join(shared, ".tmp", "bundled-marketplaces", "openai-bundled")
+ writeQAFile(t, filepath.Join(bundled, ".agents", "plugins", "marketplace.json"),
+ `{"name":"openai-bundled","plugins":[{"name":"browser","source":{"source":"local","path":"./plugins/browser"}}]}`)
+ writeQAFile(t, filepath.Join(bundled, "plugins", "browser", ".codex-plugin", "plugin.json"),
+ `{"name":"browser","version":"1.0.0","description":"marketplace discovery fixture"}`)
+ config := fmt.Sprintf(tc.configFmt, bundled)
+ external := filepath.Join(root, "external")
+ if tc.name == "external_local_marketplace" {
+ writeQAFile(t, filepath.Join(external, ".agents", "plugins", "marketplace.json"),
+ `{"name":"rewrite-independent","plugins":[]}`)
+ }
+
+ preserved := ""
+ if tc.preservedFmt != "" {
+ preserved = fmt.Sprintf(tc.preservedFmt, bundled)
+ if tc.name == "nested_source_preserved" {
+ metadata := filepath.Join(filepath.Dir(bundled), "artwork")
+ if err := os.MkdirAll(metadata, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ preserved = fmt.Sprintf(tc.preservedFmt, metadata)
+ }
+ if tc.name == "external_local_marketplace" {
+ preserved = fmt.Sprintf(tc.preservedFmt, external)
+ }
+ config += "\n" + preserved
+ }
+ writeQAFile(t, filepath.Join(shared, "config.toml"), config)
+ list := func(home string) (bool, string) {
+ t.Helper()
+ cmd := exec.Command(codex, "plugin", "marketplace", "list")
+ cmd.Dir = filepath.Dir(home)
+ cmd.Env = append(os.Environ(), "CODEX_HOME="+home)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("Codex CLI failed: %v\n%s", err, out)
+ }
+ return strings.Contains(string(out), "openai-bundled"), strings.ReplaceAll(strings.TrimSpace(string(out)), filepath.Dir(home), "<fixture>")
+ }
+ sharedFound, sharedOutput := list(shared)
+ if !sharedFound {
+ t.Fatalf("control failed, valid config at shared home should expose bundle: %s", sharedOutput)
+ }
+ t.Setenv("CODEX_HOME", shared)
+ task := filepath.Join(filepath.Dir(shared), "task")
+ opts := CodexHomeOptions{GOOS: "darwin", CodexVersion: "0.169.1"}
+ for attempt := 1; attempt <= 2; attempt++ {
+ if err := prepareCodexHomeWithOpts(task, opts, logger); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(task, ".tmp", "bundled-marketplaces")
+ _, linkErr := os.Readlink(link)
+ taskConfig, err := os.ReadFile(filepath.Join(task, "config.toml"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ found, output := list(task)
+ t.Logf("prepare %d: task link exists=%t, source points into task=%t, openai-bundled discovered=%t, CLI=%s",
+ attempt, linkErr == nil, strings.Contains(string(taskConfig), link), found, output)
+ if preserved != "" && !strings.Contains(string(taskConfig), preserved) {
+ marker := "[marketplaces.openai-bundled.metadata]\n"
+ _, rest, _ := strings.Cut(string(taskConfig), marker)
+ actual, _, _ := strings.Cut(rest, "\n")
+ t.Errorf("prepare %d: unrelated TOML content changed; expected %s; got %s",
+ attempt,
+ strings.ReplaceAll(strings.TrimSpace(strings.TrimPrefix(preserved, marker)), root, "<fixture>"),
+ strings.ReplaceAll(actual, root, "<fixture>"))
+ }
+ if tc.name == "external_local_marketplace" && !strings.Contains(output, "rewrite-independent") {
+ t.Errorf("independent marketplace disappeared: %s", output)
+ }
+ if !found {
+ t.Errorf("expected the task to discover the same bundled marketplace that Codex accepted in the shared home")
+ }
+ }
+ after, err := os.ReadFile(filepath.Join(shared, "config.toml"))
+ if err != nil || string(after) != config {
+ t.Fatalf("shared config changed during task preparation: %v", err)
+ }
+ })
+ }
+}
+
+func writeQAFile(t *testing.T, path string, data string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(data), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/server/internal/daemon/execenv/codex_bundled_marketplaces_test.go b/server/internal/daemon/execenv/codex_bundled_marketplaces_test.go
new file mode 100644
index 0000000000..174370a806
--- /dev/null
+++ b/server/internal/daemon/execenv/codex_bundled_marketplaces_test.go
@@ -0,0 +1,457 @@
+package execenv
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// writeSharedBundledMarketplace materializes a minimal openai-bundled
+// marketplace under sharedHome, the way ChatGPT Desktop does before a task
+// runs.
+func writeSharedBundledMarketplace(t *testing.T, sharedHome string) (bundledRoot, marketplaceDir string) {
+ t.Helper()
+ bundledRoot = filepath.Join(sharedHome, ".tmp", "bundled-marketplaces")
+ marketplaceDir = filepath.Join(bundledRoot, "openai-bundled")
+ if err := os.MkdirAll(filepath.Join(marketplaceDir, ".agents", "plugins"), 0o755); err != nil {
+ t.Fatalf("create shared marketplace dir: %v", err)
+ }
+ manifest := `{"name":"openai-bundled","plugins":[{"name":"browser","source":{"source":"local","path":"./plugins/browser"}}]}`
+ if err := os.WriteFile(filepath.Join(marketplaceDir, ".agents", "plugins", "marketplace.json"), []byte(manifest), 0o644); err != nil {
+ t.Fatalf("write shared marketplace manifest: %v", err)
+ }
+ return bundledRoot, marketplaceDir
+}
+
+// writeTaskConfigWithMarketplaces writes a copied-style config.toml whose
+// marketplaces tables mirror what ChatGPT Desktop leaves in a real shared
+// home: one bundled local source inside the shared home, one local source
+// outside it, and unrelated surrounding content that must survive untouched.
+func writeTaskConfigWithMarketplaces(t *testing.T, codexHome, sharedBundledRoot, outsideSource string) string {
+ t.Helper()
+ config := `model = "gpt-6.2-sol"
+
+[mcp_servers.node_repl]
+command = "/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node_repl"
+
+[marketplaces.openai-bundled]
+source_type = "local"
+source = "` + filepath.Join(sharedBundledRoot, "openai-bundled") + `"
+
+[marketplaces.openai-primary-runtime]
+source_type = "local"
+source = "` + outsideSource + `"
+
+[plugins."browser@openai-bundled"]
+enabled = false
+
+[plugins."codex-app-tools@openai-bundled"]
+enabled = true
+`
+ path := filepath.Join(codexHome, "config.toml")
+ if err := os.WriteFile(path, []byte(config), 0o644); err != nil {
+ t.Fatalf("write task config: %v", err)
+ }
+ return path
+}
+
+func TestExposeSharedCodexBundledMarketplacesLinksAndRepointsSource(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+ outside := filepath.Join(t.TempDir(), "codex-runtimes", "primary-runtime")
+ configPath := writeTaskConfigWithMarketplaces(t, codexHome, bundledRoot, outside)
+
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err != nil {
+ t.Fatalf("exposeSharedCodexBundledMarketplaces: %v", err)
+ }
+
+ link := filepath.Join(codexHome, ".tmp", "bundled-marketplaces")
+ fi, err := os.Lstat(link)
+ if err != nil {
+ t.Fatalf("task bundled marketplaces link: %v", err)
+ }
+ if fi.Mode()&os.ModeSymlink == 0 {
+ t.Fatalf("task bundled marketplaces is not a symlink: mode %v", fi.Mode())
+ }
+ if target, err := os.Readlink(link); err != nil || target != bundledRoot {
+ t.Fatalf("link target = %q, err %v; want %q", target, err, bundledRoot)
+ }
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ config := string(data)
+
+ wantSource := "source = " + strconv.Quote(filepath.Join(codexHome, ".tmp", "bundled-marketplaces", "openai-bundled"))
+ if !strings.Contains(config, wantSource) {
+ t.Fatalf("config does not contain repointed bundled source %s:\n%s", wantSource, config)
+ }
+ if !strings.Contains(config, "source = "+strconv.Quote(outside)) {
+ t.Fatalf("config lost the outside marketplace source:\n%s", config)
+ }
+ // Non-marketplace content must survive the patch verbatim.
+ if !strings.Contains(config, `[plugins."browser@openai-bundled"]`) {
+ t.Fatalf("config lost unrelated sections:\n%s", config)
+ }
+ // The linked marketplace must resolve to the shared manifest, so the CLI
+ // actually finds the plugins behind the repointed source.
+ if _, err := os.Stat(filepath.Join(link, "openai-bundled", ".agents", "plugins", "marketplace.json")); err != nil {
+ t.Fatalf("linked marketplace manifest not reachable: %v", err)
+ }
+}
+
+func TestExposeSharedCodexBundledMarketplacesAbsentSharedHomeIsNoop(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot := filepath.Join(sharedHome, ".tmp", "bundled-marketplaces")
+ configPath := writeTaskConfigWithMarketplaces(t, codexHome, bundledRoot, filepath.Join(t.TempDir(), "elsewhere"))
+
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err != nil {
+ t.Fatalf("exposeSharedCodexBundledMarketplaces: %v", err)
+ }
+ if _, err := os.Lstat(filepath.Join(codexHome, ".tmp")); !os.IsNotExist(err) {
+ t.Fatalf("task .tmp should not be created when the shared home has no bundled marketplaces: %v", err)
+ }
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ if !strings.Contains(string(data), "source = "+strconv.Quote(filepath.Join(bundledRoot, "openai-bundled"))) {
+ t.Fatalf("config source should stay untouched when there is nothing to expose:\n%s", data)
+ }
+}
+
+func TestExposeSharedCodexBundledMarketplacesIdempotentAndRebuildsStaleLink(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+ configPath := writeTaskConfigWithMarketplaces(t, codexHome, bundledRoot, filepath.Join(t.TempDir(), "elsewhere"))
+ wantSource := "source = " + strconv.Quote(filepath.Join(codexHome, ".tmp", "bundled-marketplaces", "openai-bundled"))
+
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err != nil {
+ t.Fatalf("first expose: %v", err)
+ }
+
+ // A stale link (wrong target) must be rebuilt, and a re-run must be a
+ // no-op on the already-correct state — prepare runs on every reuse.
+ stale := filepath.Join(codexHome, ".tmp", "bundled-marketplaces")
+ if err := os.Remove(stale); err != nil {
+ t.Fatalf("remove link for stale test: %v", err)
+ }
+ if err := os.Symlink(t.TempDir(), stale); err != nil {
+ t.Fatalf("create stale link: %v", err)
+ }
+ for i := 0; i < 2; i++ {
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err != nil {
+ t.Fatalf("expose run %d: %v", i, err)
+ }
+ if target, err := os.Readlink(stale); err != nil || target != bundledRoot {
+ t.Fatalf("run %d: link target = %q, err %v; want %q", i, target, err, bundledRoot)
+ }
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("run %d: read config: %v", i, err)
+ }
+ if !strings.Contains(string(data), wantSource) {
+ t.Fatalf("run %d: config lost repointed source:\n%s", i, data)
+ }
+ }
+ if got := strings.Count(string(mustRead(t, configPath)), wantSource); got != 1 {
+ t.Fatalf("config contains repointed source %d times, want 1", got)
+ }
+}
+
+func TestRewriteSharedBundledMarketplaceSourcesSkipsMissingAndLiteralSources(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+
+ // A source pointing at a shared bundled path that no longer exists must
+ // stay untouched (EvalSymlinks fails), and a literal-string source must
+ // still be repointed.
+ config := `[marketplaces.gone]
+source_type = "local"
+source = "` + filepath.Join(bundledRoot, "vanished") + `"
+
+[marketplaces.literal]
+source = '` + filepath.Join(bundledRoot, "openai-bundled") + `'
+`
+ configPath := filepath.Join(codexHome, "config.toml")
+ if err := os.WriteFile(configPath, []byte(config), 0o644); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ if err := rewriteSharedBundledMarketplaceSources(configPath, bundledRoot, filepath.Join(codexHome, ".tmp", "bundled-marketplaces")); err != nil {
+ t.Fatalf("rewriteSharedBundledMarketplaceSources: %v", err)
+ }
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ got := string(data)
+ if !strings.Contains(got, "source = "+strconv.Quote(filepath.Join(bundledRoot, "vanished"))) {
+ t.Fatalf("missing shared source must stay untouched:\n%s", got)
+ }
+ if !strings.Contains(got, "source = "+strconv.Quote(filepath.Join(codexHome, ".tmp", "bundled-marketplaces", "openai-bundled"))) {
+ t.Fatalf("literal-string source must be repointed:\n%s", got)
+ }
+}
+
+func mustRead(t *testing.T, path string) []byte {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ return data
+}
+
+// TestExposeSharedCodexBundledMarketplacesSpellingVariants covers the valid
+// TOML spellings a user config can legally use: trailing comments on the
+// table header and on the source line, and a quoted key. Every variant must
+// resolve the same way the CLI resolves it — full parse for discovery, line
+// splice for the rewrite — and produce a config whose source points into the
+// task home.
+func TestExposeSharedCodexBundledMarketplacesSpellingVariants(t *testing.T) {
+ for _, tc := range []struct {
+ name, header, sourceLineFormat string
+ }{
+ {"canonical", "[marketplaces.openai-bundled]", "source = %q"},
+ {"source_comment", "[marketplaces.openai-bundled]", "source = %q # Desktop bundle"},
+ {"header_comment", "[marketplaces.openai-bundled] # Desktop bundle", "source = %q"},
+ {"quoted_source_key", "[marketplaces.openai-bundled]", `"source" = %q`},
+ {"literal_string_value", "[marketplaces.openai-bundled]", "source = '%s'"},
+ {"comment_and_quoted_key", `[marketplaces.openai-bundled] # comment`, `"source" = %q # trailing`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+ sharedSource := filepath.Join(bundledRoot, "openai-bundled")
+
+ var sourceLine string
+ if strings.Contains(tc.sourceLineFormat, "%s") {
+ sourceLine = fmt.Sprintf(tc.sourceLineFormat, sharedSource)
+ } else {
+ sourceLine = fmt.Sprintf(tc.sourceLineFormat, sharedSource)
+ }
+ config := tc.header + "\nsource_type = \"local\"\n" + sourceLine + "\n"
+ configPath := filepath.Join(codexHome, "config.toml")
+ if err := os.WriteFile(configPath, []byte(config), 0o644); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err != nil {
+ t.Fatalf("exposeSharedCodexBundledMarketplaces: %v", err)
+ }
+
+ // The key spelling varies per case (bare or quoted), so assert on
+ // the repointed value itself, not on a fixed `source = ` prefix.
+ wantSource := strconv.Quote(filepath.Join(codexHome, ".tmp", "bundled-marketplaces", "openai-bundled"))
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ if !strings.Contains(string(data), wantSource) {
+ t.Fatalf("config does not contain repointed source %s:\n%s", wantSource, data)
+ }
+ if strings.Contains(string(data), strconv.Quote(sharedSource)) {
+ t.Fatalf("config still carries the shared-home source:\n%s", data)
+ }
+ // The trailing comment after the value must survive the splice.
+ if strings.Contains(sourceLine, "#") && !strings.Contains(string(data), "#") {
+ t.Fatalf("trailing comment was dropped by the rewrite:\n%s", data)
+ }
+ })
+ }
+}
+
+// A task home whose .tmp was swapped for a symlink (a reused home a previous
+// task could write) must make the expose step fail loudly instead of
+// following the interior link with MkdirAll/RemoveAll/createDirLink.
+func TestExposeSharedCodexBundledMarketplacesRefusesSymlinkedTmp(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+ configPath := writeTaskConfigWithMarketplaces(t, codexHome, bundledRoot, filepath.Join(t.TempDir(), "elsewhere"))
+
+ outside := t.TempDir()
+ outsideMarker := filepath.Join(outside, "probe")
+ if err := os.WriteFile(outsideMarker, []byte("keep"), 0o644); err != nil {
+ t.Fatalf("write probe: %v", err)
+ }
+ // Swap the .tmp component itself for a link that points outside the task
+ // home. A symlinked leaf is safe (Remove only ever unlinks it), but the
+ // interior component would make MkdirAll/RemoveAll/createDirLink operate
+ // outside the home, so the expose step must refuse it outright.
+ if err := os.Symlink(outside, filepath.Join(codexHome, ".tmp")); err != nil {
+ t.Fatalf("plant symlinked .tmp: %v", err)
+ }
+
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err == nil {
+ t.Fatalf("expected the symlinked interior component to be refused")
+ }
+ if _, err := os.Stat(outsideMarker); err != nil {
+ t.Fatalf("outside probe vanished — the interior link was followed: %v", err)
+ }
+ // The task config must be untouched by the refused attempt.
+ if data, err := os.ReadFile(configPath); err != nil || !strings.Contains(string(data), "openai-bundled") {
+ t.Fatalf("config changed by refused expose: %v %s", err, data)
+ }
+}
+
+// A codexHome that is itself a symlink must be refused, not written through.
+func TestExposeSharedCodexBundledMarketplacesRefusesSymlinkedHome(t *testing.T) {
+ sharedHome := t.TempDir()
+ writeSharedBundledMarketplace(t, sharedHome)
+ realHome := t.TempDir()
+ linkedHome := filepath.Join(t.TempDir(), "linked-home")
+ if err := os.Symlink(realHome, linkedHome); err != nil {
+ t.Fatalf("create linked home: %v", err)
+ }
+
+ if err := exposeSharedCodexBundledMarketplaces(linkedHome, sharedHome); err == nil {
+ t.Fatalf("expected a symlinked codex home to be refused")
+ }
+}
+
+// TestExposeSharedCodexBundledMarketplacesStructuralVariants covers the
+// marketplace tables spelled with top-level dotted
+// keys, inline tables, and multi-line literal values must all be repointed,
+// and a multi-line MCP env string that happens to contain `source = "..."`
+// text must survive byte-for-byte.
+func TestExposeSharedCodexBundledMarketplacesStructuralVariants(t *testing.T) {
+ for _, tc := range []struct {
+ name, configFormat string
+ }{
+ {"dotted_keys", "marketplaces.openai-bundled.source_type = \"local\"\nmarketplaces.openai-bundled.source = %q\n"},
+ {"inline_table", "[marketplaces]\nopenai-bundled = { source_type = \"local\", source = %q }\n"},
+ {"multiline_literal", "[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = '''\n%s\n'''\n"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+ sharedSource := filepath.Join(bundledRoot, "openai-bundled")
+
+ config := fmt.Sprintf(tc.configFormat, sharedSource)
+ configPath := filepath.Join(codexHome, "config.toml")
+ if err := os.WriteFile(configPath, []byte(config), 0o644); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err != nil {
+ t.Fatalf("exposeSharedCodexBundledMarketplaces: %v", err)
+ }
+
+ wantSource := strconv.Quote(filepath.Join(codexHome, ".tmp", "bundled-marketplaces", "openai-bundled"))
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ if !strings.Contains(string(data), wantSource) {
+ t.Fatalf("config does not contain repointed source %s:\n%s", wantSource, data)
+ }
+ if strings.Contains(string(data), strconv.Quote(sharedSource)) {
+ t.Fatalf("config still carries the shared-home source:\n%s", data)
+ }
+ })
+ }
+}
+
+// The rewrite must only touch marketplace source values. A multi-line MCP env
+// string whose CONTENT lines read `source = "<shared path>"` is one string
+// AST node under mcp_servers — its bytes must survive untouched even though
+// its text matches the stale source line-by-line.
+func TestRewriteSparesNonMarketplaceMultilineValues(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+ sharedSource := filepath.Join(bundledRoot, "openai-bundled")
+
+ config := `[marketplaces.openai-bundled]
+source_type = "local"
+source = "` + sharedSource + `"
+
+[mcp_servers.rewrite_probe_fixture]
+command = "/usr/bin/true"
+[mcp_servers.rewrite_probe_fixture.env]
+REWRITE_PROBE_SENTINEL = '''
+source = "` + sharedSource + `"
+'''
+`
+ configPath := filepath.Join(codexHome, "config.toml")
+ if err := os.WriteFile(configPath, []byte(config), 0o644); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ if err := rewriteSharedBundledMarketplaceSources(configPath, bundledRoot, filepath.Join(codexHome, ".tmp", "bundled-marketplaces")); err != nil {
+ t.Fatalf("rewriteSharedBundledMarketplaceSources: %v", err)
+ }
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ got := string(data)
+ if !strings.Contains(got, "source = "+strconv.Quote(filepath.Join(codexHome, ".tmp", "bundled-marketplaces", "openai-bundled"))) {
+ t.Fatalf("marketplace source was not repointed:\n%s", got)
+ }
+ if !strings.Contains(got, "source = "+strconv.Quote(sharedSource)) {
+ t.Fatalf("unrelated MCP env content was altered:\n%s", got)
+ }
+ if strings.Count(got, strconv.Quote(sharedSource)) != 1 {
+ t.Fatalf("expected exactly one untouched shared-source occurrence (the sentinel):\n%s", got)
+ }
+}
+
+// A nested sub-table under a marketplace (marketplaces.<name>.metadata.source)
+// is unrelated content that happens to share the root — only the exact
+// three-segment marketplace source field is repointed.
+func TestRewriteSparesNestedMarketplaceSubtableSource(t *testing.T) {
+ sharedHome := t.TempDir()
+ codexHome := t.TempDir()
+ bundledRoot, _ := writeSharedBundledMarketplace(t, sharedHome)
+ sharedSource := filepath.Join(bundledRoot, "openai-bundled")
+ artwork := filepath.Join(bundledRoot, "artwork")
+ if err := os.MkdirAll(artwork, 0o755); err != nil {
+ t.Fatalf("create artwork dir: %v", err)
+ }
+
+ config := `[marketplaces.openai-bundled]
+source_type = "local"
+source = "` + sharedSource + `"
+
+[marketplaces.openai-bundled.metadata]
+source = "` + artwork + `"
+`
+ configPath := filepath.Join(codexHome, "config.toml")
+ if err := os.WriteFile(configPath, []byte(config), 0o644); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ if err := rewriteSharedBundledMarketplaceSources(configPath, bundledRoot, filepath.Join(codexHome, ".tmp", "bundled-marketplaces")); err != nil {
+ t.Fatalf("rewriteSharedBundledMarketplaceSources: %v", err)
+ }
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("read config: %v", err)
+ }
+ got := string(data)
+ if !strings.Contains(got, "source = "+strconv.Quote(filepath.Join(codexHome, ".tmp", "bundled-marketplaces", "openai-bundled"))) {
+ t.Fatalf("marketplace source was not repointed:\n%s", got)
+ }
+ if !strings.Contains(got, "source = "+strconv.Quote(artwork)) {
+ t.Fatalf("nested metadata source must keep its shared path:\n%s", got)
+ }
+ if strings.Count(got, strconv.Quote(artwork)) != 1 {
+ t.Fatalf("nested source must appear exactly once, unmodified:\n%s", got)
+ }
+}
diff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.go
index 97a1a72115..30fcefdb0b 100644
--- a/server/internal/daemon/execenv/codex_home.go
+++ b/server/internal/daemon/execenv/codex_home.go
@@ -272,6 +272,16 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *s
if err := exposeSharedCodexPluginCache(codexHome, sharedHome); err != nil {
logger.Warn("execenv: codex-home plugin cache exposure failed", "error", err)
}
+ // Expose the desktop app's bundled plugin marketplaces (openai-bundled:
+ // browser, chrome, ...) inside the task home. The CLI resolves bundled
+ // marketplace sources against the ACTIVE CODEX_HOME and silently drops
+ // ones outside it, so without this the task loses the marketplace whose
+ // browser plugin owns the Stop/Interrupt hooks that tell node_repl
+ // "turn_ended" — no notification, no tab cleanup, no session release.
+ // See codex_bundled_marketplaces.go.
+ if err := exposeSharedCodexBundledMarketplaces(codexHome, sharedHome); err != nil {
+ logger.Warn("execenv: codex-home bundled marketplaces exposure failed", "error", err)
+ }
// Write a daemon-managed sandbox block into config.toml. On macOS we may
// need to fall back to danger-full-access because of openai/codex#10390,