You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by ak...@apache.org on 2026/06/05 07:37:28 UTC

(tooling-gofannon) 04/25: ISSUE-008: env vars editor UI

This is an automated email from the ASF dual-hosted git repository.

andrewmusselman pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-gofannon.git

commit 58831d2669229023d8c2ac36b2fa9098a3950530
Author: Andrew Musselman <ak...@apache.org>
AuthorDate: Thu Jun 4 06:59:53 2026 +0000

    ISSUE-008: env vars editor UI
    
    Adds the frontend half of ISSUE-008 that was missing from the original
    patch. New EnvVarsEditor component renders key/value rows with masked
    values (reveal toggle per row), add/remove affordances, and duplicate-key
    detection. Lives in a new 'Environment Variables' accordion section
    between the Schemas section and Data Store Configuration in ViewAgent.
    
    Empty rows the user left behind mid-edit are filtered out of the save
    payload (in both handleSave and handleSaveNewAgent) so the backend
    doesn't store {key: '', value: ''} blanks. Duplicate keys are flagged
    in the UI but not blocked from saving -- the backend will silently
    take the last value per key, which matches the os.environ semantics
    the user expects.
    
    Pure frontend change. Depends on the backend half of ISSUE-008 being
    deployed (the env_vars field on the agent model and the runtime
    overlay in services/environ_proxy.py), but doesn't break anything
    if the backend is older -- it just sends an envVars field the
    backend ignores.
---
 webapp/packages/api/user-service/models/agent.py   |   5 +
 webapp/packages/api/user-service/routes.py         |   2 +
 .../webui/src/components/EnvVarsEditor.jsx         | 187 +++++++++++++++++++++
 .../src/pages/AgentCreationFlow/RunsScreen.jsx     |   1 +
 webapp/packages/webui/src/pages/ViewAgent.jsx      |  28 +++
 webapp/packages/webui/src/services/agentService.js |   3 +
 6 files changed, 226 insertions(+)

diff --git a/webapp/packages/api/user-service/models/agent.py b/webapp/packages/api/user-service/models/agent.py
index fe41f06..cee0ee6 100644
--- a/webapp/packages/api/user-service/models/agent.py
+++ b/webapp/packages/api/user-service/models/agent.py
@@ -207,6 +207,11 @@ class RunCodeRequest(BaseModel):
     # group nested-agent activity. Falls back to "sandbox_agent" if not
     # provided (legacy clients).
     friendly_name: Optional[str] = Field(default=None, alias="friendlyName")
+    # ISSUE-008 follow-up: per-agent env vars threaded from the editor so the
+    # runtime overlay sees them. Without this the /agents/run-code endpoints
+    # had no way to know which env_vars belong to the code being run, since
+    # they receive code as a payload rather than fetching an agent record.
+    env_vars: Optional[List[AgentEnvVar]] = Field(default=None, alias="envVars")
     model_config = ConfigDict(populate_by_name=True)
 
 class RunCodeResponse(BaseModel):
diff --git a/webapp/packages/api/user-service/routes.py b/webapp/packages/api/user-service/routes.py
index 507518a..5e82c9f 100644
--- a/webapp/packages/api/user-service/routes.py
+++ b/webapp/packages/api/user-service/routes.py
@@ -726,6 +726,7 @@ async def run_agent_code_stream(
                 user_basic_info=user_basic_info,
                 agent_name=request.friendly_name or "sandbox_agent",
                 trace=trace,
+                env_vars=request.env_vars,
             )
             schema_warnings = validate_output_against_schema(result, request.output_schema)
             if schema_warnings:
