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
24 changes: 24 additions & 0 deletions UPSTREAM.md
Original file line number Diff line number Diff line change
Expand Up @@ -2290,3 +2290,27 @@ When T3 changes those viewers' open or layout code, carry it into the session fu
When aligning, check that T3's `OfficePages` props, the paint keys (`paint:`, `slide:`) and the
worker method maps still meet these seams. A T3 text layer for slides, or find of its own, should
replace Scient's rather than run beside it.

## Subagent thread fields

T3's `makeSubagentChildThread` (`packages/provider-core/src/server/subagentProjection.ts`) builds a
subagent from a copy of its parent thread. Delegated tasks and Claude's and Codex's native
subagents all use it. A copy carried Scient's own thread state into every subagent: a subagent of a
forked conversation claimed to be that fork, so `delegate_task` from a fork failed and fork, import,
rollback and usage-limit readers misjudged the subagent. `SCIENT_DERIVED_THREAD_RESETS`
(`scientDerivedThread.ts`) is spread after the copy inside the `derived-thread-fields` seam. It also
resets the parent's opens, list position and snooze wake, as T3's own fork does. The seam's other
line drops `delegatedFrom`, matching T3's open pingdotgg/t3code#30334 word for word; once T3 merges
it, that line gives way to T3's. The field table in `scient-fork/DelegatedTaskFromFork.test.ts`
decides every thread field for subagents, so an alignment that adds one fails typecheck until it
is classified.

## Copied guest links

