blob: 6a65d9ade5e835d4ce3a9b8615f3fd9987cea0b4 [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { cleanup, effect, keymap, platform, Scroll, signal, Text, View, type JSX } from 'nsh';
import { Button, Input } from 'nsh/base';
import {
formatCompactTime,
mirrorPage,
snippetRuns,
type MirrorReader,
type MirrorApproval,
type MirrorMessage,
type MirrorProjects,
type MirrorSearch,
type MirroredSession,
type MirrorSessions,
type MirrorTranscript,
type ServerUiTheme,
type SessionRef,
} from './makaServer';
type Labels = {
title: string;
offline: string;
synced(timestamp: number): string;
readOnly(computer: string): string;
pendingApprovals: string;
user: string;
assistant: string;
connect?: string;
projects: string;
sessions: string;
search: string;
clear: string;
clearSearch: string;
next: string;
back: string;
empty: string;
tooLarge: string;
loadFailed: string;
};
const MAX_SILENT_CONFLICT_RETRIES = 2;
export function MirrorBrowser(props: {
rootId?: string;
session(): SessionRef | null;
open(session: SessionRef): void;
/** Shown only when the user explicitly paused/disconnected a computer and may resume it. */
connect?(rootId: string): void;
hostName(rootId: string): string;
read: MirrorReader;
labels(): Labels;
theme(): ServerUiTheme<JSX.Element>;
renderMarkdown?(text: string, message: MirrorMessage): JSX.Element;
formatError?(cause: unknown): string;
/** Suppress outer chrome padding/header when hosted inside a ModalDialog. */
embedded?: boolean;
}) {
const touch = platform.os === 'ios' || platform.os === 'android';
const terminal = platform.idiom === 'terminal';
const cursor = signal<unknown | null>(null);
const lastSynced = signal<number | null>(null);
const messages = signal<MirrorMessage[]>([]);
const approvals = signal<MirrorApproval[]>([]);
const sessions = signal<MirroredSession[]>([]);
const projects = signal<MirrorProjects['projects']>([]);
const project = signal<{
rootId: string;
projectId: string;
name: string;
repoIdentity: string | null;
} | null>(null);
const hits = signal<MirrorSearch['hits']>([]);
const searched = signal('');
const query = signal('');
const title = signal('');
const failure = signal('');
const busy = signal(false);
const scrollMetrics = signal({ offsetY: 0, contentHeight: 0, viewportHeight: 0 });
effect(() => {
if (searched() || cursor() === null || busy() || failure()) return;
const { offsetY, contentHeight, viewportHeight } = scrollMetrics();
if (viewportHeight > 0 && contentHeight - viewportHeight - offsetY <= 240) {
void load(true);
}
});
const computer = () => props.session()?.rootId ?? props.rootId;
const insetX = () => (props.embedded ? 0 : 16);
const formatTime = (ms: number) => formatCompactTime(ms);
const describeError = (cause: unknown) =>
props.formatError ? props.formatError(cause) : props.labels().loadFailed;
let generation = 0;
let unbindEscape: (() => void) | undefined;
cleanup(() => {
generation++;
unbindEscape?.();
});
const focusRing = () => {
const t = props.theme();
return terminal
? { backgroundColor: t.colors.raised }
: {
outlineStyle: 'solid' as const,
outlineWidth: 2,
outlineColor: t.colors.accent,
outlineOffset: -2,
};
};
const load = async (more = false) => {
const id = ++generation;
const session = props.session();
const checkout = project();
failure.set('');
busy.set(true);
try {
let next = more ? cursor() : undefined;
let attempt = 0;
let result: Awaited<ReturnType<typeof mirrorPage>> | null = null;
while (attempt <= MAX_SILENT_CONFLICT_RETRIES) {
result = await mirrorPage(
props.read,
session
? {
kind: 'transcript',
rootId: session.rootId,
sessionId: session.sessionId,
cursor: next,
}
: {
kind: 'sessions',
rootId: checkout?.rootId ?? props.rootId,
repoIdentity: checkout?.repoIdentity ?? undefined,
cursor: next,
},
);
if (id !== generation) return;
if (result.reply.kind !== 'changed') break;
next = undefined;
attempt++;
}
if (!result || id !== generation) return;
if (result.reply.kind === 'too_large') {
failure.set(props.labels().tooLarge);
return;
}
if (result.reply.kind !== 'ready') return;
const append = more && !result.restarted && attempt === 0;
if (session) {
const value = result.reply.value as MirrorTranscript;
cursor.set(value.nextCursor);
lastSynced.set(value.lastSyncedAtMs);
title.set(value.title);
approvals.set(value.pendingApprovals);
messages.set(append ? [...messages(), ...value.messages] : value.messages);
} else {
const value = result.reply.value as MirrorSessions;
const root = checkout?.rootId ?? props.rootId;
lastSynced.set(
value.coverage.find((source) => source.rootId === root)?.lastSyncedAtMs ?? null,
);
const items = checkout
? value.sessions.filter((row) => row.projectId === checkout.projectId)
: value.sessions;
cursor.set(value.nextCursor);
sessions.set(append ? [...sessions(), ...items] : items);
}
} catch (cause) {
if (id === generation) failure.set(describeError(cause));
} finally {
if (id === generation) busy.set(false);
}
};
effect(() => {
props.session();
props.rootId;
project();
cursor.set(null);
messages.set([]);
approvals.set([]);
sessions.set([]);
lastSynced.set(null);
title.set('');
hits.set([]);
searched.set('');
void load();
});
effect(() => {
if (props.session()) return;
let live = true;
cleanup(() => {
live = false;
});
void props
.read({ kind: 'projects' })
.then((reply) => {
if (live && reply.kind === 'ready') projects.set((reply.value as MirrorProjects).projects);
})
.catch((cause) => {
if (live) failure.set(describeError(cause));
});
});
const search = async (text = query().trim()) => {
if (!text) {
if (searched()) {
searched.set('');
hits.set([]);
void load();
}
return;
}
const id = ++generation;
searched.set(text);
hits.set([]);
busy.set(true);
failure.set('');
try {
let reply = await props.read({ kind: 'search', query: text });
if (id !== generation) return;
if (reply.kind === 'changed') {
reply = await props.read({ kind: 'search', query: text });
if (id !== generation) return;
}
if (reply.kind === 'ready') hits.set((reply.value as MirrorSearch).hits);
else if (reply.kind === 'too_large') failure.set(props.labels().tooLarge);
} catch (cause) {
if (id === generation) failure.set(describeError(cause));
} finally {
if (id === generation) busy.set(false);
}
};
const clearSearch = () => {
query.set('');
void search('');
};
const open = ({ rootId, sessionId, kind }: SessionRef) => props.open({ rootId, sessionId, kind });
const actionButton = (
label: string,
press: () => void,
options?: { subtle?: boolean; accessibilityLabel?: string },
) => (
<Button
accessibilityLabel={options?.accessibilityLabel ?? label}
disabled={busy()}
onPress={press}
style={{
minHeight: touch ? 44 : 32,
paddingHorizontal: 12,
borderRadius: props.theme().radius(8),
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
backgroundColor: options?.subtle ? 'transparent' : props.theme().colors.raised,
}}
hoverStyle={{
backgroundColor: options?.subtle
? props.theme().colors.raised
: props.theme().colors.pressed,
}}
activeStyle={{ backgroundColor: props.theme().colors.pressed }}
focusStyle={focusRing()}
disabledStyle={{ opacity: 0.4 }}
>
<Text
style={{
...props.theme().type.secondary,
fontWeight: '500',
color: options?.subtle ? props.theme().colors.secondary : props.theme().colors.text,
}}
>
{label}
</Text>
</Button>
);
const listRow = (
label: string,
press: () => void,
detail?: string | JSX.Element,
emphasized = false,
) => (
<Button
accessibilityLabel={label}
onPress={press}
style={{
minHeight: touch ? 44 : 32,
paddingHorizontal: 12,
paddingVertical: 8,
borderRadius: props.theme().radius(8),
alignItems: 'stretch',
justifyContent: 'center',
gap: 2,
}}
hoverStyle={{ backgroundColor: props.theme().colors.raised }}
activeStyle={{ backgroundColor: props.theme().colors.pressed }}
focusStyle={focusRing()}
>
<Text
style={[
{
...props.theme().type.body,
fontWeight: emphasized ? '500' : '400',
color: props.theme().colors.text,
},
{ numberOfLines: 1 },
]}
>
{label}
</Text>
<If when={typeof detail === 'string' && detail.length > 0}>
<Text
style={[
{
...props.theme().type.caption,
color: props.theme().colors.muted,
},
{ numberOfLines: 2 },
]}
>
{detail as string}
</Text>
</If>
<If when={detail !== undefined && typeof detail !== 'string'}>{detail as JSX.Element}</If>
</Button>
);
const sectionTitle = (label: string) => (
<Text
role="header"
style={{
...props.theme().type.section,
color: props.theme().colors.muted,
paddingHorizontal: 12,
paddingTop: 12,
paddingBottom: 4,
}}
>
{label}
</Text>
);
const renderSnippet = (rootId: string, snippet: string) => {
const runs = snippetRuns(snippet);
return (
<Text
style={[
{
...props.theme().type.caption,
color: props.theme().colors.muted,
},
{ numberOfLines: 2 },
]}
>
<Text>{props.hostName(rootId)} ยท </Text>
<Each of={runs}>
{(run) => (
<Text
style={
run().matched ? { color: props.theme().colors.text, fontWeight: '600' } : undefined
}
>
{run().text}
</Text>
)}
</Each>
</Text>
);
};
return (
<View
ref={(node) => {
unbindEscape?.();
unbindEscape =
!touch && node
? keymap.bind(
'escape',
() => {
if (!searched() && !query().trim()) return false;
clearSearch();
return true;
},
{ within: node },
)
: undefined;
}}
style={{ flex: 1, minHeight: 0 }}
>
<If when={!props.embedded}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
paddingHorizontal: insetX(),
paddingVertical: 12,
borderBottomWidth: props.theme().lineWidth,
borderBottomColor: props.theme().colors.line,
}}
>
<View style={{ flex: 1, minWidth: 0, gap: 2 }}>
<Text
style={[
{
...props.theme().type.title,
color: props.theme().colors.text,
},
{ numberOfLines: 1 },
]}
>
{title() || project()?.name || props.labels().title}
</Text>
<If when={computer() || lastSynced() !== null}>
<View
style={{ flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', gap: 8 }}
>
<If when={computer()}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>
<If when={!props.session()}>
<View
style={{
width: 6,
height: 6,
borderRadius: 3,
backgroundColor: props.theme().colors.warning,
}}
/>
</If>
<Text
style={{
...props.theme().type.caption,
fontWeight: '500',
color: props.session()
? props.theme().colors.secondary
: props.theme().colors.warning,
}}
>
{props.session()
? props.hostName(computer()!)
: `${props.hostName(computer()!)} ยท ${props.labels().offline}`}
</Text>
</View>
</If>
<If when={lastSynced() !== null}>
<Text
style={{ ...props.theme().type.caption, color: props.theme().colors.muted }}
>
{props.labels().synced(lastSynced()!)}
</Text>
</If>
</View>
</If>
</View>
<If when={computer() && props.connect && props.labels().connect}>
{actionButton(props.labels().connect!, () => props.connect?.(computer()!))}
</If>
</View>
</If>
<If when={!props.session()}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
gap: 8,
paddingHorizontal: insetX(),
paddingTop: props.embedded ? 0 : 12,
paddingBottom: 8,
}}
>
<Input
accessibilityLabel={props.labels().search}
placeholder={props.labels().search}
value={query()}
onChange={({ value }) => {
query.set(value);
if (!value.trim() && searched()) void search('');
}}
onSubmit={() => void search()}
style={{
flex: 1,
minHeight: touch ? 44 : 32,
paddingHorizontal: 12,
paddingVertical: touch ? 8 : 4,
borderRadius: props.theme().radius(8),
backgroundColor: props.theme().colors.field,
borderWidth: props.theme().lineWidth,
borderColor: props.theme().colors.line,
color: props.theme().colors.text,
placeholderColor: props.theme().colors.muted,
...props.theme().type.body,
}}
focusStyle={
terminal
? { backgroundColor: props.theme().colors.raised }
: { borderColor: props.theme().colors.accent }
}
/>
<If when={searched() || query().trim().length > 0}>
{actionButton(props.labels().clear, clearSearch, {
subtle: true,
accessibilityLabel: props.labels().clearSearch,
})}
</If>
</View>
</If>
<If when={failure()}>
<View
style={{
marginHorizontal: insetX(),
marginTop: 8,
padding: 12,
borderRadius: props.theme().radius(8),
backgroundColor: props.theme().colors.card,
}}
>
<Text
role="alert"
style={{
...props.theme().type.secondary,
color: props.theme().colors.danger,
}}
>
{failure()}
</Text>
</View>
</If>
<Scroll
style={{ flex: 1, minHeight: 0 }}
onLayout={({ bounds: frame }) =>
scrollMetrics.update((prev) => ({ ...prev, viewportHeight: frame.size.height }))
}
onScroll={(event) => {
scrollMetrics.set({
offsetY: event.offset.y,
contentHeight: event.contentSize.height,
viewportHeight: event.size.height,
});
}}
>
<View
onLayout={({ bounds: frame }) =>
scrollMetrics.update((prev) => ({ ...prev, contentHeight: frame.size.height }))
}
>
<If
when={props.session()}
else={
<View
style={{ paddingHorizontal: props.embedded ? 0 : 8, paddingVertical: 8, gap: 4 }}
>
<If
when={searched()}
else={
<>
<If when={project()}>
<View style={{ alignItems: 'flex-start', paddingHorizontal: 4 }}>
{actionButton(props.labels().back, () => project.set(null), {
subtle: true,
})}
</View>
</If>
<If when={!project()}>
<If
when={projects()
.flatMap((item) => item.checkouts)
.some((row) => !props.rootId || row.rootId === props.rootId)}
>
{sectionTitle(props.labels().projects)}
<Each
of={projects()
.flatMap((item) => item.checkouts)
.filter((row) => !props.rootId || row.rootId === props.rootId)}
key={({ rootId, projectId }) => JSON.stringify([rootId, projectId])}
>
{(row) =>
listRow(
row().name,
() => project.set(row()),
props.hostName(row().rootId),
true,
)
}
</Each>
</If>
</If>
{sectionTitle(props.labels().sessions)}
<Each
of={sessions()}
key={({ rootId, sessionId }) => JSON.stringify([rootId, sessionId])}
>
{(row) =>
listRow(row().title, () => open(row()), props.hostName(row().rootId))
}
</Each>
<If
when={!busy() && !failure() && sessions().length === 0 && cursor() === null}
>
<Text
style={{
...props.theme().type.secondary,
color: props.theme().colors.muted,
paddingHorizontal: 12,
paddingVertical: 16,
}}
>
{props.labels().empty}
</Text>
</If>
</>
}
>
<Each
of={hits()}
key={({ rootId, sessionId }) => JSON.stringify([rootId, sessionId])}
>
{(hit) =>
listRow(
hit().title,
() => open(hit()),
renderSnippet(hit().rootId, hit().snippet),
)
}
</Each>
<If when={!busy() && !failure() && hits().length === 0}>
<Text
style={{
...props.theme().type.secondary,
color: props.theme().colors.muted,
paddingHorizontal: 12,
paddingVertical: 16,
}}
>
{props.labels().empty}
</Text>
</If>
</If>
</View>
}
>
<View
style={{
width: '100%',
maxWidth: 760,
alignSelf: 'center',
paddingHorizontal: 16,
paddingVertical: 16,
gap: 12,
}}
>
<If when={approvals().length}>
<View
style={{
backgroundColor: props.theme().colors.card,
borderRadius: props.theme().radius(12),
padding: 12,
gap: 8,
}}
>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>
<View
style={{
width: 6,
height: 6,
borderRadius: 3,
backgroundColor: props.theme().colors.warning,
}}
/>
<Text
style={{
...props.theme().type.secondary,
fontWeight: '600',
color: props.theme().colors.text,
}}
>
{props.labels().pendingApprovals}
</Text>
</View>
<Each of={approvals()} key={(approval) => approval.requestId}>
{(approval) => (
<View style={{ gap: 2 }}>
<Text
style={{
...props.theme().type.body,
color: props.theme().colors.text,
}}
>
{approval().summary}
</Text>
<Text
style={{
...props.theme().type.caption,
color: props.theme().colors.muted,
}}
>
{formatTime(approval().createdAtMs)}
</Text>
</View>
)}
</Each>
</View>
</If>
<Each of={messages()} key={(message) => message.messageId}>
{(message) => {
const isUser = () => message().role === 'user';
return (
<View
style={{
alignSelf: isUser() ? 'flex-end' : 'stretch',
maxWidth: isUser() ? '85%' : '100%',
backgroundColor: isUser() ? props.theme().colors.card : undefined,
borderRadius: props.theme().radius(12),
paddingHorizontal: isUser() ? 12 : 4,
paddingVertical: isUser() ? 8 : 4,
gap: 4,
}}
>
<Text
style={{
...props.theme().type.caption,
color: props.theme().colors.muted,
}}
>
{isUser()
? props.labels().user
: message().role === 'assistant'
? props.labels().assistant
: message().role}
{message().createdAtMs != null &&
` ยท ${formatTime(message().createdAtMs!)}`}
</Text>
<If
when={!isUser() && Boolean(props.renderMarkdown)}
else={
<Text
style={{
...props.theme().type.body,
color: props.theme().colors.text,
userSelect: 'text',
}}
>
{message().bodyText}
</Text>
}
>
{props.renderMarkdown!(message().bodyText, message())}
</If>
</View>
);
}}
</Each>
</View>
</If>
</View>
</Scroll>
<If when={props.session()}>
<View
style={{
paddingHorizontal: insetX(),
paddingVertical: 12,
borderTopWidth: props.theme().lineWidth,
borderTopColor: props.theme().colors.line,
}}
>
<Input
accessibilityLabel={props.labels().readOnly(props.hostName(computer()!))}
placeholder={props.labels().readOnly(props.hostName(computer()!))}
disabled
multiline
value=""
style={{
minHeight: touch ? 44 : 32,
paddingHorizontal: 12,
paddingVertical: 8,
borderRadius: props.theme().radius(8),
borderWidth: props.theme().lineWidth,
borderColor: props.theme().colors.line,
backgroundColor: props.theme().colors.card,
color: props.theme().colors.secondary,
placeholderColor: props.theme().colors.secondary,
...props.theme().type.secondary,
}}
/>
</View>
</If>
</View>
);
}