feat(projects): authorize home channel admins

Signed-off-by: John Tennant <jtennant@squareup.com>
This commit is contained in:
John Tennant
2026-08-31 15:49:10 -04:00
parent bc006f6708
commit eb18afaacd
28 changed files with 1628 additions and 116 deletions

View File

@@ -82,10 +82,14 @@ test("buildProjectHomeFromFetcher scopes startup lookup to the active channel",
extraFilter: { "#buzz-channel": [channelId] },
});
assert.deepEqual(calls[1], {
kinds: [1622],
extraFilter: undefined,
});
assert.deepEqual(calls[2], {
kinds: [30617],
extraFilter: { "#buzz-channel": [channelId] },
});
assert.deepEqual(calls[2], {
assert.deepEqual(calls[3], {
kinds: [5],
extraFilter: { "#a": [`30621:${owner}:relay`, repositoryAddress] },
});

View File

@@ -3,6 +3,7 @@ import type { RelayEvent } from "@/shared/api/types";
import {
KIND_DELETION,
KIND_PROJECT_ANNOUNCEMENT,
KIND_PROJECT_REVISION,
KIND_REPO_ANNOUNCEMENT,
} from "@/shared/constants/kinds";
import { absorbStandaloneProjectRepositories } from "./lib/projectCollection";
@@ -179,10 +180,12 @@ export async function buildProjectsFromFetcher(
viewerPubkey?: string | null;
} = {},
): Promise<Project[]> {
const [projectEvents, repositoryEvents] = await Promise.all([
fetchExhaustively([KIND_PROJECT_ANNOUNCEMENT]),
fetchExhaustively([KIND_REPO_ANNOUNCEMENT]),
]);
const [projectEvents, projectRevisionEvents, repositoryEvents] =
await Promise.all([
fetchExhaustively([KIND_PROJECT_ANNOUNCEMENT]),
fetchExhaustively([KIND_PROJECT_REVISION]),
fetchExhaustively([KIND_REPO_ANNOUNCEMENT]),
]);
// Tombstones are fetched second (not in parallel) because the `#a` scoping
// needs the announcement coordinates; both announcement kinds are small,
@@ -207,6 +210,7 @@ export async function buildProjectsFromFetcher(
return absorbStandaloneProjectRepositories(
buildProjectReadModels({
projectEvents,
projectRevisionEvents,
repositoryEvents,
deletionEvents: tombstoneResult.events,
relayOrigin: options.relayOrigin ?? null,
@@ -233,7 +237,7 @@ export async function buildProjectHomeFromFetcher(
(kinds, extraFilter) =>
fetchExhaustively(
kinds,
kinds.includes(KIND_DELETION)
kinds.includes(KIND_DELETION) || kinds.includes(KIND_PROJECT_REVISION)
? extraFilter
: { ...extraFilter, "#buzz-channel": [channelId] },
),

View File

@@ -48,6 +48,23 @@ function projectEvent(repositoryTags, overrides = {}) {
};
}
function projectRevision(id, expected, operation, channelId, overrides = {}) {
return {
id,
kind: 1622,
pubkey: "d".repeat(64),
created_at: 201,
content: "",
tags: [
["a", `30621:${PROJECT_OWNER}:sprout`],
["e", expected],
["op", operation],
["channel", channelId],
],
...overrides,
};
}
test("eventToRepository preserves repository-scoped identity and clone data", () => {
const repository = eventToRepository(
repositoryEvent(FRONTEND_OWNER, "frontend"),
@@ -117,6 +134,65 @@ test("buildProjectReadModels keeps extra related channel ids", () => {
assert.deepEqual(projects[0].relatedChannelIds, [relatedA, relatedB]);
});
test("buildProjectReadModels folds the relay-authorized related-channel revision chain", () => {
const relatedA = "22222222-2222-4222-8222-222222222222";
const relatedB = "33333333-3333-4333-8333-333333333333";
const base = projectEvent([["buzz-related-channel", relatedA]], {
id: "a".repeat(64),
});
const addId = "b".repeat(64);
const removeId = "c".repeat(64);
const [project] = buildProjectReadModels({
projectEvents: [base],
projectRevisionEvents: [
projectRevision(removeId, addId, "remove-related-channel", relatedA),
projectRevision(addId, base.id, "add-related-channel", relatedB),
],
repositoryEvents: [],
relayOrigin: RELAY_ORIGIN,
});
assert.deepEqual(project.relatedChannelIds, [relatedB]);
assert.equal(project.effectiveRevisionId, removeId);
});
test("buildProjectReadModels ignores stale branches and malformed revisions", () => {
const relatedA = "22222222-2222-4222-8222-222222222222";
const relatedB = "33333333-3333-4333-8333-333333333333";
const base = projectEvent([], { id: "a".repeat(64) });
const [project] = buildProjectReadModels({
projectEvents: [base],
projectRevisionEvents: [
projectRevision(
"b".repeat(64),
"f".repeat(64),
"add-related-channel",
relatedA,
),
projectRevision("c".repeat(64), base.id, "replace-all", relatedB),
projectRevision(
"d".repeat(64),
base.id,
"add-related-channel",
relatedA,
{
tags: [
["a", `30621:${PROJECT_OWNER}:other-project`],
["e", base.id],
["op", "add-related-channel"],
["channel", relatedA],
],
},
),
],
repositoryEvents: [],
relayOrigin: RELAY_ORIGIN,
});
assert.deepEqual(project.relatedChannelIds, []);
assert.equal(project.effectiveRevisionId, base.id);
});
test("buildProjectReadModels keeps unclaimed repositories as implicit projects", () => {
const frontendAddress = `30617:${PROJECT_OWNER}:frontend`;
const projects = buildProjectReadModels({

View File

@@ -1,6 +1,7 @@
import type { RelayEvent } from "@/shared/api/types";
import {
KIND_PROJECT_ANNOUNCEMENT,
KIND_PROJECT_REVISION,
KIND_REPO_ANNOUNCEMENT,
} from "@/shared/constants/kinds";
import { effectiveCloneUrls } from "./lib/projectCloneUrl";
@@ -38,6 +39,8 @@ export type Project = {
* unrecognized metadata, so older readers ignore it.
*/
relatedChannelIds: string[];
/** Current base or collaborative revision id used as the next CAS token. */
effectiveRevisionId?: string;
status: string;
projectAddress: string;
primaryRepositoryAddress: string | null;
@@ -56,6 +59,7 @@ export function isExplicitProject(project: Project): boolean {
type BuildProjectReadModelsInput = {
projectEvents: RelayEvent[];
projectRevisionEvents?: RelayEvent[];
repositoryEvents: RelayEvent[];
/** NIP-09 kind:5 deletion events relevant to projects and repositories. */
deletionEvents?: RelayEvent[];
@@ -381,6 +385,7 @@ export function eventToExplicitProject(
createdAt: event.created_at,
projectChannelId,
relatedChannelIds,
effectiveRevisionId: event.id.toLowerCase(),
status: visibility === "listed" ? "active" : "unlisted",
projectAddress,
primaryRepositoryAddress,
@@ -408,6 +413,7 @@ function repositoryToLegacyProject(repository: Repository): Project {
createdAt: repository.createdAt,
projectChannelId: null,
relatedChannelIds: [],
effectiveRevisionId: repository.id.toLowerCase(),
status: repository.status,
projectAddress: repository.repoAddress,
primaryRepositoryAddress: repository.repoAddress,
@@ -454,6 +460,7 @@ function projectIsListingEligible(
export function buildProjectReadModels({
projectEvents,
projectRevisionEvents = [],
repositoryEvents,
deletionEvents = [],
relayOrigin,
@@ -501,7 +508,7 @@ export function buildProjectReadModels({
return project &&
projectIsListingEligible(project, viewerPubkey) &&
!hiddenAddresses.has(project.projectAddress)
? [project]
? [applyProjectRevisionEvents(project, event.id, projectRevisionEvents)]
: [];
});
const claimedRepositories = new Set(
@@ -525,6 +532,64 @@ export function buildProjectReadModels({
);
}
function singletonRevisionTag(event: RelayEvent, name: string): string | null {
const matches = event.tags.filter(
(tag) => tag.length === 2 && tag[0] === name && Boolean(tag[1]),
);
return matches.length === 1 ? matches[0][1] : null;
}
/** Fold the relay-authorized linear revision chain rooted at a Project head. */
export function applyProjectRevisionEvents(
project: Project,
baseEventId: string,
events: RelayEvent[],
): Project {
let effectiveRevisionId = baseEventId.toLowerCase();
let relatedChannelIds = [...project.relatedChannelIds];
const candidates = events.filter(
(event) =>
event.kind === KIND_PROJECT_REVISION &&
singletonRevisionTag(event, "a") === project.projectAddress,
);
for (;;) {
const next = candidates.find(
(event) =>
singletonRevisionTag(event, "e")?.toLowerCase() === effectiveRevisionId,
);
if (!next) break;
const operation = singletonRevisionTag(next, "op");
const channelId = singletonRevisionTag(next, "channel");
if (!channelId || !isValidProjectChannelId(channelId)) break;
if (operation === "add-related-channel") {
if (
channelId === project.projectChannelId ||
relatedChannelIds.includes(channelId) ||
relatedChannelIds.length >= MAX_PROJECT_RELATED_CHANNELS
) {
break;
}
relatedChannelIds.push(channelId);
} else if (operation === "remove-related-channel") {
if (!relatedChannelIds.includes(channelId)) break;
relatedChannelIds = relatedChannelIds.filter(
(candidate) => candidate !== channelId,
);
} else {
break;
}
effectiveRevisionId = next.id.toLowerCase();
}
return {
...project,
createdAt:
events.find((event) => event.id.toLowerCase() === effectiveRevisionId)
?.created_at ?? project.createdAt,
effectiveRevisionId,
relatedChannelIds,
};
}
export function selectProjectRepository(
project: Project | null | undefined,
requestedRepositoryId: string | null | undefined,

View File

@@ -0,0 +1,102 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildProjectRelatedChannelRevisionTemplate,
removeProjectRelatedChannel,
} from "./projectRelatedChannelRevision.ts";
const HOME = "11111111-1111-4111-8111-111111111111";
const RELATED = "22222222-2222-4222-8222-222222222222";
const OWNER = "a".repeat(64);
function project(overrides = {}) {
return {
effectiveRevisionId: "b".repeat(64),
legacy: false,
projectAddress: `30621:${OWNER}:buzz`,
projectChannelId: HOME,
relatedChannelIds: [],
...overrides,
};
}
test("buildProjectRelatedChannelRevisionTemplate builds add and remove CAS operations", () => {
assert.deepEqual(
buildProjectRelatedChannelRevisionTemplate(
project(),
RELATED,
"add-related-channel",
),
{
kind: 1622,
content: "",
tags: [
["a", `30621:${OWNER}:buzz`],
["e", "b".repeat(64)],
["op", "add-related-channel"],
["channel", RELATED],
],
},
);
assert.equal(
buildProjectRelatedChannelRevisionTemplate(
project({ relatedChannelIds: [RELATED] }),
RELATED,
"remove-related-channel",
).tags[2][1],
"remove-related-channel",
);
});
test("buildProjectRelatedChannelRevisionTemplate rejects stale and invalid mutations", () => {
assert.throws(
() =>
buildProjectRelatedChannelRevisionTemplate(
project({ effectiveRevisionId: undefined }),
RELATED,
"add-related-channel",
),
/Refresh/,
);
assert.throws(
() =>
buildProjectRelatedChannelRevisionTemplate(
project(),
HOME,
"add-related-channel",
),
/home channel/,
);
assert.throws(
() =>
buildProjectRelatedChannelRevisionTemplate(
project({ relatedChannelIds: [RELATED] }),
RELATED,
"add-related-channel",
),
/already related/,
);
});
test("removeProjectRelatedChannel publishes a remove revision and advances local state", async () => {
const calls = [];
const updated = await removeProjectRelatedChannel(
project({ relatedChannelIds: [RELATED] }),
RELATED,
{
signEvent: async (template) => ({
...template,
id: "c".repeat(64),
pubkey: OWNER,
created_at: 123,
}),
publishEvent: async (...args) => calls.push(args),
},
);
assert.equal(calls.length, 1);
assert.equal(calls[0][0].tags[2][1], "remove-related-channel");
assert.deepEqual(updated.relatedChannelIds, []);
assert.equal(updated.effectiveRevisionId, "c".repeat(64));
});

View File

@@ -0,0 +1,98 @@
import type { Project } from "@/features/projects/projectModels";
import { isValidProjectChannelId } from "@/features/projects/projectModels";
import { relayClient } from "@/shared/api/relayClient";
import { signRelayEvent } from "@/shared/api/tauri";
import type { RelayEvent } from "@/shared/api/types";
import { KIND_PROJECT_REVISION } from "@/shared/constants/kinds";
export type ProjectRelatedChannelOperation =
| "add-related-channel"
| "remove-related-channel";
export function buildProjectRelatedChannelRevisionTemplate(
project: Pick<
Project,
| "effectiveRevisionId"
| "legacy"
| "projectAddress"
| "projectChannelId"
| "relatedChannelIds"
>,
channelId: string,
operation: ProjectRelatedChannelOperation,
) {
if (project.legacy || !project.projectAddress.startsWith("30621:")) {
throw new Error("Only explicit Projects can link related channels.");
}
const expectedRevision = project.effectiveRevisionId?.toLowerCase();
if (!expectedRevision || !/^[0-9a-f]{64}$/.test(expectedRevision)) {
throw new Error("Refresh this Project before changing its channels.");
}
const normalizedChannelId = channelId.trim().toLowerCase();
if (!isValidProjectChannelId(normalizedChannelId)) {
throw new Error("Project channel is invalid.");
}
if (normalizedChannelId === project.projectChannelId?.toLowerCase()) {
throw new Error("The Project home channel cannot also be related.");
}
const alreadyRelated = project.relatedChannelIds.some(
(candidate) => candidate.toLowerCase() === normalizedChannelId,
);
if (operation === "add-related-channel" && alreadyRelated) {
throw new Error("That channel is already related to this Project.");
}
if (operation === "remove-related-channel" && !alreadyRelated) {
throw new Error("That channel is not related to this Project.");
}
return {
kind: KIND_PROJECT_REVISION,
content: "",
tags: [
["a", project.projectAddress],
["e", expectedRevision],
["op", operation],
["channel", normalizedChannelId],
],
};
}
export async function publishProjectRelatedChannelRevision(
project: Parameters<typeof buildProjectRelatedChannelRevisionTemplate>[0],
channelId: string,
operation: ProjectRelatedChannelOperation,
deps?: {
publishEvent?: typeof relayClient.publishEvent;
signEvent?: typeof signRelayEvent;
},
): Promise<RelayEvent> {
const event = await (deps?.signEvent ?? signRelayEvent)(
buildProjectRelatedChannelRevisionTemplate(project, channelId, operation),
);
await (deps?.publishEvent ?? relayClient.publishEvent.bind(relayClient))(
event,
"Could not confirm the Project channel change. Refresh before retrying.",
"Could not change the Project's related channels.",
);
return event;
}
export async function removeProjectRelatedChannel(
project: Project,
channelId: string,
deps?: Parameters<typeof publishProjectRelatedChannelRevision>[3],
): Promise<Project> {
const revision = await publishProjectRelatedChannelRevision(
project,
channelId,
"remove-related-channel",
deps,
);
return {
...project,
createdAt: revision.created_at,
effectiveRevisionId: revision.id.toLowerCase(),
relatedChannelIds: project.relatedChannelIds.filter(
(candidate) => candidate.toLowerCase() !== channelId.toLowerCase(),
),
};
}

View File

@@ -2,10 +2,8 @@ import { Plus } from "lucide-react";
import * as React from "react";
import { toast } from "sonner";
import { useIsManagedAgent } from "@/features/agent-memory/hooks";
import { useAppNavigation } from "@/app/navigation/useAppNavigation";
import { useUsersBatchQuery } from "@/features/profile/hooks";
import { ownsAuthorAgent } from "@/features/profile/lib/identity";
import { useChannelMembersQuery } from "@/features/channels/hooks";
import type { Project } from "@/features/projects/hooks";
import { useAddProjectChannelMutation } from "@/features/projects/useAddProjectChannel";
import { CreateChannelDialog } from "@/features/sidebar/ui/CreateChannelDialog";
@@ -21,25 +19,7 @@ export function ProjectChannelManagement({
const { goChannel } = useAppNavigation();
const [createOpen, setCreateOpen] = React.useState(false);
const createMutation = useAddProjectChannelMutation();
const ownerProfileQuery = useUsersBatchQuery([project.owner], {
enabled: Boolean(identityPubkey),
});
const projectOwnerProfile =
ownerProfileQuery.data?.profiles[project.owner.toLowerCase()];
const projectOwnerIsManaged = useIsManagedAgent(project.owner) === true;
const viewerIsProjectOwner =
identityPubkey?.toLowerCase() === project.owner.toLowerCase();
const viewerOwnsProjectAgent = ownsAuthorAgent(
projectOwnerProfile,
identityPubkey,
);
const canEdit =
!project.legacy &&
(viewerIsProjectOwner || projectOwnerIsManaged || viewerOwnsProjectAgent);
const ownerControlAgentPubkey =
viewerOwnsProjectAgent && !projectOwnerIsManaged && !viewerIsProjectOwner
? project.owner
: undefined;
const canEdit = useCanManageProjectChannels(project, identityPubkey);
return (
<>
@@ -51,7 +31,6 @@ export function ProjectChannelManagement({
onCreate={async (input) => {
const result = await createMutation.mutateAsync({
...input,
ownerControlAgentPubkey,
project,
});
toast.success(`Channel "#${result.channel.name}" created.`);
@@ -70,7 +49,9 @@ export function ProjectChannelManagement({
onClick={() => setCreateOpen(true)}
size="icon"
title={
canEdit ? "Add channel" : "Only the project owner can add channels"
canEdit
? "Add channel"
: "Only the Project owner or a home-channel admin can add channels"
}
type="button"
variant="ghost"
@@ -80,3 +61,19 @@ export function ProjectChannelManagement({
</>
);
}
export function useCanManageProjectChannels(
project: Project,
identityPubkey?: string,
): boolean {
const homeMembersQuery = useChannelMembersQuery(project.projectChannelId);
const viewerHomeRole = homeMembersQuery.data?.find(
(member) => member.pubkey.toLowerCase() === identityPubkey?.toLowerCase(),
)?.role;
return (
!project.legacy &&
(identityPubkey?.toLowerCase() === project.owner.toLowerCase() ||
viewerHomeRole === "owner" ||
viewerHomeRole === "admin")
);
}

View File

@@ -26,6 +26,14 @@ import { cn } from "@/shared/lib/cn";
import type { EntityLinkTab } from "@/shared/lib/entityLink";
import { Button } from "@/shared/ui/button";
import { ProjectChannelManagement } from "./ProjectChannelManagement";
import { useCanManageProjectChannels } from "./ProjectChannelManagement";
import { useRemoveProjectRelatedChannelMutation } from "@/features/projects/useRemoveProjectRelatedChannel";
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
} from "@/shared/ui/context-menu";
import { ProjectRepositoryManagement } from "./ProjectRepositoryManagement";
import { SECTION_ACTION_VISIBILITY_CLASS } from "@/features/sidebar/ui/sidebarSectionStyles";
@@ -152,23 +160,22 @@ function ContextNavButton({
function ChannelContextRow({
channel,
onClick,
onRemove,
projectHome,
testId,
}: {
channel: Channel;
onClick?: () => void;
onRemove?: () => void;
projectHome?: boolean;
testId: string;
}) {
const Icon = projectHome ? ProjectChannelIcon : Hash;
if (onClick) {
return (
<ContextNavButton icon={<Icon />} onClick={onClick} testId={testId}>
{channel.name}
</ContextNavButton>
);
}
return (
const row = onClick ? (
<ContextNavButton icon={<Icon />} onClick={onClick} testId={testId}>
{channel.name}
</ContextNavButton>
) : (
<div
className={`${PROJECT_HOME_SIDEBAR_ROW_CLASS} pointer-events-none flex items-center`}
data-testid={testId}
@@ -176,6 +183,17 @@ function ChannelContextRow({
<ContextRowContent icon={<Icon />}>{channel.name}</ContextRowContent>
</div>
);
if (!onRemove) return row;
return (
<ContextMenu>
<ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuItem onSelect={onRemove}>
Remove from Project
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
);
}
export function ProjectHomeContextPanel({
@@ -219,6 +237,11 @@ export function ProjectHomeContextPanel({
...project.repositories.flatMap((repository) => repository.contributors),
]).size;
const activityQuery = useProjectActivitySummariesQuery([project]);
const canManageProjectChannels = useCanManageProjectChannels(
project,
identityPubkey,
);
const removeProjectChannelMutation = useRemoveProjectRelatedChannelMutation();
const activity = activityQuery.data?.[project.id];
const repoStateQuery = useRepoStateQuery(firstRepository);
const defaultBranch = firstRepository
@@ -344,6 +367,15 @@ export function ProjectHomeContextPanel({
? undefined
: () => onOpenChannel(binding.channel.id)
}
onRemove={
!isHome && canManageProjectChannels
? () =>
removeProjectChannelMutation.mutate({
channelId: binding.channel.id,
project,
})
: undefined
}
projectHome={isHome}
testId={
isHome

View File

@@ -16,6 +16,7 @@ function makeProject(overrides = {}) {
createdAt: 100,
projectChannelId: "11111111-1111-4111-8111-111111111111",
relatedChannelIds: [],
effectiveRevisionId: "f".repeat(64),
status: "active",
projectAddress: `30621:${OWNER}:platform`,
primaryRepositoryAddress: null,
@@ -105,7 +106,7 @@ test("addProjectChannel removes its channel and does not publish when the projec
createChannel: async () => ({ id: CREATED_CHANNEL }),
deleteChannel: async (channelId) => deleted.push(channelId),
fetchEvents: async () => fetchResults.shift() ?? [],
publishOwnerAnnouncement: async () => {
publishRevision: async () => {
publishCalls += 1;
throw new Error("must not publish a stale project replacement");
},
@@ -132,7 +133,7 @@ test("addProjectChannel removes its channel when project publication fails", asy
fetchCalls += 1;
return [liveHead];
},
publishOwnerAnnouncement: async () => {
publishRevision: async () => {
throw new Error("publication failed");
},
}),
@@ -142,3 +143,32 @@ test("addProjectChannel removes its channel when project publication fails", asy
assert.equal(fetchCalls, 2);
assert.deepEqual(deleted, [CREATED_CHANNEL]);
});
test("addProjectChannel publishes an actor-signed revision and advances the local CAS head", async () => {
const liveHead = makeLiveHead(100);
const revision = {
id: "e".repeat(64),
kind: 1622,
pubkey: "b".repeat(64),
created_at: 110,
content: "",
tags: [],
};
const calls = [];
const result = await addProjectChannel(input(), {
applyAgents: async () => {},
applyCanvas: async () => {},
createChannel: async () => ({ id: CREATED_CHANNEL }),
fetchEvents: async () => [liveHead],
publishRevision: async (...args) => {
calls.push(args);
return revision;
},
});
assert.deepEqual(calls, [
[input().project, CREATED_CHANNEL, "add-related-channel"],
]);
assert.deepEqual(result.project.relatedChannelIds, [CREATED_CHANNEL]);
assert.equal(result.project.effectiveRevisionId, revision.id);
});

View File

@@ -8,14 +8,16 @@ import {
import { useApplyTemplate } from "@/features/channel-templates/useApplyTemplate";
import { type Project, projectsQueryKey } from "@/features/projects/hooks";
import { isUnsupportedProjectKindError } from "@/features/projects/projectCreation";
import { buildProjectRelatedChannelPatchTemplate } from "@/features/projects/projectChannelCreation";
import { addRelatedChannelToProject } from "@/features/projects/projectModels";
import { publishOwnedAgentProjectAnnouncements } from "@/features/projects/projectOwnerControl";
import { publishProjectRelatedChannelRevision } from "@/features/projects/projectRelatedChannelRevision";
import { markProjectDataAuthoritative } from "@/features/projects/projectSnapshot";
import { publishProjectOwnerAnnouncement } from "@/shared/api/projectGit";
import { relayClient } from "@/shared/api/relayClient";
import { deleteChannel as deleteChannelApi } from "@/shared/api/tauriChannels";
import type { Channel, ChannelVisibility } from "@/shared/api/types";
import type {
Channel,
ChannelVisibility,
RelayEvent,
} from "@/shared/api/types";
import { KIND_PROJECT_ANNOUNCEMENT } from "@/shared/constants/kinds";
export type AddProjectChannelInput = {
@@ -43,8 +45,7 @@ export async function addProjectChannel(
createChannel: ReturnType<typeof useCreateChannelMutation>["mutateAsync"];
deleteChannel?: typeof deleteChannelApi;
fetchEvents?: typeof relayClient.fetchEvents;
publishOwnedAgentAnnouncements?: typeof publishOwnedAgentProjectAnnouncements;
publishOwnerAnnouncement?: typeof publishProjectOwnerAnnouncement;
publishRevision?: typeof publishProjectRelatedChannelRevision;
},
): Promise<{ channel: Channel; project: Project }> {
const {
@@ -53,8 +54,7 @@ export async function addProjectChannel(
createChannel,
deleteChannel = deleteChannelApi,
fetchEvents = relayClient.fetchEvents.bind(relayClient),
publishOwnedAgentAnnouncements = publishOwnedAgentProjectAnnouncements,
publishOwnerAnnouncement = publishProjectOwnerAnnouncement,
publishRevision = publishProjectRelatedChannelRevision,
} = deps;
const targetOwner = input.project.owner.toLowerCase();
@@ -114,60 +114,35 @@ export async function addProjectChannel(
);
}
const templates = buildProjectRelatedChannelPatchTemplate({
channelId: channel.id,
liveHead: confirmedLiveHead,
ownerPubkey: targetOwner,
});
let projectCreatedAt = confirmedLiveHead.created_at;
if (!templates.alreadyBound) {
const createdAt = Math.max(
Math.floor(Date.now() / 1_000),
confirmedLiveHead.created_at + 1,
);
try {
if (input.ownerControlAgentPubkey) {
const events = await publishOwnedAgentAnnouncements(
input.ownerControlAgentPubkey,
[{ ...templates.project, createdAt }],
);
projectCreatedAt =
events.find((event) => event.kind === KIND_PROJECT_ANNOUNCEMENT)
?.created_at ?? createdAt;
} else {
const publication = await publishOwnerAnnouncement({
...templates.project,
createdAt,
targetOwner,
});
if (publication.publicationError) {
throw new Error(publication.publicationError);
}
projectCreatedAt = publication.event.created_at;
}
} catch (error) {
await removeCreatedChannelAndThrow(
isUnsupportedProjectKindError(error)
? new Error(
"This relay does not support projects yet, so the channel could not be linked.",
)
: error instanceof Error
? error
: new Error("Could not link the channel to this project."),
);
}
}
const revision: RelayEvent = await publishRevision(
input.project,
channel.id,
"add-related-channel",
).catch((error: unknown) =>
removeCreatedChannelAndThrow(
isUnsupportedProjectKindError(error)
? new Error(
"This relay does not support collaborative Project channels yet, so the channel could not be linked.",
)
: error instanceof Error
? error
: new Error("Could not link the channel to this project."),
),
);
await applyCanvas(input.templateId, channel.id, input.name);
void applyAgents(input.templateId, channel.id);
return {
channel,
project: addRelatedChannelToProject(
input.project,
channel.id,
projectCreatedAt,
),
project: {
...addRelatedChannelToProject(
input.project,
channel.id,
revision.created_at,
),
effectiveRevisionId: revision.id.toLowerCase(),
},
};
}

View File

@@ -0,0 +1,28 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { projectsQueryKey } from "@/features/projects/hooks";
import type { Project } from "@/features/projects/projectModels";
import { removeProjectRelatedChannel } from "@/features/projects/projectRelatedChannelRevision";
import { markProjectDataAuthoritative } from "@/features/projects/projectSnapshot";
export function useRemoveProjectRelatedChannelMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
channelId,
project,
}: {
channelId: string;
project: Project;
}) => removeProjectRelatedChannel(project, channelId),
onSuccess: (project) => {
markProjectDataAuthoritative(project, "local-write");
queryClient.setQueryData<Project[]>(projectsQueryKey, (current = []) =>
current.map((candidate) =>
candidate.id === project.id ? project : candidate,
),
);
void queryClient.invalidateQueries({ queryKey: projectsQueryKey });
},
});
}

View File

@@ -74,6 +74,8 @@ export const KIND_GIT_PATCH = 1617;
export const KIND_GIT_PULL_REQUEST = 1618;
export const KIND_GIT_PR_UPDATE = 1619;
export const KIND_GIT_ISSUE = 1621;
// NIP-MP: actor-signed, relay-authorized Project revision operation.
export const KIND_PROJECT_REVISION = 1622;
export const KIND_GIT_STATUS_OPEN = 1630;
export const KIND_GIT_STATUS_MERGED = 1631;
export const KIND_GIT_STATUS_CLOSED = 1632;