Skip to content

Commit 9d90c5a

Browse files
committed
feat(signals): restore a past value from a signal's history
Each value-history entry of a component's own writable signal, linked signal or model gets a Restore button. The page keeps the raw value of each kept history entry and writes that exact value back with set(), so large values, values with masked secrets and values that are not JSON restore exactly. Only the redacted result goes over the wire. A write locator matches graph nodes to the component's own fields. The restore is refused when the field cannot be matched, the entry is gone or the value changed in place. It is gated like component edits: a live, non-native page with actions.components allowed. Refs #367
1 parent 190248c commit 9d90c5a

16 files changed

Lines changed: 1342 additions & 21 deletions

File tree

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
2+
import type { DevframeRpcClient } from 'devframe/client';
3+
import { afterEach, describe, expect, it, vi } from 'vitest';
4+
import { SignalInspector } from '../pages/signal-inspector';
5+
6+
const at = (s: number) => new Date(2026, 0, 1, 10, 0, s).getTime();
7+
8+
const graph = {
9+
pageId: 'p1',
10+
nodes: [
11+
{
12+
id: '1',
13+
kind: 'signal',
14+
label: 'query',
15+
epoch: 2,
16+
value: 'c',
17+
locator: { id: 'c1', key: 'query' },
18+
},
19+
{ id: '2', kind: 'computed', label: 'shout', epoch: 2, value: 'C' },
20+
],
21+
edges: [],
22+
component: { id: 'c1', name: 'App', tag: 'app-root', path: 'app-root' },
23+
history: {
24+
'1': [
25+
{ epoch: 0, value: 'a', at: at(1), source: 'initial' },
26+
{ epoch: 1, value: 'b', at: at(2), source: 'write' },
27+
{ epoch: 2, value: 'c', at: at(3), source: 'write' },
28+
],
29+
'2': [
30+
{ epoch: 1, value: 'A', at: at(1), source: 'initial' },
31+
{ epoch: 2, value: 'C', at: at(3), source: 'sample' },
32+
],
33+
},
34+
};
35+
36+
async function render(
37+
meta: Record<string, unknown> = {},
38+
call: (name: string, args?: unknown) => Promise<unknown> = () => Promise.resolve([]),
39+
page: Record<string, unknown> = { pageId: 'p1', roots: [] },
40+
) {
41+
const state = (value: unknown) => Promise.resolve({ value: () => value, on: () => () => {} });
42+
const rpc = {
43+
call,
44+
callEvent: () => Promise.resolve(),
45+
sharedState: (name: string) =>
46+
state(
47+
name === 'signal-graph'
48+
? { graph, pages: { p1: graph } }
49+
: name === 'component-tree'
50+
? { pages: { p1: page } }
51+
: { pages: {} },
52+
),
53+
};
54+
const fixture = TestBed.createComponent(SignalInspector);
55+
fixture.componentRef.setInput('rpc', {
56+
connectionMeta: meta,
57+
scope: () => ({ rpc }),
58+
} as unknown as DevframeRpcClient);
59+
for (let i = 0; i < 3; i++) {
60+
await new Promise((resolve) => setTimeout(resolve));
61+
await fixture.whenStable();
62+
}
63+
return fixture;
64+
}
65+
66+
async function select(fixture: ComponentFixture<SignalInspector>, id: string) {
67+
fixture.componentInstance.selectedId.set(id);
68+
await fixture.whenStable();
69+
fixture.detectChanges();
70+
}
71+
72+
const restoreButtons = (fixture: ComponentFixture<unknown>) =>
73+
Array.from(
74+
(fixture.nativeElement as HTMLElement).querySelectorAll<HTMLButtonElement>('button.restore'),
75+
);
76+
77+
const text = (fixture: ComponentFixture<unknown>) =>
78+
(fixture.nativeElement as HTMLElement).textContent?.replace(/\s+/g, ' ') ?? '';
79+
80+
describe('Restore on signal history', () => {
81+
afterEach(() => TestBed.resetTestingModule());
82+
83+
it('offers a named Restore button on each past entry of a located signal', async () => {
84+
const fixture = await render();
85+
await select(fixture, '1');
86+
const buttons = restoreButtons(fixture);
87+
// The newest entry is the current value, so it has no button.
88+
expect(buttons.map((b) => b.getAttribute('aria-label'))).toEqual([
89+
'Restore value from 10:00:02.000',
90+
'Restore value from 10:00:01.000',
91+
]);
92+
expect(buttons.every((b) => b.type === 'button' && !b.disabled)).toBe(true);
93+
});
94+
95+
it('sends the entry to the page and shows the answer', async () => {
96+
const call = vi.fn(async (name: string) =>
97+
name === 'request-signal-restore' ? { ok: true, key: 'query' } : [],
98+
);
99+
const fixture = await render({}, call);
100+
await select(fixture, '1');
101+
restoreButtons(fixture)[0].click();
102+
await fixture.whenStable();
103+
fixture.detectChanges();
104+
expect(call).toHaveBeenCalledWith('request-signal-restore', {
105+
pageId: 'p1',
106+
request: { component: 'c1', node: '1', epoch: 1 },
107+
});
108+
const status = (fixture.nativeElement as HTMLElement).querySelector('.restore-result');
109+
expect(status?.getAttribute('role')).toBe('status');
110+
expect(status?.textContent?.trim()).toBe('Restored query to the value from 10:00:02.000.');
111+
});
112+
113+
it('shows the page refusal as an error', async () => {
114+
const fixture = await render({}, async (name) =>
115+
name === 'request-signal-restore' ? { error: 'Epoch 1 is no longer kept.' } : [],
116+
);
117+
await select(fixture, '1');
118+
restoreButtons(fixture)[0].click();
119+
await fixture.whenStable();
120+
fixture.detectChanges();
121+
const status = (fixture.nativeElement as HTMLElement).querySelector('.restore-result');
122+
expect(status?.classList.contains('restore-error')).toBe(true);
123+
expect(status?.textContent?.trim()).toBe('Epoch 1 is no longer kept.');
124+
});
125+
126+
it('has no Restore for a node without a locator', async () => {
127+
const fixture = await render();
128+
await select(fixture, '2');
129+
expect(text(fixture)).toContain('Value history');
130+
expect(restoreButtons(fixture)).toHaveLength(0);
131+
});
132+
133+
it('hides Restore with a reason when component writes are off', async () => {
134+
const fixture = await render({ configs: { pangular: { actions: { components: false } } } });
135+
await select(fixture, '1');
136+
expect(restoreButtons(fixture)).toHaveLength(0);
137+
expect(text(fixture)).toContain(
138+
'Restore is off. Editing component properties and signals is turned off in the devtools config (actions.components).',
139+
);
140+
});
141+
142+
it('hides Restore in a saved report and on a native page', async () => {
143+
const report = await render({ backend: 'static' });
144+
await select(report, '1');
145+
expect(restoreButtons(report)).toHaveLength(0);
146+
expect(text(report)).toContain('Restore is off. A saved report cannot write to the app.');
147+
TestBed.resetTestingModule();
148+
149+
const native = await render({}, undefined, {
150+
pageId: 'p1',
151+
roots: [],
152+
platform: 'nativescript',
153+
});
154+
await select(native, '1');
155+
expect(restoreButtons(native)).toHaveLength(0);
156+
expect(text(native)).toContain('Restore is off. It needs the app open in a browser.');
157+
});
158+
});

