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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FORK.md
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ migrations after upstream migrations.

93. `vp run check:changed` compares against J5's trunk ([#701](https://github.com/Jacksondr5/j5code/issues/701)). Upstream's `scripts/check-changed.ts` defaults its base ref to `origin/main`, which a J5 clone does not have, so a bare run stopped with "no merge base". The default is `origin/j5/main` (the `ref` line and the usage comment above it); a ref passed on the command line still wins. Upstream's `docs/operations/development.md` keeps its `origin/main` wording, as J5 does not edit upstream's docs. On every rebase, keep the default when upstream rewrites the script.

94. Cmd+K names who wrote a person's message it found ([#809](https://github.com/Jacksondr5/j5code/issues/809)). Upstream labels every user-role hit "You:", which is wrong for anyone else's words in a shared conversation. Upstream's `OrchestrationThreadSearchMatch` (`packages/contracts/src/threadSearch.ts`) gains an optional `author`, J5's `ThreadSearchAuthor` (`you`, or `person` with the name they wrote under). The server fills it in J5-owned code: `connectionView` (case 69) labels each search's matches through `apps/server/src/j5/sharing/searchAuthors.ts`, by the message's `j5_a2a_message_author` record (case 80), or as the first owner's when a person typed it before the thread was shared. ws.ts is unchanged. On the web, `ThreadSearchMatchExcerpt` (`apps/web/src/components/ThreadSearchMatch.tsx`) draws `threadSearchMatchLabel` (`apps/web/src/j5/sharing/searchAuthorLabel.ts`) in place of its "You"/"Agent" choice, and the author is passed through `CommandPaletteThreadContentMatch` (`CommandPalette.logic.ts`), `CommandPaletteThreadItems.tsx` and the sidebar's `SidebarThreadRow.tsx`. A match without `author`, from an older server or any message no person typed, keeps upstream's label. Mobile's palette still says "You". On every rebase, keep the field on the match and the one-line label call.
94. Cmd+K names who wrote a person's message it found ([#809](https://github.com/Jacksondr5/j5code/issues/809)). Upstream labels every user-role hit "You:", which is wrong for anyone else's words in a shared conversation. Upstream's `OrchestrationThreadSearchMatch` (`packages/contracts/src/threadSearch.ts`) gains an optional `author`, J5's `ThreadSearchAuthor` (`you`, or `person` with the name they wrote under). The server fills it in J5-owned code: `connectionView` (case 69) labels each search's matches through `apps/server/src/j5/sharing/searchAuthors.ts`, by the message's `j5_a2a_message_author` record (case 80), or as the first owner's when a person wrote it while the first owner was the only person who could write there, typed or as an Inbox reply (`typedByFirstOwner` in `messageStamps.ts`, which case 80's `listThreadAuthors` uses too, so the timeline agrees). ws.ts is unchanged. On the web, `ThreadSearchMatchExcerpt` (`apps/web/src/components/ThreadSearchMatch.tsx`) draws `threadSearchMatchLabel` (`apps/web/src/j5/sharing/searchAuthorLabel.ts`) in place of its "You"/"Agent" choice, and the author is passed through `CommandPaletteThreadContentMatch` (`CommandPalette.logic.ts`), `CommandPaletteThreadItems.tsx` and the sidebar's `SidebarThreadRow.tsx`. A match without `author`, from an older server or any message no person typed, keeps upstream's label. Mobile's palette still says "You". On every rebase, keep the field on the match and the one-line label call.

## Pin and upstream advance runbook

Expand Down
146 changes: 143 additions & 3 deletions apps/server/src/j5/sharing/SharedConversation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import type { PersonLevel, PersonScope } from "@t3tools/contracts/j5";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/sql/SqlClient";
import * as TestClock from "effect/testing/TestClock";

import type { ParticipantId } from "../a2a/contracts.ts";
import { Access } from "./Access.ts";
Expand All @@ -35,11 +38,15 @@ const jackson = Effect.gen(function* () {
return owner.personId;
});

/** A person given levels the way an Owner gives them: through the access core. */
/** Past `AT`, when a thread is shared after the messages these tests write at `AT`. */
const AFTER = Date.parse(AT) + 60_000;

