Compare commits

..
3 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
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
10 changed files with 268 additions and 681 deletions

No files matched your search

-15
View File
@@ -1,20 +1,5 @@
# Changelog
## [9.16.4] - 2026-09-16
### Changed
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
## [9.16.3] - 2026-09-14
### Added
- Take back your sites one at a time — every name waiting for you now has its own Publish, Show, and Delete buttons, so you can keep the few you want and clear out the rest
- Show opens a site by its Nostr address before you decide about it, so you can look at names that never loaded in a browser
### Changed
- Deleting a name only gives it up on shakespeare.wtf — anything published to Nostr stays yours
- Names that couldn't be taken back safely can now be cleared out, instead of only explaining why they were stuck
## [9.16.2] - 2026-09-13
### Changed
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "shakespeare.diy",
"version": "9.16.4",
"version": "9.16.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shakespeare.diy",
"version": "9.16.4",
"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.4",
"version": "9.16.2",
"type": "module",
"author": {
"name": "shakespeare.diy",
-15
View File
@@ -1,20 +1,5 @@
# Changelog
## [9.16.4] - 2026-09-16
### Changed
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
## [9.16.3] - 2026-09-14
### Added
- Take back your sites one at a time — every name waiting for you now has its own Publish, Show, and Delete buttons, so you can keep the few you want and clear out the rest
- Show opens a site by its Nostr address before you decide about it, so you can look at names that never loaded in a browser
### Changed
- Deleting a name only gives it up on shakespeare.wtf — anything published to Nostr stays yours
- Names that couldn't be taken back safely can now be cleared out, instead of only explaining why they were stuck
## [9.16.2] - 2026-09-13
### Changed
+209 -469
View File
@@ -1,9 +1,7 @@
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
import { AlertCircle, Check, ExternalLink, Eye, Loader2, Rocket, Tag, Trash2 } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { AlertCircle, Check, ExternalLink, Loader2, Rocket, Trash2 } from 'lucide-react';
import {
Dialog,
DialogContent,
@@ -12,30 +10,14 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNpanelClaims, type NpanelClaimPlan, type NpanelTakenSite } from '@/hooks/useNpanelClaims';
import type { NpanelProvider } from '@/contexts/DeploySettingsContext';
import { claimNpanelHostname, deleteNpanelClaim } from '@/lib/deploy/npanelApi';
import {
NAMED_SITE_KIND,
nsitePreviewUrl,
republishTags,
retitleTags,
sitePreviewUrl,
} from '@/lib/deploy/npanelMigration';
import { claimNpanelHostname } from '@/lib/deploy/npanelApi';
import { NAMED_SITE_KIND, republishTags, retitleTags } from '@/lib/deploy/npanelMigration';
import { checkRelayCoverage, forwardMissing, host, publishToRelays } from '@/lib/deploy/publishToRelays';
/** Where a single name has got to. */
@@ -43,18 +25,9 @@ type RowStatus =
| { kind: 'waiting' }
| { kind: 'publishing' }
| { kind: 'claiming' }
| { kind: 'deleting' }
| { kind: 'deleted'; note?: string }
| { kind: 'done'; partial?: string }
| { kind: 'failed'; error: string };
/** A name a person has asked to delete, and has not confirmed yet. */
interface PendingDeletion {
hostname: string;
/** Whether a copy of the site is published under their own key. */
published: boolean;
}
/** What the last coverage run found, as a sentence per relay. */
interface CoverageReport {
lines: string[];
@@ -79,11 +52,6 @@ function describeStep(claim: NpanelClaimPlan): string {
}
}
/** The `d` tag of an event, which for a named site is the site's identifier. */
function eventIdentifier(event: NostrEvent): string {
return event.tags.find(([name]) => name === 'd')?.[1] ?? '';
}
/** "took 3 of 5 relays", where that is worth saying. */
function coverageNote(accepted: string[], rejected: { url: string; reason: string }[]): string | undefined {
if (!rejected.length) return undefined;
@@ -98,11 +66,8 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
const { data, isLoading, error } = useNpanelClaims(open ? provider : undefined);
const [statuses, setStatuses] = useState<Record<string, RowStatus>>({});
const [running, setRunning] = useState<null | 'migrate' | 'titles' | 'coverage' | 'row'>(null);
const [running, setRunning] = useState<null | 'migrate' | 'titles' | 'coverage'>(null);
const [coverage, setCoverage] = useState<CoverageReport | null>(null);
const [confirming, setConfirming] = useState<PendingDeletion | null>(null);
/** Whether anything has happened that the cached lists do not know about. */
const [dirty, setDirty] = useState(false);
const claims = data?.waiting ?? [];
const actionable = claims.filter((claim) => claim.step.kind !== 'blocked');
@@ -112,19 +77,12 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
const strays = (data?.taken ?? []).filter((site) => site.stray);
const done = Object.values(statuses).filter((status) => status.kind === 'done').length;
const deleted = Object.values(statuses).filter((status) => status.kind === 'deleted').length;
const failed = Object.values(statuses).filter((status) => status.kind === 'failed').length;
const setStatus = (hostname: string, status: RowStatus) => {
setStatuses((previous) => ({ ...previous, [hostname]: status }));
};
/** Whether a row has already reached a state no further action applies to. */
const settled = (hostname: string): boolean => {
const kind = statuses[hostname]?.kind;
return kind === 'done' || kind === 'deleted';
};
/**
* Take back one name.
*
@@ -145,7 +103,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
kind: NAMED_SITE_KIND,
content: claim.step.manifest.content,
created_at: Math.floor(Date.now() / 1000),
tags: republishTags(claim.step.manifest, claim.step.identifier, {
tags: republishTags(claim.step.manifest, claim.step.identifier, provider.relayUrls, {
title: claim.suggestedTitle,
description: claim.suggestedDescription,
}),
@@ -187,54 +145,33 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
});
};
/**
* Give a name up rather than take it back.
*
* Only npanel forgets anything. The archive's manifest stays on relays under
* the archive's key, and a copy published under the user's own key stays
* theirs — what ends is this gateway serving the name and holding it for
* them. Saying otherwise in the confirmation would be a promise nothing here
* can keep.
*/
const removeClaim = async (hostname: string): Promise<void> => {
if (!user) return;
setStatus(hostname, { kind: 'deleting' });
await deleteNpanelClaim(provider.dashboardHost, user.signer, hostname);
setStatus(hostname, { kind: 'deleted' });
};
/**
* Undo a manifest published for a name that can never load.
*
* Both halves, because there is no useful middle state: a relay is asked to
* forget the event, and the gateway to forget the name. Keeping the record
* for a hostname whose TLS handshake has always failed and always will would
* leave a row in this list forever with nothing to do about it.
*
* The gateway going second is deliberate — it is the recoverable half. A
* deletion request cannot be taken back, so it is the one that has to be
* worth making on its own.
*/
/** Ask a relay to forget a manifest that was published for an unusable name. */
const removeStray = async (site: NpanelTakenSite): Promise<void> => {
if (!user) return;
setStatus(site.hostname, { kind: 'publishing' });
const deletion = await user.signer.signEvent({
kind: 5,
content: 'Published for a hostname no certificate can cover.',
created_at: Math.floor(Date.now() / 1000),
tags: [
['e', site.event.id],
['a', `${site.event.kind}:${user.pubkey}:${eventIdentifier(site.event)}`],
['k', String(site.event.kind)],
],
});
try {
const identifier = site.event.tags.find(([name]) => name === 'd')?.[1] ?? '';
const deletion = await user.signer.signEvent({
kind: 5,
content: 'Published for a hostname no certificate can cover.',
created_at: Math.floor(Date.now() / 1000),
tags: [
['e', site.event.id],
['a', `${site.event.kind}:${user.pubkey}:${identifier}`],
['k', String(site.event.kind)],
],
});
await publishToRelays(nostr, deletion, provider.relayUrls);
await removeClaim(site.hostname);
setStatus(site.hostname, { kind: 'deleted', note: 'Retracted, and taken off the gateway.' });
await publishToRelays(nostr, deletion, provider.relayUrls);
setStatus(site.hostname, { kind: 'done' });
} catch (err) {
setStatus(site.hostname, {
kind: 'failed',
error: err instanceof Error ? err.message : 'Failed',
});
}
};
/** Run `action` over `rows`, one at a time, recording failures per row. */
@@ -244,7 +181,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
action: (row: T) => Promise<void>,
): Promise<void> => {
for (const row of rows) {
if (settled(key(row))) continue;
if (statuses[key(row)]?.kind === 'done') continue;
try {
await action(row);
@@ -257,30 +194,6 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
}
};
/**
* One row's action, on its own.
*
* Still holds the whole dialog while it runs. A signer answers one request at
* a time whatever the UI allows, and two buttons that look live but queue
* behind each other read as a hang.
*/
const runRow = async (hostname: string, action: () => Promise<void>): Promise<void> => {
setRunning('row');
try {
await action();
// Deliberately not refetched here. Somebody clearing out twenty sites
// clicks twenty times, and re-reading the list after each one would cost
// a signature and a relay round trip to learn what the row already says.
// The list is caught up when the dialog closes.
setDirty(true);
} catch (err) {
setStatus(hostname, { kind: 'failed', error: err instanceof Error ? err.message : 'Failed' });
}
setRunning(null);
};
const migrateAll = async () => {
setRunning('migrate');
// One at a time: a remote signer answers one request at a time anyway, and
@@ -288,7 +201,6 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
// than a hundred simultaneous errors.
await runEach(actionable, (claim) => claim.hostname, migrate);
setRunning(null);
setDirty(true);
// Whatever succeeded is no longer waiting, and whatever failed still is.
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
};
@@ -297,7 +209,6 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
setRunning('titles');
await runEach(retitlable, (site) => site.hostname, retitle);
setRunning(null);
setDirty(true);
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
};
@@ -357,19 +268,6 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
<Loader2 className="h-3 w-3 animate-spin" /> Claiming…
</span>
);
case 'deleting':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" /> Deleting…
</span>
);
case 'deleted':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Check className="h-3 w-3 shrink-0" />
{status.note ?? `Deleted from ${provider.domain}.`}
</span>
);
case 'done':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
@@ -397,349 +295,191 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
const busy = running !== null;
/** Names still worth running the bulk button over. */
const remaining = actionable.filter((claim) => !settled(claim.hostname)).length;
/**
* Where this sitting has got to, said once.
*
* Deleting is reported alongside taking names back rather than folded into
* it, because they are opposite decisions and somebody who has just made
* thirty of them should be able to see that they did.
*/
const summary = (() => {
const parts: string[] = [];
if (done) parts.push(`${done} done`);
if (deleted) parts.push(`${deleted} deleted`);
if (failed) parts.push(`${failed} failed`);
if (failed) return `${parts.join(', ')} — try the failed ones again.`;
if (parts.length) {
return `${parts.join(', ')}. A republished site takes the gateway about a minute to pick up.`;
}
return `${remaining} to migrate.`;
})();
/**
* Close, and let the lists catch up.
*
* Marked stale rather than refetched: the query is disabled while the dialog
* is shut, so nothing is asked until somebody opens it again — and asking
* costs a signature, which on a remote signer costs a round trip.
*/
const close = () => {
if (dirty) {
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
queryClient.invalidateQueries({ queryKey: ['npanel-claim-count'] });
}
onOpenChange(false);
};
/**
* What can be done about one name, minus whatever does not apply to it.
*
* Every row gets its own controls rather than only the bulk button, because
* the list is not a queue of decisions already made. Somebody with forty
* names on file wants three of them back and the rest gone, and until now the
* only thing the dialog would do was hand them all forty.
*/
const renderActions = (
hostname: string,
options: {
/** Where the site can be looked at, when anywhere can show it. */
preview?: string;
/** The one thing this row's section does to a name that is staying. */
act?: { label: string; icon: LucideIcon; run: () => Promise<void> };
/** Present when the name can be given up. `published` decides what the confirmation promises. */
deletable?: { published: boolean };
},
) => {
const gone = settled(hostname);
const ActionIcon = options.act?.icon;
return (
<div className="shrink-0 flex items-center gap-1">
{options.preview && (
<Button size="sm" variant="ghost" className="h-8 px-2 text-muted-foreground" asChild>
<a href={options.preview} target="_blank" rel="noreferrer">
<Eye className="h-4 w-4 sm:mr-1.5" />
<span className="hidden sm:inline">Show</span>
</a>
</Button>
)}
{options.act && ActionIcon && !gone && (
<Button
size="sm"
variant="outline"
className="h-8 px-2"
disabled={busy}
onClick={() => runRow(hostname, options.act!.run)}
>
<ActionIcon className="h-4 w-4 sm:mr-1.5" />
<span className="hidden sm:inline">{options.act.label}</span>
</Button>
)}
{options.deletable && !gone && (
<Button
size="sm"
variant="ghost"
className="h-8 px-2 text-muted-foreground hover:text-destructive"
disabled={busy}
aria-label={`Delete ${hostname}`}
onClick={() => setConfirming({ hostname, published: options.deletable!.published })}
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
);
};
return (
<>
<Dialog open={open} onOpenChange={busy ? undefined : (next) => (next ? onOpenChange(true) : close())}>
<DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader className="shrink-0">
<DialogTitle>Take back your sites</DialogTitle>
<DialogDescription>
These names on {provider.domain} were yours before this gateway took the domain over.
They are being served from an archive key until you publish your own copy.
</DialogDescription>
</DialogHeader>
<Dialog open={open} onOpenChange={busy ? undefined : onOpenChange}>
<DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader className="shrink-0">
<DialogTitle>Take back your sites</DialogTitle>
<DialogDescription>
These names on {provider.domain} were yours before this gateway took the domain over.
They are being served from an archive key until you publish your own copy.
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto space-y-6 py-2">
{isLoading && (
<div className="space-y-2">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error.message}</AlertDescription>
</Alert>
)}
{data && !claims.length && !data.taken.length && (
<p className="text-sm text-muted-foreground py-8 text-center">
Nothing is waiting for you here.
</p>
)}
{actionable.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Waiting for you</h4>
<div className="rounded-md border divide-y">
{actionable.map((claim) => (
<div key={claim.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
</div>
{renderActions(claim.hostname, {
preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain),
// The word the button uses is the work it does. A name
// whose site is already on this key publishes nothing.
act: {
label: claim.step.kind === 'republish' ? 'Publish' : 'Claim',
icon: Rocket,
run: () => migrate(claim),
},
// A `claim` step, either reason, means a copy of the site
// is already published under this key and survives the
// name going away. A `republish` step means it is not.
deletable: { published: claim.step.kind === 'claim' },
})}
</div>
))}
</div>
</div>
)}
{retitlable.length > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Titled after their address</h4>
<p className="text-xs text-muted-foreground">
The archive could only call a site by its hostname. These say what they are
actually called, so the name they publish under can too.
</p>
</div>
<Button size="sm" variant="outline" onClick={fixTitles} disabled={busy}>
{running === 'titles' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Fix titles'}
</Button>
</div>
<div className="rounded-md border divide-y">
{retitlable.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.',
)}
</div>
</div>
{renderActions(site.hostname, {
preview: sitePreviewUrl(
`${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`,
site.hostname,
provider.domain,
),
act: { label: 'Retitle', icon: Tag, run: () => retitle(site) },
deletable: { published: true },
})}
</div>
))}
</div>
</div>
)}
{(data?.events.length ?? 0) > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Relay coverage</h4>
<p className="text-xs text-muted-foreground">
A site is only as findable as the relays holding its manifest. This sends the
events you already published to the relays that do not have them — same events,
no signing.
</p>
</div>
<Button size="sm" variant="outline" onClick={fixCoverage} disabled={busy}>
{running === 'coverage' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Check relays'}
</Button>
</div>
{coverage && (
<div className="rounded-md border bg-muted/30 p-3 space-y-1">
{coverage.lines.map((line) => (
<p key={line} className="text-xs font-mono text-muted-foreground break-words">
{line}
</p>
))}
</div>
)}
</div>
)}
{strays.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Published for a name that cannot load</h4>
<div className="rounded-md border border-dashed divide-y">
{strays.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0 space-y-0.5">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
`No certificate covers a name this deep under ${provider.domain}.`,
)}
</div>
</div>
{/*
One button, not two. What is wrong with these is that
they exist at all, so there is no version of retracting
the manifest that leaves the gateway's record worth
keeping — the name has never loaded for anyone and never
will. The hostname is unservable, so the preview can only
come from the address.
*/}
{renderActions(site.hostname, {
preview: nsitePreviewUrl(
`${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`,
),
act: { label: 'Retract', icon: Trash2, run: () => removeStray(site) },
})}
</div>
))}
</div>
</div>
)}
{blocked.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Needs a decision</h4>
<p className="text-xs text-muted-foreground">
Nothing here can be taken back safely without you choosing something first. Deleting
is a decision too, and for most of these it is the right one.
</p>
<div className="rounded-md border border-dashed divide-y">
{blocked.map((claim) => (
<div key={claim.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0 space-y-0.5">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
</div>
{renderActions(claim.hostname, {
preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain),
deletable: { published: claim.mine },
})}
</div>
))}
</div>
</div>
)}
</div>
<DialogFooter className="shrink-0 gap-2 sm:justify-between items-center">
<span className="text-xs text-muted-foreground">{summary}</span>
<div className="flex gap-2">
<Button variant="outline" onClick={() => close()} disabled={busy}>
Close
</Button>
<Button onClick={migrateAll} disabled={busy || remaining === 0}>
{running === 'migrate' ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Migrating…
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
{failed > 0 ? 'Retry' : `Migrate all (${remaining})`}
</>
)}
</Button>
<div className="flex-1 overflow-y-auto space-y-6 py-2">
{isLoading && (
<div className="space-y-2">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
</DialogFooter>
</DialogContent>
</Dialog>
)}
<AlertDialog open={confirming !== null} onOpenChange={(next) => !next && setConfirming(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {confirming?.hostname}?</AlertDialogTitle>
<AlertDialogDescription>
{provider.name} stops serving this name and stops holding it for you, and it goes back
to being anybody's to take. This cannot be undone.{' '}
{confirming?.published
? 'The site itself stays published under your key, and can still be reached by its address.'
: 'The archived copy stays on Nostr under the key that published it — this only ends the gateway serving it.'}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => {
const hostname = confirming?.hostname;
setConfirming(null);
if (hostname) void runRow(hostname, () => removeClaim(hostname));
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error.message}</AlertDescription>
</Alert>
)}
{data && !claims.length && !data.taken.length && (
<p className="text-sm text-muted-foreground py-8 text-center">
Nothing is waiting for you here.
</p>
)}
{actionable.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Waiting for you</h4>
<div className="rounded-md border divide-y">
{actionable.map((claim) => (
<div key={claim.hostname} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
</div>
<span className="shrink-0 text-xs rounded-full px-2 py-0.5 border text-muted-foreground">
{claim.step.kind === 'republish' ? 'republish' : 'claim'}
</span>
</div>
))}
</div>
</div>
)}
{retitlable.length > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Titled after their address</h4>
<p className="text-xs text-muted-foreground">
The archive could only call a site by its hostname. These say what they are
actually called, so the name they publish under can too.
</p>
</div>
<Button size="sm" variant="outline" onClick={fixTitles} disabled={busy}>
{running === 'titles' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Fix titles'}
</Button>
</div>
<div className="rounded-md border divide-y">
{retitlable.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.',
)}
</div>
</div>
</div>
))}
</div>
</div>
)}
{(data?.events.length ?? 0) > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Relay coverage</h4>
<p className="text-xs text-muted-foreground">
A site is only as findable as the relays holding its manifest. This sends the
events you already published to the relays that do not have them — same events,
no signing.
</p>
</div>
<Button size="sm" variant="outline" onClick={fixCoverage} disabled={busy}>
{running === 'coverage' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Check relays'}
</Button>
</div>
{coverage && (
<div className="rounded-md border bg-muted/30 p-3 space-y-1">
{coverage.lines.map((line) => (
<p key={line} className="text-xs font-mono text-muted-foreground break-words">
{line}
</p>
))}
</div>
)}
</div>
)}
{strays.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Published for a name that cannot load</h4>
<div className="rounded-md border border-dashed divide-y">
{strays.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-4 p-3">
<div className="min-w-0 space-y-0.5">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
`No certificate covers a name this deep under ${provider.domain}.`,
)}
</div>
</div>
<Button
size="sm"
variant="ghost"
className="shrink-0"
onClick={() => removeStray(site)}
disabled={busy}
>
<Trash2 className="h-4 w-4 mr-1.5" />
Retract
</Button>
</div>
))}
</div>
</div>
)}
{blocked.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Needs a decision</h4>
<div className="rounded-md border border-dashed divide-y">
{blocked.map((claim) => (
<div key={claim.hostname} className="p-3 space-y-0.5">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<p className="text-xs text-muted-foreground">{describeStep(claim)}</p>
</div>
))}
</div>
</div>
)}
</div>
<DialogFooter className="shrink-0 gap-2 sm:justify-between items-center">
<span className="text-xs text-muted-foreground">
{failed > 0
? `${done} done, ${failed} failed — run it again to retry.`
: done > 0
? `${done} done. A republished site takes the gateway about a minute to pick up.`
: `${actionable.length} to migrate.`}
</span>
<div className="flex gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
Close
</Button>
<Button onClick={migrateAll} disabled={busy || actionable.length === 0}>
{running === 'migrate' ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Migrating…
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
{failed > 0 ? 'Retry' : `Migrate all (${actionable.length})`}
</>
)}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+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);
+5 -7
View File
@@ -250,8 +250,8 @@ async function runConcurrent<T>(
* - HEAD-checks each file on each Blossom server before uploading
* - PUTs files to Blossom servers with pre-signed auth headers
* - Publishes a single kind-15128 (root) or kind-35128 (named) site manifest event
* containing all ["path", "/path", sha256] tags and ["server", url] Blossom
* hints — no separate kind 10002 or kind 10063 published
* containing all ["path", "/path", sha256] tags, ["server", url] Blossom hints,
* and ["relay", url] relay hints — no separate kind 10002 or kind 10063 published
*
* Named sites (kind 35128, siteIdentifier set):
* URL = https://{base36pubkey}{siteIdentifier}.{gateway}
@@ -367,10 +367,8 @@ export class NsiteAdapter implements DeployAdapter {
pathTags.push(['path', '/404.html', indexFile.sha256]);
}
// NIP-5A defines no relay-hint tag for a manifest, so the relays a site was
// published to are not written into it. Where to find the event is the
// reader's problem and the author's kind 10002, not the manifest's.
const serverTags: string[][] = serverBases.map(url => ['server', url]);
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
const tags: string[][] = [];
@@ -379,7 +377,7 @@ export class NsiteAdapter implements DeployAdapter {
tags.push(['d', this.siteIdentifier]);
}
tags.push(...pathTags, ...serverTags);
tags.push(...pathTags, ...serverTags, ...relayTags);
if (this.siteTitle) {
tags.push(['title', this.siteTitle]);
@@ -401,7 +399,7 @@ export class NsiteAdapter implements DeployAdapter {
});
// ── Step 5: Publish manifest ──────────────────────────────────────────────
// Blossom server hints are embedded as tags in the manifest itself —
// Relay and server hints are embedded as tags in the manifest itself —
// no separate kind 10002 or kind 10063 events are published.
//
// Relay by relay, because the site is only as findable as the relays that
-29
View File
@@ -179,32 +179,3 @@ export async function claimNpanelHostname(
throw await npanelError(response, `Could not take back ${hostname}`);
}
}
/**
* Give a name up rather than take it back.
*
* The gateway forgets the hostname entirely: it stops serving the archived
* site, stops holding the name, and the name goes back to being anybody's. What
* this cannot touch is the network — the archive's manifest is its own event
* under its own key, and a copy the user published is theirs to retract — so
* this is a request to one server and nothing more.
*/
export async function deleteNpanelClaim(
dashboardHost: string,
signer: NostrSigner,
hostname: string,
signal?: AbortSignal,
): Promise<void> {
const response = await npanelRequest(
dashboardHost,
signer,
'DELETE',
`/api/claims/${encodeURIComponent(hostname)}`,
undefined,
signal,
);
if (!response.ok) {
throw await npanelError(response, `Could not delete ${hostname}`);
}
}
+7 -61
View File
@@ -3,14 +3,11 @@ import type { NostrEvent } from '@nostrify/nostrify';
import type { NpanelClaim } from './npanelApi';
import {
NAMED_SITE_KIND,
ROOT_SITE_KIND,
hasArchiveTitle,
isServableHostname,
nsitePreviewUrl,
planClaim,
republishTags,
retitleTags,
sitePreviewUrl,
} from './npanelMigration';
const PUBKEY = 'a'.repeat(64);
@@ -98,54 +95,6 @@ describe('isServableHostname', () => {
});
});
describe('nsitePreviewUrl', () => {
it('addresses a named site by its base36 pubkey and identifier', () => {
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:mysite`)).toMatch(/^https:\/\/[0-9a-z]{50}mysite\.nsite\.lol$/);
});
it('addresses a root site by its npub', () => {
expect(nsitePreviewUrl(`${ROOT_SITE_KIND}:${ARCHIVE}:`)).toMatch(/^https:\/\/npub1[0-9a-z]+\.nsite\.lol$/);
});
it('has nowhere to send an identifier that will not fit a DNS label', () => {
// About a quarter of what this migration carries: the host it came from
// named sites after projects and never had to fit one in a subdomain.
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`)).toBeUndefined();
// Uppercase resolves as a DNS label and then matches no `d` tag, which is
// worse than no link at all.
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:ErrorTime`)).toBeUndefined();
});
it('says nothing about an address it cannot read', () => {
expect(nsitePreviewUrl(null)).toBeUndefined();
expect(nsitePreviewUrl(undefined)).toBeUndefined();
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:not-a-pubkey:mysite`)).toBeUndefined();
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:`)).toBeUndefined();
});
});
describe('sitePreviewUrl', () => {
it('prefers the address, which outlives both the name and its certificate', () => {
expect(sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:mysite`, 'mysite.shakespeare.wtf', DOMAIN)).toMatch(
/\.nsite\.lol$/,
);
});
it('falls back to the hostname when no gateway label can hold the identifier', () => {
expect(
sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`, 'long.shakespeare.wtf', DOMAIN),
).toBe('https://long.shakespeare.wtf');
});
it('offers nothing for a name that is neither servable nor addressable', () => {
// A link to a certificate error is worse than no button.
expect(sitePreviewUrl(null, 'a.b.shakespeare.wtf', DOMAIN)).toBeUndefined();
expect(
sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`, 'a.b.shakespeare.wtf', DOMAIN),
).toBeUndefined();
});
});
describe('republishTags', () => {
it('keeps the files and where to fetch them, and takes the archive’s words', () => {
const manifest = claim().manifest;
@@ -154,15 +103,15 @@ describe('republishTags', () => {
const tags = republishTags(
{ ...manifest, tags: [...manifest.tags, ['relay', 'wss://gone.example']] },
'mysite',
['wss://relay.ditto.pub'],
{ title: 'My Site', description: 'What it is for.' },
);
expect(tags[0]).toEqual(['d', 'mysite']);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
expect(tags).toContainEqual(['server', 'https://blossom.ditto.pub/']);
// NIP-5A has no relay-hint tag, so the archive's are dropped and none of
// ours take their place.
expect(tags.some(([name]) => name === 'relay' || name === 'r')).toBe(false);
expect(tags).toContainEqual(['relay', 'wss://relay.ditto.pub']);
expect(tags).not.toContainEqual(['relay', 'wss://gone.example']);
expect(tags.filter(([name]) => name === 'd')).toHaveLength(1);
// The archive's title was the hostname and its `alt` says the site is
@@ -180,7 +129,7 @@ describe('republishTags', () => {
// Roughly a third of these are shells that set their title from JavaScript.
// No title is what an nsite manifest without one has always meant, and is
// better than a domain wearing a name's clothes.
const tags = republishTags(manifest, 'mysite', {});
const tags = republishTags(manifest, 'mysite', [], {});
expect(tags.some(([name]) => name === 'title')).toBe(false);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
@@ -188,7 +137,7 @@ describe('republishTags', () => {
});
describe('retitleTags', () => {
it('swaps the archive’s words, drops the tags NIP-5A never had, and passes the rest through', () => {
it('swaps the archive’s words and passes everything else through', () => {
const event = {
id: 'e'.repeat(64),
pubkey: PUBKEY,
@@ -208,13 +157,10 @@ describe('retitleTags', () => {
const tags = retitleTags(event, { title: 'My Site' });
expect(tags).toContainEqual(['d', 'mysite']);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
// Built from the event as relays hold it, so a site redeployed since this
// migration ran keeps whatever it has become.
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
expect(tags).toContainEqual(['server', 'https://blossom.ditto.pub/']);
// Except the relay hints an older deploy wrote, which re-signing is the
// chance to stop carrying.
expect(tags.some(([name]) => name === 'relay')).toBe(false);
expect(tags).toContainEqual(['relay', 'wss://relay.ditto.pub']);
expect(tags).toContainEqual(['title', 'My Site']);
expect(tags.filter(([name]) => name === 'title')).toHaveLength(1);
});
+6 -82
View File
@@ -1,26 +1,9 @@
import { nip19 } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
import { buildNsiteUrl, isValidDTag } from '@/lib/utils/nsite';
import type { NpanelClaim, NpanelClaimManifest } from './npanelApi';
/** nsite named-site kind. Everything a gateway archived is one of these. */
export const NAMED_SITE_KIND = 35128;
/** nsite root-site kind. One per key, which is why one is never republished. */
export const ROOT_SITE_KIND = 15128;
/**
* A gateway that serves any nsite from its address alone.
*
* Not this gateway, deliberately. Everything in this list is a decision about a
* site somebody has not looked at in a year, and the honest way to show them one
* is from an address rather than from the name that is in question — a name
* about to be deleted, or one that no certificate covers and that has therefore
* never loaded for anyone. It reads the same relays this provider publishes to,
* so the archive's copy is as findable there as anywhere.
*/
const PREVIEW_GATEWAY = 'nsite.lol';
/**
* Tags the archive wrote about itself, which are not the site's to carry.
*
@@ -77,59 +60,6 @@ export function isServableHostname(hostname: string, domain: string): boolean {
return label.length > 0 && !label.includes('.');
}
/**
* Somewhere the site at an address can actually be looked at.
*
* Preferred over the hostname because a preview is worth most for the names the
* hostname cannot show: one too deep for a wildcard certificate, which answers a
* TLS error and always has, and one about to be deleted, which will stop
* answering at all. An address survives both.
*
* Undefined when the identifier is longer than a DNS label leaves room for —
* about a quarter of what this migration carries, because the host it came from
* named sites after projects and never had to fit one in a subdomain. There is
* no address-based URL for those on any gateway, so callers fall back to the
* hostname where the hostname works.
*/
export function nsitePreviewUrl(address: string | null | undefined): string | undefined {
if (!address) return undefined;
const [kind, pubkey, ...rest] = address.split(':');
const identifier = rest.join(':');
if (!/^[0-9a-f]{64}$/i.test(pubkey ?? '')) return undefined;
if (Number(kind) === ROOT_SITE_KIND && !identifier) {
return buildNsiteUrl({ pubkeyHex: pubkey, npub: nip19.npubEncode(pubkey), gateway: PREVIEW_GATEWAY });
}
if (Number(kind) === NAMED_SITE_KIND && isValidDTag(identifier)) {
return buildNsiteUrl({
pubkeyHex: pubkey,
npub: nip19.npubEncode(pubkey),
gateway: PREVIEW_GATEWAY,
siteIdentifier: identifier,
});
}
return undefined;
}
/**
* Where to send somebody who wants to see a site before deciding about it.
*
* {@link nsitePreviewUrl} first, the hostname second, and nothing at all for a
* name that is both unservable and unaddressable — which is a real combination
* here, and better shown as no button than as a link to a certificate error.
*/
export function sitePreviewUrl(
address: string | null | undefined,
hostname: string,
domain: string,
): string | undefined {
return nsitePreviewUrl(address) ?? (isServableHostname(hostname, domain) ? `https://${hostname}` : undefined);
}
/**
* Decide how a single waiting name gets back to its owner.
*
@@ -208,14 +138,13 @@ export function planClaim(
* called gets no title, which is what an nsite manifest without one has always
* meant and is more honest than a domain.
*
* The archive's relay hints are dropped and not replaced. NIP-5A gives a
* manifest no tag for saying where it was published, so the archive's `relay`
* and `r` tags are tags that were never part of the spec, and re-signing them
* under someone else's key would only spread them further.
* Relay hints are replaced for the same reason: the archive's say where the
* archive published, and this event is going somewhere else.
*/
export function republishTags(
manifest: NpanelClaimManifest,
identifier: string,
relayUrls: string[],
identity: SiteIdentity = {},
): string[][] {
const kept = manifest.tags.filter(
@@ -227,6 +156,7 @@ export function republishTags(
['d', identifier],
...kept,
...describeTags(identity),
...relayUrls.map((url) => ['relay', url]),
];
}
@@ -237,16 +167,10 @@ export function republishTags(
* holds, because the two are not always the same thing: a site republished by
* this migration and then redeployed normally has moved on, and rebuilding it
* out of the gateway's copy would quietly restore an older version of the site.
* Everything but the archive's own words and the relay hints NIP-5A never
* defined is passed through untouched; signing an event is the moment to stop
* carrying a tag that does not exist.
* Everything but the archive's own words is passed through untouched.
*/
export function retitleTags(event: NostrEvent, identity: SiteIdentity): string[][] {
const kept = event.tags.filter(
([name]) => name !== 'relay' && name !== 'r' && !ARCHIVE_TAGS.has(name),
);
return [...kept, ...describeTags(identity)];
return [...event.tags.filter(([name]) => !ARCHIVE_TAGS.has(name)), ...describeTags(identity)];
}
/**