Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion browser/data-browser/src/chunks/Demo/demoWorkspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
commits,
server,
classes,
Datatype,
type JSONValue,
type Resource,
type Store,
Expand Down Expand Up @@ -170,9 +171,11 @@ export async function createDemoMessage(
isA: [dataBrowser.classes.message, ...(opts.extraClasses ?? [])],
propVals: {
[core.properties.description]: opts.text,
[DEMO_SPEAKER]: opts.author,
},
});
// The speaker property is local to the demo and not published on
// atomicdata.dev, so validating it would fetch a 404 for every message.
await message.set(DEMO_SPEAKER, opts.author, true, Datatype.STRING);
await message.save();

return message;
Expand Down
49 changes: 49 additions & 0 deletions browser/data-browser/src/chunks/Demo/startDemo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, it, vi } from 'vitest';
import type { Store } from '@tomic/react';

vi.mock('./DemoDirector', () => ({ DemoDirector: class {} }));
vi.mock('./demoWorkspace', () => ({
createDemoWorkspace: vi.fn(),
saveDemoManifest: vi.fn(),
}));
vi.mock('./guestAgent', () => ({ ensureAgentForDemo: vi.fn() }));

const { cleanupDemoDrive } = await import('./startDemo');

const GUEST = 'atomic:agent:guest';
const DRIVE = 'atomic:demo-drive';
const TEAM = 'atomic:team-table';
const ROW = 'atomic:team-row';

/** A store whose local database holds a demo drive, its team table, a
* teammate row and the guest's own profile row (the agent resource). */
function demoStore() {
const children: Record<string, string[]> = {
[DRIVE]: [TEAM],
[TEAM]: [ROW, GUEST],
};
const removed: string[] = [];
const store = {
getAgent: () => ({ subject: GUEST }),
queryLocalDb: async ({ value }: { property: string; value: string }) => ({
subjects: children[value] ?? [],
}),
removeResource: (subject: string) => removed.push(subject),
unregisterLocalOnlyDrive: vi.fn(),
getResource: async () => ({ get: () => undefined }),
};

return { store: store as unknown as Store, removed };
}

describe('cleanupDemoDrive', () => {
it('removes the demo drive and what it holds, but not the guest identity', async () => {
const { store, removed } = demoStore();

await cleanupDemoDrive(store, DRIVE);

expect(removed.sort()).toEqual([DRIVE, ROW, TEAM].sort());
expect(removed).not.toContain(GUEST);
expect(store.unregisterLocalOnlyDrive).toHaveBeenCalledWith(DRIVE);
});
});
21 changes: 20 additions & 1 deletion browser/data-browser/src/chunks/Demo/startDemo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ function saveDemoDrives(drives: string[]): void {
localStorage.setItem(DEMO_DRIVES_KEY, JSON.stringify(drives));
}

/** Where demo setup is, so a report of a stalled setup can say where. */
export type DemoSetupStep = 'storage' | 'identity' | 'cleanup' | 'workspace';