/** A person given levels the way an Owner gives them: through the access core, after `AT`. */
const personWith = Effect.fn("test.personWith")(function* (
name: string,
levels: ReadonlyArray<{ readonly scope: PersonScope; readonly level: PersonLevel }>,
) {
if ((yield* Clock.currentTimeMillis) < AFTER) yield* TestClock.setTime(AFTER);
const people = yield* PersonAccess;
const access = yield* Access;
const created = yield* people.createPerson({ displayName: name });
Expand Down Expand Up @@ -219,6 +226,8 @@ it.effect(
[
{ name: "Jackson", level: "owner", you: false, hasNote: true },
{ name: "Priya", level: "collaborator", you: true, hasNote: false },
// The message from before sharing, which no one is recorded for: the first owner's.
{ name: "Jackson", level: "owner", you: false, hasNote: false },
],
);
// The prefix a client strips is exactly what the platform put on the stored text.
Expand Down Expand Up @@ -338,15 +347,27 @@ it.effect("a fork names who wrote the messages it shows, and none after its fork
return forked;
});
const fork = yield* forkFrom("thread:fork", source, `run:${second.messageId}`);
// The fork's own message, from a thread only one person writes to, names no one.
// The fork's own message, from a thread only one person writes to, is recorded for no one:
// the first owner's, to its forks too.
yield* taken(fork, "message:fork-own", "completed");
const forkOfFork = yield* forkFrom("thread:fork-of-fork", fork, "run:message:fork-own");

const sourceRead = yield* authors(source, priya);
for (const threadId of [fork, forkOfFork]) {
const read = yield* authors(threadId, priya);
assert.isFalse(read.shared);
assert.deepStrictEqual(read.authors, sourceRead.authors.slice(0, 2));
assert.deepStrictEqual(read.authors, [
...sourceRead.authors.slice(0, 2),
{
messageId: "message:fork-own",
name: "Jackson",
level: "owner",
editedBy: null,
you: false,
note: null,
storedPrefix: "",
},
]);
}
assert.deepStrictEqual(
sourceRead.authors.map((entry) => entry.messageId),
Expand All @@ -355,6 +376,125 @@ it.effect("a fork names who wrote the messages it shows, and none after its fork
}).pipe(Effect.provide(conversationLayer)),
);

/**
* A message upstream holds with no author recorded here, as the origin says, written at
* `createdAt` (`AT` by default) with a completed run.
*/
const unrecorded = Effect.fn("test.unrecorded")(function* (
threadId: ThreadId,
messageId: string,
origin: Record<string, unknown>,
createdAt = AT,
) {
const sql = yield* SqlClient.SqlClient;
yield* taken(threadId, messageId, "completed");
yield* sql`
UPDATE orchestration_v2_projection_messages
SET created_at = ${createdAt}, payload_json = ${JSON.stringify({ text: messageId, ...origin })}
WHERE message_id = ${messageId}
`;
});

const typed = { createdBy: "user", creationSource: "web" };
/** What upstream writes when a person declines an approval with feedback. */
const feedback = { createdBy: "user", creationSource: "server" };
const asOwner = (messageId: string) => ({
messageId,
name: "Jackson",
level: "owner" as const,
editedBy: null,
you: false,
note: null,
storedPrefix: "",
});
const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis));

it.effect("a message a person wrote before sharing is the first owner's to everyone else", () =>
Effect.gen(function* () {
const owner = yield* jackson;
const threadId = yield* thread("thread:before-sharing");
yield* unrecorded(threadId, "message:typed", typed);
yield* unrecorded(threadId, "message:j5:a2a:delivery:inbox", {
createdBy: "user",
creationSource: "mcp",
});
// None of these was written by a person.
yield* unrecorded(threadId, "message:j5:a2a:delivery:agent", {
createdBy: "agent",
creationSource: "mcp",
});
yield* unrecorded(threadId, "message:j5:a2a:delivery:notice", {
createdBy: "system",
creationSource: "mcp",
});
yield* unrecorded(threadId, "message:session", { createdBy: "user", creationSource: "mcp" });
yield* unrecorded(threadId, "message:scheduled", {
...typed,
scheduledTaskId: "task:nightly",
});
yield* unrecorded(threadId, "message:sent", { ...typed, senderThreadId: "thread:elsewhere" });
const priya = yield* personWith("Priya", onThread(threadId));
const sam = yield* personWith("Sam", onThread(threadId, "viewer"));
// Once Priya can write, every person's message is recorded: what is not, the server wrote,
// such as an approval's feedback, from the moment she could on.
yield* unrecorded(threadId, "approval-feedback:at-sharing", feedback, iso(AFTER));
yield* unrecorded(threadId, "approval-feedback:later", feedback, iso(AFTER + 60_000));

for (const reader of [priya, sam]) {
assert.deepStrictEqual((yield* authors(threadId, reader)).authors, [
asOwner("message:typed"),
asOwner("message:j5:a2a:delivery:inbox"),
]);
}
// The first owner's own view draws them as theirs already.
assert.deepStrictEqual((yield* authors(threadId, owner)).authors, []);
}).pipe(Effect.provide(conversationLayer)),
);

it.effect("a thread shared only with Viewers keeps the first owner's later messages theirs", () =>
Effect.gen(function* () {
const threadId = yield* thread("thread:viewers-only");
yield* jackson;
const sam = yield* personWith("Sam", onThread(threadId, "viewer"));
// Sent after Sam could read the thread: a Viewer does not make it shared, so none is recorded.
yield* unrecorded(threadId, "message:while-watched", typed, iso(AFTER + 60_000));

const read = yield* authors(threadId, sam);
assert.isFalse(read.shared);
assert.deepStrictEqual(read.authors, [asOwner("message:while-watched")]);
}).pipe(Effect.provide(conversationLayer)),
);

it.effect("a fork reads each inherited message against its own thread's sharing", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* jackson;
const source = yield* thread("thread:fork-cutoff-source");
yield* unrecorded(source, "message:source-before", typed);
const priya = yield* personWith("Priya", onThread(source));
yield* unrecorded(source, "approval-feedback:source", feedback, iso(AFTER + 60_000));
const fork = yield* thread("thread:fork-cutoff", PROJECT, {
parent: source,
relationship: "fork",
});
yield* sql`
UPDATE orchestration_v2_projection_threads
SET payload_json = json_set(payload_json, '$.forkedFrom',
json_object('type', 'run', 'threadId', ${source}, 'runId', 'run:approval-feedback:source'))
WHERE thread_id = ${fork}
`;
const sam = yield* personWith("Sam", onThread(fork, "viewer"));

// The fork is shared with no writer, but the feedback came after its source was shared.
for (const reader of [priya, sam]) {
assert.deepStrictEqual(
(yield* authors(fork, reader)).authors.map((entry) => entry.messageId),
["message:source-before"],
);
}
}).pipe(Effect.provide(conversationLayer)),
);

