Jelajahi Sumber

feat: #625 Option to save suggested values in the browser local storage across different args

jamesread 5 bulan lalu
induk
melakukan
661bcdda08

+ 5 - 0
frontend/resources/scripts/gen/olivetin/api/v1/olivetin_pb.d.ts

@@ -99,6 +99,11 @@ export declare type ActionArgument = Message<"olivetin.api.v1.ActionArgument"> &
    * @generated from field: map<string, string> suggestions = 7;
    */
   suggestions: { [key: string]: string };
+
+  /**
+   * @generated from field: string suggestions_browser_key = 8;
+   */
+  suggestionsBrowserKey: string;
 };
 
 /**

File diff ditekan karena terlalu besar
+ 0 - 0
frontend/resources/scripts/gen/olivetin/api/v1/olivetin_pb.js


+ 62 - 2
frontend/resources/vue/views/ArgumentForm.vue

@@ -12,10 +12,13 @@
                 {{ formatLabel(arg.title) }}
               </label>
 
-              <datalist v-if="arg.suggestions && Object.keys(arg.suggestions).length > 0" :id="`${arg.name}-choices`">
+              <datalist v-if="(arg.suggestions && Object.keys(arg.suggestions).length > 0) || getBrowserSuggestions(arg).length > 0" :id="`${arg.name}-choices`">
                 <option v-for="(suggestion, key) in arg.suggestions" :key="key" :value="key">
                   {{ suggestion }}
                 </option>
+                <option v-for="(suggestion, index) in getBrowserSuggestions(arg)" :key="`browser-${index}`" :value="suggestion">
+                  {{ suggestion }}
+                </option>
               </datalist>
 
               <select v-if="getInputComponent(arg) === 'select'" :id="arg.name" :name="arg.name" :value="getArgumentValue(arg)"
@@ -28,7 +31,7 @@
               <component v-else :is="getInputComponent(arg)" :id="arg.name" :name="arg.name" 
                 :value="(arg.type === 'checkbox' || arg.type === 'confirmation') ? undefined : getArgumentValue(arg)"
                 :checked="(arg.type === 'checkbox' || arg.type === 'confirmation') ? getArgumentValue(arg) : undefined"
-                :list="arg.suggestions ? `${arg.name}-choices` : undefined" 
+                :list="(arg.suggestions || getBrowserSuggestions(arg).length > 0) ? `${arg.name}-choices` : undefined" 
                 :type="getInputComponent(arg) !== 'select' ? getInputType(arg) : undefined"
                 :rows="arg.type === 'raw_string_multiline' ? 5 : undefined"
                 :step="arg.type === 'datetime' ? 1 : undefined" :pattern="getPattern(arg)"
@@ -313,6 +316,60 @@ function getUniqueId() {
   }
 }
 
+function getBrowserSuggestions(arg) {
+  if (!arg.suggestionsBrowserKey) {
+    return []
+  }
+  
+  try {
+    const stored = localStorage.getItem(`olivetin-suggestions-${arg.suggestionsBrowserKey}`)
+    if (stored) {
+      const suggestions = JSON.parse(stored)
+      return Array.isArray(suggestions) ? suggestions : []
+    }
+  } catch (err) {
+    console.warn('Failed to load browser suggestions:', err)
+  }
+  
+  return []
+}
+
+function saveBrowserSuggestions() {
+  for (const arg of actionArguments.value) {
+    if (arg.suggestionsBrowserKey) {
+      const value = argValues.value[arg.name]
+      
+      // Only save non-empty values for non-checkbox/confirmation types
+      if (value && value !== '' && arg.type !== 'checkbox' && arg.type !== 'confirmation') {
+        try {
+          const key = `olivetin-suggestions-${arg.suggestionsBrowserKey}`
+          const stored = localStorage.getItem(key)
+          let suggestions = []
+          
+          if (stored) {
+            suggestions = JSON.parse(stored)
+            if (!Array.isArray(suggestions)) {
+              suggestions = []
+            }
+          }
+          
+          // Add value if not already present
+          if (!suggestions.includes(value)) {
+            suggestions.unshift(value) // Add to beginning
+            // Keep only the most recent 50 suggestions
+            if (suggestions.length > 50) {
+              suggestions = suggestions.slice(0, 50)
+            }
+            localStorage.setItem(key, JSON.stringify(suggestions))
+          }
+        } catch (err) {
+          console.warn('Failed to save browser suggestions:', err)
+        }
+      }
+    }
+  }
+}
+
 async function startAction(actionArgs) {
   const startActionArgs = {
     bindingId: props.bindingId,
@@ -356,6 +413,9 @@ async function handleSubmit(event) {
   const argvs = getArgumentValues()
   console.log('argument form has elements that passed validation')
   
+  // Save values to localStorage for arguments with suggestionsBrowserKey
+  saveBrowserSuggestions()
+  
   try {
     const response = await startAction(argvs)
     router.push(`/logs/${response.executionTrackingId}`)

+ 19 - 0
integration-tests/tests/suggestionsBrowserKey/config.yaml

@@ -0,0 +1,19 @@
+---
+listenAddressSingleHTTPFrontend: 0.0.0.0:1337
+
+logLevel: "DEBUG"
+checkForUpdates: false
+
+actions:
+  - title: Test suggestionsBrowserKey
+    shell: "echo 'Input value: {{ testInput }}, Second input: {{ testInput2 }}'"
+    icon: ping
+    arguments:
+      - name: testInput
+        title: Test Input
+        description: "This input uses suggestionsBrowserKey"
+        suggestionsBrowserKey: test-suggestions-key
+      - name: testInput2
+        title: Test Input 2
+        description: "This input shares the same suggestionsBrowserKey"
+        suggestionsBrowserKey: test-suggestions-key

+ 320 - 0
integration-tests/tests/suggestionsBrowserKey/suggestionsBrowserKey.mjs

@@ -0,0 +1,320 @@
+import { describe, it, before, after } from 'mocha'
+import { expect } from 'chai'
+import { By, Condition } from 'selenium-webdriver'
+import {
+  getRootAndWait,
+  getActionButton,
+  takeScreenshotOnFailure,
+  getTerminalBuffer,
+} from '../../lib/elements.js'
+
+async function openArgumentForm() {
+  await getRootAndWait()
+  const btn = await getActionButton(webdriver, 'Test suggestionsBrowserKey')
+  await btn.click()
+
+  await webdriver.wait(
+    new Condition('wait for argument form page', async () => {
+      const url = await webdriver.getCurrentUrl()
+      return url.includes('/actionBinding/') && url.includes('/argumentForm')
+    }),
+    5000
+  )
+}
+
+async function getTestInput() {
+  return await webdriver.findElement(By.id('testInput'))
+}
+
+async function getTestInput2() {
+  return await webdriver.findElement(By.id('testInput2'))
+}
+
+async function getDatalistOptions(inputName = 'testInput') {
+  return await webdriver.findElements(By.css(`datalist#${inputName}-choices option`))
+}
+
+async function submitForm() {
+  const submitButton = await webdriver.findElement(By.css('button[name="start"]'))
+  await submitButton.click()
+}
+
+async function waitForLogsPage() {
+  await webdriver.wait(
+    new Condition('wait for logs page', async () => {
+      const url = await webdriver.getCurrentUrl()
+      return url.includes('/logs/') && !url.endsWith('/logs')
+    }),
+    5000
+  )
+}
+
+async function waitForExecutionComplete() {
+  await webdriver.wait(
+    new Condition('wait for execution status', async () => {
+      const statusElements = await webdriver.findElements(By.id('execution-dialog-status'))
+      return statusElements.length > 0
+    }),
+    5000
+  )
+
+  await webdriver.wait(
+    new Condition('wait for execution to finish', async () => {
+      try {
+        const statusElement = await webdriver.findElement(By.id('execution-dialog-status'))
+        const statusText = await statusElement.getText()
+        return !statusText.includes('Executing')
+      } catch (e) {
+        return false
+      }
+    }),
+    5000
+  )
+
+  await webdriver.sleep(500)
+}
+
+async function getLocalStorageItem(key) {
+  return await webdriver.executeScript(`return localStorage.getItem('${key}')`)
+}
+
+async function clearLocalStorage() {
+  await webdriver.executeScript('return localStorage.clear()')
+}
+
+describe('config: suggestionsBrowserKey', function () {
+  before(async function () {
+    await runner.start('suggestionsBrowserKey')
+  })
+
+  after(async () => {
+    await runner.stop()
+  })
+
+  afterEach(function () {
+    takeScreenshotOnFailure(this.currentTest, webdriver)
+  })
+
+  it('Input fields with suggestionsBrowserKey are rendered', async function () {
+    await openArgumentForm()
+
+    const input1 = await getTestInput()
+    expect(await input1.getTagName()).to.equal('input')
+    expect(await input1.getAttribute('type')).to.equal('text')
+
+    const label1 = await webdriver.findElement(By.css('label[for="testInput"]'))
+    expect(await label1.getText()).to.contain('Test Input')
+
+    const input2 = await getTestInput2()
+    expect(await input2.getTagName()).to.equal('input')
+    expect(await input2.getAttribute('type')).to.equal('text')
+
+    const label2 = await webdriver.findElement(By.css('label[for="testInput2"]'))
+    expect(await label2.getText()).to.contain('Test Input 2')
+  })
+
+  it('Submitting form saves value to localStorage', async function () {
+    this.timeout(15000)
+    
+    // Clear localStorage first
+    await clearLocalStorage()
+    
+    await openArgumentForm()
+
+    const input = await getTestInput()
+    const testValue = 'test-value-123'
+    await input.clear()
+    await input.sendKeys(testValue)
+
+    await submitForm()
+    await waitForLogsPage()
+    await waitForExecutionComplete()
+
+    // Verify value was saved to localStorage
+    const stored = await getLocalStorageItem('olivetin-suggestions-test-suggestions-key')
+    expect(stored).to.not.be.null
+    
+    const suggestions = JSON.parse(stored)
+    expect(suggestions).to.be.an('array')
+    expect(suggestions).to.include(testValue)
+  })
+
+  it('Previously saved values appear in datalist', async function () {
+    this.timeout(15000)
+    
+    // First, save a value to localStorage
+    const testValue = 'saved-suggestion-456'
+    await webdriver.executeScript(`
+      const key = 'olivetin-suggestions-test-suggestions-key';
+      localStorage.setItem(key, JSON.stringify(['${testValue}']));
+    `)
+
+    // Open the form
+    await openArgumentForm()
+
+    // Check that datalist exists and contains the saved value
+    const datalist = await webdriver.findElement(By.id('testInput-choices'))
+    expect(datalist).to.not.be.null
+
+    const options = await getDatalistOptions()
+    expect(options.length).to.be.greaterThan(0)
+
+    // Check if the saved value appears in the datalist
+    let foundValue = false
+    for (const option of options) {
+      const value = await option.getAttribute('value')
+      if (value === testValue) {
+        foundValue = true
+        break
+      }
+    }
+    expect(foundValue).to.be.true
+  })
+
+  it('Multiple submissions accumulate suggestions', async function () {
+    this.timeout(20000)
+    
+    // Clear localStorage first
+    await clearLocalStorage()
+
+    // Submit first value
+    await openArgumentForm()
+    const input1 = await getTestInput()
+    await input1.clear()
+    await input1.sendKeys('first-value')
+    await submitForm()
+    await waitForLogsPage()
+    await waitForExecutionComplete()
+
+    // Submit second value
+    await openArgumentForm()
+    const input2 = await getTestInput()
+    await input2.clear()
+    await input2.sendKeys('second-value')
+    await submitForm()
+    await waitForLogsPage()
+    await waitForExecutionComplete()
+
+    // Verify both values are in localStorage
+    const stored = await getLocalStorageItem('olivetin-suggestions-test-suggestions-key')
+    expect(stored).to.not.be.null
+    
+    const suggestions = JSON.parse(stored)
+    expect(suggestions).to.be.an('array')
+    expect(suggestions).to.include('first-value')
+    expect(suggestions).to.include('second-value')
+    expect(suggestions[0]).to.equal('second-value') // Most recent should be first
+  })
+
+  it('Empty values are not saved to localStorage', async function () {
+    this.timeout(15000)
+    
+    // Clear localStorage first
+    await clearLocalStorage()
+
+    await openArgumentForm()
+
+    const input = await getTestInput()
+    // Leave input empty (or clear it if it has a default)
+    await input.clear()
+
+    await submitForm()
+    await waitForLogsPage()
+    await waitForExecutionComplete()
+
+    // Verify empty value was not saved - localStorage should be null or not contain the key
+    const stored = await getLocalStorageItem('olivetin-suggestions-test-suggestions-key')
+    // Should be null since empty values are not saved
+    expect(stored).to.be.null
+  })
+
+  it('Suggestions are shared across inputs with the same suggestionsBrowserKey', async function () {
+    this.timeout(20000)
+    
+    // Clear localStorage first
+    await clearLocalStorage()
+
+    // Submit a value using the first input
+    await openArgumentForm()
+    const input1 = await getTestInput()
+    await input1.clear()
+    await input1.sendKeys('shared-value-from-input1')
+    await submitForm()
+    await waitForLogsPage()
+    await waitForExecutionComplete()
+
+    // Open the form again and verify the value appears in both datalists
+    await openArgumentForm()
+    
+    // Check first input's datalist
+    const datalist1 = await webdriver.findElement(By.id('testInput-choices'))
+    expect(datalist1).to.not.be.null
+    const options1 = await getDatalistOptions('testInput')
+    let foundInInput1 = false
+    for (const option of options1) {
+      const value = await option.getAttribute('value')
+      if (value === 'shared-value-from-input1') {
+        foundInInput1 = true
+        break
+      }
+    }
+    expect(foundInInput1).to.be.true
+
+    // Check second input's datalist
+    const datalist2 = await webdriver.findElement(By.id('testInput2-choices'))
+    expect(datalist2).to.not.be.null
+    const options2 = await getDatalistOptions('testInput2')
+    let foundInInput2 = false
+    for (const option of options2) {
+      const value = await option.getAttribute('value')
+      if (value === 'shared-value-from-input1') {
+        foundInInput2 = true
+        break
+      }
+    }
+    expect(foundInInput2).to.be.true
+
+    // Now submit a value using the second input
+    const input2 = await getTestInput2()
+    await input2.clear()
+    await input2.sendKeys('shared-value-from-input2')
+    await submitForm()
+    await waitForLogsPage()
+    await waitForExecutionComplete()
+
+    // Verify both values appear in both datalists
+    await openArgumentForm()
+    
+    // Check that both values are in the first input's datalist
+    const options1After = await getDatalistOptions('testInput')
+    let foundValue1 = false
+    let foundValue2 = false
+    for (const option of options1After) {
+      const value = await option.getAttribute('value')
+      if (value === 'shared-value-from-input1') {
+        foundValue1 = true
+      }
+      if (value === 'shared-value-from-input2') {
+        foundValue2 = true
+      }
+    }
+    expect(foundValue1).to.be.true
+    expect(foundValue2).to.be.true
+
+    // Check that both values are in the second input's datalist
+    const options2After = await getDatalistOptions('testInput2')
+    foundValue1 = false
+    foundValue2 = false
+    for (const option of options2After) {
+      const value = await option.getAttribute('value')
+      if (value === 'shared-value-from-input1') {
+        foundValue1 = true
+      }
+      if (value === 'shared-value-from-input2') {
+        foundValue2 = true
+      }
+    }
+    expect(foundValue1).to.be.true
+    expect(foundValue2).to.be.true
+  })
+})

+ 1 - 0
proto/olivetin/api/v1/olivetin.proto

@@ -25,6 +25,7 @@ message ActionArgument {
 
 	string description = 6;
 	map<string, string> suggestions = 7;
+	string suggestions_browser_key = 8;
 }
 
 message ActionArgumentChoice {

+ 21 - 12
service/gen/olivetin/api/v1/olivetin.pb.go

@@ -122,16 +122,17 @@ func (x *Action) GetTimeout() int32 {
 }
 
 type ActionArgument struct {
-	state         protoimpl.MessageState  `protogen:"open.v1"`
-	Name          string                  `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
-	Title         string                  `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"`
-	Type          string                  `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"`
-	DefaultValue  string                  `protobuf:"bytes,4,opt,name=default_value,json=defaultValue,proto3" json:"default_value,omitempty"`
-	Choices       []*ActionArgumentChoice `protobuf:"bytes,5,rep,name=choices,proto3" json:"choices,omitempty"`
-	Description   string                  `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"`
-	Suggestions   map[string]string       `protobuf:"bytes,7,rep,name=suggestions,proto3" json:"suggestions,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
-	unknownFields protoimpl.UnknownFields
-	sizeCache     protoimpl.SizeCache
+	state                 protoimpl.MessageState  `protogen:"open.v1"`
+	Name                  string                  `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+	Title                 string                  `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"`
+	Type                  string                  `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"`
+	DefaultValue          string                  `protobuf:"bytes,4,opt,name=default_value,json=defaultValue,proto3" json:"default_value,omitempty"`
+	Choices               []*ActionArgumentChoice `protobuf:"bytes,5,rep,name=choices,proto3" json:"choices,omitempty"`
+	Description           string                  `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"`
+	Suggestions           map[string]string       `protobuf:"bytes,7,rep,name=suggestions,proto3" json:"suggestions,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+	SuggestionsBrowserKey string                  `protobuf:"bytes,8,opt,name=suggestions_browser_key,json=suggestionsBrowserKey,proto3" json:"suggestions_browser_key,omitempty"`
+	unknownFields         protoimpl.UnknownFields
+	sizeCache             protoimpl.SizeCache
 }
 
 func (x *ActionArgument) Reset() {
@@ -213,6 +214,13 @@ func (x *ActionArgument) GetSuggestions() map[string]string {
 	return nil
 }
 
+func (x *ActionArgument) GetSuggestionsBrowserKey() string {
+	if x != nil {
+		return x.SuggestionsBrowserKey
+	}
+	return ""
+}
+
 type ActionArgumentChoice struct {
 	state         protoimpl.MessageState `protogen:"open.v1"`
 	Value         string                 `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
@@ -3849,7 +3857,7 @@ const file_olivetin_api_v1_olivetin_proto_rawDesc = "" +
 	"\targuments\x18\x05 \x03(\v2\x1f.olivetin.api.v1.ActionArgumentR\targuments\x12$\n" +
 	"\x0epopup_on_start\x18\x06 \x01(\tR\fpopupOnStart\x12\x14\n" +
 	"\x05order\x18\a \x01(\x05R\x05order\x12\x18\n" +
-	"\atimeout\x18\b \x01(\x05R\atimeout\"\xea\x02\n" +
+	"\atimeout\x18\b \x01(\x05R\atimeout\"\xa2\x03\n" +
 	"\x0eActionArgument\x12\x12\n" +
 	"\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" +
 	"\x05title\x18\x02 \x01(\tR\x05title\x12\x12\n" +
@@ -3857,7 +3865,8 @@ const file_olivetin_api_v1_olivetin_proto_rawDesc = "" +
 	"\rdefault_value\x18\x04 \x01(\tR\fdefaultValue\x12?\n" +
 	"\achoices\x18\x05 \x03(\v2%.olivetin.api.v1.ActionArgumentChoiceR\achoices\x12 \n" +
 	"\vdescription\x18\x06 \x01(\tR\vdescription\x12R\n" +
-	"\vsuggestions\x18\a \x03(\v20.olivetin.api.v1.ActionArgument.SuggestionsEntryR\vsuggestions\x1a>\n" +
+	"\vsuggestions\x18\a \x03(\v20.olivetin.api.v1.ActionArgument.SuggestionsEntryR\vsuggestions\x126\n" +
+	"\x17suggestions_browser_key\x18\b \x01(\tR\x15suggestionsBrowserKey\x1a>\n" +
 	"\x10SuggestionsEntry\x12\x10\n" +
 	"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
 	"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"B\n" +

+ 8 - 7
service/internal/api/apiActions.go

@@ -122,13 +122,14 @@ func buildAction(actionBinding *executor.ActionBinding, rr *DashboardRenderReque
 
 	for _, cfgArg := range action.Arguments {
 		pbArg := apiv1.ActionArgument{
-			Name:         cfgArg.Name,
-			Title:        cfgArg.Title,
-			Type:         cfgArg.Type,
-			Description:  cfgArg.Description,
-			DefaultValue: cfgArg.Default,
-			Choices:      buildChoices(cfgArg),
-			Suggestions:  cfgArg.Suggestions,
+			Name:                  cfgArg.Name,
+			Title:                 cfgArg.Title,
+			Type:                  cfgArg.Type,
+			Description:           cfgArg.Description,
+			DefaultValue:          cfgArg.Default,
+			Choices:               buildChoices(cfgArg),
+			Suggestions:           cfgArg.Suggestions,
+			SuggestionsBrowserKey: cfgArg.SuggestionsBrowserKey,
 		}
 
 		btn.Arguments = append(btn.Arguments, &pbArg)

+ 10 - 9
service/internal/config/config.go

@@ -34,15 +34,16 @@ type Action struct {
 
 // ActionArgument objects appear on Actions.
 type ActionArgument struct {
-	Name        string                 `koanf:"name"`
-	Title       string                 `koanf:"title"`
-	Description string                 `koanf:"description"`
-	Type        string                 `koanf:"type"`
-	Default     string                 `koanf:"default"`
-	Choices     []ActionArgumentChoice `koanf:"choices"`
-	Entity      string                 `koanf:"entity"`
-	RejectNull  bool                   `koanf:"rejectNull"`
-	Suggestions map[string]string      `koanf:"suggestions"`
+	Name                 string                 `koanf:"name"`
+	Title                string                 `koanf:"title"`
+	Description          string                 `koanf:"description"`
+	Type                 string                 `koanf:"type"`
+	Default              string                 `koanf:"default"`
+	Choices              []ActionArgumentChoice `koanf:"choices"`
+	Entity               string                 `koanf:"entity"`
+	RejectNull           bool                   `koanf:"rejectNull"`
+	Suggestions          map[string]string      `koanf:"suggestions"`
+	SuggestionsBrowserKey string                `koanf:"suggestionsBrowserKey"`
 }
 
 // ActionArgumentChoice represents a predefined choice for an argument.

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini