@app-vitals/agent-admin 1.112.0 → 1.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -156,17 +156,21 @@ test.describe("member, self-serve off: agents", () => {
156
156
  });
157
157
 
158
158
  test.describe("member, self-serve off: settings and account", () => {
159
- test("no settings are available: no nav and refused URLs", async ({
159
+ test("only Preferences is available: no admin-only nav and refused URLs", async ({
160
160
  page,
161
161
  context,
162
162
  }) => {
163
163
  await harness.signIn(context, EMAILS.member1);
164
164
  const base = harness.adminUrl;
165
165
 
166
- // /admin/settings has no first item for a member and shows no sidebar.
166
+ // /admin/settings lands a member on Preferences, the only item every role
167
+ // has, so the sidebar lists that one entry and nothing admin- or owner-only.
167
168
  const landing = await page.goto(`${base}/admin/settings`);
168
- expect(landing?.status()).toBe(404);
169
- await expect(page.locator("nav.settings-sidebar")).toHaveCount(0);
169
+ expect(landing?.status()).toBe(200);
170
+ await expect(page.locator("nav.settings-sidebar a")).toHaveCount(1);
171
+ await expect(
172
+ page.locator('nav.settings-sidebar a[href^="/admin/settings/preferences"]'),
173
+ ).toHaveCount(1);
170
174
 
171
175
  // A page the member can reach links to none of the admin-only or
172
176
  // owner-only items.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.112.0",
3
+ "version": "1.113.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.112.0",
47
+ "@app-vitals/agent-lib": "1.113.0",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
package/src/admin-boot.ts CHANGED
@@ -47,8 +47,8 @@ import { createAccountCreatedNotifier } from "./account-created-notifier.ts";
47
47
  import { AccountInviteService } from "./account-invites.ts";
48
48
  import { AccountLifecycle } from "./account-lifecycle.ts";
49
49
  import { AccountMemberService } from "./account-members.ts";
50
- import { ensureAccountMember } from "./ensure-account-member.ts";
51
50
  import { AccountOnboardingService } from "./account-onboarding.ts";
51
+ import { AccountRepoLookupService } from "./account-repo-lookup.ts";
52
52
  import { AccountTrialExpirySweeper } from "./account-trial-expiry-sweeper.ts";
53
53
  import { AccountTrialWarningSweeper } from "./account-trial-warning-sweeper.ts";
54
54
  import { AccountService } from "./accounts.ts";
@@ -98,13 +98,10 @@ import {
98
98
  import { parseChatCredentialConfig } from "./chat-credential-config.ts";
99
99
  import { HttpChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
100
100
  import { SystemClock } from "./clock.ts";
101
- import {
102
- PrismaInstallationAgents,
103
- PrismaInstallationAudit,
104
- } from "./installation-ports.ts";
105
101
  import { CronRunNowService } from "./cron-run-now.ts";
106
102
  import { parseCronRunNowConfig } from "./cron-run-now-config.ts";
107
103
  import { isDevAuthAllowed } from "./dev-auth-guard.ts";
104
+ import { ensureAccountMember } from "./ensure-account-member.ts";
108
105
  import { HttpGithubAppProvisioningClient } from "./github-app-provisioning-client.ts";
109
106
  import {
110
107
  createGithubAccessPreview,
@@ -124,10 +121,13 @@ import {
124
121
  } from "./github-repo-refresher.ts";
125
122
  import { HttpGoogleAuthClient } from "./google-auth-client.ts";
126
123
  import { HttpChatClient } from "./http-chat-client.ts";
124
+ import {
125
+ PrismaInstallationAgents,
126
+ PrismaInstallationAudit,
127
+ } from "./installation-ports.ts";
127
128
  import { HttpOktaAuthClient } from "./okta-auth-client.ts";
128
129
  import { mountPlatformApis } from "./platform-routes.ts";
129
130
  import { parsePodServiceAccountConfig } from "./pod-service-account-config.ts";
130
- import { AccountRepoLookupService } from "./account-repo-lookup.ts";
131
131
  import { PrincipalLookupService } from "./principal-lookup.ts";
132
132
  import { createAdminPrismaClient } from "./prisma-client.ts";
133
133
  import { isPushEnabled } from "./push-sender.ts";
@@ -139,12 +139,14 @@ import { HttpSlackProvisioningClient } from "./slack-provisioning-client.ts";
139
139
  import { SpecialtyTypes } from "./specialty-types.ts";
140
140
  import { runStartupPolicyReconcile } from "./startup-policy-reconcile.ts";
141
141
  import { runTemplateSeed } from "./template-seed.ts";
142
+ import { createTimezoneResolver } from "./timezone-resolver.ts";
142
143
  import { makeStrictTokenCrypto, makeTokenCrypto } from "./token-crypto.ts";
143
144
  import {
144
145
  resolveTrialExpirySweepIntervalMs,
145
146
  TrialExpirySweeper,
146
147
  } from "./trial-expiry-sweeper.ts";
147
148
  import { TrialExpiryWarningSweeper } from "./trial-expiry-warning-sweeper.ts";
149
+ import { UserPrefsService } from "./user-prefs.ts";
148
150
 
149
151
  // startAdmin() is the process boot: it runs the real migration preflight,
150
152
  // constructs a real PrismaClient (live DB connection), calls Bun.serve to bind
@@ -394,7 +396,13 @@ export async function startAdmin(
394
396
  // may build on exists and before any route is mounted. With no extensions
395
397
  // (or hookless ones) every contribution below is empty and the admin is the
396
398
  // bare platform.
399
+ const resolveTimezone = createTimezoneResolver({
400
+ userPrefs: new UserPrefsService(prisma),
401
+ members: new AccountMemberService(prisma),
402
+ deployment: process.env.SHIPWRIGHT_ADMIN_TZ,
403
+ });
397
404
  const extensionContext: AdminExtensionContext = {
405
+ resolveTimezone,
398
406
  env: process.env,
399
407
  prisma,
400
408
  sessionSecret,
@@ -737,6 +745,7 @@ export async function startAdmin(
737
745
  lifecycle: accountLifecycle,
738
746
  },
739
747
  timezone: adminTz,
748
+ userPrefs: new UserPrefsService(prisma),
740
749
  ...(chatClient ? { chatClient } : {}),
741
750
  ...(pushService
742
751
  ? {
@@ -113,6 +113,15 @@ export interface AdminExtensionContext {
113
113
  appBaseUrl: string;
114
114
  /** SHIPWRIGHT_ADMIN_TZ, when set: the admin UI's display timezone. */
115
115
  timezone?: string;
116
+ /**
117
+ * Per-request display timezone: the signed-in user's saved setting, then
118
+ * the browser `tz` cookie, then the deployment default. Prefer this over
119
+ * the boot-time `timezone` when rendering a page for a request.
120
+ */
121
+ resolveTimezone?: (input: {
122
+ email?: string | undefined;
123
+ cookie?: string | undefined;
124
+ }) => Promise<string>;
116
125
  /** Web Push, present only when VAPID is fully configured. */
117
126
  push?: { service: PushService; maxDetail: string; vapidPublicKey: string };
118
127
  /** Sentry, present only when SENTRY_DSN is set (as the admin API gets it). */
@@ -157,7 +166,7 @@ export interface AgentDetailCardContext {
157
166
  isAdmin: boolean;
158
167
  /** The agent's owning account; null for unassigned agents. */
159
168
  accountId?: string | null;
160
- /** The admin UI's display timezone (IANA name). */
169
+ /** The display timezone (IANA name), resolved for this request. */
161
170
  timezone?: string;
162
171
  }
163
172
 
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { themeBootScript } from "@app-vitals/agent-lib/web/toolbar.ts";
18
18
  import { baseStyles, escapeHtml } from "./admin-ui-styles.ts";
19
+ import { tzCookieScript } from "./timezone-resolver.ts";
19
20
 
20
21
  interface RenderAdminPageOptions {
21
22
  /** Raw, unescaped page title — HTML-escaped internally before rendering. */
@@ -54,6 +55,7 @@ export function renderAdminPage(opts: RenderAdminPageOptions): string {
54
55
  <title>${escapeHtml(opts.title)}</title>
55
56
  <meta name="color-scheme" content="light dark" />
56
57
  ${themeBootScript()}
58
+ ${tzCookieScript()}
57
59
  <style>${baseStyles()}${opts.extraStyles ?? ""}</style>${opts.headExtra ? `\n ${opts.headExtra}` : ""}
58
60
  </head>
59
61
  ${bodyTag}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * admin/src/admin-ui-preferences-pages.ts
3
+ * Render function for Settings > Preferences (per-user display timezone).
4
+ * Pure string -> string; routes live in admin-ui-preferences.ts.
5
+ */
6
+
7
+ import { renderAdminPage } from "./admin-ui-layout.ts";
8
+ import {
9
+ SETTINGS_PREFERENCES_PATH as BASE,
10
+ buildSettingsNav,
11
+ renderSettingsLayout,
12
+ type SettingsNav,
13
+ } from "./admin-ui-settings-layout.ts";
14
+ import { escapeHtml } from "./admin-ui-styles.ts";
15
+
16
+ export interface PreferencesPageOpts {
17
+ userEmail: string;
18
+ isAdmin?: boolean;
19
+ isOwner?: boolean;
20
+ nav?: SettingsNav;
21
+ /** Saved zone, or null when the browser timezone is used. */
22
+ savedTimezone: string | null;
23
+ /** The zone in effect for this request. */
24
+ effectiveTimezone: string;
25
+ /** Whether the viewer has a member profile to save onto. */
26
+ canSave: boolean;
27
+ /** IANA zone names for the picker. */
28
+ zones: readonly string[];
29
+ error?: string;
30
+ notice?: string;
31
+ }
32
+
33
+ /** The IANA zones the runtime knows, always including UTC. */
34
+ export function supportedTimezones(): string[] {
35
+ const zones = Intl.supportedValuesOf("timeZone");
36
+ return zones.includes("UTC") ? zones : ["UTC", ...zones];
37
+ }
38
+
39
+ export function renderPreferencesPage(o: PreferencesPageOpts): string {
40
+ const error = o.error
41
+ ? `<div class="alert alert-error">${escapeHtml(o.error)}</div>`
42
+ : "";
43
+ const notice = o.notice
44
+ ? `<div class="alert alert-success">${escapeHtml(o.notice)}</div>`
45
+ : "";
46
+ const options = [
47
+ `<option value=""${o.savedTimezone === null ? " selected" : ""}>Use browser timezone</option>`,
48
+ ...o.zones.map(
49
+ (z) =>
50
+ `<option value="${escapeHtml(z)}"${z === o.savedTimezone ? " selected" : ""}>${escapeHtml(z)}</option>`,
51
+ ),
52
+ ].join("");
53
+ const form = o.canSave
54
+ ? `<form method="POST" action="${BASE}/save" style="display:flex;gap:8px;align-items:end;flex-wrap:wrap">
55
+ <label>Timezone <select name="timezone" class="form-input">${options}</select></label>
56
+ <button type="submit" class="btn btn-primary">Save</button>
57
+ </form>
58
+ <form method="POST" action="${BASE}/clear" style="margin-top:8px">
59
+ <button type="submit" class="btn btn-secondary">Use browser timezone</button>
60
+ </form>`
61
+ : `<p class="help-text">Your sign-in has no member profile, so a timezone cannot be saved. The browser timezone is used.</p>`;
62
+ return renderAdminPage({
63
+ title: "Preferences — Settings — Shipwright Admin",
64
+ body: renderSettingsLayout({
65
+ userName: o.userEmail,
66
+ title: "Preferences",
67
+ nav: o.nav ?? buildSettingsNav({ preferences: true }),
68
+ active: BASE,
69
+ isAdmin: o.isAdmin ?? false,
70
+ isOwner: o.isOwner ?? false,
71
+ body: `${error}${notice}
72
+ <div class="card">
73
+ <div class="card-title">Display timezone</div>
74
+ <p class="help-text">Dates and times in the admin UI use this timezone. Leave it unset to follow your browser. Currently showing: ${escapeHtml(o.effectiveTimezone)}.</p>
75
+ ${form}
76
+ </div>`,
77
+ }),
78
+ });
79
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * admin/src/admin-ui-preferences.smoke.test.ts
3
+ * Settings > Preferences: per-user timezone save/clear, and the per-request
4
+ * resolution chain (user setting, tz cookie, deployment default) through the
5
+ * full admin UI app.
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import { makeMockDeps, makeSessionCookie } from "./admin-ui.fixtures.ts";
10
+ import { createAdminUIApp } from "./admin-ui.ts";
11
+ import { InvalidTimezoneError, isValidIanaTimezone } from "./user-prefs.ts";
12
+
13
+ const EMAIL = "m@acme.com";
14
+
15
+ function setup(opts: { deployment?: string; member?: boolean } = {}) {
16
+ const store = new Map<string, string | null>();
17
+ const userPrefs = {
18
+ getTimezone: async (id: string) => store.get(id) ?? null,
19
+ upsertByMemberId: async (
20
+ id: string,
21
+ patch: { timezone?: string | null },
22
+ ) => {
23
+ if (patch.timezone != null && !isValidIanaTimezone(patch.timezone)) {
24
+ throw new InvalidTimezoneError(patch.timezone);
25
+ }
26
+ store.set(id, patch.timezone ?? null);
27
+ return null;
28
+ },
29
+ };
30
+ const accountServices = {
31
+ accounts: { getByMemberEmail: async () => ({ id: "a1", name: "Acme" }) },
32
+ members: {
33
+ getByEmail: async (e: string) =>
34
+ e === EMAIL && opts.member !== false
35
+ ? { id: "mem-1", role: "member", accountId: "a1" }
36
+ : null,
37
+ },
38
+ } as never;
39
+ const app = createAdminUIApp(
40
+ makeMockDeps({
41
+ userPrefs,
42
+ accountServices,
43
+ ...(opts.deployment ? { timezone: opts.deployment } : {}),
44
+ }),
45
+ );
46
+ return { app, store };
47
+ }
48
+
49
+ const session = async () =>
50
+ `admin_session=${await makeSessionCookie(undefined, "u2", EMAIL, false)}`;
51
+
52
+ async function get(
53
+ app: ReturnType<typeof createAdminUIApp>,
54
+ path: string,
55
+ extraCookie = "",
56
+ ) {
57
+ return app.request(path, {
58
+ headers: { cookie: `${await session()}${extraCookie}` },
59
+ });
60
+ }
61
+
62
+ async function post(
63
+ app: ReturnType<typeof createAdminUIApp>,
64
+ path: string,
65
+ fields: Record<string, string>,
66
+ ) {
67
+ return app.request(path, {
68
+ method: "POST",
69
+ body: new URLSearchParams(fields).toString(),
70
+ headers: {
71
+ "Content-Type": "application/x-www-form-urlencoded",
72
+ cookie: await session(),
73
+ },
74
+ redirect: "manual",
75
+ });
76
+ }
77
+
78
+ // The mock agent was created at 2024-01-01T00:00Z.
79
+ const LA_DATE = "12/31/2023";
80
+ const TOKYO_DATE = "1/1/2024";
81
+
82
+ describe("Settings > Preferences", () => {
83
+ it("renders the picker with the browser option and a nav entry", async () => {
84
+ const { app } = setup();
85
+ const res = await get(app, "/admin/settings/preferences");
86
+ expect(res.status).toBe(200);
87
+ const body = await res.text();
88
+ expect(body).toContain("Use browser timezone");
89
+ expect(body).toContain('<option value="Asia/Tokyo"');
90
+ expect(body).toContain('href="/admin/settings/preferences"');
91
+ });
92
+
93
+ it("saves, shows, and clears the user timezone", async () => {
94
+ const { app, store } = setup();
95
+ const saved = await post(app, "/admin/settings/preferences/save", {
96
+ timezone: "Asia/Tokyo",
97
+ });
98
+ expect(saved.status).toBe(302);
99
+ expect(store.get("mem-1")).toBe("Asia/Tokyo");
100
+ const page = await (await get(app, "/admin/settings/preferences")).text();
101
+ expect(page).toContain('<option value="Asia/Tokyo" selected>');
102
+
103
+ const cleared = await post(app, "/admin/settings/preferences/clear", {});
104
+ expect(cleared.status).toBe(302);
105
+ expect(store.get("mem-1")).toBeNull();
106
+ });
107
+
108
+ it("treats an empty selection as clear", async () => {
109
+ const { app, store } = setup();
110
+ store.set("mem-1", "Asia/Tokyo");
111
+ await post(app, "/admin/settings/preferences/save", { timezone: "" });
112
+ expect(store.get("mem-1")).toBeNull();
113
+ });
114
+
115
+ it("rejects an invalid timezone with 422 and saves nothing", async () => {
116
+ const { app, store } = setup();
117
+ const res = await post(app, "/admin/settings/preferences/save", {
118
+ timezone: "Not/AZone",
119
+ });
120
+ expect(res.status).toBe(422);
121
+ expect(store.has("mem-1")).toBe(false);
122
+ });
123
+
124
+ it("403s a save from a viewer with no member profile", async () => {
125
+ const { app } = setup({ member: false });
126
+ const res = await post(app, "/admin/settings/preferences/save", {
127
+ timezone: "UTC",
128
+ });
129
+ expect(res.status).toBe(403);
130
+ });
131
+
132
+ it("includes the browser cookie script on pages", async () => {
133
+ const { app } = setup();
134
+ const body = await (await get(app, "/admin/agents")).text();
135
+ expect(body).toContain("resolvedOptions().timeZone");
136
+ });
137
+ });
138
+
139
+ describe("per-request timezone resolution", () => {
140
+ it("uses the deployment default with no setting and no cookie", async () => {
141
+ const { app } = setup({ deployment: "America/Los_Angeles" });
142
+ expect(await (await get(app, "/admin/agents")).text()).toContain(LA_DATE);
143
+ });
144
+
145
+ it("uses the browser cookie when nothing is saved", async () => {
146
+ const { app } = setup();
147
+ const body = await (
148
+ await get(app, "/admin/agents", "; tz=Asia%2FTokyo")
149
+ ).text();
150
+ expect(body).toContain(TOKYO_DATE);
151
+ });
152
+
153
+ it("ignores an invalid cookie", async () => {
154
+ const { app } = setup();
155
+ const res = await get(app, "/admin/agents", "; tz=Bogus%2FZone");
156
+ expect(res.status).toBe(200);
157
+ expect(await res.text()).toContain(LA_DATE);
158
+ });
159
+
160
+ it("prefers the saved setting over the cookie", async () => {
161
+ const { app, store } = setup();
162
+ store.set("mem-1", "America/Los_Angeles");
163
+ const body = await (
164
+ await get(app, "/admin/agents", "; tz=Asia%2FTokyo")
165
+ ).text();
166
+ expect(body).toContain(LA_DATE);
167
+ });
168
+ });
@@ -0,0 +1,103 @@
1
+ /**
2
+ * admin/src/admin-ui-preferences.ts
3
+ * GET/POST /admin/settings/preferences: the signed-in user's own display
4
+ * timezone. Visible to every role; keyed by the viewer's AccountMember id.
5
+ */
6
+
7
+ import type { Context, Hono, MiddlewareHandler } from "hono";
8
+ import type { AccountMemberService } from "./account-members.ts";
9
+ import type { AdminUIEnv } from "./admin-ui.ts";
10
+ import {
11
+ renderPreferencesPage,
12
+ supportedTimezones,
13
+ } from "./admin-ui-preferences-pages.ts";
14
+ import {
15
+ SETTINGS_PREFERENCES_PATH as BASE,
16
+ type SettingsNav,
17
+ } from "./admin-ui-settings-layout.ts";
18
+ import { InvalidTimezoneError, type UserPrefsService } from "./user-prefs.ts";
19
+
20
+ export interface AdminPreferencesRouteDeps {
21
+ requireAuth: MiddlewareHandler<AdminUIEnv>;
22
+ userPrefs: Pick<UserPrefsService, "getTimezone" | "upsertByMemberId">;
23
+ members: Pick<AccountMemberService, "getByEmail">;
24
+ settingsNav?: SettingsNav;
25
+ /** Zone in effect for the request (set by the per-request resolver). */
26
+ effectiveTimezone: (c: Context<AdminUIEnv>) => string;
27
+ html: (content: string, opts?: { status?: number }) => Response;
28
+ }
29
+
30
+ const NOTICES: Record<string, string> = {
31
+ saved: "Timezone saved.",
32
+ cleared: "Timezone cleared; your browser timezone is used.",
33
+ };
34
+
35
+ export function registerAdminPreferencesRoutes(
36
+ app: Hono<AdminUIEnv>,
37
+ deps: AdminPreferencesRouteDeps,
38
+ ): void {
39
+ const member = (email: string) =>
40
+ deps.members.getByEmail(email).catch(() => null);
41
+
42
+ app.get(BASE, deps.requireAuth, async (c) => {
43
+ const me = await member(c.var.userEmail);
44
+ const saved = me ? await deps.userPrefs.getTimezone(me.id) : null;
45
+ const key = c.req.query("notice");
46
+ return deps.html(
47
+ renderPreferencesPage({
48
+ userEmail: c.var.userEmail,
49
+ isAdmin: c.var.isAdmin === true,
50
+ isOwner: me?.role === "owner",
51
+ ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
52
+ savedTimezone: saved,
53
+ effectiveTimezone: deps.effectiveTimezone(c),
54
+ canSave: me !== null,
55
+ zones: supportedTimezones(),
56
+ ...(key && NOTICES[key] ? { notice: NOTICES[key] } : {}),
57
+ }),
58
+ );
59
+ });
60
+
61
+ async function save(
62
+ c: Context<AdminUIEnv>,
63
+ timezone: string | null,
64
+ notice: string,
65
+ ): Promise<Response> {
66
+ const me = await member(c.var.userEmail);
67
+ if (!me) return new Response("Forbidden", { status: 403 });
68
+ try {
69
+ await deps.userPrefs.upsertByMemberId(me.id, { timezone });
70
+ } catch (err) {
71
+ if (!(err instanceof InvalidTimezoneError)) throw err;
72
+ return deps.html(
73
+ renderPreferencesPage({
74
+ userEmail: c.var.userEmail,
75
+ isAdmin: c.var.isAdmin === true,
76
+ isOwner: me.role === "owner",
77
+ ...(deps.settingsNav ? { nav: deps.settingsNav } : {}),
78
+ savedTimezone: await deps.userPrefs.getTimezone(me.id),
79
+ effectiveTimezone: deps.effectiveTimezone(c),
80
+ canSave: true,
81
+ zones: supportedTimezones(),
82
+ error: "That is not a valid timezone.",
83
+ }),
84
+ { status: 422 },
85
+ );
86
+ }
87
+ return c.redirect(`${BASE}?notice=${notice}`, 302);
88
+ }
89
+
90
+ app.post(`${BASE}/save`, deps.requireAuth, async (c) => {
91
+ let form: FormData;
92
+ try {
93
+ form = await c.req.formData();
94
+ } catch {
95
+ form = new FormData();
96
+ }
97
+ const tz = (form.get("timezone")?.toString() ?? "").trim();
98
+ // An empty selection means "use the browser timezone".
99
+ return tz === "" ? save(c, null, "cleared") : save(c, tz, "saved");
100
+ });
101
+
102
+ app.post(`${BASE}/clear`, deps.requireAuth, (c) => save(c, null, "cleared"));
103
+ }
@@ -125,6 +125,7 @@ export const SETTINGS_GHE_PATH = "/admin/settings/github-enterprise";
125
125
  export const SETTINGS_ACCOUNT_PATH = "/admin/account";
126
126
  export const SETTINGS_ACCOUNTS_PATH = "/admin/accounts";
127
127
  export const SETTINGS_TEMPLATES_PATH = "/admin/settings/templates";
128
+ export const SETTINGS_PREFERENCES_PATH = "/admin/settings/preferences";
128
129
  export const SETTINGS_SLACK_CONFIG_TOKEN_PATH =
129
130
  "/admin/settings/slack-config-token";
130
131
 
@@ -137,6 +138,8 @@ export interface BuildSettingsNavOptions {
137
138
  templates?: boolean;
138
139
  /** Include the Slack config token item (its routes are registered). */
139
140
  slackConfigToken?: boolean;
141
+ /** Include the Preferences item (per-user timezone), visible to every role. */
142
+ preferences?: boolean;
140
143
  /** Extension-contributed items (SGL-2.1). */
141
144
  extraItems?: readonly SettingsNavContribution[];
142
145
  }
@@ -183,9 +186,17 @@ export function buildSettingsNav(
183
186
  if (opts.accounts) {
184
187
  sections.push({
185
188
  label: "Account",
186
- items: [{ label: "Account", path: SETTINGS_ACCOUNT_PATH }],
189
+ items: [
190
+ { label: "Account", path: SETTINGS_ACCOUNT_PATH, ownerOnly: true },
191
+ ],
187
192
  });
188
193
  }
194
+ if (opts.preferences) {
195
+ const section = sections.find((s) => s.label === "Account");
196
+ const item = { label: "Preferences", path: SETTINGS_PREFERENCES_PATH };
197
+ if (section) section.items.push(item);
198
+ else sections.push({ label: "Account", items: [item] });
199
+ }
189
200
  if (platform.length > 0)
190
201
  sections.push({ label: "Platform", items: platform });
191
202
  const base: SettingsNav = { sections };
package/src/admin-ui.ts CHANGED
@@ -54,8 +54,8 @@ import { registerAdminGithubEnterpriseRoutes } from "./admin-ui-github-enterpris
54
54
  import type { GheOrgs } from "./admin-ui-github-enterprise-pages.ts";
55
55
  import {
56
56
  type GithubUninstallPreviewView,
57
- renderGithubAccessError,
58
57
  MAX_INSTALL_REPOSITORIES,
58
+ renderGithubAccessError,
59
59
  renderGithubOrgsFragment,
60
60
  renderGithubUninstallConfirm,
61
61
  } from "./admin-ui-github-identity-pages.ts";
@@ -98,6 +98,7 @@ import {
98
98
  renderProvisionXappTokenPage,
99
99
  settingsRedirectSection,
100
100
  } from "./admin-ui-pages.ts";
101
+ import { registerAdminPreferencesRoutes } from "./admin-ui-preferences.ts";
101
102
  import {
102
103
  buildSettingsNav,
103
104
  filterSettingsNavForRole,
@@ -208,12 +209,20 @@ import {
208
209
  type SpecialtyTypeResolver,
209
210
  SpecialtyTypes,
210
211
  } from "./specialty-types.ts";
212
+ import {
213
+ createTimezoneResolver,
214
+ DEFAULT_TIMEZONE,
215
+ TIMEZONE_COOKIE,
216
+ } from "./timezone-resolver.ts";
217
+ import type { UserPrefsService } from "./user-prefs.ts";
211
218
 
212
219
  export type AdminUIEnv = {
213
220
  Variables: {
214
221
  userEmail: string;
215
222
  isAdmin: boolean;
216
223
  settingsNav?: SettingsNav;
224
+ /** Display timezone resolved for this request (user, cookie, default). */
225
+ timezone?: string;
217
226
  };
218
227
  };
219
228
 
@@ -590,6 +599,13 @@ export interface AdminUIDeps {
590
599
  * Defaults to "America/Los_Angeles" when absent.
591
600
  */
592
601
  timezone?: string;
602
+ /**
603
+ * Per-user preferences store. When present (with `accountServices`), the
604
+ * display timezone is resolved per request from the user's saved setting,
605
+ * then the browser `tz` cookie, then `timezone`, and Settings > Preferences
606
+ * is registered. Absent: the fixed `timezone` is used for every request.
607
+ */
608
+ userPrefs?: Pick<UserPrefsService, "getTimezone" | "upsertByMemberId">;
593
609
  /**
594
610
  * Extra `?error=` codes (code → message) an extension's routes redirect to
595
611
  * the agent detail page with — merged over the platform's own codes.
@@ -1027,7 +1043,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1027
1043
  githubAppClient,
1028
1044
  appBaseUrl,
1029
1045
  devAuthEnabled = false,
1030
- timezone = "America/Los_Angeles",
1046
+ timezone: deploymentTimezone,
1031
1047
  chatClient,
1032
1048
  pwaAssetsDir = PWA_ASSETS_DIR,
1033
1049
  appVersion = "0.0.0",
@@ -1041,6 +1057,10 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1041
1057
  // toggle-render gate and the route-503 gate can't drift.
1042
1058
  const pushEnabled = Boolean(pushService && vapidPublicKey);
1043
1059
 
1060
+ // Fixed display timezone for requests the per-request resolver does not
1061
+ // cover (and the deployment default it falls back to).
1062
+ const timezone = deploymentTimezone ?? DEFAULT_TIMEZONE;
1063
+
1044
1064
  const app = new Hono<AdminUIEnv>();
1045
1065
 
1046
1066
  const requireAuth = createUIAuthMiddleware(sessionSecret, {
@@ -1050,12 +1070,19 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1050
1070
  });
1051
1071
 
1052
1072
  const accountNavEnabled = accountServices !== undefined;
1073
+ const preferencesEnabled = Boolean(deps.userPrefs && accountServices);
1074
+ const resolveRequestTimezone = createTimezoneResolver({
1075
+ ...(deps.userPrefs ? { userPrefs: deps.userPrefs } : {}),
1076
+ ...(accountServices ? { members: accountServices.members } : {}),
1077
+ deployment: timezone,
1078
+ });
1053
1079
 
1054
1080
  const settingsNav = buildSettingsNav({
1055
1081
  githubEnterprise: Boolean(githubEnterpriseApi),
1056
1082
  templates: Boolean(templateService),
1057
1083
  slackConfigToken: Boolean(slackConfigToken),
1058
1084
  accounts: accountNavEnabled,
1085
+ preferences: preferencesEnabled,
1059
1086
  extraItems: deps.settingsNavItems ?? [],
1060
1087
  });
1061
1088
 
@@ -1092,12 +1119,32 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1092
1119
  await next();
1093
1120
  });
1094
1121
 
1122
+ // Per-request display timezone: the user's saved setting, then the tz
1123
+ // cookie, then the deployment default. Only when preferences are wired;
1124
+ // otherwise handlers fall back to the fixed timezone.
1125
+ if (preferencesEnabled) {
1126
+ app.use("/admin/*", async (c, next) => {
1127
+ const token = getCookie(c, SESSION_COOKIE);
1128
+ const user = token ? await getSessionUser(token, sessionSecret) : null;
1129
+ c.set(
1130
+ "timezone",
1131
+ await resolveRequestTimezone({
1132
+ email: user?.email,
1133
+ cookie: getCookie(c, TIMEZONE_COOKIE),
1134
+ }),
1135
+ );
1136
+ await next();
1137
+ });
1138
+ }
1139
+ const tzOf = (c: Context<AdminUIEnv>): string => c.var.timezone ?? timezone;
1140
+
1095
1141
  // GHE-1.4: per-request toolbar audience; TOOLBAR_NAV_ITEMS decides visibility.
1096
1142
  if (
1097
1143
  githubEnterpriseApi ||
1098
1144
  templateService ||
1099
1145
  slackConfigToken ||
1100
- accountNavEnabled
1146
+ accountNavEnabled ||
1147
+ preferencesEnabled
1101
1148
  ) {
1102
1149
  app.use("/admin/*", async (c, next) => {
1103
1150
  const token = getCookie(c, SESSION_COOKIE);
@@ -1652,7 +1699,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1652
1699
  );
1653
1700
  }
1654
1701
  return html(
1655
- renderAgentsPage(agents, c.var.userEmail, c.var.isAdmin, timezone, {
1702
+ renderAgentsPage(agents, c.var.userEmail, c.var.isAdmin, tzOf(c), {
1656
1703
  accountNames,
1657
1704
  queueActivityLinks: deps.queueActivityLinks,
1658
1705
  successMsg,
@@ -2510,7 +2557,12 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2510
2557
  }
2511
2558
  }
2512
2559
  }
2513
- return html(renderInstallationReposBody(view, { appIdMismatch, timezone }));
2560
+ return html(
2561
+ renderInstallationReposBody(view, {
2562
+ appIdMismatch,
2563
+ timezone: tzOf(c),
2564
+ }),
2565
+ );
2514
2566
  });
2515
2567
 
2516
2568
  // IRM-3.2: the single Sync confirm (over the IRM-3.1 preview) and its apply.
@@ -2528,7 +2580,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2528
2580
  renderSyncConfirm(
2529
2581
  c.req.param("id") ?? "",
2530
2582
  (await res.json()) as GithubSyncPreviewView,
2531
- timezone,
2583
+ tzOf(c),
2532
2584
  ),
2533
2585
  );
2534
2586
  });
@@ -2598,7 +2650,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2598
2650
  warnings,
2599
2651
  )
2600
2652
  : [],
2601
- timezone,
2653
+ tzOf(c),
2602
2654
  ),
2603
2655
  );
2604
2656
  },
@@ -2785,7 +2837,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2785
2837
  userEmail: c.var.userEmail,
2786
2838
  isAdmin: c.var.isAdmin,
2787
2839
  accountId: agent.accountId ?? null,
2788
- timezone,
2840
+ timezone: tzOf(c),
2789
2841
  },
2790
2842
  );
2791
2843
 
@@ -2847,7 +2899,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2847
2899
  newToken,
2848
2900
  successMsg,
2849
2901
  warning,
2850
- timezone,
2902
+ timezone: tzOf(c),
2851
2903
  extensionCardsHtml: cards.header,
2852
2904
  configurationCardsHtml: cards.configuration,
2853
2905
  queueActivityLinks: deps.queueActivityLinks,
@@ -3859,7 +3911,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3859
3911
  userEmail: c.var.userEmail,
3860
3912
  isAdmin: c.var.isAdmin,
3861
3913
  accountId: agent.accountId ?? null,
3862
- timezone,
3914
+ timezone: tzOf(c),
3863
3915
  },
3864
3916
  ["configuration"],
3865
3917
  );
@@ -3878,7 +3930,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
3878
3930
  section: "access",
3879
3931
  canManage,
3880
3932
  newToken: rawToken,
3881
- timezone,
3933
+ timezone: tzOf(c),
3882
3934
  extensionCardsHtml: cards.header,
3883
3935
  configurationCardsHtml: cards.configuration,
3884
3936
  queueActivityLinks: deps.queueActivityLinks,
@@ -4696,7 +4748,8 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4696
4748
  githubEnterpriseApi ||
4697
4749
  templateService ||
4698
4750
  slackConfigToken ||
4699
- accountNavEnabled
4751
+ accountNavEnabled ||
4752
+ preferencesEnabled
4700
4753
  ) {
4701
4754
  app.get("/admin/settings", requireAuth, async (c) => {
4702
4755
  // Admins without an account would 404 on the Account item; skip it.
@@ -4771,6 +4824,19 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
4771
4824
  });
4772
4825
  }
4773
4826
 
4827
+ // ─── Preferences (per-user display timezone) ─────────────────────────────
4828
+
4829
+ if (deps.userPrefs && accountServices) {
4830
+ registerAdminPreferencesRoutes(app, {
4831
+ requireAuth,
4832
+ userPrefs: deps.userPrefs,
4833
+ members: accountServices.members,
4834
+ settingsNav,
4835
+ effectiveTimezone: (c) => c.var.timezone ?? timezone,
4836
+ html,
4837
+ });
4838
+ }
4839
+
4774
4840
  // ─── Account page (SSP-3.2) ───────────────────────────────────────────────
4775
4841
 
4776
4842
  if (accountServices) {
@@ -0,0 +1,88 @@
1
+ /**
2
+ * admin/src/timezone-resolver.ts
3
+ * Per-request display timezone: the signed-in user's saved setting, then the
4
+ * browser-set `tz` cookie, then the deployment default. An invalid value at
5
+ * any level falls through to the next; nothing here throws.
6
+ */
7
+
8
+ import type { AccountMemberService } from "./account-members.ts";
9
+ import { isValidIanaTimezone, type UserPrefsService } from "./user-prefs.ts";
10
+
11
+ /** Used when neither the user, the cookie nor the deployment supplies a zone. */
12
+ export const DEFAULT_TIMEZONE = "America/Los_Angeles";
13
+
14
+ export const TIMEZONE_COOKIE = "tz";
15
+
16
+ export interface TimezoneSources {
17
+ /** The user's saved setting. */
18
+ user?: string | null;
19
+ /** The browser-reported zone from the tz cookie. */
20
+ cookie?: string | null;
21
+ /** The deployment default (SHIPWRIGHT_ADMIN_TZ). */
22
+ deployment?: string | null;
23
+ }
24
+
25
+ const usable = (tz: string | null | undefined): tz is string =>
26
+ typeof tz === "string" && isValidIanaTimezone(tz);
27
+
28
+ /** First valid of user, cookie, deployment; else the built-in default. */
29
+ export function resolveTimezone(src: TimezoneSources): string {
30
+ for (const tz of [src.user, src.cookie, src.deployment]) {
31
+ if (usable(tz)) return tz;
32
+ }
33
+ return DEFAULT_TIMEZONE;
34
+ }
35
+
36
+ /** The decoded tz cookie from a Cookie header, if present and well-formed. */
37
+ export function parseTzCookie(header: string | null | undefined) {
38
+ if (!header) return undefined;
39
+ for (const part of header.split(";")) {
40
+ const eq = part.indexOf("=");
41
+ if (eq < 0 || part.slice(0, eq).trim() !== TIMEZONE_COOKIE) continue;
42
+ try {
43
+ return decodeURIComponent(part.slice(eq + 1).trim());
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ export interface TimezoneResolverDeps {
52
+ userPrefs?: Pick<UserPrefsService, "getTimezone">;
53
+ members?: Pick<AccountMemberService, "getByEmail">;
54
+ /** Deployment default; invalid or absent falls to DEFAULT_TIMEZONE. */
55
+ deployment?: string | null;
56
+ }
57
+
58
+ export type TimezoneResolver = (input: {
59
+ email?: string | undefined;
60
+ cookie?: string | undefined;
61
+ }) => Promise<string>;
62
+
63
+ /** Async resolver that looks up the user's saved setting by signed-in email. */
64
+ export function createTimezoneResolver(
65
+ deps: TimezoneResolverDeps,
66
+ ): TimezoneResolver {
67
+ return async ({ email, cookie }) => {
68
+ let user: string | null = null;
69
+ if (email && deps.userPrefs && deps.members) {
70
+ try {
71
+ const member = await deps.members.getByEmail(email);
72
+ if (member) user = await deps.userPrefs.getTimezone(member.id);
73
+ } catch {
74
+ // a failed lookup falls through to the cookie
75
+ }
76
+ }
77
+ return resolveTimezone({ user, cookie, deployment: deps.deployment });
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Small inline script: records the browser's IANA zone in the tz cookie (one
83
+ * year, site-wide). The resolver ignores the cookie when the user has a saved
84
+ * setting, so it is safe to set unconditionally.
85
+ */
86
+ export function tzCookieScript(): string {
87
+ return `<script>(function(){try{var z=Intl.DateTimeFormat().resolvedOptions().timeZone;if(!z)return;var e=encodeURIComponent(z);if(document.cookie.split("; ").indexOf("tz="+e)>=0)return;document.cookie="tz="+e+"; path=/; max-age=31536000; SameSite=Lax"}catch(_){}})();</script>`;
88
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * admin/src/timezone-resolver.unit.test.ts
3
+ * Per-request display timezone: user setting, then tz cookie, then deployment
4
+ * default; an invalid value at any level falls through.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import {
9
+ createTimezoneResolver,
10
+ DEFAULT_TIMEZONE,
11
+ parseTzCookie,
12
+ resolveTimezone,
13
+ tzCookieScript,
14
+ } from "./timezone-resolver.ts";
15
+
16
+ describe("resolveTimezone", () => {
17
+ it("prefers the user setting", () => {
18
+ expect(
19
+ resolveTimezone({
20
+ user: "Europe/Paris",
21
+ cookie: "Asia/Tokyo",
22
+ deployment: "UTC",
23
+ }),
24
+ ).toBe("Europe/Paris");
25
+ });
26
+
27
+ it("uses the cookie when there is no user setting", () => {
28
+ expect(
29
+ resolveTimezone({ user: null, cookie: "Asia/Tokyo", deployment: "UTC" }),
30
+ ).toBe("Asia/Tokyo");
31
+ });
32
+
33
+ it("uses the deployment default when neither is set", () => {
34
+ expect(resolveTimezone({ deployment: "UTC" })).toBe("UTC");
35
+ });
36
+
37
+ it("falls back to the built-in default last", () => {
38
+ expect(resolveTimezone({})).toBe(DEFAULT_TIMEZONE);
39
+ expect(DEFAULT_TIMEZONE).toBe("America/Los_Angeles");
40
+ });
41
+
42
+ it("falls through an invalid user setting to the cookie", () => {
43
+ expect(resolveTimezone({ user: "Not/AZone", cookie: "Asia/Tokyo" })).toBe(
44
+ "Asia/Tokyo",
45
+ );
46
+ });
47
+
48
+ it("falls through an invalid cookie to the deployment default", () => {
49
+ expect(resolveTimezone({ cookie: "bogus", deployment: "UTC" })).toBe("UTC");
50
+ });
51
+
52
+ it("falls through an invalid deployment default without throwing", () => {
53
+ expect(resolveTimezone({ user: "x", cookie: "y", deployment: "z" })).toBe(
54
+ DEFAULT_TIMEZONE,
55
+ );
56
+ });
57
+ });
58
+
59
+ describe("parseTzCookie", () => {
60
+ it("reads and decodes the tz cookie", () => {
61
+ expect(parseTzCookie("a=1; tz=America%2FChicago; b=2")).toBe(
62
+ "America/Chicago",
63
+ );
64
+ });
65
+ it("returns undefined when absent or malformed", () => {
66
+ expect(parseTzCookie(undefined)).toBeUndefined();
67
+ expect(parseTzCookie("a=1")).toBeUndefined();
68
+ expect(parseTzCookie("tz=%E0%A4%A")).toBeUndefined();
69
+ });
70
+ });
71
+
72
+ describe("createTimezoneResolver", () => {
73
+ const members = {
74
+ getByEmail: async (e: string) =>
75
+ e === "m@acme.com" ? ({ id: "mem-1" } as never) : null,
76
+ };
77
+
78
+ it("resolves the stored setting by the member's id", async () => {
79
+ const resolve = createTimezoneResolver({
80
+ userPrefs: { getTimezone: async (id) => (id === "mem-1" ? "UTC" : null) },
81
+ members,
82
+ deployment: "Asia/Tokyo",
83
+ });
84
+ expect(await resolve({ email: "m@acme.com", cookie: "Europe/Paris" })).toBe(
85
+ "UTC",
86
+ );
87
+ });
88
+
89
+ it("uses the cookie for a member with nothing saved", async () => {
90
+ const resolve = createTimezoneResolver({
91
+ userPrefs: { getTimezone: async () => null },
92
+ members,
93
+ });
94
+ expect(await resolve({ email: "m@acme.com", cookie: "Europe/Paris" })).toBe(
95
+ "Europe/Paris",
96
+ );
97
+ });
98
+
99
+ it("falls through when the lookup throws or the email is unknown", async () => {
100
+ const boom = createTimezoneResolver({
101
+ userPrefs: {
102
+ getTimezone: async () => {
103
+ throw new Error("db down");
104
+ },
105
+ },
106
+ members,
107
+ deployment: "UTC",
108
+ });
109
+ expect(await boom({ email: "m@acme.com" })).toBe("UTC");
110
+ expect(await boom({ email: "nobody@acme.com" })).toBe("UTC");
111
+ expect(await boom({})).toBe("UTC");
112
+ });
113
+
114
+ it("works with no stores at all", async () => {
115
+ const resolve = createTimezoneResolver({});
116
+ expect(await resolve({ cookie: "UTC" })).toBe("UTC");
117
+ });
118
+ });
119
+
120
+ describe("tzCookieScript", () => {
121
+ it("is a script tag that sets the tz cookie from Intl", () => {
122
+ const s = tzCookieScript();
123
+ expect(s.startsWith("<script>")).toBe(true);
124
+ expect(s).toContain("resolvedOptions().timeZone");
125
+ expect(s).toContain("tz=");
126
+ });
127
+ });