From ac45a4fbd8afa592d14c791604b1192e1961e084 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:00:20 -0800 Subject: [PATCH 1/3] fix: harden stores, quota history and shutdown paths - Auth stores reject delete paths outside the managed auth directory (file, git, object and Postgres stores) and write auth files atomically. - bbolt KV store refuses reads and writes after Close instead of racing it; plain sets skip the existence check NX/XX need. - Quota history: History holds the store open while it reads, plan caches reset when recording stops or moves, a future last-sample time no longer delays the first poll, day durations reject NaN/Inf/overflow, and the scan bound cannot overflow. - Session-affinity snapshots are deleted once expired; a failed local KV store disables affinity persistence instead of leaving it half on. - Postgres store: pooled connections are bounded and closed on exit; the refresh journal ensures its schema before reads and completions. - Object refresh journal always removes its capability probe; cooldown and Meta token temp files are 0600 and fsynced before rename. - Codex websocket SOCKS dials honour the request context; Codex/OpenAI thinking appliers mutate an ojson.Doc as the conventions require. - Server exit tests run the child without a controlling TTY. Co-Authored-By: Claude Opus 5.5 --- cmd/server/main.go | 5 + cmd/server/main_exit_other_test.go | 7 ++ cmd/server/main_exit_test.go | 1 + cmd/server/main_exit_unix_test.go | 20 ++++ internal/auth/meta/meta.go | 19 +++- internal/kvstore/bolt_store.go | 53 ++++++---- internal/quotahistory/recorder.go | 20 +++- internal/quotahistory/settings.go | 13 ++- internal/quotahistory/store.go | 4 +- .../executor/codex_websockets_connection.go | 13 ++- internal/store/gitstore.go | 18 +++- internal/store/object_refresh_journal.go | 14 ++- internal/store/objectstore.go | 98 ++++++++++++------- internal/store/postgres_refresh_journal.go | 12 +++ internal/store/postgresstore.go | 44 +++++---- internal/thinking/provider/codex/apply.go | 7 +- internal/thinking/provider/openai/apply.go | 7 +- sdk/auth/filestore.go | 19 +++- .../auth/conductor_refresh_disabled_test.go | 2 +- sdk/cliproxy/auth/cooldown_state.go | 10 ++ sdk/cliproxy/auth/session_persistence.go | 2 + sdk/cliproxy/kv_store.go | 8 +- 22 files changed, 294 insertions(+), 102 deletions(-) create mode 100644 cmd/server/main_exit_other_test.go create mode 100644 cmd/server/main_exit_unix_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index fdfb6b983ce..b9585d19f56 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -488,6 +488,11 @@ func run() (exitStatus int) { log.Errorf("failed to initialize postgres token store: %v", err) return 1 } + defer func() { + if errClose := pgStoreInst.Close(); errClose != nil { + log.Warnf("failed to close postgres token store: %v", errClose) + } + }() examplePath := filepath.Join(wd, "config.example.yaml") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { diff --git a/cmd/server/main_exit_other_test.go b/cmd/server/main_exit_other_test.go new file mode 100644 index 00000000000..e5fe308a5a0 --- /dev/null +++ b/cmd/server/main_exit_other_test.go @@ -0,0 +1,7 @@ +//go:build !unix + +package main + +import "os/exec" + +func detachControllingTTY(_ *exec.Cmd) {} diff --git a/cmd/server/main_exit_test.go b/cmd/server/main_exit_test.go index f82cb4f46b4..84c3886da77 100644 --- a/cmd/server/main_exit_test.go +++ b/cmd/server/main_exit_test.go @@ -39,6 +39,7 @@ func newServerExitCommand(t *testing.T, dir string, args ...string) (*exec.Cmd, t.Cleanup(cancel) cmdArgs := append([]string{"-test.run=^TestServerExitHelper$", "--"}, args...) command := exec.CommandContext(ctx, os.Args[0], cmdArgs...) + detachControllingTTY(command) command.Dir = dir // Isolate from host store environment variables and prevent external network calls. command.Env = append(os.Environ(), diff --git a/cmd/server/main_exit_unix_test.go b/cmd/server/main_exit_unix_test.go new file mode 100644 index 00000000000..8df52fb2d0d --- /dev/null +++ b/cmd/server/main_exit_unix_test.go @@ -0,0 +1,20 @@ +//go:build unix + +package main + +import ( + "os/exec" + "syscall" +) + +// detachControllingTTY puts the child in a new session so Bubbletea cannot open +// the parent terminal's /dev/tty when tests expect a non-interactive failure. +func detachControllingTTY(cmd *exec.Cmd) { + if cmd == nil { + return + } + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = &syscall.SysProcAttr{} + } + cmd.SysProcAttr.Setsid = true +} diff --git a/internal/auth/meta/meta.go b/internal/auth/meta/meta.go index 29b19bb25cb..d572203bf2c 100644 --- a/internal/auth/meta/meta.go +++ b/internal/auth/meta/meta.go @@ -199,17 +199,32 @@ func (ts *MetaTokenStorage) SaveTokenToFile(authFilePath string) error { if err != nil { return fmt.Errorf("meta token storage: create token file: %w", err) } - defer func() { _ = os.Remove(file.Name()) }() + tmpPath := file.Name() + cleanupTmp := true + defer func() { + if cleanupTmp { + _ = os.Remove(tmpPath) + } + }() + if errChmod := file.Chmod(0o600); errChmod != nil { + _ = file.Close() + return fmt.Errorf("meta token storage: chmod token file: %w", errChmod) + } if _, errWrite := file.Write(append(raw, '\n')); errWrite != nil { _ = file.Close() return fmt.Errorf("meta token storage: write token file: %w", errWrite) } + if errSync := file.Sync(); errSync != nil { + _ = file.Close() + return fmt.Errorf("meta token storage: sync token file: %w", errSync) + } if errClose := file.Close(); errClose != nil { return fmt.Errorf("meta token storage: close token file: %w", errClose) } - if errRename := os.Rename(file.Name(), authFilePath); errRename != nil { + if errRename := os.Rename(tmpPath, authFilePath); errRename != nil { return fmt.Errorf("meta token storage: replace token file: %w", errRename) } + cleanupTmp = false return nil } diff --git a/internal/kvstore/bolt_store.go b/internal/kvstore/bolt_store.go index 4ea8211a8bb..9df721702e6 100644 --- a/internal/kvstore/bolt_store.go +++ b/internal/kvstore/bolt_store.go @@ -87,6 +87,8 @@ func WithSweepBatchSize(batchSize int) BoltStoreOption { // BoltStore implements KVClient backed by a local bbolt database file. type BoltStore struct { + dbMu sync.RWMutex + closed bool db *bbolt.DB path string nowFunc func() time.Time @@ -171,6 +173,9 @@ func (s *BoltStore) Close() error { s.closeOnce.Do(func() { close(s.stopCh) <-s.doneCh + s.dbMu.Lock() + defer s.dbMu.Unlock() + s.closed = true if s.db != nil { s.closeErr = s.db.Close() } @@ -186,12 +191,22 @@ func (s *BoltStore) now() time.Time { } func (s *BoltStore) view(fn func(tx *bbolt.Tx, now time.Time) error) error { + s.dbMu.RLock() + defer s.dbMu.RUnlock() + if s.closed || s.db == nil { + return errStoreClosed + } return s.db.View(func(tx *bbolt.Tx) error { return fn(tx, s.now()) }) } func (s *BoltStore) update(fn func(tx *bbolt.Tx, now time.Time) error) error { + s.dbMu.RLock() + defer s.dbMu.RUnlock() + if s.closed || s.db == nil { + return errStoreClosed + } runner := s.db.Update if s.runUpdate != nil { runner = s.runUpdate @@ -332,26 +347,28 @@ func (s *BoltStore) KVSet(ctx context.Context, key string, value []byte, opts KV if b == nil { return fmt.Errorf("kvstore: bucket not found") } - var exists bool - if raw := b.Get(keyBytes); raw != nil { - _, _, expired, errDecode := decodeEnvelope(raw, nowNano) - if errDecode != nil { - return errDecode - } - if expired { - if errDel := b.Delete(keyBytes); errDel != nil { - return errDel + if opts.NX || opts.XX { + var exists bool + if raw := b.Get(keyBytes); raw != nil { + _, _, expired, errDecode := decodeEnvelope(raw, nowNano) + if errDecode != nil { + return errDecode + } + if expired { + if errDel := b.Delete(keyBytes); errDel != nil { + return errDel + } + exists = false + } else { + exists = true } - exists = false - } else { - exists = true } - } - if opts.NX && exists { - return nil - } - if opts.XX && !exists { - return nil + if opts.NX && exists { + return nil + } + if opts.XX && !exists { + return nil + } } if errPut := b.Put(keyBytes, encodeEnvelope(value, expiresAt)); errPut != nil { return errPut diff --git a/internal/quotahistory/recorder.go b/internal/quotahistory/recorder.go index 30b92a4ebcf..8990efb2e15 100644 --- a/internal/quotahistory/recorder.go +++ b/internal/quotahistory/recorder.go @@ -175,11 +175,20 @@ func (r *Recorder) Apply(s Settings) error { if s == r.settings && running == s.Enabled { return nil } + prevPath := r.settings.Path r.stopLocked() r.settings = s r.providers.Store(s.Providers) r.forgetUntracked(s.Enabled) r.pluginIDs.Store(nil) + if !s.Enabled || s.Path != prevPath { + r.plansMu.Lock() + clear(r.plans) + clear(r.profileAttempts) + clear(r.customers) + clear(r.customerAttempts) + r.plansMu.Unlock() + } if !s.Enabled { return nil } @@ -265,8 +274,11 @@ func (r *Recorder) run(ctx context.Context, store *Store, s Settings) { delay := r.startupDelay if last := store.lastTime(); last > 0 { - if remaining := s.Interval - r.now().Sub(time.UnixMilli(last)); remaining > delay { - delay = remaining + elapsed := r.now().Sub(time.UnixMilli(last)) + if elapsed >= 0 { + if remaining := s.Interval - elapsed; remaining > delay { + delay = remaining + } } } timer := time.NewTimer(delay) @@ -644,11 +656,15 @@ func (r *Recorder) History(since, until int64) (History, error) { } r.mu.Lock() store, s := r.store, r.settings + if store != nil { + r.wg.Add(1) + } r.mu.Unlock() out.IntervalSeconds = int64(s.Interval / time.Second) if store == nil { return out, nil } + defer r.wg.Done() out.Enabled = true if until <= 0 { until = out.Now diff --git a/internal/quotahistory/settings.go b/internal/quotahistory/settings.go index d1a4194f294..e679243f594 100644 --- a/internal/quotahistory/settings.go +++ b/internal/quotahistory/settings.go @@ -6,6 +6,7 @@ package quotahistory import ( "fmt" + "math" "path/filepath" "sort" "strconv" @@ -116,10 +117,18 @@ func parseDuration(raw string) (time.Duration, bool) { } if days, found := strings.CutSuffix(raw, "d"); found { n, errParse := strconv.ParseFloat(days, 64) - if errParse != nil || n <= 0 { + if errParse != nil || math.IsNaN(n) || math.IsInf(n, 0) || n <= 0 { return 0, false } - return time.Duration(n * float64(24*time.Hour)), true + const maxDays = float64(math.MaxInt64) / float64(24*time.Hour) + if n >= maxDays { + return 0, false + } + d := time.Duration(n * float64(24*time.Hour)) + if d <= 0 { + return 0, false + } + return d, true } d, errParse := time.ParseDuration(raw) if errParse != nil || d <= 0 { diff --git a/internal/quotahistory/store.go b/internal/quotahistory/store.go index 567b0fff619..e8f1293e8bf 100644 --- a/internal/quotahistory/store.go +++ b/internal/quotahistory/store.go @@ -107,8 +107,8 @@ func (s *Store) put(rec record) error { func (s *Store) scan(since, until int64, fn func(record)) error { return s.db.View(func(tx *bbolt.Tx) error { c := tx.Bucket(samplesBucket).Cursor() - limit := timeKey(until + 1) - for k, v := c.Seek(timeKey(since)); k != nil && bytes.Compare(k[:min(8, len(k))], limit) < 0; k, v = c.Next() { + untilKey := timeKey(until) + for k, v := c.Seek(timeKey(since)); k != nil && bytes.Compare(k[:min(8, len(k))], untilKey) <= 0; k, v = c.Next() { var rec record if errUnmarshal := json.Unmarshal(v, &rec); errUnmarshal != nil { continue diff --git a/internal/runtime/executor/codex_websockets_connection.go b/internal/runtime/executor/codex_websockets_connection.go index 65361da6fde..a9827be0816 100644 --- a/internal/runtime/executor/codex_websockets_connection.go +++ b/internal/runtime/executor/codex_websockets_connection.go @@ -191,9 +191,11 @@ func frameCodexWebsocketRequestBody(body []byte) []byte { if len(body) == 0 { return nil } - wsReqBody, errSet := ojson.SetBytes(body, "type", "response.create") - if errSet == nil && len(wsReqBody) > 0 { - return wsReqBody + doc := ojson.NewDoc(body) + if errSet := doc.Set("type", "response.create"); errSet == nil { + if wsReqBody := doc.Bytes(); len(wsReqBody) > 0 { + return wsReqBody + } } return body } @@ -302,7 +304,10 @@ func newProxyAwareWebsocketDialer(ctx context.Context, cfg *config.Config, auth return dialer } dialer.Proxy = nil - dialer.NetDialContext = func(_ context.Context, network, addr string) (net.Conn, error) { + dialer.NetDialContext = func(dialCtx context.Context, network, addr string) (net.Conn, error) { + if ctxDialer, ok := socksDialer.(proxy.ContextDialer); ok { + return ctxDialer.DialContext(dialCtx, network, addr) + } return socksDialer.Dial(network, addr) } case "http", "https": diff --git a/internal/store/gitstore.go b/internal/store/gitstore.go index d4e55cca235..cdf3922027e 100644 --- a/internal/store/gitstore.go +++ b/internal/store/gitstore.go @@ -707,14 +707,24 @@ func (s *GitTokenStore) guardWatcherAuthRemovalLocked(message string, relPaths [ } func (s *GitTokenStore) resolveDeletePath(id string) (string, error) { - if strings.ContainsRune(id, os.PathSeparator) || filepath.IsAbs(id) { - return id, nil - } dir := s.baseDirSnapshot() + if filepath.IsAbs(id) { + clean := filepath.Clean(id) + if dir != "" { + if rel, errRel := filepath.Rel(dir, clean); errRel != nil || isOutsideManagedDir(rel) { + return "", fmt.Errorf("git token store: path %s outside managed auth directory", id) + } + } + return clean, nil + } if dir == "" { return "", fmt.Errorf("auth filestore: directory not configured") } - return filepath.Join(dir, id), nil + clean := filepath.Clean(filepath.FromSlash(id)) + if isOutsideManagedDir(clean) { + return "", fmt.Errorf("git token store: invalid auth identifier %s", id) + } + return filepath.Join(dir, clean), nil } func (s *GitTokenStore) readAuthFile(path, baseDir string) (*cliproxyauth.Auth, error) { diff --git a/internal/store/object_refresh_journal.go b/internal/store/object_refresh_journal.go index bb8e8401aee..464aebe2b7b 100644 --- a/internal/store/object_refresh_journal.go +++ b/internal/store/object_refresh_journal.go @@ -33,6 +33,9 @@ func (s *ObjectTokenStore) RefreshClaim(ctx context.Context, key string) (bool, } func (s *ObjectTokenStore) RefreshRead(ctx context.Context, key string) ([]byte, error) { + if s == nil || s.client == nil { + return nil, fmt.Errorf("object refresh journal is unavailable") + } object, errGet := s.client.GetObject(ctx, s.cfg.Bucket, s.refreshObjectKey(key, "receipt"), minio.GetObjectOptions{}) if errGet != nil { return nil, errGet @@ -57,6 +60,9 @@ func (s *ObjectTokenStore) RefreshRead(ctx context.Context, key string) ([]byte, } func (s *ObjectTokenStore) RefreshComplete(ctx context.Context, key string, receipt []byte) error { + if s == nil || s.client == nil { + return fmt.Errorf("object refresh journal is unavailable") + } s.refreshClaims.Delete(key) created, errCreate := s.createRefreshObject(ctx, s.refreshObjectKey(key, "receipt"), receipt) if errCreate != nil { @@ -211,6 +217,11 @@ func (s *ObjectTokenStore) probeRefreshConditionalCreate(ctx context.Context) er if errFirst != nil || !first { return fmt.Errorf("refresh journal conditional-create probe failed: %v", errFirst) } + defer func() { + if errRemove := s.client.RemoveObject(ctx, s.cfg.Bucket, key, minio.RemoveObjectOptions{}); errRemove != nil { + log.Warnf("remove refresh journal capability probe: %v", errRemove) + } + }() second, errSecond := s.createRefreshObject(ctx, key, []byte("probe")) if errSecond != nil { return errSecond @@ -218,8 +229,5 @@ func (s *ObjectTokenStore) probeRefreshConditionalCreate(ctx context.Context) er if second { return fmt.Errorf("object backend does not enforce conditional creation; refresh refused") } - if errRemove := s.client.RemoveObject(ctx, s.cfg.Bucket, key, minio.RemoveObjectOptions{}); errRemove != nil { - log.Warnf("remove refresh journal capability probe: %v", errRemove) - } return nil } diff --git a/internal/store/objectstore.go b/internal/store/objectstore.go index be7c17abc32..4949d8cd8b5 100644 --- a/internal/store/objectstore.go +++ b/internal/store/objectstore.go @@ -224,12 +224,8 @@ func (s *ObjectTokenStore) Save(ctx context.Context, auth *cliproxyauth.Auth) (s return "", fmt.Errorf("object store: read existing metadata: %w", errRead) } if !contentsMatch { - tmp := path + ".tmp" - if errWrite := os.WriteFile(tmp, raw, 0o600); errWrite != nil { - return "", fmt.Errorf("object store: write temp auth file: %w", errWrite) - } - if errRename := os.Rename(tmp, path); errRename != nil { - return "", fmt.Errorf("object store: rename auth file: %w", errRename) + if errWrite := misc.WriteFileAtomic(path, raw, 0o600); errWrite != nil { + return "", fmt.Errorf("object store: write auth file: %w", errWrite) } } default: @@ -471,13 +467,32 @@ func (s *ObjectTokenStore) syncAuthFromBucket(ctx context.Context) error { return nil } +func (s *ObjectTokenStore) relativeAuthPath(path string) (string, error) { + if s == nil || strings.TrimSpace(s.authDir) == "" { + return "", fmt.Errorf("object store: auth directory not configured") + } + candidate := path + if !filepath.IsAbs(candidate) { + candidate = filepath.Join(s.authDir, filepath.FromSlash(candidate)) + } + clean := filepath.Clean(candidate) + rel, err := filepath.Rel(s.authDir, clean) + if err != nil { + return "", fmt.Errorf("object store: resolve auth relative path: %w", err) + } + if isOutsideManagedDir(rel) { + return "", fmt.Errorf("object store: path %s outside managed auth directory", path) + } + return filepath.ToSlash(rel), nil +} + func (s *ObjectTokenStore) uploadAuth(ctx context.Context, path string) error { if path == "" { return nil } - rel, err := filepath.Rel(s.authDir, path) + rel, err := s.relativeAuthPath(path) if err != nil { - return fmt.Errorf("object store: resolve auth relative path: %w", err) + return err } data, err := os.ReadFile(path) if err != nil { @@ -489,7 +504,7 @@ func (s *ObjectTokenStore) uploadAuth(ctx context.Context, path string) error { if len(data) == 0 { return s.deleteAuthObject(ctx, path) } - key := objectStoreAuthPrefix + "/" + filepath.ToSlash(rel) + key := objectStoreAuthPrefix + "/" + rel return s.putObject(ctx, key, data, "application/json") } @@ -497,11 +512,11 @@ func (s *ObjectTokenStore) deleteAuthObject(ctx context.Context, path string) er if path == "" { return nil } - rel, err := filepath.Rel(s.authDir, path) + rel, err := s.relativeAuthPath(path) if err != nil { - return fmt.Errorf("object store: resolve auth relative path: %w", err) + return err } - key := objectStoreAuthPrefix + "/" + filepath.ToSlash(rel) + key := objectStoreAuthPrefix + "/" + rel return s.deleteObject(ctx, key) } @@ -550,25 +565,33 @@ func (s *ObjectTokenStore) resolveAuthPath(auth *cliproxyauth.Auth) (string, err if auth == nil { return "", fmt.Errorf("object store: auth is nil") } + var candidate string if auth.Attributes != nil { if path := strings.TrimSpace(auth.Attributes["path"]); path != "" { if filepath.IsAbs(path) { - return path, nil + candidate = filepath.Clean(path) + } else { + candidate = filepath.Join(s.authDir, filepath.FromSlash(path)) } - return filepath.Join(s.authDir, path), nil } } - fileName := strings.TrimSpace(auth.FileName) - if fileName == "" { - fileName = strings.TrimSpace(auth.ID) - } - if fileName == "" { - return "", fmt.Errorf("object store: auth %s missing filename", auth.ID) + if candidate == "" { + fileName := strings.TrimSpace(auth.FileName) + if fileName == "" { + fileName = strings.TrimSpace(auth.ID) + } + if fileName == "" { + return "", fmt.Errorf("object store: auth %s missing filename", auth.ID) + } + if !strings.HasSuffix(strings.ToLower(fileName), ".json") { + fileName += ".json" + } + candidate = filepath.Join(s.authDir, filepath.FromSlash(fileName)) } - if !strings.HasSuffix(strings.ToLower(fileName), ".json") { - fileName += ".json" + if _, errRel := s.relativeAuthPath(candidate); errRel != nil { + return "", errRel } - return filepath.Join(s.authDir, fileName), nil + return candidate, nil } func (s *ObjectTokenStore) resolveDeletePath(id string) (string, error) { @@ -576,21 +599,26 @@ func (s *ObjectTokenStore) resolveDeletePath(id string) (string, error) { if id == "" { return "", fmt.Errorf("object store: id is empty") } - // Absolute paths are honored as-is; callers must ensure they point inside the mirror. + var candidate string if filepath.IsAbs(id) { - return id, nil - } - // Treat any non-absolute id (including nested like "team/foo") as relative to the mirror authDir. - // Normalize separators and guard against path traversal. - clean := filepath.Clean(filepath.FromSlash(id)) - if clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) { - return "", fmt.Errorf("object store: invalid auth identifier %s", id) + candidate = filepath.Clean(id) + } else { + // Treat any non-absolute id (including nested like "team/foo") as relative to the mirror authDir. + // Normalize separators and guard against path traversal. + clean := filepath.Clean(filepath.FromSlash(id)) + if isOutsideManagedDir(clean) { + return "", fmt.Errorf("object store: invalid auth identifier %s", id) + } + // Ensure .json suffix. + if !strings.HasSuffix(strings.ToLower(clean), ".json") { + clean += ".json" + } + candidate = filepath.Join(s.authDir, clean) } - // Ensure .json suffix. - if !strings.HasSuffix(strings.ToLower(clean), ".json") { - clean += ".json" + if _, errRel := s.relativeAuthPath(candidate); errRel != nil { + return "", errRel } - return filepath.Join(s.authDir, clean), nil + return candidate, nil } func (s *ObjectTokenStore) readAuthFile(path, baseDir string) (*cliproxyauth.Auth, error) { diff --git a/internal/store/postgres_refresh_journal.go b/internal/store/postgres_refresh_journal.go index 965ee5c7f26..83c580e2d88 100644 --- a/internal/store/postgres_refresh_journal.go +++ b/internal/store/postgres_refresh_journal.go @@ -71,6 +71,12 @@ func (s *PostgresStore) ensureRefreshSchema(ctx context.Context) error { } func (s *PostgresStore) RefreshRead(ctx context.Context, key string) ([]byte, error) { + if s == nil || s.db == nil { + return nil, fmt.Errorf("postgres refresh journal is unavailable") + } + if errSchema := s.ensureRefreshSchema(ctx); errSchema != nil { + return nil, errSchema + } var receipt []byte errRead := s.db.QueryRowContext(ctx, "SELECT receipt FROM "+s.refreshTable()+" WHERE id = $1", key).Scan(&receipt) if errors.Is(errRead, sql.ErrNoRows) { @@ -83,6 +89,12 @@ func (s *PostgresStore) RefreshRead(ctx context.Context, key string) ([]byte, er } func (s *PostgresStore) RefreshComplete(ctx context.Context, key string, receipt []byte) error { + if s == nil || s.db == nil { + return fmt.Errorf("postgres refresh journal is unavailable") + } + if errSchema := s.ensureRefreshSchema(ctx); errSchema != nil { + return errSchema + } s.refreshClaims.Delete(key) result, errUpdate := s.db.ExecContext(ctx, "UPDATE "+s.refreshTable()+" SET receipt = $2 WHERE id = $1 AND receipt IS NULL", key, receipt) if errUpdate != nil { diff --git a/internal/store/postgresstore.go b/internal/store/postgresstore.go index 48969cbfa8e..6d186726305 100644 --- a/internal/store/postgresstore.go +++ b/internal/store/postgresstore.go @@ -95,6 +95,9 @@ func NewPostgresStore(ctx context.Context, cfg PostgresStoreConfig) (*PostgresSt if err != nil { return nil, fmt.Errorf("postgres store: open database connection: %w", err) } + db.SetMaxOpenConns(16) + db.SetMaxIdleConns(8) + db.SetConnMaxLifetime(30 * time.Minute) if err = db.PingContext(ctx); err != nil { _ = db.Close() return nil, fmt.Errorf("postgres store: ping database: %w", err) @@ -232,6 +235,11 @@ func (s *PostgresStore) Save(ctx context.Context, auth *cliproxyauth.Auth) (stri // Runtime updates must not recreate a disabled credential whose source file // was deliberately removed. Login and migration callers explicitly mark the // save when creating a missing disabled credential is intentional. + relID, err := s.relativeAuthID(path) + if err != nil { + return "", err + } + if auth.Disabled && !cliproxyauth.HasAuthCreationIntent(ctx) { if _, statErr := os.Stat(path); errors.Is(statErr, fs.ErrNotExist) { return "", nil @@ -275,12 +283,8 @@ func (s *PostgresStore) Save(ctx context.Context, auth *cliproxyauth.Auth) (stri return "", fmt.Errorf("postgres store: read existing metadata: %w", errRead) } if !contentsMatch { - tmp := path + ".tmp" - if errWrite := os.WriteFile(tmp, raw, 0o600); errWrite != nil { - return "", fmt.Errorf("postgres store: write temp auth file: %w", errWrite) - } - if errRename := os.Rename(tmp, path); errRename != nil { - return "", fmt.Errorf("postgres store: rename auth file: %w", errRename) + if errWrite := misc.WriteFileAtomic(path, raw, 0o600); errWrite != nil { + return "", fmt.Errorf("postgres store: write auth file: %w", errWrite) } } default: @@ -298,10 +302,6 @@ func (s *PostgresStore) Save(ctx context.Context, auth *cliproxyauth.Auth) (stri auth.FileName = auth.ID } - relID, err := s.relativeAuthID(path) - if err != nil { - return "", err - } if err = s.upsertAuthRecord(ctx, relID, path); err != nil { return "", err } @@ -390,6 +390,10 @@ func (s *PostgresStore) Delete(ctx context.Context, id string) error { if err != nil { return err } + relID, err := s.relativeAuthID(path) + if err != nil { + return err + } s.mu.Lock() defer s.mu.Unlock() @@ -397,10 +401,6 @@ func (s *PostgresStore) Delete(ctx context.Context, id string) error { if err = os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("postgres store: delete auth file: %w", err) } - relID, err := s.relativeAuthID(path) - if err != nil { - return err - } return s.deleteAuthRecord(ctx, relID) } @@ -643,25 +643,29 @@ func (s *PostgresStore) resolveAuthPath(auth *cliproxyauth.Auth) (string, error) } func (s *PostgresStore) resolveDeletePath(id string) (string, error) { - if strings.ContainsRune(id, os.PathSeparator) || filepath.IsAbs(id) { - return id, nil + if filepath.IsAbs(id) { + return filepath.Clean(id), nil } return filepath.Join(s.authDir, filepath.FromSlash(id)), nil } +func isOutsideManagedDir(rel string) bool { + return rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) +} + func (s *PostgresStore) relativeAuthID(path string) (string, error) { if s == nil { return "", fmt.Errorf("postgres store: store not initialized") } if !filepath.IsAbs(path) { - path = filepath.Join(s.authDir, path) + path = filepath.Join(s.authDir, filepath.FromSlash(path)) } clean := filepath.Clean(path) rel, err := filepath.Rel(s.authDir, clean) if err != nil { return "", fmt.Errorf("postgres store: compute relative path: %w", err) } - if strings.HasPrefix(rel, "..") { + if isOutsideManagedDir(rel) { return "", fmt.Errorf("postgres store: path %s outside managed directory", path) } return filepath.ToSlash(rel), nil @@ -672,7 +676,7 @@ func (s *PostgresStore) absoluteAuthPath(id string) (string, error) { return "", fmt.Errorf("postgres store: store not initialized") } clean := filepath.Clean(filepath.FromSlash(id)) - if strings.HasPrefix(clean, "..") { + if isOutsideManagedDir(clean) { return "", fmt.Errorf("postgres store: invalid auth identifier %s", id) } path := filepath.Join(s.authDir, clean) @@ -680,7 +684,7 @@ func (s *PostgresStore) absoluteAuthPath(id string) (string, error) { if err != nil { return "", err } - if strings.HasPrefix(rel, "..") { + if isOutsideManagedDir(rel) { return "", fmt.Errorf("postgres store: resolved auth path escapes auth directory") } return path, nil diff --git a/internal/thinking/provider/codex/apply.go b/internal/thinking/provider/codex/apply.go index e493c7c2e2d..6d73e7d4607 100644 --- a/internal/thinking/provider/codex/apply.go +++ b/internal/thinking/provider/codex/apply.go @@ -30,8 +30,11 @@ func (a *Applier) Apply(body []byte, config thinking.ThinkingConfig, modelInfo * if len(body) == 0 || !ojson.ValidBytes(body) { body = []byte("{}") } - result, _ := ojson.SetBytes(body, "reasoning.effort", effort) - return result, nil + doc := ojson.NewDoc(body) + if errSet := doc.Set("reasoning.effort", effort); errSet != nil { + return body, nil + } + return doc.Bytes(), nil } // ApplyDoc applies thinking configuration onto doc in place. diff --git a/internal/thinking/provider/openai/apply.go b/internal/thinking/provider/openai/apply.go index b0b998faec2..27a0a9922ce 100644 --- a/internal/thinking/provider/openai/apply.go +++ b/internal/thinking/provider/openai/apply.go @@ -30,8 +30,11 @@ func (a *Applier) Apply(body []byte, config thinking.ThinkingConfig, modelInfo * if len(body) == 0 || !ojson.ValidBytes(body) { body = []byte("{}") } - result, _ := ojson.SetBytes(body, "reasoning_effort", effort) - return result, nil + doc := ojson.NewDoc(body) + if errSet := doc.Set("reasoning_effort", effort); errSet != nil { + return body, nil + } + return doc.Bytes(), nil } // ApplyDoc applies thinking configuration onto doc in place. diff --git a/sdk/auth/filestore.go b/sdk/auth/filestore.go index 8ae00acbc60..a512a945b28 100644 --- a/sdk/auth/filestore.go +++ b/sdk/auth/filestore.go @@ -212,14 +212,25 @@ func (s *FileTokenStore) Delete(ctx context.Context, id string) error { } func (s *FileTokenStore) resolveDeletePath(id string) (string, error) { - if strings.ContainsRune(id, os.PathSeparator) || filepath.IsAbs(id) { - return id, nil - } dir := s.baseDirSnapshot() + if filepath.IsAbs(id) { + clean := filepath.Clean(id) + if dir != "" { + rel, errRel := filepath.Rel(dir, clean) + if errRel != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + return "", fmt.Errorf("auth filestore: path %s outside managed directory", id) + } + } + return clean, nil + } if dir == "" { return "", fmt.Errorf("auth filestore: directory not configured") } - return filepath.Join(dir, id), nil + clean := filepath.Clean(filepath.FromSlash(id)) + if clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) || filepath.IsAbs(clean) { + return "", fmt.Errorf("auth filestore: invalid auth identifier %s", id) + } + return filepath.Join(dir, clean), nil } func (s *FileTokenStore) readAuthFiles(path, baseDir string) ([]*cliproxyauth.Auth, error) { diff --git a/sdk/cliproxy/auth/conductor_refresh_disabled_test.go b/sdk/cliproxy/auth/conductor_refresh_disabled_test.go index 681b887be31..050d3688ba7 100644 --- a/sdk/cliproxy/auth/conductor_refresh_disabled_test.go +++ b/sdk/cliproxy/auth/conductor_refresh_disabled_test.go @@ -2,7 +2,6 @@ package auth import ( "context" - "encoding/base64" "errors" "fmt" "net/http" @@ -10,6 +9,7 @@ import ( "testing" "time" + "github.com/MoeForge/moego/base64" cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" ) diff --git a/sdk/cliproxy/auth/cooldown_state.go b/sdk/cliproxy/auth/cooldown_state.go index 6609508d8d9..0a33f3d4aae 100644 --- a/sdk/cliproxy/auth/cooldown_state.go +++ b/sdk/cliproxy/auth/cooldown_state.go @@ -237,6 +237,11 @@ func writeCooldownStateGroup(ctx context.Context, path string, records []Cooldow return fmt.Errorf("create cooldown state temp file: %w", errCreate) } tmp := tmpFile.Name() + if errChmod := tmpFile.Chmod(0o600); errChmod != nil { + _ = tmpFile.Close() + _ = os.Remove(tmp) + return fmt.Errorf("chmod cooldown state temp file: %w", errChmod) + } if _, errWrite := tmpFile.Write(data); errWrite != nil { if errClose := tmpFile.Close(); errClose != nil { _ = os.Remove(tmp) @@ -245,6 +250,11 @@ func writeCooldownStateGroup(ctx context.Context, path string, records []Cooldow _ = os.Remove(tmp) return fmt.Errorf("write cooldown state temp file: %w", errWrite) } + if errSync := tmpFile.Sync(); errSync != nil { + _ = tmpFile.Close() + _ = os.Remove(tmp) + return fmt.Errorf("sync cooldown state temp file: %w", errSync) + } if errClose := tmpFile.Close(); errClose != nil { _ = os.Remove(tmp) return fmt.Errorf("close cooldown state temp file: %w", errClose) diff --git a/sdk/cliproxy/auth/session_persistence.go b/sdk/cliproxy/auth/session_persistence.go index 5e6f86bfcec..ca468d59925 100644 --- a/sdk/cliproxy/auth/session_persistence.go +++ b/sdk/cliproxy/auth/session_persistence.go @@ -267,6 +267,8 @@ func (p *sessionAffinityPersistence) flush() { ttl := expiresAt.Sub(p.now()) if ttl > 0 { _, errWrite = client.KVSet(context.Background(), affinitySnapshotKey, doc.Bytes(), kvstore.KVSetOptions{PX: ttl}) + } else { + _, errWrite = client.KVDel(context.Background(), affinitySnapshotKey) } } } diff --git a/sdk/cliproxy/kv_store.go b/sdk/cliproxy/kv_store.go index 93014b42a72..748bf444429 100644 --- a/sdk/cliproxy/kv_store.go +++ b/sdk/cliproxy/kv_store.go @@ -24,7 +24,13 @@ func (s *Service) applyKVStoreConfig(cfg *config.Config) { } return } - if errConfigure := kvstore.ConfigureLocal(true, cfg.EffectiveKVStorePath()); errConfigure == nil && s.coreManager != nil { + if errConfigure := kvstore.ConfigureLocal(true, cfg.EffectiveKVStorePath()); errConfigure != nil { + if s.coreManager != nil { + s.coreManager.SetSessionAffinityPersistenceEnabled(false) + } + return + } + if s.coreManager != nil { s.coreManager.SetSessionAffinityPersistenceEnabled(true) } } From f309c53decd0f8165bb0600daddb789e279e4d47 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:00:20 -0800 Subject: [PATCH 2/3] fix(web): remove layout shifts on load and after interaction Audited every panel route at 390px and 1440px on a throttled connection with the cache disabled, then clicked through the main flows. Fixes target each cause: - Skeletons take the loaded size: dashboard stat tiles are real Stat tiles with inline skeletons and a reserved hint line; the accounts table skeleton has its header, last row count and last height; pool panels and the first pool keep their last height (useRememberedSize/lastLayout); the model-rules rail skeleton matches the phone chip row. - Data-dependent rows render while loading: provider tab rows, pending tab counts (count: null), toolbar summaries, the Connect key row and hint, the routing model line, and header actions. - Live text cannot re-wrap: one-line quota summary (attention first), one-line pool meta with the stale badge standing in for the time, dashboard window as a title pill, fixed-basis section headers, logs readouts with fixed boxes, tabular digits panel-wide. - Buttons keep their width while loading (spinner over a hidden label); the plugin update dot no longer widens its tab. - The pool chart measures its width before paint (it painted 80px too tall on phones first), and pools are not dropped before history answers. - The accounts bulk-action bar floats in a sticky dock instead of pushing the rows down under the pointer. - Sidebar plugin pages and other layout facts are remembered per viewer. DESIGN.md records the layout-stability rules. The dev fixture accepts &latency= to reproduce slow data. Co-Authored-By: Claude Opus 5.5 --- web/DESIGN.md | 15 +- web/src/components/layout/navigation.tsx | 32 ++++- web/src/components/ui/Button.tsx | 11 +- web/src/components/ui/PageHeader.tsx | 20 ++- web/src/components/ui/PageLayout.module.scss | 9 ++ .../ui/Skeleton/Skeleton.module.scss | 5 + web/src/components/ui/Skeleton/Skeleton.tsx | 14 +- web/src/components/ui/Stat.tsx | 19 ++- web/src/components/ui/Tabs.module.scss | 2 + web/src/components/ui/Tabs.tsx | 8 +- web/src/features/authFiles/AuthFilesPage.tsx | 131 ++++++++++++------ .../authFiles/components/AccountsTable.tsx | 5 +- .../components/SelectionBar.module.scss | 21 ++- .../authFiles/components/SelectionBar.tsx | 15 +- .../modelRules/ModelRules.module.scss | 9 +- .../modelRules/ModelRulesWorkspace.tsx | 16 ++- web/src/features/connect/ConnectPage.tsx | 20 ++- web/src/features/dashboard/DashboardPage.tsx | 25 ++-- .../features/dashboard/dashboard.module.scss | 6 - web/src/features/logs/LogsPage.module.scss | 17 +++ .../features/plugins/PluginsPage.module.scss | 7 +- web/src/features/plugins/PluginsPage.tsx | 22 ++- web/src/features/quota/QuotaPage.module.scss | 12 +- web/src/features/quota/QuotaPage.tsx | 48 +++++-- .../features/quota/__fixtures__/devFixture.ts | 10 +- .../quota/components/AccountDetail.tsx | 2 +- .../features/quota/components/PoolChart.tsx | 6 +- .../components/QuotaPoolCard.module.scss | 26 +++- .../quota/components/QuotaPoolCard.tsx | 38 +++-- .../features/routing/RoutingPage.module.scss | 4 + web/src/features/routing/RoutingPage.tsx | 14 +- web/src/hooks/useRememberedSize.ts | 40 ++++++ web/src/i18n/locales/en.json | 5 +- web/src/pages/SystemPage.module.scss | 3 +- web/src/pages/SystemPage.tsx | 15 +- web/src/styles/components.scss | 12 ++ web/src/styles/global.scss | 3 + web/src/utils/lastLayout.ts | 39 ++++++ web/tests/codexCreditOverageUi.test.ts | 2 +- 39 files changed, 578 insertions(+), 130 deletions(-) create mode 100644 web/src/hooks/useRememberedSize.ts create mode 100644 web/src/utils/lastLayout.ts diff --git a/web/DESIGN.md b/web/DESIGN.md index 8cc32dae1b3..7107231f9b8 100644 --- a/web/DESIGN.md +++ b/web/DESIGN.md @@ -62,8 +62,9 @@ code; replace them when you touch a file. Sass `$spacing-*`, `$radius-*`, `$font | Page title | 18px / 600 (`--text-xl`), via `PageHeader` | | Headline metric | 32px max (`--text-display`), one per page, via `Stat size="lg"` | -Nothing in the chrome is larger than 20px. Numbers use `font-variant-numeric: -tabular-nums` (`.tabular`, built into `Stat`, `Badge`, `Table`). Mono (`.mono`, +Nothing in the chrome is larger than 20px. Digits are tabular everywhere +(`font-variant-numeric: tabular-nums` on `body`), so live numbers never change width +as they tick; `.tabular` remains for markup that resets it. Mono (`.mono`, `--font-mono`) is only for code, keys, IDs, paths, addresses and log lines. No uppercase, no letter-spaced labels, no gradient text. @@ -145,6 +146,16 @@ are stacked with a 24px gap by the shell. - **Loading**: `Skeleton` blocks shaped like the content, or an inline `Spinner` with a label. Never a full-page splash. +- **Layout stability**: nothing moves when data arrives or after a click. + - Skeletons take the loaded content's exact size. Build them from the real component + (`Stat` with `Skeleton inline` values, `reserveHint`) or size them from the last + visit with `useRememberedSize` / `utils/lastLayout` (row counts, optional rows). + - Rows and controls that depend on data (tab rows, toolbar summaries, hints) render + a placeholder of the same size while loading. A pending tab count is `count: null`. + - Live text that changes length gets one line (`PageHeader singleLineDescription`) + or a fixed box; right-aligned readouts get a min-width. + - `Button loading` keeps its label laid out under the spinner; never swap the icon. + - Bulk-action bars float (sticky dock); they never enter the page flow. - **Empty**: one `EmptyState` with a plain title, one sentence and at most one action. - **Error**: `.error-box` (or a `destructive` `Badge` for a row) saying what failed and what to do next; keep the rest of the page usable. Toasts confirm actions; they do diff --git a/web/src/components/layout/navigation.tsx b/web/src/components/layout/navigation.tsx index c801e963ef6..8b643780ea7 100644 --- a/web/src/components/layout/navigation.tsx +++ b/web/src/components/layout/navigation.tsx @@ -62,11 +62,35 @@ export const isNavLinkActive = (item: NavLinkItem, pathname: string) => { return paths.some((path) => trimmed === path || (path !== '/' && trimmed.startsWith(`${path}/`))); }; +const PLUGIN_RESOURCES_CACHE_KEY = 't3code-proxy.nav-plugin-pages'; + +// The last plugin pages seen for a hub, so the sidebar opens at its final +// height instead of growing when the plugin list arrives. +const readCachedPluginResources = (apiBase: string): PluginResourceEntry[] => { + try { + const cached = JSON.parse(localStorage.getItem(PLUGIN_RESOURCES_CACHE_KEY) ?? 'null'); + return cached?.apiBase === apiBase && Array.isArray(cached.resources) ? cached.resources : []; + } catch { + return []; + } +}; + +const writeCachedPluginResources = (apiBase: string, resources: PluginResourceEntry[]) => { + try { + localStorage.setItem(PLUGIN_RESOURCES_CACHE_KEY, JSON.stringify({ apiBase, resources })); + } catch { + // Storage is a convenience; the list still loads from the hub. + } +}; + /** Plugin-contributed pages, reloaded on connection and on the refresh event. */ function usePluginResources() { const connectionStatus = useAuthStore((state) => state.connectionStatus); const supportsPlugin = useAuthStore((state) => state.supportsPlugin); - const [resources, setResources] = useState([]); + const apiBase = useAuthStore((state) => state.apiBase); + const [resources, setResources] = useState(() => + readCachedPluginResources(apiBase) + ); const load = useCallback(async () => { if (connectionStatus !== 'connected' || !supportsPlugin) { @@ -75,11 +99,13 @@ function usePluginResources() { } try { const plugins = await pluginsApi.list(); - setResources(collectPluginResourceEntries(plugins.plugins)); + const next = collectPluginResourceEntries(plugins.plugins); + setResources(next); + writeCachedPluginResources(apiBase, next); } catch { setResources([]); } - }, [connectionStatus, supportsPlugin]); + }, [apiBase, connectionStatus, supportsPlugin]); return { resources, load }; } diff --git a/web/src/components/ui/Button.tsx b/web/src/components/ui/Button.tsx index d1349836480..ff7305960b7 100644 --- a/web/src/components/ui/Button.tsx +++ b/web/src/components/ui/Button.tsx @@ -40,7 +40,14 @@ export function Button({ ...rest }: PropsWithChildren) { const hasChildren = children !== null && children !== undefined && children !== false; - const classes = buttonClassName(variant, size, [fullWidth && 'btn-full', className]); + // A labelled button keeps its label laid out (hidden) while loading and + // centres the spinner over it, so the button never changes width. + const overlay = loading && hasChildren; + const classes = buttonClassName(variant, size, [ + fullWidth && 'btn-full', + overlay && 'btn-loading', + className, + ]); return ( ); } diff --git a/web/src/components/ui/PageHeader.tsx b/web/src/components/ui/PageHeader.tsx index 71febccc558..44c4fec03b2 100644 --- a/web/src/components/ui/PageHeader.tsx +++ b/web/src/components/ui/PageHeader.tsx @@ -5,6 +5,12 @@ interface PageHeaderProps { title: ReactNode; /** One plain sentence about what the page is for. Optional. */ description?: ReactNode; + /** + * Keep the description on one line (ellipsis, full text as a tooltip). Use it + * for live summaries whose length changes as data arrives, so the header + * never changes height. + */ + singleLineDescription?: boolean; /** Inline context after the title, e.g. a count Badge. */ meta?: ReactNode; /** Right-aligned actions; at most one `variant="primary"` button. */ @@ -18,6 +24,7 @@ interface PageHeaderProps { export function PageHeader({ title, description, + singleLineDescription = false, meta, actions, tabs, @@ -31,7 +38,18 @@ export function PageHeader({

{title}

{meta ?
{meta}
: null} - {description ?

{description}

: null} + {description ? ( +

+ {description} +

+ ) : null} {actions ?
{actions}
: null} diff --git a/web/src/components/ui/PageLayout.module.scss b/web/src/components/ui/PageLayout.module.scss index 7f50fdc8faf..2314b3f0547 100644 --- a/web/src/components/ui/PageLayout.module.scss +++ b/web/src/components/ui/PageLayout.module.scss @@ -55,6 +55,12 @@ font-size: var(--text-base); } +.descriptionSingleLine { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + .actions { display: flex; align-items: center; @@ -166,8 +172,11 @@ flex-wrap: wrap; } +// A fixed basis (like the page header's) makes the actions wrap only for their +// own width, never because a live description grew. .sectionText { display: flex; + flex: 1 1 16rem; flex-direction: column; gap: 2px; min-width: 0; diff --git a/web/src/components/ui/Skeleton/Skeleton.module.scss b/web/src/components/ui/Skeleton/Skeleton.module.scss index a66481195f1..e2edefffa36 100644 --- a/web/src/components/ui/Skeleton/Skeleton.module.scss +++ b/web/src/components/ui/Skeleton/Skeleton.module.scss @@ -5,6 +5,11 @@ animation: skeleton-pulse 1.4s ease-in-out infinite; } +.inline { + display: inline-block; + vertical-align: middle; +} + @keyframes skeleton-pulse { 50% { opacity: 0.55; diff --git a/web/src/components/ui/Skeleton/Skeleton.tsx b/web/src/components/ui/Skeleton/Skeleton.tsx index 62b6d158ceb..667574a1041 100644 --- a/web/src/components/ui/Skeleton/Skeleton.tsx +++ b/web/src/components/ui/Skeleton/Skeleton.tsx @@ -5,15 +5,25 @@ interface SkeletonProps extends HTMLAttributes { width?: number | string; height?: number | string; rounded?: number | string; + /** Sit inside a line of text (label, value) so the line keeps its text height. */ + inline?: boolean; } -export function Skeleton({ width, height, rounded, className, style, ...rest }: SkeletonProps) { +export function Skeleton({ + width, + height, + rounded, + inline = false, + className, + style, + ...rest +}: SkeletonProps) { const merged: CSSProperties = { ...style, width: width ?? style?.width, height: height ?? style?.height, borderRadius: rounded ?? style?.borderRadius, }; - const cls = [styles.skeleton, className].filter(Boolean).join(' '); + const cls = [styles.skeleton, inline && styles.inline, className].filter(Boolean).join(' '); return ); } diff --git a/web/src/components/ui/Tabs.module.scss b/web/src/components/ui/Tabs.module.scss index aae8262da56..1e486b977e0 100644 --- a/web/src/components/ui/Tabs.module.scss +++ b/web/src/components/ui/Tabs.module.scss @@ -51,6 +51,8 @@ } .count { + // Room for two digits, so a tab keeps its width while a count loads or changes. + min-width: 2ch; color: var(--muted-foreground); font-size: var(--text-sm); font-weight: 400; diff --git a/web/src/components/ui/Tabs.tsx b/web/src/components/ui/Tabs.tsx index ec0b2a7d9c4..e4a47fd9669 100644 --- a/web/src/components/ui/Tabs.tsx +++ b/web/src/components/ui/Tabs.tsx @@ -6,8 +6,8 @@ export interface TabItem { label: ReactNode; /** 16px icon shown before the label. */ icon?: ReactNode; - /** Optional count shown after the label. */ - count?: number; + /** Optional count shown after the label; `null` holds its space while it loads. */ + count?: number | null; disabled?: boolean; } @@ -99,6 +99,10 @@ export function Tabs({ {item.label} {typeof item.count === 'number' ? ( {item.count} + ) : item.count === null ? ( + ) : null} ); diff --git a/web/src/features/authFiles/AuthFilesPage.tsx b/web/src/features/authFiles/AuthFilesPage.tsx index 151973aac48..7be4213ef6f 100644 --- a/web/src/features/authFiles/AuthFilesPage.tsx +++ b/web/src/features/authFiles/AuthFilesPage.tsx @@ -23,6 +23,9 @@ import { } from '@/components/ui/icons'; import { copyToClipboard } from '@/utils/clipboard'; import { getQuotaCacheKey } from '@/utils/quota/identity'; +import { recallLayoutFlag, recallLayoutNumber, rememberLayout } from '@/utils/lastLayout'; +import { layoutBreakpoint, useRememberedSize } from '@/hooks/useRememberedSize'; +import { Skeleton } from '@/components/ui/Skeleton'; import { getTypeLabel, isProblemAuthFile, @@ -31,7 +34,10 @@ import { type ResolvedTheme, } from '@/features/authFiles/constants'; import { AccountRow } from '@/features/authFiles/components/AccountRow'; -import { AccountsTable, AccountsTableSkeleton } from '@/features/authFiles/components/AccountsTable'; +import { + AccountsTable, + AccountsTableSkeleton, +} from '@/features/authFiles/components/AccountsTable'; import { AuthFileDetailsSheet } from '@/features/authFiles/components/AuthFileDetailsSheet'; import { AuthFileModelsModal } from '@/features/authFiles/components/AuthFileModelsModal'; import { AuthFileRefreshResults } from '@/features/authFiles/components/AuthFileRefreshResults'; @@ -331,7 +337,10 @@ export function AuthFilesPage() { (file) => selectedFiles.has(file.name) && statusUpdating[getAuthFileRefreshKey(file)] === true ); const batchStatusDisabled = - disableControls || selectedNames.length === 0 || batchStatusUpdating || selectedHasStatusUpdating; + disableControls || + selectedNames.length === 0 || + batchStatusUpdating || + selectedHasStatusUpdating; const activeCount = files.filter((file) => file.disabled !== true).length; const problemCount = files.filter(isProblemAuthFile).length; @@ -401,6 +410,31 @@ export function AuthFilesPage() { const isNoResults = !loading && files.length > 0 && pageItems.length === 0; const showTabs = providerTabs.length > 2; + // The first-load skeleton takes the shape the list had last time: the same + // row count, provider tabs and pagination, so nothing moves when it arrives. + const [lastLayout] = useState(() => ({ + rows: Math.max( + 1, + Math.min(PAGE_SIZES[PAGE_SIZES.length - 1], recallLayoutNumber('auth-files.rows', 6)) + ), + tabs: recallLayoutFlag('auth-files.tabs', true), + pagination: recallLayoutFlag('auth-files.pagination', false), + })); + const firstLoad = loading && files.length === 0; + const hasPagination = sorted.length > PAGE_SIZES[0]; + // Rows can be taller than the skeleton's (a second status line), so the + // skeleton also starts at the table's last height. + const [tableRef, rememberedTableHeight] = useRememberedSize( + `auth-files.table.${layoutBreakpoint()}`, + !loading && !error && pageItems.length > 0 && expanded.size === 0 + ); + useEffect(() => { + if (loading || error) return; + rememberLayout('auth-files.rows', pageItems.length); + rememberLayout('auth-files.tabs', showTabs); + rememberLayout('auth-files.pagination', hasPagination); + }, [error, hasPagination, loading, pageItems.length, showTabs]); + const description = loading ? t('auth_files.description') : [ @@ -477,10 +511,14 @@ export function AuthFilesPage() { } tabs={ - showTabs ? ( + showTabs || (firstLoad && lastLayout.tabs) ? ( { setFilter(value); @@ -567,7 +605,9 @@ export function AuthFilesPage() { )} {loading ? ( - +
+ +
) : isNoResults ? ( ) : pageItems.length > 0 ? ( - - {pageItems.map((file) => { - const key = getQuotaCacheKey(file); - return ( - - ); - })} - +
+ + {pageItems.map((file) => { + const key = getQuotaCacheKey(file); + return ( + + ); + })} + +
) : null} - {!loading && sorted.length > PAGE_SIZES[0] && ( + {firstLoad && lastLayout.pagination && ( + + )} + + {!loading && hasPagination && (
{t('auth_files.pagination_info', { diff --git a/web/src/features/authFiles/components/AccountsTable.tsx b/web/src/features/authFiles/components/AccountsTable.tsx index 65222844b7b..a2126a6299a 100644 --- a/web/src/features/authFiles/components/AccountsTable.tsx +++ b/web/src/features/authFiles/components/AccountsTable.tsx @@ -53,6 +53,8 @@ function AccountsTableHeader({ ); } +const noop = () => undefined; + /** Accounts list: a table on desktop, stacked rows under 768px (CSS only). */ export function AccountsTable({ children, ...header }: AccountsTableProps) { return ( @@ -63,10 +65,11 @@ export function AccountsTable({ children, ...header }: AccountsTableProps) { ); } -/** Row-shaped placeholders for the first load. */ +/** Row-shaped placeholders for the first load, under the real header. */ export function AccountsTableSkeleton({ rows = 6 }: { rows?: number }) { return ( + {Array.from({ length: rows }, (_, index) => ( diff --git a/web/src/features/authFiles/components/SelectionBar.module.scss b/web/src/features/authFiles/components/SelectionBar.module.scss index d116a902de4..bfec96327dc 100644 --- a/web/src/features/authFiles/components/SelectionBar.module.scss +++ b/web/src/features/authFiles/components/SelectionBar.module.scss @@ -1,7 +1,21 @@ -.bar { +// Zero-height, so it never moves the page; sticks to the bottom of the scroll view. +.dock { position: sticky; - top: 8px; + bottom: 16px; z-index: 5; + flex: none; + height: 0; + margin: 0 auto; + width: 100%; + max-width: calc(var(--content-max-width) + 2 * var(--page-padding-x)); + padding: 0 var(--page-padding-x); +} + +.bar { + position: absolute; + right: var(--page-padding-x); + bottom: 0; + left: var(--page-padding-x); display: flex; align-items: center; justify-content: space-between; @@ -11,7 +25,8 @@ padding: 6px 8px 6px 12px; border: 1px solid var(--border); border-radius: var(--radius-lg); - background: var(--card); + background: var(--popover); + box-shadow: var(--shadow-popover); } .start, diff --git a/web/src/features/authFiles/components/SelectionBar.tsx b/web/src/features/authFiles/components/SelectionBar.tsx index cfc510e0c8d..80ae391fa06 100644 --- a/web/src/features/authFiles/components/SelectionBar.tsx +++ b/web/src/features/authFiles/components/SelectionBar.tsx @@ -1,3 +1,4 @@ +import { createPortal } from 'react-dom'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/Button'; import { DropdownMenu, DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/DropdownMenu'; @@ -21,8 +22,10 @@ export type SelectionBarProps = { }; /** - * Bulk actions for the selected accounts. Rendered in the page flow above the list - * only while something is selected; delete asks for confirmation naming the count. + * Bulk actions for the selected accounts, shown only while something is selected; + * delete asks for confirmation naming the count. It floats at the bottom of the + * main column instead of sitting in the page flow, so ticking the first checkbox + * never pushes the rows down under the pointer. */ export function SelectionBar(props: SelectionBarProps) { const { @@ -44,7 +47,7 @@ export function SelectionBar(props: SelectionBarProps) { if (selectionCount === 0) return null; - return ( + const bar = (
@@ -91,4 +94,10 @@ export function SelectionBar(props: SelectionBarProps) {
); + + // The scrolling main column (#main-content's parent) hosts a zero-height sticky dock. + const host = + typeof document === 'undefined' ? null : document.getElementById('main-content')?.parentElement; + const dock =
{bar}
; + return host ? createPortal(dock, host) : dock; } diff --git a/web/src/features/authFiles/modelRules/ModelRules.module.scss b/web/src/features/authFiles/modelRules/ModelRules.module.scss index 2d65f756594..d51e18668b2 100644 --- a/web/src/features/authFiles/modelRules/ModelRules.module.scss +++ b/web/src/features/authFiles/modelRules/ModelRules.module.scss @@ -103,6 +103,10 @@ min-width: 0; } +.railSkeletonBlock { + height: 220px; +} + .rail { display: flex; flex-direction: column; @@ -555,8 +559,9 @@ position: static; } - .railSkeleton { - display: none; + // The rail becomes one row of provider chips; its skeleton takes the same height. + .railSkeletonBlock { + height: 32px; } .rail { diff --git a/web/src/features/authFiles/modelRules/ModelRulesWorkspace.tsx b/web/src/features/authFiles/modelRules/ModelRulesWorkspace.tsx index 532e7ee0a88..dade262cea8 100644 --- a/web/src/features/authFiles/modelRules/ModelRulesWorkspace.tsx +++ b/web/src/features/authFiles/modelRules/ModelRulesWorkspace.tsx @@ -205,7 +205,7 @@ export function ModelRulesWorkspace({ meta={ meta.length > 0 ? {meta.join(' · ')} : undefined } - actions={status === 'ready' ? headerExtra : undefined} + actions={status === 'ready' || status === 'loading' ? headerExtra : undefined} tabs={ ariaLabel={t('model_rules.section_label')} @@ -220,10 +220,16 @@ export function ModelRulesWorkspace({ {status === 'loading' ? ( -
- +
+ {rail && ( + + )} ) : keysLoading ? ( - + ) : keys.length === 0 ? (

{t('connect.no_keys')}{' '} @@ -214,8 +225,11 @@ export function ConnectPage() {

)} - {keys.length > 0 && !revealed ? ( -

{t('connect.key_placeholder_hint')}

+ {/* Shown while keys load and in both reveal states, so the snippets below never move. */} + {keysLoading || keys.length > 0 ? ( +

+ {revealed ? t('connect.key_revealed_hint') : t('connect.key_placeholder_hint')} +

) : null} diff --git a/web/src/features/dashboard/DashboardPage.tsx b/web/src/features/dashboard/DashboardPage.tsx index af7363d622d..8663c89db46 100644 --- a/web/src/features/dashboard/DashboardPage.tsx +++ b/web/src/features/dashboard/DashboardPage.tsx @@ -43,10 +43,12 @@ export function DashboardPage() { const header = ( {t('dashboard.window_badge', { window: windowLabel })} + ) : undefined } /> ); @@ -72,11 +74,14 @@ export function DashboardPage() { <> {header}
+ {/* The real Stat with placeholder content, so the skeleton has the tiles' exact size. */} {Array.from({ length: 4 }, (_, index) => ( -
- - -
+ } + value={} + reserveHint + /> ))}
@@ -91,6 +96,7 @@ export function DashboardPage() {
diff --git a/web/src/features/dashboard/dashboard.module.scss b/web/src/features/dashboard/dashboard.module.scss index d79e2963d53..0b84739cb5b 100644 --- a/web/src/features/dashboard/dashboard.module.scss +++ b/web/src/features/dashboard/dashboard.module.scss @@ -14,12 +14,6 @@ } } -.statSkeleton { - display: flex; - flex-direction: column; - gap: var(--space-2); -} - .errorRow { display: flex; align-items: center; diff --git a/web/src/features/logs/LogsPage.module.scss b/web/src/features/logs/LogsPage.module.scss index 06aaaabb11c..dd1ae93722a 100644 --- a/web/src/features/logs/LogsPage.module.scss +++ b/web/src/features/logs/LogsPage.module.scss @@ -339,6 +339,23 @@ gap: 6px; } +// Wide enough for the largest count ("10000 of 10000 cached lines"), so the +// right-aligned readout keeps its box as the numbers grow. On phones the two +// readouts always take a line each, so "Updated …" arriving never re-wraps them. +.bufferStatus { + min-width: 27ch; + text-align: end; +} + +@include mobile { + .readStatus, + .bufferStatus { + flex-basis: 100%; + min-width: 0; + text-align: start; + } +} + .statusDot { width: 6px; height: 6px; diff --git a/web/src/features/plugins/PluginsPage.module.scss b/web/src/features/plugins/PluginsPage.module.scss index 6867c2c9821..b5ac76a2a4c 100644 --- a/web/src/features/plugins/PluginsPage.module.scss +++ b/web/src/features/plugins/PluginsPage.module.scss @@ -15,14 +15,15 @@ } } +// Pinned to the tab's corner, so the tab keeps its width when updates are found. .updateDot { - display: inline-block; + position: absolute; + top: 8px; + right: -7px; width: 6px; height: 6px; - margin-left: 6px; border-radius: 50%; background: var(--warning); - vertical-align: middle; } .notice { diff --git a/web/src/features/plugins/PluginsPage.tsx b/web/src/features/plugins/PluginsPage.tsx index f56cc237d60..54c7a330541 100644 --- a/web/src/features/plugins/PluginsPage.tsx +++ b/web/src/features/plugins/PluginsPage.tsx @@ -4,6 +4,8 @@ import { Badge } from '@/components/ui/Badge'; import { Input } from '@/components/ui/Input'; import { PageHeader } from '@/components/ui/PageHeader'; import { Tabs } from '@/components/ui/Tabs'; +import { Skeleton } from '@/components/ui/Skeleton'; +import { useRememberedSize } from '@/hooks/useRememberedSize'; import { Toolbar } from '@/components/ui/Toolbar'; import { IconAlertTriangle, IconSearch } from '@/components/ui/icons'; import { useAuthStore } from '@/stores'; @@ -190,17 +192,24 @@ export function PluginsPage() { ) : null} ), - count: data ? data.plugins.length : undefined, + count: data ? data.plugins.length : null, }, { value: 'store', label: t('plugin_management.view_store'), - count: store.data ? store.data.plugins.length : undefined, + count: store.data ? store.data.plugins.length : null, }, ]} /> ); + // The summary's placeholder starts at the width the text had last visit. + const [summaryRef, rememberedSummaryWidth] = useRememberedSize( + 'plugins.summary-width', + Boolean(data) && view !== 'store', + { dimension: 'width' } + ); + return (
) : data ? ( - + {t('plugin_management.summary_effective', { effective: effectiveCount, total: data.plugins.length, @@ -251,7 +260,12 @@ export function PluginsPage() { {pluginsDir} - ) : null + ) : ( + // Same line while the list loads, so the toolbar never wraps late. + + ) } > (() => { const canPool = (entry: QuotaFileEntry) => { + // Until the recorder answers, a provider may still have recorded windows: + // keep its card instead of dropping it and adding it back. + if (quotaHistory.status === 'loading') return true; const status = settledQuota[entry.type][getQuotaCacheKey(entry.file)]?.status; if (status !== 'success' && status !== 'error') return true; return Boolean(liveReads.get(historyAuthIndex(entry.file))?.windows.length); @@ -372,7 +377,7 @@ export function QuotaPage() { if (!providers.has(entry.type) && canPool(entry)) providers.add(entry.type); }); return [...providers].sort((a, b) => poolOrder(a) - poolOrder(b)); - }, [activeTab, liveReads, recordedProviders, settledQuota, tabEntries]); + }, [activeTab, liveReads, quotaHistory.status, recordedProviders, settledQuota, tabEntries]); const pooledEntries = useMemo( () => tabEntries.filter((entry) => (pooledProviders as string[]).includes(entry.type)), [pooledProviders, tabEntries] @@ -722,10 +727,12 @@ export function QuotaPage() { ? t('quota_overview.summary_loading') : t('quota_overview.summary_none') : [ - t('quota_overview.summary', { count: accountTotal, providers: providerSummary }), + // Attention leads: on narrow screens the one-line summary truncates the provider list, + // which the tabs below repeat. attentionCount > 0 ? t('quota_overview.summary_attention', { count: attentionCount }) : '', + t('quota_overview.summary', { count: accountTotal, providers: providerSummary }), ] .filter(Boolean) .join(' · '); @@ -744,6 +751,18 @@ export function QuotaPage() { ]; const firstLoad = loading && entries.length === 0; + const poolLoading = quotaHistory.status === 'loading' && !historyReady; + // The first-load placeholder takes the shape the page had last visit: tab row, + // view switch and the first pool's height, so nothing moves when data arrives. + const [lastLayout] = useState(() => ({ + tabs: recallLayoutFlag('quota.tabs', true), + views: recallLayoutFlag('quota.views', true), + })); + const [pageRef, rememberedFirstPool] = useRememberedSize( + `quota.first-pool.${layoutBreakpoint()}`, + !firstLoad && !poolLoading && view === 'pools', + { selector: ':scope > section' } + ); const noAccounts = !loading && !error && accountTotal === 0; const isSearchEmpty = !loading && stockTabEntries.length > 0 && filteredEntries.length === 0; const showViews = pooledProviders.length > 0; @@ -761,11 +780,16 @@ export function QuotaPage() { ); // Search and sort only earn their space once there are several accounts to sift. const showStockToolbar = stockTabEntries.length > STOCK_TOOLBAR_MIN || search !== ''; - const poolLoading = quotaHistory.status === 'loading' && !historyReady; const historyIntervalSeconds = poolHistory.intervalSeconds; const shiftSpan = (direction: -1 | 1) => setPinnedSpan(shiftPoolSpan(span, direction)); - const viewSwitch = showViews ? ( + useEffect(() => { + if (firstLoad || error) return; + rememberLayout('quota.tabs', filterTypes.length > 1); + rememberLayout('quota.views', showViews); + }, [error, filterTypes.length, firstLoad, showViews]); + + const viewSwitch = showViews || (firstLoad && lastLayout.views) ? ( ) : null; const providerTabs = - filterTypes.length > 1 ? ( + filterTypes.length > 1 || (firstLoad && lastLayout.tabs) ? ( @@ -808,10 +832,14 @@ export function QuotaPage() { }; return ( -
+
@@ -857,8 +885,8 @@ export function QuotaPage() { {firstLoad && (
{t('quota_overview.loading')} - - + {lastLayout.views && } +
)} diff --git a/web/src/features/quota/__fixtures__/devFixture.ts b/web/src/features/quota/__fixtures__/devFixture.ts index 88fa2d0a605..7999dee3d09 100644 --- a/web/src/features/quota/__fixtures__/devFixture.ts +++ b/web/src/features/quota/__fixtures__/devFixture.ts @@ -6,7 +6,7 @@ * `&pool=owner` for the owner's hub (Claude Pro + Max 5x, Codex Plus + prolite, * one Antigravity account with four group windows, one xAI weekly window), * `&pool=live` for a hub's real `quota-history` response saved (untracked) as - * `__fixtures__/live.local.json`, and `&weights=off` to simulate a hub without server-side plan weights + * `__fixtures__/live.local.json`, and `&weights=off` to simulate a hub without server-side plan weights, `&latency=` to delay answers * (`/routing/plan-weights` 404, weights kept in the browser). Loaded through a dynamic import * guarded by `import.meta.env.DEV`, so production bundles never contain it. * @@ -50,6 +50,10 @@ export function installQuotaHistoryFixture(): void { const params = new URLSearchParams(window.location.search); const historyOff = params.get('history') === 'off'; const weightsOff = params.get('weights') === 'off'; + // `&latency=` slows every answer (staggered per call) to surface layout + // shifts that only appear when data arrives late and out of order. + const latency = Math.max(120, Number(params.get('latency')) || 0); + let calls = 0; const liveDump = Object.values( import.meta.glob('./live.local.json', { eager: true, import: 'default' }) )[0] as { now: number; accounts: never[]; samples: never[] } | undefined; @@ -119,7 +123,9 @@ export function installQuotaHistoryFixture(): void { config, }); - await new Promise((resolve) => setTimeout(resolve, 120)); + calls += 1; + const delay = latency <= 120 ? latency : latency * (0.5 + ((calls * 37) % 10) / 10); + await new Promise((resolve) => setTimeout(resolve, delay)); if (!historyOff && method === 'get' && /\/quota-history$/.test(path)) { const since = Number(config.params?.since ?? 0); diff --git a/web/src/features/quota/components/AccountDetail.tsx b/web/src/features/quota/components/AccountDetail.tsx index ad60d958bfe..98b5c040494 100644 --- a/web/src/features/quota/components/AccountDetail.tsx +++ b/web/src/features/quota/components/AccountDetail.tsx @@ -193,7 +193,7 @@ export function AccountDetail(props: AccountDetailProps) { title={t('auth_files.quota_refresh_hint')} > - {!loading && diff --git a/web/src/features/quota/components/PoolChart.tsx b/web/src/features/quota/components/PoolChart.tsx index 6423108a475..a4d80bc6c8a 100644 --- a/web/src/features/quota/components/PoolChart.tsx +++ b/web/src/features/quota/components/PoolChart.tsx @@ -9,8 +9,8 @@ */ import { - useEffect, useId, + useLayoutEffect, useMemo, useRef, useState, @@ -106,7 +106,9 @@ export function PoolChart({ const [hoverX, setHoverX] = useState(null); const clipId = `${useId().replace(/:/g, '')}-clip`; - useEffect(() => { + // Before paint: the height follows the width (compact under COMPACT_WIDTH), so a + // first frame at the default width would paint 80px too tall on phones and jump. + useLayoutEffect(() => { const node = wrapRef.current; if (!node) return; const measure = () => setWidth(Math.max(280, Math.round(node.clientWidth))); diff --git a/web/src/features/quota/components/QuotaPoolCard.module.scss b/web/src/features/quota/components/QuotaPoolCard.module.scss index 6ca57fbc12e..ce46f7e421d 100644 --- a/web/src/features/quota/components/QuotaPoolCard.module.scss +++ b/web/src/features/quota/components/QuotaPoolCard.module.scss @@ -19,12 +19,26 @@ flex-shrink: 0; } +// Always one badge-high line, whether or not the reading has arrived. .meta { - display: inline-flex; + display: flex; align-items: center; - gap: var(--space-1) var(--space-3); - flex-wrap: wrap; + gap: var(--space-3); + min-width: 0; + min-height: 20px; + white-space: nowrap; font-variant-numeric: tabular-nums; + + > * { + flex-shrink: 0; + } +} + +.meta > .metaText { + flex-shrink: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; } .headControls { @@ -182,6 +196,12 @@ vertical-align: bottom; } +// Fills a loading panel held at its remembered height. +.fillSkeleton { + flex: 1 1 0; + min-height: 0; +} + .noData { display: flex; align-items: center; diff --git a/web/src/features/quota/components/QuotaPoolCard.tsx b/web/src/features/quota/components/QuotaPoolCard.tsx index a2b2cfbe0b7..2fe3ac2daa0 100644 --- a/web/src/features/quota/components/QuotaPoolCard.tsx +++ b/web/src/features/quota/components/QuotaPoolCard.tsx @@ -28,6 +28,7 @@ import { IconSlidersHorizontal } from '@/components/ui/icons'; import { Section } from '@/components/ui/Section'; import { Skeleton } from '@/components/ui/Skeleton'; import { Stat } from '@/components/ui/Stat'; +import { layoutBreakpoint, useRememberedSize } from '@/hooks/useRememberedSize'; import type { QuotaHistory } from '@/services/api'; import type { ResolvedTheme } from '@/types'; import { getAuthFileIcon, getTypeColor, getTypeLabel } from '@/features/authFiles/constants'; @@ -243,6 +244,12 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const notBy = t('quota_pool.not_by', { date: formatMonthDay(spanEnd, locale) }); const hasData = series.some((line) => line.view.tracks.length > 0); + // While loading, the panel takes the height it had last visit, so the chart, + // legend and the table below stay put when the history arrives. + const [panelRef, rememberedPanelHeight] = useRememberedSize( + `quota-pool.${provider}.${layoutBreakpoint()}`, + !loading && hasData + ); const firstEmptyValue = (view: PoolView): ReactNode => view.firstEmpty ? ( <> @@ -341,14 +348,20 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const description = ( {t('quota_pool.accounts_count', { count: accountCount })} - {lastReadAt !== null && ( - {t('quota_pool.last_reading', { time: formatClock(lastReadAt, locale) })} - )} - {stale && lastReadAt !== null && ( - + {/* One line: a stale badge stands in for the reading time (kept in its tooltip), + so the header never wraps when the history arrives. */} + {lastReadAt !== null && stale ? ( + {t('quota_pool.stale', { duration: formatDuration(now - lastReadAt) })} - )} + ) : lastReadAt !== null ? ( + + {t('quota_pool.last_reading', { time: formatClock(lastReadAt, locale) })} + + ) : null} ); @@ -572,9 +585,14 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { } >
@@ -582,7 +600,11 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { {summary} {loading ? ( - + ) : !hasData ? (
{onReadNow ? t('quota_pool.no_reading') : t('quota_pool.no_samples')} diff --git a/web/src/features/routing/RoutingPage.module.scss b/web/src/features/routing/RoutingPage.module.scss index 89b9de678af..634a6ed1e17 100644 --- a/web/src/features/routing/RoutingPage.module.scss +++ b/web/src/features/routing/RoutingPage.module.scss @@ -378,6 +378,10 @@ $label-x: $tier-pad + 1px + $index-size + 8px; // where tier names begin } .modelProgress { + // Full width, text from the start: neither the box nor the text's start moves + // as progress turns into the model count. + align-self: stretch; + text-align: start; font-size: var(--text-xs); font-variant-numeric: tabular-nums; color: var(--muted-foreground); diff --git a/web/src/features/routing/RoutingPage.tsx b/web/src/features/routing/RoutingPage.tsx index 69da690f144..9f0cf662a44 100644 --- a/web/src/features/routing/RoutingPage.tsx +++ b/web/src/features/routing/RoutingPage.tsx @@ -312,11 +312,15 @@ export function RoutingPage() { className={styles.modelField} id="routing-model-preview" /> - {modelProgress ? ( - - {t('routing.models_loading', { done: modelProgress.done, total: modelProgress.total })} - - ) : null} + {/* Always one line: progress while sources load, then the model count, so the + tiers below never move when loading ends. */} + + {modelProgress + ? t('routing.models_loading', { done: modelProgress.done, total: modelProgress.total }) + : modelOptions.length > 0 + ? t('routing.models_count', { count: modelOptions.length }) + : '\u00a0'} +
); diff --git a/web/src/hooks/useRememberedSize.ts b/web/src/hooks/useRememberedSize.ts new file mode 100644 index 00000000000..a54472e4b20 --- /dev/null +++ b/web/src/hooks/useRememberedSize.ts @@ -0,0 +1,40 @@ +import { useEffect, useRef, useState } from 'react'; +import { recallLayoutNumber, rememberLayout } from '@/utils/lastLayout'; + +/** `narrow` or `wide`, so phone and desktop layouts remember their own sizes. */ +export const layoutBreakpoint = (): 'narrow' | 'wide' => + typeof window !== 'undefined' && window.innerWidth < 768 ? 'narrow' : 'wide'; + +interface RememberedSizeOptions { + /** Measure the ref's first match for this selector instead of the ref itself. */ + selector?: string; + dimension?: 'height' | 'width'; +} + +/** + * Remembers an element's rendered size while `record` is true, and returns the + * size remembered from the last visit (read once, on mount) as `[ref, size]`. + * A loading placeholder sized to it keeps its place when the content arrives. + */ +export function useRememberedSize( + name: string, + record: boolean, + { selector, dimension = 'height' }: RememberedSizeOptions = {} +) { + const ref = useRef(null); + const [remembered] = useState(() => recallLayoutNumber(name, 0) || undefined); + + useEffect(() => { + const root = ref.current; + const element = selector ? root?.querySelector(selector) : root; + if (!record || !element || typeof ResizeObserver === 'undefined') return; + const observer = new ResizeObserver(() => { + const size = Math.round(element.getBoundingClientRect()[dimension]); + if (size > 0) rememberLayout(name, size); + }); + observer.observe(element); + return () => observer.disconnect(); + }, [dimension, name, record, selector]); + + return [ref, remembered] as const; +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index eeb066ffdc0..4520ff648a0 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -138,7 +138,7 @@ "dashboard": { "title": "Activity", "description": "Requests through the hub, in 10-minute buckets.", - "description_window": "Requests through the hub over the last {{window}}, in 10-minute buckets.", + "window_badge": "Last {{window}}", "window_m": "{{minutes}}m", "window_h": "{{hours}}h", "window_hm": "{{hours}}h {{minutes}}m", @@ -1885,6 +1885,8 @@ "entry": "Request in", "model_placeholder": "All models (type a model to preview its route)", "models_loading": "Loading models {{done}}/{{total}}", + "models_count_one": "{{count}} model", + "models_count": "{{count}} models", "tier_primary": "Preferred", "tier_backup": "Fallback {{index}}", "tier_priority": "Priority {{priority}}", @@ -2681,6 +2683,7 @@ "copy_key": "Copy key", "key_copied": "Key copied", "key_placeholder_hint": "Snippets show a placeholder while the key is hidden. Copy still includes the real key.", + "key_revealed_hint": "Snippets show the real key while it is visible. Hide it before sharing your screen.", "copy_failed": "Could not copy to the clipboard", "copied": "Copied", "claude_title": "Claude Code", diff --git a/web/src/pages/SystemPage.module.scss b/web/src/pages/SystemPage.module.scss index a29d0387817..701a93ac1ba 100644 --- a/web/src/pages/SystemPage.module.scss +++ b/web/src/pages/SystemPage.module.scss @@ -135,7 +135,8 @@ } dd { - min-height: 0; + // One text line plus padding, so a loading skeleton row is as tall as its value. + min-height: calc(1lh + 8px); padding-top: 2px; } diff --git a/web/src/pages/SystemPage.tsx b/web/src/pages/SystemPage.tsx index 5b4d7abc2f1..3e71475634b 100644 --- a/web/src/pages/SystemPage.tsx +++ b/web/src/pages/SystemPage.tsx @@ -9,6 +9,7 @@ import { Input } from '@/components/ui/Input'; import { PageHeader } from '@/components/ui/PageHeader'; import { Section } from '@/components/ui/Section'; import { Skeleton } from '@/components/ui/Skeleton'; +import { useRememberedSize } from '@/hooks/useRememberedSize'; import { Table, TableBody, @@ -259,6 +260,13 @@ export function SystemPage() { }, ]; + // The model count's placeholder starts at the width the count had last visit. + const [countRef, rememberedCountWidth] = useRememberedSize( + 'system.models-count-width', + models.length > 0, + { dimension: 'width' } + ); + return ( <> @@ -335,9 +343,14 @@ export function SystemPage() { ariaLabel={t('system_info.models_search')} end={ models.length > 0 ? ( - + {t('system_info.models_count', { count: rows.length })} + ) : modelsLoading ? ( + // Holds the count's line while the list loads, so the toolbar never wraps late. + ) : null } > diff --git a/web/src/styles/components.scss b/web/src/styles/components.scss index 48180c678a0..62e0df342ba 100644 --- a/web/src/styles/components.scss +++ b/web/src/styles/components.scss @@ -65,6 +65,18 @@ height: 14px; border-width: 2px; } + + &.btn-loading { + > .loading-spinner { + position: absolute; + inset: 0; + margin: auto; + } + + > .btn-label { + visibility: hidden; + } + } } .btn-primary { diff --git a/web/src/styles/global.scss b/web/src/styles/global.scss index cf1dce9e9b8..d8c1e4f86e2 100644 --- a/web/src/styles/global.scss +++ b/web/src/styles/global.scss @@ -11,6 +11,9 @@ body { background-color: var(--background); color: var(--foreground); + // Counts, countdowns and percentages update live all over the panel; equal-width + // digits keep a number from changing width (and nudging its neighbours) as it ticks. + font-variant-numeric: tabular-nums; } ::selection { diff --git a/web/src/utils/lastLayout.ts b/web/src/utils/lastLayout.ts new file mode 100644 index 00000000000..248a7aa36a6 --- /dev/null +++ b/web/src/utils/lastLayout.ts @@ -0,0 +1,39 @@ +/** + * Layout facts from the viewer's last visit (row counts, whether an optional + * row was shown), so skeletons take the size the loaded page will have instead + * of a guess. Per browser, best effort: every read has a fallback. + */ + +const STORAGE_KEY = 't3code-proxy.last-layout'; + +type LastLayout = Record; + +const read = (): LastLayout => { + try { + const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}'); + return parsed && typeof parsed === 'object' ? (parsed as LastLayout) : {}; + } catch { + return {}; + } +}; + +export function recallLayoutNumber(name: string, fallback: number): number { + const value = read()[name]; + return typeof value === 'number' && Number.isFinite(value) ? value : fallback; +} + +export function recallLayoutFlag(name: string, fallback: boolean): boolean { + const value = read()[name]; + return typeof value === 'boolean' ? value : fallback; +} + +export function rememberLayout(name: string, value: number | boolean): void { + try { + const current = read(); + if (current[name] === value) return; + current[name] = value; + localStorage.setItem(STORAGE_KEY, JSON.stringify(current)); + } catch { + // Storage is a convenience; skeletons fall back to their defaults. + } +} diff --git a/web/tests/codexCreditOverageUi.test.ts b/web/tests/codexCreditOverageUi.test.ts index ff0e3a2dc3e..d41afd5a388 100644 --- a/web/tests/codexCreditOverageUi.test.ts +++ b/web/tests/codexCreditOverageUi.test.ts @@ -162,7 +162,7 @@ describe('CodexCreditOverageDialog', () => { expect(markup).not.toContain('checked=""'); const footer = markup.slice(markup.indexOf('modal-footer')); expect(footer.match(/]*disabled=""[^>]*>Save<\/span>/); + expect(footer).toMatch(/]*disabled=""[^>]*>]*>Save<\/span>/); expect(footer).not.toContain('Cancel'); }); From 8eb94a8c03fa32aa8f55c2964670276050a30029 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Thu, 3 Dec 2026 04:59:01 -0800 Subject: [PATCH 3/3] fix(web): keep controls still after clicks and live updates Follow-up from clicking through every main flow at 390px and 1440px: - StableLabel lays out every alternative of a toggling label in one cell, so Hide/Show emails, Pause/Resume, Copy/Copied, Read now/Refresh, Cancel/Close and the login connection toggle never change width. - Quota span control: Today is always laid out (hidden on today's span) and Chart options is icon-only on phones, so stepping the span never wraps the toolbar and drops the pools 36px. - Pool accounts table uses a fixed layout with header widths, so live countdowns and credit counts no longer re-balance its columns. - Connect key box is sized by the row, not the key text, so revealing the key does not move Copy or re-wrap the row. - Provider tiles keep a badge-high caption line when a sign-in status replaces it. - The YAML editor shows once CodeMirror has measured its lines, so line numbers no longer jump when the tab opens. - Excluded-model rules show placeholder match lines and hold the chip row's last height while a provider's catalog loads. Co-Authored-By: Claude Opus 5.5 --- .../excludedModels/ExcludedModelsPicker.tsx | 124 ++++++++++++------ web/src/components/ui/StableLabel.tsx | 35 +++++ .../components/AuthFileDetailsSheet.tsx | 6 +- .../components/AuthFileQuotaSection.tsx | 12 +- .../authFiles/components/SelectionBar.tsx | 6 +- .../config/components/ConfigSourceEditor.tsx | 16 ++- .../features/connect/ConnectPage.module.scss | 10 +- web/src/features/connect/ConnectPage.tsx | 2 +- .../features/connect/components/CodeBlock.tsx | 6 +- web/src/features/dashboard/DashboardPage.tsx | 1 - web/src/features/logs/LogsPage.tsx | 7 +- .../oauth/components/ProviderTile.module.scss | 7 + web/src/features/plugins/PluginsPage.tsx | 1 - web/src/features/quota/QuotaPage.tsx | 40 +++--- .../quota/components/AccountDetail.tsx | 8 +- .../components/PoolAccountsTable.module.scss | 33 +++++ .../quota/components/PoolAccountsTable.tsx | 26 ++-- .../components/QuotaPoolToolbar.module.scss | 14 ++ .../quota/components/QuotaPoolToolbar.tsx | 4 +- web/src/features/quota/components/SpanNav.tsx | 18 ++- .../pages/AuthFilesOAuthExcludedEditPage.tsx | 1 + web/src/pages/login/LoginForm.tsx | 6 +- web/src/styles/components.scss | 15 +++ 23 files changed, 311 insertions(+), 87 deletions(-) create mode 100644 web/src/components/ui/StableLabel.tsx diff --git a/web/src/components/excludedModels/ExcludedModelsPicker.tsx b/web/src/components/excludedModels/ExcludedModelsPicker.tsx index a866c2b8efb..ecc1ddda2c2 100644 --- a/web/src/components/excludedModels/ExcludedModelsPicker.tsx +++ b/web/src/components/excludedModels/ExcludedModelsPicker.tsx @@ -1,11 +1,15 @@ -import { useCallback, useId, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { IconAlertTriangle, IconChevronDown, IconLoader2 } from '@/components/ui/icons'; +import { Skeleton } from '@/components/ui/Skeleton'; +import { layoutBreakpoint } from '@/hooks/useRememberedSize'; +import { recallLayoutNumber, rememberLayout } from '@/utils/lastLayout'; import { ExcludedModelChipRow, ExcludedModelRuleChip } from './ExcludedModelRuleChip'; import { ExcludedModelsPanel, type ExcludedModelCandidate } from './ExcludedModelsPanel'; import { formatExcludedRulesText, getModelExclusionState, + isWildcardRule, matchedModelsByRule, normalizeExcludedRules, replaceCustomExcludedRules, @@ -42,6 +46,11 @@ export interface ExcludedModelsPickerProps { showRuleEditor?: boolean; labelledBy?: string; + /** + * Names this rule set (e.g. the provider) so the chip row can hold its last + * height while the catalog loads; wildcard matches only appear once it has. + */ + layoutKey?: string; className?: string; } @@ -56,6 +65,7 @@ export function ExcludedModelsPicker({ reservedRuleMessage, showRuleEditor = true, labelledBy, + layoutKey, className, }: ExcludedModelsPickerProps) { const { t } = useTranslation(); @@ -98,6 +108,26 @@ export function ExcludedModelsPicker({ const hasCatalog = catalogState === 'ready' && candidates.length > 0; + const chipLayoutName = layoutKey ? `excluded-chips.${layoutKey}.${layoutBreakpoint()}` : null; + const chipRowRef = useRef(null); + useEffect(() => { + const element = chipRowRef.current; + if (!chipLayoutName || !hasCatalog || typeof ResizeObserver === 'undefined') return; + if (!element) { + rememberLayout(chipLayoutName, 0); + return; + } + const observer = new ResizeObserver(() => + rememberLayout(chipLayoutName, Math.round(element.getBoundingClientRect().height)) + ); + observer.observe(element); + return () => observer.disconnect(); + }, [chipLayoutName, hasCatalog]); + const heldChipHeight = + chipLayoutName && catalogState === 'loading' + ? recallLayoutNumber(chipLayoutName, 0) || undefined + : undefined; + /** 通配符派生出的模型(排除掉已显式勾选的,那些走实线 chip)。 */ const derivedModels = useMemo(() => { if (!hasCatalog) return []; @@ -232,44 +262,49 @@ export function ExcludedModelsPicker({
- {exactRules.length > 0 || derivedModels.length > 0 || unknownRules.length > 0 ? ( - - {exactRules.map((rule) => ( - commit(toggleExcludedRule(rules, rule, false))} - removeAriaLabel={t('excluded_models.chip_remove', { rule })} - disabled={disabled} - /> - ))} - {derivedModels.slice(0, DERIVED_CHIP_LIMIT).map((item) => ( - - ))} - {derivedModels.length > DERIVED_CHIP_LIMIT ? ( - - {t('excluded_models.chips_more', { n: derivedModels.length - DERIVED_CHIP_LIMIT })} - - ) : null} - {unknownRules.map((rule) => ( - commit(toggleExcludedRule(rules, rule, false))} - removeAriaLabel={t('excluded_models.chip_remove', { rule })} - disabled={disabled} - /> - ))} - + {exactRules.length > 0 || + derivedModels.length > 0 || + unknownRules.length > 0 || + heldChipHeight ? ( +
+ + {exactRules.map((rule) => ( + commit(toggleExcludedRule(rules, rule, false))} + removeAriaLabel={t('excluded_models.chip_remove', { rule })} + disabled={disabled} + /> + ))} + {derivedModels.slice(0, DERIVED_CHIP_LIMIT).map((item) => ( + + ))} + {derivedModels.length > DERIVED_CHIP_LIMIT ? ( + + {t('excluded_models.chips_more', { n: derivedModels.length - DERIVED_CHIP_LIMIT })} + + ) : null} + {unknownRules.map((rule) => ( + commit(toggleExcludedRule(rules, rule, false))} + removeAriaLabel={t('excluded_models.chip_remove', { rule })} + disabled={disabled} + /> + ))} + +
) : null} {showRuleEditor ? ( @@ -309,6 +344,17 @@ export function ExcludedModelsPicker({ ))} + ) : catalogState === 'loading' && customRules.some(isWildcardRule) ? ( + // The same lines while the catalog loads, so the counts arrive in place. + // Only wildcards: an exact model ID may turn into a chip once the catalog is known. + ) : null}

{t('excluded_models.rules_hint')}

diff --git a/web/src/components/ui/StableLabel.tsx b/web/src/components/ui/StableLabel.tsx new file mode 100644 index 00000000000..b1e6a6b8cca --- /dev/null +++ b/web/src/components/ui/StableLabel.tsx @@ -0,0 +1,35 @@ +import type { ReactNode } from 'react'; + +interface StableLabelProps { + /** Every label this control can show; the widest sets its width. */ + labels: readonly string[]; + /** The label to show now (one of `labels`). */ + active: string; + /** Optional element before the label (an icon), outside the stacked text. */ + icon?: ReactNode; +} + +/** + * A label that swaps text in place ("Hide emails" / "Show emails", "Copy" / + * "Copied") without changing the control's width: every alternative is laid + * out in the same grid cell and only the active one is visible, so nothing + * next to the control moves when it is clicked. + */ +export function StableLabel({ labels, active, icon }: StableLabelProps) { + return ( + <> + {icon} + + {labels.map((label) => ( + + {label} + + ))} + + + ); +} diff --git a/web/src/features/authFiles/components/AuthFileDetailsSheet.tsx b/web/src/features/authFiles/components/AuthFileDetailsSheet.tsx index ac1d1ad166d..ba9347e809b 100644 --- a/web/src/features/authFiles/components/AuthFileDetailsSheet.tsx +++ b/web/src/features/authFiles/components/AuthFileDetailsSheet.tsx @@ -6,6 +6,7 @@ import { Button } from '@/components/ui/Button'; import { LoadingSpinner } from '@/components/ui/LoadingSpinner'; import { Input } from '@/components/ui/Input'; import { ToggleSwitch } from '@/components/ui/ToggleSwitch'; +import { StableLabel } from '@/components/ui/StableLabel'; import { useNotificationStore } from '@/stores'; import type { PrefixProxyEditorField, @@ -135,7 +136,10 @@ export function AuthFileDetailsSheet(props: AuthFileDetailsSheetProps) { onClick={handleCancelClick} disabled={editor?.saving === true} > - {dirty ? t('common.cancel') : t('common.close')} + {resetQuotaAction}
diff --git a/web/src/features/authFiles/components/SelectionBar.tsx b/web/src/features/authFiles/components/SelectionBar.tsx index 80ae391fa06..7d06bf63517 100644 --- a/web/src/features/authFiles/components/SelectionBar.tsx +++ b/web/src/features/authFiles/components/SelectionBar.tsx @@ -1,7 +1,11 @@ import { createPortal } from 'react-dom'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/Button'; -import { DropdownMenu, DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/DropdownMenu'; +import { + DropdownMenu, + DropdownMenuItem, + DropdownMenuSeparator, +} from '@/components/ui/DropdownMenu'; import { IconChevronDown } from '@/components/ui/icons'; import styles from './SelectionBar.module.scss'; diff --git a/web/src/features/config/components/ConfigSourceEditor.tsx b/web/src/features/config/components/ConfigSourceEditor.tsx index 8f85edf5235..2781dcbc3b5 100644 --- a/web/src/features/config/components/ConfigSourceEditor.tsx +++ b/web/src/features/config/components/ConfigSourceEditor.tsx @@ -1,4 +1,4 @@ -import { useMemo, type Ref } from 'react'; +import { useEffect, useMemo, useRef, useState, type Ref } from 'react'; import CodeMirror, { type ReactCodeMirrorRef } from '@uiw/react-codemirror'; import { yaml } from '@codemirror/lang-yaml'; import { search, searchKeymap, highlightSelectionMatches } from '@codemirror/search'; @@ -25,6 +25,17 @@ export default function ConfigSourceEditor({ () => [yaml(), search(), highlightSelectionMatches(), keymap.of(searchKeymap)], [] ); + // CodeMirror's first frame places lines from an estimated line height and + // corrects them once it has measured; show it only after that correction so + // the line numbers never jump. + const [measured, setMeasured] = useState(false); + const frameRef = useRef(0); + useEffect(() => () => cancelAnimationFrame(frameRef.current), []); + const handleCreateEditor = () => { + frameRef.current = requestAnimationFrame(() => { + frameRef.current = requestAnimationFrame(() => setMeasured(true)); + }); + }; return (
) : keys.length === 0 ? ( diff --git a/web/src/features/connect/components/CodeBlock.tsx b/web/src/features/connect/components/CodeBlock.tsx index 08809fc5c92..05bb7d91916 100644 --- a/web/src/features/connect/components/CodeBlock.tsx +++ b/web/src/features/connect/components/CodeBlock.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/Button'; import { IconCheck, IconCopy } from '@/components/ui/icons'; +import { StableLabel } from '@/components/ui/StableLabel'; import { useNotificationStore } from '@/stores'; import { copyToClipboard } from '@/utils/clipboard'; import styles from './CodeBlock.module.scss'; @@ -53,7 +54,10 @@ export function CodeBlock({ code, copyText, label, path = false, copyLabel }: Co
diff --git a/web/src/features/dashboard/DashboardPage.tsx b/web/src/features/dashboard/DashboardPage.tsx index 8663c89db46..cce4c655dc7 100644 --- a/web/src/features/dashboard/DashboardPage.tsx +++ b/web/src/features/dashboard/DashboardPage.tsx @@ -27,7 +27,6 @@ export function DashboardPage() { const { connected, loading, error, counts, traffic, providers, credentials, refresh } = useDashboardOverview(); - const windowLabel = (() => { if (traffic.windowMinutes <= 0) return ''; const { hours, minutes } = splitWindowMinutes(traffic.windowMinutes); diff --git a/web/src/features/logs/LogsPage.tsx b/web/src/features/logs/LogsPage.tsx index 81d4f161926..97cfc8c0178 100644 --- a/web/src/features/logs/LogsPage.tsx +++ b/web/src/features/logs/LogsPage.tsx @@ -47,6 +47,7 @@ import { filterLogEntries, } from '@/features/logs/model/logSelectors'; import { Select } from '@/components/ui/Select'; +import { StableLabel } from '@/components/ui/StableLabel'; import { formatUnixTimestamp } from '@/utils/format'; import { MANAGEMENT_API_PREFIX } from '@/utils/constants'; import { HTTP_METHODS, STATUS_GROUPS, type LogState } from './model/logTypes'; @@ -155,7 +156,6 @@ export function LogsPage() { } }; - const downloadErrorLog = async (name: string) => { const session = requests.session.capture(); try { @@ -496,7 +496,10 @@ export function LogsPage() { onClick={() => setAutoRefresh(!autoRefresh)} disabled={autoRefreshDisabled} > - {autoRefresh ? t('logs.pause') : t('logs.resume')} + { void loadAll(); }, [loadAll]); diff --git a/web/src/features/quota/QuotaPage.tsx b/web/src/features/quota/QuotaPage.tsx index 3c0402dffe5..6c69c736b45 100644 --- a/web/src/features/quota/QuotaPage.tsx +++ b/web/src/features/quota/QuotaPage.tsx @@ -32,6 +32,7 @@ import { SegmentedControl, Tabs } from '@/components/ui/Tabs'; import { Toolbar } from '@/components/ui/Toolbar'; import { Select } from '@/components/ui/Select'; import { Skeleton } from '@/components/ui/Skeleton'; +import { StableLabel } from '@/components/ui/StableLabel'; import { useNow } from '@/hooks/useNow'; import { useAuthStore, useNotificationStore, useQuotaStore, useThemeStore } from '@/stores'; import type { AuthFileItem, ResolvedTheme } from '@/types'; @@ -789,18 +790,19 @@ export function QuotaPage() { rememberLayout('quota.views', showViews); }, [error, filterTypes.length, firstLoad, showViews]); - const viewSwitch = showViews || (firstLoad && lastLayout.views) ? ( - - ) : null; + const viewSwitch = + showViews || (firstLoad && lastLayout.views) ? ( + + ) : null; const providerTabs = filterTypes.length > 1 || (firstLoad && lastLayout.tabs) ? ( +
diff --git a/web/src/features/quota/components/PoolAccountsTable.module.scss b/web/src/features/quota/components/PoolAccountsTable.module.scss index 8d037d7068e..416b0a469a1 100644 --- a/web/src/features/quota/components/PoolAccountsTable.module.scss +++ b/web/src/features/quota/components/PoolAccountsTable.module.scss @@ -2,12 +2,45 @@ /* Accounts table under a pool. Meters are neutral; status shows as text too. */ +// Fixed layout: column widths come from the header, never from cell text, so a +// live countdown or a credit count arriving cannot re-balance the columns. .table { min-width: 720px; + table-layout: fixed; td { white-space: nowrap; } + + // Data cells clip at their column; the expanded detail row spans the table. + tr:not(.detailRow) > td { + overflow: hidden; + text-overflow: ellipsis; + } +} + +.colAccount { + width: 220px; +} + +.colPlan { + width: 96px; +} + +.colWeight { + width: 84px; +} + +.colWindow { + width: 132px; +} + +.colReset { + width: 168px; +} + +.colCredits { + width: 176px; } .accountCell { diff --git a/web/src/features/quota/components/PoolAccountsTable.tsx b/web/src/features/quota/components/PoolAccountsTable.tsx index 96bf1f887b4..3dae2125000 100644 --- a/web/src/features/quota/components/PoolAccountsTable.tsx +++ b/web/src/features/quota/components/PoolAccountsTable.tsx @@ -216,14 +216,18 @@ export function PoolAccountsTable({ > - {t('quota_accounts.col_account')} - {t('quota_accounts.col_plan')} - + {t('quota_accounts.col_account')} + {t('quota_accounts.col_plan')} + {t('quota_accounts.col_weight')} {generic ? ( windowColumns.map((column) => ( - + {column.group && column.period ? ( {column.group} @@ -236,13 +240,17 @@ export function PoolAccountsTable({ )) ) : ( <> - {labels.fiveHour} - {labels.weekly} + {labels.fiveHour} + {labels.weekly} )} - {!generic && showScoped && {labels.scoped}} - {resetLabel} - {showCredits && {t('quota_accounts.col_banked')}} + {!generic && showScoped && ( + {labels.scoped} + )} + {resetLabel} + {showCredits && ( + {t('quota_accounts.col_banked')} + )} diff --git a/web/src/features/quota/components/QuotaPoolToolbar.module.scss b/web/src/features/quota/components/QuotaPoolToolbar.module.scss index d77d4b94170..600ada122b9 100644 --- a/web/src/features/quota/components/QuotaPoolToolbar.module.scss +++ b/web/src/features/quota/components/QuotaPoolToolbar.module.scss @@ -1,9 +1,23 @@ +@use '../../../styles/mixins' as *; + .triggerInner { display: inline-flex; align-items: center; gap: 6px; } +.todayIdle { + visibility: hidden; +} + +// Phones get the icon alone, so the span controls, Today and the options fit +// one row in every state. +@include mobile { + .triggerLabel { + display: none; + } +} + .menuLabel { padding: 6px 8px 2px; color: var(--muted-foreground); diff --git a/web/src/features/quota/components/QuotaPoolToolbar.tsx b/web/src/features/quota/components/QuotaPoolToolbar.tsx index f579eb5e849..c9d42c2a1aa 100644 --- a/web/src/features/quota/components/QuotaPoolToolbar.tsx +++ b/web/src/features/quota/components/QuotaPoolToolbar.tsx @@ -65,10 +65,10 @@ export function QuotaPoolToolbar(props: QuotaPoolToolbarProps) { ariaLabel={t('quota_pool.chart_options')} minWidth={220} trigger={ - } diff --git a/web/src/features/quota/components/SpanNav.tsx b/web/src/features/quota/components/SpanNav.tsx index 61fd34c47e2..c30175c64c3 100644 --- a/web/src/features/quota/components/SpanNav.tsx +++ b/web/src/features/quota/components/SpanNav.tsx @@ -40,11 +40,19 @@ export function SpanNav({ spanStart, spanEnd, isToday, onShift, onToday, locale icon={} onClick={() => onShift(1)} /> - {!isToday && ( - - )} + {/* Always laid out (hidden on today's span), so stepping away from today never + widens the toolbar and wraps the controls beside it. */} +
); } diff --git a/web/src/pages/AuthFilesOAuthExcludedEditPage.tsx b/web/src/pages/AuthFilesOAuthExcludedEditPage.tsx index 2f288b8ec16..86aa68dd45d 100644 --- a/web/src/pages/AuthFilesOAuthExcludedEditPage.tsx +++ b/web/src/pages/AuthFilesOAuthExcludedEditPage.tsx @@ -246,6 +246,7 @@ export function AuthFilesOAuthExcludedEditPage() { onRetryCatalog={() => retryCatalog(selected)} disabled={disabled} labelledBy={pickerLabelId} + layoutKey={`oauth-excluded.${selected}`} /> diff --git a/web/src/pages/login/LoginForm.tsx b/web/src/pages/login/LoginForm.tsx index 51b3dd5853e..8c4a84573b6 100644 --- a/web/src/pages/login/LoginForm.tsx +++ b/web/src/pages/login/LoginForm.tsx @@ -2,6 +2,7 @@ import { useId, useRef, type FormEvent } from 'react'; import { useTranslation } from 'react-i18next'; import { SelectionCheckbox } from '@/components/ui/SelectionCheckbox'; import { IconAlertTriangle, IconCheck, IconEye, IconEyeOff } from '@/components/ui/icons'; +import { StableLabel } from '@/components/ui/StableLabel'; import styles from './LoginForm.module.scss'; export interface LoginFormProps { @@ -73,7 +74,10 @@ export function LoginForm({ if (!next) keyInputRef.current?.focus(); }} > - {editingBase ? t('login.connection_done') : t('login.connection_edit')} + {editingBase ? ( diff --git a/web/src/styles/components.scss b/web/src/styles/components.scss index 62e0df342ba..20c20e274bc 100644 --- a/web/src/styles/components.scss +++ b/web/src/styles/components.scss @@ -320,6 +320,21 @@ textarea { font-variant-numeric: tabular-nums; } +/* ---------------------------------------------------------- StableLabel */ + +// Alternatives share one grid cell; the widest sets the width (see StableLabel). +.stable-label { + display: inline-grid; + + > * { + grid-area: 1 / 1; + } +} + +.stable-label-ghost { + visibility: hidden; +} + /* --------------------------------------------------------------- Spinner */ .loading-spinner {