/**
* Start the demo: mint a guest agent if nobody is signed in, tear down
* EVERY previous demo drive, build a FRESH workspace, start the
Expand All @@ -39,16 +42,23 @@ function saveDemoDrives(drives: string[]): void {
* demo drive this browser ever created (tracked in localStorage), not
* just the last one, covering runs whose manifest was lost.
*/
export async function startDemoWorkspace(store: Store): Promise<DemoManifest> {
export async function startDemoWorkspace(
store: Store,
onStep: (step: DemoSetupStep) => void = () => {},
): Promise<DemoManifest> {
onStep('storage');
await enableLoro();

onStep('identity');
const isGuest = await ensureAgentForDemo(store);

activeDirector?.stop();
activeDirector = undefined;

onStep('cleanup');
await cleanupAllDemoDrives(store);

onStep('workspace');
const manifest = await createDemoWorkspace(store, { guest: isGuest });

saveDemoDrives([manifest.drive]);
Expand Down Expand Up @@ -121,6 +131,15 @@ export async function cleanupDemoDrive(
frontier = next;
}

// A guest's profile row is the guest's own agent resource (see
// `createGuestProfile`), so it is parented under this drive's team
// table. The identity outlives the demo: removing it would tombstone the
// agent for the rest of the session, and a later save on it (keeping a
// template links the guest's home on it) would have nothing to save to.
// The next demo run rewrites the row in place.
const agent = store.getAgent()?.subject;
if (agent) doomed.delete(agent);

for (const subject of doomed) {
store.removeResource(subject, false);
}
Expand Down
21 changes: 21 additions & 0 deletions browser/data-browser/src/chunks/Templates/demoSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,24 @@ export function readTemplateDemo(): TemplateDemo | undefined {
/* Storage is unavailable or a previous version wrote invalid data. */
}
}

/** The interactive demo's manifest, reduced to what the chrome needs. The
* full manifest lives in the demo chunk; reading these two fields here keeps
* that chunk out of the main bundle. */
export function readInteractiveDemo():
| { drive: string; welcomeDoc: string }
| undefined {
try {
const value = JSON.parse(
localStorage.getItem('atomic.demoWorkspace') ?? 'null',
);
if (
value &&
typeof value.drive === 'string' &&
typeof value.welcomeDoc === 'string'
)
return { drive: value.drive, welcomeDoc: value.welcomeDoc };
} catch {
/* Storage is unavailable or a previous version wrote invalid data. */
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,33 @@ import type { Store } from '@tomic/react';
import { prepareTemplateDrive } from './prepareTemplateDrive';
import { fetchManagedInfo } from '../../helpers/managedServer';
import { getManagedEnrollments } from '../../helpers/managed/enrollmentApi';
import { getManagedAccount } from '../../helpers/managed/session';

vi.mock('../../helpers/managedServer', () => ({
fetchManagedInfo: vi.fn(),
}));
vi.mock('../../helpers/managed/enrollmentApi', () => ({
getManagedEnrollments: vi.fn(),
}));
vi.mock('../../helpers/managed/session', () => ({
getManagedAccount: vi.fn(),
}));

const home = 'did:ad:home';
const node = 'https://node1.example';

function fixture(local = false) {
function fixture(local = false, guest = false) {
const store = {
getServerUrl: () => node,
getAgent: () => ({ privateDriveSubject: async () => home }),
getAgent: () => ({
subject: 'did:ad:agent:owner',
privateDriveSubject: async () => home,
}),
// Real accounts get a personal drive at signup; demo guests never do.
getResource: async () => ({ get: () => (guest ? undefined : home) }),
isLocalOnlyDrive: () => local,
makeDriveLocal: vi.fn(async () => {}),
registerLocalOnlyDrive: vi.fn(),
};

return store as unknown as Store & typeof store;
Expand All @@ -33,6 +43,8 @@ beforeEach(() => {
});
vi.mocked(getManagedEnrollments).mockReset();
vi.mocked(getManagedEnrollments).mockResolvedValue([]);
vi.mocked(getManagedAccount).mockReset();
vi.mocked(getManagedAccount).mockResolvedValue({ email: 'a@example.com' });
});

describe('template drive preparation', () => {
Expand Down Expand Up @@ -92,4 +104,24 @@ describe('template drive preparation', () => {
'Missing attachment',
);
});

it('lets a demo guest create a browser-only drive without an account', async () => {
const store = fixture(false, true);
vi.mocked(getManagedAccount).mockResolvedValue(null);
await prepareTemplateDrive(store);
expect(getManagedEnrollments).not.toHaveBeenCalled();
// Nothing to verify on the server: a guest's home was never there.
expect(store.makeDriveLocal).not.toHaveBeenCalled();
expect(store.registerLocalOnlyDrive).toHaveBeenCalledExactlyOnceWith(home);
});

it('still asks a signed-out account to sign in', async () => {
const store = fixture();
vi.mocked(getManagedAccount).mockResolvedValue(null);
vi.mocked(getManagedEnrollments).mockRejectedValue(
new Error('Sign in to check Cloud Server hosting.'),
);
await expect(prepareTemplateDrive(store)).rejects.toThrow('Sign in');
expect(store.makeDriveLocal).not.toHaveBeenCalled();
});
});
18 changes: 18 additions & 0 deletions browser/data-browser/src/chunks/Templates/prepareTemplateDrive.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { Store } from '@tomic/react';
import { fetchManagedInfo } from '../../helpers/managedServer';
import { getManagedEnrollments } from '../../helpers/managed/enrollmentApi';
import { localAgentIsDisposable } from '../../helpers/managed/reconcile';
import { getManagedAccount } from '../../helpers/managed/session';
import { prepareDriveSharing } from '../../helpers/managed/prepareDriveSharing';
import { sameOrigin } from '../../helpers/serverUrl';

Expand All @@ -15,6 +17,22 @@ export async function prepareTemplateDrive(store: Store): Promise<void> {
const home = await agent.privateDriveSubject();
if (store.isLocalOnlyDrive(home)) return;

// A demo guest has no account, so nothing can be hosted for it, and asking
// the control plane only fails with "Sign in". Its home was never on the
// server either (only a real signup creates one there), so there is no
// server copy to verify against: asking the node for its inventory just
// times out. Its home lives on this device only. A real account without a
// session still has to sign in: its home may be hosted.
if (
agent.subject &&
!(await getManagedAccount()) &&
(await localAgentIsDisposable(store, agent.subject))
) {
store.registerLocalOnlyDrive(home);

return;
}

const enrollments = await getManagedEnrollments(true);
const enrolledHereOrUnknown = enrollments.some(
enrollment =>
Expand Down
Loading