Skip to content
Open
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
7 changes: 5 additions & 2 deletions FORK.md

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions apps/mobile/src/features/home/HomeScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { useThreadSearch } from "../../state/queries";
import { requestThreadMessageJump } from "../threads/threadMessageJump";
import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches";
import { useThreadListV2 } from "../threads/useThreadListV2";
import { connectingWorkspace, useCrewListWaiting } from "../../j5/crew/spawnedChildren";
import { useThreadListNow } from "../threads/use-thread-list-now";
import { useSearchScrollRestoration } from "../workspace/useSearchScrollRestoration";
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
Expand Down Expand Up @@ -652,8 +653,10 @@ export function HomeScreen(props: HomeScreenProps) {
workingShelfEnabled,
};

// J5 (case 115): threads waiting for their first spawned-children answer are still loading.
const j5ListWaiting = useCrewListWaiting(props.threads);
const hasAnyThreads =
props.threads.some((thread) => thread.archivedAt === null) ||
(!j5ListWaiting && props.threads.some((thread) => thread.archivedAt === null)) ||
props.pendingTasks.length > 0 ||
threadListV2Layout.settledCount > 0;
const selectedEnvironmentLabel =
Expand All @@ -662,7 +665,7 @@ export function HomeScreen(props: HomeScreenProps) {
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
catalogState: j5ListWaiting ? connectingWorkspace(props.catalogState) : props.catalogState,
projectCount: props.projects.length,
});

