Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
chore: fix refactor regressions (#4283)
Kyle Mendell4d6e150f240a
diff --git a/backend/internal/backup/service.go b/backend/internal/backup/service.goindex e2fcf66bc..fe8c61883 100644--- a/backend/internal/backup/service.go+++ b/backend/internal/backup/service.go@@ -4,6 +4,7 @@package backupimport (+ "bytes""cmp""context""crypto/rand"@@ -15,6 +16,7 @@ import ("fmt""io""log/slog"+ "maps""path""regexp""slices"@@ -137,6 +139,7 @@ type Engine struct {handlers map[string]func(context.Context, string, []byte, bool) errorfailures map[string]func(context.Context, string, []byte, error) errorleases map[string]*runs.Lease+ unresolved map[string]backup.DurableRunCommandexecutionReady func() boolauthorize func(context.Context, backup.DurableRunCommand) error}@@ -170,6 +173,7 @@ func NewEngine(ctx context.Context, admission *runs.Admission, imageService *imaleases: make(map[string]*runs.Lease,),+ unresolved: make(map[string]backup.DurableRunCommand),}}@@ -933,6 +937,8 @@ func (e *Engine) Register(runtime *francis.Runtime) error {}// SubmitDurableRun persists the accepted command before dispatching its work.+// A nil error means the run was accepted or its outcome is still unresolved;+// an error means the intent was confirmed absent and admission is the caller's.func (e *Engine) SubmitDurableRun(ctx context.Context, command backup.DurableRunCommand, lease *runs.Lease) error {if e == nil || e.service == nil {return errors.New("backup actor host is unavailable")@@ -949,13 +955,30 @@ func (e *Engine) SubmitDurableRun(ctx context.Context, command backup.DurableRun}e.leases[command.RunID] = leasee.mu.Unlock()- _, err := e.service.Invoke(context.WithoutCancel(ctx), backupRunTypeInternal, command.RunID, "submit", command)- if err != nil {+ ctx = context.WithoutCancel(ctx)+ _, err := e.service.Invoke(ctx, backupRunTypeInternal, command.RunID, "submit", command)+ if err == nil {+ return nil+ }+ var state backup.DurableRunState+ readErr := e.service.GetState(ctx, backupRunTypeInternal, command.RunID, &state)+ switch {+ case readErr == nil && sameDurableCommandInternal(state.Command, command):+ slog.WarnContext(ctx, "backup run accepted after submit error", "runID", command.RunID, "error", err)+ return nil+ case readErr == nil || errors.Is(readErr, actor.ErrStateNotFound):e.mu.Lock()delete(e.leases, command.RunID)e.mu.Unlock()+ return err+ default:+ // Keep admission parked until reconciliation can read the intent back.+ slog.WarnContext(ctx, "backup run outcome unresolved", "runID", command.RunID, "error", err, "readError", readErr)+ e.mu.Lock()+ e.unresolved[command.RunID] = command+ e.mu.Unlock()+ return nil}- return err}// AcquireDurableRun keeps the original admission, or reacquires it after a restart.@@ -977,19 +1000,36 @@ func (a *backupRunActorInternal) Invoke(ctx context.Context, _ string, data acto}var state backup.DurableRunStateerr := a.service.GetState(ctx, backupRunTypeInternal, a.id, &state)- if errors.Is(err, actor.ErrStateNotFound) {+ switch {+ case errors.Is(err, actor.ErrStateNotFound):state = backup.DurableRunState{Command: command, Status: scheduler.Queued}if setStateErr := a.service.SetState(ctx, backupRunTypeInternal, a.id, state, nil); setStateErr != nil {return nil, setStateErr}- } else if err != nil {+ case err != nil:return nil, err+ case !sameDurableCommandInternal(state.Command, command):+ return nil, errors.New("backup run already exists with a different command")}if state.Status == scheduler.Succeeded || state.Status == scheduler.Failed || state.Status == scheduler.NeedsAttention {return nil, nil}- _, _, err = a.service.Dispatch(ctx, backupRunTypeInternal, a.id, "execute", nil, actor.WithIdempotencyKey(a.id))- return nil, err+ // The intent is persisted, so ReconcileDispatches repairs a failed dispatch.+ if _, _, dispatchErr := a.service.Dispatch(ctx, backupRunTypeInternal, a.id, "execute", nil, actor.WithIdempotencyKey(a.id)); dispatchErr != nil {+ slog.WarnContext(ctx, "dispatch accepted backup run", "runID", a.id, "error", dispatchErr)+ }+ return nil, nil+}++func sameDurableCommandInternal(a, b backup.DurableRunCommand) bool {+ return a.UserID == b.UserID &&+ a.EnvironmentID == b.EnvironmentID &&+ a.Permission == b.Permission &&+ a.RequestedWithKey == b.RequestedWithKey &&+ a.Kind == b.Kind &&+ a.RunID == b.RunID &&+ a.ActivityID == b.ActivityID &&+ bytes.Equal(a.Payload, b.Payload)}func (a *backupRunActorInternal) Job(ctx context.Context, _ string, _ actor.Envelope) error {@@ -1151,45 +1191,83 @@ func (e *Engine) ActiveActivityIDs(ctx context.Context) ([]string, error) {return ids, nil}-// ReconcileDispatches repairs accepted commands whose dispatch was interrupted.+// ReconcileDispatches resolves unresolved submissions and repairs accepted+// commands whose dispatch was interrupted.func (e *Engine) ReconcileDispatches(ctx context.Context) error {+ failures := e.resolveUnresolvedRunsInternal(ctx)states, err := e.activeRunsInternal(ctx)if err != nil {- return err+ return errors.Join(append(failures, err)...)}for _, state := range states {if state.Status == scheduler.NeedsAttention {continue}- jobs, listJobsErr := e.service.ListJobs(ctx, backupRunTypeInternal, state.Command.RunID)- if listJobsErr != nil {- return listJobsErr+ if repairErr := e.repairDispatchInternal(ctx, state.Command.RunID); repairErr != nil {+ failures = append(failures, fmt.Errorf("repair backup run %s: %w", state.Command.RunID, repairErr))}- live := false- for _, job := range jobs {- if !job.Status.IsTerminal() {- live = true- break- }- if job.Status == actor.JobStatusDeadLettered {- if _, retryJobErr := e.service.RetryJob(ctx, job.JobID); retryJobErr != nil {- return retryJobErr- }- live = true- break- }- if deleteJobErr := e.service.DeleteJob(ctx, backupRunTypeInternal, state.Command.RunID, job.JobID); deleteJobErr != nil && !errors.Is(deleteJobErr, actor.ErrJobNotFound) {- return deleteJobErr- }+ }+ return errors.Join(failures...)+}++func (e *Engine) repairDispatchInternal(ctx context.Context, runID string) error {+ jobs, err := e.service.ListJobs(ctx, backupRunTypeInternal, runID)+ if err != nil {+ return err+ }+ for _, job := range jobs {+ if !job.Status.IsTerminal() {+ return nil+ }+ if job.Status == actor.JobStatusDeadLettered {+ _, retryJobErr := e.service.RetryJob(ctx, job.JobID)+ return retryJobErr+ }+ if deleteJobErr := e.service.DeleteJob(ctx, backupRunTypeInternal, runID, job.JobID); deleteJobErr != nil && !errors.Is(deleteJobErr, actor.ErrJobNotFound) {+ return deleteJobErr}- if live {+ }+ _, _, err = e.service.Dispatch(ctx, backupRunTypeInternal, runID, "execute", nil, actor.WithIdempotencyKey(runID))+ return err+}++// resolveUnresolvedRunsInternal reads back submissions whose outcome was+// unknown. Found intents continue as accepted; confirmed absence releases+// admission and fails the run through its kind's failure handler.+func (e *Engine) resolveUnresolvedRunsInternal(ctx context.Context) []error {+ e.mu.Lock()+ pending := maps.Clone(e.unresolved)+ e.mu.Unlock()+ var failures []error+ for runID, command := range pending {+ var state backup.DurableRunState+ readErr := e.service.GetState(ctx, backupRunTypeInternal, runID, &state)+ if readErr != nil && !errors.Is(readErr, actor.ErrStateNotFound) {+ failures = append(failures, fmt.Errorf("read back backup run %s: %w", runID, readErr))continue}- if _, _, dispatchErr := e.service.Dispatch(ctx, backupRunTypeInternal, state.Command.RunID, "execute", nil, actor.WithIdempotencyKey(state.Command.RunID)); dispatchErr != nil {- return dispatchErr+ e.mu.Lock()+ lease := e.leases[runID]+ failure := e.failures[command.Kind]+ if readErr != nil {+ delete(e.leases, runID)}+ e.mu.Unlock()+ if readErr != nil {+ lease.Release(ctx)+ // Stay unresolved until the failure is recorded, so a later tick retries it.+ if failure != nil {+ if failErr := failure(ctx, runID, command.Payload, errors.New("backup run was not accepted")); failErr != nil {+ failures = append(failures, fmt.Errorf("fail backup run %s: %w", runID, failErr))+ continue+ }+ }+ }+ e.mu.Lock()+ delete(e.unresolved, runID)+ e.mu.Unlock()}- return nil+ return failures}// ExpiredRunIDs returns the IDs of succeeded runs with snapshots that falldiff --git a/backend/internal/environment/helpers.go b/backend/internal/environment/helpers.goindex af1d28862..8b087ae95 100644--- a/backend/internal/environment/helpers.go+++ b/backend/internal/environment/helpers.go@@ -1,6 +1,7 @@package environmentimport (+ "hash/maphash""strings""sync"@@ -29,6 +30,23 @@ type remoteEnvSnapshotCacheInternal struct {revision uint64}+// environmentCacheKeyInternal scopes cached records to a cache generation so+// loads that started before a write can never be served after it.+type environmentCacheKeyInternal struct {+ gen uint64+ id string+}++// environmentCacheStripes bounds generation tracking: a write orphans only the+// cached records whose IDs hash to its stripe.+const environmentCacheStripes = 64++var environmentCacheSeed = maphash.MakeSeed()++func environmentCacheStripeInternal(id string) int {+ return int(maphash.String(environmentCacheSeed, id) % environmentCacheStripes)+}+// runtimeWatchersInternal fans a coalesced wake-up out to everyone watching for// environment liveness changes.type runtimeWatchersInternal struct {@@ -49,8 +67,8 @@ func newEdgeTokenCacheInternal() *edgeTokenCacheInternal {// newEnvironmentCacheInternal caches environment records by ID, including// misses, for hot paths that only read CRUD-managed fields.-func newEnvironmentCacheInternal() *hot.HotCache[string, Environment] {- return hot.NewHotCache[string, Environment](hot.LRU, 256).+func newEnvironmentCacheInternal() *hot.HotCache[environmentCacheKeyInternal, Environment] {+ return hot.NewHotCache[environmentCacheKeyInternal, Environment](hot.LRU, 256).WithTTL(environmentCacheTTL).WithMissingSharedCache().WithJanitor().diff --git a/backend/internal/environment/service.go b/backend/internal/environment/service.goindex 0a71cc9fb..d84870d3c 100644--- a/backend/internal/environment/service.go+++ b/backend/internal/environment/service.go@@ -10,6 +10,7 @@ import ("net/url""slices""strings"+ "sync/atomic""time""uuid"@@ -57,7 +58,8 @@ type EnvironmentService struct {settingsService *settings.SettingsServiceedgeTokens *edgeTokenCacheInternalremoteEnvs *remoteEnvSnapshotCacheInternal- environmentCache *hot.HotCache[string, Environment]+ environmentCache *hot.HotCache[environmentCacheKeyInternal, Environment]+ environmentGens [environmentCacheStripes]atomic.Uint64// jobs carries the scheduler and app lifecycle context, injected// post-construction via SetScheduler (manager-only). Each enabled environment@@ -267,6 +269,7 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrlif createLocalEnvironmentErr := s.db.WithContext(ctx).Create(localEnv).Error; createLocalEnvironmentErr != nil {return fmt.Errorf("failed to create local environment: %w", createLocalEnvironmentErr)}+ s.invalidateEnvironmentCacheInternal(LocalEnvironmentID)slog.InfoContext(ctx, "created local environment record", "id", LocalEnvironmentID)return nil@@ -731,17 +734,18 @@ func (s *EnvironmentService) ListActiveRemoteEnvironments(ctx context.Context) (// GetEnvironmentByIDCached is GetEnvironmentByID behind a short TTL cache that// also remembers unknown IDs. Status and heartbeat fields may be stale.func (s *EnvironmentService) GetEnvironmentByIDCached(ctx context.Context, id string) (*Environment, error) {- envRecord, found, err := s.environmentCache.GetWithLoaders(id, func(ids []string) (map[string]Environment, error) {- found := make(map[string]Environment, len(ids))- for _, environmentID := range ids {- loaded, loadErr := s.GetEnvironmentByID(ctx, environmentID)+ key := environmentCacheKeyInternal{gen: s.environmentGens[environmentCacheStripeInternal(id)].Load(), id: id}+ envRecord, found, err := s.environmentCache.GetWithLoaders(key, func(keys []environmentCacheKeyInternal) (map[environmentCacheKeyInternal]Environment, error) {+ found := make(map[environmentCacheKeyInternal]Environment, len(keys))+ for _, k := range keys {+ loaded, loadErr := s.GetEnvironmentByID(ctx, k.id)if errors.Is(loadErr, ErrEnvironmentNotFound) {continue}if loadErr != nil {return nil, loadErr}- found[environmentID] = *loaded+ found[k] = *loaded}return found, nil})@@ -754,12 +758,25 @@ func (s *EnvironmentService) GetEnvironmentByIDCached(ctx context.Context, id streturn &envRecord, nil}-// invalidateEnvironmentCacheInternal drops a cached record after a CRUD write.+// invalidateEnvironmentCacheInternal starts a new generation for id's stripe+// after a committed write, orphaning its cached record and in-flight loads.func (s *EnvironmentService) invalidateEnvironmentCacheInternal(id string) {- if s == nil || s.environmentCache == nil || id == "" {+ if s == nil || s.environmentCache == nil {return}- s.environmentCache.Delete(id)+ previous := s.environmentGens[environmentCacheStripeInternal(id)].Add(1) - 1+ s.environmentCache.Delete(environmentCacheKeyInternal{gen: previous, id: id})+}++// invalidateAllEnvironmentCacheInternal covers writes whose affected IDs are unknown.+func (s *EnvironmentService) invalidateAllEnvironmentCacheInternal() {+ if s == nil || s.environmentCache == nil {+ return+ }+ for i := range s.environmentGens {+ s.environmentGens[i].Add(1)+ }+ s.environmentCache.Purge()}func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams, accessibleEnvIDs []string) ([]environment.Environment, pagination.Response, error) {@@ -1682,7 +1699,12 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(}s.remoteEnvs.put(envRecord)- s.invalidateEnvironmentCacheInternal(envRecord.ID)+ // A rebind also clears the binding on other environments.+ if rebind {+ s.invalidateAllEnvironmentCacheInternal()+ } else {+ s.invalidateEnvironmentCacheInternal(envRecord.ID)+ }s.NotifyRuntimeStateChanged()return &envRecord, nil}@@ -1695,6 +1717,7 @@ func (s *EnvironmentService) DetachSwarmNodeEnvironment(ctx context.Context, parUpdates(map[string]any{"parent_environment_id": nil, "swarm_node_id": nil, "updated_at": &now}).Error; err != nil {return fmt.Errorf("failed to detach swarm node environment: %w", err)}+ s.invalidateAllEnvironmentCacheInternal()s.NotifyRuntimeStateChanged()return nil@@ -1781,6 +1804,7 @@ func (s *EnvironmentService) UpdateSwarmNodeIdentity(ctx context.Context, envID,if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {return fmt.Errorf("failed to update swarm node identity: %w", err)}+ s.invalidateEnvironmentCacheInternal(envID)s.NotifyRuntimeStateChanged()return nildiff --git a/backend/internal/updater/children/execution/service.go b/backend/internal/updater/children/execution/service.goindex 334e79308..0639f97cb 100644--- a/backend/internal/updater/children/execution/service.go+++ b/backend/internal/updater/children/execution/service.go@@ -12,6 +12,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/updater""github.com/italypaleale/francis/actor""github.com/italypaleale/francis/host/local"+ "gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -214,24 +215,30 @@ func (s *Service) dispatchSingleInternal(ctx context.Context, state updater.Singreturn err}+// repairSinglesInternal scans every persisted update, collecting per-entry+// failures so one bad entry cannot block repair of the rest.func (s *Service) repairSinglesInternal(ctx context.Context) error {+ var failures []errorfor cursor := ""; ; {page, err := s.singleUpdates.ListStates(ctx, StateType, &actor.ListStatesOpts{IncludeData: true, After: cursor, Limit: 100})if err != nil {- return err+ return errors.Join(append(failures, err)...)}for _, entry := range page.States {- var state updater.SingleUpdateState- if decodeErr := entry.Data.Decode(&state); decodeErr != nil {- return decodeErr+ if ctxErr := ctx.Err(); ctxErr != nil {+ return errors.Join(append(failures, ctxErr)...)+ }+ state, decodeErr := decodeSingleStateInternal(entry)+ if decodeErr == nil {+ decodeErr = s.repairSingleInternal(ctx, state)}- if repairSingleErr := s.repairSingleInternal(ctx, state); repairSingleErr != nil {- return repairSingleErr+ if decodeErr != nil {+ failures = append(failures, fmt.Errorf("repair container update %s: %w", entry.ActorID, decodeErr))}}cursor = page.AfterID()if cursor == "" {- return nil+ return errors.Join(failures...)}}}@@ -244,6 +251,10 @@ func (s *Service) repairSingleInternal(ctx context.Context, state updater.Singlereturn nil}detail, err := s.activity.GetActivityDetail(ctx, "0", state.Command.ActivityID, 1)+ // Pruned or deleted history needs no projection repair.+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil+ }if err != nil {return err}@@ -258,6 +269,15 @@ func (s *Service) repairSingleInternal(ctx context.Context, state updater.Singlereturn nil}+func decodeSingleStateInternal(entry actor.StateInfo) (updater.SingleUpdateState, error) {+ var state updater.SingleUpdateState+ if entry.Data == nil {+ return state, errors.New("empty update state")+ }+ err := entry.Data.Decode(&state)+ return state, err+}+func (a *singleUpdateActorInternal) Job(ctx context.Context, _ string, data actor.Envelope) error {s := a.serviceif s.coordinator != nil && !s.coordinator.Active() {@@ -451,11 +471,11 @@ func (s *Service) ActiveUpdateActivityIDs(ctx context.Context) ([]string, error)return nil, err}for _, entry := range page.States {- var state updater.SingleUpdateState- if decodeErr := entry.Data.Decode(&state); decodeErr != nil {- return nil, decodeErr+ // States are keyed by activity ID, so an undecodable entry is still protected.+ if _, decodeErr := decodeSingleStateInternal(entry); decodeErr != nil {+ s.logger().WarnContext(ctx, "decode container update state", "activityID", entry.ActorID, "error", decodeErr)}- ids = append(ids, state.Command.ActivityID)+ ids = append(ids, entry.ActorID)}cursor = page.AfterID()if cursor == "" {diff --git a/backend/pkg/libarcane/registryauth/helpers.go b/backend/pkg/libarcane/registryauth/helpers.goindex 501d6b30c..e052893b2 100644--- a/backend/pkg/libarcane/registryauth/helpers.go+++ b/backend/pkg/libarcane/registryauth/helpers.go@@ -38,8 +38,12 @@ func ExtractRegistryHost(imageRef string) string {// optional repository namespace: "https://ghcr.io/acme/" yields ("ghcr.io", "acme").func SplitRegistryURL(url string) (host, namespace string) {url = strings.TrimSpace(url)- url = strings.TrimPrefix(url, "https://")- url = strings.TrimPrefix(url, "http://")+ for _, scheme := range []string{"https://", "http://"} {+ if len(url) >= len(scheme) && strings.EqualFold(url[:len(scheme)], scheme) {+ url = url[len(scheme):]+ break+ }+ }host, namespace, _ = strings.Cut(strings.Trim(url, "/"), "/")host = strings.ToLower(host)if host == "registry-1.docker.io" || host == "index.docker.io" {diff --git a/cli/go.mod b/cli/go.modindex e9561ab54..fac04f6ca 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -15,6 +15,7 @@ require (github.com/charmbracelet/x/term v0.2.2github.com/getarcaneapp/arcane/types/v2 v2.14.0github.com/mattn/go-runewidth v0.0.30+ github.com/muesli/cancelreader v0.2.2github.com/samber/hot v0.13.1github.com/spf13/cobra v1.10.2github.com/spf13/pflag v1.0.10@@ -56,7 +57,6 @@ require (github.com/moby/docker-image-spec v1.3.1 // indirectgithub.com/moby/moby/api v1.56.1 // indirectgithub.com/moby/moby/client v0.6.1 // indirect- github.com/muesli/cancelreader v0.2.2 // indirectgithub.com/muesli/mango v0.2.0 // indirectgithub.com/muesli/mango-cobra v1.3.0 // indirectgithub.com/muesli/mango-pflag v0.2.0 // indirectdiff --git a/cli/internal/output/confirm.go b/cli/internal/output/confirm.goindex 66d897c95..3963ba980 100644--- a/cli/internal/output/confirm.go+++ b/cli/internal/output/confirm.go@@ -5,9 +5,12 @@ import ("errors""fmt""io"+ "os""strings"+ "charm.land/bubbles/v2/textinput"tea "charm.land/bubbletea/v2"+ "github.com/muesli/cancelreader")// Confirm uses a terminal selector, falling back to line input for scripts.@@ -20,30 +23,211 @@ func Confirm(ctx context.Context, input io.Reader, out io.Writer, label string)if _, err := fmt.Fprintf(out, "%s (y/N): ", strings.TrimSpace(label)); err != nil {return false, err}- var answer string- if _, err := fmt.Fscanln(input, &answer); err != nil && !errors.Is(err, io.EOF) {- return false, fmt.Errorf("failed to read confirmation input: %w", err)+ answer, err := ReadWithContext(ctx, input, func(r io.Reader) (string, error) {+ var answer string+ _, err := fmt.Fscanln(r, &answer)+ return answer, err+ })+ if ctxErr := ctx.Err(); ctxErr != nil {+ return false, ctxErr}- if err := ctx.Err(); err != nil {- return false, err+ if err != nil && !errors.Is(err, io.EOF) {+ return false, fmt.Errorf("failed to read confirmation input: %w", err)}return strings.EqualFold(answer, "y") || strings.EqualFold(answer, "yes"), nil}model, err := tea.NewProgram(confirmModel{label: label, out: out}, tea.WithContext(ctx), tea.WithInput(input), tea.WithOutput(out)).Run()+ if promptErr := programErrInternal(ctx, err, "confirmation prompt"); promptErr != nil {+ return false, promptErr+ }+ result, ok := model.(confirmModel)+ if !ok {+ return false, errors.New("confirmation returned an unexpected result")+ }+ return result.confirmed, nil+}++// Secret reads a masked value from a terminal, or one line from piped input.+// An empty value asks the caller to pass flagName instead.+func Secret(ctx context.Context, input io.Reader, out io.Writer, label, flagName string) (string, error) {+ if err := ctx.Err(); err != nil {+ return "", err+ }+ if !IsTerminal(input) {+ value, err := ReadWithContext(ctx, input, readLineInternal)+ if err != nil {+ return "", err+ }+ if value == "" {+ return "", fmt.Errorf("%s is required; pass --%s", strings.ToLower(label), flagName)+ }+ return value, nil+ }+ defer SuspendProgress()()+ field := textinput.New()+ field.Prompt = label + ": "+ field.EchoMode = textinput.EchoPassword+ field.Focus()+ model, err := tea.NewProgram(secretModel{input: field}, tea.WithContext(ctx), tea.WithInput(input), tea.WithOutput(out)).Run()+ if promptErr := programErrInternal(ctx, err, "secret prompt"); promptErr != nil {+ return "", promptErr+ }+ result, ok := model.(secretModel)+ if !ok {+ return "", errors.New("secret prompt returned an unexpected result")+ }+ if !result.submitted {+ return "", context.Canceled+ }+ return result.input.Value(), nil+}++// ReadWithContext reads input until read returns or ctx is canceled.+// Pipes, sockets and terminals are interrupted in place; regular files never+// block; other readers fall back to readAsyncInternal.+func ReadWithContext[T any](ctx context.Context, input io.Reader, read func(io.Reader) (T, error)) (T, error) {+ var value T+ var err, closeErr error+ mode, isFile := fileModeInternal(input)+ if isFile && mode.IsRegular() {+ // kqueue never reports a regular file readable at EOF, so poll nothing.+ value, err = read(input)+ } else if reader := pollableReaderInternal(input, isFile); reader != nil {+ stop := context.AfterFunc(ctx, func() { reader.Cancel() })+ value, err = read(reader)+ stop()+ if releaseErr := reader.Close(); releaseErr != nil {+ closeErr = fmt.Errorf("release input reader: %w", releaseErr)+ }+ } else {+ value, err = readAsyncInternal(ctx, input, read)+ }+ if ctxErr := ctx.Err(); ctxErr != nil {+ var zero T+ return zero, errors.Join(ctxErr, closeErr)+ }+ return value, errors.Join(err, closeErr)+}++func fileModeInternal(input io.Reader) (os.FileMode, bool) {+ file, ok := input.(interface{ Stat() (os.FileInfo, error) })+ if !ok {+ return 0, false+ }+ info, err := file.Stat()+ if err != nil {+ return 0, false+ }+ return info.Mode(), true+}++// pollableReaderInternal wraps a non-regular file in a reader whose blocked+// Read can be canceled, or returns nil when the platform cannot poll it.+func pollableReaderInternal(input io.Reader, isFile bool) cancelreader.CancelReader {+ if !isFile {+ return nil+ }+ reader, err := cancelreader.NewReader(input)+ if err != nil {+ return nil+ }+ return reader+}++// readAsyncInternal serves readers that cannot be interrupted, such as an+// embedder's io.Pipe. Cancellation stops waiting; the goroutine exits when the+// caller-owned reader returns, which closing it forces.+func readAsyncInternal[T any](ctx context.Context, input io.Reader, read func(io.Reader) (T, error)) (T, error) {+ type result struct {+ value T+ err error+ }+ done := make(chan result, 1)+ go func() {+ value, err := read(input)+ done <- result{value, err}+ }()+ select {+ case r := <-done:+ return r.value, r.err+ case <-ctx.Done():+ var zero T+ return zero, ctx.Err()+ }+}++// readLineInternal reads byte by byte so input after the newline stays+// available to the next prompt.+func readLineInternal(r io.Reader) (string, error) {+ var line []byte+ buf := make([]byte, 1)+ for {+ n, err := r.Read(buf)+ if n > 0 && buf[0] == '\n' {+ break+ }+ if n > 0 {+ line = append(line, buf[0])+ }+ if errors.Is(err, io.EOF) {+ break+ }+ if err != nil {+ return "", err+ }+ }+ return strings.TrimSuffix(string(line), "\r"), nil+}++// programErrInternal maps prompt cancellation, including Ctrl+C in raw mode,+// to a context error.+func programErrInternal(ctx context.Context, err error, name string) error {if ctx.Err() != nil {- return false, ctx.Err()+ return ctx.Err()}if errors.Is(err, tea.ErrInterrupted) {- return false, context.Canceled+ return context.Canceled}if err != nil {- return false, fmt.Errorf("confirmation prompt: %w", err)+ return fmt.Errorf("%s: %w", name, err)}- result, ok := model.(confirmModel)- if !ok {- return false, errors.New("confirmation returned an unexpected result")+ return nil+}++type secretModel struct {+ input textinput.Model+ done, submitted bool+}++func (m secretModel) Init() tea.Cmd { return nil }++func (m secretModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {+ if m.done {+ return m, nil}- return result.confirmed, nil+ if key, ok := msg.(tea.KeyPressMsg); ok {+ switch key.String() {+ case "enter":+ m.done, m.submitted = true, true+ return m, tea.Quit+ case "esc":+ m.done = true+ return m, tea.Quit+ case "ctrl+c":+ m.done = true+ return m, tea.Interrupt+ }+ }+ var cmd tea.Cmd+ m.input, cmd = m.input.Update(msg)+ return m, cmd+}++func (m secretModel) View() tea.View {+ if m.done {+ return tea.NewView("")+ }+ return tea.NewView(m.input.View() + "\n")}type confirmModel struct {diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.goindex d730c3de5..477b57af9 100644--- a/cli/pkg/admin/users/cmd.go+++ b/cli/pkg/admin/users/cmd.go@@ -2,10 +2,8 @@ package usersimport ("fmt"- "os""strings"- "github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/types/v2/user""github.com/spf13/cobra"@@ -138,16 +136,9 @@ var createCmd = &cobra.Command{}if userCreatePassword == "" {- resume := output.SuspendProgress()- defer resume()- _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Password: ")- bytePassword, readPasswordErr := term.ReadPassword(os.Stdin.Fd())- resume()- if readPasswordErr != nil {- return fmt.Errorf("failed to read password: %w", readPasswordErr)+ if userCreatePassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Password", "password"); err != nil {+ return fmt.Errorf("failed to read password: %w", err)}- userCreatePassword = string(bytePassword)- _, _ = fmt.Fprintln(output.Stdout())}req := user.CreateUser{diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.goindex c645bf489..852b30579 100644--- a/cli/pkg/auth/cmd.go+++ b/cli/pkg/auth/cmd.go@@ -6,12 +6,10 @@ import ("fmt""io""net/http"- "os""strconv""strings""time"- "github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/types/v2/auth""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/user"@@ -239,29 +237,17 @@ var passwordCmd = &cobra.Command{newPassword, _ := cmd.Flags().GetString("new")if currentPassword == "" {- resume := output.SuspendProgress()- defer resume()- _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Current password: ")- bytePassword, err := term.ReadPassword(os.Stdin.Fd())- if err != nil {+ var err error+ if currentPassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Current password", "current"); err != nil {return fmt.Errorf("failed to read current password: %w", err)}- currentPassword = string(bytePassword)- _, _ = fmt.Fprintln(cmd.ErrOrStderr())- resume()}if newPassword == "" {- resume := output.SuspendProgress()- defer resume()- _, _ = fmt.Fprint(cmd.ErrOrStderr(), "New password: ")- bytePassword, err := term.ReadPassword(os.Stdin.Fd())- if err != nil {+ var err error+ if newPassword, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "New password", "new"); err != nil {return fmt.Errorf("failed to read new password: %w", err)}- newPassword = string(bytePassword)- _, _ = fmt.Fprintln(cmd.ErrOrStderr())- resume()}c, err := cmdutil.ClientFromCommand(cmd)@@ -309,11 +295,8 @@ var refreshCmd = &cobra.Command{refreshToken = cfg.RefreshToken}if refreshToken == "" {- resume := output.SuspendProgress()- defer resume()- _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Refresh token: ")- if _, scanlnErr := fmt.Fscanln(cmd.InOrStdin(), &refreshToken); scanlnErr != nil {- return fmt.Errorf("failed to read refresh token: %w", scanlnErr)+ if refreshToken, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Refresh token", "refresh-token"); err != nil {+ return fmt.Errorf("failed to read refresh token: %w", err)}}diff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.goindex d9120c41c..8ed53cb9a 100644--- a/cli/pkg/auth/federated.go+++ b/cli/pkg/auth/federated.go@@ -158,7 +158,7 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider, audiencetokenStdin, _ := cmd.Flags().GetBool("token-stdin")if tokenStdin || stdinHasDataInternal() {- data, err := io.ReadAll(os.Stdin)+ data, err := output.ReadWithContext(cmd.Context(), cmd.InOrStdin(), io.ReadAll)if err != nil {return "", "", fmt.Errorf("failed to read token from stdin: %w", err)}diff --git a/cli/pkg/backups/cmd.go b/cli/pkg/backups/cmd.goindex 32161b177..196c36aec 100644--- a/cli/pkg/backups/cmd.go+++ b/cli/pkg/backups/cmd.go@@ -9,7 +9,6 @@ import ("os""strconv"- "github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/types/v2/backup""github.com/getarcaneapp/arcane/types/v2/base""github.com/spf13/cobra"@@ -235,19 +234,10 @@ var restoreCmd = &cobra.Command{key := restoreRecoveryKeyif key == "" {- if !prompt.IsInteractive() {- return errors.New("recovery key is required; pass --recovery-key")- }- resume := output.SuspendProgress()- defer resume()- _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Recovery key: ")- byteKey, err := term.ReadPassword(os.Stdin.Fd())- resume()- if err != nil {+ var err error+ if key, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Recovery key", "recovery-key"); err != nil {return fmt.Errorf("failed to read recovery key: %w", err)}- key = string(byteKey)- _, _ = fmt.Fprintln(output.Stdout())if key == "" {return errors.New("recovery key is required")}@@ -580,19 +570,10 @@ var recoveryKeySetCmd = &cobra.Command{RunE: func(cmd *cobra.Command, args []string) error {key := setRecoveryKeyif key == "" {- if !prompt.IsInteractive() {- return errors.New("recovery key is required; pass --recovery-key")- }- resume := output.SuspendProgress()- defer resume()- _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Recovery key: ")- byteKey, err := term.ReadPassword(os.Stdin.Fd())- resume()- if err != nil {+ var err error+ if key, err = output.Secret(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), "Recovery key", "recovery-key"); err != nil {return fmt.Errorf("failed to read recovery key: %w", err)}- key = string(byteKey)- _, _ = fmt.Fprintln(output.Stdout())}if key == "" {return errors.New("recovery key is required; use --recovery-key")diff --git a/cli/pkg/root.go b/cli/pkg/root.goindex 01635f1a3..3eab994e1 100644--- a/cli/pkg/root.go+++ b/cli/pkg/root.go@@ -169,6 +169,8 @@ var rootCmd = &cobra.Command{func Execute() {ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) //nolint:forbidigo // CLI process context.+ // Restore default handling after the first interrupt so a second one exits.+ context.AfterFunc(ctx, cancel)if err := fang.Execute(ctx,rootCmd,diff --git a/frontend/src/lib/components/dialogs/update-all-dialog.svelte b/frontend/src/lib/components/dialogs/update-all-dialog.svelteindex c45ddf939..e5ffd3ab9 100644--- a/frontend/src/lib/components/dialogs/update-all-dialog.svelte+++ b/frontend/src/lib/components/dialogs/update-all-dialog.svelte@@ -6,8 +6,9 @@import ReleaseNotes from '#lib/components/release-notes.svelte';import { Button } from '#lib/components/ui/button/index.js';import * as Dialog from '#lib/components/ui/dialog/index.js';+ import * as Popover from '#lib/components/ui/popover/index.js';import Spinner from '#lib/components/ui/spinner/spinner.svelte';- import { SuccessIcon, ClockIcon, AlertIcon, AlertTriangleIcon, ExternalLinkIcon } from '#lib/icons/index.js';+ import { SuccessIcon, ClockIcon, AlertIcon, AlertTriangleIcon, ExternalLinkIcon, InfoIcon } from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';import { APIError } from '#lib/services/api-service.js';import systemUpgradeService from '#lib/services/api/system-upgrade-service.js';@@ -481,11 +482,30 @@{/if}<Dialog.Title><span class="block min-w-0 truncate">{title}</span></Dialog.Title></div>- {#if totalCount > 0}- <span class="shrink-0 text-xs text-muted-foreground tabular-nums">- {m.environments_update_all_progress({ done: doneCount, total: totalCount })}- </span>- {/if}+ <div class="flex shrink-0 items-center gap-1 pr-6">+ {#if totalCount > 0}+ <span class="text-xs text-muted-foreground tabular-nums">+ {m.environments_update_all_progress({ done: doneCount, total: totalCount })}+ </span>+ {/if}+ {#if phase === 'running'}+ <Popover.Root>+ <Popover.Trigger>+ {#snippet child({ props })}+ <Button {...props} variant="ghost" size="icon" class="size-7" aria-label={m.info()}>+ <InfoIcon class="size-4" />+ </Button>+ {/snippet}+ </Popover.Trigger>+ <Popover.Content align="end" class="w-80">+ <div class="space-y-2 text-xs leading-relaxed text-muted-foreground">+ <p>{m.environments_update_all_manager_note()}</p>+ <p>{m.environments_update_all_reconnection_note()}</p>+ </div>+ </Popover.Content>+ </Popover.Root>+ {/if}+ </div></div></Dialog.Header>@@ -588,13 +608,6 @@<span>{job ? m.environments_update_all_in_progress() : m.environments_update_all_loading_status()}</span></div>{/if}-- {#if phase === 'running'}- <div class="border-t border-border/60 bg-muted/30 px-6 py-3">- <p class="text-xs leading-relaxed text-muted-foreground">{m.environments_update_all_manager_note()}</p>- <p class="mt-1 text-xs leading-relaxed text-muted-foreground">{m.environments_update_all_reconnection_note()}</p>- </div>- {/if}{/if}<Dialog.Footer>diff --git a/frontend/src/lib/layouts/settings-page-layout.svelte b/frontend/src/lib/layouts/settings-page-layout.svelteindex cbc897d6a..2c7050fde 100644--- a/frontend/src/lib/layouts/settings-page-layout.svelte+++ b/frontend/src/lib/layouts/settings-page-layout.svelte@@ -6,6 +6,7 @@import { ArcaneButton } from '#lib/components/arcane-button/index.js';import { UiConfigDisabledTag } from '#lib/components/badges/index.js';import StatCard from '#lib/components/stat-card.svelte';+ import { IsMobile } from '#lib/hooks/is-mobile.svelte.js';import { getSettingsFormContext, hasSettingsFormContext } from '#lib/hooks/settings-form-context.js';import { ResetIcon, type IconType } from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';@@ -41,11 +42,12 @@const formContext = hasSettingsFormContext() ? getSettingsFormContext() : undefined;const formState = $derived(formContext?.activeForm);+ const isMobile = new IsMobile();</script><div class={cn('px-2 py-4 pb-5 sm:px-6 sm:py-6 sm:pb-10 lg:px-8', className)}><div class="border-b border-border/50 pb-4 sm:pb-6">- <div class="flex items-center justify-between gap-4">+ <div class="flex flex-wrap items-center justify-between gap-4"><div class="flex flex-1 items-start gap-3 sm:gap-4">{#if Icon}<div@@ -84,8 +86,8 @@<UiConfigDisabledTag />{/if}- {#if pageType === 'form' && formState?.saveFunction && !showReadOnlyTag}- <div class="hidden items-center gap-2 md:flex">+ {#if pageType === 'form' && formState?.saveFunction && !showReadOnlyTag && !isMobile.current}+ <div class="flex flex-wrap items-center justify-end gap-2">{#if formState.hasChanges}<span class="mr-2 text-xs text-warning">{m.common_unsaved_changes()}</span>{:else}diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex 916ca232f..7e48c1a2b 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -75,8 +75,10 @@ export const queryKeys = {list: (options: SearchPaginationSortRequest) => ['container-registries', stableSerialize(options)] as const,pullUsage: () => ['container-registries', 'pull-usage'] as const,detail: (registryId: string) => ['container-registries', 'detail', registryId] as const,+ repositoriesPrefix: (registryId: string) => ['container-registries', 'repositories', registryId] as const,repositories: (registryId: string, options: SearchPaginationSortRequest) =>['container-registries', 'repositories', registryId, stableSerialize(options)] as const,+ tagsPrefix: (registryId: string, repository: string) => ['container-registries', 'tags', registryId, repository] as const,tags: (registryId: string, repository: string, options: SearchPaginationSortRequest) =>['container-registries', 'tags', registryId, repository, stableSerialize(options)] as const},diff --git a/frontend/src/routes/(app)/customize/registries/[id]/+page.svelte b/frontend/src/routes/(app)/customize/registries/[id]/+page.svelteindex d65995bb1..557dabf69 100644--- a/frontend/src/routes/(app)/customize/registries/[id]/+page.svelte+++ b/frontend/src/routes/(app)/customize/registries/[id]/+page.svelte@@ -1,5 +1,6 @@<script lang="ts">import { goto, refreshAll } from '$app/navigation';+ import { useQueryClient } from '@tanstack/svelte-query';import { toast } from 'svelte-sonner';import type { ActionButton } from '#lib/components/action-button-group/types.js';@@ -17,9 +18,11 @@import { AlertTriangleIcon, ArrowRightIcon, RegistryIcon, SearchIcon, TagIcon, TrashIcon } from '#lib/icons/index.js';import { ResourceDetailLayout } from '#lib/layouts/index.js';import { m } from '#lib/paraglide/messages.js';+ import { queryKeys } from '#lib/query/query-keys.js';import { containerRegistryService } from '#lib/services/container-registry-service.js';import type { RegistryTag } from '#lib/types/docker.js';import { cn } from '#lib/utils.js';+ import { extractApiErrorMessage } from '#lib/utils/api.js';import { hasPermission } from '#lib/utils/auth.js';import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions.js';import { bytes, formatRelativeTime } from '#lib/utils/formatting.js';@@ -28,6 +31,8 @@let { data } = $props();+ const queryClient = useQueryClient();+const registry = $derived(data.registry);const registryLabel = $derived(registry.url || 'docker.io');// Repository names already carry any namespace from the registry URL.@@ -97,10 +102,22 @@}}+ // Loader queries outlive their stale windows only until invalidated, so+ // drop every cached page and search variant before rerunning loaders.async function refresh() {refreshing = true;- await refreshAll();- refreshing = false;+ try {+ const registries = queryKeys.containerRegistries;+ await queryClient.invalidateQueries({ queryKey: registries.repositoriesPrefix(registry.id), refetchType: 'none' });+ if (repository) {+ await queryClient.invalidateQueries({ queryKey: registries.tagsPrefix(registry.id, repository), refetchType: 'none' });+ }+ await refreshAll();+ } catch (err) {+ toast.error(m.common_refresh_failed({ resource: m.common_registry() }), { description: extractApiErrorMessage(err) });+ } finally {+ refreshing = false;+ }}function handleDeleteOne(tag: string) {@@ -115,7 +132,7 @@failureMessage: m.registries_delete_tag_failed({ reference }),onSuccess: async () => {toast.success(m.registries_delete_tag_success({ reference }));- await refreshAll();+ await refresh();}});}@@ -148,7 +165,7 @@},setLoading: (loading) => (bulkDeleting = loading),onComplete: async ({ success }) => {- if (success > 0) await refreshAll();+ if (success > 0) await refresh();},clearSelection: () => {selected = [];