Forks made before #914 copied their source's `guestShare`, so an invite to the source could open
the fork. A thread is always created without a share of its own, so a share already in its
`thread.created` event was copied (`scient/guest/ownGuestShare.ts`). The `copied-guest-share`
seams in T3's `ProjectionStore.findGuestShareThreadId` and `GuestShareService.authorize` refuse
such a share, for invites and for sessions already redeemed. They protect forks already in users'
databases, whose events still carry the copy, and need `thread.created` events to stay unpruned,
as T3's maintenance keeps them. T3 has no copy path, so it needs no such check.
12 changes: 12 additions & 0 deletions apps/server/src/guest/GuestShareService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
import { guestShareView, guestThreadModel } from "./guestView.ts";
// SCIENT-FORK:START copied-guest-share
import * as SqlClient from "effect/sql/SqlClient";
import { shareCopiedAtCreation } from "../scient/guest/ownGuestShare.ts";
// SCIENT-FORK:END
import {
classifyGuestUploads,
GUEST_UPLOAD_HEADER_BYTES,
Expand Down Expand Up @@ -219,6 +223,9 @@ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread |

const make = Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
// SCIENT-FORK:START copied-guest-share
const sql = yield* SqlClient.SqlClient;
// SCIENT-FORK:END
const commandOutputs = yield* CommandOutputHub.CommandOutputHub;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const serverSettings = yield* ServerSettings.ServerSettingsService;
Expand Down Expand Up @@ -328,6 +335,11 @@ const make = Effect.gen(function* () {
thread.deletedAt !== null ||
DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt) ||
(kind === "session" && share.guestName === null) ||
// SCIENT-FORK:START copied-guest-share
(yield* shareCopiedAtCreation(sql, thread.id, share.id).pipe(
Effect.orElseSucceed(() => true),
)) ||
// SCIENT-FORK:END
(yield* connectHostname) !== share.host
) {
return yield* inactive;
Expand Down
10 changes: 8 additions & 2 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
// SCIENT-FORK:START
import * as Option from "effect/Option";
import { shareCopiedAtCreation } from "../scient/guest/ownGuestShare.ts";
// SCIENT-FORK:END
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
Expand Down Expand Up @@ -9563,13 +9564,18 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
const findGuestShareThreadId = Effect.fn("ProjectionStore.findGuestShareThreadId")(function* (
shareId: GuestShareId,
) {
// SCIENT-FORK:START copied-guest-share — a copied share never wins the lookup.
const rows = yield* sql<{ readonly thread_id: string }>`
SELECT thread_id
FROM orchestration_v2_projection_threads
WHERE json_extract(payload_json, '$.guestShare.id') = ${shareId}
LIMIT 1
`;
return rows[0] === undefined ? null : ThreadId.make(rows[0].thread_id);
for (const row of rows) {
const threadId = ThreadId.make(row.thread_id);
if (!(yield* shareCopiedAtCreation(sql, threadId, shareId))) return threadId;
}
return null;
// SCIENT-FORK:END
}, Effect.mapError(shellSnapshotReadError));

const listOlderSettledThreads: ProjectionStoreV2Shape["listOlderSettledThreads"] = Effect.fn(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
import {
CommandId,
EventId,
GuestShareId,
MessageId,
ProjectId,
ProviderDriverKind,
Expand Down Expand Up @@ -122,6 +123,23 @@ it.effect(
threadId,
sectionId: ThreadSectionId.make("section:research"),
});
yield* store.apply({
id: EventId.make("fork-source-guest-share"),
type: "thread.metadata-updated",
threadId,
occurredAt: now,
payload: {
...(yield* store.getThread(threadId)),
guestShare: {
id: GuestShareId.make("guest-share:fork-source"),
host: "guest.example.test",
createdAt: DateTime.formatIso(now),
expiresAt: DateTime.formatIso(DateTime.add(now, { days: 1 })),
guestName: null,
messages: [],
},
},
});
const firstRunId = RunId.make("fork-completed-run");
const secondRunId = RunId.make("fork-running-run");
const runs: OrchestrationV2Run[] = [firstRunId, secondRunId].map((id, index) => ({
Expand Down Expand Up @@ -332,6 +350,8 @@ it.effect(
yield* assertForkShellCounts;
assert.ok(shell.threads.every((thread) => !("conversationForkBoundaries" in thread)));
assert.equal(target.thread.sectionId, ThreadSectionId.make("section:research"));
// A guest invited to the source must never resolve to the fork.
assert.isNull(target.thread.guestShare);
assert.equal(target.thread.conversationFork?.status, "ready");
assert.equal(target.thread.forkedFrom, null);
assert.equal(target.runs.length, 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,12 @@ const make = Effect.gen(function* () {
linkedPullRequest: null,
branchPullRequest: null,
pullRequests: [],
// A guest link and a remote delegation belong to the thread they were made for.
guestShare: null,
delegatedFrom: undefined,
opens: null,
lastSnoozeWakeAt: null,
autoSettleDisabledAt: null,
};
const events: OrchestrationV2DomainEvent[] = [
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { assert, it } from "@effect/vitest";
import {
CommandId,
EnvironmentId,
EventId,
MessageId,
type OrchestrationV2AppThread,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";

import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import { CodexProviderCapabilitiesV2 } from "../Adapters/CodexAdapterV2.ts";
import * as EffectOutbox from "../EffectOutbox.ts";
import * as Orchestrator from "../Orchestrator.ts";
import * as ProjectionStore from "../ProjectionStore.ts";
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
import * as ProviderReplayHarness from "../testkit/ProviderReplayHarness.ts";

const instanceId = ProviderInstanceId.make("codex");
const modelSelection = { instanceId, model: "gpt-5.1-codex" };
const adapter = {
instanceId,
driver: ProviderDriverKind.make("codex"),
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
openSession: () => Effect.die("No provider process needed to admit a delegated task"),
} as ProviderAdapter.ProviderAdapterV2["Service"];
const layerDatabase = SqlitePersistence.layerMemory;
const layerTest = Layer.mergeAll(
layerDatabase,
ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
ProviderReplayHarness.layerWithRegistry(
{ name: "delegated-task-from-fork" },
ProviderAdapterRegistry.layerFromAdapters([adapter]),
{ databaseLayer: layerDatabase, runEffectWorker: false },
),
);

// What a delegated subagent takes from its parent thread. The Record makes a field added
// by an upstream merge fail typecheck until someone decides it.
const helperFields = {
createdBy: "set",
creationSource: "set",
id: "set",
projectId: "inherited",
workspaceAuthorityRevision: "set",
title: "set",
providerInstanceId: "set",
modelSelection: "set",
runtimeMode: "set",
interactionMode: "set",
branch: "inherited",
worktreePath: "inherited",
linkedPullRequest: "reset",
pullRequests: "set",
branchPullRequest: "inherited",
activeProviderThreadId: "set",
historyOrigin: "reset",
linkOrigin: "inherited",
delegatedFrom: "reset",
lineage: "set",
forkedFrom: "set",
createdAt: "set",
updatedAt: "set",
archivedAt: "reset",
settledOverride: "reset",
settledAt: "reset",
unsettledAt: "reset",
snoozedUntil: "reset",
snoozedAt: "reset",
lastSnoozeWakeAt: "reset",
limitRecovery: "reset",
guestShare: "reset",
pinnedAt: "reset",
autoSettleDisabledAt: "reset",
pinOrderKey: "reset",
activeOrderKey: "reset",
tags: "inherited",
lastVisitedAt: "reset",
opens: "reset",
titleRegeneration: "reset",
lastTitleRegeneration: "inherited",
rollbackRequestId: "reset",
rollbackCompletedRequestId: "reset",
rollbackFailure: "reset",
deletedAt: "reset",
sectionId: "inherited",
conversationImport: "reset",
forkLineage: "reset",
conversationFork: "reset",
} as const satisfies Record<keyof OrchestrationV2AppThread, "inherited" | "reset" | "set">;

it.effect("starts a delegated task from a forked conversation as a plain helper", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const parentThreadId = ThreadId.make("thread:forked-parent");
const rollbackId = CommandId.make("rollback:forked-parent");
yield* orchestrator.dispatch({
type: "thread.create",
commandId: CommandId.make("create-forked-parent"),
threadId: parentThreadId,
projectId: ProjectId.make("project:forked-parent"),
title: "Forked parent",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/forked-parent",
worktreePath: "/repo-worktree",
createdBy: "user",
creationSource: "web",
});
const now = yield* DateTime.now;
const parentState = {
delegatedFrom: {
environmentId: EnvironmentId.make("environment:remote"),
threadId: ThreadId.make("thread:remote-parent"),
title: "Remote parent",
},
unsettledAt: now,
lastSnoozeWakeAt: now,
activeOrderKey: "a0",
rollbackRequestId: rollbackId,
rollbackCompletedRequestId: rollbackId,
rollbackFailure: { requestId: rollbackId, message: "Rollback failed" },
forkLineage: {
originThreadId: ThreadId.make("thread:fork-origin"),
baselineAssistantMessageId: null,
},
conversationFork: {
commandId: CommandId.make("fork:forked-parent"),
sourceThreadId: ThreadId.make("thread:fork-origin"),
workspaceMode: "local",
status: "ready",
cwd: "/repo-worktree",
checkpointRef: null,
checkpointOid: null,
attachmentCopies: [],
error: null,
},
} as const satisfies Partial<OrchestrationV2AppThread>;
yield* projections.apply({
id: EventId.make("forked-parent:fork-state"),
type: "thread.metadata-updated",
threadId: parentThreadId,
occurredAt: now,
payload: { ...(yield* projections.getThread(parentThreadId)), ...parentState },
});
yield* orchestrator.dispatch({
type: "message.dispatch",
commandId: CommandId.make("start-forked-parent"),
threadId: parentThreadId,
messageId: MessageId.make("message:forked-parent"),
text: "Ask for a review",
attachments: [],
dispatchMode: { type: "start_immediately" },
createdBy: "user",
creationSource: "web",
});
const parent = yield* projections.getThreadProjection(parentThreadId);
const parentRun = parent.runs[0]!;

yield* orchestrator.dispatch({
type: "delegated_task.request",
commandId: CommandId.make("delegate-from-fork"),
parentThreadId,
parentRunId: parentRun.id,
parentNodeId: parentRun.rootNodeId!,
task: "Review the plan",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
createdBy: "agent",
creationSource: "mcp",
});

const task = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]!;
const child = yield* projections.getThreadProjection(task.childThreadId!);
assert.equal(child.thread.lineage.relationshipToParent, "subagent");
assert.lengthOf(child.runs, 1);
for (const [field, rule] of Object.entries(helperFields)) {
if (rule !== "inherited") continue;
const key = field as keyof OrchestrationV2AppThread;
assert.deepEqual(child.thread[key], parent.thread[key], `${field} is inherited`);
}
for (const [field, value] of Object.entries(parentState)) {
assert.equal(helperFields[field as keyof typeof parentState], "reset");
assert.notDeepEqual(
child.thread[field as keyof typeof parentState],
value,
`${field} is reset`,
);
}
}).pipe(Effect.provide(layerTest)),
);
Loading
Loading