919a39e49a
* feat(auth): add auth core — identities, sessions, PATs, invites, mode state machine Phase 1 of opt-in authentication + multi-user segregation: - internal/auth: argon2id password hashing (PHC), opaque session/PAT tokens (SHA-256 at rest), login rate limiter, auth-mode state machine (disabled/setup/enabled), setup-wizard promotion of the pre-auth default-user row into the admin account, invites, admin user management with last-admin guard. - internal/auth/store: auth_identities (OIDC-ready), auth_sessions, auth_api_tokens, auth_invites tables (SQLite+Postgres dialects). - internal/auth/authn: request-identity plumbing (gin + plain contexts), RequireAdmin middleware. - users table: display_name/role/status columns via new MigrateLogger wiring; AccountRepository surface (consumer-scoped, keeps existing Repository fakes untouched). - config: AuthConfig.Required/SessionTTLHours/CookieName (KANDEV_AUTH_REQUIRED), FeaturesConfig.Auth; profiles.yaml + runtime flag registry entry for KANDEV_FEATURES_AUTH. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): enforce opt-in auth over HTTP — middleware, auth API, boot payload Phase 2 of opt-in authentication + multi-user segregation: - internal/auth/httpmw: global gin middleware after CORS. Disabled mode injects the synthetic single-user admin identity (behavior unchanged); enabled mode resolves session cookie then PAT bearer, with an explicit allowlist (health, SPA bootstrap reads, credential endpoints, self-authenticating webhooks), deferral for WS/proxy upgrades and office agent JWTs, and SPA shell availability for the login page. - internal/auth/httpapi: full auth surface — setup wizard, login/logout, me, password change, sessions, PATs, invites (mint/preview/accept), auth settings (enable/disable), admin user management. - Boot payload: initialState.auth block always present; unauthenticated visitors on auth-enabled instances get features+auth only (no data). - External MCP: PAT required once auth is enabled (open while disabled). - Admin guards on destructive system routes and runtime-flag overrides. - Startup warning when bound non-loopback with auth disabled (ServerConfig.NonLoopbackBinds fail-closed nudge). - Wiring: auth store in Repositories, auth service in Services, ClaimUnownedWorkspaces backfill on the task repository. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): per-user workspace scoping across HTTP services Phase 3 of opt-in authentication + multi-user segregation: - Task service: workspaces, workflows, repositories, and tasks are scoped to the request identity (owner-only visibility; pre-auth unowned rows stay shared). Denials use *NotFound sentinels - no existence leak. Internal callers and the disabled-mode synthetic identity remain unscoped, preserving behavior exactly when auth is off. - CreateWorkspace stamps the authenticated caller as owner. - Session chokepoint: lifecycle Manager.GetOrEnsureExecution runs a settable session-access check covering shell/files/ports/vscode/LSP. - Secrets: per-user user_id column, scoped CRUD/list, ClaimUnowned wired into the setup-wizard backfills. - Boot payload inherits scoping automatically. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): scope WebSocket gateway to authenticated users Phase 4 of opt-in authentication + multi-user segregation: - Connection auth: /ws, /terminal, /lsp, /vscode, /port-proxy routes are guarded when auth is enabled - session cookie (same-origin upgrade), resolved identity from the HTTP middleware, or ?token=<PAT> for headerless programmatic clients; JSON 401 before any upgrade. - Client identity: every WS client carries its authn.Identity; dispatched RPC actions (workspace.list, task CRUD, ...) run under a context carrying it, so WS RPC gets the same per-user scoping as HTTP. - Subscription checks: task/session subscribe+focus verify workspace visibility via the task service; user topic subscriptions are pinned to the client's own user. - Broadcast routing: new Hub.BroadcastToWorkspace routes workspace-scoped events (task/workflow/repo/office/session-state) to the owner's clients only, with safe fallbacks (unowned/unresolvable -> broadcast) so events never vanish; instance-wide events (executors, environments, agent profiles, system jobs) stay global by design. - Replaced the long-standing discarded-token TODO in HandleConnection. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): add feature spec and backend architecture notes for opt-in auth - docs/specs/auth/spec.md: product behavior (opt-in, setup wizard, per-user workspaces, sessions/PATs, invites, public surface, v1 limits) - apps/backend/AGENTS.md: internal/auth package layout + scoping rules for new service entry points and WS broadcast call sites Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): public documentation for opt-in authentication - New docs/public/authentication.md: enabling, users & invites, PATs, public endpoints, limitations, disabling - run-as-a-service.md: network-security note now points at the real authentication boundary instead of reverse-proxy-only guidance - meta.json: nav entry under Configure Kandev Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): ADR for opt-in authentication architecture Records the load-bearing choices: mode state machine + synthetic identity in disabled mode, opaque DB-backed credentials over JWTs, default-user promotion at setup, service-layer scoping with no-admin-bypass, and the explicit public allowlist. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): auth UI — login, setup wizard, invites, users & account settings Adds the frontend half of opt-in authentication: a pre-auth gate in main.tsx that renders the setup wizard or login/invite pages instead of the app shell whenever the boot payload's auth block says so, a new `auth` store slice + feature flag mirroring the backend's StatePayload, credentialed fetch (`credentials: "include"`) with a 401 handler that clears the session and redirects to /login, and a full auth-api.ts client for the /api/v1/auth and /api/v1/users routes. Settings additions: a System > Users page (list/create/disable/promote users, invite-link dialog) and System > Authentication page (enable/ disable with confirm + env-locked banner), gated on the `auth` feature flag and admin role. A new Account sidebar group (Profile & Password, API Tokens) is shown to signed-in users once auth is enabled. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(auth): E2E lifecycle suite + fix workspace event WS leak it caught New dedicated Playwright auth project (backend restarts with KANDEV_AUTH_REQUIRED=true, isolated from the tokenless default suite): setup-mode boot gating, admin setup wizard, login/logout + bad credentials, PATs, admin-surface authorization, anonymous WS rejection, UI login flow, and the acceptance test - two-user segregation across HTTP, boot payload, and WebSocket. The segregation spec immediately caught a real leak: workspace.* event payloads carry their ID as 'id' (the payload IS the workspace DTO), not 'workspace_id', so BroadcastToWorkspace fell back to broadcast-to-all for workspace create/update/delete. Fixed with action-aware extraction plus a unit regression test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): close cross-user access gaps found in security audit Two independent security audits of the auth branch found several authorization gaps where session/workspace-scoped surfaces were not wired to the new per-user chokepoint. All fixed: - IDOR on reverse-proxy/terminal routes (vscode, port-proxy, terminal): these resolve executions via GetExecutionBySessionID / GetOrEnsureExecutionForEnvironment / EnsurePassthroughExecution, which skipped the session-access check that only GetOrEnsureExecution ran. Added the check inside the env/passthrough resolvers (before the cache short-circuit) and an explicit CheckSessionAccess gate in the two bare-lookup proxy handlers. An authenticated non-owner can no longer reach another user's IDE, forwarded ports, or shell. - Cross-user agent-conversation read: ListMessages / ListMessagesPaginated / SearchMessages now authorize the session. - Cross-user repository-script read/inject: script CRUD now authorizes the parent repository's workspace. - Office HTTP surface: a group middleware enforces workspace ownership on :wsId routes for real users (agent-JWT callers keep their claim scoping). - Login rate-limit bypass: SetTrustedProxies(nil) so a spoofed X-Forwarded-For can't rotate the limiter key on a directly-reachable backend. - Invite double-provisioning race: MarkInviteUsed is now the atomic serialization point (consumed before user creation). - Setup wizard: serialized with a mutex so concurrent first-visitors can't corrupt the promoted admin profile. - Log sanitizer: explicit kandev_pat_ redaction rule. Regression tests added for message/script scoping and the execution-access-before-cache invariant. Auth E2E (incl. two-user segregation) still green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): scope repository active-session-count endpoint GET /api/v1/repositories/:id/active-session-count went through CountActiveSessionsByRepository, which was not identity-scoped - a cross-user info leak of another owner's active session counts. Added the same authorizeRepositoryID gate the script routes use. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): add json tags to auth store models — omit digests, fix token UI The auth store structs (APIToken, Invite, LoginIdentity, Session) had db: tags but no json: tags, so the handlers that serialize them directly sent Go-cased keys (CreatedAt, Name) AND leaked the SHA-256/password digests to clients. Two consequences: - The API-tokens UI showed 'Invalid Date' and an empty name (frontend reads created_at/name). - token_sha256 / password_hash were serialized in list responses. Added json tags with snake_case keys the frontend reads and json:"-" on every credential digest. Regression test asserts digests never serialize and the snake_case timestamp/name keys are present. Also adds the auth-screenshots capture spec (artifacts gitignored). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): move auth enable into feature toggles; show current user in sidebar Remove the standalone Authentication settings page and its dedicated settings/get-auth-settings API surface now that enabling auth lives in the Feature Toggles system, and drop env_required now that /auth/me no longer returns it. Add a current-user chip with a logout action to the sidebar footer, shown only in enabled auth mode. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(auth): make features.auth the single on/off control Per review feedback: authentication configuration now lives entirely in the existing Feature Toggles system rather than a separate Authentication settings section. - The auth mode is derived from the features.auth runtime flag (KANDEV_FEATURES_AUTH): off -> disabled, on+no-admin -> setup, on+admin -> enabled. Removed the parallel auth.mode system setting, the SetEnabled service method, GET/PATCH /api/v1/auth/settings, the AuthConfig.Required field, KANDEV_AUTH_REQUIRED, and the auth service's Settings-store dependency and EnvRequired/env_required. - The features.auth registry entry is re-described as the actual enable switch (high-risk, restart-required) and defaults off in every profile (dev was previously true — that only revealed UI before; now it would enforce, so it must be an explicit opt-in). - Setup no longer persists a mode; completing the wizard creates the admin and the mode auto-derives to enabled. - Startup 'exposed without auth' warning + all docs (public guide, run-as-a-service, spec, ADR, AGENTS.md) point at the feature toggle. - E2E: auth specs use KANDEV_FEATURES_AUTH; screenshot spec captures the Feature Toggles page instead of the removed Authentication page; the member-restriction assertion targets an admin invite route. - Tests updated across service/httpmw/httpapi/profiles for the derived mode; full suite green (only pre-existing sandbox-FS failures remain). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): complete cross-user isolation — integrations, automation, plan/walkthrough, session reads A follow-up isolation audit found that per-user scoping had been wired into the task service, secrets, office, and the WS gateway — but several workspace/task/session-scoped surfaces still resolved a caller-supplied ID with no ownership gate. Closed all of them; cross-user access now returns 404 across the board. - Integrations (jira/linear/sentry/slack/azure-devops/gitlab/github/ workflow-sync): a global middleware authorizes the workspace_id (query, or gitlab's /workspaces/:id/ path) on those route groups. Previously a member who knew another user's workspace ID could read/overwrite their integration connection config and watches. - Automation: workspace-authorizer seam gates get/list/create/update/delete/ enable/disable, triggers, run history, and — critically — the webhook secret. Was fully cross-tenant over WS before. - Task plans (PlanService) and walkthroughs (WalkthroughService): task- authorizer seam on every read/write. These bypassed the task service. - Session reads that hit the repo directly — session turns, task context, git snapshots, file reviews — now call AuthorizeSession/TaskAccess. Internal callers (pollers, schedulers, MCP) carry no identity and stay unscoped; disabled mode is unaffected. Regression tests added (plan/walkthrough scoping, automation authorizer matrix, integration path extraction) and the two-user E2E now asserts integration routes are shielded. Docs (spec, ADR, public guide) updated to state what is isolated and that filesystem/agent-credential isolation remains an OS-level limitation. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): current-user chip uses border hover, not accent fill The sidebar current-user chip used hover:bg-accent (a purpleish fill). Switch to the border-hover idiom used elsewhere (border border-transparent -> hover:border-border) with the neutral hover:bg-muted/50 the adjacent workspace picker uses, so the hover reads as a subtle outline instead of a colored background. Screenshot spec now captures the chip hover state. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): right-align current-user chip in the sidebar footer Push the user chip to the far right of the expanded footer (ml-auto) so it sits opposite the left-aligned icon buttons; collapsed mode keeps the centered vertical stack unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): reject synthetic identity on management routes and scope office run broadcasts Address code-review findings on the opt-in authentication PR: - P1: while auth is disabled the middleware injects a synthetic admin (RoleAdmin), and RequireAdmin alone let it through — so anyone hitting a not-yet-enabled instance could mint a PAT or plant an admin that survives enablement and hijacks first-run setup. Add authn.RequireRealIdentity and guard the credential/session/user-management routes with it (public bootstrap routes stay reachable). Responds 404 while disabled. - P1: office run events carry task_id but no workspace_id, so they fell back to a global broadcast and leaked across users. Resolve the workspace from the task and route via the new Hub.BroadcastToWorkspaceOrDrop, which fails closed (drops rather than global-broadcasts) when the workspace is unknown and auth is enforced. - nit: type createAuthSlice as a single-arg creator and call it with just set. Also register the authentication docs page and its settings routes in docs/public/coverage.json so the public-docs validator passes. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
733 lines
28 KiB
Go
733 lines
28 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"github.com/kandev/kandev/internal/db"
|
|
"github.com/kandev/kandev/internal/db/dialect"
|
|
"github.com/kandev/kandev/internal/user/models"
|
|
)
|
|
|
|
const (
|
|
DefaultUserID = "default-user"
|
|
DefaultUserEmail = "default@kandev.local"
|
|
)
|
|
|
|
type sqliteRepository struct {
|
|
db *sqlx.DB // writer
|
|
ro *sqlx.DB // reader
|
|
ownsDB bool
|
|
}
|
|
|
|
var _ Repository = (*sqliteRepository)(nil)
|
|
|
|
func newSQLiteRepositoryWithDB(writer, reader *sqlx.DB) (*sqliteRepository, error) {
|
|
return newSQLiteRepository(writer, reader, false)
|
|
}
|
|
|
|
func newSQLiteRepository(writer, reader *sqlx.DB, ownsDB bool) (*sqliteRepository, error) {
|
|
repo := &sqliteRepository{db: writer, ro: reader, ownsDB: ownsDB}
|
|
if err := repo.initSchema(); err != nil {
|
|
if ownsDB {
|
|
if closeErr := writer.Close(); closeErr != nil {
|
|
return nil, fmt.Errorf("failed to close database after schema error: %w", closeErr)
|
|
}
|
|
}
|
|
return nil, fmt.Errorf("failed to initialize schema: %w", err)
|
|
}
|
|
return repo, nil
|
|
}
|
|
|
|
func (r *sqliteRepository) initSchema() error {
|
|
schema := `
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id TEXT PRIMARY KEY,
|
|
email TEXT NOT NULL,
|
|
display_name TEXT NOT NULL DEFAULT '',
|
|
role TEXT NOT NULL DEFAULT 'admin',
|
|
status TEXT NOT NULL DEFAULT 'active',
|
|
settings TEXT NOT NULL DEFAULT '{}',
|
|
created_at TIMESTAMP NOT NULL,
|
|
updated_at TIMESTAMP NOT NULL
|
|
);
|
|
`
|
|
if _, err := r.db.Exec(schema); err != nil {
|
|
return err
|
|
}
|
|
r.runMigrations()
|
|
|
|
return r.ensureDefaultUser()
|
|
}
|
|
|
|
// runMigrations evolves existing databases. CREATE TABLE IF NOT EXISTS is a
|
|
// no-op on a table that already exists, so every added column must also appear
|
|
// here as an idempotent ADD COLUMN (see apps/backend/CLAUDE.md, ADR 0027).
|
|
func (r *sqliteRepository) runMigrations() {
|
|
m := db.NewMigrateLogger(r.db, nil)
|
|
m.Apply("users.display_name", "ALTER TABLE users ADD COLUMN display_name TEXT NOT NULL DEFAULT ''")
|
|
// Default 'admin': the pre-auth singleton default-user becomes the admin
|
|
// when authentication is enabled. Explicit CreateUser calls always set role.
|
|
m.Apply("users.role", "ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'admin'")
|
|
m.Apply("users.status", "ALTER TABLE users ADD COLUMN status TEXT NOT NULL DEFAULT 'active'")
|
|
// Safe pre-auth: the table only ever held the single default-user row.
|
|
m.Apply("users.email_unique", "CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users(email)")
|
|
}
|
|
|
|
func (r *sqliteRepository) ensureDefaultUser() error {
|
|
ctx := context.Background()
|
|
var count int
|
|
if err := r.db.QueryRowContext(ctx, r.db.Rebind("SELECT COUNT(1) FROM users WHERE id = ?"), DefaultUserID).Scan(&count); err != nil {
|
|
return err
|
|
}
|
|
if count == 0 {
|
|
now := time.Now().UTC()
|
|
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
|
INSERT INTO users (id, email, display_name, role, status, settings, created_at, updated_at)
|
|
VALUES (?, ?, '', ?, ?, '{}', ?, ?)
|
|
`), DefaultUserID, DefaultUserEmail, models.RoleAdmin, models.StatusActive, now, now)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *sqliteRepository) Close() error {
|
|
if !r.ownsDB {
|
|
return nil
|
|
}
|
|
return r.db.Close()
|
|
}
|
|
|
|
const userColumns = "id, email, display_name, role, status, created_at, updated_at"
|
|
|
|
func (r *sqliteRepository) GetUser(ctx context.Context, id string) (*models.User, error) {
|
|
row := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
|
|
SELECT `+userColumns+`
|
|
FROM users WHERE id = ?
|
|
`), id)
|
|
return scanUser(row)
|
|
}
|
|
|
|
func (r *sqliteRepository) GetDefaultUser(ctx context.Context) (*models.User, error) {
|
|
return r.GetUser(ctx, DefaultUserID)
|
|
}
|
|
|
|
func (r *sqliteRepository) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
|
|
row := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
|
|
SELECT `+userColumns+`
|
|
FROM users WHERE email = ?
|
|
`), email)
|
|
return scanUser(row)
|
|
}
|
|
|
|
func (r *sqliteRepository) ListUsers(ctx context.Context) ([]*models.User, error) {
|
|
rows, err := r.ro.QueryContext(ctx, `
|
|
SELECT `+userColumns+`
|
|
FROM users ORDER BY created_at ASC, id ASC
|
|
`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = rows.Close() }()
|
|
users := []*models.User{}
|
|
for rows.Next() {
|
|
user, err := scanUser(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
users = append(users, user)
|
|
}
|
|
return users, rows.Err()
|
|
}
|
|
|
|
func (r *sqliteRepository) CreateUser(ctx context.Context, user *models.User) error {
|
|
now := time.Now().UTC()
|
|
user.CreatedAt = now
|
|
user.UpdatedAt = now
|
|
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
|
INSERT INTO users (id, email, display_name, role, status, settings, created_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?, '{}', ?, ?)
|
|
`), user.ID, user.Email, user.DisplayName, user.Role, user.Status, user.CreatedAt, user.UpdatedAt)
|
|
return err
|
|
}
|
|
|
|
// UpdateUserProfile sets identity-facing fields. Used by the setup wizard to
|
|
// promote the pre-auth default-user row into the admin account (preserving the
|
|
// row keeps all existing user settings intact) and by profile edits.
|
|
func (r *sqliteRepository) UpdateUserProfile(ctx context.Context, id, email, displayName, role string) (*models.User, error) {
|
|
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
|
UPDATE users SET email = ?, display_name = ?, role = ?, updated_at = ?
|
|
WHERE id = ?
|
|
`), email, displayName, role, time.Now().UTC(), id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := checkUserRowsAffected(result, id); err != nil {
|
|
return nil, err
|
|
}
|
|
return r.getUserFromWriter(ctx, id)
|
|
}
|
|
|
|
func (r *sqliteRepository) UpdateUserRoleStatus(ctx context.Context, id, role, status string) (*models.User, error) {
|
|
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
|
UPDATE users SET role = ?, status = ?, updated_at = ?
|
|
WHERE id = ?
|
|
`), role, status, time.Now().UTC(), id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := checkUserRowsAffected(result, id); err != nil {
|
|
return nil, err
|
|
}
|
|
return r.getUserFromWriter(ctx, id)
|
|
}
|
|
|
|
// getUserFromWriter reads through the writer connection so callers observe
|
|
// their own just-committed mutation (the reader pool may lag under WAL).
|
|
func (r *sqliteRepository) getUserFromWriter(ctx context.Context, id string) (*models.User, error) {
|
|
row := r.db.QueryRowContext(ctx, r.db.Rebind(`
|
|
SELECT `+userColumns+`
|
|
FROM users WHERE id = ?
|
|
`), id)
|
|
return scanUser(row)
|
|
}
|
|
|
|
func checkUserRowsAffected(result sqlResult, userID string) error {
|
|
rows, err := result.RowsAffected()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to check rows affected: %w", err)
|
|
}
|
|
if rows == 0 {
|
|
return fmt.Errorf("user not found: %s", userID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *sqliteRepository) GetUserSettings(ctx context.Context, userID string) (*models.UserSettings, error) {
|
|
return r.getUserSettings(ctx, r.ro, userID)
|
|
}
|
|
|
|
func (r *sqliteRepository) getUserSettings(ctx context.Context, conn *sqlx.DB, userID string) (*models.UserSettings, error) {
|
|
row := conn.QueryRowContext(ctx, conn.Rebind(`
|
|
SELECT settings, updated_at
|
|
FROM users WHERE id = ?
|
|
`), userID)
|
|
settings, err := scanUserSettings(row, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return settings, nil
|
|
}
|
|
|
|
func (r *sqliteRepository) UpsertUserSettingsPreservingTaskCreateLastUsed(
|
|
ctx context.Context,
|
|
settings *models.UserSettings,
|
|
patch *models.TaskCreateLastUsed,
|
|
) (*models.UserSettings, error) {
|
|
settings.UpdatedAt = time.Now().UTC()
|
|
if settings.CreatedAt.IsZero() {
|
|
settings.CreatedAt = settings.UpdatedAt
|
|
}
|
|
settingsPayload, err := marshalUserSettingsPayload(settings)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if dialect.IsPostgres(r.db.DriverName()) {
|
|
return r.upsertUserSettingsPreservingTaskCreateLastUsedPostgres(ctx, settings, settingsPayload, patch)
|
|
}
|
|
settingsExpr := `json_set(
|
|
json(?),
|
|
'$.task_create_last_used',
|
|
json(COALESCE(json_extract(
|
|
CASE WHEN settings IS NULL OR settings = 'null' OR settings = '' THEN '{}' ELSE settings END,
|
|
'$.task_create_last_used'
|
|
), '{}'))
|
|
)`
|
|
args := []any{string(settingsPayload)}
|
|
if patch != nil {
|
|
patchArgs := makeTaskCreateLastUsedJSONSetArgs(*patch)
|
|
if len(patchArgs) > 0 {
|
|
placeholders := strings.TrimSuffix(strings.Repeat("?, ?, ", len(patchArgs)/2), ", ")
|
|
settingsExpr = fmt.Sprintf("json_set(%s, %s)", settingsExpr, placeholders)
|
|
args = append(args, patchArgs...)
|
|
}
|
|
}
|
|
query := fmt.Sprintf(`
|
|
UPDATE users
|
|
SET settings = %s, updated_at = ?
|
|
WHERE id = ?
|
|
`, settingsExpr)
|
|
args = append(args, settings.UpdatedAt, settings.UserID)
|
|
result, err := r.db.ExecContext(ctx, r.db.Rebind(query), args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := checkUserSettingsRowsAffected(result, settings.UserID); err != nil {
|
|
return nil, err
|
|
}
|
|
return r.getUserSettings(ctx, r.db, settings.UserID)
|
|
}
|
|
|
|
func (r *sqliteRepository) upsertUserSettingsPreservingTaskCreateLastUsedPostgres(
|
|
ctx context.Context,
|
|
settings *models.UserSettings,
|
|
settingsPayload []byte,
|
|
patch *models.TaskCreateLastUsed,
|
|
) (*models.UserSettings, error) {
|
|
query, patchArgs := buildPostgresUserSettingsPreservingTaskCreateLastUsedUpdate(patch)
|
|
args := append([]any{string(settingsPayload)}, patchArgs...)
|
|
args = append(args, settings.UpdatedAt, settings.UserID)
|
|
result, err := r.db.ExecContext(ctx, r.db.Rebind(query), args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := checkUserSettingsRowsAffected(result, settings.UserID); err != nil {
|
|
return nil, err
|
|
}
|
|
return r.getUserSettings(ctx, r.db, settings.UserID)
|
|
}
|
|
|
|
func (r *sqliteRepository) UpdateTaskCreateLastUsed(ctx context.Context, userID string, patch models.TaskCreateLastUsed) (*models.UserSettings, error) {
|
|
if dialect.IsPostgres(r.db.DriverName()) {
|
|
return r.updateTaskCreateLastUsedPostgres(ctx, userID, patch)
|
|
}
|
|
patchArgs := makeTaskCreateLastUsedJSONSetArgs(patch)
|
|
if len(patchArgs) == 0 {
|
|
return r.getUserSettings(ctx, r.db, userID)
|
|
}
|
|
base := "CASE WHEN settings IS NULL OR settings = 'null' OR settings = '' THEN '{}' ELSE settings END"
|
|
settingsExpr := fmt.Sprintf(
|
|
"json_set(%s, '$.task_create_last_used', json(COALESCE(json_extract(%s, '$.task_create_last_used'), '{}')))",
|
|
base,
|
|
base,
|
|
)
|
|
placeholders := strings.TrimSuffix(strings.Repeat("?, ?, ", len(patchArgs)/2), ", ")
|
|
settingsExpr = fmt.Sprintf("json_set(%s, %s)", settingsExpr, placeholders)
|
|
query := `
|
|
UPDATE users
|
|
SET settings = %s, updated_at = ?
|
|
WHERE id = ?
|
|
`
|
|
now := time.Now().UTC()
|
|
args := append([]any{}, patchArgs...)
|
|
args = append(args, now, userID)
|
|
result, err := r.db.ExecContext(ctx, r.db.Rebind(fmt.Sprintf(query, settingsExpr)), args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := checkUserSettingsRowsAffected(result, userID); err != nil {
|
|
return nil, err
|
|
}
|
|
return r.getUserSettings(ctx, r.db, userID)
|
|
}
|
|
|
|
func (r *sqliteRepository) updateTaskCreateLastUsedPostgres(ctx context.Context, userID string, patch models.TaskCreateLastUsed) (*models.UserSettings, error) {
|
|
query, args := buildPostgresTaskCreateLastUsedUpdate(patch)
|
|
if len(args) == 0 {
|
|
return r.getUserSettings(ctx, r.db, userID)
|
|
}
|
|
now := time.Now().UTC()
|
|
args = append(args, now, userID)
|
|
result, err := r.db.ExecContext(ctx, r.db.Rebind(query), args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := checkUserSettingsRowsAffected(result, userID); err != nil {
|
|
return nil, err
|
|
}
|
|
return r.getUserSettings(ctx, r.db, userID)
|
|
}
|
|
|
|
func makeTaskCreateLastUsedJSONSetArgs(patch models.TaskCreateLastUsed) []any {
|
|
args := []any{}
|
|
if patch.RepositoryID != "" {
|
|
args = append(args, "$.task_create_last_used.repository_id", patch.RepositoryID)
|
|
}
|
|
if patch.Branch != "" || patch.RepositoryID != "" {
|
|
args = append(args, "$.task_create_last_used.branch", patch.Branch)
|
|
}
|
|
if patch.AgentProfileID != "" {
|
|
args = append(args, "$.task_create_last_used.agent_profile_id", patch.AgentProfileID)
|
|
}
|
|
if patch.ExecutorProfileID != "" {
|
|
args = append(args, "$.task_create_last_used.executor_profile_id", patch.ExecutorProfileID)
|
|
}
|
|
return args
|
|
}
|
|
|
|
func buildPostgresTaskCreateLastUsedUpdate(patch models.TaskCreateLastUsed) (string, []any) {
|
|
base := "(CASE WHEN settings IS NULL OR settings = 'null' OR settings = '' THEN '{}'::jsonb ELSE settings::jsonb END)"
|
|
expr := fmt.Sprintf("jsonb_set(%s, '{task_create_last_used}', COALESCE(%s->'task_create_last_used', '{}'::jsonb), true)", base, base)
|
|
args := []any{}
|
|
expr, args = applyPostgresTaskCreateLastUsedPatch(expr, patch, args)
|
|
query := fmt.Sprintf(`
|
|
UPDATE users
|
|
SET settings = %s::text, updated_at = ?
|
|
WHERE id = ?
|
|
`, expr)
|
|
return query, args
|
|
}
|
|
|
|
func buildPostgresUserSettingsPreservingTaskCreateLastUsedUpdate(patch *models.TaskCreateLastUsed) (string, []any) {
|
|
base := "(CASE WHEN settings IS NULL OR settings = 'null' OR settings = '' THEN '{}'::jsonb ELSE settings::jsonb END)"
|
|
expr := fmt.Sprintf("jsonb_set(?::jsonb, '{task_create_last_used}', COALESCE(%s->'task_create_last_used', '{}'::jsonb), true)", base)
|
|
args := []any{}
|
|
if patch != nil {
|
|
expr, args = applyPostgresTaskCreateLastUsedPatch(expr, *patch, args)
|
|
}
|
|
query := fmt.Sprintf(`
|
|
UPDATE users
|
|
SET settings = %s::text, updated_at = ?
|
|
WHERE id = ?
|
|
`, expr)
|
|
return query, args
|
|
}
|
|
|
|
func applyPostgresTaskCreateLastUsedPatch(expr string, patch models.TaskCreateLastUsed, args []any) (string, []any) {
|
|
if patch.RepositoryID != "" {
|
|
expr = fmt.Sprintf("jsonb_set(%s, '{task_create_last_used,repository_id}', to_jsonb(?::text), true)", expr)
|
|
args = append(args, patch.RepositoryID)
|
|
}
|
|
if patch.Branch != "" || patch.RepositoryID != "" {
|
|
expr = fmt.Sprintf("jsonb_set(%s, '{task_create_last_used,branch}', to_jsonb(?::text), true)", expr)
|
|
args = append(args, patch.Branch)
|
|
}
|
|
if patch.AgentProfileID != "" {
|
|
expr = fmt.Sprintf("jsonb_set(%s, '{task_create_last_used,agent_profile_id}', to_jsonb(?::text), true)", expr)
|
|
args = append(args, patch.AgentProfileID)
|
|
}
|
|
if patch.ExecutorProfileID != "" {
|
|
expr = fmt.Sprintf("jsonb_set(%s, '{task_create_last_used,executor_profile_id}', to_jsonb(?::text), true)", expr)
|
|
args = append(args, patch.ExecutorProfileID)
|
|
}
|
|
return expr, args
|
|
}
|
|
|
|
func marshalUserSettingsPayload(settings *models.UserSettings) ([]byte, error) {
|
|
lspAutoStart := settings.LspAutoStartLanguages
|
|
if lspAutoStart == nil {
|
|
lspAutoStart = []string{}
|
|
}
|
|
lspAutoInstall := settings.LspAutoInstallLanguages
|
|
if lspAutoInstall == nil {
|
|
lspAutoInstall = []string{}
|
|
}
|
|
lspServerConfigs := settings.LspServerConfigs
|
|
if lspServerConfigs == nil {
|
|
lspServerConfigs = map[string]map[string]interface{}{}
|
|
}
|
|
savedLayouts := settings.SavedLayouts
|
|
if savedLayouts == nil {
|
|
savedLayouts = []models.SavedLayout{}
|
|
}
|
|
sidebarViews := settings.SidebarViews
|
|
if sidebarViews == nil {
|
|
sidebarViews = []models.SidebarView{}
|
|
}
|
|
sidebarTaskPrefs := normalizeSidebarTaskPrefs(settings.SidebarTaskPrefs)
|
|
keyboardShortcuts := settings.KeyboardShortcuts
|
|
if keyboardShortcuts == nil {
|
|
keyboardShortcuts = map[string]interface{}{}
|
|
}
|
|
return json.Marshal(map[string]interface{}{
|
|
"workspace_id": settings.WorkspaceID,
|
|
"kanban_view_mode": settings.KanbanViewMode,
|
|
"workflow_filter_id": settings.WorkflowFilterID,
|
|
"repository_ids": settings.RepositoryIDs,
|
|
"tasks_list_sort": models.NormalizeTasksListSort(settings.TasksListSort),
|
|
"tasks_list_group": models.NormalizeTasksListGroup(settings.TasksListGroup),
|
|
"initial_setup_complete": settings.InitialSetupComplete,
|
|
"preferred_shell": settings.PreferredShell,
|
|
"default_editor_id": settings.DefaultEditorID,
|
|
"enable_preview_on_click": settings.EnablePreviewOnClick,
|
|
"chat_submit_key": settings.ChatSubmitKey,
|
|
"review_auto_mark_on_scroll": settings.ReviewAutoMarkOnScroll,
|
|
"confirm_task_archive": settings.ConfirmTaskArchive,
|
|
"mcp_task_agent_profile_default": models.NormalizeMCPTaskAgentProfileDefault(settings.MCPTaskAgentProfileDefault),
|
|
"show_release_notification": settings.ShowReleaseNotification,
|
|
"release_notes_last_seen_version": settings.ReleaseNotesLastSeenVersion,
|
|
"lsp_auto_start_languages": lspAutoStart,
|
|
"lsp_auto_install_languages": lspAutoInstall,
|
|
"lsp_server_configs": lspServerConfigs,
|
|
"saved_layouts": savedLayouts,
|
|
"sidebar_views": sidebarViews,
|
|
"sidebar_active_view_id": settings.SidebarActiveViewID,
|
|
"sidebar_draft": settings.SidebarDraft,
|
|
"sidebar_task_prefs": sidebarTaskPrefs,
|
|
"task_create_last_used": settings.TaskCreateLastUsed,
|
|
"jira_saved_views": settings.JiraSavedViews,
|
|
"jira_task_presets": settings.JiraTaskPresets,
|
|
"github_saved_presets": settings.GitHubSavedPresets,
|
|
"github_default_query_presets": settings.GitHubDefaultQueryPresets,
|
|
"gitlab_saved_presets": settings.GitLabSavedPresets,
|
|
"default_utility_agent_id": settings.DefaultUtilityAgentID,
|
|
"default_utility_model": settings.DefaultUtilityModel,
|
|
"keyboard_shortcuts": keyboardShortcuts,
|
|
"terminal_link_behavior": settings.TerminalLinkBehavior,
|
|
"terminal_font_family": settings.TerminalFontFamily,
|
|
"terminal_font_size": settings.TerminalFontSize,
|
|
"changes_panel_layout": settings.ChangesPanelLayout,
|
|
"system_metrics_display": settings.SystemMetricsDisplay,
|
|
"app_status_bar_order": normalizeAppStatusBarOrder(settings.AppStatusBarOrder),
|
|
"voice_mode": settings.VoiceMode,
|
|
})
|
|
}
|
|
|
|
func checkUserSettingsRowsAffected(result sqlResult, userID string) error {
|
|
rows, err := result.RowsAffected()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to check rows affected: %w", err)
|
|
}
|
|
if rows == 0 {
|
|
return fmt.Errorf("user not found: %s", userID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type sqlResult interface {
|
|
RowsAffected() (int64, error)
|
|
}
|
|
|
|
func scanUser(scanner interface{ Scan(dest ...any) error }) (*models.User, error) {
|
|
user := &models.User{}
|
|
if err := scanner.Scan(&user.ID, &user.Email, &user.DisplayName, &user.Role, &user.Status, &user.CreatedAt, &user.UpdatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
return user, nil
|
|
}
|
|
|
|
// defaultVoiceModeSettings returns the baseline VoiceMode configuration for
|
|
// users with no saved preferences. Mirrored on the frontend; keep in sync.
|
|
func defaultVoiceModeSettings() models.VoiceModeSettings {
|
|
return models.VoiceModeSettings{
|
|
Enabled: true,
|
|
Engine: "auto",
|
|
Language: "auto",
|
|
Mode: "toggle",
|
|
AutoSend: false,
|
|
WhisperWebModel: "base",
|
|
}
|
|
}
|
|
|
|
// storedVoiceMode is the on-disk JSON shape — uses *bool for `enabled` so we
|
|
// can distinguish "absent" (older rows written before the toggle existed —
|
|
// must default to true) from "explicitly false" (user disabled the feature).
|
|
type storedVoiceMode struct {
|
|
Enabled *bool `json:"enabled"`
|
|
Engine string `json:"engine"`
|
|
Language string `json:"language"`
|
|
Mode string `json:"mode"`
|
|
AutoSend bool `json:"auto_send"`
|
|
WhisperWebModel string `json:"whisper_web_model"`
|
|
}
|
|
|
|
// mergeVoiceModeDefaults fills in zero/missing fields on a stored VoiceMode
|
|
// payload so older user rows (written before VoiceMode existed) still produce
|
|
// usable settings instead of empty strings the frontend would reject.
|
|
func mergeVoiceModeDefaults(stored *storedVoiceMode) models.VoiceModeSettings {
|
|
out := defaultVoiceModeSettings()
|
|
if stored == nil {
|
|
return out
|
|
}
|
|
if stored.Enabled != nil {
|
|
out.Enabled = *stored.Enabled
|
|
}
|
|
if stored.Engine != "" {
|
|
out.Engine = stored.Engine
|
|
}
|
|
if stored.Language != "" {
|
|
out.Language = stored.Language
|
|
}
|
|
if stored.Mode != "" {
|
|
out.Mode = stored.Mode
|
|
}
|
|
if stored.WhisperWebModel != "" {
|
|
out.WhisperWebModel = stored.WhisperWebModel
|
|
}
|
|
out.AutoSend = stored.AutoSend
|
|
return out
|
|
}
|
|
|
|
func scanUserSettings(scanner interface{ Scan(dest ...any) error }, userID string) (*models.UserSettings, error) {
|
|
settings := &models.UserSettings{}
|
|
var settingsRaw string
|
|
if err := scanner.Scan(&settingsRaw, &settings.UpdatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
settings.UserID = userID
|
|
if settingsRaw == "" || settingsRaw == "{}" {
|
|
settings.RepositoryIDs = []string{}
|
|
settings.TasksListSort = models.TasksListSortDefault
|
|
settings.TasksListGroup = models.TasksListGroupDefault
|
|
settings.ShowReleaseNotification = true
|
|
settings.ReviewAutoMarkOnScroll = true
|
|
settings.ConfirmTaskArchive = true
|
|
settings.MCPTaskAgentProfileDefault = models.MCPTaskAgentProfileDefaultCurrentTask
|
|
settings.ChatSubmitKey = "cmd_enter"
|
|
settings.KeyboardShortcuts = map[string]interface{}{}
|
|
settings.TerminalLinkBehavior = "new_tab"
|
|
settings.ChangesPanelLayout = "tree"
|
|
settings.SidebarViews = []models.SidebarView{}
|
|
settings.SidebarTaskPrefs = normalizeSidebarTaskPrefs(models.SidebarTaskPrefs{})
|
|
settings.AppStatusBarOrder = normalizeAppStatusBarOrder(models.AppStatusBarOrder{})
|
|
settings.VoiceMode = defaultVoiceModeSettings()
|
|
return settings, nil
|
|
}
|
|
var payload struct {
|
|
WorkspaceID string `json:"workspace_id"`
|
|
KanbanViewMode string `json:"kanban_view_mode"`
|
|
WorkflowFilterID string `json:"workflow_filter_id"`
|
|
RepositoryIDs []string `json:"repository_ids"`
|
|
TasksListSort string `json:"tasks_list_sort"`
|
|
TasksListGroup string `json:"tasks_list_group"`
|
|
InitialSetupComplete bool `json:"initial_setup_complete"`
|
|
PreferredShell string `json:"preferred_shell"`
|
|
DefaultEditorID string `json:"default_editor_id"`
|
|
EnablePreviewOnClick bool `json:"enable_preview_on_click"`
|
|
ChatSubmitKey string `json:"chat_submit_key"`
|
|
ReviewAutoMarkOnScroll *bool `json:"review_auto_mark_on_scroll"`
|
|
ConfirmTaskArchive *bool `json:"confirm_task_archive"`
|
|
MCPTaskAgentProfileDefault string `json:"mcp_task_agent_profile_default"`
|
|
ShowReleaseNotification *bool `json:"show_release_notification"`
|
|
ReleaseNotesLastSeenVersion string `json:"release_notes_last_seen_version"`
|
|
LspAutoStartLanguages []string `json:"lsp_auto_start_languages"`
|
|
LspAutoInstallLanguages []string `json:"lsp_auto_install_languages"`
|
|
LspServerConfigs map[string]map[string]interface{} `json:"lsp_server_configs"`
|
|
SavedLayouts []models.SavedLayout `json:"saved_layouts"`
|
|
SidebarViews []models.SidebarView `json:"sidebar_views"`
|
|
SidebarActiveViewID string `json:"sidebar_active_view_id"`
|
|
SidebarDraft *models.SidebarViewDraft `json:"sidebar_draft"`
|
|
SidebarTaskPrefs models.SidebarTaskPrefs `json:"sidebar_task_prefs"`
|
|
TaskCreateLastUsed models.TaskCreateLastUsed `json:"task_create_last_used"`
|
|
JiraSavedViews json.RawMessage `json:"jira_saved_views"`
|
|
JiraTaskPresets json.RawMessage `json:"jira_task_presets"`
|
|
GitHubSavedPresets json.RawMessage `json:"github_saved_presets"`
|
|
GitHubDefaultQueryPresets json.RawMessage `json:"github_default_query_presets"`
|
|
GitLabSavedPresets json.RawMessage `json:"gitlab_saved_presets"`
|
|
DefaultUtilityAgentID string `json:"default_utility_agent_id"`
|
|
DefaultUtilityModel string `json:"default_utility_model"`
|
|
KeyboardShortcuts map[string]interface{} `json:"keyboard_shortcuts"`
|
|
TerminalLinkBehavior string `json:"terminal_link_behavior"`
|
|
TerminalFontFamily string `json:"terminal_font_family"`
|
|
TerminalFontSize int `json:"terminal_font_size"`
|
|
ChangesPanelLayout string `json:"changes_panel_layout"`
|
|
SystemMetricsDisplay models.SystemMetricsDisplaySettings `json:"system_metrics_display"`
|
|
AppStatusBarOrder models.AppStatusBarOrder `json:"app_status_bar_order"`
|
|
VoiceMode *storedVoiceMode `json:"voice_mode"`
|
|
}
|
|
if err := json.Unmarshal([]byte(settingsRaw), &payload); err != nil {
|
|
return nil, err
|
|
}
|
|
settings.WorkspaceID = payload.WorkspaceID
|
|
settings.KanbanViewMode = payload.KanbanViewMode
|
|
settings.WorkflowFilterID = payload.WorkflowFilterID
|
|
settings.RepositoryIDs = payload.RepositoryIDs
|
|
settings.TasksListSort = models.NormalizeTasksListSort(payload.TasksListSort)
|
|
settings.TasksListGroup = models.NormalizeTasksListGroup(payload.TasksListGroup)
|
|
settings.InitialSetupComplete = payload.InitialSetupComplete
|
|
settings.PreferredShell = payload.PreferredShell
|
|
settings.DefaultEditorID = payload.DefaultEditorID
|
|
settings.EnablePreviewOnClick = payload.EnablePreviewOnClick
|
|
settings.ChatSubmitKey = payload.ChatSubmitKey
|
|
// Default to "cmd_enter" if empty
|
|
if settings.ChatSubmitKey == "" {
|
|
settings.ChatSubmitKey = "cmd_enter"
|
|
}
|
|
// Default to true when not set
|
|
if payload.ReviewAutoMarkOnScroll != nil {
|
|
settings.ReviewAutoMarkOnScroll = *payload.ReviewAutoMarkOnScroll
|
|
} else {
|
|
settings.ReviewAutoMarkOnScroll = true
|
|
}
|
|
if payload.ConfirmTaskArchive != nil {
|
|
settings.ConfirmTaskArchive = *payload.ConfirmTaskArchive
|
|
} else {
|
|
settings.ConfirmTaskArchive = true
|
|
}
|
|
settings.MCPTaskAgentProfileDefault = models.NormalizeMCPTaskAgentProfileDefault(payload.MCPTaskAgentProfileDefault)
|
|
if payload.ShowReleaseNotification != nil {
|
|
settings.ShowReleaseNotification = *payload.ShowReleaseNotification
|
|
} else {
|
|
settings.ShowReleaseNotification = true
|
|
}
|
|
settings.ReleaseNotesLastSeenVersion = payload.ReleaseNotesLastSeenVersion
|
|
settings.LspAutoStartLanguages = payload.LspAutoStartLanguages
|
|
if settings.LspAutoStartLanguages == nil {
|
|
settings.LspAutoStartLanguages = []string{}
|
|
}
|
|
settings.LspAutoInstallLanguages = payload.LspAutoInstallLanguages
|
|
if settings.LspAutoInstallLanguages == nil {
|
|
settings.LspAutoInstallLanguages = []string{}
|
|
}
|
|
settings.LspServerConfigs = payload.LspServerConfigs
|
|
settings.SavedLayouts = payload.SavedLayouts
|
|
if settings.SavedLayouts == nil {
|
|
settings.SavedLayouts = []models.SavedLayout{}
|
|
}
|
|
settings.SidebarViews = payload.SidebarViews
|
|
if settings.SidebarViews == nil {
|
|
settings.SidebarViews = []models.SidebarView{}
|
|
}
|
|
settings.SidebarActiveViewID = payload.SidebarActiveViewID
|
|
settings.SidebarDraft = payload.SidebarDraft
|
|
settings.SidebarTaskPrefs = normalizeSidebarTaskPrefs(payload.SidebarTaskPrefs)
|
|
settings.TaskCreateLastUsed = payload.TaskCreateLastUsed
|
|
settings.JiraSavedViews = payload.JiraSavedViews
|
|
settings.JiraTaskPresets = payload.JiraTaskPresets
|
|
settings.GitHubSavedPresets = payload.GitHubSavedPresets
|
|
settings.GitHubDefaultQueryPresets = payload.GitHubDefaultQueryPresets
|
|
settings.GitLabSavedPresets = payload.GitLabSavedPresets
|
|
settings.DefaultUtilityAgentID = payload.DefaultUtilityAgentID
|
|
settings.DefaultUtilityModel = payload.DefaultUtilityModel
|
|
settings.KeyboardShortcuts = payload.KeyboardShortcuts
|
|
if settings.KeyboardShortcuts == nil {
|
|
settings.KeyboardShortcuts = map[string]interface{}{}
|
|
}
|
|
if payload.TerminalLinkBehavior != "" {
|
|
settings.TerminalLinkBehavior = payload.TerminalLinkBehavior
|
|
} else {
|
|
settings.TerminalLinkBehavior = "new_tab"
|
|
}
|
|
settings.TerminalFontFamily = payload.TerminalFontFamily
|
|
settings.TerminalFontSize = payload.TerminalFontSize
|
|
settings.VoiceMode = mergeVoiceModeDefaults(payload.VoiceMode)
|
|
settings.SystemMetricsDisplay = payload.SystemMetricsDisplay
|
|
settings.AppStatusBarOrder = normalizeAppStatusBarOrder(payload.AppStatusBarOrder)
|
|
if payload.ChangesPanelLayout == "flat" {
|
|
settings.ChangesPanelLayout = "flat"
|
|
} else {
|
|
settings.ChangesPanelLayout = "tree"
|
|
}
|
|
return settings, nil
|
|
}
|
|
|
|
func normalizeSidebarTaskPrefs(prefs models.SidebarTaskPrefs) models.SidebarTaskPrefs {
|
|
if prefs.PinnedTaskIDs == nil {
|
|
prefs.PinnedTaskIDs = []string{}
|
|
}
|
|
if prefs.OrderedTaskIDs == nil {
|
|
prefs.OrderedTaskIDs = []string{}
|
|
}
|
|
if prefs.SubtaskOrderByParentID == nil {
|
|
prefs.SubtaskOrderByParentID = map[string][]string{}
|
|
}
|
|
return prefs
|
|
}
|
|
|
|
func normalizeAppStatusBarOrder(order models.AppStatusBarOrder) models.AppStatusBarOrder {
|
|
if order.LeftItemIDs == nil {
|
|
order.LeftItemIDs = []string{}
|
|
}
|
|
if order.RightItemIDs == nil {
|
|
order.RightItemIDs = []string{}
|
|
}
|
|
return order
|
|
}
|