π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(environment): repair the two dead ends found walking the environments page (#20483)
Rdmclin277633d1d2934
diff --git a/apps/server/src/routers/lambda/sandboxStorage.ts b/apps/server/src/routers/lambda/sandboxStorage.tsindex 811a2ce05bb..c980b2c97ca 100644--- a/apps/server/src/routers/lambda/sandboxStorage.ts+++ b/apps/server/src/routers/lambda/sandboxStorage.ts@@ -1079,17 +1079,32 @@ export const sandboxStorageRouter = router({.findByIds(topicIds).catch(() => []): [];- const titles = new Map(+ // Where the conversation lives, as well as what it is called: a topic is+ // addressed as `group/<groupId>/<topicId>` when it belongs to a group and+ // `agent/<agentId>/<topicId>` otherwise, so a link built from the topic+ // alone cannot resolve and the panel's one way back into the run is a 404.+ // A group topic carries BOTH ids, which is why the group one is returned+ // rather than inferred from the absence of an agent.+ const topicInfo = new Map(topics.filter((topic) => topic.userId === ctx.userId)- .map((topic) => [topic.id, topic.title]),+ .map((topic) => [+ topic.id,+ { agentId: topic.agentId, groupId: topic.groupId, title: topic.title },+ ]),);return {- sessions: merged.map((session) => ({- ...session,- topicTitle: (session.topicId && titles.get(session.topicId)) || null,- })),+ sessions: merged.map((session) => {+ const info = session.topicId ? topicInfo.get(session.topicId) : undefined;++ return {+ ...session,+ topicAgentId: info?.agentId ?? null,+ topicGroupId: info?.groupId ?? null,+ topicTitle: info?.title || null,+ };+ }),unavailable: pages.includes(null),};}),diff --git a/src/features/EnvironmentManager/CreateEnvironmentModal.tsx b/src/features/EnvironmentManager/CreateEnvironmentModal.tsxindex aa64d5499cc..a0f73a70d0f 100644--- a/src/features/EnvironmentManager/CreateEnvironmentModal.tsx+++ b/src/features/EnvironmentManager/CreateEnvironmentModal.tsx@@ -31,148 +31,163 @@ import { useEnvironmentActions } from './useEnvironmentData';* explain what each part does.*/interface CreateEnvironmentContentProps {+ /**+ * Called with the new environment's id once it exists. An environment is a+ * specification; nothing runs in it until it has an instance, so creating one+ * is the middle of the task rather than the end of it and the caller takes+ * the person to that next step instead of returning them to a list.+ */+ onCreated?: (environmentId: string) => void;visibility?: EnvironmentVisibility;}-const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(({ visibility }) => {- const { t } = useTranslation('setting');- const { close } = useModalContext();- const actions = useEnvironmentActions();+const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(+ ({ onCreated, visibility }) => {+ const { t } = useTranslation('setting');+ const { close } = useModalContext();+ const actions = useEnvironmentActions();- const [name, setName] = useState('');- // Tracks whether the name is still the one the repository suggested. A name- // the person typed is theirs, and picking a different repository must not- // overwrite it; a suggested one is just a default and follows the pick.- const [nameIsSuggested, setNameIsSuggested] = useState(true);- const [repository, setRepository] = useState<GithubRepositorySelection | undefined>();- const [creating, setCreating] = useState(false);- // The Enter that confirms an IME candidate reaches `keydown` as an Enter,- // so a Chinese name would submit the dialog on the keystroke that picked it.- const { compositionProps, isComposingRef } = useIMECompositionEvent();- const [error, setError] = useState<string | undefined>();+ const [name, setName] = useState('');+ // Tracks whether the name is still the one the repository suggested. A name+ // the person typed is theirs, and picking a different repository must not+ // overwrite it; a suggested one is just a default and follows the pick.+ const [nameIsSuggested, setNameIsSuggested] = useState(true);+ const [repository, setRepository] = useState<GithubRepositorySelection | undefined>();+ const [creating, setCreating] = useState(false);+ // The Enter that confirms an IME candidate reaches `keydown` as an Enter,+ // so a Chinese name would submit the dialog on the keystroke that picked it.+ const { compositionProps, isComposingRef } = useIMECompositionEvent();+ const [error, setError] = useState<string | undefined>();- const trimmed = name.trim();+ const trimmed = name.trim();- const pickRepository = (selection: GithubRepositorySelection | undefined) => {- setRepository(selection);- setError(undefined);- // Naming a thing that does not exist yet is the harder half of this dialog,- // so the repository answers it: an environment for a repository is almost- // always called after it.- if (nameIsSuggested) setName(selection?.repository ?? '');- };+ const pickRepository = (selection: GithubRepositorySelection | undefined) => {+ setRepository(selection);+ setError(undefined);+ // Naming a thing that does not exist yet is the harder half of this dialog,+ // so the repository answers it: an environment for a repository is almost+ // always called after it.+ if (nameIsSuggested) setName(selection?.repository ?? '');+ };- const create = async () => {- setCreating(true);- setError(undefined);- try {- await actions.createEnvironment({- // The repository is the environment's one source. Every repository- // carries the owner GitHub reported for it, so the checkout URL is- // built from the pair rather than from whichever owner the list was- // filtered by β those differ for a repository reached as a collaborator.- configuration: repository- ? {- sources: [- {- kind: 'git',- ref: repository.defaultBranch,- url: `https://github.com/${repository.owner}/${repository.repository}`,- },- ],- }- : undefined,- name: trimmed,- // Created into the pool the person is looking at. Opening the dialog- // from the Private tab and having the result land in the workspace's- // shared list would be a publication nobody asked for.- visibility,- });- close();- } catch (cause) {- // The one failure the user can act on is a name already taken, and it is- // fixed by typing a different one β so it belongs next to the field- // rather than in a toast that outlives the dialog.- setError(- (cause as { message?: string })?.message === 'DUPLICATE_ENVIRONMENT_NAME'- ? t('environments.duplicateName')- : t('environments.createFailed'),- );- } finally {- setCreating(false);- }- };+ const create = async () => {+ setCreating(true);+ setError(undefined);+ try {+ const created = await actions.createEnvironment({+ // The repository is the environment's one source. Every repository+ // carries the owner GitHub reported for it, so the checkout URL is+ // built from the pair rather than from whichever owner the list was+ // filtered by β those differ for a repository reached as a collaborator.+ configuration: repository+ ? {+ sources: [+ {+ kind: 'git',+ ref: repository.defaultBranch,+ url: `https://github.com/${repository.owner}/${repository.repository}`,+ },+ ],+ }+ : undefined,+ name: trimmed,+ // Created into the pool the person is looking at. Opening the dialog+ // from the Private tab and having the result land in the workspace's+ // shared list would be a publication nobody asked for.+ visibility,+ });+ close();+ // After the dialog, not instead of it: the person sees the environment+ // land and is then asked for the one thing that makes it runnable.+ if (created?.id) onCreated?.(created.id);+ } catch (cause) {+ // The one failure the user can act on is a name already taken, and it is+ // fixed by typing a different one β so it belongs next to the field+ // rather than in a toast that outlives the dialog.+ setError(+ (cause as { message?: string })?.message === 'DUPLICATE_ENVIRONMENT_NAME'+ ? t('environments.duplicateName')+ : t('environments.createFailed'),+ );+ } finally {+ setCreating(false);+ }+ };- // Created in the workspace's pool, an environment is published from its- // first instance on β and an instance keeps whatever a session leaves in its- // home directory, credentials included. So creating one there asks the same- // question publishing one does, with the same explanation, rather than- // publishing it silently because of which tab happened to be open.- const submit = () => {- if (!trimmed || creating) return;- if (visibility !== 'public') return void create();+ // Created in the workspace's pool, an environment is published from its+ // first instance on β and an instance keeps whatever a session leaves in its+ // home directory, credentials included. So creating one there asks the same+ // question publishing one does, with the same explanation, rather than+ // publishing it silently because of which tab happened to be open.+ const submit = () => {+ if (!trimmed || creating) return;+ if (visibility !== 'public') return void create();- confirmModal({- content: <VisibilityConfirmContent capturedState variant={'publish'} />,- okText: t('environments.create'),- onOk: create,- title: t('environments.visibility.createPublishedConfirmTitle'),- });- };+ confirmModal({+ content: <VisibilityConfirmContent capturedState variant={'publish'} />,+ okText: t('environments.create'),+ onOk: create,+ title: t('environments.visibility.createPublishedConfirmTitle'),+ });+ };- return (- <>- {/* Repository first, name second. The name is the harder question and the+ return (+ <>+ {/* Repository first, name second. The name is the harder question and therepository usually answers it, so asking for the name first makes theperson invent something they are about to be handed. */}- <Flexbox gap={12} paddingBlock={8} paddingInline={16}>- <GithubRepositoryPicker value={repository} onChange={pickRepository} onLeave={close} />+ <Flexbox gap={12} paddingBlock={8} paddingInline={16}>+ <GithubRepositoryPicker value={repository} onChange={pickRepository} onLeave={close} />- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {t('environments.nameLabel')}- </Text>- <Input- autoFocus- placeholder={t('environments.namePlaceholder')}- value={name}- onChange={(event) => {- setName(event.target.value);- setNameIsSuggested(false);- setError(undefined);- }}- onKeyDown={(event) => {- if (event.key === 'Enter' && !isComposingRef.current) void submit();- }}- {...compositionProps}- />- {error && (- <Text fontSize={12} type={'danger'}>- {error}+ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('environments.nameLabel')}</Text>- )}+ <Input+ autoFocus+ placeholder={t('environments.namePlaceholder')}+ value={name}+ onChange={(event) => {+ setName(event.target.value);+ setNameIsSuggested(false);+ setError(undefined);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && !isComposingRef.current) void submit();+ }}+ {...compositionProps}+ />+ {error && (+ <Text fontSize={12} type={'danger'}>+ {error}+ </Text>+ )}+ </Flexbox></Flexbox>- </Flexbox>- <ModalFooter>- <Button onClick={close}>{t('environments.cancel')}</Button>- <Button- disabled={!trimmed}- loading={creating}- type={'primary'}- onClick={() => void submit()}- >- {t('environments.create')}- </Button>- </ModalFooter>- </>- );-});+ <ModalFooter>+ <Button onClick={close}>{t('environments.cancel')}</Button>+ <Button+ disabled={!trimmed}+ loading={creating}+ type={'primary'}+ onClick={() => void submit()}+ >+ {t('environments.create')}+ </Button>+ </ModalFooter>+ </>+ );+ },+);CreateEnvironmentContent.displayName = 'CreateEnvironmentContent';-export const openCreateEnvironmentModal = (visibility?: EnvironmentVisibility) =>+export const openCreateEnvironmentModal = (+ visibility?: EnvironmentVisibility,+ onCreated?: (environmentId: string) => void,+) =>createModal({- content: <CreateEnvironmentContent visibility={visibility} />,+ content: <CreateEnvironmentContent visibility={visibility} onCreated={onCreated} />,footer: null,maskClosable: true,styles: { content: { padding: 0 } },diff --git a/src/features/EnvironmentManager/SessionHistorySection.tsx b/src/features/EnvironmentManager/SessionHistorySection.tsxindex a619fbe9fd0..fa7ef9fa73f 100644--- a/src/features/EnvironmentManager/SessionHistorySection.tsx+++ b/src/features/EnvironmentManager/SessionHistorySection.tsx@@ -14,9 +14,9 @@ import {} from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router';import ListSkeleton from '@/components/ListSkeleton';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { formatSize } from '@/utils/format';import { type SandboxSessionRecord, useInstances, useInstanceSessions } from './useEnvironmentData';@@ -93,15 +93,36 @@ const duration = (session: SandboxSessionRecord, running: boolean): string | undreturn `${hours < 10 ? hours.toFixed(1) : Math.round(hours)} h`;};+/**+ * Where a run's conversation lives, or `undefined` when it has no page.+ *+ * A topic is addressed as `group/<groupId>/<topicId>` when it belongs to a+ * group and `agent/<agentId>/<topicId>` otherwise β the topic alone does not+ * resolve, and a bare `/chat?topic=<id>` resolves to nothing at all, which is+ * what sent the panel's one way back into a run to the 404 page.+ *+ * A group topic carries an agent id too β the member that answered β so the+ * group is checked FIRST; reading the agent would open that member's own+ * surface instead of the conversation the run came from. The workspace prefix+ * is added by `useWorkspaceAwareNavigate`, so it is absent here on purpose.+ */+export const conversationPath = (session: SandboxSessionRecord): string | undefined => {+ if (session.management || !session.topicId) return undefined;+ if (session.topicGroupId) return `/group/${session.topicGroupId}/${session.topicId}`;++ return session.topicAgentId ? `/agent/${session.topicAgentId}/${session.topicId}` : undefined;+};+const SessionRow = memo<{ running: boolean; session: SandboxSessionRecord }>(({ running, session }) => {const { t } = useTranslation('setting');- const navigate = useNavigate();+ const navigate = useWorkspaceAwareNavigate();const isBuild = session.kind === 'build';/** No end recorded, and the lease says nobody is holding its instance. */const stale = !session.endedAt && !running;const elapsed = duration(session, running);+ const conversation = conversationPath(session);// Three kinds of run, told apart by how they were started: a build from// the environment's specification, a console session from the file// browser, or a conversation β the common case, named by its topic.@@ -173,9 +194,13 @@ const SessionRow = memo<{ running: boolean; session: SandboxSessionRecord }>()}{/* Railway's "View logs" on the active deployment: the one thing to dowith a run in progress is go to it. Only a conversation has somewhere- to go; a build and a console session have no page of their own. */}- {running && session.topicId && !session.management && (- <Button size={'small'} onClick={() => navigate(`/chat?topic=${session.topicId}`)}>+ to go; a build and a console session have no page of their own.+ A conversation is addressed as `agent/<agentId>/<topicId>` under the+ active workspace, so the agent is required too and the navigate has+ to be the workspace-aware one β a bare `/chat?topic=<id>` resolved to+ nothing and sent the one way back into a run to the 404 page. */}+ {running && conversation && (+ <Button size={'small'} onClick={() => navigate(conversation)}>{t('environments.sessions.openConversation')}</Button>)}diff --git a/src/features/EnvironmentManager/index.tsx b/src/features/EnvironmentManager/index.tsxindex 9cc9c27c5c8..13a59187c93 100644--- a/src/features/EnvironmentManager/index.tsx+++ b/src/features/EnvironmentManager/index.tsx@@ -117,9 +117,14 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })setSelectedId((current) => (current === id ? undefined : id));};- // The row's shortcut: open the environment so the new instance is seen- // landing in its list, and ask for the instance in the same dialog the- // panel's own button opens.+ // Open the environment so the new instance is seen landing in its list, and+ // ask for the instance in the same dialog the panel's own button opens.+ //+ // Both the row's shortcut and the step straight after creating an+ // environment: a specification with no instance runs nothing, so stopping at+ // the new row would hand back an environment that cannot be used and no hint+ // that anything is missing. Dismissing the instance dialog still lands on+ // that environment's panel, whose empty state asks for the same thing.const createInstance = (id: string) => {setSelectedId(id);openCreateInstanceModal({ environmentId: id });@@ -172,7 +177,7 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })<Buttonicon={<Icon icon={PlusIcon} />}type={'primary'}- onClick={() => openCreateEnvironmentModal(visibility)}+ onClick={() => openCreateEnvironmentModal(visibility, createInstance)}>{t('environments.create')}</Button>@@ -203,7 +208,7 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })action={<Buttonicon={<Icon icon={PlusIcon} />}- onClick={() => openCreateEnvironmentModal(visibility)}+ onClick={() => openCreateEnvironmentModal(visibility, createInstance)}>{t('environments.create')}</Button>diff --git a/src/features/EnvironmentManager/sessionHistory.test.ts b/src/features/EnvironmentManager/sessionHistory.test.tsindex 0079b3b1fb4..af162732997 100644--- a/src/features/EnvironmentManager/sessionHistory.test.ts+++ b/src/features/EnvironmentManager/sessionHistory.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { runningSessionIds, withoutBuildVehicles } from './SessionHistorySection';+import { conversationPath, runningSessionIds, withoutBuildVehicles } from './SessionHistorySection';const session = (overrides: Partial<any>): any => ({buildId: null,@@ -15,6 +15,8 @@ const session = (overrides: Partial<any>): any => ({sessionUserId: 'user_1',snapshotBytes: null,startedAt: '2026-09-24T02:00:00.000Z',+ topicAgentId: null,+ topicGroupId: null,topicId: null,topicTitle: null,...overrides,@@ -154,3 +156,33 @@ describe('runningSessionIds', () => {expect(running([session({ instanceId: null })], holding('inst-a'))).toEqual([]);});});++describe('conversationPath', () => {+ it('addresses the conversation by its agent, not by the topic alone', () => {+ // `/chat?topic=<id>` is not a route: it rendered the 404 page, so the one+ // way back from a running run into the conversation went nowhere.+ expect(conversationPath(session({ topicAgentId: 'agt_1', topicId: 'tpc_1' }))).toBe(+ '/agent/agt_1/tpc_1',+ );+ });++ it('offers nothing when the agent is unknown', () => {+ // The topic is another member's, or was deleted β a link built from half+ // the address would 404 exactly like the old one did.+ expect(conversationPath(session({ topicAgentId: null, topicId: 'tpc_1' }))).toBeUndefined();+ });++ it('sends a group run back to the group, not to the member that answered', () => {+ // A group topic carries an agent id too β the member whose turn it was.+ // Reading that first opens a different conversation than the run came from.+ expect(+ conversationPath(session({ topicAgentId: 'agt_1', topicGroupId: 'grp_1', topicId: 'tpc_1' })),+ ).toBe('/group/grp_1/tpc_1');+ });++ it('offers nothing for a management session', () => {+ expect(+ conversationPath(session({ management: true, topicAgentId: 'agt_1', topicId: 'tpc_1' })),+ ).toBeUndefined();+ });+});diff --git a/src/features/EnvironmentManager/useEnvironmentData.ts b/src/features/EnvironmentManager/useEnvironmentData.tsindex 1c0ae3569b2..d7e553fa874 100644--- a/src/features/EnvironmentManager/useEnvironmentData.ts+++ b/src/features/EnvironmentManager/useEnvironmentData.ts@@ -276,8 +276,13 @@ export const useEnvironmentActions = () => {name: string;visibility?: EnvironmentVisibility;}) => {- await sandboxStorageService.createEnvironment(params);+ // Returned, not discarded: an environment with no instance cannot run+ // anything, so the caller chains straight into creating the first one and+ // needs the id to do it.+ const created = await sandboxStorageService.createEnvironment(params);await refreshEnvironments();++ return created;},/**