Skip to content

Commit e943530

Browse files
feat(ui): add time and date format settings and message timestamps (#2223)
* feat(ui): add time and date format settings and message timestamps * fix(ui): address review feedback on time and date settings * test(visual): add Language tab baselines * test(e2e): mask the message time in the extension host visual test * test(e2e): update the chat sidebar baseline for the message time * test(e2e): give the masked message time a fixed width so the mask box is stable * test(e2e): iterate the message times with forEach (no DOM.Iterable in this tsconfig) * test(e2e): regenerate the chat sidebar baseline from CI with a fixed-width message time * feat(ui): make the time format a real radio group with roving focus and arrow keys * test(host): cover saving the date and time settings and returning them to the webview * test(ui): cover the date format on older messages across user, assistant and completion rows * test(e2e): pin the masked message time to one fixed-size line, and update the baseline * refactor(ui): drop the unused formatDate; no tooltip that repeats an absolute time * fix(ui): select the time format option that receives focus; keep keyboard behaviour assertions in Vitest * test: assert the webview state refresh after a save; cover the date format in another display language * test(ui): cover the task header time and the display language fallback * fix(ui): save the three date and time settings all-or-nothing * test(ui): cover the message time while editing, and an invalid task time in the header * fix(ui): unwind overlapping failed saves in any order, keep imports, follow the existing error path for other keys, honest failure text * fix(import): restore display settings if settings import write fails * fix(import): wait for every display write before restoring * fix(import): say which display settings could not be restored * refactor: one write chain for saves and imports of the display settings * fix: validate display values, order writes per key down to storage, read what a write replaces when it starts * test: cover the handed-over previous value of a queued write * fix: keep a store made outside a save when a failed write is rolled back * fix: count only stores by others, and re-read a handed-over value if someone stored the key before the write started * fix: a finished write is the base of a later queued one; no empty block for an invalid timestamp * test: cover a write that had started when the earlier one finished * fix(import): keep the display writes active until every step has succeeded; baseline a handed-over value at the store that held it * fix: hand a rolled-back value on only while nobody else stored the key; test omitted display keys from non-default values * fix: count only stores by others directly, marking the store being issued here * fix: a rejected outside store of a tracked setting is not a store to protect * fix: number the stores by others, so a rejected one cancels only itself * fix: keep the stores by others only while a write of the key is pending * fix: keep recording stores by others while the restore of an undone write waits in the queue * test: two restores waiting for one key * refactor: one helper for the count of waiting restores * fix: put the cache back when a store of a tracked setting is rejected * fix: validate the display language on the host; fall back to English for an unusable locale; reconcile the cache from storage when a tracked store is rejected * fix: re-stamp the earlier write only if nobody else stored the key; the bookkeeping hook covers every map * test: an empty experiments or customSupportPrompts value in a display-settings save * refactor: drop the rollback logic for the display settings; keep host-side validation of the values * fix: the public API writes check the display settings like updateSettings * test: document the partial-failure behaviour of the display settings save; Playwright stories for the timestamp rows, task header and absolute history time * test: fix the timestamp stories: the footer date format, and a focus target only where there is a control * test: Linux baselines for the timestamp rows, the expanded task header and the absolute history time, in four themes * ci: rerun the visual check (the welcome contrast check sampled a fade in progress; it passed on the run before) * test: the partial-save contract of the public API path; tooltip and future-day coverage for the message time * feat: ContextProxy.setValues reads the cache back for failed keys and reports which keys were stored and which were not * fix: setValues reads a failed secret back from the secret storage too * test: cover the report wording and the pass-through key in ContextProxy.setValues * fix: SettingsWriteError.cause overrides Error.cause * fix: a failed store reads its key back into the cache for every setting and for secrets, guarded against newer writes; the first failure stays the cause * fix: the secret read-back has a deadline so the write error reaches the caller; the cache read-back is documented and tested as best effort for global state * test: a failed secret store that a newer write has superseded is not read back * fix: ContextProxy releases the write owner when a write is over and handles storage that throws at once; tests for secret deletion, the error name and owner release * fix: refreshSecrets takes over a key from a pending write, so a failed write's read-back cannot hide the loaded secret * fix: refreshSecrets detects a write that started and finished during its read (per-key write count); the race test holds back the right key * feat: a save that changes a time or date setting waits for the host's answer (settingsSaveResult) and keeps the edit unsaved after a failure * chore: knip does not count the webview test helpers as unused files
1 parent 1c15695 commit e943530

77 files changed

Lines changed: 3854 additions & 76 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
-898 Bytes
Loading

‎apps/vscode-e2e/src/visual/electron.visual.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,21 @@ for (const scenario of scenarios) {
8989
const tokenCountMask = webviewFrame
9090
.frameLocator("iframe")
9191
.locator('[data-testid="context-tokens-count"],[data-testid="context-window-size"]')
92+
// The time under each message is the real send time, so it changes on every run, and so does the length
93+
// of its text ("Today 9:05 AM" and "Yesterday 12:36 PM" are not equally long). A mask covers the
94+
// element's box, so that box needs a fixed size as well: without it the masked area differs between
95+
// runs, in width and, when the text wraps onto a second line, in height.
96+
await contentFrame.evaluate(() => {
97+
document.querySelectorAll<HTMLElement>('[data-testid="message-timestamp"]').forEach((time) => {
98+
time.style.setProperty("width", "160px", "important")
99+
time.style.setProperty("white-space", "nowrap", "important")
100+
time.style.setProperty("overflow", "hidden", "important")
101+
})
102+
})
103+
// Mask it, as the token counters above, and keep the rest of the scene byte-stable.
104+
const messageTimeMask = webviewFrame.frameLocator("iframe").locator('[data-testid="message-timestamp"]')
92105
await expect(sidebar).toHaveScreenshot(`electron-${scenario.name}-sidebar.png`, {
93-
mask: [tokenCountMask],
106+
mask: [tokenCountMask, messageTimeMask],
94107
})
95108

96109
if (scenario.webviewSnapshot) {

‎knip.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"src/**/*.{ts,tsx}!",
4848
"../src/shared/*.ts!",
4949
"!src/utils/test-utils.tsx!",
50+
"!src/**/__tests__/**!",
5051
"!src/vite-plugins/**!",
5152
"!src/**/*.visual.tsx!",
5253
"!src/**/*.visual.{fixture,i18n}.{ts,tsx}!"

‎packages/types/src/global-settings.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,21 @@ export const globalSettingsSchema = z.object({
280280
* When unset (or `null`), the webview inherits VS Code's `--vscode-font-size`.
281281
*/
282282
chatFontSize: z.number().int().min(8).max(32).nullish(),
283+
/**
284+
* Clock format used when rendering timestamps. "auto" follows the display language's locale.
285+
* @default "auto"
286+
*/
287+
timeFormat: z.enum(["auto", "12h", "24h"]).optional(),
288+
/**
289+
* How dates are written. "auto" follows the display language's locale.
290+
* @default "auto"
291+
*/
292+
dateFormat: z.enum(["auto", "mdy", "dmy", "ymd"]).optional(),
293+
/**
294+
* Show relative times ("5 min ago") in task history; when off, show the absolute date/time.
295+
* @default true
296+
*/
297+
showRelativeTimes: z.boolean().optional(),
283298
/**
284299
* Controls the keyboard behavior for sending messages in the chat input.
285300
* - "send": Enter sends message, Shift+Enter creates newline (default)

‎packages/types/src/vscode-extension-host.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export interface ExtensionMessage {
5050
| typeof VsCodeLmModelsMessageType.vsCodeLmModels
5151
| typeof VsCodeLmModelsMessageType.githubCopilotModels
5252
| typeof VsCodeLmModelsMessageType.githubCopilotSignInResult
53+
| "settingsSaveResult"
5354
| "vsCodeLmApiAvailable"
5455
| "updatePrompt"
5556
| "systemPrompt"
@@ -341,6 +342,9 @@ export type ExtensionState = Pick<
341342
| "includeTaskHistoryInEnhance"
342343
| "reasoningBlockCollapsed"
343344
| "chatFontSize"
345+
| "timeFormat"
346+
| "dateFormat"
347+
| "showRelativeTimes"
344348
| "enterBehavior"
345349
| "includeCurrentTime"
346350
| "includeCurrentCost"

‎src/core/config/ContextProxy.ts‎

Lines changed: 137 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,37 @@ type RooCodeSettingsKey = keyof RooCodeSettings
3030

3131
const PASS_THROUGH_STATE_KEYS = ["taskHistory"]
3232

33+
/** `ContextProxy.setValues` could not store every key: which ones it stored, which it did not, and the first failure. */
34+
export class SettingsWriteError extends Error {
35+
constructor(
36+
readonly committed: string[],
37+
readonly failed: string[],
38+
override readonly cause: unknown,
39+
) {
40+
super(
41+
`Could not store ${failed.join(", ")}${committed.length > 0 ? ` (stored: ${committed.join(", ")})` : ""}: ${
42+
cause instanceof Error ? cause.message : String(cause)
43+
}`,
44+
)
45+
this.name = "SettingsWriteError"
46+
}
47+
}
48+
49+
/** How long the read-back of a failed secret may take: the write error must reach the caller even if it never settles. */
50+
const SECRET_READBACK_TIMEOUT_MS = 5_000
51+
52+
const withinReadBackDeadline = <T>(read: PromiseLike<T>, key: string): Promise<T> =>
53+
new Promise<T>((resolve, reject) => {
54+
const timer = setTimeout(
55+
() =>
56+
reject(new Error(`Reading back ${key} did not finish in ${SECRET_READBACK_TIMEOUT_MS / 1000} seconds`)),
57+
SECRET_READBACK_TIMEOUT_MS,
58+
)
59+
Promise.resolve(read)
60+
.then(resolve, reject)
61+
.finally(() => clearTimeout(timer))
62+
})
63+
3364
export const isPassThroughStateKey = (key: string) => PASS_THROUGH_STATE_KEYS.includes(key)
3465

3566
const globalSettingsExportSchema = globalSettingsSchema.omit({
@@ -360,13 +391,42 @@ export class ContextProxy {
360391
return value !== undefined ? value : defaultValue
361392
}
362393

394+
/**
395+
* The write that last set each cached key, so a failed write only corrects the cache while it is still the latest:
396+
* a newer write of the key has its own outcome, and an older failure must not replace its value.
397+
*/
398+
private readonly stateWriteOwner = new Map<string, object>()
399+
private readonly secretWriteOwner = new Map<string, object>()
400+
/** How many writes of each secret were started. Unlike the owners, it is not cleared when a write is over. */
401+
private readonly secretWriteCount = new Map<string, number>()
402+
363403
updateGlobalState<K extends GlobalStateKey>(key: K, value: GlobalState[K]) {
364404
if (isPassThroughStateKey(key)) {
365405
return this.originalContext.globalState.update(key, value)
366406
}
367407

408+
// The cache is updated first, so a read right after the call sees the value. If the store rejects, the cache is
409+
// read back from the Memento (`globalState.get`) so that it shows what the Memento holds. This is best effort: a
410+
// Memento can keep the attempted value in memory after a rejected update, in which case the cache and the
411+
// Memento agree and only the durable copy, which cannot be read, may differ until the key is written again.
412+
// The entry of the key is removed when the write is over (if it is still the latest), so the map only holds the
413+
// writes that are in flight. An update that throws at once is turned into a rejection, so it is handled the same.
414+
const owner = {}
415+
this.stateWriteOwner.set(key, owner)
368416
this.stateCache[key] = value
369-
return this.originalContext.globalState.update(key, value)
417+
const release = () => {
418+
if (this.stateWriteOwner.get(key) === owner) this.stateWriteOwner.delete(key)
419+
}
420+
return (async () => this.originalContext.globalState.update(key, value))().then(release, (error: unknown) => {
421+
try {
422+
if (this.stateWriteOwner.get(key) === owner) {
423+
this.stateCache[key] = this.originalContext.globalState.get<GlobalState[K]>(key)
424+
}
425+
} finally {
426+
release()
427+
}
428+
throw error
429+
})
370430
}
371431

372432
private getAllGlobalState(): GlobalState {
@@ -384,12 +444,54 @@ export class ContextProxy {
384444

385445
storeSecret(key: SecretStateKey, value?: string) {
386446
// Update cache.
447+
const owner = {}
448+
this.secretWriteOwner.set(key, owner)
449+
this.secretWriteCount.set(key, (this.secretWriteCount.get(key) ?? 0) + 1)
387450
this.secretCache[key] = value
388451

389-
// Write directly to context.
390-
return value === undefined
391-
? this.originalContext.secrets.delete(key)
392-
: this.originalContext.secrets.store(key, value)
452+
// Write directly to context. If the write rejects, the cache is read back from the secret storage while this
453+
// write is still the latest of the key; if that fails too, the value that was never stored is dropped from the
454+
// cache (it stays empty until the next write, `refreshSecrets` or a restart) rather than being served.
455+
// The entry of the key is removed when the write and its read-back are over (if it is still the latest). A store
456+
// that throws at once is turned into a rejection, so it is handled the same.
457+
const release = () => {
458+
if (this.secretWriteOwner.get(key) === owner) this.secretWriteOwner.delete(key)
459+
}
460+
const stored = (async () =>
461+
value === undefined
462+
? this.originalContext.secrets.delete(key)
463+
: this.originalContext.secrets.store(key, value))()
464+
return stored.then(release, async (error: unknown) => {
465+
try {
466+
if (this.secretWriteOwner.get(key) === owner) {
467+
try {
468+
const readBack = await withinReadBackDeadline(this.originalContext.secrets.get(key), key)
469+
if (this.secretWriteOwner.get(key) === owner) this.secretCache[key] = readBack
470+
} catch (readError) {
471+
logger.error(
472+
`Error reading back secret ${key}: ${readError instanceof Error ? readError.message : String(readError)}`,
473+
)
474+
if (this.secretWriteOwner.get(key) === owner) this.secretCache[key] = undefined
475+
}
476+
}
477+
} finally {
478+
release()
479+
}
480+
throw error
481+
})
482+
}
483+
484+
/**
485+
* Loads one secret into the cache. A write of the key that started while the secret was being read has its own
486+
* outcome, even if it is already over, so the (older) value that was read is dropped. Otherwise the load takes over the key from a write that is
487+
* still pending, so that a failure of that write cannot replace what was just loaded.
488+
*/
489+
private async refreshSecret(key: SecretStateKey) {
490+
const writes = this.secretWriteCount.get(key)
491+
const value = await this.originalContext.secrets.get(key)
492+
if (this.secretWriteCount.get(key) !== writes) return
493+
this.secretWriteOwner.delete(key)
494+
this.secretCache[key] = value
393495
}
394496

395497
/**
@@ -400,7 +502,7 @@ export class ContextProxy {
400502
const promises = [
401503
...SECRET_STATE_KEYS.map(async (key) => {
402504
try {
403-
this.secretCache[key] = await this.originalContext.secrets.get(key)
505+
await this.refreshSecret(key)
404506
} catch (error) {
405507
logger.error(
406508
`Error refreshing secret ${key}: ${error instanceof Error ? error.message : String(error)}`,
@@ -409,7 +511,7 @@ export class ContextProxy {
409511
}),
410512
...GLOBAL_SECRET_KEYS.map(async (key) => {
411513
try {
412-
this.secretCache[key] = await this.originalContext.secrets.get(key)
514+
await this.refreshSecret(key)
413515
} catch (error) {
414516
logger.error(
415517
`Error refreshing global secret ${key}: ${error instanceof Error ? error.message : String(error)}`,
@@ -555,9 +657,36 @@ export class ContextProxy {
555657
return { ...globalState, ...secretState }
556658
}
557659

660+
/**
661+
* Writes every value at once. This is not a transaction, for any setting: each key is stored on its own, and the
662+
* stores that completed are not undone. If any store rejects, every store is still awaited (the call stays pending
663+
* until the last one has settled) and then rejects with a `SettingsWriteError` that says which keys were stored and
664+
* which were not. A failed store has already read its key back into the cache (see `updateGlobalState` and
665+
* `storeSecret`; best effort for global state, whose Memento may keep the attempted value). Callers that need more than this, such as a
666+
* rollback, must provide it themselves.
667+
*/
558668
public async setValues(values: RooCodeSettings) {
559669
const entries = Object.entries(values) as [RooCodeSettingsKey, unknown][]
560-
await Promise.all(entries.map(([key, value]) => this.setValue(key, value)))
670+
const results = await Promise.allSettled(entries.map(([key, value]) => this.setValue(key, value)))
671+
672+
const committed: string[] = []
673+
const failed: string[] = []
674+
let cause: unknown
675+
let hasCause = false
676+
for (const [index, [key]] of entries.entries()) {
677+
const result = results[index]
678+
if (result.status === "fulfilled") {
679+
committed.push(key)
680+
continue
681+
}
682+
// The first failure is the cause, even when it was rejected without a reason.
683+
if (!hasCause) {
684+
cause = result.reason
685+
hasCause = true
686+
}
687+
failed.push(key)
688+
}
689+
if (failed.length > 0) throw new SettingsWriteError(committed, failed, cause)
561690
}
562691

563692
/**

0 commit comments

Comments
 (0)