it.effect("a fork tells its reader only what they could know of who wrote before it", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
Expand Down
68 changes: 62 additions & 6 deletions apps/server/src/j5/sharing/SharedConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/sql/SqlClient";
import type * as Statement from "effect/sql/Statement";
import type * as SqlError from "effect/sql/SqlError";

import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts";
Expand Down Expand Up @@ -297,8 +298,8 @@ const make = Effect.gen(function* () {
const unrecordedAuthor = Effect.fn("j5.sharing.sharedConversation.unrecordedAuthor")(function* (
messageId: string,
) {
const rows = yield* sql<MessageOrigin>`
SELECT ${sql.literal(messageOriginColumns("message"))}
const rows = yield* sql<MessageOrigin & { readonly message_id: string }>`
SELECT message.message_id, ${sql.literal(messageOriginColumns("message"))}
FROM orchestration_v2_projection_messages AS message WHERE message_id = ${messageId}
`;
const row = rows[0];
Expand Down Expand Up @@ -542,6 +543,57 @@ const make = Effect.gen(function* () {
}).pipe(Effect.catch(failClosed));
});

/**
* A thread's messages, its own and those a fork shows, that no person is recorded for but a
* person wrote: the first owner's, as search names them (`typedByFirstOwner`). Their own view
* draws them as theirs already, so they are read only for anyone else.
*/
const firstOwnersUnrecorded = Effect.fn("j5.sharing.sharedConversation.firstOwnersUnrecorded")(
function* (
viewer: ParticipantId | null,
threadId: ThreadId,
forkSources: Statement.Fragment,
mayKnow: (personId: string) => Effect.Effect<boolean, PersonAccessStorageError>,
) {
const owner = yield* people.firstOwner;
if (owner.personId === viewer) return [];
const rows = yield* sql<MessageOrigin & { readonly message_id: string }>`
${forkSources}
SELECT message.message_id, ${sql.literal(messageOriginColumns("message"))}
FROM orchestration_v2_projection_messages AS message
WHERE message.thread_id = ${threadId} AND message.role = 'user'
AND NOT EXISTS (
SELECT 1 FROM j5_a2a_message_author AS author
WHERE author.thread_id = message.thread_id AND author.message_id = message.message_id
)
UNION ALL
SELECT message.message_id, ${sql.literal(messageOriginColumns("message"))}
FROM source
JOIN orchestration_v2_projection_runs AS forked_at ON forked_at.run_id = source.run_id
JOIN orchestration_v2_projection_messages AS message
ON message.thread_id = source.thread_id AND message.role = 'user'
JOIN orchestration_v2_projection_runs AS run
ON run.run_id = message.run_id AND run.ordinal <= forked_at.ordinal
WHERE NOT EXISTS (
SELECT 1 FROM j5_a2a_message_author AS author
WHERE author.thread_id = message.thread_id AND author.message_id = message.message_id
)
`;
const written = rows.filter(typedByFirstOwner);
if (written.length === 0) return [];
const name = (yield* mayKnow(owner.personId)) ? owner.displayName : null;
return written.map((row): MessageAuthor => ({
messageId: row.message_id,
name,
level: "owner",
editedBy: null,
you: false,
note: null,
storedPrefix: "",
}));
},
);

const threadAuthors: SharedConversationShape["threadAuthors"] = Effect.fn(
"j5.sharing.sharedConversation.threadAuthors",
)(function* (viewer, threadId) {
Expand All @@ -552,9 +604,7 @@ const make = Effect.gen(function* () {
// upstream's `buildVisibleTurnItems` does; those keep their authors, and nothing past the fork
// point is named. A reader need not reach the source, so an inherited record applies only where
// the shown text begins with its prefix, restating what they already receive.
const authors = yield* sql<
AuthorRow & { readonly created_at: string; readonly inherited: 0 | 1 }
>`
const forkSources = sql`
WITH RECURSIVE source (thread_id, run_id) AS (
SELECT json_extract(payload_json, '$.forkedFrom.threadId'),
json_extract(payload_json, '$.forkedFrom.runId')
Expand All @@ -567,6 +617,11 @@ const make = Effect.gen(function* () {
JOIN orchestration_v2_projection_threads AS thread ON thread.thread_id = source.thread_id
WHERE json_extract(thread.payload_json, '$.forkedFrom.type') = 'run'
)
`;
const authors = yield* sql<
AuthorRow & { readonly created_at: string; readonly inherited: 0 | 1 }
>`
${forkSources}
SELECT message_id, person_id, display_name, level, edited_by, note, told_json,
stored_prefix, created_at, 0 AS inherited
FROM j5_a2a_message_author
Expand Down Expand Up @@ -618,6 +673,7 @@ const make = Effect.gen(function* () {
known.set(personId, visible);
return visible;
});
const unrecorded = yield* firstOwnersUnrecorded(viewer, threadId, forkSources, mayKnow);
const told = yield* Effect.forEach(authors, (row) =>
Effect.gen(function* () {
const author: MessageAuthor = {
Expand All @@ -635,7 +691,7 @@ const make = Effect.gen(function* () {
);
return {
shared: recorded.length > 0,
authors: told,
authors: [...told, ...unrecorded],
answers: answers.map((row): PromptAnswer => ({
requestId: row.request_id,
name: row.display_name,
Expand Down
Loading
Loading