Compare commits

...
9 Commits
Author SHA1 Message Date
Chad Curtis e3118bde09 Merge branch 'fix/evict-stale-tool-outputs' into 'main'
Draft: Evict large tool outputs from old messages before sending to API

See merge request soapbox-pub/shakespeare!112
2026-09-14 15:43:48 +00:00
Alex Gleason 9c48425c01 release: v9.16.2 2026-09-13 23:59:56 -05:00
Alex Gleason 344a73c6c3 Bring up the migration where somebody runs into it
Taking back a site had one way in: a button in Settings under Deploy, which said
the same thing to everybody and could not say whether anything was actually
waiting. On the gateway this was built for, two people out of eight hundred and
seven have used it.

The moment it is needed is the one somebody types a name they used to own, and
until now that moment did the opposite — the name came back taken and the button
went dead, because a name being held for its previous owner looks exactly like a
stranger's to anyone who does not ask. The gateway can now be asked, so the field
says the name is being held for them and offers the step that gets it back, in
place of a refusal with nowhere to go. The deploy dialog owns that list rather
than the field, because one recognised name is rarely all somebody has waiting.

npanel also refuses to add a name it is holding, saying to take it back instead —
a sentence that was being shown as a flat red alert with no way to act on it.
That refusal now carries the same offer.

And the settings card asks how many are waiting instead of guessing. It costs a
signature on a page nobody asked to sign on, which is the thing this deliberately
did not do before; the difference is that it is now two counted rows rather than
a read of every claimed deploy, and that the card says nothing at all unless
there is something to say. A card that cannot tell whether it applies to you is
one most people learn to ignore before it ever does.
2026-09-13 22:27:18 -05:00
Alex Gleason 4928819a0e ci: remove the ssh deploy job
deploy-nsite covers deployment now, and the rsync-over-ssh job was broken.
2026-09-13 21:33:48 -05:00
Alex Gleason 9d91542ec6 chore: sync package-lock version to 9.16.1 2026-09-13 21:25:45 -05:00
Alex Gleason 28d53e0100 release: v9.16.1 2026-09-13 21:24:10 -05:00
Alex Gleason dbb90df240 Let somebody deploy to a name they already own
The deploy form asked the gateway whether a name was free, which is not the
question it needed answered. A name somebody recovered in the migration is
theirs, is already serving their site, and came back "taken" — so the button
went dead with "That name is taken on shakespeare.wtf. Try another." about their
own site. Every name anyone took back was in this state: a hundred and four of
them for one person.

The form had an escape hatch for exactly this, and it was too narrow. It knew a
name was the user's own only if this project had deployed to it before, read out
of the project's own deploy record. A name recovered through the migration dialog
has no such record — the site was published, the hostname repointed, and nothing
about it ever went through this form.

So the question is asked properly instead. The anonymous ask happens first and is
usually the end of it, because a name somebody is picking is usually free. Only a
name that comes back taken is asked about again with a signature, which is the
one branch where the distinction exists and the one place worth spending a remote
signer on. A gateway too old to answer the second question leaves the first
answer standing, which is the behavior as it was.

The deploy itself never needed fixing: bindHostname asks for the host, is given
it, finds it already points where it is about to point, and returns. The form was
the only thing in the way.

Also compares the saved name trimmed, since that is what gets deployed — a
trailing space is not a different name, and typing one told people their own site
was somebody else's.
2026-09-13 19:25:30 -05:00
Chad Curtis 272e07795e Soften tool output eviction: keep prefix and require 2+ assistant turns
- Preserve the first 1 KiB of truncated tool output instead of replacing
  with a zero-information placeholder, so the model retains partial context
  and can decide whether to re-fetch.
- Only evict tool outputs that are at least 2 assistant turns old, not
  everything before the most recent assistant message. This prevents
  truncating outputs the model may still need on the immediately following
  turn in multi-step agentic workflows.
2026-04-10 19:44:19 -05:00
Chad Curtis ebd6fc9a10 Evict large tool outputs from old messages before sending to API
Add evictSeenToolOutputs following the same pattern as evictSeenImages. Tool
results larger than 1 KiB that the model has already seen and responded to are
replaced with a short placeholder at send time. This prevents multi-MB tool
output history from being re-sent on every subsequent turn in long agentic
sessions.
2026-04-10 19:29:28 -05:00
14 changed files with 490 additions and 55 deletions