@@ -850,6 +851,7 @@ async def run_agent_code(
                 user_basic_info=user_basic_info,
                 agent_name=request.friendly_name or "sandbox_agent",
                 trace=trace,
+                env_vars=request.env_vars,
             )
         except Exception as _exc:
             logger.log(
diff --git a/webapp/packages/webui/src/components/EnvVarsEditor.jsx b/webapp/packages/webui/src/components/EnvVarsEditor.jsx
new file mode 100644
index 0000000..4c41ad9
--- /dev/null
+++ b/webapp/packages/webui/src/components/EnvVarsEditor.jsx
@@ -0,0 +1,187 @@
+import React, { useState } from 'react';
+import PropTypes from 'prop-types';
+import {
+  Box,
+  Typography,
+  TextField,
+  IconButton,
+  Button,
+  Tooltip,
+  InputAdornment,
+  Alert,
+} from '@mui/material';
+import AddIcon from '@mui/icons-material/Add';
+import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
+import VisibilityIcon from '@mui/icons-material/Visibility';
+import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
+
+/**
+ * Editor for an agent's per-run environment variables.
+ *
+ * Mirrors the existing SchemaEditor's pattern: it owns the row-level UI
+ * (add/delete/edit) and pushes the full updated list back up via setEnvVars
+ * on every change. The parent component is responsible for persisting the
+ * field on save -- this component never calls the API directly.
+ *
+ * Values are masked by default (password-input style) with a per-row
+ * reveal toggle. This is purely a frontend convenience to avoid shoulder-
+ * surfing in shared screens; values are still sent in cleartext over the
+ * (TLS-protected) save request and stored encrypted at rest by the
+ * backend's Fernet key.
+ *
+ * Empty rows (no key) are filtered out before save by the parent's save
+ * handler; this keeps the editor relaxed about trailing empty rows while
+ * the user is mid-edit.
+ */
+const EnvVarsEditor = ({ envVars = [], setEnvVars }) => {
+  // Per-row reveal toggle. Keyed by index because keys themselves can be
+  // duplicated transiently while the user is typing.
+  const [revealed, setRevealed] = useState({});
+
+  const handleAdd = () => {
+    setEnvVars([...envVars, { key: '', value: '' }]);
+  };
+
+  const handleRemove = (index) => {
+    setEnvVars(envVars.filter((_, i) => i !== index));
+    // Drop the reveal flag for the removed index and renumber the rest.
+    const next = {};
+    Object.entries(revealed).forEach(([k, v]) => {
+      const i = parseInt(k, 10);
+      if (i < index) next[i] = v;
+      else if (i > index) next[i - 1] = v;
+    });
+    setRevealed(next);
+  };
+
+  const handleKeyChange = (index, value) => {
+    const next = [...envVars];
+    next[index] = { ...next[index], key: value };
+    setEnvVars(next);
+  };
+
+  const handleValueChange = (index, value) => {
+    const next = [...envVars];
+    next[index] = { ...next[index], value };
+    setEnvVars(next);
+  };
+
+  const toggleReveal = (index) => {
+    setRevealed((prev) => ({ ...prev, [index]: !prev[index] }));
+  };
+
+  // Detect duplicate keys (case-sensitive). os.getenv is case-sensitive on
+  // Linux which is where the backend runs, so we flag duplicates as the
+  // user types rather than letting them save a list where two rows fight
+  // for the same key.
+  const keyCounts = envVars.reduce((acc, { key }) => {
+    if (key) acc[key] = (acc[key] || 0) + 1;
+    return acc;
+  }, {});
+  const duplicates = Object.entries(keyCounts)
+    .filter(([, count]) => count > 1)
+    .map(([k]) => k);
+
+  return (
+    <Box>
+      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
+        Key/value pairs that will be available to the agent's code at run time
+        via <code>os.getenv("KEY")</code> or <code>os.environ["KEY"]</code>.
+        Values are encrypted at rest. Other agents running in the same process
+        do not see your env vars.
+      </Typography>
+
+      {duplicates.length > 0 && (
+        <Alert severity="warning" sx={{ mb: 2 }}>
+          Duplicate keys: {duplicates.map((k) => <code key={k} style={{ marginRight: 8 }}>{k}</code>)}
+          {' '}-- only the last value for each key will be used at runtime.
+        </Alert>
+      )}
+
+      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, mb: 2 }}>
+        {envVars.length === 0 && (
+          <Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
+            No env vars configured. Click &ldquo;Add variable&rdquo; below to add one.
+          </Typography>
+        )}
+
+        {envVars.map((row, index) => (
+          <Box
+            key={index}
+            sx={{
+              display: 'flex',
+              gap: 1,
+              alignItems: 'flex-start',
+            }}
+          >
+            <TextField
+              label="Key"
+              value={row.key || ''}
+              onChange={(e) => handleKeyChange(index, e.target.value)}
+              placeholder="MY_API_KEY"
+              size="small"
+              sx={{ flex: '0 0 32%', fontFamily: 'monospace' }}
+              InputProps={{ sx: { fontFamily: 'monospace' } }}
+              error={duplicates.includes(row.key)}
+            />
+            <TextField
+              label="Value"
+              value={row.value || ''}
+              onChange={(e) => handleValueChange(index, e.target.value)}
+              type={revealed[index] ? 'text' : 'password'}
+              size="small"
+              sx={{ flex: 1, fontFamily: 'monospace' }}
+              InputProps={{
+                sx: { fontFamily: 'monospace' },
+                endAdornment: (
+                  <InputAdornment position="end">
+                    <Tooltip title={revealed[index] ? 'Hide' : 'Reveal'}>
+                      <IconButton
+                        size="small"
+                        onClick={() => toggleReveal(index)}
+                        edge="end"
+                      >
+                        {revealed[index] ? <VisibilityOffIcon fontSize="small" /> : <VisibilityIcon fontSize="small" />}
+                      </IconButton>
+                    </Tooltip>
+                  </InputAdornment>
+                ),
+              }}
+            />
+            <Tooltip title="Remove this variable">
+              <IconButton
+                size="small"
+                onClick={() => handleRemove(index)}
+                sx={{ mt: 0.5 }}
+                aria-label="remove env var"
+              >
+                <DeleteOutlineIcon />
+              </IconButton>
+            </Tooltip>
+          </Box>
+        ))}
+      </Box>
+
+      <Button
+        variant="outlined"
+        startIcon={<AddIcon />}
+        onClick={handleAdd}
+        size="small"
+      >
+        Add variable
+      </Button>
+    </Box>
+  );
+};
+
+EnvVarsEditor.propTypes = {
+  envVars: PropTypes.arrayOf(
+    PropTypes.shape({
+      key: PropTypes.string,
+      value: PropTypes.string,
+    }),
+  ),
+  setEnvVars: PropTypes.func.isRequired,
+};
+
+export default EnvVarsEditor;
diff --git a/webapp/packages/webui/src/pages/AgentCreationFlow/RunsScreen.jsx b/webapp/packages/webui/src/pages/AgentCreationFlow/RunsScreen.jsx
index 8ecc4fd..1c57fae 100644
--- a/webapp/packages/webui/src/pages/AgentCreationFlow/RunsScreen.jsx
+++ b/webapp/packages/webui/src/pages/AgentCreationFlow/RunsScreen.jsx
@@ -314,6 +314,7 @@ const RunsScreen = () => {
       const response = await agentService.runCodeInSandboxStreaming(
         generatedCode, castInput, tools, gofannonAgents, llmSettings, outputSchema, friendlyName,
         onTraceEvent,
+        agentData?.envVars,
       );
       if (response.error) {
         setError(response.error);
diff --git a/webapp/packages/webui/src/pages/ViewAgent.jsx b/webapp/packages/webui/src/pages/ViewAgent.jsx
index 125e7ca..a81afc4 100644
--- a/webapp/packages/webui/src/pages/ViewAgent.jsx
+++ b/webapp/packages/webui/src/pages/ViewAgent.jsx
@@ -58,6 +58,7 @@ import CodeEditor from '../components/CodeEditor';
 import SpecViewerModal from '../components/SpecViewerModal';
 import ModelConfigDialog from '../components/ModelConfigDialog';
 import SchemaEditor from '../components/SchemaEditor';
+import EnvVarsEditor from '../components/EnvVarsEditor';
 import DataStoreConfigAccordion from '../components/DataStoreConfigAccordion';
 import AgentChainView from '../components/AgentChainView';
 import ToolsSelectionDialog from './AgentCreationFlow/ToolsSelectionDialog';
@@ -310,6 +311,10 @@ const ViewAgent = () => {
         docstring: agent.docstring,
         friendlyName: canonicalName,
         dataStoreConfig: agent.dataStoreConfig || [],
+        // ISSUE-008: persist per-agent env vars. Filter empty rows so the
+        // backend doesn't store {key: '', value: ''} blanks the user left
+        // behind mid-edit.
+        envVars: (agent.envVars || []).filter((ev) => ev.key && ev.key.trim()),
       };
       await agentService.updateAgent(agentId, updatePayload);
       setSuccessMessage('Agent updated successfully!');
@@ -364,6 +369,8 @@ const ViewAgent = () => {
         docstring: agent.docstring,
         friendlyName: canonicalName,
         dataStoreConfig: agent.dataStoreConfig || [],
+        // ISSUE-008: persist per-agent env vars on the create path too.
+        envVars: (agent.envVars || []).filter((ev) => ev.key && ev.key.trim()),
       };
       const savedAgent = await agentService.saveAgent(agentData);
       setSuccessMessage('Agent saved successfully!');
@@ -780,6 +787,14 @@ const ViewAgent = () => {
     syncToContext('outputSchema', newSchema);
   };
 
+  // ISSUE-008: env vars don't flow through AgentCreationFlowContext today
+  // (they're not needed by the code generator), so we only mirror the value
+  // into local agent state. The context could grow envVars later if some
+  // other screen needs to read them mid-creation-flow.
+  const handleEnvVarsChange = (newEnvVars) => {
+    setAgent(prev => ({ ...prev, envVars: newEnvVars }));
+  };
+
   if (loading) {
     return (
       <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
@@ -1047,6 +1062,19 @@ const ViewAgent = () => {
             </AccordionDetails>
         </Accordion>
 
+        {/* Environment Variables Section (ISSUE-008) */}
+        <Accordion>
+            <AccordionSummary expandIcon={<ExpandMoreIcon />}>
+                <Typography>Environment Variables</Typography>
+            </AccordionSummary>
+            <AccordionDetails>
+                <EnvVarsEditor
+                    envVars={agent.envVars || []}
+                    setEnvVars={handleEnvVarsChange}
+                />
+            </AccordionDetails>
+        </Accordion>
+
         {/* Data Store Configuration Section */}
         <Accordion>
             <AccordionSummary expandIcon={<ExpandMoreIcon />}>
diff --git a/webapp/packages/webui/src/services/agentService.js b/webapp/packages/webui/src/services/agentService.js
index e90645a..b8ba73b 100644
--- a/webapp/packages/webui/src/services/agentService.js
+++ b/webapp/packages/webui/src/services/agentService.js
@@ -123,6 +123,7 @@ class AgentService {
   async runCodeInSandboxStreaming(
     code, inputDict, tools, gofannonAgents, llmSettings, outputSchema, friendlyName,
     onEvent,
+    envVars,
   ) {
     const requestBody = {
       code,
@@ -132,6 +133,8 @@ class AgentService {
       llmSettings,
       outputSchema,
       friendlyName,
+      // ISSUE-008: per-agent env vars threaded to the runtime overlay
+      envVars,
     };
 
     const authHeaders = await this._getAuthHeaders();


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org