‎app/src/pages/signal-inspector.ts‎

Lines changed: 137 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ import {
1616
import { DatePipe, JsonPipe, NgTemplateOutlet } from '@angular/common';
1717
import type { DevframeRpcClient } from 'devframe/client';
1818
import { pickPage, type ReportedPage } from '../live-pages';
19+
import { actionAllowed, actionBlockedMessage } from '../devtools-config';
20+
import { isNativePage } from '../native-page';
21+
import { isStaticReport } from '../rpc';
1922
import { hostPageId } from '../page-id';
2023
import { angularPageFor, injectAngularPages } from '../angular-pages';
2124
import { AngularUnavailable } from '../ui/angular-unavailable';
@@ -34,6 +37,14 @@ interface SignalNode {
3437
changes?: number;
3538
/** Created by Angular's own code, hidden unless the user shows framework signals. */
3639
framework?: boolean;
40+
/** The component field that holds this writable signal, so history entries can be restored. */
41+
locator?: { id: string; key: string };
42+
}
43+
44+
interface RestoreResult {
45+
ok?: boolean;
46+
key?: string;
47+
error?: string;
3748
}
3849

3950
interface SignalEdge {
@@ -359,6 +370,20 @@ const KIND_COLORS: Record<string, string> = {
359370
@if (selectedHistory().length) {
360371
<h4 [id]="'history-heading-' + id">{{ label }}</h4>
361372
<p class="history-summary">{{ historySummary(id) }}</p>
373+
@let restoreNode = restorable(id);
374+
@if (restoreNode) {
375+
@if (restoreBlocked(); as reason) {
376+
<p class="hint">Restore is off. {{ reason }}</p>
377+
}
378+
<p
379+
class="restore-result"
380+
role="status"
381+
[class.has-text]="restoreResult()?.id === id"
382+
[class.restore-error]="restoreResult()?.id === id && restoreResult()?.error"
383+
>
384+
{{ restoreResult()?.id === id ? restoreResult()?.text : '' }}
385+
</p>
386+
}
362387
<ol
363388
class="history scroll-box"
364389
tabindex="0"
@@ -375,6 +400,18 @@ const KIND_COLORS: Record<string, string> = {
375400
@if (change.missed) {
376401
<span class="missed">{{ change.missed }} earlier not captured</span>
377402
}
403+
@if (restoreNode && !restoreBlocked() && !$first) {
404+
@let time = change.at | date: 'HH:mm:ss.SSS';
405+
<button
406+
type="button"
407+
class="restore"
408+
[attr.aria-label]="'Restore value from ' + time"
409+
[attr.aria-disabled]="restoring() || null"
410+
(click)="restore(restoreNode, change, time ?? '')"
411+
>
412+
Restore
413+
</button>
414+
}
378415
</span>
379416
<pre>{{ change.value | json }}</pre>
380417
@if (change.stack?.length) {
@@ -1425,6 +1462,49 @@ const KIND_COLORS: Record<string, string> = {
14251462
.missed {
14261463
color: var(--warn);
14271464
}
1465+
.restore {
1466+
margin-left: auto;
1467+
height: 22px;
1468+
padding: 0 8px;
1469+
border: 1px solid var(--border-strong);
1470+
border-radius: var(--radius-sm);
1471+
background: var(--surface-2);
1472+
color: var(--text);
1473+
font: inherit;
1474+
font-size: 11px;
1475+
font-weight: 500;
1476+
cursor: pointer;
1477+
transition:
1478+
background-color 150ms var(--ease),
1479+
border-color 150ms var(--ease);
1480+
}
1481+
.restore:hover:not([aria-disabled='true']) {
1482+
background: var(--surface-3);
1483+
border-color: var(--accent-line);
1484+
}
1485+
.restore[aria-disabled='true'] {
1486+
opacity: 0.6;
1487+
cursor: progress;
1488+
}
1489+
.restore:focus-visible {
1490+
@include m.focus-ring(-2px);
1491+
}
1492+
.restore-result {
1493+
margin: 0;
1494+
font-size: 12px;
1495+
color: var(--text-2);
1496+
}
1497+
.restore-result.has-text {
1498+
margin-bottom: 8px;
1499+
}
1500+
.restore-result.restore-error {
1501+
color: var(--danger-text);
1502+
}
1503+
@media (prefers-reduced-motion: reduce) {
1504+
.restore {
1505+
transition: none;
1506+
}
1507+
}
14281508
.graph-section,
14291509
.watched {
14301510
margin-bottom: 16px;
@@ -1631,7 +1711,10 @@ export class SignalInspector {
16311711
/** Counts graph loads, so only the newest one applies its result. */
16321712
private graphLoad = 0;
16331713
private readonly treePages = signal<
1634-
Record<string, { roots?: LiveNode[]; reportedAt?: number; title?: string; url?: string }>
1714+
Record<
1715+
string,
1716+
{ roots?: LiveNode[]; reportedAt?: number; title?: string; url?: string; platform?: string }
1717+
>
16351718
>({});
16361719
private readonly graphState = signal<{
16371720
graph: SignalGraph | null;
@@ -1799,6 +1882,59 @@ export class SignalInspector {
17991882
return id ? [...(this.graph()?.history?.[id] ?? [])].reverse() : [];
18001883
});
18011884

1885+
/**
1886+
* Why history entries cannot be restored on the shown page, or '' when they
1887+
* can: the same gate as component edits (a live browser page with
1888+
* `actions.components` on).
1889+
*/
1890+
readonly restoreBlocked = computed(() => {
1891+
const client = this.rpc();
1892+
if (isStaticReport(client)) return 'A saved report cannot write to the app.';
1893+
const pageId = this.graph()?.pageId;
1894+
if (isNativePage(pageId ? this.treePages()[pageId] : null)) {
1895+
return 'It needs the app open in a browser.';
1896+
}
1897+
if (!actionAllowed(client, 'components')) return actionBlockedMessage('components');
1898+
return '';
1899+
});
1900+
readonly restoring = signal(false);
1901+
readonly restoreResult = signal<{ id: string; text: string; error: boolean } | null>(null);
1902+
1903+
/** The node with this id when its history can be restored: a writable field of the shown component. */
1904+
restorable(id: string): SignalNode | null {
1905+
const g = this.graph();
1906+
const node = g?.nodes.find((n) => n.id === id);
1907+
return node?.locator && g?.component && node.locator.id === g.component.id ? node : null;
1908+
}
1909+
1910+
/** Writes the value the page kept for this entry back to the signal. */
1911+
async restore(node: SignalNode, change: SignalChange, time: string) {
1912+
const client = this.rpc();
1913+
const pageId = this.graph()?.pageId;
1914+
const locator = node.locator;
1915+
if (!client || !pageId || !locator || this.restoring() || this.restoreBlocked()) return;
1916+
this.restoring.set(true);
1917+
let result: RestoreResult;
1918+
try {
1919+
result = ((await client.scope('pangular').rpc.call('request-signal-restore', {
1920+
pageId,
1921+
request: { component: locator.id, node: node.id, epoch: change.epoch },
1922+
})) ?? {}) as RestoreResult;
1923+
} catch {
1924+
result = { error: 'The devtools server did not answer. Try again.' };
1925+
}
1926+
this.restoring.set(false);
1927+
this.restoreResult.set(
1928+
result.ok
1929+
? {
1930+
id: node.id,
1931+
text: `Restored ${result.key ?? locator.key} to the value from ${time}.`,
1932+
error: false,
1933+
}
1934+
: { id: node.id, text: result.error ?? 'The page did not restore it.', error: true },
1935+
);
1936+
}
1937+
18021938
/** Why a writable signal has no exact set entries, when the panel can tell. */
18031939
readonly writeHint = computed(() => {
18041940
const node = this.selectedNode();

‎apps/docs/src/content/getting-started/configuration.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ Actions are the writes that the panel and agents make to your app or the server.
155155
| `actions.ngrx` | `true` | Restoring NgRx state from the change log and dispatching `@ngrx/store` actions. Drops the `dispatch-ngrx-action` and `restore-ngrx-state` agent tools. |
156156
| `actions.http` | `true` | Editing fault injection rules and SSR overrides, and clearing the HTTP timeline. Drops the `set-http-rule`, `remove-http-rule`, `set-ssr-override` and `remove-ssr-override` agent tools and HTTP clearing in `clear-recordings`. |
157157
| `actions.analog` | `true` | The Analog request playground and clearing server calls. Drops the `analog-call-api` agent tool and Analog clearing in `clear-recordings`. |
158-
| `actions.components` | `true` | Editing component inputs, properties and writable signals from the **Components** tab. Drops the `set-component-property` and `set-signal` agent tools. |
158+
| `actions.components` | `true` | Editing component inputs, properties and writable signals from the **Components** tab, and **Restore** in the **Signals** value history. Drops the `set-component-property` and `set-signal` agent tools. |
159159
| `actions.tanstackQuery` | `true` | Invalidating and refetching a query from the **Queries** tab. Drops the `query-action` agent tool. |
160160
| `actions.plugins` | `true` | Every plugin's page actions, from the **Plugins** tab and from its tools. Drops the plugin tools that are not `read`. |
161161
| `actions` | `true` | All of the above. |

‎apps/docs/src/content/inspectors/signals.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ Click an entry under **Dependencies (producers)** or **Consumers** to open that
8080

8181
### Resources
8282

83-
Angular builds each `resource()`, `httpResource()` and `rxResource()` from several internal signals, labeled `Resource#name.value`, `Resource#name.state` and so on. The tab folds them into one card under **Resources**, and leaves them out of the **Signals** list. Each card shows:
83+
Angular builds each `resource()`, `httpResource()` and `rxResource()` from several internal signals, labeled `Resource#name.value`, `Resource#name.state` and so on. The tab folds them into one card under **Resources**, and leaves them out of the **Signals** list. Angular labels these signals from 21.0.1. On earlier versions they have no names, so the tab shows no **Resources** cards and lists them as unnamed nodes. Each card shows:
8484

8585
| Field | Meaning |
8686
| --------------- | ----------------------------------------------------------------------------------------- |
@@ -109,6 +109,22 @@ When values change faster than the overlay reads the page, an entry says how man
109109

110110
The line above the list counts the changes, for example **3 changes recorded, newest first.** The list keeps the last 50 entries. Past that, the line says **showing the last 50**, and the count keeps growing.
111111

112+
### Restore a past value
113+
114+
Each entry but the newest has a **Restore** button when the signal is a `signal()`, `linkedSignal()` or `model()` field of the shown component. Click it to set the signal back to that entry's value with `.set()`, the same write `pangular:set-signal` makes. A line above the list says what was restored, or why the page refused.
115+
116+
The page writes the value it kept when it recorded the entry, not the copy the panel shows. A value the history cut to fit, or showed with masked secrets, comes back whole, and the value never leaves the page.
117+
118+
| Case | What happens |
119+
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
120+
| `computed()`, a signal input, or a signal of a service | No **Restore** button. |
121+
| Unnamed signal | **Restore** shows once the page tells the field apart from the other fields by value and version. |
122+
| Entry past the last 50, or the page reloaded | The page refuses: the entry is no longer in its history. |
123+
| The app changed the value in place after it was recorded | The page refuses, because the value no longer matches the entry. |
124+
| `actions.components` is `false`, a saved report or a native app | No **Restore** button, and a note says why. |
125+
126+
See [`actions`](../getting-started/configuration.md#actions) for the option.
127+
112128
### Watched signals
113129

114130
Click **Watch** on a card to watch that signal. The page then logs each of its changes to the browser console, as `[pangular] Signal count set to 3`, and the **Watched** section above the list shows it with its value, its change count and a **Stop watching** button. **Recent changes** lists the last 20 changes of every watched signal in the graph, newest first.

0 commit comments

Comments
 (0)