No files matched your search

-18
View File
@@ -28,24 +28,6 @@ test:
- npm run build
- npm run test
deploy:
stage: deploy
rules:
- if: $CI_COMMIT_TAG
when: never
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH && $DEPLOY_SSH_KEY && $DEPLOY_TARGET
script:
- npm ci
- npm run build
- cp dist/index.html dist/404.html
- apt-get update -qq && apt-get install -y --no-install-recommends rsync openssh-client >/dev/null
- mkdir -p ~/.ssh && chmod 700 ~/.ssh
- echo "$DEPLOY_SSH_KEY" | tr -d '\r' > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
- ssh-keyscan -H "${DEPLOY_TARGET##*@}" >> ~/.ssh/known_hosts 2>/dev/null
- rsync -av --exclude=/sw.js --exclude=/index.html -e "ssh -i ~/.ssh/id_ed25519" dist/ "${DEPLOY_TARGET}:/"
- rsync -av -e "ssh -i ~/.ssh/id_ed25519" dist/index.html "${DEPLOY_TARGET}:/"
- rsync -av -e "ssh -i ~/.ssh/id_ed25519" dist/sw.js "${DEPLOY_TARGET}:/"
deploy-nsite:
stage: deploy
timeout: 10 minutes
+13
View File
@@ -1,5 +1,18 @@
# Changelog
## [9.16.2] - 2026-09-13
### Changed
- Deploy settings now says how many of your names are waiting to be taken back, and stays quiet when there are none
### Fixed
- Names you published before shakespeare.wtf changed hands are recognized as yours as you type them — the Deploy screen offers to hand them back instead of reporting them taken by somebody else
## [9.16.1] - 2026-09-13
### Fixed
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
## [9.16.0] - 2026-09-13
### Added
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "shakespeare.diy",
"version": "9.15.0",
"version": "9.16.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shakespeare.diy",
"version": "9.15.0",
"version": "9.16.1",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^8.1.0",
+1 -1
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "9.16.0",
"version": "9.16.2",
"type": "module",
"author": {
"name": "shakespeare.diy",
+13
View File
@@ -1,5 +1,18 @@
# Changelog
## [9.16.2] - 2026-09-13
### Changed
- Deploy settings now says how many of your names are waiting to be taken back, and stays quiet when there are none
### Fixed
- Names you published before shakespeare.wtf changed hands are recognized as yours as you type them — the Deploy screen offers to hand them back instead of reporting them taken by somebody else
## [9.16.1] - 2026-09-13
### Fixed
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
## [9.16.0] - 2026-09-13
### Added
+45 -2
View File
@@ -17,7 +17,8 @@ import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useGit } from '@/hooks/useGit';
import { NostrURI } from '@/lib/NostrURI';
import { Link } from 'react-router-dom';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { DeployProvider, NpanelProvider } from '@/contexts/DeploySettingsContext';
import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
import { NpanelDeployForm } from '@/components/deploy/NpanelDeployForm';
@@ -154,6 +155,24 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const [isNpanelFormValid, setIsNpanelFormValid] = useState(true);
/**
* The gateway whose held names are being looked at, if any.
*
* Owned here rather than by the name field, because what someone recognising
* one of their names wants is usually all of them, and because the dialog
* that hands them back outlives the field that prompted it.
*/
const [migratingProvider, setMigratingProvider] = useState<NpanelProvider | null>(null);
/**
* Whether the deploy failed because the gateway is holding the name for this
* user, which is a refusal with something to do about it.
*
* Read off the sentence npanel sent rather than a status code, since the 409
* it arrives as also covers a name somebody else holds and a name that is
* simply configured already.
*/
const heldName = error !== null && /being held for you/i.test(error);
// .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy
const [nsiteVfsConfig, setNsiteVfsConfig] = useState<NsiteVfsConfig | null>(null);
@@ -627,6 +646,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
onSiteTitleChange={handleNpanelSiteTitleChange}
onSiteDescriptionChange={handleNpanelSiteDescriptionChange}
onValidationChange={handleNpanelValidationChange}
onTakeBackSites={() => setMigratingProvider(npanelProvider)}
/>
);
}
@@ -978,7 +998,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
<AlertDescription className="space-y-2">
<p>{error}</p>
{/* The gateway refuses a name it is holding for this user
and says to take it back instead. Saying so and leaving
them to find out where is the worst of both. */}
{heldName && selectedProvider?.type === 'npanel' && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setMigratingProvider(selectedProvider)}
>
Take back your sites
</Button>
)}
</AlertDescription>
</Alert>
)}
@@ -1015,6 +1050,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
)}
</div>
)}
{migratingProvider && (
<NpanelMigrationDialog
open
onOpenChange={(open) => !open && setMigratingProvider(null)}
provider={migratingProvider}
/>
)}
</div>
);
}
+55 -6
View File
@@ -1,8 +1,10 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle, Check, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { checkNameAvailable, type NameAvailability } from '@/lib/deploy/NpanelAdapter';
/** How long typing has to stop before the gateway is asked about a name. */
@@ -23,17 +25,36 @@ interface NpanelDeployFormProps {
onSiteTitleChange: (title: string) => void;
onSiteDescriptionChange: (description: string) => void;
onValidationChange?: (isValid: boolean) => void;
/**
* Open the list of names this gateway is holding for whoever signs in.
*
* Passed in rather than opened here: recognising one name is usually not the
* whole of what somebody has waiting, and the dialog that hands them all back
* belongs above this field rather than inside it.
*/
onTakeBackSites?: () => void;
}
/** What the field is currently saying about the name in it. */
type NameState =
| { kind: 'empty' }
| { kind: 'mine' }
| { kind: 'waiting' }
| { kind: 'checking' }
| { kind: 'free' }
| { kind: 'unavailable'; message: string };
function describe(availability: NameAvailability, domain: string): NameState {
// A name the gateway recognises as this user's own. It is spoken for, and
// they are who it is spoken for by — deploying updates the site already
// there rather than taking anything.
if (availability.reason === 'mine') return { kind: 'mine' };
// Theirs from before the gateway, and still held for them. Not somewhere
// they can deploy until they take it back, which is a thing they can do
// from here rather than a wall.
if (availability.reason === 'waiting') return { kind: 'waiting' };
if (availability.available) return { kind: 'free' };
if (availability.reason === 'taken') {
@@ -55,7 +76,9 @@ export function NpanelDeployForm({
onSiteTitleChange,
onSiteDescriptionChange,
onValidationChange,
onTakeBackSites,
}: NpanelDeployFormProps) {
const { user } = useCurrentUser();
const [subdomain, setSubdomain] = useState(savedSubdomain || projectId);
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
@@ -87,12 +110,12 @@ export function NpanelDeployForm({
// The name this project already deployed to is not "taken" — it is theirs,
// and asking the gateway would truthfully say taken and alarm them about
// their own site.
const isOwnName = Boolean(savedSubdomain) && subdomain === savedSubdomain;
// their own site. Compared trimmed, since that is what gets deployed: a
// trailing space is not a different name.
const trimmed = subdomain.trim();
const isOwnName = Boolean(savedSubdomain) && trimmed === savedSubdomain;
useEffect(() => {
const trimmed = subdomain.trim();
if (!trimmed) {
setNameState({ kind: 'empty' });
return;
@@ -106,10 +129,14 @@ export function NpanelDeployForm({
const controller = new AbortController();
const timer = setTimeout(async () => {
// Signed, where there is someone to sign: a name this user owns but this
// project has never deployed to — one they took back through the
// migration — is otherwise indistinguishable from a stranger's.
const availability = await checkNameAvailable(
dashboardHost,
`${trimmed}.${domain}`,
controller.signal,
user?.signer,
);
if (!controller.signal.aborted) setNameState(describe(availability, domain));
}, AVAILABILITY_DEBOUNCE_MS);
@@ -118,12 +145,16 @@ export function NpanelDeployForm({
controller.abort();
clearTimeout(timer);
};
}, [subdomain, isOwnName, dashboardHost, domain]);
}, [trimmed, isOwnName, dashboardHost, domain, user?.signer]);
// A name still being checked stays deployable: the gateway decides for real
// when the deploy runs, and blocking the button on an in-flight request would
// make the form feel stuck on a slow connection.
const isValid = subdomain.trim() !== '' && nameState.kind !== 'unavailable';
// A name still waiting is not one to deploy to: the gateway would refuse,
// because taking it back is what turns it into somewhere this user can
// publish. The field says so and offers the step rather than the refusal.
const isValid =
subdomain.trim() !== '' && nameState.kind !== 'unavailable' && nameState.kind !== 'waiting';
useEffect(() => {
onValidationChange?.(isValid);
@@ -183,6 +214,24 @@ export function NpanelDeployForm({
</p>
)}
{nameState.kind === 'waiting' && (
<div className="rounded-md border border-dashed p-3 space-y-2">
<p className="text-sm">
<span className="font-mono">{subdomain.trim()}.{domain}</span> is being held for you.
</p>
<p className="text-xs text-muted-foreground">
You published it before {domain} moved to this gateway. It is being served from an
archive until you take it back, which publishes your own copy and points the name at
it.
</p>
{onTakeBackSites && (
<Button type="button" variant="outline" size="sm" onClick={onTakeBackSites}>
Take back your sites
</Button>
)}
</div>
)}
{nameState.kind === 'unavailable' && (
<div className="flex items-start gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
+35 -1
View File
@@ -3,7 +3,12 @@ import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import type { NpanelProvider } from '@/contexts/DeploySettingsContext';
import { fetchNpanelClaims, type NpanelClaim } from '@/lib/deploy/npanelApi';
import {
fetchNpanelClaimCount,
fetchNpanelClaims,
type NpanelClaim,
type NpanelClaimCount,
} from '@/lib/deploy/npanelApi';
import {
NAMED_SITE_KIND,
hasArchiveTitle,
@@ -156,3 +161,32 @@ export function useNpanelClaims(provider: NpanelProvider | undefined) {
},
});
}
/**
* How many names a gateway is holding for the logged-in user.
*
* Separate from {@link useNpanelClaims} because it is asked at a different
* moment and must cost a different amount. That one runs when somebody opens
* the dialog and has already decided to look; it reads every claimed deploy on
* the gateway and queries relays for this user's own events. This one runs
* because a settings page was opened, so it is one signature and two counted
* rows, and a gateway that cannot answer it says nothing rather than failing.
*/
export function useNpanelClaimCount(provider: NpanelProvider | undefined) {
const { user } = useCurrentUser();
return useQuery<NpanelClaimCount>({
queryKey: ['npanel-claim-count', provider?.dashboardHost, user?.pubkey],
enabled: Boolean(provider && user),
// Nobody's list of waiting names changes on its own, and every refetch
// costs a signature — which on a remote signer costs a round trip. Long
// enough that opening settings twice in a sitting asks once.
staleTime: 30 * 60 * 1000,
refetchOnWindowFocus: false,
retry: false,
queryFn: async ({ signal }) => {
if (!provider || !user) return { waiting: 0, taken: 0 };
return await fetchNpanelClaimCount(provider.dashboardHost, user.signer, signal);
},
});
}
+38
View File
@@ -396,6 +396,41 @@ export class SessionManager {
});
};
// Replace large tool result content with a truncated prefix for messages the
// model has already seen and responded to at least twice. Like evictSeenImages,
// this is a send-time transformation only — session.messages stays intact for
// the UI. We keep the first TOOL_OUTPUT_EVICTION_THRESHOLD bytes so the model
// retains partial context and can decide whether to re-fetch the full output.
const TOOL_OUTPUT_EVICTION_THRESHOLD = 1024; // 1 KiB
const TOOL_OUTPUT_MIN_ASSISTANT_TURNS = 2; // Only evict after 2+ assistant responses
const evictSeenToolOutputs = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
// Collect indices of all assistant messages.
const assistantIndices: number[] = [];
for (let i = 0; i < msgs.length; i++) {
if (msgs[i].role === 'assistant') {
assistantIndices.push(i);
}
}
// Need at least TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1 assistant messages:
// the ones that have "seen" the tool output, plus the current pending turn.
if (assistantIndices.length < TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1) return msgs;
// The eviction cutoff is the assistant message N turns back from the end.
// Tool results before this index have been processed by at least N assistant
// turns, so truncating them is safe.
const cutoffIdx = assistantIndices[assistantIndices.length - TOOL_OUTPUT_MIN_ASSISTANT_TURNS];
return msgs.map((msg, idx) => {
if (idx >= cutoffIdx) return msg;
if (msg.role !== 'tool') return msg;
if (typeof msg.content !== 'string') return msg;
if (msg.content.length <= TOOL_OUTPUT_EVICTION_THRESHOLD) return msg;
return { ...msg, content: msg.content.slice(0, TOOL_OUTPUT_EVICTION_THRESHOLD) + '\n\n[… truncated]' };
});
};
// Prepare messages for AI
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
@@ -403,6 +438,9 @@ export class SessionManager {
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
// Evict large tool outputs the model has already processed.
messages = evictSeenToolOutputs(messages);
// Evict images the model has already seen (all except the last user message).
// This is a send-time transformation only — session.messages stays intact for the UI.
messages = evictSeenImages(messages);
+77
View File
@@ -222,4 +222,81 @@ describe('checkNameAvailable', () => {
available: true,
});
});
it('asks again as the signer when a name comes back taken', async () => {
// "Taken" and "taken by you" are the same word to a stranger and opposite
// answers to the person about to deploy.
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: true, reason: 'mine' })),
);
await expect(
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
).resolves.toMatchObject({ available: true, reason: 'mine' });
expect(fetchMock).toHaveBeenCalledTimes(2);
// The first ask carries nothing; only the second spends a signature.
const [, anonymous] = fetchMock.mock.calls[0];
expect((anonymous as RequestInit | undefined)?.headers).toBeUndefined();
const signed = fetchMock.mock.calls[1][0] as Request;
expect(signed.headers.get('Authorization')).toMatch(/^Nostr /);
expect(signed.url).toBe(`https://${DASHBOARD_HOST}/api/hosts/x.${DOMAIN}/available`);
});
it('spends no signature on a name that is free', async () => {
// Picking a new name is the common case, and a remote signer on the other
// end of every keystroke is not something to spend it on.
fetchMock.mockResolvedValue(new Response(JSON.stringify({ hostname: 'x', available: true })));
await checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('keeps the public answer when the gateway is too old to know better', async () => {
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
)
.mockResolvedValueOnce(new Response('nope', { status: 404 }));
await expect(
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
).resolves.toMatchObject({ available: false, reason: 'taken' });
});
});
describe('checkNameAvailable, for a name held for its previous owner', () => {
it('reports waiting rather than taken', async () => {
// The state almost every unclaimed name is in: an archive serving it, so
// the public answer is taken and the useful answer is that it is theirs.
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'waiting' })),
);
await expect(
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
).resolves.toMatchObject({ available: false, reason: 'waiting' });
});
it('says nothing more to somebody who did not sign', async () => {
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
);
await expect(checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`)).resolves.toMatchObject({
reason: 'taken',
});
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
+34 -7
View File
@@ -10,7 +10,18 @@ const NAMED_SITE_KIND = 35128;
export interface NameAvailability {
hostname: string;
available: boolean;
reason?: 'taken' | 'invalid';
/**
* Why it is not free, or — with `available` — that it is not free of somebody
* else.
*
* `mine` is a name this signer can already point somewhere. `waiting` is one
* the gateway is holding for them from before it took the domain over: not
* free, not theirs to deploy to yet, and one claim away from both. Both come
* only from a signed request, and only from a gateway new enough to answer
* one; an older one says `taken`, which is not wrong, just of no use to the
* person the name belongs to.
*/
reason?: 'taken' | 'invalid' | 'mine' | 'waiting';
/** Present when `reason` is `invalid`; written to be shown to whoever typed it. */
error?: string;
}
@@ -18,9 +29,15 @@ export interface NameAvailability {
/**
* Ask whether a name can still be claimed.
*
* Unauthenticated, and deliberately so: someone choosing a name has not decided
* to make an account yet, and making them prove who they are to find out their
* first choice is taken would be a strange order to do things in.
* Asked anonymously first, and deliberately so: someone choosing a name has not
* decided to make an account yet, and making them prove who they are to find out
* their first choice is taken would be a strange order to do things in.
*
* A name that comes back taken is then asked about again, signed, because
* "taken" and "taken by you" are the same answer to a stranger and opposite
* answers to the person about to deploy. Only on that branch: a free name is the
* common case while somebody is picking one, and signing every keystroke would
* put a remote signer on the other end of the typing.
*
* A network failure answers `available: true` rather than blocking the person.
* Being wrong that way costs a clear error at deploy time; being wrong the other
@@ -30,13 +47,23 @@ export async function checkNameAvailable(
dashboardHost: string,
hostname: string,
signal?: AbortSignal,
signer?: NostrSigner,
): Promise<NameAvailability> {
const url = `https://${dashboardHost}/api/hosts/${encodeURIComponent(hostname)}/available`;
const path = `/api/hosts/${encodeURIComponent(hostname)}/available`;
try {
const response = await fetch(url, { signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS) });
const response = await fetch(`https://${dashboardHost}${path}`, {
signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS),
});
if (!response.ok) return { hostname, available: true };
return (await response.json()) as NameAvailability;
const availability = (await response.json()) as NameAvailability;
if (availability.available || availability.reason !== 'taken' || !signer) return availability;
const asOwner = await npanelRequest(dashboardHost, signer, 'GET', path, undefined, signal);
if (!asOwner.ok) return availability;
return (await asOwner.json()) as NameAvailability;
} catch {
return { hostname, available: true };
}
+87
View File
@@ -0,0 +1,87 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { getPublicKey, generateSecretKey } from 'nostr-tools';
import type { NostrSigner } from '@nostrify/nostrify';
import { fetchNpanelClaimCount } from './npanelApi';
const DASHBOARD_HOST = 'npanel.example.test';
const pubkey = getPublicKey(generateSecretKey());
/**
* A signer that fills in the fields a real one would, without signing.
*
* Signing for real is not available here: jsdom's TextEncoder returns a
* Uint8Array from its own realm, which fails the `instanceof` check inside
* @noble/hashes, so nostr-tools cannot hash an event under this environment.
* Nothing here verifies a signature — what matters is which request goes out
* and what is made of the answer.
*/
const signer: NostrSigner = {
getPublicKey: async () => pubkey,
signEvent: async (template) => ({
...template,
id: 'f'.repeat(64),
pubkey,
sig: '0'.repeat(128),
}),
} as NostrSigner;
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('fetchNpanelClaimCount', () => {
it('asks the gateway only for the count', async () => {
fetchMock.mockResolvedValue(new Response(JSON.stringify({ waiting: 3, taken: 1 })));
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
waiting: 3,
taken: 1,
});
const request = fetchMock.mock.calls[0][0] as Request;
expect(request.url).toBe(`https://${DASHBOARD_HOST}/api/claims?summary=1`);
expect(request.headers.get('Authorization')).toMatch(/^Nostr /);
});
it('reports nothing waiting when the gateway answers with the list instead', async () => {
// An older gateway ignores the parameter and returns every claim, which is
// a different shape rather than a bigger number — counting it would be
// inventing one.
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ claims: [{ hostname: `a.example.test` }] })),
);
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
waiting: 0,
taken: 0,
});
});
it('reports nothing waiting when the gateway cannot be reached', async () => {
// This runs because somebody opened a settings page. A number that failed
// to arrive is not an error worth showing them.
fetchMock.mockRejectedValue(new Error('offline'));
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
waiting: 0,
taken: 0,
});
});
it('reports nothing waiting when the gateway refuses', async () => {
fetchMock.mockResolvedValue(new Response('nope', { status: 403 }));
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
waiting: 0,
taken: 0,
});
});
});
+44
View File
@@ -114,6 +114,50 @@ export async function fetchNpanelClaims(
return claims;
}
/** How many names a gateway is holding for somebody, and how many they took. */
export interface NpanelClaimCount {
waiting: number;
taken: number;
}
/**
* The count alone, without working out what to do about any of them.
*
* {@link fetchNpanelClaims} reads every file of every claimed deploy and returns
* a manifest each, which is the right price for the dialog that hands the names
* back and much too high for the sentence that gets somebody to open it. A
* gateway too old to know the parameter answers with the list instead, so the
* shape is checked rather than assumed — and a gateway that fails outright
* reports nothing waiting, since a number nobody can fetch should not become an
* error on a settings page.
*/
export async function fetchNpanelClaimCount(
dashboardHost: string,
signer: NostrSigner,
signal?: AbortSignal,
): Promise<NpanelClaimCount> {
const none: NpanelClaimCount = { waiting: 0, taken: 0 };
try {
const response = await npanelRequest(
dashboardHost,
signer,
'GET',
'/api/claims?summary=1',
undefined,
signal,
);
if (!response.ok) return none;
const body = (await response.json()) as Partial<NpanelClaimCount>;
if (typeof body.waiting !== 'number' || typeof body.taken !== 'number') return none;
return { waiting: body.waiting, taken: body.taken };
} catch {
return none;
}
}
/** Point a name waiting for this signer at a site they published. */
export async function claimNpanelHostname(
dashboardHost: string,
+46 -18
View File
@@ -15,6 +15,7 @@ import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog';
import { useNpanelClaimCount } from '@/hooks/useNpanelClaims';
import { Button } from '@/components/ui/button';
import {
DndContext,
@@ -344,27 +345,13 @@ export function DeploySettings() {
</div>
)}
{/* Sites held for their previous owner on a gateway that took over a
domain. Shown without asking the gateway first: finding out costs
a signature, and a signing prompt nobody asked for is worse than a
button that sometimes opens an empty list. */}
{user && settings.providers.map((provider) => (
provider.type === 'npanel' ? (
<div
<HeldSites
key={`migrate-${provider.id}`}
className="rounded-lg border border-dashed p-4 flex flex-wrap items-center justify-between gap-3"
>
<div className="space-y-1">
<h4 className="text-sm font-medium">Sites from before {provider.name}</h4>
<p className="text-sm text-muted-foreground">
Names you published on {provider.domain} under the old host are being served
from an archive until you take them back.
</p>
</div>
<Button variant="outline" onClick={() => setMigratingProvider(provider)}>
Take back sites
</Button>
</div>
provider={provider}
onOpen={() => setMigratingProvider(provider)}
/>
) : null
))}
@@ -440,4 +427,45 @@ export function DeploySettings() {
);
}
/**
* Sites held for their previous owner on a gateway that took over a domain.
*
* The count is asked for on load, rather than the card standing there saying
* "you may have sites waiting" to everyone forever. Almost nobody does, and a
* card that cannot tell them apart is one most people learn to ignore before
* it ever applies to them — while the person it does apply to has a few names
* being served from an archive under a key that is not theirs, which is worth
* one signature to say out loud.
*
* It is only the count: {@link useNpanelClaimCount} is two counted rows, not
* the deploy-by-deploy read the dialog does when somebody opens it.
*/
function HeldSites({ provider, onOpen }: { provider: NpanelProvider; onOpen: () => void }) {
const { data } = useNpanelClaimCount(provider);
// Nothing to say until the gateway says there is something, so a gateway with
// no migration behind it — every gateway but the one — shows nothing at all.
if (!data?.waiting) return null;
return (
<div className="rounded-lg border border-dashed p-4 flex flex-wrap items-center justify-between gap-3">
<div className="space-y-1">
<h4 className="text-sm font-medium">
{data.waiting === 1
? `One name is waiting for you on ${provider.domain}`
: `${data.waiting} names are waiting for you on ${provider.domain}`}
</h4>
<p className="text-sm text-muted-foreground">
You published {data.waiting === 1 ? 'it' : 'them'} before {provider.domain} moved to{' '}
{provider.name}. {data.waiting === 1 ? 'It is' : 'They are'} being served from an archive
until you take {data.waiting === 1 ? 'it' : 'them'} back.
</p>
</div>
<Button variant="outline" onClick={onOpen}>
Take back sites
</Button>
</div>
);
}
export default DeploySettings;