1// Package backend provides transport-agnostic operations for managing
2// workspaces, sessions, agents, permissions, and events. It is consumed
3// by protocol-specific layers such as HTTP (server) and ACP.
4package backend
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "log/slog"
11 "path/filepath"
12 "runtime"
13 "sync"
14 "time"
15
16 "github.com/charmbracelet/crush/internal/app"
17 "github.com/charmbracelet/crush/internal/config"
18 "github.com/charmbracelet/crush/internal/csync"
19 "github.com/charmbracelet/crush/internal/db"
20 "github.com/charmbracelet/crush/internal/proto"
21 "github.com/charmbracelet/crush/internal/skills"
22 "github.com/charmbracelet/crush/internal/ui/util"
23 "github.com/charmbracelet/crush/internal/version"
24 "github.com/google/uuid"
25)
26
27// Common errors returned by backend operations.
28var (
29 ErrWorkspaceNotFound = errors.New("workspace not found")
30 ErrLSPClientNotFound = errors.New("LSP client not found")
31 ErrAgentNotInitialized = errors.New("agent coordinator not initialized")
32 ErrPathRequired = errors.New("path is required")
33 ErrInvalidPermissionAction = errors.New("invalid permission action")
34 ErrUnknownCommand = errors.New("unknown command")
35 ErrInvalidClientID = errors.New("invalid client_id")
36 ErrClientNotAttached = errors.New("client not attached")
37)
38
39// DefaultCreateGrace is the window in which a client must open an SSE
40// stream after creating a workspace before its creation hold is
41// released. Exposed as a package variable so tests can shorten it.
42var DefaultCreateGrace = 30 * time.Second
43
44// ShutdownFunc is called when the backend needs to trigger a server
45// shutdown (e.g. when the last workspace is removed).
46type ShutdownFunc func()
47
48// Backend provides transport-agnostic business logic for the Crush
49// server. It manages workspaces and delegates to [app.App] services.
50//
51// Locking order: when both [Backend.mu] and [Workspace.clientsMu] are
52// held at once, [Backend.mu] is acquired first. Detach paths
53// ([detachStream], [releaseHoldLocked], [expireHold]) only hold
54// [Workspace.clientsMu] briefly, drop it, then call [teardown] which
55// takes [Backend.mu] (and then re-takes [Workspace.clientsMu] to
56// re-check that the workspace has not been re-claimed). This avoids
57// the AB/BA hazard with [CreateWorkspace], which holds [Backend.mu]
58// while calling [registerClient] so that a workspace cannot be torn
59// down beneath it.
60type Backend struct {
61 workspaces *csync.Map[string, *Workspace]
62 // pathIndex maps a resolved absolute workspace path to its
63 // workspace ID. Reads and writes are serialised via mu so
64 // concurrent CreateWorkspace calls at the same path deduplicate
65 // deterministically.
66 pathIndex map[string]string
67 mu sync.Mutex
68
69 cfg *config.ConfigStore
70 ctx context.Context
71 shutdownFn ShutdownFunc
72 createGrace time.Duration
73}
74
75// clientState tracks one client's claim on a workspace.
76//
77// - streams counts the number of live SSE event streams the client
78// currently has open against the workspace.
79// - holdTimer is non-nil iff the client created the workspace but has
80// not yet attached an SSE stream; it fires after createGrace and
81// releases the hold.
82// - currentSessionID records which session this client is currently
83// viewing. Empty string means the client has no session selected
84// (e.g. the landing screen). Cleared automatically when the
85// clientState entry is removed.
86//
87// streams and holdTimer are mutually exclusive in practice (the hold
88// timer is stopped the moment an SSE stream attaches), but both being
89// zero/nil means the entry has been released and should be removed.
90type clientState struct {
91 streams int
92 holdTimer *time.Timer
93 currentSessionID string
94}
95
96// Workspace represents a running [app.App] workspace with its
97// associated resources and state.
98type Workspace struct {
99 *app.App
100 ID string
101 Path string
102 Cfg *config.ConfigStore
103 Env []string
104 Skills *skills.Manager
105
106 // resolvedPath is the path used as the dedup key in
107 // Backend.pathIndex. It is filepath.EvalSymlinks(filepath.Abs(Path))
108 // with fallback to the cleaned absolute path.
109 resolvedPath string
110
111 // clientsMu guards clients. It is held only briefly (no IO).
112 clientsMu sync.Mutex
113 // clients tracks each client's claim on this workspace. Refcount
114 // is a derived value: len(clients).
115 clients map[string]*clientState
116
117 // shutdownFn is the function invoked by [Backend.teardown] to
118 // release the workspace's underlying resources. It defaults to the
119 // embedded [app.App.Shutdown]; tests may override it to avoid
120 // driving a full [app.App] through shutdown.
121 shutdownFn func()
122}
123
124// invokeShutdown calls the workspace shutdown hook if set, falling
125// back to the embedded [app.App.Shutdown] when not.
126func (w *Workspace) invokeShutdown() {
127 if w.shutdownFn != nil {
128 w.shutdownFn()
129 return
130 }
131 if w.App != nil {
132 w.Shutdown()
133 }
134}
135
136// New creates a new [Backend].
137func New(ctx context.Context, cfg *config.ConfigStore, shutdownFn ShutdownFunc) *Backend {
138 return &Backend{
139 workspaces: csync.NewMap[string, *Workspace](),
140 pathIndex: make(map[string]string),
141 cfg: cfg,
142 ctx: ctx,
143 shutdownFn: shutdownFn,
144 createGrace: DefaultCreateGrace,
145 }
146}
147
148// SetCreateGrace overrides the create-grace window. Intended for tests
149// that need short timeouts.
150func (b *Backend) SetCreateGrace(d time.Duration) {
151 b.mu.Lock()
152 defer b.mu.Unlock()
153 b.createGrace = d
154}
155
156// GetWorkspace retrieves a workspace by ID.
157func (b *Backend) GetWorkspace(id string) (*Workspace, error) {
158 ws, ok := b.workspaces.Get(id)
159 if !ok {
160 return nil, ErrWorkspaceNotFound
161 }
162 return ws, nil
163}
164
165// ListWorkspaces returns all running workspaces.
166func (b *Backend) ListWorkspaces() []proto.Workspace {
167 workspaces := []proto.Workspace{}
168 for _, ws := range b.workspaces.Seq2() {
169 workspaces = append(workspaces, workspaceToProto(ws))
170 }
171 return workspaces
172}
173
174// CreateWorkspace initializes a new workspace from the given
175// parameters, or returns an existing workspace if one already exists at
176// the same resolved path (first-wins semantics).
177//
178// args.ClientID must be a valid UUID identifying the calling client;
179// the resulting workspace registers a creation hold on behalf of that
180// client which is released either by the first SSE attach (which
181// converts it into a stream claim) or by the grace window expiring.
182func (b *Backend) CreateWorkspace(args proto.Workspace) (*Workspace, proto.Workspace, error) {
183 if args.Path == "" {
184 return nil, proto.Workspace{}, ErrPathRequired
185 }
186 clientID, err := validateClientID(args.ClientID)
187 if err != nil {
188 return nil, proto.Workspace{}, err
189 }
190
191 key, err := resolveWorkspaceKey(args.Path)
192 if err != nil {
193 return nil, proto.Workspace{}, fmt.Errorf("failed to resolve workspace path: %w", err)
194 }
195
196 b.mu.Lock()
197 if existingID, ok := b.pathIndex[key]; ok {
198 if ws, found := b.workspaces.Get(existingID); found {
199 // Hold b.mu while registering: teardown also
200 // acquires b.mu before tearing the workspace
201 // down, so this guarantees the workspace we
202 // return cannot be torn out from under us
203 // between lookup and registerClient. Lock order
204 // here is b.mu -> ws.clientsMu.
205 logFirstWinsMismatch(ws, args)
206 b.registerClient(ws, clientID)
207 b.mu.Unlock()
208 return ws, workspaceToProto(ws), nil
209 }
210 // pathIndex referenced a workspace that has since been
211 // removed; clean the stale entry and fall through.
212 delete(b.pathIndex, key)
213 }
214 b.mu.Unlock()
215
216 id := uuid.New().String()
217 cfg, err := config.Init(args.Path, args.DataDir, args.Debug)
218 if err != nil {
219 return nil, proto.Workspace{}, fmt.Errorf("failed to initialize config: %w", err)
220 }
221
222 cfg.Overrides().SkipPermissionRequests = args.YOLO
223
224 if err := createDotCrushDir(cfg.Config().Options.DataDirectory); err != nil {
225 return nil, proto.Workspace{}, fmt.Errorf("failed to create data directory: %w", err)
226 }
227
228 conn, err := db.Connect(b.ctx, cfg.Config().Options.DataDirectory, db.WithDataDirLock(true))
229 if err != nil {
230 return nil, proto.Workspace{}, fmt.Errorf("failed to connect to database: %w", err)
231 }
232
233 // Discover skills once per workspace, before app.New. The backend
234 // hosts multiple workspaces concurrently, so the manager is
235 // constructed WITHOUT WithGlobalMirror to prevent last-writer-wins
236 // cross-talk between workspaces.
237 allSkills, activeSkills, skillStates := skills.DiscoverFromConfig(skillsDiscoveryConfig(cfg))
238 skillsMgr := skills.NewManager(allSkills, activeSkills, skillStates)
239
240 appWorkspace, err := app.New(b.ctx, conn, cfg, skillsMgr)
241 if err != nil {
242 return nil, proto.Workspace{}, fmt.Errorf("failed to create app workspace: %w", err)
243 }
244
245 ws := &Workspace{
246 App: appWorkspace,
247 ID: id,
248 Path: args.Path,
249 Cfg: cfg,
250 Env: args.Env,
251 Skills: skillsMgr,
252 resolvedPath: key,
253 clients: make(map[string]*clientState),
254 }
255
256 b.mu.Lock()
257 // Re-check the index under the lock: a concurrent caller may have
258 // won the race between the initial unlock and here.
259 if existingID, ok := b.pathIndex[key]; ok {
260 if existing, found := b.workspaces.Get(existingID); found {
261 // Register under b.mu so teardown cannot run
262 // between lookup and registerClient. Lock order
263 // is b.mu -> ws.clientsMu.
264 logFirstWinsMismatch(existing, args)
265 b.registerClient(existing, clientID)
266 b.mu.Unlock()
267 ws.invokeShutdown()
268 return existing, workspaceToProto(existing), nil
269 }
270 delete(b.pathIndex, key)
271 }
272 b.workspaces.Set(id, ws)
273 b.pathIndex[key] = id
274 // Register the originating client's hold while still holding
275 // b.mu so the workspace is observable with its claim from the
276 // moment it appears in the index.
277 b.registerClient(ws, clientID)
278 b.mu.Unlock()
279
280 if args.Version != "" && args.Version != version.Version {
281 slog.Warn(
282 "Client/server version mismatch",
283 "client", args.Version,
284 "server", version.Version,
285 )
286 appWorkspace.SendEvent(util.NewWarnMsg(fmt.Sprintf(
287 "Server version %q differs from client version %q. Consider restarting the server.",
288 version.Version, args.Version,
289 )))
290 }
291
292 return ws, workspaceToProto(ws), nil
293}
294
295// skillsDiscoveryConfig adapts a *config.ConfigStore to the
296// skills.DiscoveryConfig that DiscoverFromConfig consumes.
297func skillsDiscoveryConfig(cfg *config.ConfigStore) skills.DiscoveryConfig {
298 opts := cfg.Config().Options
299 var paths, disabled []string
300 if opts != nil {
301 paths = opts.SkillsPaths
302 disabled = opts.DisabledSkills
303 }
304 var resolver func(string) (string, error)
305 if r := cfg.Resolver(); r != nil {
306 resolver = r.ResolveValue
307 }
308 return skills.DiscoveryConfig{
309 SkillsPaths: paths,
310 DisabledSkills: disabled,
311 Resolver: resolver,
312 }
313}
314
315// skillStatesToProto converts internal skill discovery states into the
316// wire format.
317func skillStatesToProto(states []*skills.SkillState) []proto.SkillState {
318 if len(states) == 0 {
319 return nil
320 }
321 out := make([]proto.SkillState, len(states))
322 for i, s := range states {
323 entry := proto.SkillState{
324 Name: s.Name,
325 Path: s.Path,
326 State: proto.SkillDiscoveryState(s.State),
327 }
328 if s.Err != nil {
329 entry.Error = s.Err.Error()
330 }
331 out[i] = entry
332 }
333 return out
334}
335
336// AttachClient registers a new SSE stream for the given client on the
337// workspace. The stream's deferred cleanup must call DetachClient with
338// the same arguments to release the claim.
339//
340// The lookup and the clients-map mutation are performed under
341// [Backend.mu] so that AttachClient cannot race with [Backend.teardown]:
342// teardown also holds [Backend.mu] while removing the workspace from
343// b.workspaces, so once AttachClient observes the workspace and takes
344// ws.clientsMu (under b.mu), no concurrent teardown can succeed without
345// re-checking the (now non-empty) clients map. Lock order is the
346// canonical b.mu -> ws.clientsMu.
347func (b *Backend) AttachClient(workspaceID, clientID string) error {
348 if _, err := validateClientID(clientID); err != nil {
349 return err
350 }
351
352 b.mu.Lock()
353 defer b.mu.Unlock()
354 ws, ok := b.workspaces.Get(workspaceID)
355 if !ok {
356 return ErrWorkspaceNotFound
357 }
358
359 ws.clientsMu.Lock()
360 defer ws.clientsMu.Unlock()
361 cs, ok := ws.clients[clientID]
362 if !ok {
363 // Defensive: SSE attach without a prior CreateWorkspace by
364 // this client still installs a stream claim so the stream
365 // stays alive for its duration.
366 ws.clients[clientID] = &clientState{streams: 1}
367 return nil
368 }
369 if cs.holdTimer != nil {
370 cs.holdTimer.Stop()
371 cs.holdTimer = nil
372 }
373 cs.streams++
374 return nil
375}
376
377// DetachClient releases one SSE stream's hold on the workspace. If the
378// client has no other streams and no pending creation hold, its claim
379// is removed and the workspace is torn down once refcount hits zero.
380func (b *Backend) DetachClient(workspaceID, clientID string) {
381 ws, ok := b.workspaces.Get(workspaceID)
382 if !ok {
383 return
384 }
385 b.detachStream(ws, clientID)
386}
387
388// releaseHold releases the creation hold for a client, if any. Active
389// stream claims are unaffected. Idempotent: returns nil if the
390// workspace or the client's hold no longer exist.
391func (b *Backend) releaseHold(workspaceID, clientID string) error {
392 if _, err := validateClientID(clientID); err != nil {
393 return err
394 }
395 ws, ok := b.workspaces.Get(workspaceID)
396 if !ok {
397 return nil
398 }
399 b.releaseHoldLocked(ws, clientID)
400 return nil
401}
402
403// registerClient installs (idempotently) the given client's claim on
404// the workspace and starts a grace timer if the entry is fresh.
405func (b *Backend) registerClient(ws *Workspace, clientID string) {
406 ws.clientsMu.Lock()
407 defer ws.clientsMu.Unlock()
408 if _, ok := ws.clients[clientID]; ok {
409 // Idempotent: a duplicate CreateWorkspace from the same
410 // client does not add a second claim.
411 return
412 }
413 cs := &clientState{}
414 cs.holdTimer = time.AfterFunc(b.createGrace, func() {
415 b.expireHold(ws, clientID, cs)
416 })
417 ws.clients[clientID] = cs
418}
419
420// expireHold is the body of the grace timer. It runs in its own
421// goroutine and races against AttachClient/releaseHold; the timer
422// stays valid only while the entry's holdTimer still points at it.
423func (b *Backend) expireHold(ws *Workspace, clientID string, timer *clientState) {
424 ws.clientsMu.Lock()
425 cs, ok := ws.clients[clientID]
426 if !ok || cs != timer || cs.holdTimer == nil || cs.streams > 0 {
427 ws.clientsMu.Unlock()
428 return
429 }
430 cs.holdTimer = nil
431 delete(ws.clients, clientID)
432 teardown := len(ws.clients) == 0
433 ws.clientsMu.Unlock()
434 if teardown {
435 b.teardown(ws)
436 }
437}
438
439func (b *Backend) releaseHoldLocked(ws *Workspace, clientID string) {
440 ws.clientsMu.Lock()
441 cs, ok := ws.clients[clientID]
442 if !ok {
443 ws.clientsMu.Unlock()
444 return
445 }
446 if cs.holdTimer != nil {
447 cs.holdTimer.Stop()
448 cs.holdTimer = nil
449 }
450 teardown := false
451 if cs.streams == 0 {
452 delete(ws.clients, clientID)
453 teardown = len(ws.clients) == 0
454 }
455 ws.clientsMu.Unlock()
456 if teardown {
457 b.teardown(ws)
458 }
459}
460
461func (b *Backend) detachStream(ws *Workspace, clientID string) {
462 ws.clientsMu.Lock()
463 cs, ok := ws.clients[clientID]
464 if !ok {
465 ws.clientsMu.Unlock()
466 return
467 }
468 if cs.streams > 0 {
469 cs.streams--
470 }
471 teardown := false
472 if cs.streams == 0 && cs.holdTimer == nil {
473 delete(ws.clients, clientID)
474 teardown = len(ws.clients) == 0
475 }
476 ws.clientsMu.Unlock()
477 if teardown {
478 b.teardown(ws)
479 }
480}
481
482// teardown removes the workspace from the index, shuts down its
483// underlying [app.App], and triggers a server shutdown if it was the
484// last workspace alive.
485//
486// Callers reach teardown after observing len(ws.clients) == 0 while
487// holding ws.clientsMu and then releasing it. Between that release
488// and the b.mu.Lock below, a concurrent CreateWorkspace may have
489// re-registered a client (CreateWorkspace holds b.mu while doing so,
490// so it is mutually exclusive with this critical section). teardown
491// re-checks under both locks (in the canonical b.mu -> ws.clientsMu
492// order) and aborts if the workspace has been re-claimed.
493func (b *Backend) teardown(ws *Workspace) {
494 b.mu.Lock()
495 ws.clientsMu.Lock()
496 if len(ws.clients) > 0 {
497 // Race: a CreateWorkspace re-registered a client
498 // between the detach path dropping ws.clientsMu and us
499 // taking b.mu. Abort: the workspace is still alive.
500 ws.clientsMu.Unlock()
501 b.mu.Unlock()
502 return
503 }
504 ws.clientsMu.Unlock()
505 if existing, ok := b.pathIndex[ws.resolvedPath]; ok && existing == ws.ID {
506 delete(b.pathIndex, ws.resolvedPath)
507 }
508 b.workspaces.Del(ws.ID)
509 remaining := b.workspaces.Len()
510 b.mu.Unlock()
511
512 ws.invokeShutdown()
513
514 if remaining == 0 && b.shutdownFn != nil {
515 slog.Info("Last workspace removed, shutting down server...")
516 b.shutdownFn()
517 }
518}
519
520// DeleteWorkspace is the public entry point used by the HTTP DELETE
521// handler. It releases the named client's creation hold; live streams
522// from the same client remain attached and continue holding the
523// workspace open until their own deferred DetachClient runs.
524func (b *Backend) DeleteWorkspace(id, clientID string) error {
525 return b.releaseHold(id, clientID)
526}
527
528// SetCurrentSession records which session the given client is
529// currently viewing within the workspace. Passing an empty sessionID
530// clears the client's current-session entry (e.g. the client has
531// returned to the landing screen).
532//
533// The client must be actually attached — i.e. its [clientState] entry
534// must exist and have at least one live stream. A bare creation hold
535// (streams == 0) is rejected with [ErrClientNotAttached]. This
536// guards against zombie writes from a client that has detached and
537// against ghost presence from a hold-only client that never opened an
538// SSE stream.
539func (b *Backend) SetCurrentSession(workspaceID, clientID, sessionID string) error {
540 if _, err := validateClientID(clientID); err != nil {
541 return err
542 }
543 ws, ok := b.workspaces.Get(workspaceID)
544 if !ok {
545 return ErrWorkspaceNotFound
546 }
547 ws.clientsMu.Lock()
548 defer ws.clientsMu.Unlock()
549 cs, ok := ws.clients[clientID]
550 if !ok || cs.streams == 0 {
551 // No entry, or hold-only (no live stream): refuse the
552 // write. The presence record this is meant to feed
553 // should only reflect clients that can actually observe
554 // session events.
555 return ErrClientNotAttached
556 }
557 cs.currentSessionID = sessionID
558 return nil
559}
560
561// AttachedClients returns the number of clients currently viewing
562// sessionID in the given workspace. Only clients with at least one live
563// SSE stream (streams > 0) AND a matching currentSessionID are counted;
564// pure creation holds do not contribute. Returns [ErrWorkspaceNotFound]
565// if the workspace is unknown.
566func (b *Backend) AttachedClients(workspaceID, sessionID string) (int, error) {
567 ws, ok := b.workspaces.Get(workspaceID)
568 if !ok {
569 return 0, ErrWorkspaceNotFound
570 }
571 return ws.AttachedClientsForSession(sessionID), nil
572}
573
574// AttachedClientsForSession returns the number of clients in this
575// workspace whose currentSessionID equals sessionID and which have at
576// least one live SSE stream. Hold-only clients (streams == 0) do not
577// contribute. Acquires the workspace's [clientsMu] briefly; the
578// returned count is a point-in-time snapshot.
579func (w *Workspace) AttachedClientsForSession(sessionID string) int {
580 w.clientsMu.Lock()
581 defer w.clientsMu.Unlock()
582 n := 0
583 for _, cs := range w.clients {
584 if cs.streams > 0 && cs.currentSessionID == sessionID {
585 n++
586 }
587 }
588 return n
589}
590
591// GetWorkspaceProto returns the proto representation of a workspace.
592func (b *Backend) GetWorkspaceProto(id string) (proto.Workspace, error) {
593 ws, err := b.GetWorkspace(id)
594 if err != nil {
595 return proto.Workspace{}, err
596 }
597 return workspaceToProto(ws), nil
598}
599
600// VersionInfo returns server version information.
601func (b *Backend) VersionInfo() proto.VersionInfo {
602 return proto.VersionInfo{
603 Version: version.Version,
604 Commit: version.Commit,
605 BuildID: version.BuildID,
606 GoVersion: runtime.Version(),
607 Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
608 }
609}
610
611// Config returns the server-level configuration.
612func (b *Backend) Config() *config.ConfigStore {
613 return b.cfg
614}
615
616// Shutdown initiates a graceful server shutdown.
617func (b *Backend) Shutdown() {
618 if b.shutdownFn != nil {
619 b.shutdownFn()
620 }
621}
622
623// resolveWorkspaceKey returns a stable canonical form of path suitable
624// for use as a dedup key. It applies filepath.Abs, then attempts
625// filepath.EvalSymlinks; because EvalSymlinks errors on non-existent
626// paths, it falls back to the cleaned absolute path in that case.
627func resolveWorkspaceKey(path string) (string, error) {
628 abs, err := filepath.Abs(path)
629 if err != nil {
630 return "", err
631 }
632 if resolved, err := filepath.EvalSymlinks(abs); err == nil {
633 return resolved, nil
634 }
635 return abs, nil
636}
637
638// validateClientID returns the trimmed UUID string or an error if the
639// input is empty or not a valid UUID.
640func validateClientID(id string) (string, error) {
641 if id == "" {
642 return "", ErrInvalidClientID
643 }
644 if _, err := uuid.Parse(id); err != nil {
645 return "", fmt.Errorf("%w: %v", ErrInvalidClientID, err)
646 }
647 return id, nil
648}
649
650func workspaceToProto(ws *Workspace) proto.Workspace {
651 cfg := ws.Cfg.Config()
652 out := proto.Workspace{
653 ID: ws.ID,
654 Path: ws.Path,
655 YOLO: ws.Cfg.Overrides().SkipPermissionRequests,
656 DataDir: cfg.Options.DataDirectory,
657 Debug: cfg.Options.Debug,
658 Config: cfg,
659 Env: ws.Env,
660 Version: version.Version,
661 }
662 if ws.Skills != nil {
663 out.Skills = skillStatesToProto(ws.Skills.States())
664 }
665 return out
666}
667
668// logFirstWinsMismatch emits a debug line whenever a second
669// CreateWorkspace at the same resolved path arrives with flags that
670// differ from the originating workspace. The existing workspace wins;
671// the incoming flags are silently ignored.
672//
673// The comparison is done against the incoming args as the caller sent
674// them — including empty/zero values — rather than after defaulting.
675// This means that, for example, a second caller who omits DataDir
676// while the first set one will still log the mismatch.
677func logFirstWinsMismatch(existing *Workspace, args proto.Workspace) {
678 existingCfg := existing.Cfg.Config()
679 existingYOLO := existing.Cfg.Overrides().SkipPermissionRequests
680 if existingYOLO == args.YOLO &&
681 existingCfg.Options.Debug == args.Debug &&
682 existingCfg.Options.DataDirectory == args.DataDir &&
683 stringSlicesEqual(existing.Env, args.Env) {
684 return
685 }
686 slog.Debug(
687 "Workspace flag mismatch on duplicate create; first wins",
688 "workspace_id", existing.ID,
689 "path", existing.Path,
690 "existing_yolo", existingYOLO,
691 "requested_yolo", args.YOLO,
692 "existing_debug", existingCfg.Options.Debug,
693 "requested_debug", args.Debug,
694 "existing_data_dir", existingCfg.Options.DataDirectory,
695 "requested_data_dir", args.DataDir,
696 "existing_env", existing.Env,
697 "requested_env", args.Env,
698 )
699}
700
701// stringSlicesEqual reports whether a and b contain the same strings
702// in the same order. nil and empty are treated as equal.
703func stringSlicesEqual(a, b []string) bool {
704 if len(a) != len(b) {
705 return false
706 }
707 for i := range a {
708 if a[i] != b[i] {
709 return false
710 }
711 }
712 return true
713}