Expand Down
5 changes: 4 additions & 1 deletion apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { useThreadListV2 } from "./useThreadListV2";
import { useCrewListWaiting } from "../../j5/crew/spawnedChildren";
import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
import { requestThreadMessageJump } from "./threadMessageJump";
import { useThreadListSearchMatches } from "./useThreadListSearchMatches";
Expand Down Expand Up @@ -680,6 +681,8 @@ function ThreadNavigationSidebarPane(
filterMenu,
onOpenSettings: props.onOpenSettings,
});
// J5 (case 115): threads waiting for their first spawned-children answer are still loading.
const j5ListWaiting = useCrewListWaiting(threads);
const listEmpty = (
<Text
className={
Expand All @@ -688,7 +691,7 @@ function ThreadNavigationSidebarPane(
: "px-2 py-4 text-sm text-drawer-foreground-muted"
}
>
{catalogState.isLoadingConnections
{catalogState.isLoadingConnections || j5ListWaiting
? "Loading threads…"
: Platform.OS === "android" && !catalogState.hasConnections
? "No environments connected"
Expand Down
3 changes: 2 additions & 1 deletion apps/mobile/src/features/threads/thread-work-log.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";

import { AppText as Text } from "../../components/ui/AppText";
import { J5Wordmark } from "../../j5/branding/J5Wordmark";
import { PromptAnsweredBy } from "../../j5/sharing/sharedConversation";
import { answeredByFollowsLabel, PromptAnsweredBy } from "../../j5/sharing/sharedConversation";
import { BrowserAppIcon } from "./BrowserAppIcon";
import { useAppActive, useReduceMotionEnabled } from "../../lib/appState";
import { cn } from "../../lib/cn";
Expand Down Expand Up @@ -1158,6 +1158,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
</WorkLogIconSlot>
<WorkLogLabel
tone={isUsageLimit ? "warning" : iconIsDestructive ? "danger" : "default"}
fitText={answeredByFollowsLabel(row.projectedItem.item, answered)}
>
{historyHasQuestion && expanded ? null : displayText}
{answerPreview && !answered ? (
Expand Down
6 changes: 5 additions & 1 deletion apps/mobile/src/features/threads/work-log-layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,21 @@ export function WorkLogPressable({
export function WorkLogLabel({
children,
tone = "default",
fitText = false,
}: {
children: ReactNode;
tone?: "default" | "danger" | "warning";
/** J5 (case 99): the label ends with its text, and what follows it takes the spare width. */
fitText?: boolean;
}) {
return (
<Text
selectable={false}
numberOfLines={1}
ellipsizeMode="tail"
className={cn(
"min-w-0 flex-1 text-sm text-foreground-muted",
"min-w-0 text-sm text-foreground-muted",
fitText ? "shrink" : "flex-1",
tone === "danger" && "font-t3-medium text-adaptive-rose-600-400",
tone === "warning" && "font-t3-medium text-warning-foreground",
)}
Expand Down
77 changes: 49 additions & 28 deletions apps/mobile/src/j5/a2a/participantIdentities.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,67 @@
import { readParticipantIdentities } from "@t3tools/client-runtime/j5/archive-flow";
import { useAtomValue } from "@effect/atom-react";
import type { ParticipantIdentities } from "@t3tools/client-runtime/j5/participant-identity";
import type { EnvironmentId } from "@t3tools/contracts";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useSyncExternalStore } from "react";

import { appAtomRegistry } from "../../state/atom-registry";
import { useWorkspaceEnvironments } from "../../state/workspace";
import { j5Environment } from "../state";
import { connectionMemory, namesExpectedAtom } from "../connection/memory";
import { pendingParticipants } from "../connection/memory.logic";

export const NO_IDENTITIES: ParticipantIdentities = { labels: new Map(), threads: new Map() };
const NO_ONE: ReadonlySet<string> = new Set();

export interface ScreenIdentities extends ParticipantIdentities {
/** Participants whose name is on its way: say nothing for them yet rather than a fallback. */
readonly pending: ReadonlySet<string>;
}

export const useConnectedEnvironmentIds = (): ReadonlySet<EnvironmentId> => {
const environments = useWorkspaceEnvironments();
const key = environments
.flatMap((environment) =>
environment.connectionState === "connected" ? [environment.environmentId] : [],
)
.sort()
.join("\n");
return useMemo(() => new Set(key === "" ? [] : (key.split("\n") as Array<EnvironmentId>)), [key]);
};

/**
* One identity read for the ids on screen; unknowns stay absent and a failed read names nobody.
* A read sent before the environment connects fails, so it waits for the connection and runs
* again on each reconnect.
* Names for the ids on screen, kept per server and paired credential, so a revisit or a new
* sender never drops the names already shown. They are read again as the screen mounts or
* reconnects; a read sent before the environment connects fails, so it waits for the connection.
*/
export function useParticipantIdentities(
environmentId: EnvironmentId,
participantIds: ReadonlyArray<string>,
): ParticipantIdentities {
): ScreenIdentities {
const idsKey = Array.from(new Set(participantIds)).sort().join("\0");
// A result answers one environment's ids; another environment's never stands in for it.
const key = `${environmentId}\n${idsKey}`;
const connected = useWorkspaceEnvironments().some(
(environment) =>
environment.environmentId === environmentId && environment.connectionState === "connected",
const connected = useConnectedEnvironmentIds().has(environmentId);
// Through a re-pair's first connection too, so the line never swaps a stand-in for the name.
const expected = useAtomValue(namesExpectedAtom).has(environmentId);
const { names: known, settled } = useSyncExternalStore(
connectionMemory.subscribe,
connectionMemory.getSnapshot,
connectionMemory.getSnapshot,
);
const [result, setResult] = useState({ key: "", identities: NO_IDENTITIES });
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads identities from the server for the ids on screen, and drops a stale answer when they change.
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads the names of the ids on screen from the server, again on each connection.
useEffect(() => {
if (idsKey === "" || !connected) return;
let active = true;
void readParticipantIdentities(
j5Environment,
appAtomRegistry,
void connectionMemory.readNames(environmentId, idsKey.split("\0"));
}, [connected, environmentId, idsKey]);
const names = known.get(environmentId) ?? NO_IDENTITIES;
const pendingKey = [
...pendingParticipants(
known,
settled,
environmentId,
idsKey.split("\0"),
).then((identities) => {
if (active) setResult({ key, identities });
});
return () => {
active = false;
};
}, [connected, environmentId, idsKey, key]);
return result.key === key ? result.identities : NO_IDENTITIES;
idsKey === "" ? [] : idsKey.split("\0"),
expected,
),
].join("\0");
const pending = useMemo(
() => (pendingKey === "" ? NO_ONE : new Set(pendingKey.split("\0"))),
[pendingKey],
);
return useMemo(() => ({ ...names, pending }), [names, pending]);
}
30 changes: 14 additions & 16 deletions apps/mobile/src/j5/a2a/timeline.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
j5MessageAuthorName,
j5SenderThreadRef,
} from "@t3tools/client-runtime/j5/participant-identity";
import { j5MessageAuthorName } from "@t3tools/client-runtime/j5/participant-identity";
import {
crewApprovalSummary,
crewDeclinedSummary,
Expand All @@ -26,6 +23,7 @@ import { useQuietThreadShell } from "../../state/entities";
import { PersonAvatar } from "../sharing/PersonAvatar";
import { SharedConversationNote } from "../sharing/SharedConversationNote";
import {
j5TimelineSenderRef,
presentJ5TimelineNotice,
type J5FeedMessagePresentation,
type J5Timeline,
Expand Down Expand Up @@ -305,15 +303,10 @@ function useSenderThread(
presentation: J5FeedMessagePresentation,
timeline: J5Timeline,
) {
const ref = j5SenderThreadRef({
environmentId: timeline.environmentId,
presentation: presentation.j5,
messageSenderThreadId: message.senderThreadId,
participantThreads: timeline.threads,
});
const ref = j5TimelineSenderRef(message, presentation.j5, timeline);
// A peer's thread opens only from a client connected to that peer, and only if the person can
// see it there; the client's own thread list answers both.
const shell = useQuietThreadShell(presentation.j5?.group === "participant" ? ref : null);
const shell = useQuietThreadShell(ref);
return { ref: shell === null ? null : ref, title: shell?.title };
}

Expand Down Expand Up @@ -389,11 +382,16 @@ function ParticipantAuthorLine(props: {
const { j5 } = props;
const openLinkedThread = useOpenLinkedThread();
const sender = useSenderThread(props.message, props.presentation, props.timeline);
const name = j5MessageAuthorName({
presentation: j5,
participantLabels: props.timeline.labels,
senderThreadTitle: sender.title,
});
// A sender whose name is on its way keeps the line's height without a stand-in word.
const named =
j5.senderId === null || !props.timeline.pending.has(j5.senderId) || !!sender.title?.trim();
const name = named
? j5MessageAuthorName({
presentation: j5,
participantLabels: props.timeline.labels,
senderThreadTitle: sender.title,
})
: " ";
const { ref } = sender;
return (
<View className="mb-1 max-w-[85%] flex-row items-center gap-1.5 pl-1">
Expand Down
37 changes: 36 additions & 1 deletion apps/mobile/src/j5/a2a/timelinePresentation.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { J5_A2A_DELIVERY_MESSAGE_PREFIX } from "@t3tools/client-runtime/j5/user-message";
import { EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";

import {
j5FoldHeader,
j5TimelineSenderRef,
presentJ5QueuedMessage,
presentJ5TimelineNotice,
resolveJ5FeedMessage,
Expand All @@ -21,6 +22,10 @@ const timeline = (viewerParticipantId: string | null): J5Timeline => ({
viewerParticipantId,
labels: new Map(),
threads: new Map(),
pending: new Set(),
accessConfirmed: true,
narrow: false,
threadListLive: true,
sharedAuthors: new Map(),
});

Expand Down Expand Up @@ -280,3 +285,33 @@ describe("j5FoldHeader", () => {
});
});
});

describe("j5TimelineSenderRef", () => {
const here = EnvironmentId.make("environment-here");
const letter = { ...delivery("agent", askRaw), senderThreadId: "thread-captain" };
const sender = (overrides: Partial<J5Timeline>) =>
j5TimelineSenderRef(letter, resolveJ5FeedMessage(letter, timeline(null)).j5, {
...timeline(null),
...overrides,
});

it("gives a narrower person only the sender thread the server named for them", () => {
// After a re-pair the thread list can still hold the last person's Captain thread.
expect(sender({ narrow: true })).toBeNull();
const named = { environmentId: here, threadId: ThreadId.make("thread-named") };
expect(sender({ narrow: true, threads: new Map([["agent:captain", named]]) })).toEqual(named);
expect(sender({})).toEqual({ environmentId: here, threadId: "thread-captain" });
});

it("names no sender thread until the server says who the new person is", () => {
expect(sender({ accessConfirmed: false })).toBeNull();
});

it("links a narrower person's sender only once the thread list was read for them", () => {
const named = { environmentId: here, threadId: ThreadId.make("thread-captain") };
const threads = new Map([["agent:captain", named]]);
// Re-paired as a Viewer, the list still holds the Owner's threads while it resyncs.
expect(sender({ narrow: true, threads, threadListLive: false })).toBeNull();
expect(sender({ narrow: true, threads, threadListLive: true })).toEqual(named);
});
});
33 changes: 33 additions & 0 deletions apps/mobile/src/j5/a2a/timelinePresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
type CrewNoticePresentation,
} from "@t3tools/client-runtime/j5/crew-notices";
import {
j5SenderThreadRef,
nameJ5NoticeParticipants,
type ParticipantIdentities,
} from "@t3tools/client-runtime/j5/participant-identity";
Expand All @@ -14,6 +15,7 @@ import {
type J5NoticeKind,
type J5PromptKind,
type J5UserMessageInput,
type J5UserMessagePresentation,
} from "@t3tools/client-runtime/j5/user-message";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MessageAuthor } from "@t3tools/contracts/j5";
Expand All @@ -23,6 +25,14 @@ import type { MessageAuthor } from "@t3tools/contracts/j5";
* who sent each message of a shared conversation.
*/
export interface J5Timeline extends ParticipantIdentities {
/** Senders whose name is still on its way. */
readonly pending: ReadonlySet<string>;
/** False after a re-pair until the server says who the new person is: no sender threads yet. */
readonly accessConfirmed: boolean;
/** The person reaches less than the whole server. */
readonly narrow: boolean;
/** The server's thread list was read over this connection, not kept from an earlier one. */
readonly threadListLive: boolean;
readonly environmentId: EnvironmentId;
readonly viewerParticipantId: string | null;
readonly sharedAuthors: ReadonlyMap<string, MessageAuthor>;
Expand Down Expand Up @@ -134,3 +144,26 @@ export function presentJ5TimelineNotice(
detail: notice.detail === null ? null : named(notice.detail),
};
}

/**
* The thread a letter's sender works in, as far as this person may know it. A narrower person
* gets only what the server's identity read names for them, and only once the thread list is
* live: until then it can still hold the last person's threads after a re-pair.
*/
export function j5TimelineSenderRef(
message: J5UserMessageInput & { readonly senderThreadId?: string | undefined },
presentation: J5UserMessagePresentation | null,
timeline: J5Timeline,
) {
if (presentation?.group !== "participant" || !timeline.accessConfirmed) return null;
if (timeline.narrow)
return presentation.senderId === null || !timeline.threadListLive
? null
: (timeline.threads.get(presentation.senderId) ?? null);
return j5SenderThreadRef({
environmentId: timeline.environmentId,
presentation,
messageSenderThreadId: message.senderThreadId,
participantThreads: timeline.threads,
});
}
8 changes: 8 additions & 0 deletions apps/mobile/src/j5/a2a/timelineState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
} from "@t3tools/client-runtime/j5/user-message";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";

import { environmentShell } from "../../state/shell";
import { accessConfirmedAtom } from "../connection/memory";
import { j5Sharing } from "../sharing/guestAccess";
import { useThreadAuthorIndex } from "../sharing/sharedConversation";
import { useParticipantIdentities } from "./participantIdentities";
Expand All @@ -17,13 +19,19 @@ export function useJ5Timeline(
messages: ReadonlyArray<J5UserMessageInput>,
): J5Timeline {
const access = useAtomValue(j5Sharing.connectionAccess(environmentId));
const accessConfirmed = useAtomValue(accessConfirmedAtom(environmentId));
const narrow = useAtomValue(j5Sharing.isNarrow(environmentId));
const threadListLive = useAtomValue(environmentShell.statusAtom(environmentId)) === "live";
const { authors } = useThreadAuthorIndex(environmentId, threadId);
const identities = useParticipantIdentities(
environmentId,
messages.flatMap((message) => participantIdsForJ5UserMessage(message)),
);
return {
...identities,
accessConfirmed,
narrow,
threadListLive,
environmentId,
viewerParticipantId: access?.kind === "person" ? access.personId : null,
sharedAuthors: authors,
Expand Down
Loading
Loading